ateIdentifier(suggestion));
  }
}
function convertSemanticMeaningToSymbolFlags(meaning) {
  let flags = 0;
  if (meaning & 4 /* Namespace */) {
    flags |= 1920 /* Namespace */;
  }
  if (meaning & 2 /* Type */) {
    flags |= 788968 /* Type */;
  }
  if (meaning & 1 /* Value */) {
    flags |= 111551 /* Value */;
  }
  return flags;
}
function getResolvedSourceFileFromImportDeclaration(context, importDeclaration, importingFile) {
  var _a;
  if (!importDeclaration || !isStringLiteralLike(importDeclaration.moduleSpecifier)) return void 0;
  const resolvedModule = (_a = context.program.getResolvedModuleFromModuleSpecifier(importDeclaration.moduleSpecifier, importingFile)) == null ? void 0 : _a.resolvedModule;
  if (!resolvedModule) return void 0;
  return context.program.getSourceFile(resolvedModule.resolvedFileName);
}

// src/services/codefixes/returnValueCorrect.ts
var fixId24 = "returnValueCorrect";
var fixIdAddReturnStatement = "fixAddReturnStatement";
var fixRemoveBracesFromArrowFunctionBody = "fixRemoveBracesFromArrowFunctionBody";
var fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen";
var errorCodes27 = [
  Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1.code,
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code
];
registerCodeFix({
  errorCodes: errorCodes27,
  fixIds: [fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen],
  getCodeActions: function getCodeActionsToCorrectReturnValue(context) {
    const { program, sourceFile, span: { start }, errorCode } = context;
    const info = getInfo9(program.getTypeChecker(), sourceFile, start, errorCode);
    if (!info) return void 0;
    if (info.kind === 0 /* MissingReturnStatement */) {
      return append(
        [getActionForfixAddReturnStatement(context, info.expression, info.statement)],
        isArrowFunction(info.declaration) ? getActionForFixRemoveBracesFromArrowFunctionBody(context, info.declaration, info.expression, info.commentSource) : void 0
      );
    } else {
      return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)];
    }
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes27, (changes, diag2) => {
    const info = getInfo9(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code);
    if (!info) return void 0;
    switch (context.fixId) {
      case fixIdAddReturnStatement:
        addReturnStatement(changes, diag2.file, info.expression, info.statement);
        break;
      case fixRemoveBracesFromArrowFunctionBody:
        if (!isArrowFunction(info.declaration)) return void 0;
        removeBlockBodyBrace(
          changes,
          diag2.file,
          info.declaration,
          info.expression,
          info.commentSource,
          /*withParen*/
          false
        );
        break;
      case fixIdWrapTheBlockWithParen:
        if (!isArrowFunction(info.declaration)) return void 0;
        wrapBlockWithParen(changes, diag2.file, info.declaration, info.expression);
        break;
      default:
        Debug.fail(JSON.stringify(context.fixId));
    }
  })
});
function createObjectTypeFromLabeledExpression(checker, label, expression) {
  const member = checker.createSymbol(4 /* Property */, label.escapedText);
  member.links.type = checker.getTypeAtLocation(expression);
  const members = createSymbolTable([member]);
  return checker.createAnonymousType(
    /*symbol*/
    void 0,
    members,
    [],
    [],
    []
  );
}
function getFixInfo(checker, declaration, expectType, isFunctionType) {
  if (!declaration.body || !isBlock(declaration.body) || length(declaration.body.statements) !== 1) return void 0;
  const firstStatement = first(declaration.body.statements);
  if (isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, checker.getTypeAtLocation(firstStatement.expression), expectType, isFunctionType)) {
    return {
      declaration,
      kind: 0 /* MissingReturnStatement */,
      expression: firstStatement.expression,
      statement: firstStatement,
      commentSource: firstStatement.expression
    };
  } else if (isLabeledStatement(firstStatement) && isExpressionStatement(firstStatement.statement)) {
    const node = factory.createObjectLiteralExpression([factory.createPropertyAssignment(firstStatement.label, firstStatement.statement.expression)]);
    const nodeType = createObjectTypeFromLabeledExpression(checker, firstStatement.label, firstStatement.statement.expression);
    if (checkFixedAssignableTo(checker, declaration, nodeType, expectType, isFunctionType)) {
      return isArrowFunction(declaration) ? {
        declaration,
        kind: 1 /* MissingParentheses */,
        expression: node,
        statement: firstStatement,
        commentSource: firstStatement.statement.expression
      } : {
        declaration,
        kind: 0 /* MissingReturnStatement */,
        expression: node,
        statement: firstStatement,
        commentSource: firstStatement.statement.expression
      };
    }
  } else if (isBlock(firstStatement) && length(firstStatement.statements) === 1) {
    const firstBlockStatement = first(firstStatement.statements);
    if (isLabeledStatement(firstBlockStatement) && isExpressionStatement(firstBlockStatement.statement)) {
      const node = factory.createObjectLiteralExpression([factory.createPropertyAssignment(firstBlockStatement.label, firstBlockStatement.statement.expression)]);
      const nodeType = createObjectTypeFromLabeledExpression(checker, firstBlockStatement.label, firstBlockStatement.statement.expression);
      if (checkFixedAssignableTo(checker, declaration, nodeType, expectType, isFunctionType)) {
        return {
          declaration,
          kind: 0 /* MissingReturnStatement */,
          expression: node,
          statement: firstStatement,
          commentSource: firstBlockStatement
        };
      }
    }
  }
  return void 0;
}
function checkFixedAssignableTo(checker, declaration, exprType, type, isFunctionType) {
  if (isFunctionType) {
    const sig = checker.getSignatureFromDeclaration(declaration);
    if (sig) {
      if (hasSyntacticModifier(declaration, 1024 /* Async */)) {
        exprType = checker.createPromiseType(exprType);
      }
      const newSig = checker.createSignature(
        declaration,
        sig.typeParameters,
        sig.thisParameter,
        sig.parameters,
        exprType,
        /*typePredicate*/
        void 0,
        sig.minArgumentCount,
        sig.flags
      );
      exprType = checker.createAnonymousType(
        /*symbol*/
        void 0,
        createSymbolTable(),
        [newSig],
        [],
        []
      );
    } else {
      exprType = checker.getAnyType();
    }
  }
  return checker.isTypeAssignableTo(exprType, type);
}
function getInfo9(checker, sourceFile, position, errorCode) {
  const node = getTokenAtPosition(sourceFile, position);
  if (!node.parent) return void 0;
  const declaration = findAncestor(node.parent, isFunctionLikeDeclaration);
  switch (errorCode) {
    case Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value.code:
      if (!declaration || !declaration.body || !declaration.type || !rangeContainsRange(declaration.type, node)) return void 0;
      return getFixInfo(
        checker,
        declaration,
        checker.getTypeFromTypeNode(declaration.type),
        /*isFunctionType*/
        false
      );
    case Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code:
      if (!declaration || !isCallExpression(declaration.parent) || !declaration.body) return void 0;
      const pos = declaration.parent.arguments.indexOf(declaration);
      if (pos === -1) return void 0;
      const type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos);
      if (!type) return void 0;
      return getFixInfo(
        checker,
        declaration,
        type,
        /*isFunctionType*/
        true
      );
    case Diagnostics.Type_0_is_not_assignable_to_type_1.code:
      if (!isDeclarationName(node) || !isVariableLike(node.parent) && !isJsxAttribute(node.parent)) return void 0;
      const initializer = getVariableLikeInitializer(node.parent);
      if (!initializer || !isFunctionLikeDeclaration(initializer) || !initializer.body) return void 0;
      return getFixInfo(
        checker,
        initializer,
        checker.getTypeAtLocation(node.parent),
        /*isFunctionType*/
        true
      );
  }
  return void 0;
}
function getVariableLikeInitializer(declaration) {
  switch (declaration.kind) {
    case 260 /* VariableDeclaration */:
    case 169 /* Parameter */:
    case 208 /* BindingElement */:
    case 172 /* PropertyDeclaration */:
    case 303 /* PropertyAssignment */:
      return declaration.initializer;
    case 291 /* JsxAttribute */:
      return declaration.initializer && (isJsxExpression(declaration.initializer) ? declaration.initializer.expression : void 0);
    case 304 /* ShorthandPropertyAssignment */:
    case 171 /* PropertySignature */:
    case 306 /* EnumMember */:
    case 348 /* JSDocPropertyTag */:
    case 341 /* JSDocParameterTag */:
      return void 0;
  }
}
function addReturnStatement(changes, sourceFile, expression, statement) {
  suppressLeadingAndTrailingTrivia(expression);
  const probablyNeedSemi = probablyUsesSemicolons(sourceFile);
  changes.replaceNode(sourceFile, statement, factory.createReturnStatement(expression), {
    leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude,
    trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude,
    suffix: probablyNeedSemi ? ";" : void 0
  });
}
function removeBlockBodyBrace(changes, sourceFile, declaration, expression, commentSource, withParen) {
  const newBody = withParen || needsParentheses(expression) ? factory.createParenthesizedExpression(expression) : expression;
  suppressLeadingAndTrailingTrivia(commentSource);
  copyComments(commentSource, newBody);
  changes.replaceNode(sourceFile, declaration.body, newBody);
}
function wrapBlockWithParen(changes, sourceFile, declaration, expression) {
  changes.replaceNode(sourceFile, declaration.body, factory.createParenthesizedExpression(expression));
}
function getActionForfixAddReturnStatement(context, expression, statement) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addReturnStatement(t, context.sourceFile, expression, statement));
  return createCodeFixAction(fixId24, changes, Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, Diagnostics.Add_all_missing_return_statement);
}
function getActionForFixRemoveBracesFromArrowFunctionBody(context, declaration, expression, commentSource) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => removeBlockBodyBrace(
    t,
    context.sourceFile,
    declaration,
    expression,
    commentSource,
    /*withParen*/
    false
  ));
  return createCodeFixAction(fixId24, changes, Diagnostics.Remove_braces_from_arrow_function_body, fixRemoveBracesFromArrowFunctionBody, Diagnostics.Remove_braces_from_all_arrow_function_bodies_with_relevant_issues);
}
function getActionForfixWrapTheBlockWithParen(context, declaration, expression) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => wrapBlockWithParen(t, context.sourceFile, declaration, expression));
  return createCodeFixAction(fixId24, changes, Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, Diagnostics.Wrap_all_object_literal_with_parentheses);
}

// src/services/codefixes/fixAddMissingMember.ts
var fixMissingMember = "fixMissingMember";
var fixMissingProperties = "fixMissingProperties";
var fixMissingAttributes = "fixMissingAttributes";
var fixMissingFunctionDeclaration = "fixMissingFunctionDeclaration";
var errorCodes28 = [
  Diagnostics.Property_0_does_not_exist_on_type_1.code,
  Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
  Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code,
  Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code,
  Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code,
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
  Diagnostics.Cannot_find_name_0.code
];
registerCodeFix({
  errorCodes: errorCodes28,
  getCodeActions(context) {
    const typeChecker = context.program.getTypeChecker();
    const info = getInfo10(context.sourceFile, context.span.start, context.errorCode, typeChecker, context.program);
    if (!info) {
      return void 0;
    }
    if (info.kind === 3 /* ObjectLiteral */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addObjectLiteralProperties(t, context, info));
      return [createCodeFixAction(fixMissingProperties, changes, Diagnostics.Add_missing_properties, fixMissingProperties, Diagnostics.Add_all_missing_properties)];
    }
    if (info.kind === 4 /* JsxAttributes */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addJsxAttributes(t, context, info));
      return [createCodeFixAction(fixMissingAttributes, changes, Diagnostics.Add_missing_attributes, fixMissingAttributes, Diagnostics.Add_all_missing_attributes)];
    }
    if (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addFunctionDeclaration(t, context, info));
      return [createCodeFixAction(fixMissingFunctionDeclaration, changes, [Diagnostics.Add_missing_function_declaration_0, info.token.text], fixMissingFunctionDeclaration, Diagnostics.Add_all_missing_function_declarations)];
    }
    if (info.kind === 1 /* Enum */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addEnumMemberDeclaration(t, context.program.getTypeChecker(), info));
      return [createCodeFixAction(fixMissingMember, changes, [Diagnostics.Add_missing_enum_member_0, info.token.text], fixMissingMember, Diagnostics.Add_all_missing_members)];
    }
    return concatenate(getActionsForMissingMethodDeclaration(context, info), getActionsForMissingMemberDeclaration(context, info));
  },
  fixIds: [fixMissingMember, fixMissingFunctionDeclaration, fixMissingProperties, fixMissingAttributes],
  getAllCodeActions: (context) => {
    const { program, fixId: fixId56 } = context;
    const checker = program.getTypeChecker();
    const seen = /* @__PURE__ */ new Set();
    const typeDeclToMembers = /* @__PURE__ */ new Map();
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      eachDiagnostic(context, errorCodes28, (diag2) => {
        const info = getInfo10(diag2.file, diag2.start, diag2.code, checker, context.program);
        if (!info || !addToSeen(seen, getNodeId(info.parentDeclaration) + "#" + (info.kind === 3 /* ObjectLiteral */ ? info.identifier : info.token.text))) {
          return;
        }
        if (fixId56 === fixMissingFunctionDeclaration && (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */)) {
          addFunctionDeclaration(changes, context, info);
        } else if (fixId56 === fixMissingProperties && info.kind === 3 /* ObjectLiteral */) {
          addObjectLiteralProperties(changes, context, info);
        } else if (fixId56 === fixMissingAttributes && info.kind === 4 /* JsxAttributes */) {
          addJsxAttributes(changes, context, info);
        } else {
          if (info.kind === 1 /* Enum */) {
            addEnumMemberDeclaration(changes, checker, info);
          }
          if (info.kind === 0 /* TypeLikeDeclaration */) {
            const { parentDeclaration, token } = info;
            const infos = getOrUpdate(typeDeclToMembers, parentDeclaration, () => []);
            if (!infos.some((i) => i.token.text === token.text)) {
              infos.push(info);
            }
          }
        }
      });
      typeDeclToMembers.forEach((infos, declaration) => {
        const supers = isTypeLiteralNode(declaration) ? void 0 : getAllSupers(declaration, checker);
        for (const info of infos) {
          if (supers == null ? void 0 : supers.some((superClassOrInterface) => {
            const superInfos = typeDeclToMembers.get(superClassOrInterface);
            return !!superInfos && superInfos.some(({ token: token2 }) => token2.text === info.token.text);
          })) continue;
          const { parentDeclaration, declSourceFile, modifierFlags, token, call, isJSFile } = info;
          if (call && !isPrivateIdentifier(token)) {
            addMethodDeclaration(context, changes, call, token, modifierFlags & 256 /* Static */, parentDeclaration, declSourceFile);
          } else {
            if (isJSFile && !isInterfaceDeclaration(parentDeclaration) && !isTypeLiteralNode(parentDeclaration)) {
              addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, !!(modifierFlags & 256 /* Static */));
            } else {
              const typeNode = getTypeNode2(checker, parentDeclaration, token);
              addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, modifierFlags & 256 /* Static */);
            }
          }
        }
      });
    }));
  }
});
function getInfo10(sourceFile, tokenPos, errorCode, checker, program) {
  var _a, _b, _c;
  const token = getTokenAtPosition(sourceFile, tokenPos);
  const parent2 = token.parent;
  if (errorCode === Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code) {
    if (!(token.kind === 19 /* OpenBraceToken */ && isObjectLiteralExpression(parent2) && isCallExpression(parent2.parent))) return void 0;
    const argIndex = findIndex(parent2.parent.arguments, (arg) => arg === parent2);
    if (argIndex < 0) return void 0;
    const signature = checker.getResolvedSignature(parent2.parent);
    if (!(signature && signature.declaration && signature.parameters[argIndex])) return void 0;
    const param = signature.parameters[argIndex].valueDeclaration;
    if (!(param && isParameter(param) && isIdentifier(param.name))) return void 0;
    const properties = arrayFrom(checker.getUnmatchedProperties(
      checker.getTypeAtLocation(parent2),
      checker.getParameterType(signature, argIndex).getNonNullableType(),
      /*requireOptionalProperties*/
      false,
      /*matchDiscriminantProperties*/
      false
    ));
    if (!length(properties)) return void 0;
    return { kind: 3 /* ObjectLiteral */, token: param.name, identifier: param.name.text, properties, parentDeclaration: parent2 };
  }
  if (token.kind === 19 /* OpenBraceToken */ && isObjectLiteralExpression(parent2)) {
    const targetType = (_a = checker.getContextualType(parent2) || checker.getTypeAtLocation(parent2)) == null ? void 0 : _a.getNonNullableType();
    const properties = arrayFrom(checker.getUnmatchedProperties(
      checker.getTypeAtLocation(parent2),
      targetType,
      /*requireOptionalProperties*/
      false,
      /*matchDiscriminantProperties*/
      false
    ));
    if (!length(properties)) return void 0;
    const identifier = "";
    return { kind: 3 /* ObjectLiteral */, token: parent2, identifier, properties, parentDeclaration: parent2 };
  }
  if (!isMemberName(token)) return void 0;
  if (isIdentifier(token) && hasInitializer(parent2) && parent2.initializer && isObjectLiteralExpression(parent2.initializer)) {
    const targetType = (_b = checker.getContextualType(token) || checker.getTypeAtLocation(token)) == null ? void 0 : _b.getNonNullableType();
    const properties = arrayFrom(checker.getUnmatchedProperties(
      checker.getTypeAtLocation(parent2.initializer),
      targetType,
      /*requireOptionalProperties*/
      false,
      /*matchDiscriminantProperties*/
      false
    ));
    if (!length(properties)) return void 0;
    return { kind: 3 /* ObjectLiteral */, token, identifier: token.text, properties, parentDeclaration: parent2.initializer };
  }
  if (isIdentifier(token) && isJsxOpeningLikeElement(token.parent)) {
    const target = getEmitScriptTarget(program.getCompilerOptions());
    const attributes = getUnmatchedAttributes(checker, target, token.parent);
    if (!length(attributes)) return void 0;
    return { kind: 4 /* JsxAttributes */, token, attributes, parentDeclaration: token.parent };
  }
  if (isIdentifier(token)) {
    const type = (_c = checker.getContextualType(token)) == null ? void 0 : _c.getNonNullableType();
    if (type && getObjectFlags(type) & 16 /* Anonymous */) {
      const signature = firstOrUndefined(checker.getSignaturesOfType(type, 0 /* Call */));
      if (signature === void 0) return void 0;
      return { kind: 5 /* Signature */, token, signature, sourceFile, parentDeclaration: findScope(token) };
    }
    if (isCallExpression(parent2) && parent2.expression === token) {
      return { kind: 2 /* Function */, token, call: parent2, sourceFile, modifierFlags: 0 /* None */, parentDeclaration: findScope(token) };
    }
  }
  if (!isPropertyAccessExpression(parent2)) return void 0;
  const leftExpressionType = skipConstraint(checker.getTypeAtLocation(parent2.expression));
  const symbol = leftExpressionType.symbol;
  if (!symbol || !symbol.declarations) return void 0;
  if (isIdentifier(token) && isCallExpression(parent2.parent)) {
    const moduleDeclaration = find(symbol.declarations, isModuleDeclaration);
    const moduleDeclarationSourceFile = moduleDeclaration == null ? void 0 : moduleDeclaration.getSourceFile();
    if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) {
      return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile: moduleDeclarationSourceFile, modifierFlags: 32 /* Export */, parentDeclaration: moduleDeclaration };
    }
    const moduleSourceFile = find(symbol.declarations, isSourceFile);
    if (sourceFile.commonJsModuleIndicator) return void 0;
    if (moduleSourceFile && !isSourceFileFromLibrary(program, moduleSourceFile)) {
      return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile: moduleSourceFile, modifierFlags: 32 /* Export */, parentDeclaration: moduleSourceFile };
    }
  }
  const classDeclaration = find(symbol.declarations, isClassLike);
  if (!classDeclaration && isPrivateIdentifier(token)) return void 0;
  const declaration = classDeclaration || find(symbol.declarations, (d) => isInterfaceDeclaration(d) || isTypeLiteralNode(d));
  if (declaration && !isSourceFileFromLibrary(program, declaration.getSourceFile())) {
    const makeStatic = !isTypeLiteralNode(declaration) && (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol);
    if (makeStatic && (isPrivateIdentifier(token) || isInterfaceDeclaration(declaration))) return void 0;
    const declSourceFile = declaration.getSourceFile();
    const modifierFlags = isTypeLiteralNode(declaration) ? 0 /* None */ : (makeStatic ? 256 /* Static */ : 0 /* None */) | (startsWithUnderscore(token.text) ? 2 /* Private */ : 0 /* None */);
    const isJSFile = isSourceFileJS(declSourceFile);
    const call = tryCast(parent2.parent, isCallExpression);
    return { kind: 0 /* TypeLikeDeclaration */, token, call, modifierFlags, parentDeclaration: declaration, declSourceFile, isJSFile };
  }
  const enumDeclaration = find(symbol.declarations, isEnumDeclaration);
  if (enumDeclaration && !(leftExpressionType.flags & 1056 /* EnumLike */) && !isPrivateIdentifier(token) && !isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) {
    return { kind: 1 /* Enum */, token, parentDeclaration: enumDeclaration };
  }
  return void 0;
}
function getActionsForMissingMemberDeclaration(context, info) {
  return info.isJSFile ? singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) : createActionsForAddMissingMemberInTypeScriptFile(context, info);
}
function createActionForAddMissingMemberInJavascriptFile(context, { parentDeclaration, declSourceFile, modifierFlags, token }) {
  if (isInterfaceDeclaration(parentDeclaration) || isTypeLiteralNode(parentDeclaration)) {
    return void 0;
  }
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingMemberInJs(t, declSourceFile, parentDeclaration, token, !!(modifierFlags & 256 /* Static */)));
  if (changes.length === 0) {
    return void 0;
  }
  const diagnostic = modifierFlags & 256 /* Static */ ? Diagnostics.Initialize_static_property_0 : isPrivateIdentifier(token) ? Diagnostics.Declare_a_private_field_named_0 : Diagnostics.Initialize_property_0_in_the_constructor;
  return createCodeFixAction(fixMissingMember, changes, [diagnostic, token.text], fixMissingMember, Diagnostics.Add_all_missing_members);
}
function addMissingMemberInJs(changeTracker, sourceFile, classDeclaration, token, makeStatic) {
  const tokenName = token.text;
  if (makeStatic) {
    if (classDeclaration.kind === 231 /* ClassExpression */) {
      return;
    }
    const className = classDeclaration.name.getText();
    const staticInitialization = initializePropertyToUndefined(factory.createIdentifier(className), tokenName);
    changeTracker.insertNodeAfter(sourceFile, classDeclaration, staticInitialization);
  } else if (isPrivateIdentifier(token)) {
    const property = factory.createPropertyDeclaration(
      /*modifiers*/
      void 0,
      tokenName,
      /*questionOrExclamationToken*/
      void 0,
      /*type*/
      void 0,
      /*initializer*/
      void 0
    );
    const lastProp = getNodeToInsertPropertyAfter(classDeclaration);
    if (lastProp) {
      changeTracker.insertNodeAfter(sourceFile, lastProp, property);
    } else {
      changeTracker.insertMemberAtStart(sourceFile, classDeclaration, property);
    }
  } else {
    const classConstructor = getFirstConstructorWithBody(classDeclaration);
    if (!classConstructor) {
      return;
    }
    const propertyInitialization = initializePropertyToUndefined(factory.createThis(), tokenName);
    changeTracker.insertNodeAtConstructorEnd(sourceFile, classConstructor, propertyInitialization);
  }
}
function initializePropertyToUndefined(obj, propertyName) {
  return factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(obj, propertyName), createUndefined()));
}
function createActionsForAddMissingMemberInTypeScriptFile(context, { parentDeclaration, declSourceFile, modifierFlags, token }) {
  const memberName = token.text;
  const isStatic2 = modifierFlags & 256 /* Static */;
  const typeNode = getTypeNode2(context.program.getTypeChecker(), parentDeclaration, token);
  const addPropertyDeclarationChanges = (modifierFlags2) => ts_textChanges_exports.ChangeTracker.with(context, (t) => addPropertyDeclaration(t, declSourceFile, parentDeclaration, memberName, typeNode, modifierFlags2));
  const actions2 = [createCodeFixAction(fixMissingMember, addPropertyDeclarationChanges(modifierFlags & 256 /* Static */), [isStatic2 ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0, memberName], fixMissingMember, Diagnostics.Add_all_missing_members)];
  if (isStatic2 || isPrivateIdentifier(token)) {
    return actions2;
  }
  if (modifierFlags & 2 /* Private */) {
    actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addPropertyDeclarationChanges(2 /* Private */), [Diagnostics.Declare_private_property_0, memberName]));
  }
  actions2.push(createAddIndexSignatureAction(context, declSourceFile, parentDeclaration, token.text, typeNode));
  return actions2;
}
function getTypeNode2(checker, node, token) {
  let typeNode;
  if (token.parent.parent.kind === 226 /* BinaryExpression */) {
    const binaryExpression = token.parent.parent;
    const otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left;
    const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression)));
    typeNode = checker.typeToTypeNode(widenedType, node, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */);
  } else {
    const contextualType = checker.getContextualType(token.parent);
    typeNode = contextualType ? checker.typeToTypeNode(
      contextualType,
      /*enclosingDeclaration*/
      void 0,
      1 /* NoTruncation */,
      8 /* AllowUnresolvedNames */
    ) : void 0;
  }
  return typeNode || factory.createKeywordTypeNode(133 /* AnyKeyword */);
}
function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, typeNode, modifierFlags) {
  const modifiers = modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : void 0;
  const property = isClassLike(node) ? factory.createPropertyDeclaration(
    modifiers,
    tokenName,
    /*questionOrExclamationToken*/
    void 0,
    typeNode,
    /*initializer*/
    void 0
  ) : factory.createPropertySignature(
    /*modifiers*/
    void 0,
    tokenName,
    /*questionToken*/
    void 0,
    typeNode
  );
  const lastProp = getNodeToInsertPropertyAfter(node);
  if (lastProp) {
    changeTracker.insertNodeAfter(sourceFile, lastProp, property);
  } else {
    changeTracker.insertMemberAtStart(sourceFile, node, property);
  }
}
function getNodeToInsertPropertyAfter(node) {
  let res;
  for (const member of node.members) {
    if (!isPropertyDeclaration(member)) break;
    res = member;
  }
  return res;
}
function createAddIndexSignatureAction(context, sourceFile, node, tokenName, typeNode) {
  const stringTypeNode = factory.createKeywordTypeNode(154 /* StringKeyword */);
  const indexingParameter = factory.createParameterDeclaration(
    /*modifiers*/
    void 0,
    /*dotDotDotToken*/
    void 0,
    "x",
    /*questionToken*/
    void 0,
    stringTypeNode,
    /*initializer*/
    void 0
  );
  const indexSignature = factory.createIndexSignature(
    /*modifiers*/
    void 0,
    [indexingParameter],
    typeNode
  );
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.insertMemberAtStart(sourceFile, node, indexSignature));
  return createCodeFixActionWithoutFixAll(fixMissingMember, changes, [Diagnostics.Add_index_signature_for_property_0, tokenName]);
}
function getActionsForMissingMethodDeclaration(context, info) {
  const { parentDeclaration, declSourceFile, modifierFlags, token, call } = info;
  if (call === void 0) {
    return void 0;
  }
  const methodName = token.text;
  const addMethodDeclarationChanges = (modifierFlags2) => ts_textChanges_exports.ChangeTracker.with(context, (t) => addMethodDeclaration(context, t, call, token, modifierFlags2, parentDeclaration, declSourceFile));
  const actions2 = [createCodeFixAction(fixMissingMember, addMethodDeclarationChanges(modifierFlags & 256 /* Static */), [modifierFlags & 256 /* Static */ ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0, methodName], fixMissingMember, Diagnostics.Add_all_missing_members)];
  if (modifierFlags & 2 /* Private */) {
    actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addMethodDeclarationChanges(2 /* Private */), [Diagnostics.Declare_private_method_0, methodName]));
  }
  return actions2;
}
function addMethodDeclaration(context, changes, callExpression, name, modifierFlags, parentDeclaration, sourceFile) {
  const importAdder = createImportAdder(sourceFile, context.program, context.preferences, context.host);
  const kind = isClassLike(parentDeclaration) ? 174 /* MethodDeclaration */ : 173 /* MethodSignature */;
  const signatureDeclaration = createSignatureDeclarationFromCallExpression(kind, context, importAdder, callExpression, name, modifierFlags, parentDeclaration);
  const containingMethodDeclaration = tryGetContainingMethodDeclaration(parentDeclaration, callExpression);
  if (containingMethodDeclaration) {
    changes.insertNodeAfter(sourceFile, containingMethodDeclaration, signatureDeclaration);
  } else {
    changes.insertMemberAtStart(sourceFile, parentDeclaration, signatureDeclaration);
  }
  importAdder.writeFixes(changes);
}
function addEnumMemberDeclaration(changes, checker, { token, parentDeclaration }) {
  const hasStringInitializer = some(parentDeclaration.members, (member) => {
    const type = checker.getTypeAtLocation(member);
    return !!(type && type.flags & 402653316 /* StringLike */);
  });
  const sourceFile = parentDeclaration.getSourceFile();
  const enumMember = factory.createEnumMember(token, hasStringInitializer ? factory.createStringLiteral(token.text) : void 0);
  const last2 = lastOrUndefined(parentDeclaration.members);
  if (last2) {
    changes.insertNodeInListAfter(sourceFile, last2, enumMember, parentDeclaration.members);
  } else {
    changes.insertMemberAtStart(sourceFile, parentDeclaration, enumMember);
  }
}
function addFunctionDeclaration(changes, context, info) {
  const quotePreference = getQuotePreference(context.sourceFile, context.preferences);
  const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host);
  const functionDeclaration = info.kind === 2 /* Function */ ? createSignatureDeclarationFromCallExpression(262 /* FunctionDeclaration */, context, importAdder, info.call, idText(info.token), info.modifierFlags, info.parentDeclaration) : createSignatureDeclarationFromSignature(
    262 /* FunctionDeclaration */,
    context,
    quotePreference,
    info.signature,
    createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference),
    info.token,
    /*modifiers*/
    void 0,
    /*optional*/
    void 0,
    /*enclosingDeclaration*/
    void 0,
    importAdder
  );
  if (functionDeclaration === void 0) {
    Debug.fail("fixMissingFunctionDeclaration codefix got unexpected error.");
  }
  isReturnStatement(info.parentDeclaration) ? changes.insertNodeBefore(
    info.sourceFile,
    info.parentDeclaration,
    functionDeclaration,
    /*blankLineBetween*/
    true
  ) : changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration);
  importAdder.writeFixes(changes);
}
function addJsxAttributes(changes, context, info) {
  const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host);
  const quotePreference = getQuotePreference(context.sourceFile, context.preferences);
  const checker = context.program.getTypeChecker();
  const jsxAttributesNode = info.parentDeclaration.attributes;
  const hasSpreadAttribute = some(jsxAttributesNode.properties, isJsxSpreadAttribute);
  const attrs = map(info.attributes, (attr) => {
    const value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr), info.parentDeclaration);
    const name = factory.createIdentifier(attr.name);
    const jsxAttribute = factory.createJsxAttribute(name, factory.createJsxExpression(
      /*dotDotDotToken*/
      void 0,
      value
    ));
    setParent(name, jsxAttribute);
    return jsxAttribute;
  });
  const jsxAttributes = factory.createJsxAttributes(hasSpreadAttribute ? [...attrs, ...jsxAttributesNode.properties] : [...jsxAttributesNode.properties, ...attrs]);
  const options = { prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : void 0 };
  changes.replaceNode(context.sourceFile, jsxAttributesNode, jsxAttributes, options);
  importAdder.writeFixes(changes);
}
function addObjectLiteralProperties(changes, context, info) {
  const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host);
  const quotePreference = getQuotePreference(context.sourceFile, context.preferences);
  const target = getEmitScriptTarget(context.program.getCompilerOptions());
  const checker = context.program.getTypeChecker();
  const props = map(info.properties, (prop) => {
    const initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), info.parentDeclaration);
    return factory.createPropertyAssignment(createPropertyNameFromSymbol(prop, target, quotePreference, checker), initializer);
  });
  const options = {
    leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude,
    trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude,
    indentation: info.indentation
  };
  changes.replaceNode(context.sourceFile, info.parentDeclaration, factory.createObjectLiteralExpression(
    [...info.parentDeclaration.properties, ...props],
    /*multiLine*/
    true
  ), options);
  importAdder.writeFixes(changes);
}
function tryGetValueFromType(context, checker, importAdder, quotePreference, type, enclosingDeclaration) {
  if (type.flags & 3 /* AnyOrUnknown */) {
    return createUndefined();
  }
  if (type.flags & (4 /* String */ | 134217728 /* TemplateLiteral */)) {
    return factory.createStringLiteral(
      "",
      /* isSingleQuote */
      quotePreference === 0 /* Single */
    );
  }
  if (type.flags & 8 /* Number */) {
    return factory.createNumericLiteral(0);
  }
  if (type.flags & 64 /* BigInt */) {
    return factory.createBigIntLiteral("0n");
  }
  if (type.flags & 16 /* Boolean */) {
    return factory.createFalse();
  }
  if (type.flags & 1056 /* EnumLike */) {
    const enumMember = type.symbol.exports ? firstOrUndefinedIterator(type.symbol.exports.values()) : type.symbol;
    const symbol = type.symbol.parent && type.symbol.parent.flags & 256 /* RegularEnum */ ? type.symbol.parent : type.symbol;
    const name = checker.symbolToExpression(
      symbol,
      111551 /* Value */,
      /*enclosingDeclaration*/
      void 0,
      /*flags*/
      64 /* UseFullyQualifiedType */
    );
    return enumMember === void 0 || name === void 0 ? factory.createNumericLiteral(0) : factory.createPropertyAccessExpression(name, checker.symbolToString(enumMember));
  }
  if (type.flags & 256 /* NumberLiteral */) {
    return factory.createNumericLiteral(type.value);
  }
  if (type.flags & 2048 /* BigIntLiteral */) {
    return factory.createBigIntLiteral(type.value);
  }
  if (type.flags & 128 /* StringLiteral */) {
    return factory.createStringLiteral(
      type.value,
      /* isSingleQuote */
      quotePreference === 0 /* Single */
    );
  }
  if (type.flags & 512 /* BooleanLiteral */) {
    return type === checker.getFalseType() || type === checker.getFalseType(
      /*fresh*/
      true
    ) ? factory.createFalse() : factory.createTrue();
  }
  if (type.flags & 65536 /* Null */) {
    return factory.createNull();
  }
  if (type.flags & 1048576 /* Union */) {
    const expression = firstDefined(type.types, (t) => tryGetValueFromType(context, checker, importAdder, quotePreference, t, enclosingDeclaration));
    return expression ?? createUndefined();
  }
  if (checker.isArrayLikeType(type)) {
    return factory.createArrayLiteralExpression();
  }
  if (isObjectLiteralType(type)) {
    const props = map(checker.getPropertiesOfType(type), (prop) => {
      const initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), enclosingDeclaration);
      return factory.createPropertyAssignment(prop.name, initializer);
    });
    return factory.createObjectLiteralExpression(
      props,
      /*multiLine*/
      true
    );
  }
  if (getObjectFlags(type) & 16 /* Anonymous */) {
    const decl = find(type.symbol.declarations || emptyArray, or(isFunctionTypeNode, isMethodSignature, isMethodDeclaration));
    if (decl === void 0) return createUndefined();
    const signature = checker.getSignaturesOfType(type, 0 /* Call */);
    if (signature === void 0) return createUndefined();
    const func = createSignatureDeclarationFromSignature(
      218 /* FunctionExpression */,
      context,
      quotePreference,
      signature[0],
      createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference),
      /*name*/
      void 0,
      /*modifiers*/
      void 0,
      /*optional*/
      void 0,
      /*enclosingDeclaration*/
      enclosingDeclaration,
      importAdder
    );
    return func ?? createUndefined();
  }
  if (getObjectFlags(type) & 1 /* Class */) {
    const classDeclaration = getClassLikeDeclarationOfSymbol(type.symbol);
    if (classDeclaration === void 0 || hasAbstractModifier(classDeclaration)) return createUndefined();
    const constructorDeclaration = getFirstConstructorWithBody(classDeclaration);
    if (constructorDeclaration && length(constructorDeclaration.parameters)) return createUndefined();
    return factory.createNewExpression(
      factory.createIdentifier(type.symbol.name),
      /*typeArguments*/
      void 0,
      /*argumentsArray*/
      void 0
    );
  }
  return createUndefined();
}
function createUndefined() {
  return factory.createIdentifier("undefined");
}
function isObjectLiteralType(type) {
  return type.flags & 524288 /* Object */ && (getObjectFlags(type) & 128 /* ObjectLiteral */ || type.symbol && tryCast(singleOrUndefined(type.symbol.declarations), isTypeLiteralNode));
}
function getUnmatchedAttributes(checker, target, source) {
  const attrsType = checker.getContextualType(source.attributes);
  if (attrsType === void 0) return emptyArray;
  const targetProps = attrsType.getProperties();
  if (!length(targetProps)) return emptyArray;
  const seenNames = /* @__PURE__ */ new Set();
  for (const sourceProp of source.attributes.properties) {
    if (isJsxAttribute(sourceProp)) {
      seenNames.add(getEscapedTextOfJsxAttributeName(sourceProp.name));
    }
    if (isJsxSpreadAttribute(sourceProp)) {
      const type = checker.getTypeAtLocation(sourceProp.expression);
      for (const prop of type.getProperties()) {
        seenNames.add(prop.escapedName);
      }
    }
  }
  return filter(targetProps, (targetProp) => isIdentifierText(targetProp.name, target, 1 /* JSX */) && !(targetProp.flags & 16777216 /* Optional */ || getCheckFlags(targetProp) & 48 /* Partial */ || seenNames.has(targetProp.escapedName)));
}
function tryGetContainingMethodDeclaration(node, callExpression) {
  if (isTypeLiteralNode(node)) {
    return void 0;
  }
  const declaration = findAncestor(callExpression, (n) => isMethodDeclaration(n) || isConstructorDeclaration(n));
  return declaration && declaration.parent === node ? declaration : void 0;
}
function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) {
  if (isTransientSymbol(symbol)) {
    const prop = checker.symbolToNode(
      symbol,
      111551 /* Value */,
      /*enclosingDeclaration*/
      void 0,
      /*flags*/
      void 0,
      1 /* WriteComputedProps */
    );
    if (prop && isComputedPropertyName(prop)) return prop;
  }
  return createPropertyNameNodeForIdentifierOrLiteral(
    symbol.name,
    target,
    quotePreference === 0 /* Single */,
    /*stringNamed*/
    false,
    /*isMethod*/
    false
  );
}
function findScope(node) {
  if (findAncestor(node, isJsxExpression)) {
    const returnStatement = findAncestor(node.parent, isReturnStatement);
    if (returnStatement) return returnStatement;
  }
  return getSourceFileOfNode(node);
}

// src/services/codefixes/fixAddMissingNewOperator.ts
var fixId25 = "addMissingNewOperator";
var errorCodes29 = [Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code];
registerCodeFix({
  errorCodes: errorCodes29,
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingNewOperator(t, sourceFile, span));
    return [createCodeFixAction(fixId25, changes, Diagnostics.Add_missing_new_operator_to_call, fixId25, Diagnostics.Add_missing_new_operator_to_all_calls)];
  },
  fixIds: [fixId25],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes29, (changes, diag2) => addMissingNewOperator(changes, context.sourceFile, diag2))
});
function addMissingNewOperator(changes, sourceFile, span) {
  const call = cast(findAncestorMatchingSpan2(sourceFile, span), isCallExpression);
  const newExpression = factory.createNewExpression(call.expression, call.typeArguments, call.arguments);
  changes.replaceNode(sourceFile, call, newExpression);
}
function findAncestorMatchingSpan2(sourceFile, span) {
  let token = getTokenAtPosition(sourceFile, span.start);
  const end = textSpanEnd(span);
  while (token.end < end) {
    token = token.parent;
  }
  return token;
}

// src/services/codefixes/fixAddMissingParam.ts
var addMissingParamFixId = "addMissingParam";
var addOptionalParamFixId = "addOptionalParam";
var errorCodes30 = [Diagnostics.Expected_0_arguments_but_got_1.code];
registerCodeFix({
  errorCodes: errorCodes30,
  fixIds: [addMissingParamFixId, addOptionalParamFixId],
  getCodeActions(context) {
    const info = getInfo11(context.sourceFile, context.program, context.span.start);
    if (info === void 0) return void 0;
    const { name, declarations, newParameters, newOptionalParameters } = info;
    const actions2 = [];
    if (length(newParameters)) {
      append(
        actions2,
        createCodeFixAction(
          addMissingParamFixId,
          ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, context.program, context.preferences, context.host, declarations, newParameters)),
          [length(newParameters) > 1 ? Diagnostics.Add_missing_parameters_to_0 : Diagnostics.Add_missing_parameter_to_0, name],
          addMissingParamFixId,
          Diagnostics.Add_all_missing_parameters
        )
      );
    }
    if (length(newOptionalParameters)) {
      append(
        actions2,
        createCodeFixAction(
          addOptionalParamFixId,
          ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, context.program, context.preferences, context.host, declarations, newOptionalParameters)),
          [length(newOptionalParameters) > 1 ? Diagnostics.Add_optional_parameters_to_0 : Diagnostics.Add_optional_parameter_to_0, name],
          addOptionalParamFixId,
          Diagnostics.Add_all_optional_parameters
        )
      );
    }
    return actions2;
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes30, (changes, diag2) => {
    const info = getInfo11(context.sourceFile, context.program, diag2.start);
    if (info) {
      const { declarations, newParameters, newOptionalParameters } = info;
      if (context.fixId === addMissingParamFixId) {
        doChange19(changes, context.program, context.preferences, context.host, declarations, newParameters);
      }
      if (context.fixId === addOptionalParamFixId) {
        doChange19(changes, context.program, context.preferences, context.host, declarations, newOptionalParameters);
      }
    }
  })
});
function getInfo11(sourceFile, program, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  const callExpression = findAncestor(token, isCallExpression);
  if (callExpression === void 0 || length(callExpression.arguments) === 0) {
    return void 0;
  }
  const checker = program.getTypeChecker();
  const type = checker.getTypeAtLocation(callExpression.expression);
  const convertibleSignatureDeclarations = filter(type.symbol.declarations, isConvertibleSignatureDeclaration);
  if (convertibleSignatureDeclarations === void 0) {
    return void 0;
  }
  const nonOverloadDeclaration = lastOrUndefined(convertibleSignatureDeclarations);
  if (nonOverloadDeclaration === void 0 || nonOverloadDeclaration.body === void 0 || isSourceFileFromLibrary(program, nonOverloadDeclaration.getSourceFile())) {
    return void 0;
  }
  const name = tryGetName2(nonOverloadDeclaration);
  if (name === void 0) {
    return void 0;
  }
  const newParameters = [];
  const newOptionalParameters = [];
  const parametersLength = length(nonOverloadDeclaration.parameters);
  const argumentsLength = length(callExpression.arguments);
  if (parametersLength > argumentsLength) {
    return void 0;
  }
  const declarations = [nonOverloadDeclaration, ...getOverloads(nonOverloadDeclaration, convertibleSignatureDeclarations)];
  for (let i = 0, pos2 = 0, paramIndex = 0; i < argumentsLength; i++) {
    const arg = callExpression.arguments[i];
    const expr = isAccessExpression(arg) ? getNameOfAccessExpression(arg) : arg;
    const type2 = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)));
    const parameter = pos2 < parametersLength ? nonOverloadDeclaration.parameters[pos2] : void 0;
    if (parameter && checker.isTypeAssignableTo(type2, checker.getTypeAtLocation(parameter))) {
      pos2++;
      continue;
    }
    const name2 = expr && isIdentifier(expr) ? expr.text : `p${paramIndex++}`;
    const typeNode = typeToTypeNode(checker, type2, nonOverloadDeclaration);
    append(newParameters, {
      pos: i,
      declaration: createParameter(
        name2,
        typeNode,
        /*questionToken*/
        void 0
      )
    });
    if (isOptionalPos(declarations, pos2)) {
      continue;
    }
    append(newOptionalParameters, {
      pos: i,
      declaration: createParameter(name2, typeNode, factory.createToken(58 /* QuestionToken */))
    });
  }
  return {
    newParameters,
    newOptionalParameters,
    name: declarationNameToString(name),
    declarations
  };
}
function tryGetName2(node) {
  const name = getNameOfDeclaration(node);
  if (name) {
    return name;
  }
  if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name) || isPropertyDeclaration(node.parent) || isParameter(node.parent)) {
    return node.parent.name;
  }
}
function typeToTypeNode(checker, type, enclosingDeclaration) {
  return checker.typeToTypeNode(checker.getWidenedType(type), enclosingDeclaration, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */) ?? factory.createKeywordTypeNode(159 /* UnknownKeyword */);
}
function doChange19(changes, program, preferences, host, declarations, newParameters) {
  const scriptTarget = getEmitScriptTarget(program.getCompilerOptions());
  forEach(declarations, (declaration) => {
    const sourceFile = getSourceFileOfNode(declaration);
    const importAdder = createImportAdder(sourceFile, program, preferences, host);
    if (length(declaration.parameters)) {
      changes.replaceNodeRangeWithNodes(
        sourceFile,
        first(declaration.parameters),
        last(declaration.parameters),
        updateParameters(importAdder, scriptTarget, declaration, newParameters),
        {
          joiner: ", ",
          indentation: 0,
          leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll,
          trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include
        }
      );
    } else {
      forEach(updateParameters(importAdder, scriptTarget, declaration, newParameters), (parameter, index) => {
        if (length(declaration.parameters) === 0 && index === 0) {
          changes.insertNodeAt(sourceFile, declaration.parameters.end, parameter);
        } else {
          changes.insertNodeAtEndOfList(sourceFile, declaration.parameters, parameter);
        }
      });
    }
    importAdder.writeFixes(changes);
  });
}
function isConvertibleSignatureDeclaration(node) {
  switch (node.kind) {
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
    case 174 /* MethodDeclaration */:
    case 219 /* ArrowFunction */:
      return true;
    default:
      return false;
  }
}
function updateParameters(importAdder, scriptTarget, node, newParameters) {
  const parameters = map(node.parameters, (p) => factory.createParameterDeclaration(
    p.modifiers,
    p.dotDotDotToken,
    p.name,
    p.questionToken,
    p.type,
    p.initializer
  ));
  for (const { pos, declaration } of newParameters) {
    const prev = pos > 0 ? parameters[pos - 1] : void 0;
    parameters.splice(
      pos,
      0,
      factory.updateParameterDeclaration(
        declaration,
        declaration.modifiers,
        declaration.dotDotDotToken,
        declaration.name,
        prev && prev.questionToken ? factory.createToken(58 /* QuestionToken */) : declaration.questionToken,
        getParameterType(importAdder, declaration.type, scriptTarget),
        declaration.initializer
      )
    );
  }
  return parameters;
}
function getOverloads(implementation, declarations) {
  const overloads = [];
  for (const declaration of declarations) {
    if (isOverload(declaration)) {
      if (length(declaration.parameters) === length(implementation.parameters)) {
        overloads.push(declaration);
        continue;
      }
      if (length(declaration.parameters) > length(implementation.parameters)) {
        return [];
      }
    }
  }
  return overloads;
}
function isOverload(declaration) {
  return isConvertibleSignatureDeclaration(declaration) && declaration.body === void 0;
}
function createParameter(name, type, questionToken) {
  return factory.createParameterDeclaration(
    /*modifiers*/
    void 0,
    /*dotDotDotToken*/
    void 0,
    name,
    questionToken,
    type,
    /*initializer*/
    void 0
  );
}
function isOptionalPos(declarations, pos) {
  return length(declarations) && some(declarations, (d) => pos < length(d.parameters) && !!d.parameters[pos] && d.parameters[pos].questionToken === void 0);
}
function getParameterType(importAdder, typeNode, scriptTarget) {
  const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget);
  if (importableReference) {
    importSymbols(importAdder, importableReference.symbols);
    return importableReference.typeNode;
  }
  return typeNode;
}

// src/services/codefixes/fixCannotFindModule.ts
var fixName2 = "fixCannotFindModule";
var fixIdInstallTypesPackage = "installTypesPackage";
var errorCodeCannotFindModule = Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations.code;
var errorCannotFindImplicitJsxImport = Diagnostics.This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_for_the_appropriate_package_installed.code;
var errorCodes31 = [
  errorCodeCannotFindModule,
  Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code,
  errorCannotFindImplicitJsxImport
];
registerCodeFix({
  errorCodes: errorCodes31,
  getCodeActions: function getCodeActionsToFixNotFoundModule(context) {
    const { host, sourceFile, span: { start }, errorCode } = context;
    const packageName = errorCode === errorCannotFindImplicitJsxImport ? getJSXImplicitImportBase(context.program.getCompilerOptions(), sourceFile) : tryGetImportedPackageName(sourceFile, start);
    if (packageName === void 0) return void 0;
    const typesPackageName = getTypesPackageNameToInstall(packageName, host, errorCode);
    return typesPackageName === void 0 ? [] : [createCodeFixAction(
      fixName2,
      /*changes*/
      [],
      [Diagnostics.Install_0, typesPackageName],
      fixIdInstallTypesPackage,
      Diagnostics.Install_all_missing_types_packages,
      getInstallCommand(sourceFile.fileName, typesPackageName)
    )];
  },
  fixIds: [fixIdInstallTypesPackage],
  getAllCodeActions: (context) => {
    return codeFixAll(context, errorCodes31, (_changes, diag2, commands) => {
      const packageName = tryGetImportedPackageName(diag2.file, diag2.start);
      if (packageName === void 0) return void 0;
      switch (context.fixId) {
        case fixIdInstallTypesPackage: {
          const pkg = getTypesPackageNameToInstall(packageName, context.host, diag2.code);
          if (pkg) {
            commands.push(getInstallCommand(diag2.file.fileName, pkg));
          }
          break;
        }
        default:
          Debug.fail(`Bad fixId: ${context.fixId}`);
      }
    });
  }
});
function getInstallCommand(fileName, packageName) {
  return { type: "install package", file: fileName, packageName };
}
function tryGetImportedPackageName(sourceFile, pos) {
  const moduleSpecifierText = tryCast(getTokenAtPosition(sourceFile, pos), isStringLiteral);
  if (!moduleSpecifierText) return void 0;
  const moduleName = moduleSpecifierText.text;
  const { packageName } = parsePackageName(moduleName);
  return isExternalModuleNameRelative(packageName) ? void 0 : packageName;
}
function getTypesPackageNameToInstall(packageName, host, diagCode) {
  var _a;
  return diagCode === errorCodeCannotFindModule ? nodeCoreModules.has(packageName) ? "@types/node" : void 0 : ((_a = host.isKnownTypesPackageName) == null ? void 0 : _a.call(host, packageName)) ? getTypesPackageName(packageName) : void 0;
}

// src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts
var errorCodes32 = [
  Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code,
  Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2.code,
  Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more.code,
  Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code,
  Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1.code,
  Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and_2_more.code
];
var fixId26 = "fixClassDoesntImplementInheritedAbstractMember";
registerCodeFix({
  errorCodes: errorCodes32,
  getCodeActions: function getCodeActionsToFixClassNotImplementingInheritedMembers(context) {
    const { sourceFile, span } = context;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingMembers(getClass2(sourceFile, span.start), sourceFile, context, t, context.preferences));
    return changes.length === 0 ? void 0 : [createCodeFixAction(fixId26, changes, Diagnostics.Implement_inherited_abstract_class, fixId26, Diagnostics.Implement_all_inherited_abstract_classes)];
  },
  fixIds: [fixId26],
  getAllCodeActions: function getAllCodeActionsToFixClassDoesntImplementInheritedAbstractMember(context) {
    const seenClassDeclarations = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes32, (changes, diag2) => {
      const classDeclaration = getClass2(diag2.file, diag2.start);
      if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) {
        addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences);
      }
    });
  }
});
function getClass2(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  return cast(token.parent, isClassLike);
}
function addMissingMembers(classDeclaration, sourceFile, context, changeTracker, preferences) {
  const extendsNode = getEffectiveBaseTypeNode(classDeclaration);
  const checker = context.program.getTypeChecker();
  const instantiatedExtendsType = checker.getTypeAtLocation(extendsNode);
  const abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember);
  const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host);
  createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, sourceFile, context, preferences, importAdder, (member) => changeTracker.insertMemberAtStart(sourceFile, classDeclaration, member));
  importAdder.writeFixes(changeTracker);
}
function symbolPointsToNonPrivateAndAbstractMember(symbol) {
  const flags = getSyntacticModifierFlags(first(symbol.getDeclarations()));
  return !(flags & 2 /* Private */) && !!(flags & 64 /* Abstract */);
}

// src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts
var fixId27 = "classSuperMustPrecedeThisAccess";
var errorCodes33 = [Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code];
registerCodeFix({
  errorCodes: errorCodes33,
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const nodes = getNodes(sourceFile, span.start);
    if (!nodes) return void 0;
    const { constructor, superCall } = nodes;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange20(t, sourceFile, constructor, superCall));
    return [createCodeFixAction(fixId27, changes, Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId27, Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)];
  },
  fixIds: [fixId27],
  getAllCodeActions(context) {
    const { sourceFile } = context;
    const seenClasses = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes33, (changes, diag2) => {
      const nodes = getNodes(diag2.file, diag2.start);
      if (!nodes) return;
      const { constructor, superCall } = nodes;
      if (addToSeen(seenClasses, getNodeId(constructor.parent))) {
        doChange20(changes, sourceFile, constructor, superCall);
      }
    });
  }
});
function doChange20(changes, sourceFile, constructor, superCall) {
  changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall);
  changes.delete(sourceFile, superCall);
}
function getNodes(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (token.kind !== 110 /* ThisKeyword */) return void 0;
  const constructor = getContainingFunction(token);
  const superCall = findSuperCall(constructor.body);
  return superCall && !superCall.expression.arguments.some((arg) => isPropertyAccessExpression(arg) && arg.expression === token) ? { constructor, superCall } : void 0;
}
function findSuperCall(n) {
  return isExpressionStatement(n) && isSuperCall(n.expression) ? n : isFunctionLike(n) ? void 0 : forEachChild(n, findSuperCall);
}

// src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts
var fixId28 = "constructorForDerivedNeedSuperCall";
var errorCodes34 = [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code];
registerCodeFix({
  errorCodes: errorCodes34,
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const ctr = getNode(sourceFile, span.start);
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange21(t, sourceFile, ctr));
    return [createCodeFixAction(fixId28, changes, Diagnostics.Add_missing_super_call, fixId28, Diagnostics.Add_all_missing_super_calls)];
  },
  fixIds: [fixId28],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes34, (changes, diag2) => doChange21(changes, context.sourceFile, getNode(diag2.file, diag2.start)))
});
function getNode(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  Debug.assert(isConstructorDeclaration(token.parent), "token should be at the constructor declaration");
  return token.parent;
}
function doChange21(changes, sourceFile, ctr) {
  const superCall = factory.createExpressionStatement(factory.createCallExpression(
    factory.createSuper(),
    /*typeArguments*/
    void 0,
    /*argumentsArray*/
    emptyArray
  ));
  changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall);
}

// src/services/codefixes/fixEnableJsxFlag.ts
var fixID = "fixEnableJsxFlag";
var errorCodes35 = [Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code];
registerCodeFix({
  errorCodes: errorCodes35,
  getCodeActions: function getCodeActionsToFixEnableJsxFlag(context) {
    const { configFile } = context.program.getCompilerOptions();
    if (configFile === void 0) {
      return void 0;
    }
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => doChange22(changeTracker, configFile));
    return [
      createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file)
    ];
  },
  fixIds: [fixID],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes35, (changes) => {
    const { configFile } = context.program.getCompilerOptions();
    if (configFile === void 0) {
      return void 0;
    }
    doChange22(changes, configFile);
  })
});
function doChange22(changeTracker, configFile) {
  setJsonCompilerOptionValue(changeTracker, configFile, "jsx", factory.createStringLiteral("react"));
}

// src/services/codefixes/fixNaNEquality.ts
var fixId29 = "fixNaNEquality";
var errorCodes36 = [
  Diagnostics.This_condition_will_always_return_0.code
];
registerCodeFix({
  errorCodes: errorCodes36,
  getCodeActions(context) {
    const { sourceFile, span, program } = context;
    const info = getInfo12(program, sourceFile, span);
    if (info === void 0) return;
    const { suggestion, expression, arg } = info;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange23(t, sourceFile, arg, expression));
    return [createCodeFixAction(fixId29, changes, [Diagnostics.Use_0, suggestion], fixId29, Diagnostics.Use_Number_isNaN_in_all_conditions)];
  },
  fixIds: [fixId29],
  getAllCodeActions: (context) => {
    return codeFixAll(context, errorCodes36, (changes, diag2) => {
      const info = getInfo12(context.program, diag2.file, createTextSpan(diag2.start, diag2.length));
      if (info) {
        doChange23(changes, diag2.file, info.arg, info.expression);
      }
    });
  }
});
function getInfo12(program, sourceFile, span) {
  const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length);
  if (diag2 === void 0 || diag2.relatedInformation === void 0) return;
  const related = find(diag2.relatedInformation, (related2) => related2.code === Diagnostics.Did_you_mean_0.code);
  if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) return;
  const token = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length));
  if (token === void 0) return;
  if (isExpression(token) && isBinaryExpression(token.parent)) {
    return { suggestion: getSuggestion(related.messageText), expression: token.parent, arg: token };
  }
  return void 0;
}
function doChange23(changes, sourceFile, arg, expression) {
  const callExpression = factory.createCallExpression(
    factory.createPropertyAccessExpression(factory.createIdentifier("Number"), factory.createIdentifier("isNaN")),
    /*typeArguments*/
    void 0,
    [arg]
  );
  const operator = expression.operatorToken.kind;
  changes.replaceNode(
    sourceFile,
    expression,
    operator === 38 /* ExclamationEqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */ ? factory.createPrefixUnaryExpression(54 /* ExclamationToken */, callExpression) : callExpression
  );
}
function getSuggestion(messageText) {
  const [, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/'(.*)'/) || [];
  return suggestion;
}

// src/services/codefixes/fixModuleAndTargetOptions.ts
registerCodeFix({
  errorCodes: [
    Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher.code,
    Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher.code,
    Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher.code
  ],
  getCodeActions: function getCodeActionsToFixModuleAndTarget(context) {
    const compilerOptions = context.program.getCompilerOptions();
    const { configFile } = compilerOptions;
    if (configFile === void 0) {
      return void 0;
    }
    const codeFixes = [];
    const moduleKind = getEmitModuleKind(compilerOptions);
    const moduleOutOfRange = moduleKind >= 5 /* ES2015 */ && moduleKind < 99 /* ESNext */;
    if (moduleOutOfRange) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => {
        setJsonCompilerOptionValue(changes2, configFile, "module", factory.createStringLiteral("esnext"));
      });
      codeFixes.push(createCodeFixActionWithoutFixAll("fixModuleOption", changes, [Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, "esnext"]));
    }
    const target = getEmitScriptTarget(compilerOptions);
    const targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */;
    if (targetOutOfRange) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => {
        const configObject = getTsConfigObjectLiteralExpression(configFile);
        if (!configObject) return;
        const options = [["target", factory.createStringLiteral("es2017")]];
        if (moduleKind === 1 /* CommonJS */) {
          options.push(["module", factory.createStringLiteral("commonjs")]);
        }
        setJsonCompilerOptionValues(tracker, configFile, options);
      });
      codeFixes.push(createCodeFixActionWithoutFixAll("fixTargetOption", changes, [Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, "es2017"]));
    }
    return codeFixes.length ? codeFixes : void 0;
  }
});

// src/services/codefixes/fixPropertyAssignment.ts
var fixId30 = "fixPropertyAssignment";
var errorCodes37 = [
  Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code
];
registerCodeFix({
  errorCodes: errorCodes37,
  fixIds: [fixId30],
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const property = getProperty2(sourceFile, span.start);
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange24(t, context.sourceFile, property));
    return [createCodeFixAction(fixId30, changes, [Diagnostics.Change_0_to_1, "=", ":"], fixId30, [Diagnostics.Switch_each_misused_0_to_1, "=", ":"])];
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes37, (changes, diag2) => doChange24(changes, diag2.file, getProperty2(diag2.file, diag2.start)))
});
function doChange24(changes, sourceFile, node) {
  changes.replaceNode(sourceFile, node, factory.createPropertyAssignment(node.name, node.objectAssignmentInitializer));
}
function getProperty2(sourceFile, pos) {
  return cast(getTokenAtPosition(sourceFile, pos).parent, isShorthandPropertyAssignment);
}

// src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts
var fixId31 = "extendsInterfaceBecomesImplements";
var errorCodes38 = [Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code];
registerCodeFix({
  errorCodes: errorCodes38,
  getCodeActions(context) {
    const { sourceFile } = context;
    const nodes = getNodes2(sourceFile, context.span.start);
    if (!nodes) return void 0;
    const { extendsToken, heritageClauses } = nodes;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChanges2(t, sourceFile, extendsToken, heritageClauses));
    return [createCodeFixAction(fixId31, changes, Diagnostics.Change_extends_to_implements, fixId31, Diagnostics.Change_all_extended_interfaces_to_implements)];
  },
  fixIds: [fixId31],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes38, (changes, diag2) => {
    const nodes = getNodes2(diag2.file, diag2.start);
    if (nodes) doChanges2(changes, diag2.file, nodes.extendsToken, nodes.heritageClauses);
  })
});
function getNodes2(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  const heritageClauses = getContainingClass(token).heritageClauses;
  const extendsToken = heritageClauses[0].getFirstToken();
  return extendsToken.kind === 96 /* ExtendsKeyword */ ? { extendsToken, heritageClauses } : void 0;
}
function doChanges2(changes, sourceFile, extendsToken, heritageClauses) {
  changes.replaceNode(sourceFile, extendsToken, factory.createToken(119 /* ImplementsKeyword */));
  if (heritageClauses.length === 2 && heritageClauses[0].token === 96 /* ExtendsKeyword */ && heritageClauses[1].token === 119 /* ImplementsKeyword */) {
    const implementsToken = heritageClauses[1].getFirstToken();
    const implementsFullStart = implementsToken.getFullStart();
    changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, factory.createToken(28 /* CommaToken */));
    const text = sourceFile.text;
    let end = implementsToken.end;
    while (end < text.length && isWhiteSpaceSingleLine(text.charCodeAt(end))) {
      end++;
    }
    changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end });
  }
}

// src/services/codefixes/fixForgottenThisPropertyAccess.ts
var fixId32 = "forgottenThisPropertyAccess";
var didYouMeanStaticMemberCode = Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code;
var errorCodes39 = [
  Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
  Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code,
  didYouMeanStaticMemberCode
];
registerCodeFix({
  errorCodes: errorCodes39,
  getCodeActions(context) {
    const { sourceFile } = context;
    const info = getInfo13(sourceFile, context.span.start, context.errorCode);
    if (!info) {
      return void 0;
    }
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25(t, sourceFile, info));
    return [createCodeFixAction(fixId32, changes, [Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId32, Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)];
  },
  fixIds: [fixId32],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes39, (changes, diag2) => {
    const info = getInfo13(diag2.file, diag2.start, diag2.code);
    if (info) doChange25(changes, context.sourceFile, info);
  })
});
function getInfo13(sourceFile, pos, diagCode) {
  const node = getTokenAtPosition(sourceFile, pos);
  if (isIdentifier(node) || isPrivateIdentifier(node)) {
    return { node, className: diagCode === didYouMeanStaticMemberCode ? getContainingClass(node).name.text : void 0 };
  }
}
function doChange25(changes, sourceFile, { node, className }) {
  suppressLeadingAndTrailingTrivia(node);
  changes.replaceNode(sourceFile, node, factory.createPropertyAccessExpression(className ? factory.createIdentifier(className) : factory.createThis(), node));
}

// src/services/codefixes/fixInvalidJsxCharacters.ts
var fixIdExpression = "fixInvalidJsxCharacters_expression";
var fixIdHtmlEntity = "fixInvalidJsxCharacters_htmlEntity";
var errorCodes40 = [
  Diagnostics.Unexpected_token_Did_you_mean_or_gt.code,
  Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code
];
registerCodeFix({
  errorCodes: errorCodes40,
  fixIds: [fixIdExpression, fixIdHtmlEntity],
  getCodeActions(context) {
    const { sourceFile, preferences, span } = context;
    const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange26(
      t,
      preferences,
      sourceFile,
      span.start,
      /*useHtmlEntity*/
      false
    ));
    const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange26(
      t,
      preferences,
      sourceFile,
      span.start,
      /*useHtmlEntity*/
      true
    ));
    return [
      createCodeFixAction(fixIdExpression, changeToExpression, Diagnostics.Wrap_invalid_character_in_an_expression_container, fixIdExpression, Diagnostics.Wrap_all_invalid_characters_in_an_expression_container),
      createCodeFixAction(fixIdHtmlEntity, changeToHtmlEntity, Diagnostics.Convert_invalid_character_to_its_html_entity_code, fixIdHtmlEntity, Diagnostics.Convert_all_invalid_characters_to_HTML_entity_code)
    ];
  },
  getAllCodeActions(context) {
    return codeFixAll(context, errorCodes40, (changes, diagnostic) => doChange26(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity));
  }
});
var htmlEntity = {
  ">": "&gt;",
  "}": "&rbrace;"
};
function isValidCharacter(character) {
  return hasProperty(htmlEntity, character);
}
function doChange26(changes, preferences, sourceFile, start, useHtmlEntity) {
  const character = sourceFile.getText()[start];
  if (!isValidCharacter(character)) {
    return;
  }
  const replacement = useHtmlEntity ? htmlEntity[character] : `{${quote(sourceFile, preferences, character)}}`;
  changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 1 }, replacement);
}

// src/services/codefixes/fixUnmatchedParameter.ts
var deleteUnmatchedParameter = "deleteUnmatchedParameter";
var renameUnmatchedParameter = "renameUnmatchedParameter";
var errorCodes41 = [
  Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name.code
];
registerCodeFix({
  fixIds: [deleteUnmatchedParameter, renameUnmatchedParameter],
  errorCodes: errorCodes41,
  getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) {
    const { sourceFile, span } = context;
    const actions2 = [];
    const info = getInfo14(sourceFile, span.start);
    if (info) {
      append(actions2, getDeleteAction(context, info));
      append(actions2, getRenameAction(context, info));
      return actions2;
    }
    return void 0;
  },
  getAllCodeActions: function getAllCodeActionsToFixUnmatchedParameter(context) {
    const tagsToSignature = /* @__PURE__ */ new Map();
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      eachDiagnostic(context, errorCodes41, ({ file, start }) => {
        const info = getInfo14(file, start);
        if (info) {
          tagsToSignature.set(info.signature, append(tagsToSignature.get(info.signature), info.jsDocParameterTag));
        }
      });
      tagsToSignature.forEach((tags, signature) => {
        if (context.fixId === deleteUnmatchedParameter) {
          const tagsSet = new Set(tags);
          changes.filterJSDocTags(signature.getSourceFile(), signature, (t) => !tagsSet.has(t));
        }
      });
    }));
  }
});
function getDeleteAction(context, { name, jsDocHost, jsDocParameterTag }) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.filterJSDocTags(context.sourceFile, jsDocHost, (t) => t !== jsDocParameterTag));
  return createCodeFixAction(
    deleteUnmatchedParameter,
    changes,
    [Diagnostics.Delete_unused_param_tag_0, name.getText(context.sourceFile)],
    deleteUnmatchedParameter,
    Diagnostics.Delete_all_unused_param_tags
  );
}
function getRenameAction(context, { name, jsDocHost, signature, jsDocParameterTag }) {
  if (!length(signature.parameters)) return void 0;
  const sourceFile = context.sourceFile;
  const tags = getJSDocTags(signature);
  const names = /* @__PURE__ */ new Set();
  for (const tag of tags) {
    if (isJSDocParameterTag(tag) && isIdentifier(tag.name)) {
      names.add(tag.name.escapedText);
    }
  }
  const parameterName = firstDefined(signature.parameters, (p) => isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : void 0);
  if (parameterName === void 0) return void 0;
  const newJSDocParameterTag = factory.updateJSDocParameterTag(
    jsDocParameterTag,
    jsDocParameterTag.tagName,
    factory.createIdentifier(parameterName),
    jsDocParameterTag.isBracketed,
    jsDocParameterTag.typeExpression,
    jsDocParameterTag.isNameFirst,
    jsDocParameterTag.comment
  );
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.replaceJSDocComment(sourceFile, jsDocHost, map(tags, (t) => t === jsDocParameterTag ? newJSDocParameterTag : t)));
  return createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [Diagnostics.Rename_param_tag_name_0_to_1, name.getText(sourceFile), parameterName]);
}
function getInfo14(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (token.parent && isJSDocParameterTag(token.parent) && isIdentifier(token.parent.name)) {
    const jsDocParameterTag = token.parent;
    const jsDocHost = getJSDocHost(jsDocParameterTag);
    const signature = getHostSignatureFromJSDoc(jsDocParameterTag);
    if (jsDocHost && signature) {
      return { jsDocHost, signature, name: token.parent.name, jsDocParameterTag };
    }
  }
  return void 0;
}

// src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts
var fixId33 = "fixUnreferenceableDecoratorMetadata";
var errorCodes42 = [Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled.code];
registerCodeFix({
  errorCodes: errorCodes42,
  getCodeActions: (context) => {
    const importDeclaration = getImportDeclaration(context.sourceFile, context.program, context.span.start);
    if (!importDeclaration) return;
    const namespaceChanges = ts_textChanges_exports.ChangeTracker.with(context, (t) => importDeclaration.kind === 276 /* ImportSpecifier */ && doNamespaceImportChange(t, context.sourceFile, importDeclaration, context.program));
    const typeOnlyChanges = ts_textChanges_exports.ChangeTracker.with(context, (t) => doTypeOnlyImportChange(t, context.sourceFile, importDeclaration, context.program));
    let actions2;
    if (namespaceChanges.length) {
      actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId33, namespaceChanges, Diagnostics.Convert_named_imports_to_namespace_import));
    }
    if (typeOnlyChanges.length) {
      actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId33, typeOnlyChanges, Diagnostics.Use_import_type));
    }
    return actions2;
  },
  fixIds: [fixId33]
});
function getImportDeclaration(sourceFile, program, start) {
  const identifier = tryCast(getTokenAtPosition(sourceFile, start), isIdentifier);
  if (!identifier || identifier.parent.kind !== 183 /* TypeReference */) return;
  const checker = program.getTypeChecker();
  const symbol = checker.getSymbolAtLocation(identifier);
  return find((symbol == null ? void 0 : symbol.declarations) || emptyArray, or(isImportClause, isImportSpecifier, isImportEqualsDeclaration));
}
function doTypeOnlyImportChange(changes, sourceFile, importDeclaration, program) {
  if (importDeclaration.kind === 271 /* ImportEqualsDeclaration */) {
    changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */, importDeclaration.name);
    return;
  }
  const importClause = importDeclaration.kind === 273 /* ImportClause */ ? importDeclaration : importDeclaration.parent.parent;
  if (importClause.name && importClause.namedBindings) {
    return;
  }
  const checker = program.getTypeChecker();
  const importsValue = !!forEachImportClauseDeclaration(importClause, (decl) => {
    if (skipAlias(decl.symbol, checker).flags & 111551 /* Value */) return true;
  });
  if (importsValue) {
    return;
  }
  changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */, importClause);
}
function doNamespaceImportChange(changes, sourceFile, importDeclaration, program) {
  ts_refactor_exports.doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, importDeclaration.parent);
}

// src/services/codefixes/fixUnusedIdentifier.ts
var fixName3 = "unusedIdentifier";
var fixIdPrefix = "unusedIdentifier_prefix";
var fixIdDelete = "unusedIdentifier_delete";
var fixIdDeleteImports = "unusedIdentifier_deleteImports";
var fixIdInfer = "unusedIdentifier_infer";
var errorCodes43 = [
  Diagnostics._0_is_declared_but_its_value_is_never_read.code,
  Diagnostics._0_is_declared_but_never_used.code,
  Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
  Diagnostics.All_imports_in_import_declaration_are_unused.code,
  Diagnostics.All_destructured_elements_are_unused.code,
  Diagnostics.All_variables_are_unused.code,
  Diagnostics.All_type_parameters_are_unused.code
];
registerCodeFix({
  errorCodes: errorCodes43,
  getCodeActions(context) {
    const { errorCode, sourceFile, program, cancellationToken } = context;
    const checker = program.getTypeChecker();
    const sourceFiles = program.getSourceFiles();
    const token = getTokenAtPosition(sourceFile, context.span.start);
    if (isJSDocTemplateTag(token)) {
      return [createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => t.delete(sourceFile, token)), Diagnostics.Remove_template_tag)];
    }
    if (token.kind === 30 /* LessThanToken */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteTypeParameters(t, sourceFile, token));
      return [createDeleteFix(changes, Diagnostics.Remove_type_parameters)];
    }
    const importDecl = tryGetFullImport(token);
    if (importDecl) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.delete(sourceFile, importDecl));
      return [createCodeFixAction(fixName3, changes, [Diagnostics.Remove_import_from_0, showModuleSpecifier(importDecl)], fixIdDeleteImports, Diagnostics.Delete_all_unused_imports)];
    } else if (isImport(token)) {
      const deletion = ts_textChanges_exports.ChangeTracker.with(context, (t) => tryDeleteDeclaration(
        sourceFile,
        token,
        t,
        checker,
        sourceFiles,
        program,
        cancellationToken,
        /*isFixAll*/
        false
      ));
      if (deletion.length) {
        return [createCodeFixAction(fixName3, deletion, [Diagnostics.Remove_unused_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDeleteImports, Diagnostics.Delete_all_unused_imports)];
      }
    }
    if (isObjectBindingPattern(token.parent) || isArrayBindingPattern(token.parent)) {
      if (isParameter(token.parent.parent)) {
        const elements = token.parent.elements;
        const diagnostic = [
          elements.length > 1 ? Diagnostics.Remove_unused_declarations_for_Colon_0 : Diagnostics.Remove_unused_declaration_for_Colon_0,
          map(elements, (e) => e.getText(sourceFile)).join(", ")
        ];
        return [
          createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteDestructuringElements(t, sourceFile, token.parent)), diagnostic)
        ];
      }
      return [
        createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteDestructuring(context, t, sourceFile, token.parent)), Diagnostics.Remove_unused_destructuring_declaration)
      ];
    }
    if (canDeleteEntireVariableStatement(sourceFile, token)) {
      return [
        createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteEntireVariableStatement(t, sourceFile, token.parent)), Diagnostics.Remove_variable_statement)
      ];
    }
    if (isIdentifier(token) && isFunctionDeclaration(token.parent)) {
      return [createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteFunctionLikeDeclaration(t, sourceFile, token.parent)), [Diagnostics.Remove_unused_declaration_for_Colon_0, token.getText(sourceFile)])];
    }
    const result = [];
    if (token.kind === 140 /* InferKeyword */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => changeInferToUnknown(t, sourceFile, token));
      const name = cast(token.parent, isInferTypeNode).typeParameter.name.text;
      result.push(createCodeFixAction(fixName3, changes, [Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, Diagnostics.Replace_all_unused_infer_with_unknown));
    } else {
      const deletion = ts_textChanges_exports.ChangeTracker.with(context, (t) => tryDeleteDeclaration(
        sourceFile,
        token,
        t,
        checker,
        sourceFiles,
        program,
        cancellationToken,
        /*isFixAll*/
        false
      ));
      if (deletion.length) {
        const name = isComputedPropertyName(token.parent) ? token.parent : token;
        result.push(createDeleteFix(deletion, [Diagnostics.Remove_unused_declaration_for_Colon_0, name.getText(sourceFile)]));
      }
    }
    const prefix = ts_textChanges_exports.ChangeTracker.with(context, (t) => tryPrefixDeclaration(t, errorCode, sourceFile, token));
    if (prefix.length) {
      result.push(createCodeFixAction(fixName3, prefix, [Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, Diagnostics.Prefix_all_unused_declarations_with_where_possible));
    }
    return result;
  },
  fixIds: [fixIdPrefix, fixIdDelete, fixIdDeleteImports, fixIdInfer],
  getAllCodeActions: (context) => {
    const { sourceFile, program, cancellationToken } = context;
    const checker = program.getTypeChecker();
    const sourceFiles = program.getSourceFiles();
    return codeFixAll(context, errorCodes43, (changes, diag2) => {
      const token = getTokenAtPosition(sourceFile, diag2.start);
      switch (context.fixId) {
        case fixIdPrefix:
          tryPrefixDeclaration(changes, diag2.code, sourceFile, token);
          break;
        case fixIdDeleteImports: {
          const importDecl = tryGetFullImport(token);
          if (importDecl) {
            changes.delete(sourceFile, importDecl);
          } else if (isImport(token)) {
            tryDeleteDeclaration(
              sourceFile,
              token,
              changes,
              checker,
              sourceFiles,
              program,
              cancellationToken,
              /*isFixAll*/
              true
            );
          }
          break;
        }
        case fixIdDelete: {
          if (token.kind === 140 /* InferKeyword */ || isImport(token)) {
            break;
          } else if (isJSDocTemplateTag(token)) {
            changes.delete(sourceFile, token);
          } else if (token.kind === 30 /* LessThanToken */) {
            deleteTypeParameters(changes, sourceFile, token);
          } else if (isObjectBindingPattern(token.parent)) {
            if (token.parent.parent.initializer) {
              break;
            } else if (!isParameter(token.parent.parent) || isNotProvidedArguments(token.parent.parent, checker, sourceFiles)) {
              changes.delete(sourceFile, token.parent.parent);
            }
          } else if (isArrayBindingPattern(token.parent.parent) && token.parent.parent.parent.initializer) {
            break;
          } else if (canDeleteEntireVariableStatement(sourceFile, token)) {
            deleteEntireVariableStatement(changes, sourceFile, token.parent);
          } else {
            tryDeleteDeclaration(
              sourceFile,
              token,
              changes,
              checker,
              sourceFiles,
              program,
              cancellationToken,
              /*isFixAll*/
              true
            );
          }
          break;
        }
        case fixIdInfer:
          if (token.kind === 140 /* InferKeyword */) {
            changeInferToUnknown(changes, sourceFile, token);
          }
          break;
        default:
          Debug.fail(JSON.stringify(context.fixId));
      }
    });
  }
});
function changeInferToUnknown(changes, sourceFile, token) {
  changes.replaceNode(sourceFile, token.parent, factory.createKeywordTypeNode(159 /* UnknownKeyword */));
}
function createDeleteFix(changes, diag2) {
  return createCodeFixAction(fixName3, changes, diag2, fixIdDelete, Diagnostics.Delete_all_unused_declarations);
}
function deleteTypeParameters(changes, sourceFile, token) {
  changes.delete(sourceFile, Debug.checkDefined(cast(token.parent, isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist"));
}
function isImport(token) {
  return token.kind === 102 /* ImportKeyword */ || token.kind === 80 /* Identifier */ && (token.parent.kind === 276 /* ImportSpecifier */ || token.parent.kind === 273 /* ImportClause */);
}
function tryGetFullImport(token) {
  return token.kind === 102 /* ImportKeyword */ ? tryCast(token.parent, isImportDeclaration) : void 0;
}
function canDeleteEntireVariableStatement(sourceFile, token) {
  return isVariableDeclarationList(token.parent) && first(token.parent.getChildren(sourceFile)) === token;
}
function deleteEntireVariableStatement(changes, sourceFile, node) {
  changes.delete(sourceFile, node.parent.kind === 243 /* VariableStatement */ ? node.parent : node);
}
function deleteDestructuringElements(changes, sourceFile, node) {
  forEach(node.elements, (n) => changes.delete(sourceFile, n));
}
function deleteDestructuring(context, changes, sourceFile, { parent: parent2 }) {
  if (isVariableDeclaration(parent2) && parent2.initializer && isCallLikeExpression(parent2.initializer)) {
    if (isVariableDeclarationList(parent2.parent) && length(parent2.parent.declarations) > 1) {
      const varStatement = parent2.parent.parent;
      const pos = varStatement.getStart(sourceFile);
      const end = varStatement.end;
      changes.delete(sourceFile, parent2);
      changes.insertNodeAt(sourceFile, end, parent2.initializer, {
        prefix: getNewLineOrDefaultFromHost(context.host, context.formatContext.options) + sourceFile.text.slice(getPrecedingNonSpaceCharacterPosition(sourceFile.text, pos - 1), pos),
        suffix: probablyUsesSemicolons(sourceFile) ? ";" : ""
      });
    } else {
      changes.replaceNode(sourceFile, parent2.parent, parent2.initializer);
    }
  } else {
    changes.delete(sourceFile, parent2);
  }
}
function tryPrefixDeclaration(changes, errorCode, sourceFile, token) {
  if (errorCode === Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) return;
  if (token.kind === 140 /* InferKeyword */) {
    token = cast(token.parent, isInferTypeNode).typeParameter.name;
  }
  if (isIdentifier(token) && canPrefix(token)) {
    changes.replaceNode(sourceFile, token, factory.createIdentifier(`_${token.text}`));
    if (isParameter(token.parent)) {
      getJSDocParameterTags(token.parent).forEach((tag) => {
        if (isIdentifier(tag.name)) {
          changes.replaceNode(sourceFile, tag.name, factory.createIdentifier(`_${tag.name.text}`));
        }
      });
    }
  }
}
function canPrefix(token) {
  switch (token.parent.kind) {
    case 169 /* Parameter */:
    case 168 /* TypeParameter */:
      return true;
    case 260 /* VariableDeclaration */: {
      const varDecl = token.parent;
      switch (varDecl.parent.parent.kind) {
        case 250 /* ForOfStatement */:
        case 249 /* ForInStatement */:
          return true;
      }
    }
  }
  return false;
}
function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, isFixAll) {
  tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll);
  if (isIdentifier(token)) {
    ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(token, checker, sourceFile, (ref) => {
      if (isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) ref = ref.parent;
      if (!isFixAll && mayDeleteExpression(ref)) {
        changes.delete(sourceFile, ref.parent.parent);
      }
    });
  }
}
function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll) {
  const { parent: parent2 } = token;
  if (isParameter(parent2)) {
    tryDeleteParameter(changes, sourceFile, parent2, checker, sourceFiles, program, cancellationToken, isFixAll);
  } else if (!(isFixAll && isIdentifier(token) && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(token, checker, sourceFile))) {
    const node = isImportClause(parent2) ? token : isComputedPropertyName(parent2) ? parent2.parent : parent2;
    Debug.assert(node !== sourceFile, "should not delete whole source file");
    changes.delete(sourceFile, node);
  }
}
function tryDeleteParameter(changes, sourceFile, parameter, checker, sourceFiles, program, cancellationToken, isFixAll = false) {
  if (mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll)) {
    if (parameter.modifiers && parameter.modifiers.length > 0 && (!isIdentifier(parameter.name) || ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile))) {
      for (const modifier of parameter.modifiers) {
        if (isModifier(modifier)) {
          changes.deleteModifier(sourceFile, modifier);
        }
      }
    } else if (!parameter.initializer && isNotProvidedArguments(parameter, checker, sourceFiles)) {
      changes.delete(sourceFile, parameter);
    }
  }
}
function isNotProvidedArguments(parameter, checker, sourceFiles) {
  const index = parameter.parent.parameters.indexOf(parameter);
  return !ts_FindAllReferences_exports.Core.someSignatureUsage(parameter.parent, sourceFiles, checker, (_, call) => !call || call.arguments.length > index);
}
function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll) {
  const { parent: parent2 } = parameter;
  switch (parent2.kind) {
    case 174 /* MethodDeclaration */:
    case 176 /* Constructor */:
      const index = parent2.parameters.indexOf(parameter);
      const referent = isMethodDeclaration(parent2) ? parent2.name : parent2;
      const entries = ts_FindAllReferences_exports.Core.getReferencedSymbolsForNode(parent2.pos, referent, program, sourceFiles, cancellationToken);
      if (entries) {
        for (const entry of entries) {
          for (const reference of entry.references) {
            if (reference.kind === ts_FindAllReferences_exports.EntryKind.Node) {
              const isSuperCall2 = isSuperKeyword(reference.node) && isCallExpression(reference.node.parent) && reference.node.parent.arguments.length > index;
              const isSuperMethodCall = isPropertyAccessExpression(reference.node.parent) && isSuperKeyword(reference.node.parent.expression) && isCallExpression(reference.node.parent.parent) && reference.node.parent.parent.arguments.length > index;
              const isOverriddenMethod = (isMethodDeclaration(reference.node.parent) || isMethodSignature(reference.node.parent)) && reference.node.parent !== parameter.parent && reference.node.parent.parameters.length > index;
              if (isSuperCall2 || isSuperMethodCall || isOverriddenMethod) return false;
            }
          }
        }
      }
      return true;
    case 262 /* FunctionDeclaration */: {
      if (parent2.name && isCallbackLike(checker, sourceFile, parent2.name)) {
        return isLastParameter(parent2, parameter, isFixAll);
      }
      return true;
    }
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
      return isLastParameter(parent2, parameter, isFixAll);
    case 178 /* SetAccessor */:
      return false;
    case 177 /* GetAccessor */:
      return true;
    default:
      return Debug.failBadSyntaxKind(parent2);
  }
}
function isCallbackLike(checker, sourceFile, name) {
  return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(name, checker, sourceFile, (reference) => isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.includes(reference));
}
function isLastParameter(func, parameter, isFixAll) {
  const parameters = func.parameters;
  const index = parameters.indexOf(parameter);
  Debug.assert(index !== -1, "The parameter should already be in the list");
  return isFixAll ? parameters.slice(index + 1).every((p) => isIdentifier(p.name) && !p.symbol.isReferenced) : index === parameters.length - 1;
}
function mayDeleteExpression(node) {
  return (isBinaryExpression(node.parent) && node.parent.left === node || (isPostfixUnaryExpression(node.parent) || isPrefixUnaryExpression(node.parent)) && node.parent.operand === node) && isExpressionStatement(node.parent.parent);
}
function deleteFunctionLikeDeclaration(changes, sourceFile, node) {
  const declarations = node.symbol.declarations;
  if (declarations) {
    for (const declaration of declarations) {
      changes.delete(sourceFile, declaration);
    }
  }
}

// src/services/codefixes/fixUnreachableCode.ts
var fixId34 = "fixUnreachableCode";
var errorCodes44 = [Diagnostics.Unreachable_code_detected.code];
registerCodeFix({
  errorCodes: errorCodes44,
  getCodeActions(context) {
    const syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken);
    if (syntacticDiagnostics.length) return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange27(t, context.sourceFile, context.span.start, context.span.length, context.errorCode));
    return [createCodeFixAction(fixId34, changes, Diagnostics.Remove_unreachable_code, fixId34, Diagnostics.Remove_all_unreachable_code)];
  },
  fixIds: [fixId34],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes44, (changes, diag2) => doChange27(changes, diag2.file, diag2.start, diag2.length, diag2.code))
});
function doChange27(changes, sourceFile, start, length2, errorCode) {
  const token = getTokenAtPosition(sourceFile, start);
  const statement = findAncestor(token, isStatement);
  if (statement.getStart(sourceFile) !== token.getStart(sourceFile)) {
    const logData = JSON.stringify({
      statementKind: Debug.formatSyntaxKind(statement.kind),
      tokenKind: Debug.formatSyntaxKind(token.kind),
      errorCode,
      start,
      length: length2
    });
    Debug.fail("Token and statement should start at the same point. " + logData);
  }
  const container = (isBlock(statement.parent) ? statement.parent : statement).parent;
  if (!isBlock(statement.parent) || statement === first(statement.parent.statements)) {
    switch (container.kind) {
      case 245 /* IfStatement */:
        if (container.elseStatement) {
          if (isBlock(statement.parent)) {
            break;
          } else {
            changes.replaceNode(sourceFile, statement, factory.createBlock(emptyArray));
          }
          return;
        }
      // falls through
      case 247 /* WhileStatement */:
      case 248 /* ForStatement */:
        changes.delete(sourceFile, container);
        return;
    }
  }
  if (isBlock(statement.parent)) {
    const end = start + length2;
    const lastStatement = Debug.checkDefined(lastWhere(sliceAfter(statement.parent.statements, statement), (s) => s.pos < end), "Some statement should be last");
    changes.deleteNodeRange(sourceFile, statement, lastStatement);
  } else {
    changes.delete(sourceFile, statement);
  }
}
function lastWhere(a, pred) {
  let last2;
  for (const value of a) {
    if (!pred(value)) break;
    last2 = value;
  }
  return last2;
}

// src/services/codefixes/fixUnusedLabel.ts
var fixId35 = "fixUnusedLabel";
var errorCodes45 = [Diagnostics.Unused_label.code];
registerCodeFix({
  errorCodes: errorCodes45,
  getCodeActions(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange28(t, context.sourceFile, context.span.start));
    return [createCodeFixAction(fixId35, changes, Diagnostics.Remove_unused_label, fixId35, Diagnostics.Remove_all_unused_labels)];
  },
  fixIds: [fixId35],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes45, (changes, diag2) => doChange28(changes, diag2.file, diag2.start))
});
function doChange28(changes, sourceFile, start) {
  const token = getTokenAtPosition(sourceFile, start);
  const labeledStatement = cast(token.parent, isLabeledStatement);
  const pos = token.getStart(sourceFile);
  const statementPos = labeledStatement.statement.getStart(sourceFile);
  const end = positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos : skipTrivia(
    sourceFile.text,
    findChildOfKind(labeledStatement, 59 /* ColonToken */, sourceFile).end,
    /*stopAfterLineBreak*/
    true
  );
  changes.deleteRange(sourceFile, { pos, end });
}

// src/services/codefixes/fixJSDocTypes.ts
var fixIdPlain = "fixJSDocTypes_plain";
var fixIdNullable = "fixJSDocTypes_nullable";
var errorCodes46 = [
  Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code,
  Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code,
  Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code
];
registerCodeFix({
  errorCodes: errorCodes46,
  getCodeActions(context) {
    const { sourceFile } = context;
    const checker = context.program.getTypeChecker();
    const info = getInfo15(sourceFile, context.span.start, checker);
    if (!info) return void 0;
    const { typeNode, type } = info;
    const original = typeNode.getText(sourceFile);
    const actions2 = [fix(type, fixIdPlain, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)];
    if (typeNode.kind === 314 /* JSDocNullableType */) {
      actions2.push(fix(type, fixIdNullable, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
    }
    return actions2;
    function fix(type2, fixId56, fixAllDescription) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange29(t, sourceFile, typeNode, type2, checker));
      return createCodeFixAction("jdocTypes", changes, [Diagnostics.Change_0_to_1, original, checker.typeToString(type2)], fixId56, fixAllDescription);
    }
  },
  fixIds: [fixIdPlain, fixIdNullable],
  getAllCodeActions(context) {
    const { fixId: fixId56, program, sourceFile } = context;
    const checker = program.getTypeChecker();
    return codeFixAll(context, errorCodes46, (changes, err) => {
      const info = getInfo15(err.file, err.start, checker);
      if (!info) return;
      const { typeNode, type } = info;
      const fixedType = typeNode.kind === 314 /* JSDocNullableType */ && fixId56 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
      doChange29(changes, sourceFile, typeNode, fixedType, checker);
    });
  }
});
function doChange29(changes, sourceFile, oldTypeNode, newType, checker) {
  changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(
    newType,
    /*enclosingDeclaration*/
    oldTypeNode,
    /*flags*/
    void 0
  ));
}
function getInfo15(sourceFile, pos, checker) {
  const decl = findAncestor(getTokenAtPosition(sourceFile, pos), isTypeContainer);
  const typeNode = decl && decl.type;
  return typeNode && { typeNode, type: getType(checker, typeNode) };
}
function isTypeContainer(node) {
  switch (node.kind) {
    case 234 /* AsExpression */:
    case 179 /* CallSignature */:
    case 180 /* ConstructSignature */:
    case 262 /* FunctionDeclaration */:
    case 177 /* GetAccessor */:
    case 181 /* IndexSignature */:
    case 200 /* MappedType */:
    case 174 /* MethodDeclaration */:
    case 173 /* MethodSignature */:
    case 169 /* Parameter */:
    case 172 /* PropertyDeclaration */:
    case 171 /* PropertySignature */:
    case 178 /* SetAccessor */:
    case 265 /* TypeAliasDeclaration */:
    case 216 /* TypeAssertionExpression */:
    case 260 /* VariableDeclaration */:
      return true;
    default:
      return false;
  }
}
function getType(checker, node) {
  if (isJSDocNullableType(node)) {
    const type = checker.getTypeFromTypeNode(node.type);
    if (type === checker.getNeverType() || type === checker.getVoidType()) {
      return type;
    }
    return checker.getUnionType(
      append([type, checker.getUndefinedType()], node.postfix ? void 0 : checker.getNullType())
    );
  }
  return checker.getTypeFromTypeNode(node);
}

// src/services/codefixes/fixMissingCallParentheses.ts
var fixId36 = "fixMissingCallParentheses";
var errorCodes47 = [
  Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code
];
registerCodeFix({
  errorCodes: errorCodes47,
  fixIds: [fixId36],
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const callName = getCallName(sourceFile, span.start);
    if (!callName) return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange30(t, context.sourceFile, callName));
    return [createCodeFixAction(fixId36, changes, Diagnostics.Add_missing_call_parentheses, fixId36, Diagnostics.Add_all_missing_call_parentheses)];
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes47, (changes, diag2) => {
    const callName = getCallName(diag2.file, diag2.start);
    if (callName) doChange30(changes, diag2.file, callName);
  })
});
function doChange30(changes, sourceFile, name) {
  changes.replaceNodeWithText(sourceFile, name, `${name.text}()`);
}
function getCallName(sourceFile, start) {
  const token = getTokenAtPosition(sourceFile, start);
  if (isPropertyAccessExpression(token.parent)) {
    let current = token.parent;
    while (isPropertyAccessExpression(current.parent)) {
      current = current.parent;
    }
    return current.name;
  }
  if (isIdentifier(token)) {
    return token;
  }
  return void 0;
}

// src/services/codefixes/fixMissingTypeAnnotationOnExports.ts
var fixId37 = "fixMissingTypeAnnotationOnExports";
var addAnnotationFix = "add-annotation";
var addInlineTypeAssertion = "add-type-assertion";
var extractExpression = "extract-expression";
var errorCodes48 = [
  Diagnostics.Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations.code,
  Diagnostics.Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations.code,
  Diagnostics.At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations.code,
  Diagnostics.Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations.code,
  Diagnostics.Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations.code,
  Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations.code,
  Diagnostics.Expression_type_can_t_be_inferred_with_isolatedDeclarations.code,
  Diagnostics.Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations.code,
  Diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations.code,
  Diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations.code,
  Diagnostics.Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDeclarations.code,
  Diagnostics.Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations.code,
  Diagnostics.Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations.code,
  Diagnostics.Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations.code,
  Diagnostics.Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations.code,
  Diagnostics.Default_exports_can_t_be_inferred_with_isolatedDeclarations.code,
  Diagnostics.Only_const_arrays_can_be_inferred_with_isolatedDeclarations.code,
  Diagnostics.Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations_Add_an_explicit_declaration_for_the_properties_assigned_to_this_function.code,
  Diagnostics.Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_supported_with_isolatedDeclarations.code,
  Diagnostics.Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations.code,
  Diagnostics.Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit.code
];
var canHaveTypeAnnotation = /* @__PURE__ */ new Set([
  177 /* GetAccessor */,
  174 /* MethodDeclaration */,
  172 /* PropertyDeclaration */,
  262 /* FunctionDeclaration */,
  218 /* FunctionExpression */,
  219 /* ArrowFunction */,
  260 /* VariableDeclaration */,
  169 /* Parameter */,
  277 /* ExportAssignment */,
  263 /* ClassDeclaration */,
  206 /* ObjectBindingPattern */,
  207 /* ArrayBindingPattern */
]);
var declarationEmitNodeBuilderFlags2 = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */;
var declarationEmitInternalNodeBuilderFlags2 = 1 /* WriteComputedProps */;
registerCodeFix({
  errorCodes: errorCodes48,
  fixIds: [fixId37],
  getCodeActions(context) {
    const fixes = [];
    addCodeAction(addAnnotationFix, fixes, context, 0 /* Full */, (f) => f.addTypeAnnotation(context.span));
    addCodeAction(addAnnotationFix, fixes, context, 1 /* Relative */, (f) => f.addTypeAnnotation(context.span));
    addCodeAction(addAnnotationFix, fixes, context, 2 /* Widened */, (f) => f.addTypeAnnotation(context.span));
    addCodeAction(addInlineTypeAssertion, fixes, context, 0 /* Full */, (f) => f.addInlineAssertion(context.span));
    addCodeAction(addInlineTypeAssertion, fixes, context, 1 /* Relative */, (f) => f.addInlineAssertion(context.span));
    addCodeAction(addInlineTypeAssertion, fixes, context, 2 /* Widened */, (f) => f.addInlineAssertion(context.span));
    addCodeAction(extractExpression, fixes, context, 0 /* Full */, (f) => f.extractAsVariable(context.span));
    return fixes;
  },
  getAllCodeActions: (context) => {
    const changes = withContext(context, 0 /* Full */, (f) => {
      eachDiagnostic(context, errorCodes48, (diag2) => {
        f.addTypeAnnotation(diag2);
      });
    });
    return createCombinedCodeActions(changes.textChanges);
  }
});
function addCodeAction(fixName8, fixes, context, typePrintMode, cb) {
  const changes = withContext(context, typePrintMode, cb);
  if (changes.result && changes.textChanges.length) {
    fixes.push(createCodeFixAction(
      fixName8,
      changes.textChanges,
      changes.result,
      fixId37,
      Diagnostics.Add_all_missing_type_annotations
    ));
  }
}
function withContext(context, typePrintMode, cb) {
  const emptyInferenceResult = { typeNode: void 0, mutatedTarget: false };
  const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context);
  const sourceFile = context.sourceFile;
  const program = context.program;
  const typeChecker = program.getTypeChecker();
  const scriptTarget = getEmitScriptTarget(program.getCompilerOptions());
  const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host);
  const fixedNodes = /* @__PURE__ */ new Set();
  const expandoPropertiesAdded = /* @__PURE__ */ new Set();
  const typePrinter = createPrinter({
    preserveSourceNewlines: false
  });
  const result = cb({ addTypeAnnotation, addInlineAssertion, extractAsVariable });
  importAdder.writeFixes(changeTracker);
  return {
    result,
    textChanges: changeTracker.getChanges()
  };
  function addTypeAnnotation(span) {
    context.cancellationToken.throwIfCancellationRequested();
    const nodeWithDiag = getTokenAtPosition(sourceFile, span.start);
    const expandoFunction = findExpandoFunction(nodeWithDiag);
    if (expandoFunction) {
      if (isFunctionDeclaration(expandoFunction)) {
        return createNamespaceForExpandoProperties(expandoFunction);
      }
      return fixIsolatedDeclarationError(expandoFunction);
    }
    const nodeMissingType = findAncestorWithMissingType(nodeWithDiag);
    if (nodeMissingType) {
      return fixIsolatedDeclarationError(nodeMissingType);
    }
    return void 0;
  }
  function createNamespaceForExpandoProperties(expandoFunc) {
    var _a;
    if (expandoPropertiesAdded == null ? void 0 : expandoPropertiesAdded.has(expandoFunc)) return void 0;
    expandoPropertiesAdded == null ? void 0 : expandoPropertiesAdded.add(expandoFunc);
    const type = typeChecker.getTypeAtLocation(expandoFunc);
    const elements = typeChecker.getPropertiesOfType(type);
    if (!expandoFunc.name || elements.length === 0) return void 0;
    const newProperties = [];
    for (const symbol of elements) {
      if (!isIdentifierText(symbol.name, getEmitScriptTarget(program.getCompilerOptions()))) continue;
      if (symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration)) continue;
      newProperties.push(factory.createVariableStatement(
        [factory.createModifier(95 /* ExportKeyword */)],
        factory.createVariableDeclarationList(
          [factory.createVariableDeclaration(
            symbol.name,
            /*exclamationToken*/
            void 0,
            typeToTypeNode2(typeChecker.getTypeOfSymbol(symbol), expandoFunc),
            /*initializer*/
            void 0
          )]
        )
      ));
    }
    if (newProperties.length === 0) return void 0;
    const modifiers = [];
    if ((_a = expandoFunc.modifiers) == null ? void 0 : _a.some((modifier) => modifier.kind === 95 /* ExportKeyword */)) {
      modifiers.push(factory.createModifier(95 /* ExportKeyword */));
    }
    modifiers.push(factory.createModifier(138 /* DeclareKeyword */));
    const namespace = factory.createModuleDeclaration(
      modifiers,
      expandoFunc.name,
      factory.createModuleBlock(newProperties),
      /*flags*/
      32 /* Namespace */ | 128 /* ExportContext */ | 33554432 /* Ambient */ | 101441536 /* ContextFlags */
    );
    changeTracker.insertNodeAfter(sourceFile, expandoFunc, namespace);
    return [Diagnostics.Annotate_types_of_properties_expando_function_in_a_namespace];
  }
  function needsParenthesizedExpressionForAssertion(node) {
    return !isEntityNameExpression(node) && !isCallExpression(node) && !isObjectLiteralExpression(node) && !isArrayLiteralExpression(node);
  }
  function createAsExpression(node, type) {
    if (needsParenthesizedExpressionForAssertion(node)) {
      node = factory.createParenthesizedExpression(node);
    }
    return factory.createAsExpression(node, type);
  }
  function createSatisfiesAsExpression(node, type) {
    if (needsParenthesizedExpressionForAssertion(node)) {
      node = factory.createParenthesizedExpression(node);
    }
    return factory.createAsExpression(factory.createSatisfiesExpression(node, getSynthesizedDeepClone(type)), type);
  }
  function addInlineAssertion(span) {
    context.cancellationToken.throwIfCancellationRequested();
    const nodeWithDiag = getTokenAtPosition(sourceFile, span.start);
    const expandoFunction = findExpandoFunction(nodeWithDiag);
    if (expandoFunction) return;
    const targetNode = findBestFittingNode(nodeWithDiag, span);
    if (!targetNode || isValueSignatureDeclaration(targetNode) || isValueSignatureDeclaration(targetNode.parent)) return;
    const isExpressionTarget = isExpression(targetNode);
    const isShorthandPropertyAssignmentTarget = isShorthandPropertyAssignment(targetNode);
    if (!isShorthandPropertyAssignmentTarget && isDeclaration(targetNode)) {
      return void 0;
    }
    if (findAncestor(targetNode, isBindingPattern)) {
      return void 0;
    }
    if (findAncestor(targetNode, isEnumMember)) {
      return void 0;
    }
    if (isExpressionTarget && (findAncestor(targetNode, isHeritageClause) || findAncestor(targetNode, isTypeNode))) {
      return void 0;
    }
    if (isSpreadElement(targetNode)) {
      return void 0;
    }
    const variableDeclaration = findAncestor(targetNode, isVariableDeclaration);
    const type = variableDeclaration && typeChecker.getTypeAtLocation(variableDeclaration);
    if (type && type.flags & 8192 /* UniqueESSymbol */) {
      return void 0;
    }
    if (!(isExpressionTarget || isShorthandPropertyAssignmentTarget)) return void 0;
    const { typeNode, mutatedTarget } = inferType(targetNode, type);
    if (!typeNode || mutatedTarget) return void 0;
    if (isShorthandPropertyAssignmentTarget) {
      changeTracker.insertNodeAt(
        sourceFile,
        targetNode.end,
        createAsExpression(
          getSynthesizedDeepClone(targetNode.name),
          typeNode
        ),
        {
          prefix: ": "
        }
      );
    } else if (isExpressionTarget) {
      changeTracker.replaceNode(
        sourceFile,
        targetNode,
        createSatisfiesAsExpression(
          getSynthesizedDeepClone(targetNode),
          typeNode
        )
      );
    } else {
      Debug.assertNever(targetNode);
    }
    return [Diagnostics.Add_satisfies_and_an_inline_type_assertion_with_0, typeToStringForDiag(typeNode)];
  }
  function extractAsVariable(span) {
    context.cancellationToken.throwIfCancellationRequested();
    const nodeWithDiag = getTokenAtPosition(sourceFile, span.start);
    const targetNode = findBestFittingNode(nodeWithDiag, span);
    if (!targetNode || isValueSignatureDeclaration(targetNode) || isValueSignatureDeclaration(targetNode.parent)) return;
    const isExpressionTarget = isExpression(targetNode);
    if (!isExpressionTarget) return;
    if (isArrayLiteralExpression(targetNode)) {
      changeTracker.replaceNode(
        sourceFile,
        targetNode,
        createAsExpression(targetNode, factory.createTypeReferenceNode("const"))
      );
      return [Diagnostics.Mark_array_literal_as_const];
    }
    const parentPropertyAssignment = findAncestor(targetNode, isPropertyAssignment);
    if (parentPropertyAssignment) {
      if (parentPropertyAssignment === targetNode.parent && isEntityNameExpression(targetNode)) return;
      const tempName = factory.createUniqueName(
        getIdentifierForNode(targetNode, sourceFile, typeChecker, sourceFile),
        16 /* Optimistic */
      );
      let replacementTarget = targetNode;
      let initializationNode = targetNode;
      if (isSpreadElement(replacementTarget)) {
        replacementTarget = walkUpParenthesizedExpressions(replacementTarget.parent);
        if (isConstAssertion2(replacementTarget.parent)) {
          initializationNode = replacementTarget = replacementTarget.parent;
        } else {
          initializationNode = createAsExpression(
            replacementTarget,
            factory.createTypeReferenceNode("const")
          );
        }
      }
      if (isEntityNameExpression(replacementTarget)) return void 0;
      const variableDefinition = factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList([
          factory.createVariableDeclaration(
            tempName,
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            initializationNode
          )
        ], 2 /* Const */)
      );
      const statement = findAncestor(targetNode, isStatement);
      changeTracker.insertNodeBefore(sourceFile, statement, variableDefinition);
      changeTracker.replaceNode(
        sourceFile,
        replacementTarget,
        factory.createAsExpression(
          factory.cloneNode(tempName),
          factory.createTypeQueryNode(
            factory.cloneNode(tempName)
          )
        )
      );
      return [Diagnostics.Extract_to_variable_and_replace_with_0_as_typeof_0, typeToStringForDiag(tempName)];
    }
  }
  function findExpandoFunction(node) {
    const expandoDeclaration = findAncestor(node, (n) => isStatement(n) ? "quit" : isExpandoPropertyDeclaration(n));
    if (expandoDeclaration && isExpandoPropertyDeclaration(expandoDeclaration)) {
      let assignmentTarget = expandoDeclaration;
      if (isBinaryExpression(assignmentTarget)) {
        assignmentTarget = assignmentTarget.left;
        if (!isExpandoPropertyDeclaration(assignmentTarget)) return void 0;
      }
      const targetType = typeChecker.getTypeAtLocation(assignmentTarget.expression);
      if (!targetType) return;
      const properties = typeChecker.getPropertiesOfType(targetType);
      if (some(properties, (p) => p.valueDeclaration === expandoDeclaration || p.valueDeclaration === expandoDeclaration.parent)) {
        const fn = targetType.symbol.valueDeclaration;
        if (fn) {
          if (isFunctionExpressionOrArrowFunction(fn) && isVariableDeclaration(fn.parent)) {
            return fn.parent;
          }
          if (isFunctionDeclaration(fn)) {
            return fn;
          }
        }
      }
    }
    return void 0;
  }
  function fixIsolatedDeclarationError(node) {
    if (fixedNodes == null ? void 0 : fixedNodes.has(node)) return void 0;
    fixedNodes == null ? void 0 : fixedNodes.add(node);
    switch (node.kind) {
      case 169 /* Parameter */:
      case 172 /* PropertyDeclaration */:
      case 260 /* VariableDeclaration */:
        return addTypeToVariableLike(node);
      case 219 /* ArrowFunction */:
      case 218 /* FunctionExpression */:
      case 262 /* FunctionDeclaration */:
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
        return addTypeToSignatureDeclaration(node, sourceFile);
      case 277 /* ExportAssignment */:
        return transformExportAssignment(node);
      case 263 /* ClassDeclaration */:
        return transformExtendsClauseWithExpression(node);
      case 206 /* ObjectBindingPattern */:
      case 207 /* ArrayBindingPattern */:
        return transformDestructuringPatterns(node);
      default:
        throw new Error(`Cannot find a fix for the given node ${node.kind}`);
    }
  }
  function addTypeToSignatureDeclaration(func, sourceFile2) {
    if (func.type) {
      return;
    }
    const { typeNode } = inferType(func);
    if (typeNode) {
      changeTracker.tryInsertTypeAnnotation(
        sourceFile2,
        func,
        typeNode
      );
      return [Diagnostics.Add_return_type_0, typeToStringForDiag(typeNode)];
    }
  }
  function transformExportAssignment(defaultExport) {
    if (defaultExport.isExportEquals) {
      return;
    }
    const { typeNode } = inferType(defaultExport.expression);
    if (!typeNode) return void 0;
    const defaultIdentifier = factory.createUniqueName("_default");
    changeTracker.replaceNodeWithNodes(sourceFile, defaultExport, [
      factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList(
          [factory.createVariableDeclaration(
            defaultIdentifier,
            /*exclamationToken*/
            void 0,
            typeNode,
            defaultExport.expression
          )],
          2 /* Const */
        )
      ),
      factory.updateExportAssignment(defaultExport, defaultExport == null ? void 0 : defaultExport.modifiers, defaultIdentifier)
    ]);
    return [
      Diagnostics.Extract_default_export_to_variable
    ];
  }
  function transformExtendsClauseWithExpression(classDecl) {
    var _a, _b;
    const extendsClause = (_a = classDecl.heritageClauses) == null ? void 0 : _a.find((p) => p.token === 96 /* ExtendsKeyword */);
    const heritageExpression = extendsClause == null ? void 0 : extendsClause.types[0];
    if (!heritageExpression) {
      return void 0;
    }
    const { typeNode: heritageTypeNode } = inferType(heritageExpression.expression);
    if (!heritageTypeNode) {
      return void 0;
    }
    const baseClassName = factory.createUniqueName(
      classDecl.name ? classDecl.name.text + "Base" : "Anonymous",
      16 /* Optimistic */
    );
    const heritageVariable = factory.createVariableStatement(
      /*modifiers*/
      void 0,
      factory.createVariableDeclarationList(
        [factory.createVariableDeclaration(
          baseClassName,
          /*exclamationToken*/
          void 0,
          heritageTypeNode,
          heritageExpression.expression
        )],
        2 /* Const */
      )
    );
    changeTracker.insertNodeBefore(sourceFile, classDecl, heritageVariable);
    const trailingComments = getTrailingCommentRanges(sourceFile.text, heritageExpression.end);
    const realEnd = ((_b = trailingComments == null ? void 0 : trailingComments[trailingComments.length - 1]) == null ? void 0 : _b.end) ?? heritageExpression.end;
    changeTracker.replaceRange(
      sourceFile,
      {
        pos: heritageExpression.getFullStart(),
        end: realEnd
      },
      baseClassName,
      {
        prefix: " "
      }
    );
    return [Diagnostics.Extract_base_class_to_variable];
  }
  let ExpressionType;
  ((ExpressionType2) => {
    ExpressionType2[ExpressionType2["Text"] = 0] = "Text";
    ExpressionType2[ExpressionType2["Computed"] = 1] = "Computed";
    ExpressionType2[ExpressionType2["ArrayAccess"] = 2] = "ArrayAccess";
    ExpressionType2[ExpressionType2["Identifier"] = 3] = "Identifier";
  })(ExpressionType || (ExpressionType = {}));
  function transformDestructuringPatterns(bindingPattern) {
    var _a;
    const enclosingVariableDeclaration = bindingPattern.parent;
    const enclosingVarStmt = bindingPattern.parent.parent.parent;
    if (!enclosingVariableDeclaration.initializer) return void 0;
    let baseExpr;
    const newNodes = [];
    if (!isIdentifier(enclosingVariableDeclaration.initializer)) {
      const tempHolderForReturn = factory.createUniqueName("dest", 16 /* Optimistic */);
      baseExpr = { expression: { kind: 3 /* Identifier */, identifier: tempHolderForReturn } };
      newNodes.push(factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList(
          [factory.createVariableDeclaration(
            tempHolderForReturn,
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            enclosingVariableDeclaration.initializer
          )],
          2 /* Const */
        )
      ));
    } else {
      baseExpr = { expression: { kind: 3 /* Identifier */, identifier: enclosingVariableDeclaration.initializer } };
    }
    const bindingElements = [];
    if (isArrayBindingPattern(bindingPattern)) {
      addArrayBindingPatterns(bindingPattern, bindingElements, baseExpr);
    } else {
      addObjectBindingPatterns(bindingPattern, bindingElements, baseExpr);
    }
    const expressionToVar = /* @__PURE__ */ new Map();
    for (const bindingElement of bindingElements) {
      if (bindingElement.element.propertyName && isComputedPropertyName(bindingElement.element.propertyName)) {
        const computedExpression = bindingElement.element.propertyName.expression;
        const identifierForComputedProperty = factory.getGeneratedNameForNode(computedExpression);
        const variableDecl = factory.createVariableDeclaration(
          identifierForComputedProperty,
          /*exclamationToken*/
          void 0,
          /*type*/
          void 0,
          computedExpression
        );
        const variableList = factory.createVariableDeclarationList([variableDecl], 2 /* Const */);
        const variableStatement = factory.createVariableStatement(
          /*modifiers*/
          void 0,
          variableList
        );
        newNodes.push(variableStatement);
        expressionToVar.set(computedExpression, identifierForComputedProperty);
      }
      const name = bindingElement.element.name;
      if (isArrayBindingPattern(name)) {
        addArrayBindingPatterns(name, bindingElements, bindingElement);
      } else if (isObjectBindingPattern(name)) {
        addObjectBindingPatterns(name, bindingElements, bindingElement);
      } else {
        const { typeNode } = inferType(name);
        let variableInitializer = createChainedExpression(bindingElement, expressionToVar);
        if (bindingElement.element.initializer) {
          const propertyName = (_a = bindingElement.element) == null ? void 0 : _a.propertyName;
          const tempName = factory.createUniqueName(
            propertyName && isIdentifier(propertyName) ? propertyName.text : "temp",
            16 /* Optimistic */
          );
          newNodes.push(factory.createVariableStatement(
            /*modifiers*/
            void 0,
            factory.createVariableDeclarationList(
              [factory.createVariableDeclaration(
                tempName,
                /*exclamationToken*/
                void 0,
                /*type*/
                void 0,
                variableInitializer
              )],
              2 /* Const */
            )
          ));
          variableInitializer = factory.createConditionalExpression(
            factory.createBinaryExpression(
              tempName,
              factory.createToken(37 /* EqualsEqualsEqualsToken */),
              factory.createIdentifier("undefined")
            ),
            factory.createToken(58 /* QuestionToken */),
            bindingElement.element.initializer,
            factory.createToken(59 /* ColonToken */),
            variableInitializer
          );
        }
        const exportModifier = hasSyntacticModifier(enclosingVarStmt, 32 /* Export */) ? [factory.createToken(95 /* ExportKeyword */)] : void 0;
        newNodes.push(factory.createVariableStatement(
          exportModifier,
          factory.createVariableDeclarationList(
            [factory.createVariableDeclaration(
              name,
              /*exclamationToken*/
              void 0,
              typeNode,
              variableInitializer
            )],
            2 /* Const */
          )
        ));
      }
    }
    if (enclosingVarStmt.declarationList.declarations.length > 1) {
      newNodes.push(factory.updateVariableStatement(
        enclosingVarStmt,
        enclosingVarStmt.modifiers,
        factory.updateVariableDeclarationList(
          enclosingVarStmt.declarationList,
          enclosingVarStmt.declarationList.declarations.filter((node) => node !== bindingPattern.parent)
        )
      ));
    }
    changeTracker.replaceNodeWithNodes(sourceFile, enclosingVarStmt, newNodes);
    return [
      Diagnostics.Extract_binding_expressions_to_variable
    ];
  }
  function addArrayBindingPatterns(bindingPattern, bindingElements, parent2) {
    for (let i = 0; i < bindingPattern.elements.length; ++i) {
      const element = bindingPattern.elements[i];
      if (isOmittedExpression(element)) {
        continue;
      }
      bindingElements.push({
        element,
        parent: parent2,
        expression: { kind: 2 /* ArrayAccess */, arrayIndex: i }
      });
    }
  }
  function addObjectBindingPatterns(bindingPattern, bindingElements, parent2) {
    for (const bindingElement of bindingPattern.elements) {
      let name;
      if (bindingElement.propertyName) {
        if (isComputedPropertyName(bindingElement.propertyName)) {
          bindingElements.push({
            element: bindingElement,
            parent: parent2,
            expression: { kind: 1 /* Computed */, computed: bindingElement.propertyName.expression }
          });
          continue;
        } else {
          name = bindingElement.propertyName.text;
        }
      } else {
        name = bindingElement.name.text;
      }
      bindingElements.push({
        element: bindingElement,
        parent: parent2,
        expression: { kind: 0 /* Text */, text: name }
      });
    }
  }
  function createChainedExpression(expression, expressionToVar) {
    const reverseTraverse = [expression];
    while (expression.parent) {
      expression = expression.parent;
      reverseTraverse.push(expression);
    }
    let chainedExpression = reverseTraverse[reverseTraverse.length - 1].expression.identifier;
    for (let i = reverseTraverse.length - 2; i >= 0; --i) {
      const nextSubExpr = reverseTraverse[i].expression;
      if (nextSubExpr.kind === 0 /* Text */) {
        chainedExpression = factory.createPropertyAccessChain(
          chainedExpression,
          /*questionDotToken*/
          void 0,
          factory.createIdentifier(nextSubExpr.text)
        );
      } else if (nextSubExpr.kind === 1 /* Computed */) {
        chainedExpression = factory.createElementAccessExpression(
          chainedExpression,
          expressionToVar.get(nextSubExpr.computed)
        );
      } else if (nextSubExpr.kind === 2 /* ArrayAccess */) {
        chainedExpression = factory.createElementAccessExpression(
          chainedExpression,
          nextSubExpr.arrayIndex
        );
      }
    }
    return chainedExpression;
  }
  function inferType(node, variableType) {
    if (typePrintMode === 1 /* Relative */) {
      return relativeType(node);
    }
    let type;
    if (isValueSignatureDeclaration(node)) {
      const signature = typeChecker.getSignatureFromDeclaration(node);
      if (signature) {
        const typePredicate = typeChecker.getTypePredicateOfSignature(signature);
        if (typePredicate) {
          if (!typePredicate.type) {
            return emptyInferenceResult;
          }
          return {
            typeNode: typePredicateToTypeNode(typePredicate, findAncestor(node, isDeclaration) ?? sourceFile, getFlags(typePredicate.type)),
            mutatedTarget: false
          };
        }
        type = typeChecker.getReturnTypeOfSignature(signature);
      }
    } else {
      type = typeChecker.getTypeAtLocation(node);
    }
    if (!type) {
      return emptyInferenceResult;
    }
    if (typePrintMode === 2 /* Widened */) {
      if (variableType) {
        type = variableType;
      }
      const widenedType = typeChecker.getWidenedLiteralType(type);
      if (typeChecker.isTypeAssignableTo(widenedType, type)) {
        return emptyInferenceResult;
      }
      type = widenedType;
    }
    const enclosingDeclaration = findAncestor(node, isDeclaration) ?? sourceFile;
    if (isParameter(node) && typeChecker.requiresAddingImplicitUndefined(node, enclosingDeclaration)) {
      type = typeChecker.getUnionType([typeChecker.getUndefinedType(), type], 0 /* None */);
    }
    return {
      typeNode: typeToTypeNode2(type, enclosingDeclaration, getFlags(type)),
      mutatedTarget: false
    };
    function getFlags(type2) {
      return (isVariableDeclaration(node) || isPropertyDeclaration(node) && hasSyntacticModifier(node, 256 /* Static */ | 8 /* Readonly */)) && type2.flags & 8192 /* UniqueESSymbol */ ? 1048576 /* AllowUniqueESSymbolType */ : 0 /* None */;
    }
  }
  function createTypeOfFromEntityNameExpression(node) {
    return factory.createTypeQueryNode(getSynthesizedDeepClone(node));
  }
  function typeFromArraySpreadElements(node, name = "temp") {
    const isConstContext = !!findAncestor(node, isConstAssertion2);
    if (!isConstContext) return emptyInferenceResult;
    return typeFromSpreads(
      node,
      name,
      isConstContext,
      (n) => n.elements,
      isSpreadElement,
      factory.createSpreadElement,
      (props) => factory.createArrayLiteralExpression(
        props,
        /*multiLine*/
        true
      ),
      (types) => factory.createTupleTypeNode(types.map(factory.createRestTypeNode))
    );
  }
  function typeFromObjectSpreadAssignment(node, name = "temp") {
    const isConstContext = !!findAncestor(node, isConstAssertion2);
    return typeFromSpreads(
      node,
      name,
      isConstContext,
      (n) => n.properties,
      isSpreadAssignment,
      factory.createSpreadAssignment,
      (props) => factory.createObjectLiteralExpression(
        props,
        /*multiLine*/
        true
      ),
      factory.createIntersectionTypeNode
    );
  }
  function typeFromSpreads(node, name, isConstContext, getChildren, isSpread, createSpread, makeNodeOfKind, finalType) {
    const intersectionTypes = [];
    const newSpreads = [];
    let currentVariableProperties;
    const statement = findAncestor(node, isStatement);
    for (const prop of getChildren(node)) {
      if (isSpread(prop)) {
        finalizesVariablePart();
        if (isEntityNameExpression(prop.expression)) {
          intersectionTypes.push(createTypeOfFromEntityNameExpression(prop.expression));
          newSpreads.push(prop);
        } else {
          makeVariable(prop.expression);
        }
      } else {
        (currentVariableProperties ?? (currentVariableProperties = [])).push(prop);
      }
    }
    if (newSpreads.length === 0) {
      return emptyInferenceResult;
    }
    finalizesVariablePart();
    changeTracker.replaceNode(sourceFile, node, makeNodeOfKind(newSpreads));
    return {
      typeNode: finalType(intersectionTypes),
      mutatedTarget: true
    };
    function makeVariable(expression) {
      const tempName = factory.createUniqueName(
        name + "_Part" + (newSpreads.length + 1),
        16 /* Optimistic */
      );
      const initializer = !isConstContext ? expression : factory.createAsExpression(
        expression,
        factory.createTypeReferenceNode("const")
      );
      const variableDefinition = factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList([
          factory.createVariableDeclaration(
            tempName,
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            initializer
          )
        ], 2 /* Const */)
      );
      changeTracker.insertNodeBefore(sourceFile, statement, variableDefinition);
      intersectionTypes.push(createTypeOfFromEntityNameExpression(tempName));
      newSpreads.push(createSpread(tempName));
    }
    function finalizesVariablePart() {
      if (currentVariableProperties) {
        makeVariable(makeNodeOfKind(
          currentVariableProperties
        ));
        currentVariableProperties = void 0;
      }
    }
  }
  function isConstAssertion2(location) {
    return isAssertionExpression(location) && isConstTypeReference(location.type);
  }
  function relativeType(node) {
    if (isParameter(node)) {
      return emptyInferenceResult;
    }
    if (isShorthandPropertyAssignment(node)) {
      return {
        typeNode: createTypeOfFromEntityNameExpression(node.name),
        mutatedTarget: false
      };
    }
    if (isEntityNameExpression(node)) {
      return {
        typeNode: createTypeOfFromEntityNameExpression(node),
        mutatedTarget: false
      };
    }
    if (isConstAssertion2(node)) {
      return relativeType(node.expression);
    }
    if (isArrayLiteralExpression(node)) {
      const variableDecl = findAncestor(node, isVariableDeclaration);
      const partName = variableDecl && isIdentifier(variableDecl.name) ? variableDecl.name.text : void 0;
      return typeFromArraySpreadElements(node, partName);
    }
    if (isObjectLiteralExpression(node)) {
      const variableDecl = findAncestor(node, isVariableDeclaration);
      const partName = variableDecl && isIdentifier(variableDecl.name) ? variableDecl.name.text : void 0;
      return typeFromObjectSpreadAssignment(node, partName);
    }
    if (isVariableDeclaration(node) && node.initializer) {
      return relativeType(node.initializer);
    }
    if (isConditionalExpression(node)) {
      const { typeNode: trueType, mutatedTarget: mTrue } = relativeType(node.whenTrue);
      if (!trueType) return emptyInferenceResult;
      const { typeNode: falseType, mutatedTarget: mFalse } = relativeType(node.whenFalse);
      if (!falseType) return emptyInferenceResult;
      return {
        typeNode: factory.createUnionTypeNode([trueType, falseType]),
        mutatedTarget: mTrue || mFalse
      };
    }
    return emptyInferenceResult;
  }
  function typeToTypeNode2(type, enclosingDeclaration, flags = 0 /* None */) {
    let isTruncated = false;
    const minimizedTypeNode = typeToMinimizedReferenceType(typeChecker, type, enclosingDeclaration, declarationEmitNodeBuilderFlags2 | flags, declarationEmitInternalNodeBuilderFlags2, {
      moduleResolverHost: program,
      trackSymbol() {
        return true;
      },
      reportTruncationError() {
        isTruncated = true;
      }
    });
    if (!minimizedTypeNode) {
      return void 0;
    }
    const result2 = typeNodeToAutoImportableTypeNode(minimizedTypeNode, importAdder, scriptTarget);
    return isTruncated ? factory.createKeywordTypeNode(133 /* AnyKeyword */) : result2;
  }
  function typePredicateToTypeNode(typePredicate, enclosingDeclaration, flags = 0 /* None */) {
    let isTruncated = false;
    const result2 = typePredicateToAutoImportableTypeNode(typeChecker, importAdder, typePredicate, enclosingDeclaration, scriptTarget, declarationEmitNodeBuilderFlags2 | flags, declarationEmitInternalNodeBuilderFlags2, {
      moduleResolverHost: program,
      trackSymbol() {
        return true;
      },
      reportTruncationError() {
        isTruncated = true;
      }
    });
    return isTruncated ? factory.createKeywordTypeNode(133 /* AnyKeyword */) : result2;
  }
  function addTypeToVariableLike(decl) {
    const { typeNode } = inferType(decl);
    if (typeNode) {
      if (decl.type) {
        changeTracker.replaceNode(getSourceFileOfNode(decl), decl.type, typeNode);
      } else {
        changeTracker.tryInsertTypeAnnotation(getSourceFileOfNode(decl), decl, typeNode);
      }
      return [Diagnostics.Add_annotation_of_type_0, typeToStringForDiag(typeNode)];
    }
  }
  function typeToStringForDiag(node) {
    setEmitFlags(node, 1 /* SingleLine */);
    const result2 = typePrinter.printNode(4 /* Unspecified */, node, sourceFile);
    if (result2.length > defaultMaximumTruncationLength) {
      return result2.substring(0, defaultMaximumTruncationLength - "...".length) + "...";
    }
    setEmitFlags(node, 0 /* None */);
    return result2;
  }
  function findAncestorWithMissingType(node) {
    return findAncestor(node, (n) => {
      return canHaveTypeAnnotation.has(n.kind) && (!isObjectBindingPattern(n) && !isArrayBindingPattern(n) || isVariableDeclaration(n.parent));
    });
  }
  function findBestFittingNode(node, span) {
    while (node && node.end < span.start + span.length) {
      node = node.parent;
    }
    while (node.parent.pos === node.pos && node.parent.end === node.end) {
      node = node.parent;
    }
    if (isIdentifier(node) && hasInitializer(node.parent) && node.parent.initializer) {
      return node.parent.initializer;
    }
    return node;
  }
}

// src/services/codefixes/fixAwaitInSyncFunction.ts
var fixId38 = "fixAwaitInSyncFunction";
var errorCodes49 = [
  Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
  Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
  Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code
];
registerCodeFix({
  errorCodes: errorCodes49,
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const nodes = getNodes3(sourceFile, span.start);
    if (!nodes) return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange31(t, sourceFile, nodes));
    return [createCodeFixAction(fixId38, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId38, Diagnostics.Add_all_missing_async_modifiers)];
  },
  fixIds: [fixId38],
  getAllCodeActions: function getAllCodeActionsToFixAwaitInSyncFunction(context) {
    const seen = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes49, (changes, diag2) => {
      const nodes = getNodes3(diag2.file, diag2.start);
      if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) return;
      doChange31(changes, context.sourceFile, nodes);
    });
  }
});
function getReturnType(expr) {
  if (expr.type) {
    return expr.type;
  }
  if (isVariableDeclaration(expr.parent) && expr.parent.type && isFunctionTypeNode(expr.parent.type)) {
    return expr.parent.type.type;
  }
}
function getNodes3(sourceFile, start) {
  const token = getTokenAtPosition(sourceFile, start);
  const containingFunction = getContainingFunction(token);
  if (!containingFunction) {
    return;
  }
  let insertBefore;
  switch (containingFunction.kind) {
    case 174 /* MethodDeclaration */:
      insertBefore = containingFunction.name;
      break;
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
      insertBefore = findChildOfKind(containingFunction, 100 /* FunctionKeyword */, sourceFile);
      break;
    case 219 /* ArrowFunction */:
      const kind = containingFunction.typeParameters ? 30 /* LessThanToken */ : 21 /* OpenParenToken */;
      insertBefore = findChildOfKind(containingFunction, kind, sourceFile) || first(containingFunction.parameters);
      break;
    default:
      return;
  }
  return insertBefore && {
    insertBefore,
    returnType: getReturnType(containingFunction)
  };
}
function doChange31(changes, sourceFile, { insertBefore, returnType }) {
  if (returnType) {
    const entityName = getEntityNameFromTypeNode(returnType);
    if (!entityName || entityName.kind !== 80 /* Identifier */ || entityName.text !== "Promise") {
      changes.replaceNode(sourceFile, returnType, factory.createTypeReferenceNode("Promise", factory.createNodeArray([returnType])));
    }
  }
  changes.insertModifierBefore(sourceFile, 134 /* AsyncKeyword */, insertBefore);
}

// src/services/codefixes/fixPropertyOverrideAccessor.ts
var errorCodes50 = [
  Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code,
  Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code
];
var fixId39 = "fixPropertyOverrideAccessor";
registerCodeFix({
  errorCodes: errorCodes50,
  getCodeActions(context) {
    const edits = doChange32(context.sourceFile, context.span.start, context.span.length, context.errorCode, context);
    if (edits) {
      return [createCodeFixAction(fixId39, edits, Diagnostics.Generate_get_and_set_accessors, fixId39, Diagnostics.Generate_get_and_set_accessors_for_all_overriding_properties)];
    }
  },
  fixIds: [fixId39],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes50, (changes, diag2) => {
    const edits = doChange32(diag2.file, diag2.start, diag2.length, diag2.code, context);
    if (edits) {
      for (const edit of edits) {
        changes.pushRaw(context.sourceFile, edit);
      }
    }
  })
});
function doChange32(file, start, length2, code, context) {
  let startPosition;
  let endPosition;
  if (code === Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code) {
    startPosition = start;
    endPosition = start + length2;
  } else if (code === Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code) {
    const checker = context.program.getTypeChecker();
    const node = getTokenAtPosition(file, start).parent;
    Debug.assert(isAccessor(node), "error span of fixPropertyOverrideAccessor should only be on an accessor");
    const containingClass = node.parent;
    Debug.assert(isClassLike(containingClass), "erroneous accessors should only be inside classes");
    const base = singleOrUndefined(getAllSupers(containingClass, checker));
    if (!base) return [];
    const name = unescapeLeadingUnderscores(getTextOfPropertyName(node.name));
    const baseProp = checker.getPropertyOfType(checker.getTypeAtLocation(base), name);
    if (!baseProp || !baseProp.valueDeclaration) return [];
    startPosition = baseProp.valueDeclaration.pos;
    endPosition = baseProp.valueDeclaration.end;
    file = getSourceFileOfNode(baseProp.valueDeclaration);
  } else {
    Debug.fail("fixPropertyOverrideAccessor codefix got unexpected error code " + code);
  }
  return generateAccessorFromProperty(file, context.program, startPosition, endPosition, context, Diagnostics.Generate_get_and_set_accessors.message);
}

// src/services/codefixes/inferFromUsage.ts
var fixId40 = "inferFromUsage";
var errorCodes51 = [
  // Variable declarations
  Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code,
  // Variable uses
  Diagnostics.Variable_0_implicitly_has_an_1_type.code,
  // Parameter declarations
  Diagnostics.Parameter_0_implicitly_has_an_1_type.code,
  Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code,
  // Get Accessor declarations
  Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code,
  Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code,
  // Set Accessor declarations
  Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code,
  // Property declarations
  Diagnostics.Member_0_implicitly_has_an_1_type.code,
  //// Suggestions
  // Variable declarations
  Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code,
  // Variable uses
  Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
  // Parameter declarations
  Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
  Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code,
  // Get Accessor declarations
  Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code,
  Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code,
  // Set Accessor declarations
  Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code,
  // Property declarations
  Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
  // Function expressions and declarations
  Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code
];
registerCodeFix({
  errorCodes: errorCodes51,
  getCodeActions(context) {
    const { sourceFile, program, span: { start }, errorCode, cancellationToken, host, preferences } = context;
    const token = getTokenAtPosition(sourceFile, start);
    let declaration;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => {
      declaration = doChange33(
        changes2,
        sourceFile,
        token,
        errorCode,
        program,
        cancellationToken,
        /*markSeen*/
        returnTrue,
        host,
        preferences
      );
    });
    const name = declaration && getNameOfDeclaration(declaration);
    return !name || changes.length === 0 ? void 0 : [createCodeFixAction(fixId40, changes, [getDiagnostic(errorCode, token), getTextOfNode(name)], fixId40, Diagnostics.Infer_all_types_from_usage)];
  },
  fixIds: [fixId40],
  getAllCodeActions(context) {
    const { sourceFile, program, cancellationToken, host, preferences } = context;
    const markSeen = nodeSeenTracker();
    return codeFixAll(context, errorCodes51, (changes, err) => {
      doChange33(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences);
    });
  }
});
function getDiagnostic(errorCode, token) {
  switch (errorCode) {
    case Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
    case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
      return isSetAccessorDeclaration(getContainingFunction(token)) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage;
    // TODO: GH#18217
    case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
    case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Infer_parameter_types_from_usage;
    case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code:
      return Diagnostics.Infer_this_type_of_0_from_usage;
    default:
      return Diagnostics.Infer_type_of_0_from_usage;
  }
}
function mapSuggestionDiagnostic(errorCode) {
  switch (errorCode) {
    case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code;
    case Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Variable_0_implicitly_has_an_1_type.code;
    case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Parameter_0_implicitly_has_an_1_type.code;
    case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code;
    case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code:
      return Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code;
    case Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code;
    case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code:
      return Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code;
    case Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Member_0_implicitly_has_an_1_type.code;
  }
  return errorCode;
}
function doChange33(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) {
  if (!isParameterPropertyModifier(token.kind) && token.kind !== 80 /* Identifier */ && token.kind !== 26 /* DotDotDotToken */ && token.kind !== 110 /* ThisKeyword */) {
    return void 0;
  }
  const { parent: parent2 } = token;
  const importAdder = createImportAdder(sourceFile, program, preferences, host);
  errorCode = mapSuggestionDiagnostic(errorCode);
  switch (errorCode) {
    // Variable and Property declarations
    case Diagnostics.Member_0_implicitly_has_an_1_type.code:
    case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code:
      if (isVariableDeclaration(parent2) && markSeen(parent2) || isPropertyDeclaration(parent2) || isPropertySignature(parent2)) {
        annotateVariableDeclaration(changes, importAdder, sourceFile, parent2, program, host, cancellationToken);
        importAdder.writeFixes(changes);
        return parent2;
      }
      if (isPropertyAccessExpression(parent2)) {
        const type = inferTypeForVariableFromUsage(parent2.name, program, cancellationToken);
        const typeNode = getTypeNodeIfAccessible(type, parent2, program, host);
        if (typeNode) {
          const typeTag = factory.createJSDocTypeTag(
            /*tagName*/
            void 0,
            factory.createJSDocTypeExpression(typeNode),
            /*comment*/
            void 0
          );
          changes.addJSDocTags(sourceFile, cast(parent2.parent.parent, isExpressionStatement), [typeTag]);
        }
        importAdder.writeFixes(changes);
        return parent2;
      }
      return void 0;
    case Diagnostics.Variable_0_implicitly_has_an_1_type.code: {
      const symbol = program.getTypeChecker().getSymbolAtLocation(token);
      if (symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) {
        annotateVariableDeclaration(changes, importAdder, getSourceFileOfNode(symbol.valueDeclaration), symbol.valueDeclaration, program, host, cancellationToken);
        importAdder.writeFixes(changes);
        return symbol.valueDeclaration;
      }
      return void 0;
    }
  }
  const containingFunction = getContainingFunction(token);
  if (containingFunction === void 0) {
    return void 0;
  }
  let declaration;
  switch (errorCode) {
    // Parameter declarations
    case Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
      if (isSetAccessorDeclaration(containingFunction)) {
        annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken);
        declaration = containingFunction;
        break;
      }
    // falls through
    case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
      if (markSeen(containingFunction)) {
        const param = cast(parent2, isParameter);
        annotateParameters(changes, importAdder, sourceFile, param, containingFunction, program, host, cancellationToken);
        declaration = param;
      }
      break;
    // Get Accessor declarations
    case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code:
    case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code:
      if (isGetAccessorDeclaration(containingFunction) && isIdentifier(containingFunction.name)) {
        annotate(changes, importAdder, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host);
        declaration = containingFunction;
      }
      break;
    // Set Accessor declarations
    case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
      if (isSetAccessorDeclaration(containingFunction)) {
        annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken);
        declaration = containingFunction;
      }
      break;
    // Function 'this'
    case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code:
      if (ts_textChanges_exports.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) {
        annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken);
        declaration = containingFunction;
      }
      break;
    default:
      return Debug.fail(String(errorCode));
  }
  importAdder.writeFixes(changes);
  return declaration;
}
function annotateVariableDeclaration(changes, importAdder, sourceFile, declaration, program, host, cancellationToken) {
  if (isIdentifier(declaration.name)) {
    annotate(changes, importAdder, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host);
  }
}
function annotateParameters(changes, importAdder, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) {
  if (!isIdentifier(parameterDeclaration.name)) {
    return;
  }
  const parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken);
  Debug.assert(containingFunction.parameters.length === parameterInferences.length, "Parameter count and inference count should match");
  if (isInJSFile(containingFunction)) {
    annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host);
  } else {
    const needParens = isArrowFunction(containingFunction) && !findChildOfKind(containingFunction, 21 /* OpenParenToken */, sourceFile);
    if (needParens) changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), factory.createToken(21 /* OpenParenToken */));
    for (const { declaration, type } of parameterInferences) {
      if (declaration && !declaration.type && !declaration.initializer) {
        annotate(changes, importAdder, sourceFile, declaration, type, program, host);
      }
    }
    if (needParens) changes.insertNodeAfter(sourceFile, last(containingFunction.parameters), factory.createToken(22 /* CloseParenToken */));
  }
}
function annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken) {
  const references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken);
  if (!references || !references.length) {
    return;
  }
  const thisInference = inferTypeFromReferences(program, references, cancellationToken).thisParameter();
  const typeNode = getTypeNodeIfAccessible(thisInference, containingFunction, program, host);
  if (!typeNode) {
    return;
  }
  if (isInJSFile(containingFunction)) {
    annotateJSDocThis(changes, sourceFile, containingFunction, typeNode);
  } else {
    changes.tryInsertThisTypeAnnotation(sourceFile, containingFunction, typeNode);
  }
}
function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) {
  changes.addJSDocTags(sourceFile, containingFunction, [
    factory.createJSDocThisTag(
      /*tagName*/
      void 0,
      factory.createJSDocTypeExpression(typeNode)
    )
  ]);
}
function annotateSetAccessor(changes, importAdder, sourceFile, setAccessorDeclaration, program, host, cancellationToken) {
  const param = firstOrUndefined(setAccessorDeclaration.parameters);
  if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) {
    let type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken);
    if (type === program.getTypeChecker().getAnyType()) {
      type = inferTypeForVariableFromUsage(param.name, program, cancellationToken);
    }
    if (isInJSFile(setAccessorDeclaration)) {
      annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type }], program, host);
    } else {
      annotate(changes, importAdder, sourceFile, param, type, program, host);
    }
  }
}
function annotate(changes, importAdder, sourceFile, declaration, type, program, host) {
  const typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
  if (typeNode) {
    if (isInJSFile(sourceFile) && declaration.kind !== 171 /* PropertySignature */) {
      const parent2 = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : declaration;
      if (!parent2) {
        return;
      }
      const typeExpression = factory.createJSDocTypeExpression(typeNode);
      const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag(
        /*tagName*/
        void 0,
        typeExpression,
        /*comment*/
        void 0
      ) : factory.createJSDocTypeTag(
        /*tagName*/
        void 0,
        typeExpression,
        /*comment*/
        void 0
      );
      changes.addJSDocTags(sourceFile, parent2, [typeTag]);
    } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, getEmitScriptTarget(program.getCompilerOptions()))) {
      changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode);
    }
  }
}
function tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, scriptTarget) {
  const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget);
  if (importableReference && changes.tryInsertTypeAnnotation(sourceFile, declaration, importableReference.typeNode)) {
    forEach(importableReference.symbols, (s) => importAdder.addImportFromExportedSymbol(
      s,
      /*isValidTypeOnlyUseSite*/
      true
    ));
    return true;
  }
  return false;
}
function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) {
  const signature = parameterInferences.length && parameterInferences[0].declaration.parent;
  if (!signature) {
    return;
  }
  const inferences = mapDefined(parameterInferences, (inference) => {
    const param = inference.declaration;
    if (param.initializer || getJSDocType(param) || !isIdentifier(param.name)) {
      return;
    }
    const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host);
    if (typeNode) {
      const name = factory.cloneNode(param.name);
      setEmitFlags(name, 3072 /* NoComments */ | 4096 /* NoNestedComments */);
      return { name: factory.cloneNode(param.name), param, isOptional: !!inference.isOptional, typeNode };
    }
  });
  if (!inferences.length) {
    return;
  }
  if (isArrowFunction(signature) || isFunctionExpression(signature)) {
    const needParens = isArrowFunction(signature) && !findChildOfKind(signature, 21 /* OpenParenToken */, sourceFile);
    if (needParens) {
      changes.insertNodeBefore(sourceFile, first(signature.parameters), factory.createToken(21 /* OpenParenToken */));
    }
    forEach(inferences, ({ typeNode, param }) => {
      const typeTag = factory.createJSDocTypeTag(
        /*tagName*/
        void 0,
        factory.createJSDocTypeExpression(typeNode)
      );
      const jsDoc = factory.createJSDocComment(
        /*comment*/
        void 0,
        [typeTag]
      );
      changes.insertNodeAt(sourceFile, param.getStart(sourceFile), jsDoc, { suffix: " " });
    });
    if (needParens) {
      changes.insertNodeAfter(sourceFile, last(signature.parameters), factory.createToken(22 /* CloseParenToken */));
    }
  } else {
    const paramTags = map(inferences, ({ name, typeNode, isOptional }) => factory.createJSDocParameterTag(
      /*tagName*/
      void 0,
      name,
      /*isBracketed*/
      !!isOptional,
      factory.createJSDocTypeExpression(typeNode),
      /*isNameFirst*/
      false,
      /*comment*/
      void 0
    ));
    changes.addJSDocTags(sourceFile, signature, paramTags);
  }
}
function getReferences(token, program, cancellationToken) {
  return mapDefined(ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), (entry) => entry.kind !== ts_FindAllReferences_exports.EntryKind.Span ? tryCast(entry.node, isIdentifier) : void 0);
}
function inferTypeForVariableFromUsage(token, program, cancellationToken) {
  const references = getReferences(token, program, cancellationToken);
  return inferTypeFromReferences(program, references, cancellationToken).single();
}
function inferTypeForParametersFromUsage(func, sourceFile, program, cancellationToken) {
  const references = getFunctionReferences(func, sourceFile, program, cancellationToken);
  return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) || func.parameters.map((p) => ({
    declaration: p,
    type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType()
  }));
}
function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) {
  let searchToken;
  switch (containingFunction.kind) {
    case 176 /* Constructor */:
      searchToken = findChildOfKind(containingFunction, 137 /* ConstructorKeyword */, sourceFile);
      break;
    case 219 /* ArrowFunction */:
    case 218 /* FunctionExpression */:
      const parent2 = containingFunction.parent;
      searchToken = (isVariableDeclaration(parent2) || isPropertyDeclaration(parent2)) && isIdentifier(parent2.name) ? parent2.name : containingFunction.name;
      break;
    case 262 /* FunctionDeclaration */:
    case 174 /* MethodDeclaration */:
    case 173 /* MethodSignature */:
      searchToken = containingFunction.name;
      break;
  }
  if (!searchToken) {
    return void 0;
  }
  return getReferences(searchToken, program, cancellationToken);
}
function inferTypeFromReferences(program, references, cancellationToken) {
  const checker = program.getTypeChecker();
  const builtinConstructors = {
    string: () => checker.getStringType(),
    number: () => checker.getNumberType(),
    Array: (t) => checker.createArrayType(t),
    Promise: (t) => checker.createPromiseType(t)
  };
  const builtins = [
    checker.getStringType(),
    checker.getNumberType(),
    checker.createArrayType(checker.getAnyType()),
    checker.createPromiseType(checker.getAnyType())
  ];
  return {
    single: single2,
    parameters,
    thisParameter
  };
  function createEmptyUsage() {
    return {
      isNumber: void 0,
      isString: void 0,
      isNumberOrString: void 0,
      candidateTypes: void 0,
      properties: void 0,
      calls: void 0,
      constructs: void 0,
      numberIndex: void 0,
      stringIndex: void 0,
      candidateThisTypes: void 0,
      inferredTypes: void 0
    };
  }
  function combineUsages(usages) {
    const combinedProperties = /* @__PURE__ */ new Map();
    for (const u of usages) {
      if (u.properties) {
        u.properties.forEach((p, name) => {
          if (!combinedProperties.has(name)) {
            combinedProperties.set(name, []);
          }
          combinedProperties.get(name).push(p);
        });
      }
    }
    const properties = /* @__PURE__ */ new Map();
    combinedProperties.forEach((ps, name) => {
      properties.set(name, combineUsages(ps));
    });
    return {
      isNumber: usages.some((u) => u.isNumber),
      isString: usages.some((u) => u.isString),
      isNumberOrString: usages.some((u) => u.isNumberOrString),
      candidateTypes: flatMap(usages, (u) => u.candidateTypes),
      properties,
      calls: flatMap(usages, (u) => u.calls),
      constructs: flatMap(usages, (u) => u.constructs),
      numberIndex: forEach(usages, (u) => u.numberIndex),
      stringIndex: forEach(usages, (u) => u.stringIndex),
      candidateThisTypes: flatMap(usages, (u) => u.candidateThisTypes),
      inferredTypes: void 0
      // clear type cache
    };
  }
  function single2() {
    return combineTypes(inferTypesFromReferencesSingle(references));
  }
  function parameters(declaration) {
    if (references.length === 0 || !declaration.parameters) {
      return void 0;
    }
    const usage = createEmptyUsage();
    for (const reference of references) {
      cancellationToken.throwIfCancellationRequested();
      calculateUsageOfNode(reference, usage);
    }
    const calls = [...usage.constructs || [], ...usage.calls || []];
    return declaration.parameters.map((parameter, parameterIndex) => {
      const types = [];
      const isRest = isRestParameter(parameter);
      let isOptional = false;
      for (const call of calls) {
        if (call.argumentTypes.length <= parameterIndex) {
          isOptional = isInJSFile(declaration);
          types.push(checker.getUndefinedType());
        } else if (isRest) {
          for (let i = parameterIndex; i < call.argumentTypes.length; i++) {
            types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[i]));
          }
        } else {
          types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex]));
        }
      }
      if (isIdentifier(parameter.name)) {
        const inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken));
        types.push(...isRest ? mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred);
      }
      const type = combineTypes(types);
      return {
        type: isRest ? checker.createArrayType(type) : type,
        isOptional: isOptional && !isRest,
        declaration: parameter
      };
    });
  }
  function thisParameter() {
    const usage = createEmptyUsage();
    for (const reference of references) {
      cancellationToken.throwIfCancellationRequested();
      calculateUsageOfNode(reference, usage);
    }
    return combineTypes(usage.candidateThisTypes || emptyArray);
  }
  function inferTypesFromReferencesSingle(references2) {
    const usage = createEmptyUsage();
    for (const reference of references2) {
      cancellationToken.throwIfCancellationRequested();
      calculateUsageOfNode(reference, usage);
    }
    return inferTypes(usage);
  }
  function calculateUsageOfNode(node, usage) {
    while (isRightSideOfQualifiedNameOrPropertyAccess(node)) {
      node = node.parent;
    }
    switch (node.parent.kind) {
      case 244 /* ExpressionStatement */:
        inferTypeFromExpressionStatement(node, usage);
        break;
      case 225 /* PostfixUnaryExpression */:
        usage.isNumber = true;
        break;
      case 224 /* PrefixUnaryExpression */:
        inferTypeFromPrefixUnaryExpression(node.parent, usage);
        break;
      case 226 /* BinaryExpression */:
        inferTypeFromBinaryExpression(node, node.parent, usage);
        break;
      case 296 /* CaseClause */:
      case 297 /* DefaultClause */:
        inferTypeFromSwitchStatementLabel(node.parent, usage);
        break;
      case 213 /* CallExpression */:
      case 214 /* NewExpression */:
        if (node.parent.expression === node) {
          inferTypeFromCallExpression(node.parent, usage);
        } else {
          inferTypeFromContextualType(node, usage);
        }
        break;
      case 211 /* PropertyAccessExpression */:
        inferTypeFromPropertyAccessExpression(node.parent, usage);
        break;
      case 212 /* ElementAccessExpression */:
        inferTypeFromPropertyElementExpression(node.parent, node, usage);
        break;
      case 303 /* PropertyAssignment */:
      case 304 /* ShorthandPropertyAssignment */:
        inferTypeFromPropertyAssignment(node.parent, usage);
        break;
      case 172 /* PropertyDeclaration */:
        inferTypeFromPropertyDeclaration(node.parent, usage);
        break;
      case 260 /* VariableDeclaration */: {
        const { name, initializer } = node.parent;
        if (node === name) {
          if (initializer) {
            addCandidateType(usage, checker.getTypeAtLocation(initializer));
          }
          break;
        }
      }
      // falls through
      default:
        return inferTypeFromContextualType(node, usage);
    }
  }
  function inferTypeFromContextualType(node, usage) {
    if (isExpressionNode(node)) {
      addCandidateType(usage, checker.getContextualType(node));
    }
  }
  function inferTypeFromExpressionStatement(node, usage) {
    addCandidateType(usage, isCallExpression(node) ? checker.getVoidType() : checker.getAnyType());
  }
  function inferTypeFromPrefixUnaryExpression(node, usage) {
    switch (node.operator) {
      case 46 /* PlusPlusToken */:
      case 47 /* MinusMinusToken */:
      case 41 /* MinusToken */:
      case 55 /* TildeToken */:
        usage.isNumber = true;
        break;
      case 40 /* PlusToken */:
        usage.isNumberOrString = true;
        break;
    }
  }
  function inferTypeFromBinaryExpression(node, parent2, usage) {
    switch (parent2.operatorToken.kind) {
      // ExponentiationOperator
      case 43 /* AsteriskAsteriskToken */:
      // MultiplicativeOperator
      // falls through
      case 42 /* AsteriskToken */:
      case 44 /* SlashToken */:
      case 45 /* PercentToken */:
      // ShiftOperator
      // falls through
      case 48 /* LessThanLessThanToken */:
      case 49 /* GreaterThanGreaterThanToken */:
      case 50 /* GreaterThanGreaterThanGreaterThanToken */:
      // BitwiseOperator
      // falls through
      case 51 /* AmpersandToken */:
      case 52 /* BarToken */:
      case 53 /* CaretToken */:
      // CompoundAssignmentOperator
      // falls through
      case 66 /* MinusEqualsToken */:
      case 68 /* AsteriskAsteriskEqualsToken */:
      case 67 /* AsteriskEqualsToken */:
      case 69 /* SlashEqualsToken */:
      case 70 /* PercentEqualsToken */:
      case 74 /* AmpersandEqualsToken */:
      case 75 /* BarEqualsToken */:
      case 79 /* CaretEqualsToken */:
      case 71 /* LessThanLessThanEqualsToken */:
      case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
      case 72 /* GreaterThanGreaterThanEqualsToken */:
      // AdditiveOperator
      // falls through
      case 41 /* MinusToken */:
      // RelationalOperator
      // falls through
      case 30 /* LessThanToken */:
      case 33 /* LessThanEqualsToken */:
      case 32 /* GreaterThanToken */:
      case 34 /* GreaterThanEqualsToken */:
        const operandType = checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left);
        if (operandType.flags & 1056 /* EnumLike */) {
          addCandidateType(usage, operandType);
        } else {
          usage.isNumber = true;
        }
        break;
      case 65 /* PlusEqualsToken */:
      case 40 /* PlusToken */:
        const otherOperandType = checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left);
        if (otherOperandType.flags & 1056 /* EnumLike */) {
          addCandidateType(usage, otherOperandType);
        } else if (otherOperandType.flags & 296 /* NumberLike */) {
          usage.isNumber = true;
        } else if (otherOperandType.flags & 402653316 /* StringLike */) {
          usage.isString = true;
        } else if (otherOperandType.flags & 1 /* Any */) {
        } else {
          usage.isNumberOrString = true;
        }
        break;
      //  AssignmentOperators
      case 64 /* EqualsToken */:
      case 35 /* EqualsEqualsToken */:
      case 37 /* EqualsEqualsEqualsToken */:
      case 38 /* ExclamationEqualsEqualsToken */:
      case 36 /* ExclamationEqualsToken */:
      case 77 /* AmpersandAmpersandEqualsToken */:
      case 78 /* QuestionQuestionEqualsToken */:
      case 76 /* BarBarEqualsToken */:
        addCandidateType(usage, checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left));
        break;
      case 103 /* InKeyword */:
        if (node === parent2.left) {
          usage.isString = true;
        }
        break;
      // LogicalOperator Or NullishCoalescing
      case 57 /* BarBarToken */:
      case 61 /* QuestionQuestionToken */:
        if (node === parent2.left && (node.parent.parent.kind === 260 /* VariableDeclaration */ || isAssignmentExpression(
          node.parent.parent,
          /*excludeCompoundAssignment*/
          true
        ))) {
          addCandidateType(usage, checker.getTypeAtLocation(parent2.right));
        }
        break;
      case 56 /* AmpersandAmpersandToken */:
      case 28 /* CommaToken */:
      case 104 /* InstanceOfKeyword */:
        break;
    }
  }
  function inferTypeFromSwitchStatementLabel(parent2, usage) {
    addCandidateType(usage, checker.getTypeAtLocation(parent2.parent.parent.expression));
  }
  function inferTypeFromCallExpression(parent2, usage) {
    const call = {
      argumentTypes: [],
      return_: createEmptyUsage()
    };
    if (parent2.arguments) {
      for (const argument of parent2.arguments) {
        call.argumentTypes.push(checker.getTypeAtLocation(argument));
      }
    }
    calculateUsageOfNode(parent2, call.return_);
    if (parent2.kind === 213 /* CallExpression */) {
      (usage.calls || (usage.calls = [])).push(call);
    } else {
      (usage.constructs || (usage.constructs = [])).push(call);
    }
  }
  function inferTypeFromPropertyAccessExpression(parent2, usage) {
    const name = escapeLeadingUnderscores(parent2.name.text);
    if (!usage.properties) {
      usage.properties = /* @__PURE__ */ new Map();
    }
    const propertyUsage = usage.properties.get(name) || createEmptyUsage();
    calculateUsageOfNode(parent2, propertyUsage);
    usage.properties.set(name, propertyUsage);
  }
  function inferTypeFromPropertyElementExpression(parent2, node, usage) {
    if (node === parent2.argumentExpression) {
      usage.isNumberOrString = true;
      return;
    } else {
      const indexType = checker.getTypeAtLocation(parent2.argumentExpression);
      const indexUsage = createEmptyUsage();
      calculateUsageOfNode(parent2, indexUsage);
      if (indexType.flags & 296 /* NumberLike */) {
        usage.numberIndex = indexUsage;
      } else {
        usage.stringIndex = indexUsage;
      }
    }
  }
  function inferTypeFromPropertyAssignment(assignment, usage) {
    const nodeWithRealType = isVariableDeclaration(assignment.parent.parent) ? assignment.parent.parent : assignment.parent;
    addCandidateThisType(usage, checker.getTypeAtLocation(nodeWithRealType));
  }
  function inferTypeFromPropertyDeclaration(declaration, usage) {
    addCandidateThisType(usage, checker.getTypeAtLocation(declaration.parent));
  }
  function removeLowPriorityInferences(inferences, priorities) {
    const toRemove = [];
    for (const i of inferences) {
      for (const { high, low } of priorities) {
        if (high(i)) {
          Debug.assert(!low(i), "Priority can't have both low and high");
          toRemove.push(low);
        }
      }
    }
    return inferences.filter((i) => toRemove.every((f) => !f(i)));
  }
  function combineFromUsage(usage) {
    return combineTypes(inferTypes(usage));
  }
  function combineTypes(inferences) {
    if (!inferences.length) return checker.getAnyType();
    const stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]);
    const priorities = [
      {
        high: (t) => t === checker.getStringType() || t === checker.getNumberType(),
        low: (t) => t === stringNumber
      },
      {
        high: (t) => !(t.flags & (1 /* Any */ | 16384 /* Void */)),
        low: (t) => !!(t.flags & (1 /* Any */ | 16384 /* Void */))
      },
      {
        high: (t) => !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(getObjectFlags(t) & 16 /* Anonymous */),
        low: (t) => !!(getObjectFlags(t) & 16 /* Anonymous */)
      }
    ];
    let good = removeLowPriorityInferences(inferences, priorities);
    const anons = good.filter((i) => getObjectFlags(i) & 16 /* Anonymous */);
    if (anons.length) {
      good = good.filter((i) => !(getObjectFlags(i) & 16 /* Anonymous */));
      good.push(combineAnonymousTypes(anons));
    }
    return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), 2 /* Subtype */));
  }
  function combineAnonymousTypes(anons) {
    if (anons.length === 1) {
      return anons[0];
    }
    const calls = [];
    const constructs = [];
    const stringIndices = [];
    const numberIndices = [];
    let stringIndexReadonly = false;
    let numberIndexReadonly = false;
    const props = createMultiMap();
    for (const anon2 of anons) {
      for (const p of checker.getPropertiesOfType(anon2)) {
        props.add(p.escapedName, p.valueDeclaration ? checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration) : checker.getAnyType());
      }
      calls.push(...checker.getSignaturesOfType(anon2, 0 /* Call */));
      constructs.push(...checker.getSignaturesOfType(anon2, 1 /* Construct */));
      const stringIndexInfo = checker.getIndexInfoOfType(anon2, 0 /* String */);
      if (stringIndexInfo) {
        stringIndices.push(stringIndexInfo.type);
        stringIndexReadonly = stringIndexReadonly || stringIndexInfo.isReadonly;
      }
      const numberIndexInfo = checker.getIndexInfoOfType(anon2, 1 /* Number */);
      if (numberIndexInfo) {
        numberIndices.push(numberIndexInfo.type);
        numberIndexReadonly = numberIndexReadonly || numberIndexInfo.isReadonly;
      }
    }
    const members = mapEntries(props, (name, types) => {
      const isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0;
      const s = checker.createSymbol(4 /* Property */ | isOptional, name);
      s.links.type = checker.getUnionType(types);
      return [name, s];
    });
    const indexInfos = [];
    if (stringIndices.length) indexInfos.push(checker.createIndexInfo(checker.getStringType(), checker.getUnionType(stringIndices), stringIndexReadonly));
    if (numberIndices.length) indexInfos.push(checker.createIndexInfo(checker.getNumberType(), checker.getUnionType(numberIndices), numberIndexReadonly));
    return checker.createAnonymousType(
      anons[0].symbol,
      members,
      calls,
      constructs,
      indexInfos
    );
  }
  function inferTypes(usage) {
    var _a, _b, _c;
    const types = [];
    if (usage.isNumber) {
      types.push(checker.getNumberType());
    }
    if (usage.isString) {
      types.push(checker.getStringType());
    }
    if (usage.isNumberOrString) {
      types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()]));
    }
    if (usage.numberIndex) {
      types.push(checker.createArrayType(combineFromUsage(usage.numberIndex)));
    }
    if (((_a = usage.properties) == null ? void 0 : _a.size) || ((_b = usage.constructs) == null ? void 0 : _b.length) || usage.stringIndex) {
      types.push(inferStructuralType(usage));
    }
    const candidateTypes = (usage.candidateTypes || []).map((t) => checker.getBaseTypeOfLiteralType(t));
    const callsType = ((_c = usage.calls) == null ? void 0 : _c.length) ? inferStructuralType(usage) : void 0;
    if (callsType && candidateTypes) {
      types.push(checker.getUnionType([callsType, ...candidateTypes], 2 /* Subtype */));
    } else {
      if (callsType) {
        types.push(callsType);
      }
      if (length(candidateTypes)) {
        types.push(...candidateTypes);
      }
    }
    types.push(...inferNamedTypesFromProperties(usage));
    return types;
  }
  function inferStructuralType(usage) {
    const members = /* @__PURE__ */ new Map();
    if (usage.properties) {
      usage.properties.forEach((u, name) => {
        const symbol = checker.createSymbol(4 /* Property */, name);
        symbol.links.type = combineFromUsage(u);
        members.set(name, symbol);
      });
    }
    const callSignatures = usage.calls ? [getSignatureFromCalls(usage.calls)] : [];
    const constructSignatures = usage.constructs ? [getSignatureFromCalls(usage.constructs)] : [];
    const indexInfos = usage.stringIndex ? [checker.createIndexInfo(
      checker.getStringType(),
      combineFromUsage(usage.stringIndex),
      /*isReadonly*/
      false
    )] : [];
    return checker.createAnonymousType(
      /*symbol*/
      void 0,
      members,
      callSignatures,
      constructSignatures,
      indexInfos
    );
  }
  function inferNamedTypesFromProperties(usage) {
    if (!usage.properties || !usage.properties.size) return [];
    const types = builtins.filter((t) => allPropertiesAreAssignableToUsage(t, usage));
    if (0 < types.length && types.length < 3) {
      return types.map((t) => inferInstantiationFromUsage(t, usage));
    }
    return [];
  }
  function allPropertiesAreAssignableToUsage(type, usage) {
    if (!usage.properties) return false;
    return !forEachEntry(usage.properties, (propUsage, name) => {
      const source = checker.getTypeOfPropertyOfType(type, name);
      if (!source) {
        return true;
      }
      if (propUsage.calls) {
        const sigs = checker.getSignaturesOfType(source, 0 /* Call */);
        return !sigs.length || !checker.isTypeAssignableTo(source, getFunctionFromCalls(propUsage.calls));
      } else {
        return !checker.isTypeAssignableTo(source, combineFromUsage(propUsage));
      }
    });
  }
  function inferInstantiationFromUsage(type, usage) {
    if (!(getObjectFlags(type) & 4 /* Reference */) || !usage.properties) {
      return type;
    }
    const generic = type.target;
    const singleTypeParameter = singleOrUndefined(generic.typeParameters);
    if (!singleTypeParameter) return type;
    const types = [];
    usage.properties.forEach((propUsage, name) => {
      const genericPropertyType = checker.getTypeOfPropertyOfType(generic, name);
      Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference.");
      types.push(...inferTypeParameters(genericPropertyType, combineFromUsage(propUsage), singleTypeParameter));
    });
    return builtinConstructors[type.symbol.escapedName](combineTypes(types));
  }
  function inferTypeParameters(genericType, usageType, typeParameter) {
    if (genericType === typeParameter) {
      return [usageType];
    } else if (genericType.flags & 3145728 /* UnionOrIntersection */) {
      return flatMap(genericType.types, (t) => inferTypeParameters(t, usageType, typeParameter));
    } else if (getObjectFlags(genericType) & 4 /* Reference */ && getObjectFlags(usageType) & 4 /* Reference */) {
      const genericArgs = checker.getTypeArguments(genericType);
      const usageArgs = checker.getTypeArguments(usageType);
      const types = [];
      if (genericArgs && usageArgs) {
        for (let i = 0; i < genericArgs.length; i++) {
          if (usageArgs[i]) {
            types.push(...inferTypeParameters(genericArgs[i], usageArgs[i], typeParameter));
          }
        }
      }
      return types;
    }
    const genericSigs = checker.getSignaturesOfType(genericType, 0 /* Call */);
    const usageSigs = checker.getSignaturesOfType(usageType, 0 /* Call */);
    if (genericSigs.length === 1 && usageSigs.length === 1) {
      return inferFromSignatures(genericSigs[0], usageSigs[0], typeParameter);
    }
    return [];
  }
  function inferFromSignatures(genericSig, usageSig, typeParameter) {
    var _a;
    const types = [];
    for (let i = 0; i < genericSig.parameters.length; i++) {
      const genericParam = genericSig.parameters[i];
      const usageParam = usageSig.parameters[i];
      const isRest = genericSig.declaration && isRestParameter(genericSig.declaration.parameters[i]);
      if (!usageParam) {
        break;
      }
      let genericParamType = genericParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration) : checker.getAnyType();
      const elementType = isRest && checker.getElementTypeOfArrayType(genericParamType);
      if (elementType) {
        genericParamType = elementType;
      }
      const targetType = ((_a = tryCast(usageParam, isTransientSymbol)) == null ? void 0 : _a.links.type) || (usageParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration) : checker.getAnyType());
      types.push(...inferTypeParameters(genericParamType, targetType, typeParameter));
    }
    const genericReturn = checker.getReturnTypeOfSignature(genericSig);
    const usageReturn = checker.getReturnTypeOfSignature(usageSig);
    types.push(...inferTypeParameters(genericReturn, usageReturn, typeParameter));
    return types;
  }
  function getFunctionFromCalls(calls) {
    return checker.createAnonymousType(
      /*symbol*/
      void 0,
      createSymbolTable(),
      [getSignatureFromCalls(calls)],
      emptyArray,
      emptyArray
    );
  }
  function getSignatureFromCalls(calls) {
    const parameters2 = [];
    const length2 = Math.max(...calls.map((c) => c.argumentTypes.length));
    for (let i = 0; i < length2; i++) {
      const symbol = checker.createSymbol(1 /* FunctionScopedVariable */, escapeLeadingUnderscores(`arg${i}`));
      symbol.links.type = combineTypes(calls.map((call) => call.argumentTypes[i] || checker.getUndefinedType()));
      if (calls.some((call) => call.argumentTypes[i] === void 0)) {
        symbol.flags |= 16777216 /* Optional */;
      }
      parameters2.push(symbol);
    }
    const returnType = combineFromUsage(combineUsages(calls.map((call) => call.return_)));
    return checker.createSignature(
      /*declaration*/
      void 0,
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      parameters2,
      returnType,
      /*typePredicate*/
      void 0,
      length2,
      0 /* None */
    );
  }
  function addCandidateType(usage, type) {
    if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) {
      (usage.candidateTypes || (usage.candidateTypes = [])).push(type);
    }
  }
  function addCandidateThisType(usage, type) {
    if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) {
      (usage.candidateThisTypes || (usage.candidateThisTypes = [])).push(type);
    }
  }
}

// src/services/codefixes/fixReturnTypeInAsyncFunction.ts
var fixId41 = "fixReturnTypeInAsyncFunction";
var errorCodes52 = [
  Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code
];
registerCodeFix({
  errorCodes: errorCodes52,
  fixIds: [fixId41],
  getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) {
    const { sourceFile, program, span } = context;
    const checker = program.getTypeChecker();
    const info = getInfo16(sourceFile, program.getTypeChecker(), span.start);
    if (!info) {
      return void 0;
    }
    const { returnTypeNode, returnType, promisedTypeNode, promisedType } = info;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange34(t, sourceFile, returnTypeNode, promisedTypeNode));
    return [createCodeFixAction(
      fixId41,
      changes,
      [Diagnostics.Replace_0_with_Promise_1, checker.typeToString(returnType), checker.typeToString(promisedType)],
      fixId41,
      Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions
    )];
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes52, (changes, diag2) => {
    const info = getInfo16(diag2.file, context.program.getTypeChecker(), diag2.start);
    if (info) {
      doChange34(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode);
    }
  })
});
function getInfo16(sourceFile, checker, pos) {
  if (isInJSFile(sourceFile)) {
    return void 0;
  }
  const token = getTokenAtPosition(sourceFile, pos);
  const func = findAncestor(token, isFunctionLikeDeclaration);
  const returnTypeNode = func == null ? void 0 : func.type;
  if (!returnTypeNode) {
    return void 0;
  }
  const returnType = checker.getTypeFromTypeNode(returnTypeNode);
  const promisedType = checker.getAwaitedType(returnType) || checker.getVoidType();
  const promisedTypeNode = checker.typeToTypeNode(
    promisedType,
    /*enclosingDeclaration*/
    returnTypeNode,
    /*flags*/
    void 0
  );
  if (promisedTypeNode) {
    return { returnTypeNode, returnType, promisedTypeNode, promisedType };
  }
}
function doChange34(changes, sourceFile, returnTypeNode, promisedTypeNode) {
  changes.replaceNode(sourceFile, returnTypeNode, factory.createTypeReferenceNode("Promise", [promisedTypeNode]));
}

// src/services/codefixes/disableJsDiagnostics.ts
var fixName4 = "disableJsDiagnostics";
var fixId42 = "disableJsDiagnostics";
var errorCodes53 = mapDefined(Object.keys(Diagnostics), (key) => {
  const diag2 = Diagnostics[key];
  return diag2.category === 1 /* Error */ ? diag2.code : void 0;
});
registerCodeFix({
  errorCodes: errorCodes53,
  getCodeActions: function getCodeActionsToDisableJsDiagnostics(context) {
    const { sourceFile, program, span, host, formatContext } = context;
    if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) {
      return void 0;
    }
    const newLineCharacter = sourceFile.checkJsDirective ? "" : getNewLineOrDefaultFromHost(host, formatContext.options);
    const fixes = [
      // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file.
      createCodeFixActionWithoutFixAll(
        fixName4,
        [createFileTextChanges(sourceFile.fileName, [
          createTextChange(
            sourceFile.checkJsDirective ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : createTextSpan(0, 0),
            `// @ts-nocheck${newLineCharacter}`
          )
        ])],
        Diagnostics.Disable_checking_for_this_file
      )
    ];
    if (ts_textChanges_exports.isValidLocationToAddComment(sourceFile, span.start)) {
      fixes.unshift(createCodeFixAction(fixName4, ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange9(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId42, Diagnostics.Add_ts_ignore_to_all_error_messages));
    }
    return fixes;
  },
  fixIds: [fixId42],
  getAllCodeActions: (context) => {
    const seenLines = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes53, (changes, diag2) => {
      if (ts_textChanges_exports.isValidLocationToAddComment(diag2.file, diag2.start)) {
        makeChange9(changes, diag2.file, diag2.start, seenLines);
      }
    });
  }
});
function makeChange9(changes, sourceFile, position, seenLines) {
  const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position);
  if (!seenLines || tryAddToSet(seenLines, lineNumber)) {
    changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore");
  }
}

// src/services/codefixes/helpers.ts
function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, sourceFile, context, preferences, importAdder, addClassElement) {
  const classMembers = classDeclaration.symbol.members;
  for (const symbol of possiblyMissingSymbols) {
    if (!classMembers.has(symbol.escapedName)) {
      addNewNodeForMemberSymbol(
        symbol,
        classDeclaration,
        sourceFile,
        context,
        preferences,
        importAdder,
        addClassElement,
        /*body*/
        void 0
      );
    }
  }
}
function getNoopSymbolTrackerWithResolver(context) {
  return {
    trackSymbol: () => false,
    moduleResolverHost: getModuleSpecifierResolverHost(context.program, context.host)
  };
}
var PreserveOptionalFlags = /* @__PURE__ */ ((PreserveOptionalFlags2) => {
  PreserveOptionalFlags2[PreserveOptionalFlags2["Method"] = 1] = "Method";
  PreserveOptionalFlags2[PreserveOptionalFlags2["Property"] = 2] = "Property";
  PreserveOptionalFlags2[PreserveOptionalFlags2["All"] = 3] = "All";
  return PreserveOptionalFlags2;
})(PreserveOptionalFlags || {});
function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional = 3 /* All */, isAmbient = false) {
  const declarations = symbol.getDeclarations();
  const declaration = firstOrUndefined(declarations);
  const checker = context.program.getTypeChecker();
  const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions());
  const kind = (declaration == null ? void 0 : declaration.kind) ?? 171 /* PropertySignature */;
  const declarationName = createDeclarationName(symbol, declaration);
  const effectiveModifierFlags = declaration ? getEffectiveModifierFlags(declaration) : 0 /* None */;
  let modifierFlags = effectiveModifierFlags & 256 /* Static */;
  modifierFlags |= effectiveModifierFlags & 1 /* Public */ ? 1 /* Public */ : effectiveModifierFlags & 4 /* Protected */ ? 4 /* Protected */ : 0 /* None */;
  if (declaration && isAutoAccessorPropertyDeclaration(declaration)) {
    modifierFlags |= 512 /* Accessor */;
  }
  const modifiers = createModifiers();
  const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
  const optional = !!(symbol.flags & 16777216 /* Optional */);
  const ambient = !!(enclosingDeclaration.flags & 33554432 /* Ambient */) || isAmbient;
  const quotePreference = getQuotePreference(sourceFile, preferences);
  const flags = 1 /* NoTruncation */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */);
  switch (kind) {
    case 171 /* PropertySignature */:
    case 172 /* PropertyDeclaration */:
      let typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, 8 /* AllowUnresolvedNames */, getNoopSymbolTrackerWithResolver(context));
      if (importAdder) {
        const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget);
        if (importableReference) {
          typeNode = importableReference.typeNode;
          importSymbols(importAdder, importableReference.symbols);
        }
      }
      addClassElement(factory.createPropertyDeclaration(
        modifiers,
        declaration ? createName(declarationName) : symbol.getName(),
        optional && preserveOptional & 2 /* Property */ ? factory.createToken(58 /* QuestionToken */) : void 0,
        typeNode,
        /*initializer*/
        void 0
      ));
      break;
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */: {
      Debug.assertIsDefined(declarations);
      let typeNode2 = checker.typeToTypeNode(
        type,
        enclosingDeclaration,
        flags,
        /*internalFlags*/
        void 0,
        getNoopSymbolTrackerWithResolver(context)
      );
      const allAccessors = getAllAccessorDeclarations(declarations, declaration);
      const orderedAccessors = allAccessors.secondAccessor ? [allAccessors.firstAccessor, allAccessors.secondAccessor] : [allAccessors.firstAccessor];
      if (importAdder) {
        const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode2, scriptTarget);
        if (importableReference) {
          typeNode2 = importableReference.typeNode;
          importSymbols(importAdder, importableReference.symbols);
        }
      }
      for (const accessor of orderedAccessors) {
        if (isGetAccessorDeclaration(accessor)) {
          addClassElement(factory.createGetAccessorDeclaration(
            modifiers,
            createName(declarationName),
            emptyArray,
            createTypeNode(typeNode2),
            createBody(body, quotePreference, ambient)
          ));
        } else {
          Debug.assertNode(accessor, isSetAccessorDeclaration, "The counterpart to a getter should be a setter");
          const parameter = getSetAccessorValueParameter(accessor);
          const parameterName = parameter && isIdentifier(parameter.name) ? idText(parameter.name) : void 0;
          addClassElement(factory.createSetAccessorDeclaration(
            modifiers,
            createName(declarationName),
            createDummyParameters(
              1,
              [parameterName],
              [createTypeNode(typeNode2)],
              1,
              /*inJs*/
              false
            ),
            createBody(body, quotePreference, ambient)
          ));
        }
      }
      break;
    }
    case 173 /* MethodSignature */:
    case 174 /* MethodDeclaration */:
      Debug.assertIsDefined(declarations);
      const signatures = type.isUnion() ? flatMap(type.types, (t) => t.getCallSignatures()) : type.getCallSignatures();
      if (!some(signatures)) {
        break;
      }
      if (declarations.length === 1) {
        Debug.assert(signatures.length === 1, "One declaration implies one signature");
        const signature = signatures[0];
        outputMethod(quotePreference, signature, modifiers, createName(declarationName), createBody(body, quotePreference, ambient));
        break;
      }
      for (const signature of signatures) {
        if (signature.declaration && signature.declaration.flags & 33554432 /* Ambient */) {
          continue;
        }
        outputMethod(quotePreference, signature, modifiers, createName(declarationName));
      }
      if (!ambient) {
        if (declarations.length > signatures.length) {
          const signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]);
          outputMethod(quotePreference, signature, modifiers, createName(declarationName), createBody(body, quotePreference));
        } else {
          Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count");
          addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, createName(declarationName), optional && !!(preserveOptional & 1 /* Method */), modifiers, quotePreference, body));
        }
      }
      break;
  }
  function outputMethod(quotePreference2, signature, modifiers2, name, body2) {
    const method = createSignatureDeclarationFromSignature(174 /* MethodDeclaration */, context, quotePreference2, signature, body2, name, modifiers2, optional && !!(preserveOptional & 1 /* Method */), enclosingDeclaration, importAdder);
    if (method) addClassElement(method);
  }
  function createModifiers() {
    let modifiers2;
    if (modifierFlags) {
      modifiers2 = combine(modifiers2, factory.createModifiersFromModifierFlags(modifierFlags));
    }
    if (shouldAddOverrideKeyword()) {
      modifiers2 = append(modifiers2, factory.createToken(164 /* OverrideKeyword */));
    }
    return modifiers2 && factory.createNodeArray(modifiers2);
  }
  function shouldAddOverrideKeyword() {
    return !!(context.program.getCompilerOptions().noImplicitOverride && declaration && hasAbstractModifier(declaration));
  }
  function createName(node) {
    if (isIdentifier(node) && node.escapedText === "constructor") {
      return factory.createComputedPropertyName(factory.createStringLiteral(idText(node), quotePreference === 0 /* Single */));
    }
    return getSynthesizedDeepClone(
      node,
      /*includeTrivia*/
      false
    );
  }
  function createBody(block, quotePreference2, ambient2) {
    return ambient2 ? void 0 : getSynthesizedDeepClone(
      block,
      /*includeTrivia*/
      false
    ) || createStubbedMethodBody(quotePreference2);
  }
  function createTypeNode(typeNode) {
    return getSynthesizedDeepClone(
      typeNode,
      /*includeTrivia*/
      false
    );
  }
  function createDeclarationName(symbol2, declaration2) {
    if (getCheckFlags(symbol2) & 262144 /* Mapped */) {
      const nameType = symbol2.links.nameType;
      if (nameType && isTypeUsableAsPropertyName(nameType)) {
        return factory.createIdentifier(unescapeLeadingUnderscores(getPropertyNameFromType(nameType)));
      }
    }
    return getSynthesizedDeepClone(
      getNameOfDeclaration(declaration2),
      /*includeTrivia*/
      false
    );
  }
}
function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) {
  const program = context.program;
  const checker = program.getTypeChecker();
  const scriptTarget = getEmitScriptTarget(program.getCompilerOptions());
  const isJs = isInJSFile(enclosingDeclaration);
  const flags = 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */ | 524288 /* AllowEmptyTuple */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */);
  const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, kind, enclosingDeclaration, flags, 8 /* AllowUnresolvedNames */, getNoopSymbolTrackerWithResolver(context));
  if (!signatureDeclaration) {
    return void 0;
  }
  let typeParameters = isJs ? void 0 : signatureDeclaration.typeParameters;
  let parameters = signatureDeclaration.parameters;
  let type = isJs ? void 0 : getSynthesizedDeepClone(signatureDeclaration.type);
  if (importAdder) {
    if (typeParameters) {
      const newTypeParameters = sameMap(typeParameters, (typeParameterDecl) => {
        let constraint = typeParameterDecl.constraint;
        let defaultType = typeParameterDecl.default;
        if (constraint) {
          const importableReference = tryGetAutoImportableReferenceFromTypeNode(constraint, scriptTarget);
          if (importableReference) {
            constraint = importableReference.typeNode;
            importSymbols(importAdder, importableReference.symbols);
          }
        }
        if (defaultType) {
          const importableReference = tryGetAutoImportableReferenceFromTypeNode(defaultType, scriptTarget);
          if (importableReference) {
            defaultType = importableReference.typeNode;
            importSymbols(importAdder, importableReference.symbols);
          }
        }
        return factory.updateTypeParameterDeclaration(
          typeParameterDecl,
          typeParameterDecl.modifiers,
          typeParameterDecl.name,
          constraint,
          defaultType
        );
      });
      if (typeParameters !== newTypeParameters) {
        typeParameters = setTextRange(factory.createNodeArray(newTypeParameters, typeParameters.hasTrailingComma), typeParameters);
      }
    }
    const newParameters = sameMap(parameters, (parameterDecl) => {
      let type2 = isJs ? void 0 : parameterDecl.type;
      if (type2) {
        const importableReference = tryGetAutoImportableReferenceFromTypeNode(type2, scriptTarget);
        if (importableReference) {
          type2 = importableReference.typeNode;
          importSymbols(importAdder, importableReference.symbols);
        }
      }
      return factory.updateParameterDeclaration(
        parameterDecl,
        parameterDecl.modifiers,
        parameterDecl.dotDotDotToken,
        parameterDecl.name,
        isJs ? void 0 : parameterDecl.questionToken,
        type2,
        parameterDecl.initializer
      );
    });
    if (parameters !== newParameters) {
      parameters = setTextRange(factory.createNodeArray(newParameters, parameters.hasTrailingComma), parameters);
    }
    if (type) {
      const importableReference = tryGetAutoImportableReferenceFromTypeNode(type, scriptTarget);
      if (importableReference) {
        type = importableReference.typeNode;
        importSymbols(importAdder, importableReference.symbols);
      }
    }
  }
  const questionToken = optional ? factory.createToken(58 /* QuestionToken */) : void 0;
  const asteriskToken = signatureDeclaration.asteriskToken;
  if (isFunctionExpression(signatureDeclaration)) {
    return factory.updateFunctionExpression(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body ?? signatureDeclaration.body);
  }
  if (isArrowFunction(signatureDeclaration)) {
    return factory.updateArrowFunction(signatureDeclaration, modifiers, typeParameters, parameters, type, signatureDeclaration.equalsGreaterThanToken, body ?? signatureDeclaration.body);
  }
  if (isMethodDeclaration(signatureDeclaration)) {
    return factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name ?? factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body);
  }
  if (isFunctionDeclaration(signatureDeclaration)) {
    return factory.updateFunctionDeclaration(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body ?? signatureDeclaration.body);
  }
  return void 0;
}
function createSignatureDeclarationFromCallExpression(kind, context, importAdder, call, name, modifierFlags, contextNode) {
  const quotePreference = getQuotePreference(context.sourceFile, context.preferences);
  const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions());
  const tracker = getNoopSymbolTrackerWithResolver(context);
  const checker = context.program.getTypeChecker();
  const isJs = isInJSFile(contextNode);
  const { typeArguments, arguments: args, parent: parent2 } = call;
  const contextualType = isJs ? void 0 : checker.getContextualType(call);
  const names = map(args, (arg) => isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) && isIdentifier(arg.name) ? arg.name.text : void 0);
  const instanceTypes = isJs ? [] : map(args, (arg) => checker.getTypeAtLocation(arg));
  const { argumentTypeNodes, argumentTypeParameters } = getArgumentTypesAndTypeParameters(
    checker,
    importAdder,
    instanceTypes,
    contextNode,
    scriptTarget,
    1 /* NoTruncation */,
    8 /* AllowUnresolvedNames */,
    tracker
  );
  const modifiers = modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : void 0;
  const asteriskToken = isYieldExpression(parent2) ? factory.createToken(42 /* AsteriskToken */) : void 0;
  const typeParameters = isJs ? void 0 : createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments);
  const parameters = createDummyParameters(
    args.length,
    names,
    argumentTypeNodes,
    /*minArgumentCount*/
    void 0,
    isJs
  );
  const type = isJs || contextualType === void 0 ? void 0 : checker.typeToTypeNode(
    contextualType,
    contextNode,
    /*flags*/
    void 0,
    /*internalFlags*/
    void 0,
    tracker
  );
  switch (kind) {
    case 174 /* MethodDeclaration */:
      return factory.createMethodDeclaration(
        modifiers,
        asteriskToken,
        name,
        /*questionToken*/
        void 0,
        typeParameters,
        parameters,
        type,
        createStubbedMethodBody(quotePreference)
      );
    case 173 /* MethodSignature */:
      return factory.createMethodSignature(
        modifiers,
        name,
        /*questionToken*/
        void 0,
        typeParameters,
        parameters,
        type === void 0 ? factory.createKeywordTypeNode(159 /* UnknownKeyword */) : type
      );
    case 262 /* FunctionDeclaration */:
      Debug.assert(typeof name === "string" || isIdentifier(name), "Unexpected name");
      return factory.createFunctionDeclaration(
        modifiers,
        asteriskToken,
        name,
        typeParameters,
        parameters,
        type,
        createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference)
      );
    default:
      Debug.fail("Unexpected kind");
  }
}
function createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments) {
  const usedNames = new Set(argumentTypeParameters.map((pair) => pair[0]));
  const constraintsByName = new Map(argumentTypeParameters);
  if (typeArguments) {
    const typeArgumentsWithNewTypes = typeArguments.filter((typeArgument) => !argumentTypeParameters.some((pair) => {
      var _a;
      return checker.getTypeAtLocation(typeArgument) === ((_a = pair[1]) == null ? void 0 : _a.argumentType);
    }));
    const targetSize = usedNames.size + typeArgumentsWithNewTypes.length;
    for (let i = 0; usedNames.size < targetSize; i += 1) {
      usedNames.add(createTypeParameterName(i));
    }
  }
  return arrayFrom(
    usedNames.values(),
    (usedName) => {
      var _a;
      return factory.createTypeParameterDeclaration(
        /*modifiers*/
        void 0,
        usedName,
        (_a = constraintsByName.get(usedName)) == null ? void 0 : _a.constraint
      );
    }
  );
}
function createTypeParameterName(index) {
  return 84 /* T */ + index <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + index) : `T${index}`;
}
function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, internalFlags, tracker) {
  const typeNode = checker.typeToTypeNode(type, contextNode, flags, internalFlags, tracker);
  if (!typeNode) {
    return void 0;
  }
  return typeNodeToAutoImportableTypeNode(typeNode, importAdder, scriptTarget);
}
function typeNodeToAutoImportableTypeNode(typeNode, importAdder, scriptTarget) {
  if (typeNode && isImportTypeNode(typeNode)) {
    const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget);
    if (importableReference) {
      importSymbols(importAdder, importableReference.symbols);
      typeNode = importableReference.typeNode;
    }
  }
  return getSynthesizedDeepClone(typeNode);
}
function endOfRequiredTypeParameters(checker, type) {
  Debug.assert(type.typeArguments);
  const fullTypeArguments = type.typeArguments;
  const target = type.target;
  for (let cutoff = 0; cutoff < fullTypeArguments.length; cutoff++) {
    const typeArguments = fullTypeArguments.slice(0, cutoff);
    const filledIn = checker.fillMissingTypeArguments(
      typeArguments,
      target.typeParameters,
      cutoff,
      /*isJavaScriptImplicitAny*/
      false
    );
    if (filledIn.every((fill, i) => fill === fullTypeArguments[i])) {
      return cutoff;
    }
  }
  return fullTypeArguments.length;
}
function typeToMinimizedReferenceType(checker, type, contextNode, flags, internalFlags, tracker) {
  let typeNode = checker.typeToTypeNode(type, contextNode, flags, internalFlags, tracker);
  if (!typeNode) {
    return void 0;
  }
  if (isTypeReferenceNode(typeNode)) {
    const genericType = type;
    if (genericType.typeArguments && typeNode.typeArguments) {
      const cutoff = endOfRequiredTypeParameters(checker, genericType);
      if (cutoff < typeNode.typeArguments.length) {
        const newTypeArguments = factory.createNodeArray(typeNode.typeArguments.slice(0, cutoff));
        typeNode = factory.updateTypeReferenceNode(typeNode, typeNode.typeName, newTypeArguments);
      }
    }
  }
  return typeNode;
}
function typePredicateToAutoImportableTypeNode(checker, importAdder, typePredicate, contextNode, scriptTarget, flags, internalFlags, tracker) {
  let typePredicateNode = checker.typePredicateToTypePredicateNode(typePredicate, contextNode, flags, internalFlags, tracker);
  if ((typePredicateNode == null ? void 0 : typePredicateNode.type) && isImportTypeNode(typePredicateNode.type)) {
    const importableReference = tryGetAutoImportableReferenceFromTypeNode(typePredicateNode.type, scriptTarget);
    if (importableReference) {
      importSymbols(importAdder, importableReference.symbols);
      typePredicateNode = factory.updateTypePredicateNode(typePredicateNode, typePredicateNode.assertsModifier, typePredicateNode.parameterName, importableReference.typeNode);
    }
  }
  return getSynthesizedDeepClone(typePredicateNode);
}
function typeContainsTypeParameter(type) {
  if (type.isUnionOrIntersection()) {
    return type.types.some(typeContainsTypeParameter);
  }
  return type.flags & 262144 /* TypeParameter */;
}
function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, internalFlags, tracker) {
  const argumentTypeNodes = [];
  const argumentTypeParameters = /* @__PURE__ */ new Map();
  for (let i = 0; i < instanceTypes.length; i += 1) {
    const instanceType = instanceTypes[i];
    if (instanceType.isUnionOrIntersection() && instanceType.types.some(typeContainsTypeParameter)) {
      const synthesizedTypeParameterName = createTypeParameterName(i);
      argumentTypeNodes.push(factory.createTypeReferenceNode(synthesizedTypeParameterName));
      argumentTypeParameters.set(synthesizedTypeParameterName, void 0);
      continue;
    }
    const widenedInstanceType = checker.getBaseTypeOfLiteralType(instanceType);
    const argumentTypeNode = typeToAutoImportableTypeNode(checker, importAdder, widenedInstanceType, contextNode, scriptTarget, flags, internalFlags, tracker);
    if (!argumentTypeNode) {
      continue;
    }
    argumentTypeNodes.push(argumentTypeNode);
    const argumentTypeParameter = getFirstTypeParameterName(instanceType);
    const instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, internalFlags, tracker) : void 0;
    if (argumentTypeParameter) {
      argumentTypeParameters.set(argumentTypeParameter, { argumentType: instanceType, constraint: instanceTypeConstraint });
    }
  }
  return { argumentTypeNodes, argumentTypeParameters: arrayFrom(argumentTypeParameters.entries()) };
}
function isAnonymousObjectConstraintType(type) {
  return type.flags & 524288 /* Object */ && type.objectFlags === 16 /* Anonymous */;
}
function getFirstTypeParameterName(type) {
  var _a;
  if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
    for (const subType of type.types) {
      const subTypeName = getFirstTypeParameterName(subType);
      if (subTypeName) {
        return subTypeName;
      }
    }
  }
  return type.flags & 262144 /* TypeParameter */ ? (_a = type.getSymbol()) == null ? void 0 : _a.getName() : void 0;
}
function createDummyParameters(argCount, names, types, minArgumentCount, inJs) {
  const parameters = [];
  const parameterNameCounts = /* @__PURE__ */ new Map();
  for (let i = 0; i < argCount; i++) {
    const parameterName = (names == null ? void 0 : names[i]) || `arg${i}`;
    const parameterNameCount = parameterNameCounts.get(parameterName);
    parameterNameCounts.set(parameterName, (parameterNameCount || 0) + 1);
    const newParameter = factory.createParameterDeclaration(
      /*modifiers*/
      void 0,
      /*dotDotDotToken*/
      void 0,
      /*name*/
      parameterName + (parameterNameCount || ""),
      /*questionToken*/
      minArgumentCount !== void 0 && i >= minArgumentCount ? factory.createToken(58 /* QuestionToken */) : void 0,
      /*type*/
      inJs ? void 0 : (types == null ? void 0 : types[i]) || factory.createKeywordTypeNode(159 /* UnknownKeyword */),
      /*initializer*/
      void 0
    );
    parameters.push(newParameter);
  }
  return parameters;
}
function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference, body) {
  let maxArgsSignature = signatures[0];
  let minArgumentCount = signatures[0].minArgumentCount;
  let someSigHasRestParameter = false;
  for (const sig of signatures) {
    minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
    if (signatureHasRestParameter(sig)) {
      someSigHasRestParameter = true;
    }
    if (sig.parameters.length >= maxArgsSignature.parameters.length && (!signatureHasRestParameter(sig) || signatureHasRestParameter(maxArgsSignature))) {
      maxArgsSignature = sig;
    }
  }
  const maxNonRestArgs = maxArgsSignature.parameters.length - (signatureHasRestParameter(maxArgsSignature) ? 1 : 0);
  const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map((symbol) => symbol.name);
  const parameters = createDummyParameters(
    maxNonRestArgs,
    maxArgsParameterSymbolNames,
    /*types*/
    void 0,
    minArgumentCount,
    /*inJs*/
    false
  );
  if (someSigHasRestParameter) {
    const restParameter = factory.createParameterDeclaration(
      /*modifiers*/
      void 0,
      factory.createToken(26 /* DotDotDotToken */),
      maxArgsParameterSymbolNames[maxNonRestArgs] || "rest",
      /*questionToken*/
      maxNonRestArgs >= minArgumentCount ? factory.createToken(58 /* QuestionToken */) : void 0,
      factory.createArrayTypeNode(factory.createKeywordTypeNode(159 /* UnknownKeyword */)),
      /*initializer*/
      void 0
    );
    parameters.push(restParameter);
  }
  return createStubbedMethod(
    modifiers,
    name,
    optional,
    /*typeParameters*/
    void 0,
    parameters,
    getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration),
    quotePreference,
    body
  );
}
function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) {
  if (length(signatures)) {
    const type = checker.getUnionType(map(signatures, checker.getReturnTypeOfSignature));
    return checker.typeToTypeNode(type, enclosingDeclaration, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */, getNoopSymbolTrackerWithResolver(context));
  }
}
function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) {
  return factory.createMethodDeclaration(
    modifiers,
    /*asteriskToken*/
    void 0,
    name,
    optional ? factory.createToken(58 /* QuestionToken */) : void 0,
    typeParameters,
    parameters,
    returnType,
    body || createStubbedMethodBody(quotePreference)
  );
}
function createStubbedMethodBody(quotePreference) {
  return createStubbedBody(Diagnostics.Method_not_implemented.message, quotePreference);
}
function createStubbedBody(text, quotePreference) {
  return factory.createBlock(
    [factory.createThrowStatement(
      factory.createNewExpression(
        factory.createIdentifier("Error"),
        /*typeArguments*/
        void 0,
        // TODO Handle auto quote preference.
        [factory.createStringLiteral(
          text,
          /*isSingleQuote*/
          quotePreference === 0 /* Single */
        )]
      )
    )],
    /*multiLine*/
    true
  );
}
function setJsonCompilerOptionValues(changeTracker, configFile, options) {
  const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile);
  if (!tsconfigObjectLiteral) return void 0;
  const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions");
  if (compilerOptionsProperty === void 0) {
    changeTracker.insertNodeAtObjectStart(
      configFile,
      tsconfigObjectLiteral,
      createJsonPropertyAssignment(
        "compilerOptions",
        factory.createObjectLiteralExpression(
          options.map(([optionName, optionValue]) => createJsonPropertyAssignment(optionName, optionValue)),
          /*multiLine*/
          true
        )
      )
    );
    return;
  }
  const compilerOptions = compilerOptionsProperty.initializer;
  if (!isObjectLiteralExpression(compilerOptions)) {
    return;
  }
  for (const [optionName, optionValue] of options) {
    const optionProperty = findJsonProperty(compilerOptions, optionName);
    if (optionProperty === void 0) {
      changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue));
    } else {
      changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue);
    }
  }
}
function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) {
  setJsonCompilerOptionValues(changeTracker, configFile, [[optionName, optionValue]]);
}
function createJsonPropertyAssignment(name, initializer) {
  return factory.createPropertyAssignment(factory.createStringLiteral(name), initializer);
}
function findJsonProperty(obj, name) {
  return find(obj.properties, (p) => isPropertyAssignment(p) && !!p.name && isStringLiteral(p.name) && p.name.text === name);
}
function tryGetAutoImportableReferenceFromTypeNode(importTypeNode, scriptTarget) {
  let symbols;
  const typeNode = visitNode(importTypeNode, visit, isTypeNode);
  if (symbols && typeNode) {
    return { typeNode, symbols };
  }
  function visit(node) {
    if (isLiteralImportTypeNode(node) && node.qualifier) {
      const firstIdentifier = getFirstIdentifier(node.qualifier);
      if (!firstIdentifier.symbol) {
        return visitEachChild(
          node,
          visit,
          /*context*/
          void 0
        );
      }
      const name = getNameForExportedSymbol(firstIdentifier.symbol, scriptTarget);
      const qualifier = name !== firstIdentifier.text ? replaceFirstIdentifierOfEntityName(node.qualifier, factory.createIdentifier(name)) : node.qualifier;
      symbols = append(symbols, firstIdentifier.symbol);
      const typeArguments = visitNodes2(node.typeArguments, visit, isTypeNode);
      return factory.createTypeReferenceNode(qualifier, typeArguments);
    }
    return visitEachChild(
      node,
      visit,
      /*context*/
      void 0
    );
  }
}
function replaceFirstIdentifierOfEntityName(name, newIdentifier) {
  if (name.kind === 80 /* Identifier */) {
    return newIdentifier;
  }
  return factory.createQualifiedName(replaceFirstIdentifierOfEntityName(name.left, newIdentifier), name.right);
}
function importSymbols(importAdder, symbols) {
  symbols.forEach((s) => importAdder.addImportFromExportedSymbol(
    s,
    /*isValidTypeOnlyUseSite*/
    true
  ));
}
function findAncestorMatchingSpan(sourceFile, span) {
  const end = textSpanEnd(span);
  let token = getTokenAtPosition(sourceFile, span.start);
  while (token.end < end) {
    token = token.parent;
  }
  return token;
}

// src/services/codefixes/generateAccessors.ts
function generateAccessorFromProperty(file, program, start, end, context, _actionName) {
  const fieldInfo = getAccessorConvertiblePropertyAtPosition(file, program, start, end);
  if (!fieldInfo || ts_refactor_exports.isRefactorErrorInfo(fieldInfo)) return void 0;
  const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context);
  const { isStatic: isStatic2, isReadonly, fieldName, accessorName, originalName, type, container, declaration } = fieldInfo;
  suppressLeadingAndTrailingTrivia(fieldName);
  suppressLeadingAndTrailingTrivia(accessorName);
  suppressLeadingAndTrailingTrivia(declaration);
  suppressLeadingAndTrailingTrivia(container);
  let accessorModifiers;
  let fieldModifiers;
  if (isClassLike(container)) {
    const modifierFlags = getEffectiveModifierFlags(declaration);
    if (isSourceFileJS(file)) {
      const modifiers = factory.createModifiersFromModifierFlags(modifierFlags);
      accessorModifiers = modifiers;
      fieldModifiers = modifiers;
    } else {
      accessorModifiers = factory.createModifiersFromModifierFlags(prepareModifierFlagsForAccessor(modifierFlags));
      fieldModifiers = factory.createModifiersFromModifierFlags(prepareModifierFlagsForField(modifierFlags));
    }
    if (canHaveDecorators(declaration)) {
      fieldModifiers = concatenate(getDecorators(declaration), fieldModifiers);
    }
  }
  updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers);
  const getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic2, container);
  suppressLeadingAndTrailingTrivia(getAccessor);
  insertAccessor(changeTracker, file, getAccessor, declaration, container);
  if (isReadonly) {
    const constructor = getFirstConstructorWithBody(container);
    if (constructor) {
      updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName);
    }
  } else {
    const setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic2, container);
    suppressLeadingAndTrailingTrivia(setAccessor);
    insertAccessor(changeTracker, file, setAccessor, declaration, container);
  }
  return changeTracker.getChanges();
}
function isConvertibleName(name) {
  return isIdentifier(name) || isStringLiteral(name);
}
function isAcceptedDeclaration(node) {
  return isParameterPropertyDeclaration(node, node.parent) || isPropertyDeclaration(node) || isPropertyAssignment(node);
}
function createPropertyName(name, originalName) {
  return isIdentifier(originalName) ? factory.createIdentifier(name) : factory.createStringLiteral(name);
}
function createAccessorAccessExpression(fieldName, isStatic2, container) {
  const leftHead = isStatic2 ? container.name : factory.createThis();
  return isIdentifier(fieldName) ? factory.createPropertyAccessExpression(leftHead, fieldName) : factory.createElementAccessExpression(leftHead, factory.createStringLiteralFromNode(fieldName));
}
function prepareModifierFlagsForAccessor(modifierFlags) {
  modifierFlags &= ~8 /* Readonly */;
  modifierFlags &= ~2 /* Private */;
  if (!(modifierFlags & 4 /* Protected */)) {
    modifierFlags |= 1 /* Public */;
  }
  return modifierFlags;
}
function prepareModifierFlagsForField(modifierFlags) {
  modifierFlags &= ~1 /* Public */;
  modifierFlags &= ~4 /* Protected */;
  modifierFlags |= 2 /* Private */;
  return modifierFlags;
}
function getAccessorConvertiblePropertyAtPosition(file, program, start, end, considerEmptySpans = true) {
  const node = getTokenAtPosition(file, start);
  const cursorRequest = start === end && considerEmptySpans;
  const declaration = findAncestor(node.parent, isAcceptedDeclaration);
  const meaning = 7 /* AccessibilityModifier */ | 256 /* Static */ | 8 /* Readonly */;
  if (!declaration || !(nodeOverlapsWithStartEnd(declaration.name, file, start, end) || cursorRequest)) {
    return {
      error: getLocaleSpecificMessage(Diagnostics.Could_not_find_property_for_which_to_generate_accessor)
    };
  }
  if (!isConvertibleName(declaration.name)) {
    return {
      error: getLocaleSpecificMessage(Diagnostics.Name_is_not_valid)
    };
  }
  if ((getEffectiveModifierFlags(declaration) & 98303 /* Modifier */ | meaning) !== meaning) {
    return {
      error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_property_with_modifier)
    };
  }
  const name = declaration.name.text;
  const startWithUnderscore = startsWithUnderscore(name);
  const fieldName = createPropertyName(startWithUnderscore ? name : getUniqueName(`_${name}`, file), declaration.name);
  const accessorName = createPropertyName(startWithUnderscore ? getUniqueName(name.substring(1), file) : name, declaration.name);
  return {
    isStatic: hasStaticModifier(declaration),
    isReadonly: hasEffectiveReadonlyModifier(declaration),
    type: getDeclarationType(declaration, program),
    container: declaration.kind === 169 /* Parameter */ ? declaration.parent.parent : declaration.parent,
    originalName: declaration.name.text,
    declaration,
    fieldName,
    accessorName,
    renameAccessor: startWithUnderscore
  };
}
function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic2, container) {
  return factory.createGetAccessorDeclaration(
    modifiers,
    accessorName,
    [],
    type,
    factory.createBlock(
      [
        factory.createReturnStatement(
          createAccessorAccessExpression(fieldName, isStatic2, container)
        )
      ],
      /*multiLine*/
      true
    )
  );
}
function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic2, container) {
  return factory.createSetAccessorDeclaration(
    modifiers,
    accessorName,
    [factory.createParameterDeclaration(
      /*modifiers*/
      void 0,
      /*dotDotDotToken*/
      void 0,
      factory.createIdentifier("value"),
      /*questionToken*/
      void 0,
      type
    )],
    factory.createBlock(
      [
        factory.createExpressionStatement(
          factory.createAssignment(
            createAccessorAccessExpression(fieldName, isStatic2, container),
            factory.createIdentifier("value")
          )
        )
      ],
      /*multiLine*/
      true
    )
  );
}
function updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) {
  const property = factory.updatePropertyDeclaration(
    declaration,
    modifiers,
    fieldName,
    declaration.questionToken || declaration.exclamationToken,
    type,
    declaration.initializer
  );
  changeTracker.replaceNode(file, declaration, property);
}
function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
  let assignment = factory.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
  if (assignment.modifiers || assignment.questionToken || assignment.exclamationToken) {
    if (assignment === declaration) assignment = factory.cloneNode(assignment);
    assignment.modifiers = void 0;
    assignment.questionToken = void 0;
    assignment.exclamationToken = void 0;
  }
  changeTracker.replacePropertyAssignment(file, declaration, assignment);
}
function updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) {
  if (isPropertyDeclaration(declaration)) {
    updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers);
  } else if (isPropertyAssignment(declaration)) {
    updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
  } else {
    changeTracker.replaceNode(file, declaration, factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, cast(fieldName, isIdentifier), declaration.questionToken, declaration.type, declaration.initializer));
  }
}
function insertAccessor(changeTracker, file, accessor, declaration, container) {
  isParameterPropertyDeclaration(declaration, declaration.parent) ? changeTracker.insertMemberAtStart(file, container, accessor) : isPropertyAssignment(declaration) ? changeTracker.insertNodeAfterComma(file, declaration, accessor) : changeTracker.insertNodeAfter(file, declaration, accessor);
}
function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) {
  if (!constructor.body) return;
  constructor.body.forEachChild(function recur(node) {
    if (isElementAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && isStringLiteral(node.argumentExpression) && node.argumentExpression.text === originalName && isWriteAccess(node)) {
      changeTracker.replaceNode(file, node.argumentExpression, factory.createStringLiteral(fieldName));
    }
    if (isPropertyAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && node.name.text === originalName && isWriteAccess(node)) {
      changeTracker.replaceNode(file, node.name, factory.createIdentifier(fieldName));
    }
    if (!isFunctionLike(node) && !isClassLike(node)) {
      node.forEachChild(recur);
    }
  });
}
function getDeclarationType(declaration, program) {
  const typeNode = getTypeAnnotationNode(declaration);
  if (isPropertyDeclaration(declaration) && typeNode && declaration.questionToken) {
    const typeChecker = program.getTypeChecker();
    const type = typeChecker.getTypeFromTypeNode(typeNode);
    if (!typeChecker.isTypeAssignableTo(typeChecker.getUndefinedType(), type)) {
      const types = isUnionTypeNode(typeNode) ? typeNode.types : [typeNode];
      return factory.createUnionTypeNode([...types, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]);
    }
  }
  return typeNode;
}
function getAllSupers(decl, checker) {
  const res = [];
  while (decl) {
    const superElement = getClassExtendsHeritageElement(decl);
    const superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression);
    if (!superSymbol) break;
    const symbol = superSymbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(superSymbol) : superSymbol;
    const superDecl = symbol.declarations && find(symbol.declarations, isClassLike);
    if (!superDecl) break;
    res.push(superDecl);
    decl = superDecl;
  }
  return res;
}

// src/services/codefixes/fixInvalidImportSyntax.ts
var fixName5 = "invalidImportSyntax";
function getCodeFixesForImportDeclaration(context, node) {
  const sourceFile = getSourceFileOfNode(node);
  const namespace = getNamespaceDeclarationNode(node);
  const opts = context.program.getCompilerOptions();
  const variations = [];
  variations.push(createAction(context, sourceFile, node, makeImport(
    namespace.name,
    /*namedImports*/
    void 0,
    node.moduleSpecifier,
    getQuotePreference(sourceFile, context.preferences)
  )));
  if (getEmitModuleKind(opts) === 1 /* CommonJS */) {
    variations.push(createAction(
      context,
      sourceFile,
      node,
      factory.createImportEqualsDeclaration(
        /*modifiers*/
        void 0,
        /*isTypeOnly*/
        false,
        namespace.name,
        factory.createExternalModuleReference(node.moduleSpecifier)
      )
    ));
  }
  return variations;
}
function createAction(context, sourceFile, node, replacement) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(sourceFile, node, replacement));
  return createCodeFixActionWithoutFixAll(fixName5, changes, [Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]);
}
registerCodeFix({
  errorCodes: [
    Diagnostics.This_expression_is_not_callable.code,
    Diagnostics.This_expression_is_not_constructable.code
  ],
  getCodeActions: getActionsForUsageOfInvalidImport
});
function getActionsForUsageOfInvalidImport(context) {
  const sourceFile = context.sourceFile;
  const targetKind = Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 213 /* CallExpression */ : 214 /* NewExpression */;
  const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), (a) => a.kind === targetKind);
  if (!node) {
    return [];
  }
  const expr = node.expression;
  return getImportCodeFixesForExpression(context, expr);
}
registerCodeFix({
  errorCodes: [
    // The following error codes cover pretty much all assignability errors that could involve an expression
    Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
    Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code,
    Diagnostics.Type_0_is_not_assignable_to_type_1.code,
    Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code,
    Diagnostics.Type_predicate_0_is_not_assignable_to_1.code,
    Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3.code,
    Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3.code,
    Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code,
    Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code,
    Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code,
    Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code
  ],
  getCodeActions: getActionsForInvalidImportLocation
});
function getActionsForInvalidImportLocation(context) {
  const sourceFile = context.sourceFile;
  const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), (a) => a.getStart() === context.span.start && a.getEnd() === context.span.start + context.span.length);
  if (!node) {
    return [];
  }
  return getImportCodeFixesForExpression(context, node);
}
function getImportCodeFixesForExpression(context, expr) {
  const type = context.program.getTypeChecker().getTypeAtLocation(expr);
  if (!(type.symbol && isTransientSymbol(type.symbol) && type.symbol.links.originatingImport)) {
    return [];
  }
  const fixes = [];
  const relatedImport = type.symbol.links.originatingImport;
  if (!isImportCall(relatedImport)) {
    addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
  }
  if (isExpression(expr) && !(isNamedDeclaration(expr.parent) && expr.parent.name === expr)) {
    const sourceFile = context.sourceFile;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(sourceFile, expr, factory.createPropertyAccessExpression(expr, "default"), {}));
    fixes.push(createCodeFixActionWithoutFixAll(fixName5, changes, Diagnostics.Use_synthetic_default_member));
  }
  return fixes;
}

// src/services/codefixes/fixStrictClassInitialization.ts
var fixName6 = "strictClassInitialization";
var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions";
var fixIdAddUndefinedType = "addMissingPropertyUndefinedType";
var fixIdAddInitializer = "addMissingPropertyInitializer";
var errorCodes54 = [Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code];
registerCodeFix({
  errorCodes: errorCodes54,
  getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) {
    const info = getInfo17(context.sourceFile, context.span.start);
    if (!info) return;
    const result = [];
    append(result, getActionForAddMissingUndefinedType(context, info));
    append(result, getActionForAddMissingDefiniteAssignmentAssertion(context, info));
    append(result, getActionForAddMissingInitializer(context, info));
    return result;
  },
  fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer],
  getAllCodeActions: (context) => {
    return codeFixAll(context, errorCodes54, (changes, diag2) => {
      const info = getInfo17(diag2.file, diag2.start);
      if (!info) return;
      switch (context.fixId) {
        case fixIdAddDefiniteAssignmentAssertions:
          addDefiniteAssignmentAssertion(changes, diag2.file, info.prop);
          break;
        case fixIdAddUndefinedType:
          addUndefinedType(changes, diag2.file, info);
          break;
        case fixIdAddInitializer:
          const checker = context.program.getTypeChecker();
          const initializer = getInitializer(checker, info.prop);
          if (!initializer) return;
          addInitializer(changes, diag2.file, info.prop, initializer);
          break;
        default:
          Debug.fail(JSON.stringify(context.fixId));
      }
    });
  }
});
function getInfo17(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (isIdentifier(token) && isPropertyDeclaration(token.parent)) {
    const type = getEffectiveTypeAnnotationNode(token.parent);
    if (type) {
      return { type, prop: token.parent, isJs: isInJSFile(token.parent) };
    }
  }
  return void 0;
}
function getActionForAddMissingDefiniteAssignmentAssertion(context, info) {
  if (info.isJs) return void 0;
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addDefiniteAssignmentAssertion(t, context.sourceFile, info.prop));
  return createCodeFixAction(fixName6, changes, [Diagnostics.Add_definite_assignment_assertion_to_property_0, info.prop.getText()], fixIdAddDefiniteAssignmentAssertions, Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties);
}
function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
  suppressLeadingAndTrailingTrivia(propertyDeclaration);
  const property = factory.updatePropertyDeclaration(
    propertyDeclaration,
    propertyDeclaration.modifiers,
    propertyDeclaration.name,
    factory.createToken(54 /* ExclamationToken */),
    propertyDeclaration.type,
    propertyDeclaration.initializer
  );
  changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
}
function getActionForAddMissingUndefinedType(context, info) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addUndefinedType(t, context.sourceFile, info));
  return createCodeFixAction(fixName6, changes, [Diagnostics.Add_undefined_type_to_property_0, info.prop.name.getText()], fixIdAddUndefinedType, Diagnostics.Add_undefined_type_to_all_uninitialized_properties);
}
function addUndefinedType(changeTracker, sourceFile, info) {
  const undefinedTypeNode = factory.createKeywordTypeNode(157 /* UndefinedKeyword */);
  const types = isUnionTypeNode(info.type) ? info.type.types.concat(undefinedTypeNode) : [info.type, undefinedTypeNode];
  const unionTypeNode = factory.createUnionTypeNode(types);
  if (info.isJs) {
    changeTracker.addJSDocTags(sourceFile, info.prop, [factory.createJSDocTypeTag(
      /*tagName*/
      void 0,
      factory.createJSDocTypeExpression(unionTypeNode)
    )]);
  } else {
    changeTracker.replaceNode(sourceFile, info.type, unionTypeNode);
  }
}
function getActionForAddMissingInitializer(context, info) {
  if (info.isJs) return void 0;
  const checker = context.program.getTypeChecker();
  const initializer = getInitializer(checker, info.prop);
  if (!initializer) return void 0;
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addInitializer(t, context.sourceFile, info.prop, initializer));
  return createCodeFixAction(fixName6, changes, [Diagnostics.Add_initializer_to_property_0, info.prop.name.getText()], fixIdAddInitializer, Diagnostics.Add_initializers_to_all_uninitialized_properties);
}
function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) {
  suppressLeadingAndTrailingTrivia(propertyDeclaration);
  const property = factory.updatePropertyDeclaration(
    propertyDeclaration,
    propertyDeclaration.modifiers,
    propertyDeclaration.name,
    propertyDeclaration.questionToken,
    propertyDeclaration.type,
    initializer
  );
  changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
}
function getInitializer(checker, propertyDeclaration) {
  return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type));
}
function getDefaultValueFromType(checker, type) {
  if (type.flags & 512 /* BooleanLiteral */) {
    return type === checker.getFalseType() || type === checker.getFalseType(
      /*fresh*/
      true
    ) ? factory.createFalse() : factory.createTrue();
  } else if (type.isStringLiteral()) {
    return factory.createStringLiteral(type.value);
  } else if (type.isNumberLiteral()) {
    return factory.createNumericLiteral(type.value);
  } else if (type.flags & 2048 /* BigIntLiteral */) {
    return factory.createBigIntLiteral(type.value);
  } else if (type.isUnion()) {
    return firstDefined(type.types, (t) => getDefaultValueFromType(checker, t));
  } else if (type.isClass()) {
    const classDeclaration = getClassLikeDeclarationOfSymbol(type.symbol);
    if (!classDeclaration || hasSyntacticModifier(classDeclaration, 64 /* Abstract */)) return void 0;
    const constructorDeclaration = getFirstConstructorWithBody(classDeclaration);
    if (constructorDeclaration && constructorDeclaration.parameters.length) return void 0;
    return factory.createNewExpression(
      factory.createIdentifier(type.symbol.name),
      /*typeArguments*/
      void 0,
      /*argumentsArray*/
      void 0
    );
  } else if (checker.isArrayLikeType(type)) {
    return factory.createArrayLiteralExpression();
  }
  return void 0;
}

// src/services/codefixes/requireInTs.ts
var fixId43 = "requireInTs";
var errorCodes55 = [Diagnostics.require_call_may_be_converted_to_an_import.code];
registerCodeFix({
  errorCodes: errorCodes55,
  getCodeActions(context) {
    const info = getInfo18(context.sourceFile, context.program, context.span.start, context.preferences);
    if (!info) {
      return void 0;
    }
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange35(t, context.sourceFile, info));
    return [createCodeFixAction(fixId43, changes, Diagnostics.Convert_require_to_import, fixId43, Diagnostics.Convert_all_require_to_import)];
  },
  fixIds: [fixId43],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => {
    const info = getInfo18(diag2.file, context.program, diag2.start, context.preferences);
    if (info) {
      doChange35(changes, context.sourceFile, info);
    }
  })
});
function doChange35(changes, sourceFile, info) {
  const { allowSyntheticDefaults, defaultImportName, namedImports, statement, moduleSpecifier } = info;
  changes.replaceNode(
    sourceFile,
    statement,
    defaultImportName && !allowSyntheticDefaults ? factory.createImportEqualsDeclaration(
      /*modifiers*/
      void 0,
      /*isTypeOnly*/
      false,
      defaultImportName,
      factory.createExternalModuleReference(moduleSpecifier)
    ) : factory.createImportDeclaration(
      /*modifiers*/
      void 0,
      factory.createImportClause(
        /*isTypeOnly*/
        false,
        defaultImportName,
        namedImports
      ),
      moduleSpecifier,
      /*attributes*/
      void 0
    )
  );
}
function getInfo18(sourceFile, program, pos, preferences) {
  const { parent: parent2 } = getTokenAtPosition(sourceFile, pos);
  if (!isRequireCall(
    parent2,
    /*requireStringLiteralLikeArgument*/
    true
  )) {
    Debug.failBadSyntaxKind(parent2);
  }
  const decl = cast(parent2.parent, isVariableDeclaration);
  const quotePreference = getQuotePreference(sourceFile, preferences);
  const defaultImportName = tryCast(decl.name, isIdentifier);
  const namedImports = isObjectBindingPattern(decl.name) ? tryCreateNamedImportsFromObjectBindingPattern(decl.name) : void 0;
  if (defaultImportName || namedImports) {
    const moduleSpecifier = first(parent2.arguments);
    return {
      allowSyntheticDefaults: getAllowSyntheticDefaultImports(program.getCompilerOptions()),
      defaultImportName,
      namedImports,
      statement: cast(decl.parent.parent, isVariableStatement),
      moduleSpecifier: isNoSubstitutionTemplateLiteral(moduleSpecifier) ? factory.createStringLiteral(moduleSpecifier.text, quotePreference === 0 /* Single */) : moduleSpecifier
    };
  }
}
function tryCreateNamedImportsFromObjectBindingPattern(node) {
  const importSpecifiers = [];
  for (const element of node.elements) {
    if (!isIdentifier(element.name) || element.initializer) {
      return void 0;
    }
    importSpecifiers.push(factory.createImportSpecifier(
      /*isTypeOnly*/
      false,
      tryCast(element.propertyName, isIdentifier),
      element.name
    ));
  }
  if (importSpecifiers.length) {
    return factory.createNamedImports(importSpecifiers);
  }
}

// src/services/codefixes/useDefaultImport.ts
var fixId44 = "useDefaultImport";
var errorCodes56 = [Diagnostics.Import_may_be_converted_to_a_default_import.code];
registerCodeFix({
  errorCodes: errorCodes56,
  getCodeActions(context) {
    const { sourceFile, span: { start } } = context;
    const info = getInfo19(sourceFile, start);
    if (!info) return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange36(t, sourceFile, info, context.preferences));
    return [createCodeFixAction(fixId44, changes, Diagnostics.Convert_to_default_import, fixId44, Diagnostics.Convert_all_to_default_imports)];
  },
  fixIds: [fixId44],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes56, (changes, diag2) => {
    const info = getInfo19(diag2.file, diag2.start);
    if (info) doChange36(changes, diag2.file, info, context.preferences);
  })
});
function getInfo19(sourceFile, pos) {
  const name = getTokenAtPosition(sourceFile, pos);
  if (!isIdentifier(name)) return void 0;
  const { parent: parent2 } = name;
  if (isImportEqualsDeclaration(parent2) && isExternalModuleReference(parent2.moduleReference)) {
    return { importNode: parent2, name, moduleSpecifier: parent2.moduleReference.expression };
  } else if (isNamespaceImport(parent2) && isImportDeclaration(parent2.parent.parent)) {
    const importNode = parent2.parent.parent;
    return { importNode, name, moduleSpecifier: importNode.moduleSpecifier };
  }
}
function doChange36(changes, sourceFile, info, preferences) {
  changes.replaceNode(sourceFile, info.importNode, makeImport(
    info.name,
    /*namedImports*/
    void 0,
    info.moduleSpecifier,
    getQuotePreference(sourceFile, preferences)
  ));
}

// src/services/codefixes/useBigintLiteral.ts
var fixId45 = "useBigintLiteral";
var errorCodes57 = [
  Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code
];
registerCodeFix({
  errorCodes: errorCodes57,
  getCodeActions: function getCodeActionsToUseBigintLiteral(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange10(t, context.sourceFile, context.span));
    if (changes.length > 0) {
      return [createCodeFixAction(fixId45, changes, Diagnostics.Convert_to_a_bigint_numeric_literal, fixId45, Diagnostics.Convert_all_to_bigint_numeric_literals)];
    }
  },
  fixIds: [fixId45],
  getAllCodeActions: (context) => {
    return codeFixAll(context, errorCodes57, (changes, diag2) => makeChange10(changes, diag2.file, diag2));
  }
});
function makeChange10(changeTracker, sourceFile, span) {
  const numericLiteral = tryCast(getTokenAtPosition(sourceFile, span.start), isNumericLiteral);
  if (!numericLiteral) {
    return;
  }
  const newText = numericLiteral.getText(sourceFile) + "n";
  changeTracker.replaceNode(sourceFile, numericLiteral, factory.createBigIntLiteral(newText));
}

// src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts
var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof";
var fixId46 = fixIdAddMissingTypeof;
var errorCodes58 = [Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code];
registerCodeFix({
  errorCodes: errorCodes58,
  getCodeActions: function getCodeActionsToAddMissingTypeof(context) {
    const { sourceFile, span } = context;
    const importType = getImportTypeNode(sourceFile, span.start);
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange37(t, sourceFile, importType));
    return [createCodeFixAction(fixId46, changes, Diagnostics.Add_missing_typeof, fixId46, Diagnostics.Add_missing_typeof)];
  },
  fixIds: [fixId46],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes58, (changes, diag2) => doChange37(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start)))
});
function getImportTypeNode(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  Debug.assert(token.kind === 102 /* ImportKeyword */, "This token should be an ImportKeyword");
  Debug.assert(token.parent.kind === 205 /* ImportType */, "Token parent should be an ImportType");
  return token.parent;
}
function doChange37(changes, sourceFile, importType) {
  const newTypeNode = factory.updateImportTypeNode(
    importType,
    importType.argument,
    importType.attributes,
    importType.qualifier,
    importType.typeArguments,
    /*isTypeOf*/
    true
  );
  changes.replaceNode(sourceFile, importType, newTypeNode);
}

// src/services/codefixes/wrapJsxInFragment.ts
var fixID2 = "wrapJsxInFragment";
var errorCodes59 = [Diagnostics.JSX_expressions_must_have_one_parent_element.code];
registerCodeFix({
  errorCodes: errorCodes59,
  getCodeActions: function getCodeActionsToWrapJsxInFragment(context) {
    const { sourceFile, span } = context;
    const node = findNodeToFix(sourceFile, span.start);
    if (!node) return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange38(t, sourceFile, node));
    return [createCodeFixAction(fixID2, changes, Diagnostics.Wrap_in_JSX_fragment, fixID2, Diagnostics.Wrap_all_unparented_JSX_in_JSX_fragment)];
  },
  fixIds: [fixID2],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes59, (changes, diag2) => {
    const node = findNodeToFix(context.sourceFile, diag2.start);
    if (!node) return void 0;
    doChange38(changes, context.sourceFile, node);
  })
});
function findNodeToFix(sourceFile, pos) {
  const lessThanToken = getTokenAtPosition(sourceFile, pos);
  const firstJsxElementOrOpenElement = lessThanToken.parent;
  let binaryExpr = firstJsxElementOrOpenElement.parent;
  if (!isBinaryExpression(binaryExpr)) {
    binaryExpr = binaryExpr.parent;
    if (!isBinaryExpression(binaryExpr)) return void 0;
  }
  if (!nodeIsMissing(binaryExpr.operatorToken)) return void 0;
  return binaryExpr;
}
function doChange38(changeTracker, sf, node) {
  const jsx = flattenInvalidBinaryExpr(node);
  if (jsx) changeTracker.replaceNode(sf, node, factory.createJsxFragment(factory.createJsxOpeningFragment(), jsx, factory.createJsxJsxClosingFragment()));
}
function flattenInvalidBinaryExpr(node) {
  const children = [];
  let current = node;
  while (true) {
    if (isBinaryExpression(current) && nodeIsMissing(current.operatorToken) && current.operatorToken.kind === 28 /* CommaToken */) {
      children.push(current.left);
      if (isJsxChild(current.right)) {
        children.push(current.right);
        return children;
      } else if (isBinaryExpression(current.right)) {
        current = current.right;
        continue;
      } else return void 0;
    } else return void 0;
  }
}

// src/services/codefixes/wrapDecoratorInParentheses.ts
var fixId47 = "wrapDecoratorInParentheses";
var errorCodes60 = [Diagnostics.Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator.code];
registerCodeFix({
  errorCodes: errorCodes60,
  getCodeActions: function getCodeActionsToWrapDecoratorExpressionInParentheses(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange11(t, context.sourceFile, context.span.start));
    return [createCodeFixAction(fixId47, changes, Diagnostics.Wrap_in_parentheses, fixId47, Diagnostics.Wrap_all_invalid_decorator_expressions_in_parentheses)];
  },
  fixIds: [fixId47],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes60, (changes, diag2) => makeChange11(changes, diag2.file, diag2.start))
});
function makeChange11(changeTracker, sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  const decorator = findAncestor(token, isDecorator);
  Debug.assert(!!decorator, "Expected position to be owned by a decorator.");
  const replacement = factory.createParenthesizedExpression(decorator.expression);
  changeTracker.replaceNode(sourceFile, decorator.expression, replacement);
}

// src/services/codefixes/convertToMappedObjectType.ts
var fixId48 = "fixConvertToMappedObjectType";
var errorCodes61 = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead.code];
registerCodeFix({
  errorCodes: errorCodes61,
  getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) {
    const { sourceFile, span } = context;
    const info = getInfo20(sourceFile, span.start);
    if (!info) return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange39(t, sourceFile, info));
    const name = idText(info.container.name);
    return [createCodeFixAction(fixId48, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId48, [Diagnostics.Convert_0_to_mapped_object_type, name])];
  },
  fixIds: [fixId48],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes61, (changes, diag2) => {
    const info = getInfo20(diag2.file, diag2.start);
    if (info) doChange39(changes, diag2.file, info);
  })
});
function getInfo20(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  const indexSignature = tryCast(token.parent.parent, isIndexSignatureDeclaration);
  if (!indexSignature) return void 0;
  const container = isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : tryCast(indexSignature.parent.parent, isTypeAliasDeclaration);
  if (!container) return void 0;
  return { indexSignature, container };
}
function createTypeAliasFromInterface(declaration, type) {
  return factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type);
}
function doChange39(changes, sourceFile, { indexSignature, container }) {
  const members = isInterfaceDeclaration(container) ? container.members : container.type.members;
  const otherMembers = members.filter((member) => !isIndexSignatureDeclaration(member));
  const parameter = first(indexSignature.parameters);
  const mappedTypeParameter = factory.createTypeParameterDeclaration(
    /*modifiers*/
    void 0,
    cast(parameter.name, isIdentifier),
    parameter.type
  );
  const mappedIntersectionType = factory.createMappedTypeNode(
    hasEffectiveReadonlyModifier(indexSignature) ? factory.createModifier(148 /* ReadonlyKeyword */) : void 0,
    mappedTypeParameter,
    /*nameType*/
    void 0,
    indexSignature.questionToken,
    indexSignature.type,
    /*members*/
    void 0
  );
  const intersectionType = factory.createIntersectionTypeNode([
    ...getAllSuperTypeNodes(container),
    mappedIntersectionType,
    ...otherMembers.length ? [factory.createTypeLiteralNode(otherMembers)] : emptyArray
  ]);
  changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType));
}

// src/services/codefixes/removeAccidentalCallParentheses.ts
var fixId49 = "removeAccidentalCallParentheses";
var errorCodes62 = [
  Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without.code
];
registerCodeFix({
  errorCodes: errorCodes62,
  getCodeActions(context) {
    const callExpression = findAncestor(getTokenAtPosition(context.sourceFile, context.span.start), isCallExpression);
    if (!callExpression) {
      return void 0;
    }
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => {
      t.deleteRange(context.sourceFile, { pos: callExpression.expression.end, end: callExpression.end });
    });
    return [createCodeFixActionWithoutFixAll(fixId49, changes, Diagnostics.Remove_parentheses)];
  },
  fixIds: [fixId49]
});

// src/services/codefixes/removeUnnecessaryAwait.ts
var fixId50 = "removeUnnecessaryAwait";
var errorCodes63 = [
  Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code
];
registerCodeFix({
  errorCodes: errorCodes63,
  getCodeActions: function getCodeActionsToRemoveUnnecessaryAwait(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange12(t, context.sourceFile, context.span));
    if (changes.length > 0) {
      return [createCodeFixAction(fixId50, changes, Diagnostics.Remove_unnecessary_await, fixId50, Diagnostics.Remove_all_unnecessary_uses_of_await)];
    }
  },
  fixIds: [fixId50],
  getAllCodeActions: (context) => {
    return codeFixAll(context, errorCodes63, (changes, diag2) => makeChange12(changes, diag2.file, diag2));
  }
});
function makeChange12(changeTracker, sourceFile, span) {
  const awaitKeyword = tryCast(getTokenAtPosition(sourceFile, span.start), (node) => node.kind === 135 /* AwaitKeyword */);
  const awaitExpression = awaitKeyword && tryCast(awaitKeyword.parent, isAwaitExpression);
  if (!awaitExpression) {
    return;
  }
  let expressionToReplace = awaitExpression;
  const hasSurroundingParens = isParenthesizedExpression(awaitExpression.parent);
  if (hasSurroundingParens) {
    const leftMostExpression = getLeftmostExpression(
      awaitExpression.expression,
      /*stopAtCallExpressions*/
      false
    );
    if (isIdentifier(leftMostExpression)) {
      const precedingToken = findPrecedingToken(awaitExpression.parent.pos, sourceFile);
      if (precedingToken && precedingToken.kind !== 105 /* NewKeyword */) {
        expressionToReplace = awaitExpression.parent;
      }
    }
  }
  changeTracker.replaceNode(sourceFile, expressionToReplace, awaitExpression.expression);
}

// src/services/codefixes/splitTypeOnlyImport.ts
var errorCodes64 = [Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code];
var fixId51 = "splitTypeOnlyImport";
registerCodeFix({
  errorCodes: errorCodes64,
  fixIds: [fixId51],
  getCodeActions: function getCodeActionsToSplitTypeOnlyImport(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => {
      return splitTypeOnlyImport(t, getImportDeclaration2(context.sourceFile, context.span), context);
    });
    if (changes.length) {
      return [createCodeFixAction(fixId51, changes, Diagnostics.Split_into_two_separate_import_declarations, fixId51, Diagnostics.Split_all_invalid_type_only_imports)];
    }
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes64, (changes, error2) => {
    splitTypeOnlyImport(changes, getImportDeclaration2(context.sourceFile, error2), context);
  })
});
function getImportDeclaration2(sourceFile, span) {
  return findAncestor(getTokenAtPosition(sourceFile, span.start), isImportDeclaration);
}
function splitTypeOnlyImport(changes, importDeclaration, context) {
  if (!importDeclaration) {
    return;
  }
  const importClause = Debug.checkDefined(importDeclaration.importClause);
  changes.replaceNode(
    context.sourceFile,
    importDeclaration,
    factory.updateImportDeclaration(
      importDeclaration,
      importDeclaration.modifiers,
      factory.updateImportClause(
        importClause,
        importClause.isTypeOnly,
        importClause.name,
        /*namedBindings*/
        void 0
      ),
      importDeclaration.moduleSpecifier,
      importDeclaration.attributes
    )
  );
  changes.insertNodeAfter(
    context.sourceFile,
    importDeclaration,
    factory.createImportDeclaration(
      /*modifiers*/
      void 0,
      factory.updateImportClause(
        importClause,
        importClause.isTypeOnly,
        /*name*/
        void 0,
        importClause.namedBindings
      ),
      importDeclaration.moduleSpecifier,
      importDeclaration.attributes
    )
  );
}

// src/services/codefixes/convertConstToLet.ts
var fixId52 = "fixConvertConstToLet";
var errorCodes65 = [Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code];
registerCodeFix({
  errorCodes: errorCodes65,
  getCodeActions: function getCodeActionsToConvertConstToLet(context) {
    const { sourceFile, span, program } = context;
    const info = getInfo21(sourceFile, span.start, program);
    if (info === void 0) return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange40(t, sourceFile, info.token));
    return [createCodeFixActionMaybeFixAll(fixId52, changes, Diagnostics.Convert_const_to_let, fixId52, Diagnostics.Convert_all_const_to_let)];
  },
  getAllCodeActions: (context) => {
    const { program } = context;
    const seen = /* @__PURE__ */ new Set();
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      eachDiagnostic(context, errorCodes65, (diag2) => {
        const info = getInfo21(diag2.file, diag2.start, program);
        if (info) {
          if (addToSeen(seen, getSymbolId(info.symbol))) {
            return doChange40(changes, diag2.file, info.token);
          }
        }
        return void 0;
      });
    }));
  },
  fixIds: [fixId52]
});
function getInfo21(sourceFile, pos, program) {
  var _a;
  const checker = program.getTypeChecker();
  const symbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, pos));
  if (symbol === void 0) return;
  const declaration = tryCast((_a = symbol == null ? void 0 : symbol.valueDeclaration) == null ? void 0 : _a.parent, isVariableDeclarationList);
  if (declaration === void 0) return;
  const constToken = findChildOfKind(declaration, 87 /* ConstKeyword */, sourceFile);
  if (constToken === void 0) return;
  return { symbol, token: constToken };
}
function doChange40(changes, sourceFile, token) {
  changes.replaceNode(sourceFile, token, factory.createToken(121 /* LetKeyword */));
}

// src/services/codefixes/fixExpectedComma.ts
var fixId53 = "fixExpectedComma";
var expectedErrorCode = Diagnostics._0_expected.code;
var errorCodes66 = [expectedErrorCode];
registerCodeFix({
  errorCodes: errorCodes66,
  getCodeActions(context) {
    const { sourceFile } = context;
    const info = getInfo22(sourceFile, context.span.start, context.errorCode);
    if (!info) return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange41(t, sourceFile, info));
    return [createCodeFixAction(
      fixId53,
      changes,
      [Diagnostics.Change_0_to_1, ";", ","],
      fixId53,
      [Diagnostics.Change_0_to_1, ";", ","]
    )];
  },
  fixIds: [fixId53],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes66, (changes, diag2) => {
    const info = getInfo22(diag2.file, diag2.start, diag2.code);
    if (info) doChange41(changes, context.sourceFile, info);
  })
});
function getInfo22(sourceFile, pos, _) {
  const node = getTokenAtPosition(sourceFile, pos);
  return node.kind === 27 /* SemicolonToken */ && node.parent && (isObjectLiteralExpression(node.parent) || isArrayLiteralExpression(node.parent)) ? { node } : void 0;
}
function doChange41(changes, sourceFile, { node }) {
  const newNode = factory.createToken(28 /* CommaToken */);
  changes.replaceNode(sourceFile, node, newNode);
}

// src/services/codefixes/fixAddVoidToPromise.ts
var fixName7 = "addVoidToPromise";
var fixId54 = "addVoidToPromise";
var errorCodes67 = [
  Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments.code,
  Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise.code
];
registerCodeFix({
  errorCodes: errorCodes67,
  fixIds: [fixId54],
  getCodeActions(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange13(t, context.sourceFile, context.span, context.program));
    if (changes.length > 0) {
      return [createCodeFixAction(fixName7, changes, Diagnostics.Add_void_to_Promise_resolved_without_a_value, fixId54, Diagnostics.Add_void_to_all_Promises_resolved_without_a_value)];
    }
  },
  getAllCodeActions(context) {
    return codeFixAll(context, errorCodes67, (changes, diag2) => makeChange13(changes, diag2.file, diag2, context.program, /* @__PURE__ */ new Set()));
  }
});
function makeChange13(changes, sourceFile, span, program, seen) {
  const node = getTokenAtPosition(sourceFile, span.start);
  if (!isIdentifier(node) || !isCallExpression(node.parent) || node.parent.expression !== node || node.parent.arguments.length !== 0) return;
  const checker = program.getTypeChecker();
  const symbol = checker.getSymbolAtLocation(node);
  const decl = symbol == null ? void 0 : symbol.valueDeclaration;
  if (!decl || !isParameter(decl) || !isNewExpression(decl.parent.parent)) return;
  if (seen == null ? void 0 : seen.has(decl)) return;
  seen == null ? void 0 : seen.add(decl);
  const typeArguments = getEffectiveTypeArguments(decl.parent.parent);
  if (some(typeArguments)) {
    const typeArgument = typeArguments[0];
    const needsParens = !isUnionTypeNode(typeArgument) && !isParenthesizedTypeNode(typeArgument) && isParenthesizedTypeNode(factory.createUnionTypeNode([typeArgument, factory.createKeywordTypeNode(116 /* VoidKeyword */)]).types[0]);
    if (needsParens) {
      changes.insertText(sourceFile, typeArgument.pos, "(");
    }
    changes.insertText(sourceFile, typeArgument.end, needsParens ? ") | void" : " | void");
  } else {
    const signature = checker.getResolvedSignature(node.parent);
    const parameter = signature == null ? void 0 : signature.parameters[0];
    const parameterType = parameter && checker.getTypeOfSymbolAtLocation(parameter, decl.parent.parent);
    if (isInJSFile(decl)) {
      if (!parameterType || parameterType.flags & 3 /* AnyOrUnknown */) {
        changes.insertText(sourceFile, decl.parent.parent.end, `)`);
        changes.insertText(sourceFile, skipTrivia(sourceFile.text, decl.parent.parent.pos), `/** @type {Promise<void>} */(`);
      }
    } else {
      if (!parameterType || parameterType.flags & 2 /* Unknown */) {
        changes.insertText(sourceFile, decl.parent.parent.expression.end, "<void>");
      }
    }
  }
}
function getEffectiveTypeArguments(node) {
  var _a;
  if (isInJSFile(node)) {
    if (isParenthesizedExpression(node.parent)) {
      const jsDocType = (_a = getJSDocTypeTag(node.parent)) == null ? void 0 : _a.typeExpression.type;
      if (jsDocType && isTypeReferenceNode(jsDocType) && isIdentifier(jsDocType.typeName) && idText(jsDocType.typeName) === "Promise") {
        return jsDocType.typeArguments;
      }
    }
  } else {
    return node.typeArguments;
  }
}

// src/services/_namespaces/ts.Completions.ts
var ts_Completions_exports = {};
__export(ts_Completions_exports, {
  CompletionKind: () => CompletionKind,
  CompletionSource: () => CompletionSource,
  SortText: () => SortText,
  StringCompletions: () => ts_Completions_StringCompletions_exports,
  SymbolOriginInfoKind: () => SymbolOriginInfoKind,
  createCompletionDetails: () => createCompletionDetails,
  createCompletionDetailsForSymbol: () => createCompletionDetailsForSymbol,
  getCompletionEntriesFromSymbols: () => getCompletionEntriesFromSymbols,
  getCompletionEntryDetails: () => getCompletionEntryDetails,
  getCompletionEntrySymbol: () => getCompletionEntrySymbol,
  getCompletionsAtPosition: () => getCompletionsAtPosition,
  getDefaultCommitCharacters: () => getDefaultCommitCharacters,
  getPropertiesForObjectExpression: () => getPropertiesForObjectExpression,
  moduleSpecifierResolutionCacheAttemptLimit: () => moduleSpecifierResolutionCacheAttemptLimit,
  moduleSpecifierResolutionLimit: () => moduleSpecifierResolutionLimit
});

// src/services/completions.ts
var moduleSpecifierResolutionLimit = 100;
var moduleSpecifierResolutionCacheAttemptLimit = 1e3;
var SortText = {
  // Presets
  LocalDeclarationPriority: "10",
  LocationPriority: "11",
  OptionalMember: "12",
  MemberDeclaredBySpreadAssignment: "13",
  SuggestedClassMembers: "14",
  GlobalsOrKeywords: "15",
  AutoImportSuggestions: "16",
  ClassMemberSnippets: "17",
  JavascriptIdentifiers: "18",
  // Transformations
  Deprecated(sortText) {
    return "z" + sortText;
  },
  ObjectLiteralProperty(presetSortText, symbolDisplayName) {
    return `${presetSortText}\0${symbolDisplayName}\0`;
  },
  SortBelow(sortText) {
    return sortText + "1";
  }
};
var allCommitCharacters = [".", ",", ";"];
var noCommaCommitCharacters = [".", ";"];
var CompletionSource = /* @__PURE__ */ ((CompletionSource2) => {
  CompletionSource2["ThisProperty"] = "ThisProperty/";
  CompletionSource2["ClassMemberSnippet"] = "ClassMemberSnippet/";
  CompletionSource2["TypeOnlyAlias"] = "TypeOnlyAlias/";
  CompletionSource2["ObjectLiteralMethodSnippet"] = "ObjectLiteralMethodSnippet/";
  CompletionSource2["SwitchCases"] = "SwitchCases/";
  CompletionSource2["ObjectLiteralMemberWithComma"] = "ObjectLiteralMemberWithComma/";
  return CompletionSource2;
})(CompletionSource || {});
var SymbolOriginInfoKind = /* @__PURE__ */ ((SymbolOriginInfoKind2) => {
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["ThisType"] = 1] = "ThisType";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMember"] = 2] = "SymbolMember";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["Export"] = 4] = "Export";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["Promise"] = 8] = "Promise";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["Nullable"] = 16] = "Nullable";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["ResolvedExport"] = 32] = "ResolvedExport";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["TypeOnlyAlias"] = 64] = "TypeOnlyAlias";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["ObjectLiteralMethod"] = 128] = "ObjectLiteralMethod";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["Ignore"] = 256] = "Ignore";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["ComputedPropertyName"] = 512] = "ComputedPropertyName";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMemberNoExport"] = 2 /* SymbolMember */] = "SymbolMemberNoExport";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMemberExport"] = 6] = "SymbolMemberExport";
  return SymbolOriginInfoKind2;
})(SymbolOriginInfoKind || {});
function originIsThisType(origin) {
  return !!(origin.kind & 1 /* ThisType */);
}
function originIsSymbolMember(origin) {
  return !!(origin.kind & 2 /* SymbolMember */);
}
function originIsExport(origin) {
  return !!(origin && origin.kind & 4 /* Export */);
}
function originIsResolvedExport(origin) {
  return !!(origin && origin.kind === 32 /* ResolvedExport */);
}
function originIncludesSymbolName(origin) {
  return originIsExport(origin) || originIsResolvedExport(origin) || originIsComputedPropertyName(origin);
}
function originIsPackageJsonImport(origin) {
  return (originIsExport(origin) || originIsResolvedExport(origin)) && !!origin.isFromPackageJson;
}
function originIsPromise(origin) {
  return !!(origin.kind & 8 /* Promise */);
}
function originIsNullableMember(origin) {
  return !!(origin.kind & 16 /* Nullable */);
}
function originIsTypeOnlyAlias(origin) {
  return !!(origin && origin.kind & 64 /* TypeOnlyAlias */);
}
function originIsObjectLiteralMethod(origin) {
  return !!(origin && origin.kind & 128 /* ObjectLiteralMethod */);
}
function originIsIgnore(origin) {
  return !!(origin && origin.kind & 256 /* Ignore */);
}
function originIsComputedPropertyName(origin) {
  return !!(origin && origin.kind & 512 /* ComputedPropertyName */);
}
function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) {
  var _a, _b, _c, _d;
  const start = timestamp();
  const needsFullResolution = isForImportStatementCompletion || getResolvePackageJsonExports(program.getCompilerOptions()) || ((_a = preferences.autoImportSpecifierExcludeRegexes) == null ? void 0 : _a.length);
  let skippedAny = false;
  let ambientCount = 0;
  let resolvedCount = 0;
  let resolvedFromCacheCount = 0;
  let cacheAttemptCount = 0;
  const result = cb({
    tryResolve,
    skippedAny: () => skippedAny,
    resolvedAny: () => resolvedCount > 0,
    resolvedBeyondLimit: () => resolvedCount > moduleSpecifierResolutionLimit
  });
  const hitRateMessage = cacheAttemptCount ? ` (${(resolvedFromCacheCount / cacheAttemptCount * 100).toFixed(1)}% hit rate)` : "";
  (_b = host.log) == null ? void 0 : _b.call(host, `${logPrefix}: resolved ${resolvedCount} module specifiers, plus ${ambientCount} ambient and ${resolvedFromCacheCount} from cache${hitRateMessage}`);
  (_c = host.log) == null ? void 0 : _c.call(host, `${logPrefix}: response is ${skippedAny ? "incomplete" : "complete"}`);
  (_d = host.log) == null ? void 0 : _d.call(host, `${logPrefix}: ${timestamp() - start}`);
  return result;
  function tryResolve(exportInfo, isFromAmbientModule) {
    if (isFromAmbientModule) {
      const result3 = resolver.getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite);
      if (result3) {
        ambientCount++;
      }
      return result3 || "failed";
    }
    const shouldResolveModuleSpecifier = needsFullResolution || preferences.allowIncompleteCompletions && resolvedCount < moduleSpecifierResolutionLimit;
    const shouldGetModuleSpecifierFromCache = !shouldResolveModuleSpecifier && preferences.allowIncompleteCompletions && cacheAttemptCount < moduleSpecifierResolutionCacheAttemptLimit;
    const result2 = shouldResolveModuleSpecifier || shouldGetModuleSpecifierFromCache ? resolver.getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite, shouldGetModuleSpecifierFromCache) : void 0;
    if (!shouldResolveModuleSpecifier && !shouldGetModuleSpecifierFromCache || shouldGetModuleSpecifierFromCache && !result2) {
      skippedAny = true;
    }
    resolvedCount += (result2 == null ? void 0 : result2.computedWithoutCacheCount) || 0;
    resolvedFromCacheCount += exportInfo.length - ((result2 == null ? void 0 : result2.computedWithoutCacheCount) || 0);
    if (shouldGetModuleSpecifierFromCache) {
      cacheAttemptCount++;
    }
    return result2 || (needsFullResolution ? "failed" : "skipped");
  }
}
function getDefaultCommitCharacters(isNewIdentifierLocation) {
  if (isNewIdentifierLocation) {
    return [];
  }
  return allCommitCharacters;
}
function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter, completionKind, cancellationToken, formatContext, includeSymbol = false) {
  var _a;
  const { previousToken } = getRelevantTokens(position, sourceFile);
  if (triggerCharacter && !isInString(sourceFile, position, previousToken) && !isValidTrigger(sourceFile, triggerCharacter, previousToken, position)) {
    return void 0;
  }
  if (triggerCharacter === " ") {
    if (preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) {
      return {
        isGlobalCompletion: true,
        isMemberCompletion: false,
        isNewIdentifierLocation: true,
        isIncomplete: true,
        entries: [],
        defaultCommitCharacters: getDefaultCommitCharacters(
          /*isNewIdentifierLocation*/
          true
        )
      };
    }
    return void 0;
  }
  const compilerOptions = program.getCompilerOptions();
  const checker = program.getTypeChecker();
  const incompleteCompletionsCache = preferences.allowIncompleteCompletions ? (_a = host.getIncompleteCompletionsCache) == null ? void 0 : _a.call(host) : void 0;
  if (incompleteCompletionsCache && completionKind === 3 /* TriggerForIncompleteCompletions */ && previousToken && isIdentifier(previousToken)) {
    const incompleteContinuation = continuePreviousIncompleteResponse(incompleteCompletionsCache, sourceFile, previousToken, program, host, preferences, cancellationToken, position);
    if (incompleteContinuation) {
      return incompleteContinuation;
    }
  } else {
    incompleteCompletionsCache == null ? void 0 : incompleteCompletionsCache.clear();
  }
  const stringCompletions = ts_Completions_StringCompletions_exports.getStringLiteralCompletions(sourceFile, position, previousToken, compilerOptions, host, program, log, preferences, includeSymbol);
  if (stringCompletions) {
    return stringCompletions;
  }
  if (previousToken && isBreakOrContinueStatement(previousToken.parent) && (previousToken.kind === 83 /* BreakKeyword */ || previousToken.kind === 88 /* ContinueKeyword */ || previousToken.kind === 80 /* Identifier */)) {
    return getLabelCompletionAtPosition(previousToken.parent);
  }
  const completionData = getCompletionData(
    program,
    log,
    sourceFile,
    compilerOptions,
    position,
    preferences,
    /*detailsEntryId*/
    void 0,
    host,
    formatContext,
    cancellationToken
  );
  if (!completionData) {
    return void 0;
  }
  switch (completionData.kind) {
    case 0 /* Data */:
      const response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position, includeSymbol);
      if (response == null ? void 0 : response.isIncomplete) {
        incompleteCompletionsCache == null ? void 0 : incompleteCompletionsCache.set(response);
      }
      return response;
    case 1 /* JsDocTagName */:
      return jsdocCompletionInfo([
        ...ts_JsDoc_exports.getJSDocTagNameCompletions(),
        ...getJSDocParameterCompletions(
          sourceFile,
          position,
          checker,
          compilerOptions,
          preferences,
          /*tagNameOnly*/
          true
        )
      ]);
    case 2 /* JsDocTag */:
      return jsdocCompletionInfo([
        ...ts_JsDoc_exports.getJSDocTagCompletions(),
        ...getJSDocParameterCompletions(
          sourceFile,
          position,
          checker,
          compilerOptions,
          preferences,
          /*tagNameOnly*/
          false
        )
      ]);
    case 3 /* JsDocParameterName */:
      return jsdocCompletionInfo(ts_JsDoc_exports.getJSDocParameterNameCompletions(completionData.tag));
    case 4 /* Keywords */:
      return specificKeywordCompletionInfo(completionData.keywordCompletions, completionData.isNewIdentifierLocation);
    default:
      return Debug.assertNever(completionData);
  }
}
function compareCompletionEntries(entryInArray, entryToInsert) {
  var _a, _b;
  let result = compareStringsCaseSensitiveUI(entryInArray.sortText, entryToInsert.sortText);
  if (result === 0 /* EqualTo */) {
    result = compareStringsCaseSensitiveUI(entryInArray.name, entryToInsert.name);
  }
  if (result === 0 /* EqualTo */ && ((_a = entryInArray.data) == null ? void 0 : _a.moduleSpecifier) && ((_b = entryToInsert.data) == null ? void 0 : _b.moduleSpecifier)) {
    result = compareNumberOfDirectorySeparators(
      entryInArray.data.moduleSpecifier,
      entryToInsert.data.moduleSpecifier
    );
  }
  if (result === 0 /* EqualTo */) {
    return -1 /* LessThan */;
  }
  return result;
}
function completionEntryDataIsResolved(data) {
  return !!(data == null ? void 0 : data.moduleSpecifier);
}
function continuePreviousIncompleteResponse(cache, file, location, program, host, preferences, cancellationToken, position) {
  const previousResponse = cache.get();
  if (!previousResponse) return void 0;
  const touchNode = getTouchingPropertyName(file, position);
  const lowerCaseTokenText = location.text.toLowerCase();
  const exportMap = getExportInfoMap(file, host, program, preferences, cancellationToken);
  const newEntries = resolvingModuleSpecifiers(
    "continuePreviousIncompleteResponse",
    host,
    ts_codefix_exports.createImportSpecifierResolver(file, program, host, preferences),
    program,
    location.getStart(),
    preferences,
    /*isForImportStatementCompletion*/
    false,
    isValidTypeOnlyAliasUseSite(location),
    (context) => {
      const entries = mapDefined(previousResponse.entries, (entry) => {
        var _a;
        if (!entry.hasAction || !entry.source || !entry.data || completionEntryDataIsResolved(entry.data)) {
          return entry;
        }
        if (!charactersFuzzyMatchInString(entry.name, lowerCaseTokenText)) {
          return void 0;
        }
        const { origin } = Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host));
        const info = exportMap.get(file.path, entry.data.exportMapKey);
        const result = info && context.tryResolve(info, !isExternalModuleNameRelative(stripQuotes(origin.moduleSymbol.name)));
        if (result === "skipped") return entry;
        if (!result || result === "failed") {
          (_a = host.log) == null ? void 0 : _a.call(host, `Unexpected failure resolving auto import for '${entry.name}' from '${entry.source}'`);
          return void 0;
        }
        const newOrigin = {
          ...origin,
          kind: 32 /* ResolvedExport */,
          moduleSpecifier: result.moduleSpecifier
        };
        entry.data = originToCompletionEntryData(newOrigin);
        entry.source = getSourceFromOrigin(newOrigin);
        entry.sourceDisplay = [textPart(newOrigin.moduleSpecifier)];
        return entry;
      });
      if (!context.skippedAny()) {
        previousResponse.isIncomplete = void 0;
      }
      return entries;
    }
  );
  previousResponse.entries = newEntries;
  previousResponse.flags = (previousResponse.flags || 0) | 4 /* IsContinuation */;
  previousResponse.optionalReplacementSpan = getOptionalReplacementSpan(touchNode);
  return previousResponse;
}
function jsdocCompletionInfo(entries) {
  return {
    isGlobalCompletion: false,
    isMemberCompletion: false,
    isNewIdentifierLocation: false,
    entries,
    defaultCommitCharacters: getDefaultCommitCharacters(
      /*isNewIdentifierLocation*/
      false
    )
  };
}
function getJSDocParameterCompletions(sourceFile, position, checker, options, preferences, tagNameOnly) {
  const currentToken = getTokenAtPosition(sourceFile, position);
  if (!isJSDocTag(currentToken) && !isJSDoc(currentToken)) {
    return [];
  }
  const jsDoc = isJSDoc(currentToken) ? currentToken : currentToken.parent;
  if (!isJSDoc(jsDoc)) {
    return [];
  }
  const func = jsDoc.parent;
  if (!isFunctionLike(func)) {
    return [];
  }
  const isJs = isSourceFileJS(sourceFile);
  const isSnippet = preferences.includeCompletionsWithSnippetText || void 0;
  const paramTagCount = countWhere(jsDoc.tags, (tag) => isJSDocParameterTag(tag) && tag.getEnd() <= position);
  return mapDefined(func.parameters, (param) => {
    if (getJSDocParameterTags(param).length) {
      return void 0;
    }
    if (isIdentifier(param.name)) {
      const tabstopCounter = { tabstop: 1 };
      const paramName = param.name.text;
      let displayText = getJSDocParamAnnotation(
        paramName,
        param.initializer,
        param.dotDotDotToken,
        isJs,
        /*isObject*/
        false,
        /*isSnippet*/
        false,
        checker,
        options,
        preferences
      );
      let snippetText = isSnippet ? getJSDocParamAnnotation(
        paramName,
        param.initializer,
        param.dotDotDotToken,
        isJs,
        /*isObject*/
        false,
        /*isSnippet*/
        true,
        checker,
        options,
        preferences,
        tabstopCounter
      ) : void 0;
      if (tagNameOnly) {
        displayText = displayText.slice(1);
        if (snippetText) snippetText = snippetText.slice(1);
      }
      return {
        name: displayText,
        kind: "parameter" /* parameterElement */,
        sortText: SortText.LocationPriority,
        insertText: isSnippet ? snippetText : void 0,
        isSnippet
      };
    } else if (param.parent.parameters.indexOf(param) === paramTagCount) {
      const paramPath = `param${paramTagCount}`;
      const displayTextResult = generateJSDocParamTagsForDestructuring(
        paramPath,
        param.name,
        param.initializer,
        param.dotDotDotToken,
        isJs,
        /*isSnippet*/
        false,
        checker,
        options,
        preferences
      );
      const snippetTextResult = isSnippet ? generateJSDocParamTagsForDestructuring(
        paramPath,
        param.name,
        param.initializer,
        param.dotDotDotToken,
        isJs,
        /*isSnippet*/
        true,
        checker,
        options,
        preferences
      ) : void 0;
      let displayText = displayTextResult.join(getNewLineCharacter(options) + "* ");
      let snippetText = snippetTextResult == null ? void 0 : snippetTextResult.join(getNewLineCharacter(options) + "* ");
      if (tagNameOnly) {
        displayText = displayText.slice(1);
        if (snippetText) snippetText = snippetText.slice(1);
      }
      return {
        name: displayText,
        kind: "parameter" /* parameterElement */,
        sortText: SortText.LocationPriority,
        insertText: isSnippet ? snippetText : void 0,
        isSnippet
      };
    }
  });
}
function generateJSDocParamTagsForDestructuring(path, pattern, initializer, dotDotDotToken, isJs, isSnippet, checker, options, preferences) {
  if (!isJs) {
    return [
      getJSDocParamAnnotation(
        path,
        initializer,
        dotDotDotToken,
        isJs,
        /*isObject*/
        false,
        isSnippet,
        checker,
        options,
        preferences,
        { tabstop: 1 }
      )
    ];
  }
  return patternWorker(path, pattern, initializer, dotDotDotToken, { tabstop: 1 });
  function patternWorker(path2, pattern2, initializer2, dotDotDotToken2, counter) {
    if (isObjectBindingPattern(pattern2) && !dotDotDotToken2) {
      const oldTabstop = counter.tabstop;
      const childCounter = { tabstop: oldTabstop };
      const rootParam = getJSDocParamAnnotation(
        path2,
        initializer2,
        dotDotDotToken2,
        isJs,
        /*isObject*/
        true,
        isSnippet,
        checker,
        options,
        preferences,
        childCounter
      );
      let childTags = [];
      for (const element of pattern2.elements) {
        const elementTags = elementWorker(path2, element, childCounter);
        if (!elementTags) {
          childTags = void 0;
          break;
        } else {
          childTags.push(...elementTags);
        }
      }
      if (childTags) {
        counter.tabstop = childCounter.tabstop;
        return [rootParam, ...childTags];
      }
    }
    return [
      getJSDocParamAnnotation(
        path2,
        initializer2,
        dotDotDotToken2,
        isJs,
        /*isObject*/
        false,
        isSnippet,
        checker,
        options,
        preferences,
        counter
      )
    ];
  }
  function elementWorker(path2, element, counter) {
    if (!element.propertyName && isIdentifier(element.name) || isIdentifier(element.name)) {
      const propertyName = element.propertyName ? tryGetTextOfPropertyName(element.propertyName) : element.name.text;
      if (!propertyName) {
        return void 0;
      }
      const paramName = `${path2}.${propertyName}`;
      return [
        getJSDocParamAnnotation(
          paramName,
          element.initializer,
          element.dotDotDotToken,
          isJs,
          /*isObject*/
          false,
          isSnippet,
          checker,
          options,
          preferences,
          counter
        )
      ];
    } else if (element.propertyName) {
      const propertyName = tryGetTextOfPropertyName(element.propertyName);
      return propertyName && patternWorker(`${path2}.${propertyName}`, element.name, element.initializer, element.dotDotDotToken, counter);
    }
    return void 0;
  }
}
function getJSDocParamAnnotation(paramName, initializer, dotDotDotToken, isJs, isObject, isSnippet, checker, options, preferences, tabstopCounter) {
  if (isSnippet) {
    Debug.assertIsDefined(tabstopCounter);
  }
  if (initializer) {
    paramName = getJSDocParamNameWithInitializer(paramName, initializer);
  }
  if (isSnippet) {
    paramName = escapeSnippetText(paramName);
  }
  if (isJs) {
    let type = "*";
    if (isObject) {
      Debug.assert(!dotDotDotToken, `Cannot annotate a rest parameter with type 'Object'.`);
      type = "Object";
    } else {
      if (initializer) {
        const inferredType = checker.getTypeAtLocation(initializer.parent);
        if (!(inferredType.flags & (1 /* Any */ | 16384 /* Void */))) {
          const sourceFile = initializer.getSourceFile();
          const quotePreference = getQuotePreference(sourceFile, preferences);
          const builderFlags = quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */;
          const typeNode = checker.typeToTypeNode(inferredType, findAncestor(initializer, isFunctionLike), builderFlags);
          if (typeNode) {
            const printer = isSnippet ? createSnippetPrinter({
              removeComments: true,
              module: options.module,
              moduleResolution: options.moduleResolution,
              target: options.target
            }) : createPrinter({
              removeComments: true,
              module: options.module,
              moduleResolution: options.moduleResolution,
              target: options.target
            });
            setEmitFlags(typeNode, 1 /* SingleLine */);
            type = printer.printNode(4 /* Unspecified */, typeNode, sourceFile);
          }
        }
      }
      if (isSnippet && type === "*") {
        type = `\${${tabstopCounter.tabstop++}:${type}}`;
      }
    }
    const dotDotDot = !isObject && dotDotDotToken ? "..." : "";
    const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : "";
    return `@param {${dotDotDot}${type}} ${paramName} ${description3}`;
  } else {
    const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : "";
    return `@param ${paramName} ${description3}`;
  }
}
function getJSDocParamNameWithInitializer(paramName, initializer) {
  const initializerText = initializer.getText().trim();
  if (initializerText.includes("\n") || initializerText.length > 80) {
    return `[${paramName}]`;
  }
  return `[${paramName}=${initializerText}]`;
}
function keywordToCompletionEntry(keyword) {
  return {
    name: tokenToString(keyword),
    kind: "keyword" /* keyword */,
    kindModifiers: "" /* none */,
    sortText: SortText.GlobalsOrKeywords
  };
}
function specificKeywordCompletionInfo(entries, isNewIdentifierLocation) {
  return {
    isGlobalCompletion: false,
    isMemberCompletion: false,
    isNewIdentifierLocation,
    entries: entries.slice(),
    defaultCommitCharacters: getDefaultCommitCharacters(isNewIdentifierLocation)
  };
}
function keywordCompletionData(keywordFilters, filterOutTsOnlyKeywords, isNewIdentifierLocation) {
  return {
    kind: 4 /* Keywords */,
    keywordCompletions: getKeywordCompletions(keywordFilters, filterOutTsOnlyKeywords),
    isNewIdentifierLocation
  };
}
function keywordFiltersFromSyntaxKind(keywordCompletion) {
  switch (keywordCompletion) {
    case 156 /* TypeKeyword */:
      return 8 /* TypeKeyword */;
    default:
      Debug.fail("Unknown mapping from SyntaxKind to KeywordCompletionFilters");
  }
}
function getOptionalReplacementSpan(location) {
  return (location == null ? void 0 : location.kind) === 80 /* Identifier */ ? createTextSpanFromNode(location) : void 0;
}
function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position, includeSymbol) {
  const {
    symbols,
    contextToken,
    completionKind,
    isInSnippetScope,
    isNewIdentifierLocation,
    location,
    propertyAccessToConvert,
    keywordFilters,
    symbolToOriginInfoMap,
    recommendedCompletion,
    isJsxInitializer,
    isTypeOnlyLocation,
    isJsxIdentifierExpected,
    isRightOfOpenTag,
    isRightOfDotOrQuestionDot,
    importStatementCompletion,
    insideJsDocTagTypeExpression,
    symbolToSortTextMap,
    hasUnresolvedAutoImports,
    defaultCommitCharacters
  } = completionData;
  let literals = completionData.literals;
  const checker = program.getTypeChecker();
  if (getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) {
    const completionInfo = getJsxClosingTagCompletion(location, sourceFile);
    if (completionInfo) {
      return completionInfo;
    }
  }
  const caseClause = findAncestor(contextToken, isCaseClause);
  if (caseClause && (isCaseKeyword(contextToken) || isNodeDescendantOf(contextToken, caseClause.expression))) {
    const tracker = newCaseClauseTracker(checker, caseClause.parent.clauses);
    literals = literals.filter((literal) => !tracker.hasValue(literal));
    symbols.forEach((symbol, i) => {
      if (symbol.valueDeclaration && isEnumMember(symbol.valueDeclaration)) {
        const value = checker.getConstantValue(symbol.valueDeclaration);
        if (value !== void 0 && tracker.hasValue(value)) {
          symbolToOriginInfoMap[i] = { kind: 256 /* Ignore */ };
        }
      }
    });
  }
  const entries = createSortedArray();
  const isChecked = isCheckedFile(sourceFile, compilerOptions);
  if (isChecked && !isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) {
    return void 0;
  }
  const uniqueNames = getCompletionEntriesFromSymbols(
    symbols,
    entries,
    /*replacementToken*/
    void 0,
    contextToken,
    location,
    position,
    sourceFile,
    host,
    program,
    getEmitScriptTarget(compilerOptions),
    log,
    completionKind,
    preferences,
    compilerOptions,
    formatContext,
    isTypeOnlyLocation,
    propertyAccessToConvert,
    isJsxIdentifierExpected,
    isJsxInitializer,
    importStatementCompletion,
    recommendedCompletion,
    symbolToOriginInfoMap,
    symbolToSortTextMap,
    isJsxIdentifierExpected,
    isRightOfOpenTag,
    includeSymbol
  );
  if (keywordFilters !== 0 /* None */) {
    for (const keywordEntry of getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && isSourceFileJS(sourceFile))) {
      if (isTypeOnlyLocation && isTypeKeyword(stringToToken(keywordEntry.name)) || !isTypeOnlyLocation && isContextualKeywordInAutoImportableExpressionSpace(keywordEntry.name) || !uniqueNames.has(keywordEntry.name)) {
        uniqueNames.add(keywordEntry.name);
        insertSorted(
          entries,
          keywordEntry,
          compareCompletionEntries,
          /*equalityComparer*/
          void 0,
          /*allowDuplicates*/
          true
        );
      }
    }
  }
  for (const keywordEntry of getContextualKeywords(contextToken, position)) {
    if (!uniqueNames.has(keywordEntry.name)) {
      uniqueNames.add(keywordEntry.name);
      insertSorted(
        entries,
        keywordEntry,
        compareCompletionEntries,
        /*equalityComparer*/
        void 0,
        /*allowDuplicates*/
        true
      );
    }
  }
  for (const literal of literals) {
    const literalEntry = createCompletionEntryForLiteral(sourceFile, preferences, literal);
    uniqueNames.add(literalEntry.name);
    insertSorted(
      entries,
      literalEntry,
      compareCompletionEntries,
      /*equalityComparer*/
      void 0,
      /*allowDuplicates*/
      true
    );
  }
  if (!isChecked) {
    getJSCompletionEntries(sourceFile, location.pos, uniqueNames, getEmitScriptTarget(compilerOptions), entries);
  }
  let caseBlock;
  if (preferences.includeCompletionsWithInsertText && contextToken && !isRightOfOpenTag && !isRightOfDotOrQuestionDot && (caseBlock = findAncestor(contextToken, isCaseBlock))) {
    const cases = getExhaustiveCaseSnippets(caseBlock, sourceFile, preferences, compilerOptions, host, program, formatContext);
    if (cases) {
      entries.push(cases.entry);
    }
  }
  return {
    flags: completionData.flags,
    isGlobalCompletion: isInSnippetScope,
    isIncomplete: preferences.allowIncompleteCompletions && hasUnresolvedAutoImports ? true : void 0,
    isMemberCompletion: isMemberCompletionKind(completionKind),
    isNewIdentifierLocation,
    optionalReplacementSpan: getOptionalReplacementSpan(location),
    entries,
    defaultCommitCharacters: defaultCommitCharacters ?? getDefaultCommitCharacters(isNewIdentifierLocation)
  };
}
function isCheckedFile(sourceFile, compilerOptions) {
  return !isSourceFileJS(sourceFile) || !!isCheckJsEnabledForFile(sourceFile, compilerOptions);
}
function getExhaustiveCaseSnippets(caseBlock, sourceFile, preferences, options, host, program, formatContext) {
  const clauses = caseBlock.clauses;
  const checker = program.getTypeChecker();
  const switchType = checker.getTypeAtLocation(caseBlock.parent.expression);
  if (switchType && switchType.isUnion() && every(switchType.types, (type) => type.isLiteral())) {
    const tracker = newCaseClauseTracker(checker, clauses);
    const target = getEmitScriptTarget(options);
    const quotePreference = getQuotePreference(sourceFile, preferences);
    const importAdder = ts_codefix_exports.createImportAdder(sourceFile, program, preferences, host);
    const elements = [];
    for (const type of switchType.types) {
      if (type.flags & 1024 /* EnumLiteral */) {
        Debug.assert(type.symbol, "An enum member type should have a symbol");
        Debug.assert(type.symbol.parent, "An enum member type should have a parent symbol (the enum symbol)");
        const enumValue = type.symbol.valueDeclaration && checker.getConstantValue(type.symbol.valueDeclaration);
        if (enumValue !== void 0) {
          if (tracker.hasValue(enumValue)) {
            continue;
          }
          tracker.addValue(enumValue);
        }
        const typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, caseBlock, target);
        if (!typeNode) {
          return void 0;
        }
        const expr = typeNodeToExpression(typeNode, target, quotePreference);
        if (!expr) {
          return void 0;
        }
        elements.push(expr);
      } else if (!tracker.hasValue(type.value)) {
        switch (typeof type.value) {
          case "object":
            elements.push(type.value.negative ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createBigIntLiteral({ negative: false, base10Value: type.value.base10Value })) : factory.createBigIntLiteral(type.value));
            break;
          case "number":
            elements.push(type.value < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-type.value)) : factory.createNumericLiteral(type.value));
            break;
          case "string":
            elements.push(factory.createStringLiteral(type.value, quotePreference === 0 /* Single */));
            break;
        }
      }
    }
    if (elements.length === 0) {
      return void 0;
    }
    const newClauses = map(elements, (element) => factory.createCaseClause(element, []));
    const newLineChar = getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options);
    const printer = createSnippetPrinter({
      removeComments: true,
      module: options.module,
      moduleResolution: options.moduleResolution,
      target: options.target,
      newLine: getNewLineKind(newLineChar)
    });
    const printNode = formatContext ? (node) => printer.printAndFormatNode(4 /* Unspecified */, node, sourceFile, formatContext) : (node) => printer.printNode(4 /* Unspecified */, node, sourceFile);
    const insertText = map(newClauses, (clause, i) => {
      if (preferences.includeCompletionsWithSnippetText) {
        return `${printNode(clause)}$${i + 1}`;
      }
      return `${printNode(clause)}`;
    }).join(newLineChar);
    const firstClause = printer.printNode(4 /* Unspecified */, newClauses[0], sourceFile);
    return {
      entry: {
        name: `${firstClause} ...`,
        kind: "" /* unknown */,
        sortText: SortText.GlobalsOrKeywords,
        insertText,
        hasAction: importAdder.hasFixes() || void 0,
        source: "SwitchCases/" /* SwitchCases */,
        isSnippet: preferences.includeCompletionsWithSnippetText ? true : void 0
      },
      importAdder
    };
  }
  return void 0;
}
function typeNodeToExpression(typeNode, languageVersion, quotePreference) {
  switch (typeNode.kind) {
    case 183 /* TypeReference */:
      const typeName = typeNode.typeName;
      return entityNameToExpression(typeName, languageVersion, quotePreference);
    case 199 /* IndexedAccessType */:
      const objectExpression = typeNodeToExpression(typeNode.objectType, languageVersion, quotePreference);
      const indexExpression = typeNodeToExpression(typeNode.indexType, languageVersion, quotePreference);
      return objectExpression && indexExpression && factory.createElementAccessExpression(objectExpression, indexExpression);
    case 201 /* LiteralType */:
      const literal = typeNode.literal;
      switch (literal.kind) {
        case 11 /* StringLiteral */:
          return factory.createStringLiteral(literal.text, quotePreference === 0 /* Single */);
        case 9 /* NumericLiteral */:
          return factory.createNumericLiteral(literal.text, literal.numericLiteralFlags);
      }
      return void 0;
    case 196 /* ParenthesizedType */:
      const exp = typeNodeToExpression(typeNode.type, languageVersion, quotePreference);
      return exp && (isIdentifier(exp) ? exp : factory.createParenthesizedExpression(exp));
    case 186 /* TypeQuery */:
      return entityNameToExpression(typeNode.exprName, languageVersion, quotePreference);
    case 205 /* ImportType */:
      Debug.fail(`We should not get an import type after calling 'codefix.typeToAutoImportableTypeNode'.`);
  }
  return void 0;
}
function entityNameToExpression(entityName, languageVersion, quotePreference) {
  if (isIdentifier(entityName)) {
    return entityName;
  }
  const unescapedName = unescapeLeadingUnderscores(entityName.right.escapedText);
  if (canUsePropertyAccess(unescapedName, languageVersion)) {
    return factory.createPropertyAccessExpression(
      entityNameToExpression(entityName.left, languageVersion, quotePreference),
      unescapedName
    );
  } else {
    return factory.createElementAccessExpression(
      entityNameToExpression(entityName.left, languageVersion, quotePreference),
      factory.createStringLiteral(unescapedName, quotePreference === 0 /* Single */)
    );
  }
}
function isMemberCompletionKind(kind) {
  switch (kind) {
    case 0 /* ObjectPropertyDeclaration */:
    case 3 /* MemberLike */:
    case 2 /* PropertyAccess */:
      return true;
    default:
      return false;
  }
}
function getJsxClosingTagCompletion(location, sourceFile) {
  const jsxClosingElement = findAncestor(location, (node) => {
    switch (node.kind) {
      case 287 /* JsxClosingElement */:
        return true;
      case 44 /* SlashToken */:
      case 32 /* GreaterThanToken */:
      case 80 /* Identifier */:
      case 211 /* PropertyAccessExpression */:
        return false;
      default:
        return "quit";
    }
  });
  if (jsxClosingElement) {
    const hasClosingAngleBracket = !!findChildOfKind(jsxClosingElement, 32 /* GreaterThanToken */, sourceFile);
    const tagName = jsxClosingElement.parent.openingElement.tagName;
    const closingTag = tagName.getText(sourceFile);
    const fullClosingTag = closingTag + (hasClosingAngleBracket ? "" : ">");
    const replacementSpan = createTextSpanFromNode(jsxClosingElement.tagName);
    const entry = {
      name: fullClosingTag,
      kind: "class" /* classElement */,
      kindModifiers: void 0,
      sortText: SortText.LocationPriority
    };
    return {
      isGlobalCompletion: false,
      isMemberCompletion: true,
      isNewIdentifierLocation: false,
      optionalReplacementSpan: replacementSpan,
      entries: [entry],
      defaultCommitCharacters: getDefaultCommitCharacters(
        /*isNewIdentifierLocation*/
        false
      )
    };
  }
  return;
}
function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) {
  getNameTable(sourceFile).forEach((pos, name) => {
    if (pos === position) {
      return;
    }
    const realName = unescapeLeadingUnderscores(name);
    if (!uniqueNames.has(realName) && isIdentifierText(realName, target)) {
      uniqueNames.add(realName);
      insertSorted(entries, {
        name: realName,
        kind: "warning" /* warning */,
        kindModifiers: "",
        sortText: SortText.JavascriptIdentifiers,
        isFromUncheckedFile: true,
        commitCharacters: []
      }, compareCompletionEntries);
    }
  });
}
function completionNameForLiteral(sourceFile, preferences, literal) {
  return typeof literal === "object" ? pseudoBigIntToString(literal) + "n" : isString(literal) ? quote(sourceFile, preferences, literal) : JSON.stringify(literal);
}
function createCompletionEntryForLiteral(sourceFile, preferences, literal) {
  return {
    name: completionNameForLiteral(sourceFile, preferences, literal),
    kind: "string" /* string */,
    kindModifiers: "" /* none */,
    sortText: SortText.LocationPriority,
    commitCharacters: []
  };
}
function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, position, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importStatementCompletion, useSemicolons, options, preferences, completionKind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol) {
  var _a, _b;
  let insertText;
  let filterText;
  let replacementSpan = getReplacementSpanForContextToken(replacementToken, position);
  let data;
  let isSnippet;
  let source = getSourceFromOrigin(origin);
  let sourceDisplay;
  let hasAction;
  let labelDetails;
  const typeChecker = program.getTypeChecker();
  const insertQuestionDot = origin && originIsNullableMember(origin);
  const useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess;
  if (origin && originIsThisType(origin)) {
    insertText = needsConvertPropertyAccess ? `this${insertQuestionDot ? "?." : ""}[${quotePropertyName(sourceFile, preferences, name)}]` : `this${insertQuestionDot ? "?." : "."}${name}`;
  } else if ((useBraces || insertQuestionDot) && propertyAccessToConvert) {
    insertText = useBraces ? needsConvertPropertyAccess ? `[${quotePropertyName(sourceFile, preferences, name)}]` : `[${name}]` : name;
    if (insertQuestionDot || propertyAccessToConvert.questionDotToken) {
      insertText = `?.${insertText}`;
    }
    const dot = findChildOfKind(propertyAccessToConvert, 25 /* DotToken */, sourceFile) || findChildOfKind(propertyAccessToConvert, 29 /* QuestionDotToken */, sourceFile);
    if (!dot) {
      return void 0;
    }
    const end = startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end;
    replacementSpan = createTextSpanFromBounds(dot.getStart(sourceFile), end);
  }
  if (isJsxInitializer) {
    if (insertText === void 0) insertText = name;
    insertText = `{${insertText}}`;
    if (typeof isJsxInitializer !== "boolean") {
      replacementSpan = createTextSpanFromNode(isJsxInitializer, sourceFile);
    }
  }
  if (origin && originIsPromise(origin) && propertyAccessToConvert) {
    if (insertText === void 0) insertText = name;
    const precedingToken = findPrecedingToken(propertyAccessToConvert.pos, sourceFile);
    let awaitText = "";
    if (precedingToken && positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
      awaitText = ";";
    }
    awaitText += `(await ${propertyAccessToConvert.expression.getText()})`;
    insertText = needsConvertPropertyAccess ? `${awaitText}${insertText}` : `${awaitText}${insertQuestionDot ? "?." : "."}${insertText}`;
    const isInAwaitExpression = tryCast(propertyAccessToConvert.parent, isAwaitExpression);
    const wrapNode = isInAwaitExpression ? propertyAccessToConvert.parent : propertyAccessToConvert.expression;
    replacementSpan = createTextSpanFromBounds(wrapNode.getStart(sourceFile), propertyAccessToConvert.end);
  }
  if (originIsResolvedExport(origin)) {
    sourceDisplay = [textPart(origin.moduleSpecifier)];
    if (importStatementCompletion) {
      ({ insertText, replacementSpan } = getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, program, preferences));
      isSnippet = preferences.includeCompletionsWithSnippetText ? true : void 0;
    }
  }
  if ((origin == null ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */) {
    hasAction = true;
  }
  if (completionKind === 0 /* ObjectPropertyDeclaration */ && contextToken && ((_a = findPrecedingToken(contextToken.pos, sourceFile, contextToken)) == null ? void 0 : _a.kind) !== 28 /* CommaToken */) {
    if (isMethodDeclaration(contextToken.parent.parent) || isGetAccessorDeclaration(contextToken.parent.parent) || isSetAccessorDeclaration(contextToken.parent.parent) || isSpreadAssignment(contextToken.parent) || ((_b = findAncestor(contextToken.parent, isPropertyAssignment)) == null ? void 0 : _b.getLastToken(sourceFile)) === contextToken || isShorthandPropertyAssignment(contextToken.parent) && getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line) {
      source = "ObjectLiteralMemberWithComma/" /* ObjectLiteralMemberWithComma */;
      hasAction = true;
    }
  }
  if (preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === 3 /* MemberLike */ && isClassLikeMemberCompletion(symbol, location, sourceFile)) {
    let importAdder;
    const memberCompletionEntry = getEntryForMemberCompletion(
      host,
      program,
      options,
      preferences,
      name,
      symbol,
      location,
      position,
      contextToken,
      formatContext
    );
    if (memberCompletionEntry) {
      ({ insertText, filterText, isSnippet, importAdder } = memberCompletionEntry);
      if ((importAdder == null ? void 0 : importAdder.hasFixes()) || memberCompletionEntry.eraseRange) {
        hasAction = true;
        source = "ClassMemberSnippet/" /* ClassMemberSnippet */;
      }
    } else {
      return void 0;
    }
  }
  if (origin && originIsObjectLiteralMethod(origin)) {
    ({ insertText, isSnippet, labelDetails } = origin);
    if (!preferences.useLabelDetailsInCompletionEntries) {
      name = name + labelDetails.detail;
      labelDetails = void 0;
    }
    source = "ObjectLiteralMethodSnippet/" /* ObjectLiteralMethodSnippet */;
    sortText = SortText.SortBelow(sortText);
  }
  if (isJsxIdentifierExpected && !isRightOfOpenTag && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none" && !(isJsxAttribute(location.parent) && location.parent.initializer)) {
    let useBraces2 = preferences.jsxAttributeCompletionStyle === "braces";
    const type = typeChecker.getTypeOfSymbolAtLocation(symbol, location);
    if (preferences.jsxAttributeCompletionStyle === "auto" && !(type.flags & 528 /* BooleanLike */) && !(type.flags & 1048576 /* Union */ && find(type.types, (type2) => !!(type2.flags & 528 /* BooleanLike */)))) {
      if (type.flags & 402653316 /* StringLike */ || type.flags & 1048576 /* Union */ && every(type.types, (type2) => !!(type2.flags & (402653316 /* StringLike */ | 32768 /* Undefined */) || isStringAndEmptyAnonymousObjectIntersection(type2)))) {
        insertText = `${escapeSnippetText(name)}=${quote(sourceFile, preferences, "$1")}`;
        isSnippet = true;
      } else {
        useBraces2 = true;
      }
    }
    if (useBraces2) {
      insertText = `${escapeSnippetText(name)}={$1}`;
      isSnippet = true;
    }
  }
  if (insertText !== void 0 && !preferences.includeCompletionsWithInsertText) {
    return void 0;
  }
  if (originIsExport(origin) || originIsResolvedExport(origin)) {
    data = originToCompletionEntryData(origin);
    hasAction = !importStatementCompletion;
  }
  const parentNamedImportOrExport = findAncestor(location, isNamedImportsOrExports);
  if (parentNamedImportOrExport) {
    const languageVersion = getEmitScriptTarget(host.getCompilationSettings());
    if (!isIdentifierText(name, languageVersion)) {
      insertText = quotePropertyName(sourceFile, preferences, name);
      if (parentNamedImportOrExport.kind === 275 /* NamedImports */) {
        scanner.setText(sourceFile.text);
        scanner.resetTokenState(position);
        if (!(scanner.scan() === 130 /* AsKeyword */ && scanner.scan() === 80 /* Identifier */)) {
          insertText += " as " + generateIdentifierForArbitraryString(name, languageVersion);
        }
      }
    } else if (parentNamedImportOrExport.kind === 275 /* NamedImports */) {
      const possibleToken = stringToToken(name);
      if (possibleToken && (possibleToken === 135 /* AwaitKeyword */ || isNonContextualKeyword(possibleToken))) {
        insertText = `${name} as ${name}_`;
      }
    }
  }
  const kind = ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, location);
  const commitCharacters = kind === "warning" /* warning */ || kind === "string" /* string */ ? [] : void 0;
  return {
    name,
    kind,
    kindModifiers: ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol),
    sortText,
    source,
    hasAction: hasAction ? true : void 0,
    isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || void 0,
    insertText,
    filterText,
    replacementSpan,
    sourceDisplay,
    labelDetails,
    isSnippet,
    isPackageJsonImport: originIsPackageJsonImport(origin) || void 0,
    isImportStatementCompletion: !!importStatementCompletion || void 0,
    data,
    commitCharacters,
    ...includeSymbol ? { symbol } : void 0
  };
}
function generateIdentifierForArbitraryString(text, languageVersion) {
  let needsUnderscore = false;
  let identifier = "";
  let ch;
  for (let i = 0; i < text.length; i += ch !== void 0 && ch >= 65536 ? 2 : 1) {
    ch = text.codePointAt(i);
    if (ch !== void 0 && (i === 0 ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) {
      if (needsUnderscore) identifier += "_";
      identifier += String.fromCodePoint(ch);
      needsUnderscore = false;
    } else {
      needsUnderscore = true;
    }
  }
  if (needsUnderscore) identifier += "_";
  return identifier || "_";
}
function isClassLikeMemberCompletion(symbol, location, sourceFile) {
  if (isInJSFile(location)) {
    return false;
  }
  const memberFlags = 106500 /* ClassMember */ & 900095 /* EnumMemberExcludes */;
  return !!(symbol.flags & memberFlags) && (isClassLike(location) || location.parent && location.parent.parent && isClassElement(location.parent) && location === location.parent.name && location.parent.getLastToken(sourceFile) === location.parent.name && isClassLike(location.parent.parent) || location.parent && isSyntaxList(location) && isClassLike(location.parent));
}
function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, position, contextToken, formatContext) {
  const classLikeDeclaration = findAncestor(location, isClassLike);
  if (!classLikeDeclaration) {
    return void 0;
  }
  let isSnippet;
  let insertText = name;
  const filterText = name;
  const checker = program.getTypeChecker();
  const sourceFile = location.getSourceFile();
  const printer = createSnippetPrinter({
    removeComments: true,
    module: options.module,
    moduleResolution: options.moduleResolution,
    target: options.target,
    omitTrailingSemicolon: false,
    newLine: getNewLineKind(getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options))
  });
  const importAdder = ts_codefix_exports.createImportAdder(sourceFile, program, preferences, host);
  let body;
  if (preferences.includeCompletionsWithSnippetText) {
    isSnippet = true;
    const emptyStmt = factory.createEmptyStatement();
    body = factory.createBlock(
      [emptyStmt],
      /*multiLine*/
      true
    );
    setSnippetElement(emptyStmt, { kind: 0 /* TabStop */, order: 0 });
  } else {
    body = factory.createBlock(
      [],
      /*multiLine*/
      true
    );
  }
  let modifiers = 0 /* None */;
  const { modifiers: presentModifiers, range: eraseRange, decorators: presentDecorators } = getPresentModifiers(contextToken, sourceFile, position);
  const isAbstract = presentModifiers & 64 /* Abstract */ && classLikeDeclaration.modifierFlagsCache & 64 /* Abstract */;
  let completionNodes = [];
  ts_codefix_exports.addNewNodeForMemberSymbol(
    symbol,
    classLikeDeclaration,
    sourceFile,
    { program, host },
    preferences,
    importAdder,
    // `addNewNodeForMemberSymbol` calls this callback function for each new member node
    // it adds for the given member symbol.
    // We store these member nodes in the `completionNodes` array.
    // Note: there might be:
    //  - No nodes if `addNewNodeForMemberSymbol` cannot figure out a node for the member;
    //  - One node;
    //  - More than one node if the member is overloaded (e.g. a method with overload signatures).
    (node) => {
      let requiredModifiers = 0 /* None */;
      if (isAbstract) {
        requiredModifiers |= 64 /* Abstract */;
      }
      if (isClassElement(node) && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node, symbol) === 1 /* NeedsOverride */) {
        requiredModifiers |= 16 /* Override */;
      }
      if (!completionNodes.length) {
        modifiers = node.modifierFlagsCache | requiredModifiers;
      }
      node = factory.replaceModifiers(node, modifiers);
      completionNodes.push(node);
    },
    body,
    ts_codefix_exports.PreserveOptionalFlags.Property,
    !!isAbstract
  );
  if (completionNodes.length) {
    const isMethod = symbol.flags & 8192 /* Method */;
    let allowedModifiers = modifiers | 16 /* Override */ | 1 /* Public */;
    if (!isMethod) {
      allowedModifiers |= 128 /* Ambient */ | 8 /* Readonly */;
    } else {
      allowedModifiers |= 1024 /* Async */;
    }
    const allowedAndPresent = presentModifiers & allowedModifiers;
    if (presentModifiers & ~allowedModifiers) {
      return void 0;
    }
    if (modifiers & 4 /* Protected */ && allowedAndPresent & 1 /* Public */) {
      modifiers &= ~4 /* Protected */;
    }
    if (allowedAndPresent !== 0 /* None */ && !(allowedAndPresent & 1 /* Public */)) {
      modifiers &= ~1 /* Public */;
    }
    modifiers |= allowedAndPresent;
    completionNodes = completionNodes.map((node) => factory.replaceModifiers(node, modifiers));
    if (presentDecorators == null ? void 0 : presentDecorators.length) {
      const lastNode = completionNodes[completionNodes.length - 1];
      if (canHaveDecorators(lastNode)) {
        completionNodes[completionNodes.length - 1] = factory.replaceDecoratorsAndModifiers(lastNode, presentDecorators.concat(getModifiers(lastNode) || []));
      }
    }
    const format = 1 /* MultiLine */ | 131072 /* NoTrailingNewLine */;
    if (formatContext) {
      insertText = printer.printAndFormatSnippetList(
        format,
        factory.createNodeArray(completionNodes),
        sourceFile,
        formatContext
      );
    } else {
      insertText = printer.printSnippetList(
        format,
        factory.createNodeArray(completionNodes),
        sourceFile
      );
    }
  }
  return { insertText, filterText, isSnippet, importAdder, eraseRange };
}
function getPresentModifiers(contextToken, sourceFile, position) {
  if (!contextToken || getLineAndCharacterOfPosition(sourceFile, position).line > getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line) {
    return { modifiers: 0 /* None */ };
  }
  let modifiers = 0 /* None */;
  let decorators;
  let contextMod;
  const range = { pos: position, end: position };
  if (isPropertyDeclaration(contextToken.parent) && (contextMod = isModifierLike2(contextToken))) {
    if (contextToken.parent.modifiers) {
      modifiers |= modifiersToFlags(contextToken.parent.modifiers) & 98303 /* Modifier */;
      decorators = contextToken.parent.modifiers.filter(isDecorator) || [];
      range.pos = Math.min(...contextToken.parent.modifiers.map((n) => n.getStart(sourceFile)));
    }
    const contextModifierFlag = modifierToFlag(contextMod);
    if (!(modifiers & contextModifierFlag)) {
      modifiers |= contextModifierFlag;
      range.pos = Math.min(range.pos, contextToken.getStart(sourceFile));
    }
    if (contextToken.parent.name !== contextToken) {
      range.end = contextToken.parent.name.getStart(sourceFile);
    }
  }
  return { modifiers, decorators, range: range.pos < range.end ? range : void 0 };
}
function isModifierLike2(node) {
  if (isModifier(node)) {
    return node.kind;
  }
  if (isIdentifier(node)) {
    const originalKeywordKind = identifierToKeywordKind(node);
    if (originalKeywordKind && isModifierKind(originalKeywordKind)) {
      return originalKeywordKind;
    }
  }
  return void 0;
}
function getEntryForObjectLiteralMethodCompletion(symbol, name, enclosingDeclaration, program, host, options, preferences, formatContext) {
  const isSnippet = preferences.includeCompletionsWithSnippetText || void 0;
  let insertText = name;
  const sourceFile = enclosingDeclaration.getSourceFile();
  const method = createObjectLiteralMethod(symbol, enclosingDeclaration, sourceFile, program, host, preferences);
  if (!method) {
    return void 0;
  }
  const printer = createSnippetPrinter({
    removeComments: true,
    module: options.module,
    moduleResolution: options.moduleResolution,
    target: options.target,
    omitTrailingSemicolon: false,
    newLine: getNewLineKind(getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options))
  });
  if (formatContext) {
    insertText = printer.printAndFormatSnippetList(16 /* CommaDelimited */ | 64 /* AllowTrailingComma */, factory.createNodeArray(
      [method],
      /*hasTrailingComma*/
      true
    ), sourceFile, formatContext);
  } else {
    insertText = printer.printSnippetList(16 /* CommaDelimited */ | 64 /* AllowTrailingComma */, factory.createNodeArray(
      [method],
      /*hasTrailingComma*/
      true
    ), sourceFile);
  }
  const signaturePrinter = createPrinter({
    removeComments: true,
    module: options.module,
    moduleResolution: options.moduleResolution,
    target: options.target,
    omitTrailingSemicolon: true
  });
  const methodSignature = factory.createMethodSignature(
    /*modifiers*/
    void 0,
    /*name*/
    "",
    method.questionToken,
    method.typeParameters,
    method.parameters,
    method.type
  );
  const labelDetails = { detail: signaturePrinter.printNode(4 /* Unspecified */, methodSignature, sourceFile) };
  return { isSnippet, insertText, labelDetails };
}
function createObjectLiteralMethod(symbol, enclosingDeclaration, sourceFile, program, host, preferences) {
  const declarations = symbol.getDeclarations();
  if (!(declarations && declarations.length)) {
    return void 0;
  }
  const checker = program.getTypeChecker();
  const declaration = declarations[0];
  const name = getSynthesizedDeepClone(
    getNameOfDeclaration(declaration),
    /*includeTrivia*/
    false
  );
  const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
  const quotePreference = getQuotePreference(sourceFile, preferences);
  const builderFlags = 33554432 /* OmitThisParameter */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */);
  switch (declaration.kind) {
    case 171 /* PropertySignature */:
    case 172 /* PropertyDeclaration */:
    case 173 /* MethodSignature */:
    case 174 /* MethodDeclaration */: {
      let effectiveType = type.flags & 1048576 /* Union */ && type.types.length < 10 ? checker.getUnionType(type.types, 2 /* Subtype */) : type;
      if (effectiveType.flags & 1048576 /* Union */) {
        const functionTypes = filter(effectiveType.types, (type2) => checker.getSignaturesOfType(type2, 0 /* Call */).length > 0);
        if (functionTypes.length === 1) {
          effectiveType = functionTypes[0];
        } else {
          return void 0;
        }
      }
      const signatures = checker.getSignaturesOfType(effectiveType, 0 /* Call */);
      if (signatures.length !== 1) {
        return void 0;
      }
      const typeNode = checker.typeToTypeNode(
        effectiveType,
        enclosingDeclaration,
        builderFlags,
        /*internalFlags*/
        void 0,
        ts_codefix_exports.getNoopSymbolTrackerWithResolver({ program, host })
      );
      if (!typeNode || !isFunctionTypeNode(typeNode)) {
        return void 0;
      }
      let body;
      if (preferences.includeCompletionsWithSnippetText) {
        const emptyStmt = factory.createEmptyStatement();
        body = factory.createBlock(
          [emptyStmt],
          /*multiLine*/
          true
        );
        setSnippetElement(emptyStmt, { kind: 0 /* TabStop */, order: 0 });
      } else {
        body = factory.createBlock(
          [],
          /*multiLine*/
          true
        );
      }
      const parameters = typeNode.parameters.map(
        (typedParam) => factory.createParameterDeclaration(
          /*modifiers*/
          void 0,
          typedParam.dotDotDotToken,
          typedParam.name,
          /*questionToken*/
          void 0,
          /*type*/
          void 0,
          typedParam.initializer
        )
      );
      return factory.createMethodDeclaration(
        /*modifiers*/
        void 0,
        /*asteriskToken*/
        void 0,
        name,
        /*questionToken*/
        void 0,
        /*typeParameters*/
        void 0,
        parameters,
        /*type*/
        void 0,
        body
      );
    }
    default:
      return void 0;
  }
}
function createSnippetPrinter(printerOptions) {
  let escapes;
  const baseWriter = ts_textChanges_exports.createWriter(getNewLineCharacter(printerOptions));
  const printer = createPrinter(printerOptions, baseWriter);
  const writer = {
    ...baseWriter,
    write: (s) => escapingWrite(s, () => baseWriter.write(s)),
    nonEscapingWrite: baseWriter.write,
    writeLiteral: (s) => escapingWrite(s, () => baseWriter.writeLiteral(s)),
    writeStringLiteral: (s) => escapingWrite(s, () => baseWriter.writeStringLiteral(s)),
    writeSymbol: (s, symbol) => escapingWrite(s, () => baseWriter.writeSymbol(s, symbol)),
    writeParameter: (s) => escapingWrite(s, () => baseWriter.writeParameter(s)),
    writeComment: (s) => escapingWrite(s, () => baseWriter.writeComment(s)),
    writeProperty: (s) => escapingWrite(s, () => baseWriter.writeProperty(s))
  };
  return {
    printSnippetList,
    printAndFormatSnippetList,
    printNode,
    printAndFormatNode
  };
  function escapingWrite(s, write) {
    const escaped = escapeSnippetText(s);
    if (escaped !== s) {
      const start = baseWriter.getTextPos();
      write();
      const end = baseWriter.getTextPos();
      escapes = append(escapes || (escapes = []), { newText: escaped, span: { start, length: end - start } });
    } else {
      write();
    }
  }
  function printSnippetList(format, list, sourceFile) {
    const unescaped = printUnescapedSnippetList(format, list, sourceFile);
    return escapes ? ts_textChanges_exports.applyChanges(unescaped, escapes) : unescaped;
  }
  function printUnescapedSnippetList(format, list, sourceFile) {
    escapes = void 0;
    writer.clear();
    printer.writeList(format, list, sourceFile, writer);
    return writer.getText();
  }
  function printAndFormatSnippetList(format, list, sourceFile, formatContext) {
    const syntheticFile = {
      text: printUnescapedSnippetList(
        format,
        list,
        sourceFile
      ),
      getLineAndCharacterOfPosition(pos) {
        return getLineAndCharacterOfPosition(this, pos);
      }
    };
    const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile);
    const changes = flatMap(list, (node) => {
      const nodeWithPos = ts_textChanges_exports.assignPositionsToNode(node);
      return ts_formatting_exports.formatNodeGivenIndentation(
        nodeWithPos,
        syntheticFile,
        sourceFile.languageVariant,
        /* indentation */
        0,
        /* delta */
        0,
        { ...formatContext, options: formatOptions }
      );
    });
    const allChanges = escapes ? toSorted(concatenate(changes, escapes), (a, b) => compareTextSpans(a.span, b.span)) : changes;
    return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges);
  }
  function printNode(hint, node, sourceFile) {
    const unescaped = printUnescapedNode(hint, node, sourceFile);
    return escapes ? ts_textChanges_exports.applyChanges(unescaped, escapes) : unescaped;
  }
  function printUnescapedNode(hint, node, sourceFile) {
    escapes = void 0;
    writer.clear();
    printer.writeNode(hint, node, sourceFile, writer);
    return writer.getText();
  }
  function printAndFormatNode(hint, node, sourceFile, formatContext) {
    const syntheticFile = {
      text: printUnescapedNode(
        hint,
        node,
        sourceFile
      ),
      getLineAndCharacterOfPosition(pos) {
        return getLineAndCharacterOfPosition(this, pos);
      }
    };
    const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile);
    const nodeWithPos = ts_textChanges_exports.assignPositionsToNode(node);
    const changes = ts_formatting_exports.formatNodeGivenIndentation(
      nodeWithPos,
      syntheticFile,
      sourceFile.languageVariant,
      /* indentation */
      0,
      /* delta */
      0,
      { ...formatContext, options: formatOptions }
    );
    const allChanges = escapes ? toSorted(concatenate(changes, escapes), (a, b) => compareTextSpans(a.span, b.span)) : changes;
    return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges);
  }
}
function originToCompletionEntryData(origin) {
  const ambientModuleName = origin.fileName ? void 0 : stripQuotes(origin.moduleSymbol.name);
  const isPackageJsonImport = origin.isFromPackageJson ? true : void 0;
  if (originIsResolvedExport(origin)) {
    const resolvedData = {
      exportName: origin.exportName,
      exportMapKey: origin.exportMapKey,
      moduleSpecifier: origin.moduleSpecifier,
      ambientModuleName,
      fileName: origin.fileName,
      isPackageJsonImport
    };
    return resolvedData;
  }
  const unresolvedData = {
    exportName: origin.exportName,
    exportMapKey: origin.exportMapKey,
    fileName: origin.fileName,
    ambientModuleName: origin.fileName ? void 0 : stripQuotes(origin.moduleSymbol.name),
    isPackageJsonImport: origin.isFromPackageJson ? true : void 0
  };
  return unresolvedData;
}
function completionEntryDataToSymbolOriginInfo(data, completionName, moduleSymbol) {
  const isDefaultExport = data.exportName === "default" /* Default */;
  const isFromPackageJson = !!data.isPackageJsonImport;
  if (completionEntryDataIsResolved(data)) {
    const resolvedOrigin = {
      kind: 32 /* ResolvedExport */,
      exportName: data.exportName,
      exportMapKey: data.exportMapKey,
      moduleSpecifier: data.moduleSpecifier,
      symbolName: completionName,
      fileName: data.fileName,
      moduleSymbol,
      isDefaultExport,
      isFromPackageJson
    };
    return resolvedOrigin;
  }
  const unresolvedOrigin = {
    kind: 4 /* Export */,
    exportName: data.exportName,
    exportMapKey: data.exportMapKey,
    symbolName: completionName,
    fileName: data.fileName,
    moduleSymbol,
    isDefaultExport,
    isFromPackageJson
  };
  return unresolvedOrigin;
}
function getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, program, preferences) {
  const replacementSpan = importStatementCompletion.replacementSpan;
  const quotedModuleSpecifier = escapeSnippetText(quote(sourceFile, preferences, origin.moduleSpecifier));
  const exportKind = origin.isDefaultExport ? 1 /* Default */ : origin.exportName === "export=" /* ExportEquals */ ? 2 /* ExportEquals */ : 0 /* Named */;
  const tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : "";
  const importKind = ts_codefix_exports.getImportKind(
    sourceFile,
    exportKind,
    program,
    /*forceImportKeyword*/
    true
  );
  const isImportSpecifierTypeOnly = importStatementCompletion.couldBeTypeOnlyImportSpecifier;
  const topLevelTypeOnlyText = importStatementCompletion.isTopLevelTypeOnly ? ` ${tokenToString(156 /* TypeKeyword */)} ` : " ";
  const importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? `${tokenToString(156 /* TypeKeyword */)} ` : "";
  const suffix = useSemicolons ? ";" : "";
  switch (importKind) {
    case 3 /* CommonJS */:
      return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} = require(${quotedModuleSpecifier})${suffix}` };
    case 1 /* Default */:
      return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} from ${quotedModuleSpecifier}${suffix}` };
    case 2 /* Namespace */:
      return { replacementSpan, insertText: `import${topLevelTypeOnlyText}* as ${escapeSnippetText(name)} from ${quotedModuleSpecifier}${suffix}` };
    case 0 /* Named */:
      return { replacementSpan, insertText: `import${topLevelTypeOnlyText}{ ${importSpecifierTypeOnlyText}${escapeSnippetText(name)}${tabStop} } from ${quotedModuleSpecifier}${suffix}` };
  }
}
function quotePropertyName(sourceFile, preferences, name) {
  if (/^\d+$/.test(name)) {
    return name;
  }
  return quote(sourceFile, preferences, name);
}
function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) {
  return localSymbol === recommendedCompletion || !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion;
}
function getSourceFromOrigin(origin) {
  if (originIsExport(origin)) {
    return stripQuotes(origin.moduleSymbol.name);
  }
  if (originIsResolvedExport(origin)) {
    return origin.moduleSpecifier;
  }
  if ((origin == null ? void 0 : origin.kind) === 1 /* ThisType */) {
    return "ThisProperty/" /* ThisProperty */;
  }
  if ((origin == null ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */) {
    return "TypeOnlyAlias/" /* TypeOnlyAlias */;
  }
}
function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, position, sourceFile, host, program, target, log, kind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol = false) {
  const start = timestamp();
  const closestSymbolDeclaration = getClosestSymbolDeclaration(contextToken, location);
  const useSemicolons = probablyUsesSemicolons(sourceFile);
  const typeChecker = program.getTypeChecker();
  const uniques = /* @__PURE__ */ new Map();
  for (let i = 0; i < symbols.length; i++) {
    const symbol = symbols[i];
    const origin = symbolToOriginInfoMap == null ? void 0 : symbolToOriginInfoMap[i];
    const info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected);
    if (!info || uniques.get(info.name) && (!origin || !originIsObjectLiteralMethod(origin)) || kind === 1 /* Global */ && symbolToSortTextMap && !shouldIncludeSymbol(symbol, symbolToSortTextMap)) {
      continue;
    }
    if (!isTypeOnlyLocation && isInJSFile(sourceFile) && symbolAppearsToBeTypeOnly(symbol)) {
      continue;
    }
    const { name, needsConvertPropertyAccess } = info;
    const originalSortText = (symbolToSortTextMap == null ? void 0 : symbolToSortTextMap[getSymbolId(symbol)]) ?? SortText.LocationPriority;
    const sortText = isDeprecated(symbol, typeChecker) ? SortText.Deprecated(originalSortText) : originalSortText;
    const entry = createCompletionEntry(
      symbol,
      sortText,
      replacementToken,
      contextToken,
      location,
      position,
      sourceFile,
      host,
      program,
      name,
      needsConvertPropertyAccess,
      origin,
      recommendedCompletion,
      propertyAccessToConvert,
      isJsxInitializer,
      importStatementCompletion,
      useSemicolons,
      compilerOptions,
      preferences,
      kind,
      formatContext,
      isJsxIdentifierExpected,
      isRightOfOpenTag,
      includeSymbol
    );
    if (!entry) {
      continue;
    }
    const shouldShadowLaterSymbols = (!origin || originIsTypeOnlyAlias(origin)) && !(symbol.parent === void 0 && !some(symbol.declarations, (d) => d.getSourceFile() === location.getSourceFile()));
    uniques.set(name, shouldShadowLaterSymbols);
    insertSorted(
      entries,
      entry,
      compareCompletionEntries,
      /*equalityComparer*/
      void 0,
      /*allowDuplicates*/
      true
    );
  }
  log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (timestamp() - start));
  return {
    has: (name) => uniques.has(name),
    add: (name) => uniques.set(name, true)
  };
  function shouldIncludeSymbol(symbol, symbolToSortTextMap2) {
    var _a;
    let allFlags = symbol.flags;
    if (!isSourceFile(location)) {
      if (isExportAssignment(location.parent)) {
        return true;
      }
      if (tryCast(closestSymbolDeclaration, isVariableDeclaration) && symbol.valueDeclaration === closestSymbolDeclaration) {
        return false;
      }
      const symbolDeclaration = symbol.valueDeclaration ?? ((_a = symbol.declarations) == null ? void 0 : _a[0]);
      if (closestSymbolDeclaration && symbolDeclaration) {
        if (isParameter(closestSymbolDeclaration) && isParameter(symbolDeclaration)) {
          const parameters = closestSymbolDeclaration.parent.parameters;
          if (symbolDeclaration.pos >= closestSymbolDeclaration.pos && symbolDeclaration.pos < parameters.end) {
            return false;
          }
        } else if (isTypeParameterDeclaration(closestSymbolDeclaration) && isTypeParameterDeclaration(symbolDeclaration)) {
          if (closestSymbolDeclaration === symbolDeclaration && (contextToken == null ? void 0 : contextToken.kind) === 96 /* ExtendsKeyword */) {
            return false;
          }
          if (isInTypeParameterDefault(contextToken) && !isInferTypeNode(closestSymbolDeclaration.parent)) {
            const typeParameters = closestSymbolDeclaration.parent.typeParameters;
            if (typeParameters && symbolDeclaration.pos >= closestSymbolDeclaration.pos && symbolDeclaration.pos < typeParameters.end) {
              return false;
            }
          }
        }
      }
      const symbolOrigin = skipAlias(symbol, typeChecker);
      if (!!sourceFile.externalModuleIndicator && !compilerOptions.allowUmdGlobalAccess && symbolToSortTextMap2[getSymbolId(symbol)] === SortText.GlobalsOrKeywords && (symbolToSortTextMap2[getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions || symbolToSortTextMap2[getSymbolId(symbolOrigin)] === SortText.LocationPriority)) {
        return false;
      }
      allFlags |= getCombinedLocalAndExportSymbolFlags(symbolOrigin);
      if (isInRightSideOfInternalImportEqualsDeclaration(location)) {
        return !!(allFlags & 1920 /* Namespace */);
      }
      if (isTypeOnlyLocation) {
        return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker);
      }
    }
    return !!(allFlags & 111551 /* Value */);
  }
  function symbolAppearsToBeTypeOnly(symbol) {
    var _a;
    const flags = getCombinedLocalAndExportSymbolFlags(skipAlias(symbol, typeChecker));
    return !(flags & 111551 /* Value */) && (!isInJSFile((_a = symbol.declarations) == null ? void 0 : _a[0]) || !!(flags & 788968 /* Type */));
  }
}
function getLabelCompletionAtPosition(node) {
  const entries = getLabelStatementCompletions(node);
  if (entries.length) {
    return {
      isGlobalCompletion: false,
      isMemberCompletion: false,
      isNewIdentifierLocation: false,
      entries,
      defaultCommitCharacters: getDefaultCommitCharacters(
        /*isNewIdentifierLocation*/
        false
      )
    };
  }
}
function getLabelStatementCompletions(node) {
  const entries = [];
  const uniques = /* @__PURE__ */ new Map();
  let current = node;
  while (current) {
    if (isFunctionLike(current)) {
      break;
    }
    if (isLabeledStatement(current)) {
      const name = current.label.text;
      if (!uniques.has(name)) {
        uniques.set(name, true);
        entries.push({
          name,
          kindModifiers: "" /* none */,
          kind: "label" /* label */,
          sortText: SortText.LocationPriority
        });
      }
    }
    current = current.parent;
  }
  return entries;
}
function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) {
  if (entryId.source === "SwitchCases/" /* SwitchCases */) {
    return { type: "cases" };
  }
  if (entryId.data) {
    const autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host);
    if (autoImport) {
      const { contextToken: contextToken2, previousToken: previousToken2 } = getRelevantTokens(position, sourceFile);
      return {
        type: "symbol",
        symbol: autoImport.symbol,
        location: getTouchingPropertyName(sourceFile, position),
        previousToken: previousToken2,
        contextToken: contextToken2,
        isJsxInitializer: false,
        isTypeOnlyLocation: false,
        origin: autoImport.origin
      };
    }
  }
  const compilerOptions = program.getCompilerOptions();
  const completionData = getCompletionData(
    program,
    log,
    sourceFile,
    compilerOptions,
    position,
    { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true },
    entryId,
    host,
    /*formatContext*/
    void 0
  );
  if (!completionData) {
    return { type: "none" };
  }
  if (completionData.kind !== 0 /* Data */) {
    return { type: "request", request: completionData };
  }
  const { symbols, literals, location, completionKind, symbolToOriginInfoMap, contextToken, previousToken, isJsxInitializer, isTypeOnlyLocation } = completionData;
  const literal = find(literals, (l) => completionNameForLiteral(sourceFile, preferences, l) === entryId.name);
  if (literal !== void 0) return { type: "literal", literal };
  return firstDefined(symbols, (symbol, index) => {
    const origin = symbolToOriginInfoMap[index];
    const info = getCompletionEntryDisplayNameForSymbol(symbol, getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected);
    return info && info.name === entryId.name && (entryId.source === "ClassMemberSnippet/" /* ClassMemberSnippet */ && symbol.flags & 106500 /* ClassMember */ || entryId.source === "ObjectLiteralMethodSnippet/" /* ObjectLiteralMethodSnippet */ && symbol.flags & (4 /* Property */ | 8192 /* Method */) || getSourceFromOrigin(origin) === entryId.source || entryId.source === "ObjectLiteralMemberWithComma/" /* ObjectLiteralMemberWithComma */) ? { type: "symbol", symbol, location, origin, contextToken, previousToken, isJsxInitializer, isTypeOnlyLocation } : void 0;
  }) || { type: "none" };
}
function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) {
  const typeChecker = program.getTypeChecker();
  const compilerOptions = program.getCompilerOptions();
  const { name, source, data } = entryId;
  const { previousToken, contextToken } = getRelevantTokens(position, sourceFile);
  if (isInString(sourceFile, position, previousToken)) {
    return ts_Completions_StringCompletions_exports.getStringLiteralCompletionDetails(name, sourceFile, position, previousToken, program, host, cancellationToken, preferences);
  }
  const symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences);
  switch (symbolCompletion.type) {
    case "request": {
      const { request } = symbolCompletion;
      switch (request.kind) {
        case 1 /* JsDocTagName */:
          return ts_JsDoc_exports.getJSDocTagNameCompletionDetails(name);
        case 2 /* JsDocTag */:
          return ts_JsDoc_exports.getJSDocTagCompletionDetails(name);
        case 3 /* JsDocParameterName */:
          return ts_JsDoc_exports.getJSDocParameterNameCompletionDetails(name);
        case 4 /* Keywords */:
          return some(request.keywordCompletions, (c) => c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */, 5 /* keyword */) : void 0;
        default:
          return Debug.assertNever(request);
      }
    }
    case "symbol": {
      const { symbol, location, contextToken: contextToken2, origin, previousToken: previousToken2 } = symbolCompletion;
      const { codeActions, sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken2, formatContext, preferences, data, source, cancellationToken);
      const symbolName2 = originIsComputedPropertyName(origin) ? origin.symbolName : symbol.name;
      return createCompletionDetailsForSymbol(symbol, symbolName2, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay);
    }
    case "literal": {
      const { literal } = symbolCompletion;
      return createSimpleDetails(completionNameForLiteral(sourceFile, preferences, literal), "string" /* string */, typeof literal === "string" ? 8 /* stringLiteral */ : 7 /* numericLiteral */);
    }
    case "cases": {
      const snippets = getExhaustiveCaseSnippets(
        contextToken.parent,
        sourceFile,
        preferences,
        program.getCompilerOptions(),
        host,
        program,
        /*formatContext*/
        void 0
      );
      if (snippets == null ? void 0 : snippets.importAdder.hasFixes()) {
        const { entry, importAdder } = snippets;
        const changes = ts_textChanges_exports.ChangeTracker.with(
          { host, formatContext, preferences },
          importAdder.writeFixes
        );
        return {
          name: entry.name,
          kind: "" /* unknown */,
          kindModifiers: "",
          displayParts: [],
          sourceDisplay: void 0,
          codeActions: [{
            changes,
            description: diagnosticToString([Diagnostics.Includes_imports_of_types_referenced_by_0, name])
          }]
        };
      }
      return {
        name,
        kind: "" /* unknown */,
        kindModifiers: "",
        displayParts: [],
        sourceDisplay: void 0
      };
    }
    case "none":
      return allKeywordsCompletions().some((c) => c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */, 5 /* keyword */) : void 0;
    default:
      Debug.assertNever(symbolCompletion);
  }
}
function createSimpleDetails(name, kind, kind2) {
  return createCompletionDetails(name, "" /* none */, kind, [displayPart(name, kind2)]);
}
function createCompletionDetailsForSymbol(symbol, name, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) {
  const { displayParts, documentation, symbolKind, tags } = checker.runWithCancellationToken(cancellationToken, (checker2) => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker2, symbol, sourceFile, location, location, 7 /* All */));
  return createCompletionDetails(name, ts_SymbolDisplay_exports.getSymbolModifiers(checker, symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay);
}
function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) {
  return { name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source, sourceDisplay: source };
}
function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source, cancellationToken) {
  if (data == null ? void 0 : data.moduleSpecifier) {
    if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken, sourceFile).replacementSpan) {
      return { codeActions: void 0, sourceDisplay: [textPart(data.moduleSpecifier)] };
    }
  }
  if (source === "ClassMemberSnippet/" /* ClassMemberSnippet */) {
    const { importAdder, eraseRange } = getEntryForMemberCompletion(
      host,
      program,
      compilerOptions,
      preferences,
      name,
      symbol,
      location,
      position,
      contextToken,
      formatContext
    );
    if ((importAdder == null ? void 0 : importAdder.hasFixes()) || eraseRange) {
      const changes = ts_textChanges_exports.ChangeTracker.with(
        { host, formatContext, preferences },
        (tracker) => {
          if (importAdder) {
            importAdder.writeFixes(tracker);
          }
          if (eraseRange) {
            tracker.deleteRange(sourceFile, eraseRange);
          }
        }
      );
      return {
        sourceDisplay: void 0,
        codeActions: [{
          changes,
          description: (importAdder == null ? void 0 : importAdder.hasFixes()) ? diagnosticToString([Diagnostics.Includes_imports_of_types_referenced_by_0, name]) : diagnosticToString([Diagnostics.Update_modifiers_of_0, name])
        }]
      };
    }
  }
  if (originIsTypeOnlyAlias(origin)) {
    const codeAction2 = ts_codefix_exports.getPromoteTypeOnlyCompletionAction(
      sourceFile,
      origin.declaration.name,
      program,
      host,
      formatContext,
      preferences
    );
    Debug.assertIsDefined(codeAction2, "Expected to have a code action for promoting type-only alias");
    return { codeActions: [codeAction2], sourceDisplay: void 0 };
  }
  if (source === "ObjectLiteralMemberWithComma/" /* ObjectLiteralMemberWithComma */ && contextToken) {
    const changes = ts_textChanges_exports.ChangeTracker.with(
      { host, formatContext, preferences },
      (tracker) => tracker.insertText(sourceFile, contextToken.end, ",")
    );
    if (changes) {
      return {
        sourceDisplay: void 0,
        codeActions: [{
          changes,
          description: diagnosticToString([Diagnostics.Add_missing_comma_for_object_member_completion_0, name])
        }]
      };
    }
  }
  if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) {
    return { codeActions: void 0, sourceDisplay: void 0 };
  }
  const checker = origin.isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker();
  const { moduleSymbol } = origin;
  const targetSymbol = checker.getMergedSymbol(skipAlias(symbol.exportSymbol || symbol, checker));
  const isJsxOpeningTagName = (contextToken == null ? void 0 : contextToken.kind) === 30 /* LessThanToken */ && isJsxOpeningLikeElement(contextToken.parent);
  const { moduleSpecifier, codeAction } = ts_codefix_exports.getImportCompletionAction(
    targetSymbol,
    moduleSymbol,
    data == null ? void 0 : data.exportMapKey,
    sourceFile,
    name,
    isJsxOpeningTagName,
    host,
    program,
    formatContext,
    previousToken && isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position,
    preferences,
    cancellationToken
  );
  Debug.assert(!(data == null ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier);
  return { sourceDisplay: [textPart(moduleSpecifier)], codeActions: [codeAction] };
}
function getCompletionEntrySymbol(program, log, sourceFile, position, entryId, host, preferences) {
  const completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences);
  return completion.type === "symbol" ? completion.symbol : void 0;
}
var CompletionKind = /* @__PURE__ */ ((CompletionKind2) => {
  CompletionKind2[CompletionKind2["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration";
  CompletionKind2[CompletionKind2["Global"] = 1] = "Global";
  CompletionKind2[CompletionKind2["PropertyAccess"] = 2] = "PropertyAccess";
  CompletionKind2[CompletionKind2["MemberLike"] = 3] = "MemberLike";
  CompletionKind2[CompletionKind2["String"] = 4] = "String";
  CompletionKind2[CompletionKind2["None"] = 5] = "None";
  return CompletionKind2;
})(CompletionKind || {});
function getRecommendedCompletion(previousToken, contextualType, checker) {
  return firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), (type) => {
    const symbol = type && type.symbol;
    return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !isAbstractConstructorSymbol(symbol)) ? getFirstSymbolInChain(symbol, previousToken, checker) : void 0;
  });
}
function getContextualType(previousToken, position, sourceFile, checker) {
  const { parent: parent2 } = previousToken;
  switch (previousToken.kind) {
    case 80 /* Identifier */:
      return getContextualTypeFromParent(previousToken, checker);
    case 64 /* EqualsToken */:
      switch (parent2.kind) {
        case 260 /* VariableDeclaration */:
          return checker.getContextualType(parent2.initializer);
        // TODO: GH#18217
        case 226 /* BinaryExpression */:
          return checker.getTypeAtLocation(parent2.left);
        case 291 /* JsxAttribute */:
          return checker.getContextualTypeForJsxAttribute(parent2);
        default:
          return void 0;
      }
    case 105 /* NewKeyword */:
      return checker.getContextualType(parent2);
    case 84 /* CaseKeyword */:
      const caseClause = tryCast(parent2, isCaseClause);
      return caseClause ? getSwitchedType(caseClause, checker) : void 0;
    case 19 /* OpenBraceToken */:
      return isJsxExpression(parent2) && !isJsxElement(parent2.parent) && !isJsxFragment(parent2.parent) ? checker.getContextualTypeForJsxAttribute(parent2.parent) : void 0;
    default:
      const argInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(previousToken, position, sourceFile, checker);
      return argInfo ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex) : isEqualityOperatorKind(previousToken.kind) && isBinaryExpression(parent2) && isEqualityOperatorKind(parent2.operatorToken.kind) ? (
        // completion at `x ===/**/` should be for the right side
        checker.getTypeAtLocation(parent2.left)
      ) : checker.getContextualType(previousToken, 4 /* Completions */) || checker.getContextualType(previousToken);
  }
}
function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) {
  const chain = checker.getAccessibleSymbolChain(
    symbol,
    enclosingDeclaration,
    /*meaning*/
    -1 /* All */,
    /*useOnlyExternalAliasing*/
    false
  );
  if (chain) return first(chain);
  return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
  var _a;
  return !!((_a = symbol.declarations) == null ? void 0 : _a.some((d) => d.kind === 307 /* SourceFile */));
}
function getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, detailsEntryId, host, formatContext, cancellationToken) {
  const typeChecker = program.getTypeChecker();
  const inCheckedFile = isCheckedFile(sourceFile, compilerOptions);
  let start = timestamp();
  let currentToken = getTokenAtPosition(sourceFile, position);
  log("getCompletionData: Get current token: " + (timestamp() - start));
  start = timestamp();
  const insideComment = isInComment(sourceFile, position, currentToken);
  log("getCompletionData: Is inside comment: " + (timestamp() - start));
  let insideJsDocTagTypeExpression = false;
  let insideJsDocImportTag = false;
  let isInSnippetScope = false;
  if (insideComment) {
    if (hasDocComment(sourceFile, position)) {
      if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
        return { kind: 1 /* JsDocTagName */ };
      } else {
        const lineStart = getLineStartPositionForPosition(position, sourceFile);
        if (!/[^*|\s(/)]/.test(sourceFile.text.substring(lineStart, position))) {
          return { kind: 2 /* JsDocTag */ };
        }
      }
    }
    const tag = getJsDocTagAtPosition(currentToken, position);
    if (tag) {
      if (tag.tagName.pos <= position && position <= tag.tagName.end) {
        return { kind: 1 /* JsDocTagName */ };
      }
      if (isJSDocImportTag(tag)) {
        insideJsDocImportTag = true;
      } else {
        const typeExpression = tryGetTypeExpressionFromTag(tag);
        if (typeExpression) {
          currentToken = getTokenAtPosition(sourceFile, position);
          if (!currentToken || !isDeclarationName(currentToken) && (currentToken.parent.kind !== 348 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken)) {
            insideJsDocTagTypeExpression = isCurrentlyEditingNode(typeExpression);
          }
        }
        if (!insideJsDocTagTypeExpression && isJSDocParameterTag(tag) && (nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) {
          return { kind: 3 /* JsDocParameterName */, tag };
        }
      }
    }
    if (!insideJsDocTagTypeExpression && !insideJsDocImportTag) {
      log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment.");
      return void 0;
    }
  }
  start = timestamp();
  const isJsOnlyLocation = !insideJsDocTagTypeExpression && !insideJsDocImportTag && isSourceFileJS(sourceFile);
  const tokens = getRelevantTokens(position, sourceFile);
  const previousToken = tokens.previousToken;
  let contextToken = tokens.contextToken;
  log("getCompletionData: Get previous token: " + (timestamp() - start));
  let node = currentToken;
  let propertyAccessToConvert;
  let isRightOfDot = false;
  let isRightOfQuestionDot = false;
  let isRightOfOpenTag = false;
  let isStartingCloseTag = false;
  let isJsxInitializer = false;
  let isJsxIdentifierExpected = false;
  let importStatementCompletion;
  let location = getTouchingPropertyName(sourceFile, position);
  let keywordFilters = 0 /* None */;
  let isNewIdentifierLocation = false;
  let flags = 0 /* None */;
  let defaultCommitCharacters;
  if (contextToken) {
    const importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken, sourceFile);
    if (importStatementCompletionInfo.keywordCompletion) {
      if (importStatementCompletionInfo.isKeywordOnlyCompletion) {
        return {
          kind: 4 /* Keywords */,
          keywordCompletions: [keywordToCompletionEntry(importStatementCompletionInfo.keywordCompletion)],
          isNewIdentifierLocation: importStatementCompletionInfo.isNewIdentifierLocation
        };
      }
      keywordFilters = keywordFiltersFromSyntaxKind(importStatementCompletionInfo.keywordCompletion);
    }
    if (importStatementCompletionInfo.replacementSpan && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) {
      flags |= 2 /* IsImportStatementCompletion */;
      importStatementCompletion = importStatementCompletionInfo;
      isNewIdentifierLocation = importStatementCompletionInfo.isNewIdentifierLocation;
    }
    if (!importStatementCompletionInfo.replacementSpan && isCompletionListBlocker(contextToken)) {
      log("Returning an empty list because completion was requested in an invalid position.");
      return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, computeCommitCharactersAndIsNewIdentifier().isNewIdentifierLocation) : void 0;
    }
    let parent2 = contextToken.parent;
    if (contextToken.kind === 25 /* DotToken */ || contextToken.kind === 29 /* QuestionDotToken */) {
      isRightOfDot = contextToken.kind === 25 /* DotToken */;
      isRightOfQuestionDot = contextToken.kind === 29 /* QuestionDotToken */;
      switch (parent2.kind) {
        case 211 /* PropertyAccessExpression */:
          propertyAccessToConvert = parent2;
          node = propertyAccessToConvert.expression;
          const leftmostAccessExpression = getLeftmostAccessExpression(propertyAccessToConvert);
          if (nodeIsMissing(leftmostAccessExpression) || (isCallExpression(node) || isFunctionLike(node)) && node.end === contextToken.pos && node.getChildCount(sourceFile) && last(node.getChildren(sourceFile)).kind !== 22 /* CloseParenToken */) {
            return void 0;
          }
          break;
        case 166 /* QualifiedName */:
          node = parent2.left;
          break;
        case 267 /* ModuleDeclaration */:
          node = parent2.name;
          break;
        case 205 /* ImportType */:
          node = parent2;
          break;
        case 236 /* MetaProperty */:
          node = parent2.getFirstToken(sourceFile);
          Debug.assert(node.kind === 102 /* ImportKeyword */ || node.kind === 105 /* NewKeyword */);
          break;
        default:
          return void 0;
      }
    } else if (!importStatementCompletion) {
      if (parent2 && parent2.kind === 211 /* PropertyAccessExpression */) {
        contextToken = parent2;
        parent2 = parent2.parent;
      }
      if (currentToken.parent === location) {
        switch (currentToken.kind) {
          case 32 /* GreaterThanToken */:
            if (currentToken.parent.kind === 284 /* JsxElement */ || currentToken.parent.kind === 286 /* JsxOpeningElement */) {
              location = currentToken;
            }
            break;
          case 44 /* SlashToken */:
            if (currentToken.parent.kind === 285 /* JsxSelfClosingElement */) {
              location = currentToken;
            }
            break;
        }
      }
      switch (parent2.kind) {
        case 287 /* JsxClosingElement */:
          if (contextToken.kind === 44 /* SlashToken */) {
            isStartingCloseTag = true;
            location = contextToken;
          }
          break;
        case 226 /* BinaryExpression */:
          if (!binaryExpressionMayBeOpenTag(parent2)) {
            break;
          }
        // falls through
        case 285 /* JsxSelfClosingElement */:
        case 284 /* JsxElement */:
        case 286 /* JsxOpeningElement */:
          isJsxIdentifierExpected = true;
          if (contextToken.kind === 30 /* LessThanToken */) {
            isRightOfOpenTag = true;
            location = contextToken;
          }
          break;
        case 294 /* JsxExpression */:
        case 293 /* JsxSpreadAttribute */:
          if (previousToken.kind === 20 /* CloseBraceToken */ || previousToken.kind === 80 /* Identifier */ && previousToken.parent.kind === 291 /* JsxAttribute */) {
            isJsxIdentifierExpected = true;
          }
          break;
        case 291 /* JsxAttribute */:
          if (parent2.initializer === previousToken && previousToken.end < position) {
            isJsxIdentifierExpected = true;
            break;
          }
          switch (previousToken.kind) {
            case 64 /* EqualsToken */:
              isJsxInitializer = true;
              break;
            case 80 /* Identifier */:
              isJsxIdentifierExpected = true;
              if (parent2 !== previousToken.parent && !parent2.initializer && findChildOfKind(parent2, 64 /* EqualsToken */, sourceFile)) {
                isJsxInitializer = previousToken;
              }
          }
          break;
      }
    }
  }
  const semanticStart = timestamp();
  let completionKind = 5 /* None */;
  let hasUnresolvedAutoImports = false;
  let symbols = [];
  let importSpecifierResolver;
  const symbolToOriginInfoMap = [];
  const symbolToSortTextMap = [];
  const seenPropertySymbols = /* @__PURE__ */ new Set();
  const isTypeOnlyLocation = isTypeOnlyCompletion();
  const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson) => {
    return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host);
  });
  if (isRightOfDot || isRightOfQuestionDot) {
    getTypeScriptMemberSymbols();
  } else if (isRightOfOpenTag) {
    symbols = typeChecker.getJsxIntrinsicTagNamesAt(location);
    Debug.assertEachIsDefined(symbols, "getJsxIntrinsicTagNames() should all be defined");
    tryGetGlobalSymbols();
    completionKind = 1 /* Global */;
    keywordFilters = 0 /* None */;
  } else if (isStartingCloseTag) {
    const tagName = contextToken.parent.parent.openingElement.tagName;
    const tagSymbol = typeChecker.getSymbolAtLocation(tagName);
    if (tagSymbol) {
      symbols = [tagSymbol];
    }
    completionKind = 1 /* Global */;
    keywordFilters = 0 /* None */;
  } else {
    if (!tryGetGlobalSymbols()) {
      return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, isNewIdentifierLocation) : void 0;
    }
  }
  log("getCompletionData: Semantic work: " + (timestamp() - semanticStart));
  const contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker);
  const isLiteralExpected = !tryCast(previousToken, isStringLiteralLike) && !isJsxIdentifierExpected;
  const literals = !isLiteralExpected ? [] : mapDefined(
    contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]),
    (t) => t.isLiteral() && !(t.flags & 1024 /* EnumLiteral */) ? t.value : void 0
  );
  const recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
  return {
    kind: 0 /* Data */,
    symbols,
    completionKind,
    isInSnippetScope,
    propertyAccessToConvert,
    isNewIdentifierLocation,
    location,
    keywordFilters,
    literals,
    symbolToOriginInfoMap,
    recommendedCompletion,
    previousToken,
    contextToken,
    isJsxInitializer,
    insideJsDocTagTypeExpression,
    symbolToSortTextMap,
    isTypeOnlyLocation,
    isJsxIdentifierExpected,
    isRightOfOpenTag,
    isRightOfDotOrQuestionDot: isRightOfDot || isRightOfQuestionDot,
    importStatementCompletion,
    hasUnresolvedAutoImports,
    flags,
    defaultCommitCharacters
  };
  function isTagWithTypeExpression(tag) {
    switch (tag.kind) {
      case 341 /* JSDocParameterTag */:
      case 348 /* JSDocPropertyTag */:
      case 342 /* JSDocReturnTag */:
      case 344 /* JSDocTypeTag */:
      case 346 /* JSDocTypedefTag */:
      case 349 /* JSDocThrowsTag */:
      case 350 /* JSDocSatisfiesTag */:
        return true;
      case 345 /* JSDocTemplateTag */:
        return !!tag.constraint;
      default:
        return false;
    }
  }
  function tryGetTypeExpressionFromTag(tag) {
    if (isTagWithTypeExpression(tag)) {
      const typeExpression = isJSDocTemplateTag(tag) ? tag.constraint : tag.typeExpression;
      return typeExpression && typeExpression.kind === 309 /* JSDocTypeExpression */ ? typeExpression : void 0;
    }
    if (isJSDocAugmentsTag(tag) || isJSDocImplementsTag(tag)) {
      return tag.class;
    }
    return void 0;
  }
  function getTypeScriptMemberSymbols() {
    completionKind = 2 /* PropertyAccess */;
    const isImportType = isLiteralImportTypeNode(node);
    const isTypeLocation = isImportType && !node.isTypeOf || isPartOfTypeNode(node.parent) || isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
    const isRhsOfImportDeclaration = isInRightSideOfInternalImportEqualsDeclaration(node);
    if (isEntityName(node) || isImportType || isPropertyAccessExpression(node)) {
      const isNamespaceName = isModuleDeclaration(node.parent);
      if (isNamespaceName) {
        isNewIdentifierLocation = true;
        defaultCommitCharacters = [];
      }
      let symbol = typeChecker.getSymbolAtLocation(node);
      if (symbol) {
        symbol = skipAlias(symbol, typeChecker);
        if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) {
          const exportedSymbols = typeChecker.getExportsOfModule(symbol);
          Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined");
          const isValidValueAccess = (symbol2) => typeChecker.isValidPropertyAccess(isImportType ? node : node.parent, symbol2.name);
          const isValidTypeAccess = (symbol2) => symbolCanBeReferencedAtTypeLocation(symbol2, typeChecker);
          const isValidAccess = isNamespaceName ? (symbol2) => {
            var _a;
            return !!(symbol2.flags & 1920 /* Namespace */) && !((_a = symbol2.declarations) == null ? void 0 : _a.every((d) => d.parent === node.parent));
          } : isRhsOfImportDeclaration ? (
            // Any kind is allowed when dotting off namespace in internal import equals declaration
            (symbol2) => isValidTypeAccess(symbol2) || isValidValueAccess(symbol2)
          ) : isTypeLocation || insideJsDocTagTypeExpression ? isValidTypeAccess : isValidValueAccess;
          for (const exportedSymbol of exportedSymbols) {
            if (isValidAccess(exportedSymbol)) {
              symbols.push(exportedSymbol);
            }
          }
          if (!isTypeLocation && !insideJsDocTagTypeExpression && symbol.declarations && symbol.declarations.some((d) => d.kind !== 307 /* SourceFile */ && d.kind !== 267 /* ModuleDeclaration */ && d.kind !== 266 /* EnumDeclaration */)) {
            let type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType();
            let insertQuestionDot = false;
            if (type.isNullableType()) {
              const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false;
              if (canCorrectToQuestionDot || isRightOfQuestionDot) {
                type = type.getNonNullableType();
                if (canCorrectToQuestionDot) {
                  insertQuestionDot = true;
                }
              }
            }
            addTypeProperties(type, !!(node.flags & 65536 /* AwaitContext */), insertQuestionDot);
          }
          return;
        }
      }
    }
    if (!isTypeLocation || isInTypeQuery(node)) {
      typeChecker.tryGetThisTypeAt(
        node,
        /*includeGlobalThis*/
        false
      );
      let type = typeChecker.getTypeAtLocation(node).getNonOptionalType();
      if (!isTypeLocation) {
        let insertQuestionDot = false;
        if (type.isNullableType()) {
          const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false;
          if (canCorrectToQuestionDot || isRightOfQuestionDot) {
            type = type.getNonNullableType();
            if (canCorrectToQuestionDot) {
              insertQuestionDot = true;
            }
          }
        }
        addTypeProperties(type, !!(node.flags & 65536 /* AwaitContext */), insertQuestionDot);
      } else {
        addTypeProperties(
          type.getNonNullableType(),
          /*insertAwait*/
          false,
          /*insertQuestionDot*/
          false
        );
      }
    }
  }
  function addTypeProperties(type, insertAwait, insertQuestionDot) {
    if (type.getStringIndexType()) {
      isNewIdentifierLocation = true;
      defaultCommitCharacters = [];
    }
    if (isRightOfQuestionDot && some(type.getCallSignatures())) {
      isNewIdentifierLocation = true;
      defaultCommitCharacters ?? (defaultCommitCharacters = allCommitCharacters);
    }
    const propertyAccess = node.kind === 205 /* ImportType */ ? node : node.parent;
    if (inCheckedFile) {
      for (const symbol of type.getApparentProperties()) {
        if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) {
          addPropertySymbol(
            symbol,
            /*insertAwait*/
            false,
            insertQuestionDot
          );
        }
      }
    } else {
      symbols.push(...filter(getPropertiesForCompletion(type, typeChecker), (s) => typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s)));
    }
    if (insertAwait && preferences.includeCompletionsWithInsertText) {
      const promiseType = typeChecker.getPromisedTypeOfPromise(type);
      if (promiseType) {
        for (const symbol of promiseType.getApparentProperties()) {
          if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, promiseType, symbol)) {
            addPropertySymbol(
              symbol,
              /*insertAwait*/
              true,
              insertQuestionDot
            );
          }
        }
      }
    }
  }
  function addPropertySymbol(symbol, insertAwait, insertQuestionDot) {
    var _a;
    const computedPropertyName = firstDefined(symbol.declarations, (decl) => tryCast(getNameOfDeclaration(decl), isComputedPropertyName));
    if (computedPropertyName) {
      const leftMostName = getLeftMostName(computedPropertyName.expression);
      const nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName);
      const firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker);
      const firstAccessibleSymbolId = firstAccessibleSymbol && getSymbolId(firstAccessibleSymbol);
      if (firstAccessibleSymbolId && addToSeen(seenPropertySymbols, firstAccessibleSymbolId)) {
        const index = symbols.length;
        symbols.push(firstAccessibleSymbol);
        const moduleSymbol = firstAccessibleSymbol.parent;
        if (!moduleSymbol || !isExternalModuleSymbol(moduleSymbol) || typeChecker.tryGetMemberInModuleExportsAndProperties(firstAccessibleSymbol.name, moduleSymbol) !== firstAccessibleSymbol) {
          symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) };
        } else {
          const fileName = isExternalModuleNameRelative(stripQuotes(moduleSymbol.name)) ? (_a = getSourceFileOfModule(moduleSymbol)) == null ? void 0 : _a.fileName : void 0;
          const { moduleSpecifier } = (importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo(
            [{
              exportKind: 0 /* Named */,
              moduleFileName: fileName,
              isFromPackageJson: false,
              moduleSymbol,
              symbol: firstAccessibleSymbol,
              targetFlags: skipAlias(firstAccessibleSymbol, typeChecker).flags
            }],
            position,
            isValidTypeOnlyAliasUseSite(location)
          ) || {};
          if (moduleSpecifier) {
            const origin = {
              kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */),
              moduleSymbol,
              isDefaultExport: false,
              symbolName: firstAccessibleSymbol.name,
              exportName: firstAccessibleSymbol.name,
              fileName,
              moduleSpecifier
            };
            symbolToOriginInfoMap[index] = origin;
          }
        }
      } else if (preferences.includeCompletionsWithInsertText) {
        if (firstAccessibleSymbolId && seenPropertySymbols.has(firstAccessibleSymbolId)) {
          return;
        }
        addSymbolOriginInfo(symbol);
        addSymbolSortInfo(symbol);
        symbols.push(symbol);
      }
    } else {
      addSymbolOriginInfo(symbol);
      addSymbolSortInfo(symbol);
      symbols.push(symbol);
    }
    function addSymbolSortInfo(symbol2) {
      if (isStaticProperty(symbol2)) {
        symbolToSortTextMap[getSymbolId(symbol2)] = SortText.LocalDeclarationPriority;
      }
    }
    function addSymbolOriginInfo(symbol2) {
      if (preferences.includeCompletionsWithInsertText) {
        if (insertAwait && addToSeen(seenPropertySymbols, getSymbolId(symbol2))) {
          symbolToOriginInfoMap[symbols.length] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) };
        } else if (insertQuestionDot) {
          symbolToOriginInfoMap[symbols.length] = { kind: 16 /* Nullable */ };
        }
      }
    }
    function getNullableSymbolOriginInfoKind(kind) {
      return insertQuestionDot ? kind | 16 /* Nullable */ : kind;
    }
  }
  function getLeftMostName(e) {
    return isIdentifier(e) ? e : isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : void 0;
  }
  function tryGetGlobalSymbols() {
    const result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() || tryGetObjectLikeCompletionSymbols() || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetImportAttributesCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() || tryGetClassLikeCompletionSymbols() || tryGetJsxCompletionSymbols() || (getGlobalCompletions(), 1 /* Success */);
    return result === 1 /* Success */;
  }
  function tryGetConstructorCompletion() {
    if (!tryGetConstructorLikeCompletionContainer(contextToken)) return 0 /* Continue */;
    completionKind = 5 /* None */;
    isNewIdentifierLocation = true;
    keywordFilters = 4 /* ConstructorParameterKeywords */;
    return 1 /* Success */;
  }
  function tryGetJsxCompletionSymbols() {
    const jsxContainer = tryGetContainingJsxElement(contextToken);
    const attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes);
    if (!attrsType) return 0 /* Continue */;
    const completionsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes, 4 /* Completions */);
    symbols = concatenate(symbols, filterJsxAttributes(getPropertiesForObjectExpression(attrsType, completionsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties));
    setSortTextToOptionalMember();
    completionKind = 3 /* MemberLike */;
    isNewIdentifierLocation = false;
    return 1 /* Success */;
  }
  function tryGetImportCompletionSymbols() {
    if (!importStatementCompletion) return 0 /* Continue */;
    isNewIdentifierLocation = true;
    collectAutoImports();
    return 1 /* Success */;
  }
  function getGlobalCompletions() {
    keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */;
    completionKind = 1 /* Global */;
    ({ isNewIdentifierLocation, defaultCommitCharacters } = computeCommitCharactersAndIsNewIdentifier());
    if (previousToken !== contextToken) {
      Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
    }
    const adjustedPosition = previousToken !== contextToken ? previousToken.getStart() : position;
    const scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
    isInSnippetScope = isSnippetScope(scopeNode);
    const symbolMeanings = (isTypeOnlyLocation ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
    const typeOnlyAliasNeedsPromotion = previousToken && !isValidTypeOnlyAliasUseSite(previousToken);
    symbols = concatenate(symbols, typeChecker.getSymbolsInScope(scopeNode, symbolMeanings));
    Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined");
    for (let i = 0; i < symbols.length; i++) {
      const symbol = symbols[i];
      if (!typeChecker.isArgumentsSymbol(symbol) && !some(symbol.declarations, (d) => d.getSourceFile() === sourceFile)) {
        symbolToSortTextMap[getSymbolId(symbol)] = SortText.GlobalsOrKeywords;
      }
      if (typeOnlyAliasNeedsPromotion && !(symbol.flags & 111551 /* Value */)) {
        const typeOnlyAliasDeclaration = symbol.declarations && find(symbol.declarations, isTypeOnlyImportDeclaration);
        if (typeOnlyAliasDeclaration) {
          const origin = { kind: 64 /* TypeOnlyAlias */, declaration: typeOnlyAliasDeclaration };
          symbolToOriginInfoMap[i] = origin;
        }
      }
    }
    if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 307 /* SourceFile */) {
      const thisType = typeChecker.tryGetThisTypeAt(
        scopeNode,
        /*includeGlobalThis*/
        false,
        isClassLike(scopeNode.parent) ? scopeNode : void 0
      );
      if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) {
        for (const symbol of getPropertiesForCompletion(thisType, typeChecker)) {
          symbolToOriginInfoMap[symbols.length] = { kind: 1 /* ThisType */ };
          symbols.push(symbol);
          symbolToSortTextMap[getSymbolId(symbol)] = SortText.SuggestedClassMembers;
        }
      }
    }
    collectAutoImports();
    if (isTypeOnlyLocation) {
      keywordFilters = contextToken && isAssertionExpression(contextToken.parent) ? 6 /* TypeAssertionKeywords */ : 7 /* TypeKeywords */;
    }
  }
  function shouldOfferImportCompletions() {
    var _a;
    if (importStatementCompletion) return true;
    if (!preferences.includeCompletionsForModuleExports) return false;
    if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true;
    if (compilerOptionsIndicateEsModules(program.getCompilerOptions())) return true;
    return ((_a = program.getSymlinkCache) == null ? void 0 : _a.call(program).hasAnySymlinks()) || !!program.getCompilerOptions().paths || programContainsModules(program);
  }
  function isSnippetScope(scopeNode) {
    switch (scopeNode.kind) {
      case 307 /* SourceFile */:
      case 228 /* TemplateExpression */:
      case 294 /* JsxExpression */:
      case 241 /* Block */:
        return true;
      default:
        return isStatement(scopeNode);
    }
  }
  function isTypeOnlyCompletion() {
    return insideJsDocTagTypeExpression || insideJsDocImportTag || !!importStatementCompletion && isTypeOnlyImportOrExportDeclaration(location.parent) || !isContextTokenValueLocation(contextToken) && (isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker) || isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
  }
  function isContextTokenValueLocation(contextToken2) {
    return contextToken2 && (contextToken2.kind === 114 /* TypeOfKeyword */ && (contextToken2.parent.kind === 186 /* TypeQuery */ || isTypeOfExpression(contextToken2.parent)) || contextToken2.kind === 131 /* AssertsKeyword */ && contextToken2.parent.kind === 182 /* TypePredicate */);
  }
  function isContextTokenTypeLocation(contextToken2) {
    if (contextToken2) {
      const parentKind = contextToken2.parent.kind;
      switch (contextToken2.kind) {
        case 59 /* ColonToken */:
          return parentKind === 172 /* PropertyDeclaration */ || parentKind === 171 /* PropertySignature */ || parentKind === 169 /* Parameter */ || parentKind === 260 /* VariableDeclaration */ || isFunctionLikeKind(parentKind);
        case 64 /* EqualsToken */:
          return parentKind === 265 /* TypeAliasDeclaration */ || parentKind === 168 /* TypeParameter */;
        case 130 /* AsKeyword */:
          return parentKind === 234 /* AsExpression */;
        case 30 /* LessThanToken */:
          return parentKind === 183 /* TypeReference */ || parentKind === 216 /* TypeAssertionExpression */;
        case 96 /* ExtendsKeyword */:
          return parentKind === 168 /* TypeParameter */;
        case 152 /* SatisfiesKeyword */:
          return parentKind === 238 /* SatisfiesExpression */;
      }
    }
    return false;
  }
  function collectAutoImports() {
    var _a, _b;
    if (!shouldOfferImportCompletions()) return;
    Debug.assert(!(detailsEntryId == null ? void 0 : detailsEntryId.data), "Should not run 'collectAutoImports' when faster path is available via `data`");
    if (detailsEntryId && !detailsEntryId.source) {
      return;
    }
    flags |= 1 /* MayIncludeAutoImports */;
    const isAfterTypeOnlyImportSpecifierModifier = previousToken === contextToken && importStatementCompletion;
    const lowerCaseTokenText = isAfterTypeOnlyImportSpecifierModifier ? "" : previousToken && isIdentifier(previousToken) ? previousToken.text.toLowerCase() : "";
    const moduleSpecifierCache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host);
    const exportInfo = getExportInfoMap(sourceFile, host, program, preferences, cancellationToken);
    const packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) == null ? void 0 : _b.call(host);
    const packageJsonFilter = detailsEntryId ? void 0 : createPackageJsonImportFilter(sourceFile, preferences, host);
    resolvingModuleSpecifiers(
      "collectAutoImports",
      host,
      importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences)),
      program,
      position,
      preferences,
      !!importStatementCompletion,
      isValidTypeOnlyAliasUseSite(location),
      (context) => {
        exportInfo.search(
          sourceFile.path,
          /*preferCapitalized*/
          isRightOfOpenTag,
          (symbolName2, targetFlags) => {
            if (!isIdentifierText(symbolName2, getEmitScriptTarget(host.getCompilationSettings()))) return false;
            if (!detailsEntryId && isStringANonContextualKeyword(symbolName2)) return false;
            if (!isTypeOnlyLocation && !importStatementCompletion && !(targetFlags & 111551 /* Value */)) return false;
            if (isTypeOnlyLocation && !(targetFlags & (1536 /* Module */ | 788968 /* Type */))) return false;
            const firstChar = symbolName2.charCodeAt(0);
            if (isRightOfOpenTag && (firstChar < 65 /* A */ || firstChar > 90 /* Z */)) return false;
            if (detailsEntryId) return true;
            return charactersFuzzyMatchInString(symbolName2, lowerCaseTokenText);
          },
          (info, symbolName2, isFromAmbientModule, exportMapKey) => {
            if (detailsEntryId && !some(info, (i) => detailsEntryId.source === stripQuotes(i.moduleSymbol.name))) {
              return;
            }
            info = filter(info, isImportableExportInfo);
            if (!info.length) {
              return;
            }
            const result = context.tryResolve(info, isFromAmbientModule) || {};
            if (result === "failed") return;
            let exportInfo2 = info[0], moduleSpecifier;
            if (result !== "skipped") {
              ({ exportInfo: exportInfo2 = info[0], moduleSpecifier } = result);
            }
            const isDefaultExport = exportInfo2.exportKind === 1 /* Default */;
            const symbol = isDefaultExport && getLocalSymbolForExportDefault(Debug.checkDefined(exportInfo2.symbol)) || Debug.checkDefined(exportInfo2.symbol);
            pushAutoImportSymbol(symbol, {
              kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */,
              moduleSpecifier,
              symbolName: symbolName2,
              exportMapKey,
              exportName: exportInfo2.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : Debug.checkDefined(exportInfo2.symbol).name,
              fileName: exportInfo2.moduleFileName,
              isDefaultExport,
              moduleSymbol: exportInfo2.moduleSymbol,
              isFromPackageJson: exportInfo2.isFromPackageJson
            });
          }
        );
        hasUnresolvedAutoImports = context.skippedAny();
        flags |= context.resolvedAny() ? 8 /* ResolvedModuleSpecifiers */ : 0;
        flags |= context.resolvedBeyondLimit() ? 16 /* ResolvedModuleSpecifiersBeyondLimit */ : 0;
      }
    );
    function isImportableExportInfo(info) {
      return isImportable(
        info.isFromPackageJson ? packageJsonAutoImportProvider : program,
        sourceFile,
        tryCast(info.moduleSymbol.valueDeclaration, isSourceFile),
        info.moduleSymbol,
        preferences,
        packageJsonFilter,
        getModuleSpecifierResolutionHost(info.isFromPackageJson),
        moduleSpecifierCache
      );
    }
  }
  function pushAutoImportSymbol(symbol, origin) {
    const symbolId = getSymbolId(symbol);
    if (symbolToSortTextMap[symbolId] === SortText.GlobalsOrKeywords) {
      return;
    }
    symbolToOriginInfoMap[symbols.length] = origin;
    symbolToSortTextMap[symbolId] = importStatementCompletion ? SortText.LocationPriority : SortText.AutoImportSuggestions;
    symbols.push(symbol);
  }
  function collectObjectLiteralMethodSymbols(members, enclosingDeclaration) {
    if (isInJSFile(location)) {
      return;
    }
    members.forEach((member) => {
      if (!isObjectLiteralMethodSymbol(member)) {
        return;
      }
      const displayName = getCompletionEntryDisplayNameForSymbol(
        member,
        getEmitScriptTarget(compilerOptions),
        /*origin*/
        void 0,
        0 /* ObjectPropertyDeclaration */,
        /*jsxIdentifierExpected*/
        false
      );
      if (!displayName) {
        return;
      }
      const { name } = displayName;
      const entryProps = getEntryForObjectLiteralMethodCompletion(
        member,
        name,
        enclosingDeclaration,
        program,
        host,
        compilerOptions,
        preferences,
        formatContext
      );
      if (!entryProps) {
        return;
      }
      const origin = { kind: 128 /* ObjectLiteralMethod */, ...entryProps };
      flags |= 32 /* MayIncludeMethodSnippets */;
      symbolToOriginInfoMap[symbols.length] = origin;
      symbols.push(member);
    });
  }
  function isObjectLiteralMethodSymbol(symbol) {
    if (!(symbol.flags & (4 /* Property */ | 8192 /* Method */))) {
      return false;
    }
    return true;
  }
  function getScopeNode(initialToken, position2, sourceFile2) {
    let scope = initialToken;
    while (scope && !positionBelongsToNode(scope, position2, sourceFile2)) {
      scope = scope.parent;
    }
    return scope;
  }
  function isCompletionListBlocker(contextToken2) {
    const start2 = timestamp();
    const result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken2) || isSolelyIdentifierDefinitionLocation(contextToken2) || isDotOfNumericLiteral(contextToken2) || isInJsxText(contextToken2) || isBigIntLiteral(contextToken2);
    log("getCompletionsAtPosition: isCompletionListBlocker: " + (timestamp() - start2));
    return result;
  }
  function isInJsxText(contextToken2) {
    if (contextToken2.kind === 12 /* JsxText */) {
      return true;
    }
    if (contextToken2.kind === 32 /* GreaterThanToken */ && contextToken2.parent) {
      if (location === contextToken2.parent && (location.kind === 286 /* JsxOpeningElement */ || location.kind === 285 /* JsxSelfClosingElement */)) {
        return false;
      }
      if (contextToken2.parent.kind === 286 /* JsxOpeningElement */) {
        return location.parent.kind !== 286 /* JsxOpeningElement */;
      }
      if (contextToken2.parent.kind === 287 /* JsxClosingElement */ || contextToken2.parent.kind === 285 /* JsxSelfClosingElement */) {
        return !!contextToken2.parent.parent && contextToken2.parent.parent.kind === 284 /* JsxElement */;
      }
    }
    return false;
  }
  function computeCommitCharactersAndIsNewIdentifier() {
    if (contextToken) {
      const containingNodeKind = contextToken.parent.kind;
      const tokenKind = keywordForNode(contextToken);
      switch (tokenKind) {
        case 28 /* CommaToken */:
          switch (containingNodeKind) {
            case 213 /* CallExpression */:
            // func( a, |
            case 214 /* NewExpression */: {
              const expression = contextToken.parent.expression;
              if (getLineAndCharacterOfPosition(sourceFile, expression.end).line !== getLineAndCharacterOfPosition(sourceFile, position).line) {
                return { defaultCommitCharacters: noCommaCommitCharacters, isNewIdentifierLocation: true };
              }
              return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: true };
            }
            case 226 /* BinaryExpression */:
              return { defaultCommitCharacters: noCommaCommitCharacters, isNewIdentifierLocation: true };
            case 176 /* Constructor */:
            // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */
            case 184 /* FunctionType */:
            // var x: (s: string, list|
            case 210 /* ObjectLiteralExpression */:
              return { defaultCommitCharacters: [], isNewIdentifierLocation: true };
            case 209 /* ArrayLiteralExpression */:
              return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: true };
            default:
              return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false };
          }
        case 21 /* OpenParenToken */:
          switch (containingNodeKind) {
            case 213 /* CallExpression */:
            // func( |
            case 214 /* NewExpression */: {
              const expression = contextToken.parent.expression;
              if (getLineAndCharacterOfPosition(sourceFile, expression.end).line !== getLineAndCharacterOfPosition(sourceFile, position).line) {
                return { defaultCommitCharacters: noCommaCommitCharacters, isNewIdentifierLocation: true };
              }
              return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: true };
            }
            case 217 /* ParenthesizedExpression */:
              return { defaultCommitCharacters: noCommaCommitCharacters, isNewIdentifierLocation: true };
            case 176 /* Constructor */:
            // constructor( |
            case 196 /* ParenthesizedType */:
              return { defaultCommitCharacters: [], isNewIdentifierLocation: true };
            default:
              return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false };
          }
        case 23 /* OpenBracketToken */:
          switch (containingNodeKind) {
            case 209 /* ArrayLiteralExpression */:
            // [ |
            case 181 /* IndexSignature */:
            // [ | : string ]
            case 189 /* TupleType */:
            // [ | : string ]
            case 167 /* ComputedPropertyName */:
              return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: true };
            default:
              return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false };
          }
        case 144 /* ModuleKeyword */:
        // module |
        case 145 /* NamespaceKeyword */:
        // namespace |
        case 102 /* ImportKeyword */:
          return { defaultCommitCharacters: [], isNewIdentifierLocation: true };
        case 25 /* DotToken */:
          switch (containingNodeKind) {
            case 267 /* ModuleDeclaration */:
              return { defaultCommitCharacters: [], isNewIdentifierLocation: true };
            default:
              return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false };
          }
        case 19 /* OpenBraceToken */:
          switch (containingNodeKind) {
            case 263 /* ClassDeclaration */:
            // class A { |
            case 210 /* ObjectLiteralExpression */:
              return { defaultCommitCharacters: [], isNewIdentifierLocation: true };
            default:
              return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false };
          }
        case 64 /* EqualsToken */:
          switch (containingNodeKind) {
            case 260 /* VariableDeclaration */:
            // const x = a|
            case 226 /* BinaryExpression */:
              return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: true };
            default:
              return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false };
          }
        case 16 /* TemplateHead */:
          return {
            defaultCommitCharacters: allCommitCharacters,
            isNewIdentifierLocation: containingNodeKind === 228 /* TemplateExpression */
            // `aa ${|
          };
        case 17 /* TemplateMiddle */:
          return {
            defaultCommitCharacters: allCommitCharacters,
            isNewIdentifierLocation: containingNodeKind === 239 /* TemplateSpan */
            // `aa ${10} dd ${|
          };
        case 134 /* AsyncKeyword */:
          return containingNodeKind === 174 /* MethodDeclaration */ || containingNodeKind === 304 /* ShorthandPropertyAssignment */ ? { defaultCommitCharacters: [], isNewIdentifierLocation: true } : { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false };
        case 42 /* AsteriskToken */:
          return containingNodeKind === 174 /* MethodDeclaration */ ? { defaultCommitCharacters: [], isNewIdentifierLocation: true } : { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false };
      }
      if (isClassMemberCompletionKeyword(tokenKind)) {
        return { defaultCommitCharacters: [], isNewIdentifierLocation: true };
      }
    }
    return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false };
  }
  function isInStringOrRegularExpressionOrTemplateLiteral(contextToken2) {
    return (isRegularExpressionLiteral(contextToken2) || isStringTextContainingNode(contextToken2)) && (rangeContainsPositionExclusive(contextToken2, position) || position === contextToken2.end && (!!contextToken2.isUnterminated || isRegularExpressionLiteral(contextToken2)));
  }
  function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() {
    const typeLiteralNode = tryGetTypeLiteralNode(contextToken);
    if (!typeLiteralNode) return 0 /* Continue */;
    const intersectionTypeNode = isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : void 0;
    const containerTypeNode = intersectionTypeNode || typeLiteralNode;
    const containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker);
    if (!containerExpectedType) return 0 /* Continue */;
    const containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode);
    const members = getPropertiesForCompletion(containerExpectedType, typeChecker);
    const existingMembers = getPropertiesForCompletion(containerActualType, typeChecker);
    const existingMemberEscapedNames = /* @__PURE__ */ new Set();
    existingMembers.forEach((s) => existingMemberEscapedNames.add(s.escapedName));
    symbols = concatenate(symbols, filter(members, (s) => !existingMemberEscapedNames.has(s.escapedName)));
    completionKind = 0 /* ObjectPropertyDeclaration */;
    isNewIdentifierLocation = true;
    return 1 /* Success */;
  }
  function tryGetObjectLikeCompletionSymbols() {
    if ((contextToken == null ? void 0 : contextToken.kind) === 26 /* DotDotDotToken */) return 0 /* Continue */;
    const symbolsStartIndex = symbols.length;
    const objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken, position, sourceFile);
    if (!objectLikeContainer) return 0 /* Continue */;
    completionKind = 0 /* ObjectPropertyDeclaration */;
    let typeMembers;
    let existingMembers;
    if (objectLikeContainer.kind === 210 /* ObjectLiteralExpression */) {
      const instantiatedType = tryGetObjectLiteralContextualType(objectLikeContainer, typeChecker);
      if (instantiatedType === void 0) {
        if (objectLikeContainer.flags & 67108864 /* InWithStatement */) {
          return 2 /* Fail */;
        }
        return 0 /* Continue */;
      }
      const completionsType = typeChecker.getContextualType(objectLikeContainer, 4 /* Completions */);
      const hasStringIndexType = (completionsType || instantiatedType).getStringIndexType();
      const hasNumberIndextype = (completionsType || instantiatedType).getNumberIndexType();
      isNewIdentifierLocation = !!hasStringIndexType || !!hasNumberIndextype;
      typeMembers = getPropertiesForObjectExpression(instantiatedType, completionsType, objectLikeContainer, typeChecker);
      existingMembers = objectLikeContainer.properties;
      if (typeMembers.length === 0) {
        if (!hasNumberIndextype) {
          return 0 /* Continue */;
        }
      }
    } else {
      Debug.assert(objectLikeContainer.kind === 206 /* ObjectBindingPattern */);
      isNewIdentifierLocation = false;
      const rootDeclaration = getRootDeclaration(objectLikeContainer.parent);
      if (!isVariableLike(rootDeclaration)) return Debug.fail("Root declaration is not variable-like.");
      let canGetType = hasInitializer(rootDeclaration) || !!getEffectiveTypeAnnotationNode(rootDeclaration) || rootDeclaration.parent.parent.kind === 250 /* ForOfStatement */;
      if (!canGetType && rootDeclaration.kind === 169 /* Parameter */) {
        if (isExpression(rootDeclaration.parent)) {
          canGetType = !!typeChecker.getContextualType(rootDeclaration.parent);
        } else if (rootDeclaration.parent.kind === 174 /* MethodDeclaration */ || rootDeclaration.parent.kind === 178 /* SetAccessor */) {
          canGetType = isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent);
        }
      }
      if (canGetType) {
        const typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
        if (!typeForObject) return 2 /* Fail */;
        typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter((propertySymbol) => {
          return typeChecker.isPropertyAccessible(
            objectLikeContainer,
            /*isSuper*/
            false,
            /*isWrite*/
            false,
            typeForObject,
            propertySymbol
          );
        });
        existingMembers = objectLikeContainer.elements;
      }
    }
    if (typeMembers && typeMembers.length > 0) {
      const filteredMembers = filterObjectMembersList(typeMembers, Debug.checkDefined(existingMembers));
      symbols = concatenate(symbols, filteredMembers);
      setSortTextToOptionalMember();
      if (objectLikeContainer.kind === 210 /* ObjectLiteralExpression */ && preferences.includeCompletionsWithObjectLiteralMethodSnippets && preferences.includeCompletionsWithInsertText) {
        transformObjectLiteralMembersSortText(symbolsStartIndex);
        collectObjectLiteralMethodSymbols(filteredMembers, objectLikeContainer);
      }
    }
    return 1 /* Success */;
  }
  function tryGetImportOrExportClauseCompletionSymbols() {
    if (!contextToken) return 0 /* Continue */;
    const namedImportsOrExports = contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 28 /* CommaToken */ ? tryCast(contextToken.parent, isNamedImportsOrExports) : isTypeKeywordTokenOrIdentifier(contextToken) ? tryCast(contextToken.parent.parent, isNamedImportsOrExports) : void 0;
    if (!namedImportsOrExports) return 0 /* Continue */;
    if (!isTypeKeywordTokenOrIdentifier(contextToken)) {
      keywordFilters = 8 /* TypeKeyword */;
    }
    const { moduleSpecifier } = namedImportsOrExports.kind === 275 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent;
    if (!moduleSpecifier) {
      isNewIdentifierLocation = true;
      return namedImportsOrExports.kind === 275 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */;
    }
    const moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier);
    if (!moduleSpecifierSymbol) {
      isNewIdentifierLocation = true;
      return 2 /* Fail */;
    }
    completionKind = 3 /* MemberLike */;
    isNewIdentifierLocation = false;
    const exports2 = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol);
    const existing = new Set(namedImportsOrExports.elements.filter((n) => !isCurrentlyEditingNode(n)).map((n) => moduleExportNameTextEscaped(n.propertyName || n.name)));
    const uniques = exports2.filter((e) => e.escapedName !== "default" /* Default */ && !existing.has(e.escapedName));
    symbols = concatenate(symbols, uniques);
    if (!uniques.length) {
      keywordFilters = 0 /* None */;
    }
    return 1 /* Success */;
  }
  function tryGetImportAttributesCompletionSymbols() {
    if (contextToken === void 0) return 0 /* Continue */;
    const importAttributes = contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 28 /* CommaToken */ ? tryCast(contextToken.parent, isImportAttributes) : contextToken.kind === 59 /* ColonToken */ ? tryCast(contextToken.parent.parent, isImportAttributes) : void 0;
    if (importAttributes === void 0) return 0 /* Continue */;
    const existing = new Set(importAttributes.elements.map(getNameFromImportAttribute));
    symbols = filter(typeChecker.getTypeAtLocation(importAttributes).getApparentProperties(), (attr) => !existing.has(attr.escapedName));
    return 1 /* Success */;
  }
  function tryGetLocalNamedExportCompletionSymbols() {
    var _a;
    const namedExports = contextToken && (contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 28 /* CommaToken */) ? tryCast(contextToken.parent, isNamedExports) : void 0;
    if (!namedExports) {
      return 0 /* Continue */;
    }
    const localsContainer = findAncestor(namedExports, or(isSourceFile, isModuleDeclaration));
    completionKind = 5 /* None */;
    isNewIdentifierLocation = false;
    (_a = localsContainer.locals) == null ? void 0 : _a.forEach((symbol, name) => {
      var _a2, _b;
      symbols.push(symbol);
      if ((_b = (_a2 = localsContainer.symbol) == null ? void 0 : _a2.exports) == null ? void 0 : _b.has(name)) {
        symbolToSortTextMap[getSymbolId(symbol)] = SortText.OptionalMember;
      }
    });
    return 1 /* Success */;
  }
  function tryGetClassLikeCompletionSymbols() {
    const decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position);
    if (!decl) return 0 /* Continue */;
    completionKind = 3 /* MemberLike */;
    isNewIdentifierLocation = true;
    keywordFilters = contextToken.kind === 42 /* AsteriskToken */ ? 0 /* None */ : isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */;
    if (!isClassLike(decl)) return 1 /* Success */;
    const classElement = contextToken.kind === 27 /* SemicolonToken */ ? contextToken.parent.parent : contextToken.parent;
    let classElementModifierFlags = isClassElement(classElement) ? getEffectiveModifierFlags(classElement) : 0 /* None */;
    if (contextToken.kind === 80 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) {
      switch (contextToken.getText()) {
        case "private":
          classElementModifierFlags = classElementModifierFlags | 2 /* Private */;
          break;
        case "static":
          classElementModifierFlags = classElementModifierFlags | 256 /* Static */;
          break;
        case "override":
          classElementModifierFlags = classElementModifierFlags | 16 /* Override */;
          break;
      }
    }
    if (isClassStaticBlockDeclaration(classElement)) {
      classElementModifierFlags |= 256 /* Static */;
    }
    if (!(classElementModifierFlags & 2 /* Private */)) {
      const baseTypeNodes = isClassLike(decl) && classElementModifierFlags & 16 /* Override */ ? singleElementArray(getEffectiveBaseTypeNode(decl)) : getAllSuperTypeNodes(decl);
      const baseSymbols = flatMap(baseTypeNodes, (baseTypeNode) => {
        const type = typeChecker.getTypeAtLocation(baseTypeNode);
        return classElementModifierFlags & 256 /* Static */ ? (type == null ? void 0 : type.symbol) && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : type && typeChecker.getPropertiesOfType(type);
      });
      symbols = concatenate(symbols, filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags));
      forEach(symbols, (symbol, index) => {
        const declaration = symbol == null ? void 0 : symbol.valueDeclaration;
        if (declaration && isClassElement(declaration) && declaration.name && isComputedPropertyName(declaration.name)) {
          const origin = {
            kind: 512 /* ComputedPropertyName */,
            symbolName: typeChecker.symbolToString(symbol)
          };
          symbolToOriginInfoMap[index] = origin;
        }
      });
    }
    return 1 /* Success */;
  }
  function isConstructorParameterCompletion(node2) {
    return !!node2.parent && isParameter(node2.parent) && isConstructorDeclaration(node2.parent.parent) && (isParameterPropertyModifier(node2.kind) || isDeclarationName(node2));
  }
  function tryGetConstructorLikeCompletionContainer(contextToken2) {
    if (contextToken2) {
      const parent2 = contextToken2.parent;
      switch (contextToken2.kind) {
        case 21 /* OpenParenToken */:
        case 28 /* CommaToken */:
          return isConstructorDeclaration(contextToken2.parent) ? contextToken2.parent : void 0;
        default:
          if (isConstructorParameterCompletion(contextToken2)) {
            return parent2.parent;
          }
      }
    }
    return void 0;
  }
  function tryGetFunctionLikeBodyCompletionContainer(contextToken2) {
    if (contextToken2) {
      let prev;
      const container = findAncestor(contextToken2.parent, (node2) => {
        if (isClassLike(node2)) {
          return "quit";
        }
        if (isFunctionLikeDeclaration(node2) && prev === node2.body) {
          return true;
        }
        prev = node2;
        return false;
      });
      return container && container;
    }
  }
  function tryGetContainingJsxElement(contextToken2) {
    if (contextToken2) {
      const parent2 = contextToken2.parent;
      switch (contextToken2.kind) {
        case 32 /* GreaterThanToken */:
        // End of a type argument list
        case 31 /* LessThanSlashToken */:
        case 44 /* SlashToken */:
        case 80 /* Identifier */:
        case 211 /* PropertyAccessExpression */:
        case 292 /* JsxAttributes */:
        case 291 /* JsxAttribute */:
        case 293 /* JsxSpreadAttribute */:
          if (parent2 && (parent2.kind === 285 /* JsxSelfClosingElement */ || parent2.kind === 286 /* JsxOpeningElement */)) {
            if (contextToken2.kind === 32 /* GreaterThanToken */) {
              const precedingToken = findPrecedingToken(
                contextToken2.pos,
                sourceFile,
                /*startNode*/
                void 0
              );
              if (!parent2.typeArguments || precedingToken && precedingToken.kind === 44 /* SlashToken */) break;
            }
            return parent2;
          } else if (parent2.kind === 291 /* JsxAttribute */) {
            return parent2.parent.parent;
          }
          break;
        // The context token is the closing } or " of an attribute, which means
        // its parent is a JsxExpression, whose parent is a JsxAttribute,
        // whose parent is a JsxOpeningLikeElement
        case 11 /* StringLiteral */:
          if (parent2 && (parent2.kind === 291 /* JsxAttribute */ || parent2.kind === 293 /* JsxSpreadAttribute */)) {
            return parent2.parent.parent;
          }
          break;
        case 20 /* CloseBraceToken */:
          if (parent2 && parent2.kind === 294 /* JsxExpression */ && parent2.parent && parent2.parent.kind === 291 /* JsxAttribute */) {
            return parent2.parent.parent.parent;
          }
          if (parent2 && parent2.kind === 293 /* JsxSpreadAttribute */) {
            return parent2.parent.parent;
          }
          break;
      }
    }
    return void 0;
  }
  function isInDifferentLineThanContextToken(contextToken2, position2) {
    return sourceFile.getLineEndOfPosition(contextToken2.getEnd()) < position2;
  }
  function isSolelyIdentifierDefinitionLocation(contextToken2) {
    const parent2 = contextToken2.parent;
    const containingNodeKind = parent2.kind;
    switch (contextToken2.kind) {
      case 28 /* CommaToken */:
        return containingNodeKind === 260 /* VariableDeclaration */ || isVariableDeclarationListButNotTypeArgument(contextToken2) || containingNodeKind === 243 /* VariableStatement */ || containingNodeKind === 266 /* EnumDeclaration */ || // enum a { foo, |
        isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 264 /* InterfaceDeclaration */ || // interface A<T, |
        containingNodeKind === 207 /* ArrayBindingPattern */ || // var [x, y|
        containingNodeKind === 265 /* TypeAliasDeclaration */ || // type Map, K, |
        // class A<T, |
        // var C = class D<T, |
        isClassLike(parent2) && !!parent2.typeParameters && parent2.typeParameters.end >= contextToken2.pos;
      case 25 /* DotToken */:
        return containingNodeKind === 207 /* ArrayBindingPattern */;
      // var [.|
      case 59 /* ColonToken */:
        return containingNodeKind === 208 /* BindingElement */;
      // var {x :html|
      case 23 /* OpenBracketToken */:
        return containingNodeKind === 207 /* ArrayBindingPattern */;
      // var [x|
      case 21 /* OpenParenToken */:
        return containingNodeKind === 299 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind);
      case 19 /* OpenBraceToken */:
        return containingNodeKind === 266 /* EnumDeclaration */;
      // enum a { |
      case 30 /* LessThanToken */:
        return containingNodeKind === 263 /* ClassDeclaration */ || // class A< |
        containingNodeKind === 231 /* ClassExpression */ || // var C = class D< |
        containingNodeKind === 264 /* InterfaceDeclaration */ || // interface A< |
        containingNodeKind === 265 /* TypeAliasDeclaration */ || // type List< |
        isFunctionLikeKind(containingNodeKind);
      case 126 /* StaticKeyword */:
        return containingNodeKind === 172 /* PropertyDeclaration */ && !isClassLike(parent2.parent);
      case 26 /* DotDotDotToken */:
        return containingNodeKind === 169 /* Parameter */ || !!parent2.parent && parent2.parent.kind === 207 /* ArrayBindingPattern */;
      // var [...z|
      case 125 /* PublicKeyword */:
      case 123 /* PrivateKeyword */:
      case 124 /* ProtectedKeyword */:
        return containingNodeKind === 169 /* Parameter */ && !isConstructorDeclaration(parent2.parent);
      case 130 /* AsKeyword */:
        return containingNodeKind === 276 /* ImportSpecifier */ || containingNodeKind === 281 /* ExportSpecifier */ || containingNodeKind === 274 /* NamespaceImport */;
      case 139 /* GetKeyword */:
      case 153 /* SetKeyword */:
        return !isFromObjectTypeDeclaration(contextToken2);
      case 80 /* Identifier */: {
        if ((containingNodeKind === 276 /* ImportSpecifier */ || containingNodeKind === 281 /* ExportSpecifier */) && contextToken2 === parent2.name && contextToken2.text === "type") {
          return false;
        }
        const ancestorVariableDeclaration = findAncestor(
          contextToken2.parent,
          isVariableDeclaration
        );
        if (ancestorVariableDeclaration && isInDifferentLineThanContextToken(contextToken2, position)) {
          return false;
        }
        break;
      }
      case 86 /* ClassKeyword */:
      case 94 /* EnumKeyword */:
      case 120 /* InterfaceKeyword */:
      case 100 /* FunctionKeyword */:
      case 115 /* VarKeyword */:
      case 102 /* ImportKeyword */:
      case 121 /* LetKeyword */:
      case 87 /* ConstKeyword */:
      case 140 /* InferKeyword */:
        return true;
      case 156 /* TypeKeyword */:
        return containingNodeKind !== 276 /* ImportSpecifier */;
      case 42 /* AsteriskToken */:
        return isFunctionLike(contextToken2.parent) && !isMethodDeclaration(contextToken2.parent);
    }
    if (isClassMemberCompletionKeyword(keywordForNode(contextToken2)) && isFromObjectTypeDeclaration(contextToken2)) {
      return false;
    }
    if (isConstructorParameterCompletion(contextToken2)) {
      if (!isIdentifier(contextToken2) || isParameterPropertyModifier(keywordForNode(contextToken2)) || isCurrentlyEditingNode(contextToken2)) {
        return false;
      }
    }
    switch (keywordForNode(contextToken2)) {
      case 128 /* AbstractKeyword */:
      case 86 /* ClassKeyword */:
      case 87 /* ConstKeyword */:
      case 138 /* DeclareKeyword */:
      case 94 /* EnumKeyword */:
      case 100 /* FunctionKeyword */:
      case 120 /* InterfaceKeyword */:
      case 121 /* LetKeyword */:
      case 123 /* PrivateKeyword */:
      case 124 /* ProtectedKeyword */:
      case 125 /* PublicKeyword */:
      case 126 /* StaticKeyword */:
      case 115 /* VarKeyword */:
        return true;
      case 134 /* AsyncKeyword */:
        return isPropertyDeclaration(contextToken2.parent);
    }
    const ancestorClassLike = findAncestor(contextToken2.parent, isClassLike);
    if (ancestorClassLike && contextToken2 === previousToken && isPreviousPropertyDeclarationTerminated(contextToken2, position)) {
      return false;
    }
    const ancestorPropertyDeclaraion = getAncestor(contextToken2.parent, 172 /* PropertyDeclaration */);
    if (ancestorPropertyDeclaraion && contextToken2 !== previousToken && isClassLike(previousToken.parent.parent) && position <= previousToken.end) {
      if (isPreviousPropertyDeclarationTerminated(contextToken2, previousToken.end)) {
        return false;
      } else if (contextToken2.kind !== 64 /* EqualsToken */ && (isInitializedProperty(ancestorPropertyDeclaraion) || hasType(ancestorPropertyDeclaraion))) {
        return true;
      }
    }
    return isDeclarationName(contextToken2) && !isShorthandPropertyAssignment(contextToken2.parent) && !isJsxAttribute(contextToken2.parent) && !((isClassLike(contextToken2.parent) || isInterfaceDeclaration(contextToken2.parent) || isTypeParameterDeclaration(contextToken2.parent)) && (contextToken2 !== previousToken || position > previousToken.end));
  }
  function isPreviousPropertyDeclarationTerminated(contextToken2, position2) {
    return contextToken2.kind !== 64 /* EqualsToken */ && (contextToken2.kind === 27 /* SemicolonToken */ || !positionsAreOnSameLine(contextToken2.end, position2, sourceFile));
  }
  function isFunctionLikeButNotConstructor(kind) {
    return isFunctionLikeKind(kind) && kind !== 176 /* Constructor */;
  }
  function isDotOfNumericLiteral(contextToken2) {
    if (contextToken2.kind === 9 /* NumericLiteral */) {
      const text = contextToken2.getFullText();
      return text.charAt(text.length - 1) === ".";
    }
    return false;
  }
  function isVariableDeclarationListButNotTypeArgument(node2) {
    return node2.parent.kind === 261 /* VariableDeclarationList */ && !isPossiblyTypeArgumentPosition(node2, sourceFile, typeChecker);
  }
  function filterObjectMembersList(contextualMemberSymbols, existingMembers) {
    if (existingMembers.length === 0) {
      return contextualMemberSymbols;
    }
    const membersDeclaredBySpreadAssignment = /* @__PURE__ */ new Set();
    const existingMemberNames = /* @__PURE__ */ new Set();
    for (const m of existingMembers) {
      if (m.kind !== 303 /* PropertyAssignment */ && m.kind !== 304 /* ShorthandPropertyAssignment */ && m.kind !== 208 /* BindingElement */ && m.kind !== 174 /* MethodDeclaration */ && m.kind !== 177 /* GetAccessor */ && m.kind !== 178 /* SetAccessor */ && m.kind !== 305 /* SpreadAssignment */) {
        continue;
      }
      if (isCurrentlyEditingNode(m)) {
        continue;
      }
      let existingName;
      if (isSpreadAssignment(m)) {
        setMembersDeclaredBySpreadAssignment(m, membersDeclaredBySpreadAssignment);
      } else if (isBindingElement(m) && m.propertyName) {
        if (m.propertyName.kind === 80 /* Identifier */) {
          existingName = m.propertyName.escapedText;
        }
      } else {
        const name = getNameOfDeclaration(m);
        existingName = name && isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0;
      }
      if (existingName !== void 0) {
        existingMemberNames.add(existingName);
      }
    }
    const filteredSymbols = contextualMemberSymbols.filter((m) => !existingMemberNames.has(m.escapedName));
    setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols);
    return filteredSymbols;
  }
  function setMembersDeclaredBySpreadAssignment(declaration, membersDeclaredBySpreadAssignment) {
    const expression = declaration.expression;
    const symbol = typeChecker.getSymbolAtLocation(expression);
    const type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, expression);
    const properties = type && type.properties;
    if (properties) {
      properties.forEach((property) => {
        membersDeclaredBySpreadAssignment.add(property.name);
      });
    }
  }
  function setSortTextToOptionalMember() {
    symbols.forEach((m) => {
      if (m.flags & 16777216 /* Optional */) {
        const symbolId = getSymbolId(m);
        symbolToSortTextMap[symbolId] = symbolToSortTextMap[symbolId] ?? SortText.OptionalMember;
      }
    });
  }
  function setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, contextualMemberSymbols) {
    if (membersDeclaredBySpreadAssignment.size === 0) {
      return;
    }
    for (const contextualMemberSymbol of contextualMemberSymbols) {
      if (membersDeclaredBySpreadAssignment.has(contextualMemberSymbol.name)) {
        symbolToSortTextMap[getSymbolId(contextualMemberSymbol)] = SortText.MemberDeclaredBySpreadAssignment;
      }
    }
  }
  function transformObjectLiteralMembersSortText(start2) {
    for (let i = start2; i < symbols.length; i++) {
      const symbol = symbols[i];
      const symbolId = getSymbolId(symbol);
      const origin = symbolToOriginInfoMap == null ? void 0 : symbolToOriginInfoMap[i];
      const target = getEmitScriptTarget(compilerOptions);
      const displayName = getCompletionEntryDisplayNameForSymbol(
        symbol,
        target,
        origin,
        0 /* ObjectPropertyDeclaration */,
        /*jsxIdentifierExpected*/
        false
      );
      if (displayName) {
        const originalSortText = symbolToSortTextMap[symbolId] ?? SortText.LocationPriority;
        const { name } = displayName;
        symbolToSortTextMap[symbolId] = SortText.ObjectLiteralProperty(originalSortText, name);
      }
    }
  }
  function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) {
    const existingMemberNames = /* @__PURE__ */ new Set();
    for (const m of existingMembers) {
      if (m.kind !== 172 /* PropertyDeclaration */ && m.kind !== 174 /* MethodDeclaration */ && m.kind !== 177 /* GetAccessor */ && m.kind !== 178 /* SetAccessor */) {
        continue;
      }
      if (isCurrentlyEditingNode(m)) {
        continue;
      }
      if (hasEffectiveModifier(m, 2 /* Private */)) {
        continue;
      }
      if (isStatic(m) !== !!(currentClassElementModifierFlags & 256 /* Static */)) {
        continue;
      }
      const existingName = getPropertyNameForPropertyNameNode(m.name);
      if (existingName) {
        existingMemberNames.add(existingName);
      }
    }
    return baseSymbols.filter(
      (propertySymbol) => !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & 2 /* Private */) && !(propertySymbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration))
    );
  }
  function filterJsxAttributes(symbols2, attributes) {
    const seenNames = /* @__PURE__ */ new Set();
    const membersDeclaredBySpreadAssignment = /* @__PURE__ */ new Set();
    for (const attr of attributes) {
      if (isCurrentlyEditingNode(attr)) {
        continue;
      }
      if (attr.kind === 291 /* JsxAttribute */) {
        seenNames.add(getEscapedTextOfJsxAttributeName(attr.name));
      } else if (isJsxSpreadAttribute(attr)) {
        setMembersDeclaredBySpreadAssignment(attr, membersDeclaredBySpreadAssignment);
      }
    }
    const filteredSymbols = symbols2.filter((a) => !seenNames.has(a.escapedName));
    setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols);
    return filteredSymbols;
  }
  function isCurrentlyEditingNode(node2) {
    return node2.getStart(sourceFile) <= position && position <= node2.getEnd();
  }
}
function tryGetObjectLikeCompletionContainer(contextToken, position, sourceFile) {
  var _a;
  if (contextToken) {
    const { parent: parent2 } = contextToken;
    switch (contextToken.kind) {
      case 19 /* OpenBraceToken */:
      // const x = { |
      case 28 /* CommaToken */:
        if (isObjectLiteralExpression(parent2) || isObjectBindingPattern(parent2)) {
          return parent2;
        }
        break;
      case 42 /* AsteriskToken */:
        return isMethodDeclaration(parent2) ? tryCast(parent2.parent, isObjectLiteralExpression) : void 0;
      case 134 /* AsyncKeyword */:
        return tryCast(parent2.parent, isObjectLiteralExpression);
      case 80 /* Identifier */:
        if (contextToken.text === "async" && isShorthandPropertyAssignment(contextToken.parent)) {
          return contextToken.parent.parent;
        } else {
          if (isObjectLiteralExpression(contextToken.parent.parent) && (isSpreadAssignment(contextToken.parent) || isShorthandPropertyAssignment(contextToken.parent) && getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line)) {
            return contextToken.parent.parent;
          }
          const ancestorNode2 = findAncestor(parent2, isPropertyAssignment);
          if ((ancestorNode2 == null ? void 0 : ancestorNode2.getLastToken(sourceFile)) === contextToken && isObjectLiteralExpression(ancestorNode2.parent)) {
            return ancestorNode2.parent;
          }
        }
        break;
      default:
        if (((_a = parent2.parent) == null ? void 0 : _a.parent) && (isMethodDeclaration(parent2.parent) || isGetAccessorDeclaration(parent2.parent) || isSetAccessorDeclaration(parent2.parent)) && isObjectLiteralExpression(parent2.parent.parent)) {
          return parent2.parent.parent;
        }
        if (isSpreadAssignment(parent2) && isObjectLiteralExpression(parent2.parent)) {
          return parent2.parent;
        }
        const ancestorNode = findAncestor(parent2, isPropertyAssignment);
        if (contextToken.kind !== 59 /* ColonToken */ && (ancestorNode == null ? void 0 : ancestorNode.getLastToken(sourceFile)) === contextToken && isObjectLiteralExpression(ancestorNode.parent)) {
          return ancestorNode.parent;
        }
    }
  }
  return void 0;
}
function getRelevantTokens(position, sourceFile) {
  const previousToken = findPrecedingToken(position, sourceFile);
  if (previousToken && position <= previousToken.end && (isMemberName(previousToken) || isKeyword(previousToken.kind))) {
    const contextToken = findPrecedingToken(
      previousToken.getFullStart(),
      sourceFile,
      /*startNode*/
      void 0
    );
    return { contextToken, previousToken };
  }
  return { contextToken: previousToken, previousToken };
}
function getAutoImportSymbolFromCompletionEntryData(name, data, program, host) {
  const containingProgram = data.isPackageJsonImport ? host.getPackageJsonAutoImportProvider() : program;
  const checker = containingProgram.getTypeChecker();
  const moduleSymbol = data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : data.fileName ? checker.getMergedSymbol(Debug.checkDefined(containingProgram.getSourceFile(data.fileName)).symbol) : void 0;
  if (!moduleSymbol) return void 0;
  let symbol = data.exportName === "export=" /* ExportEquals */ ? checker.resolveExternalModuleSymbol(moduleSymbol) : checker.tryGetMemberInModuleExportsAndProperties(data.exportName, moduleSymbol);
  if (!symbol) return void 0;
  const isDefaultExport = data.exportName === "default" /* Default */;
  symbol = isDefaultExport && getLocalSymbolForExportDefault(symbol) || symbol;
  return { symbol, origin: completionEntryDataToSymbolOriginInfo(data, name, moduleSymbol) };
}
function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) {
  if (originIsIgnore(origin)) {
    return void 0;
  }
  const name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name;
  if (name === void 0 || symbol.flags & 1536 /* Module */ && isSingleOrDoubleQuote(name.charCodeAt(0)) || isKnownSymbol(symbol)) {
    return void 0;
  }
  const validNameResult = { name, needsConvertPropertyAccess: false };
  if (isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) {
    return validNameResult;
  }
  if (symbol.flags & 2097152 /* Alias */) {
    return { name, needsConvertPropertyAccess: true };
  }
  switch (kind) {
    case 3 /* MemberLike */:
      return originIsComputedPropertyName(origin) ? { name: origin.symbolName, needsConvertPropertyAccess: false } : void 0;
    case 0 /* ObjectPropertyDeclaration */:
      return { name: JSON.stringify(name), needsConvertPropertyAccess: false };
    case 2 /* PropertyAccess */:
    case 1 /* Global */:
      return name.charCodeAt(0) === 32 /* space */ ? void 0 : { name, needsConvertPropertyAccess: true };
    case 5 /* None */:
    case 4 /* String */:
      return validNameResult;
    default:
      Debug.assertNever(kind);
  }
}
var _keywordCompletions = [];
var allKeywordsCompletions = memoize(() => {
  const res = [];
  for (let i = 83 /* FirstKeyword */; i <= 165 /* LastKeyword */; i++) {
    res.push({
      name: tokenToString(i),
      kind: "keyword" /* keyword */,
      kindModifiers: "" /* none */,
      sortText: SortText.GlobalsOrKeywords
    });
  }
  return res;
});
function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) {
  if (!filterOutTsOnlyKeywords) return getTypescriptKeywordCompletions(keywordFilter);
  const index = keywordFilter + 8 /* Last */ + 1;
  return _keywordCompletions[index] || (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter).filter((entry) => !isTypeScriptOnlyKeyword(stringToToken(entry.name))));
}
function getTypescriptKeywordCompletions(keywordFilter) {
  return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter((entry) => {
    const kind = stringToToken(entry.name);
    switch (keywordFilter) {
      case 0 /* None */:
        return false;
      case 1 /* All */:
        return isFunctionLikeBodyKeyword(kind) || kind === 138 /* DeclareKeyword */ || kind === 144 /* ModuleKeyword */ || kind === 156 /* TypeKeyword */ || kind === 145 /* NamespaceKeyword */ || kind === 128 /* AbstractKeyword */ || isTypeKeyword(kind) && kind !== 157 /* UndefinedKeyword */;
      case 5 /* FunctionLikeBodyKeywords */:
        return isFunctionLikeBodyKeyword(kind);
      case 2 /* ClassElementKeywords */:
        return isClassMemberCompletionKeyword(kind);
      case 3 /* InterfaceElementKeywords */:
        return isInterfaceOrTypeLiteralCompletionKeyword(kind);
      case 4 /* ConstructorParameterKeywords */:
        return isParameterPropertyModifier(kind);
      case 6 /* TypeAssertionKeywords */:
        return isTypeKeyword(kind) || kind === 87 /* ConstKeyword */;
      case 7 /* TypeKeywords */:
        return isTypeKeyword(kind);
      case 8 /* TypeKeyword */:
        return kind === 156 /* TypeKeyword */;
      default:
        return Debug.assertNever(keywordFilter);
    }
  }));
}
function isTypeScriptOnlyKeyword(kind) {
  switch (kind) {
    case 128 /* AbstractKeyword */:
    case 133 /* AnyKeyword */:
    case 163 /* BigIntKeyword */:
    case 136 /* BooleanKeyword */:
    case 138 /* DeclareKeyword */:
    case 94 /* EnumKeyword */:
    case 162 /* GlobalKeyword */:
    case 119 /* ImplementsKeyword */:
    case 140 /* InferKeyword */:
    case 120 /* InterfaceKeyword */:
    case 142 /* IsKeyword */:
    case 143 /* KeyOfKeyword */:
    case 144 /* ModuleKeyword */:
    case 145 /* NamespaceKeyword */:
    case 146 /* NeverKeyword */:
    case 150 /* NumberKeyword */:
    case 151 /* ObjectKeyword */:
    case 164 /* OverrideKeyword */:
    case 123 /* PrivateKeyword */:
    case 124 /* ProtectedKeyword */:
    case 125 /* PublicKeyword */:
    case 148 /* ReadonlyKeyword */:
    case 154 /* StringKeyword */:
    case 155 /* SymbolKeyword */:
    case 156 /* TypeKeyword */:
    case 158 /* UniqueKeyword */:
    case 159 /* UnknownKeyword */:
      return true;
    default:
      return false;
  }
}
function isInterfaceOrTypeLiteralCompletionKeyword(kind) {
  return kind === 148 /* ReadonlyKeyword */;
}
function isClassMemberCompletionKeyword(kind) {
  switch (kind) {
    case 128 /* AbstractKeyword */:
    case 129 /* AccessorKeyword */:
    case 137 /* ConstructorKeyword */:
    case 139 /* GetKeyword */:
    case 153 /* SetKeyword */:
    case 134 /* AsyncKeyword */:
    case 138 /* DeclareKeyword */:
    case 164 /* OverrideKeyword */:
      return true;
    default:
      return isClassMemberModifier(kind);
  }
}
function isFunctionLikeBodyKeyword(kind) {
  return kind === 134 /* AsyncKeyword */ || kind === 135 /* AwaitKeyword */ || kind === 160 /* UsingKeyword */ || kind === 130 /* AsKeyword */ || kind === 152 /* SatisfiesKeyword */ || kind === 156 /* TypeKeyword */ || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind);
}
function keywordForNode(node) {
  return isIdentifier(node) ? identifierToKeywordKind(node) ?? 0 /* Unknown */ : node.kind;
}
function getContextualKeywords(contextToken, position) {
  const entries = [];
  if (contextToken) {
    const file = contextToken.getSourceFile();
    const parent2 = contextToken.parent;
    const tokenLine = file.getLineAndCharacterOfPosition(contextToken.end).line;
    const currentLine = file.getLineAndCharacterOfPosition(position).line;
    if ((isImportDeclaration(parent2) || isExportDeclaration(parent2) && parent2.moduleSpecifier) && contextToken === parent2.moduleSpecifier && tokenLine === currentLine) {
      entries.push({
        name: tokenToString(132 /* AssertKeyword */),
        kind: "keyword" /* keyword */,
        kindModifiers: "" /* none */,
        sortText: SortText.GlobalsOrKeywords
      });
    }
  }
  return entries;
}
function getJsDocTagAtPosition(node, position) {
  return findAncestor(node, (n) => isJSDocTag(n) && rangeContainsPosition(n, position) ? true : isJSDoc(n) ? "quit" : false);
}
function getPropertiesForObjectExpression(contextualType, completionsType, obj, checker) {
  const hasCompletionsType = completionsType && completionsType !== contextualType;
  const promiseFilteredContextualType = checker.getUnionType(
    filter(
      contextualType.flags & 1048576 /* Union */ ? contextualType.types : [contextualType],
      (t) => !checker.getPromisedTypeOfPromise(t)
    )
  );
  const type = hasCompletionsType && !(completionsType.flags & 3 /* AnyOrUnknown */) ? checker.getUnionType([promiseFilteredContextualType, completionsType]) : promiseFilteredContextualType;
  const properties = getApparentProperties(type, obj, checker);
  return type.isClass() && containsNonPublicProperties(properties) ? [] : hasCompletionsType ? filter(properties, hasDeclarationOtherThanSelf) : properties;
  function hasDeclarationOtherThanSelf(member) {
    if (!length(member.declarations)) return true;
    return some(member.declarations, (decl) => decl.parent !== obj);
  }
}
function getApparentProperties(type, node, checker) {
  if (!type.isUnion()) return type.getApparentProperties();
  return checker.getAllPossiblePropertiesOfTypes(filter(type.types, (memberType) => !(memberType.flags & 402784252 /* Primitive */ || checker.isArrayLikeType(memberType) || checker.isTypeInvalidDueToUnionDiscriminant(memberType, node) || checker.typeHasCallOrConstructSignatures(memberType) || memberType.isClass() && containsNonPublicProperties(memberType.getApparentProperties()))));
}
function containsNonPublicProperties(props) {
  return some(props, (p) => !!(getDeclarationModifierFlagsFromSymbol(p) & 6 /* NonPublicAccessibilityModifier */));
}
function getPropertiesForCompletion(type, checker) {
  return type.isUnion() ? Debug.checkEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") : Debug.checkEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
}
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) {
  switch (location.kind) {
    case 352 /* SyntaxList */:
      return tryCast(location.parent, isObjectTypeDeclaration);
    case 1 /* EndOfFileToken */:
      const cls = tryCast(lastOrUndefined(cast(location.parent, isSourceFile).statements), isObjectTypeDeclaration);
      if (cls && !findChildOfKind(cls, 20 /* CloseBraceToken */, sourceFile)) {
        return cls;
      }
      break;
    case 81 /* PrivateIdentifier */:
      if (tryCast(location.parent, isPropertyDeclaration)) {
        return findAncestor(location, isClassLike);
      }
      break;
    case 80 /* Identifier */: {
      const originalKeywordKind = identifierToKeywordKind(location);
      if (originalKeywordKind) {
        return void 0;
      }
      if (isPropertyDeclaration(location.parent) && location.parent.initializer === location) {
        return void 0;
      }
      if (isFromObjectTypeDeclaration(location)) {
        return findAncestor(location, isObjectTypeDeclaration);
      }
    }
  }
  if (!contextToken) return void 0;
  if (location.kind === 137 /* ConstructorKeyword */ || isIdentifier(contextToken) && isPropertyDeclaration(contextToken.parent) && isClassLike(location)) {
    return findAncestor(contextToken, isClassLike);
  }
  switch (contextToken.kind) {
    case 64 /* EqualsToken */:
      return void 0;
    case 27 /* SemicolonToken */:
    // class c {getValue(): number; | }
    case 20 /* CloseBraceToken */:
      return isFromObjectTypeDeclaration(location) && location.parent.name === location ? location.parent.parent : tryCast(location, isObjectTypeDeclaration);
    case 19 /* OpenBraceToken */:
    // class c { |
    case 28 /* CommaToken */:
      return tryCast(contextToken.parent, isObjectTypeDeclaration);
    default:
      if (isObjectTypeDeclaration(location)) {
        if (getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line) {
          return location;
        }
        const isValidKeyword = isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword;
        return isValidKeyword(contextToken.kind) || contextToken.kind === 42 /* AsteriskToken */ || isIdentifier(contextToken) && isValidKeyword(identifierToKeywordKind(contextToken) ?? 0 /* Unknown */) ? contextToken.parent.parent : void 0;
      }
      return void 0;
  }
}
function tryGetTypeLiteralNode(node) {
  if (!node) return void 0;
  const parent2 = node.parent;
  switch (node.kind) {
    case 19 /* OpenBraceToken */:
      if (isTypeLiteralNode(parent2)) {
        return parent2;
      }
      break;
    case 27 /* SemicolonToken */:
    case 28 /* CommaToken */:
    case 80 /* Identifier */:
      if (parent2.kind === 171 /* PropertySignature */ && isTypeLiteralNode(parent2.parent)) {
        return parent2.parent;
      }
      break;
  }
  return void 0;
}
function getConstraintOfTypeArgumentProperty(node, checker) {
  if (!node) return void 0;
  if (isTypeNode(node) && isTypeReferenceType(node.parent)) {
    return checker.getTypeArgumentConstraint(node);
  }
  const t = getConstraintOfTypeArgumentProperty(node.parent, checker);
  if (!t) return void 0;
  switch (node.kind) {
    case 171 /* PropertySignature */:
      return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName);
    case 193 /* IntersectionType */:
    case 187 /* TypeLiteral */:
    case 192 /* UnionType */:
      return t;
  }
}
function isFromObjectTypeDeclaration(node) {
  return node.parent && isClassOrTypeElement(node.parent) && isObjectTypeDeclaration(node.parent.parent);
}
function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
  switch (triggerCharacter) {
    case ".":
    case "@":
      return true;
    case '"':
    case "'":
    case "`":
      return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1;
    case "#":
      return !!contextToken && isPrivateIdentifier(contextToken) && !!getContainingClass(contextToken);
    case "<":
      return !!contextToken && contextToken.kind === 30 /* LessThanToken */ && (!isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent));
    case "/":
      return !!contextToken && (isStringLiteralLike(contextToken) ? !!tryGetImportFromModuleSpecifier(contextToken) : contextToken.kind === 44 /* SlashToken */ && isJsxClosingElement(contextToken.parent));
    case " ":
      return !!contextToken && isImportKeyword(contextToken) && contextToken.parent.kind === 307 /* SourceFile */;
    default:
      return Debug.assertNever(triggerCharacter);
  }
}
function binaryExpressionMayBeOpenTag({ left }) {
  return nodeIsMissing(left);
}
function isProbablyGlobalType(type, sourceFile, checker) {
  const selfSymbol = checker.resolveName(
    "self",
    /*location*/
    void 0,
    111551 /* Value */,
    /*excludeGlobals*/
    false
  );
  if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) {
    return true;
  }
  const globalSymbol = checker.resolveName(
    "global",
    /*location*/
    void 0,
    111551 /* Value */,
    /*excludeGlobals*/
    false
  );
  if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) {
    return true;
  }
  const globalThisSymbol = checker.resolveName(
    "globalThis",
    /*location*/
    void 0,
    111551 /* Value */,
    /*excludeGlobals*/
    false
  );
  if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) {
    return true;
  }
  return false;
}
function isStaticProperty(symbol) {
  return !!(symbol.valueDeclaration && getEffectiveModifierFlags(symbol.valueDeclaration) & 256 /* Static */ && isClassLike(symbol.valueDeclaration.parent));
}
function tryGetObjectLiteralContextualType(node, typeChecker) {
  const type = typeChecker.getContextualType(node);
  if (type) {
    return type;
  }
  const parent2 = walkUpParenthesizedExpressions(node.parent);
  if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */ && node === parent2.left) {
    return typeChecker.getTypeAtLocation(parent2);
  }
  if (isExpression(parent2)) {
    return typeChecker.getContextualType(parent2);
  }
  return void 0;
}
function getImportStatementCompletionInfo(contextToken, sourceFile) {
  var _a, _b, _c;
  let keywordCompletion;
  let isKeywordOnlyCompletion = false;
  const candidate = getCandidate();
  return {
    isKeywordOnlyCompletion,
    keywordCompletion,
    isNewIdentifierLocation: !!(candidate || keywordCompletion === 156 /* TypeKeyword */),
    isTopLevelTypeOnly: !!((_b = (_a = tryCast(candidate, isImportDeclaration)) == null ? void 0 : _a.importClause) == null ? void 0 : _b.isTypeOnly) || !!((_c = tryCast(candidate, isImportEqualsDeclaration)) == null ? void 0 : _c.isTypeOnly),
    couldBeTypeOnlyImportSpecifier: !!candidate && couldBeTypeOnlyImportSpecifier(candidate, contextToken),
    replacementSpan: getSingleLineReplacementSpanForImportCompletionNode(candidate)
  };
  function getCandidate() {
    const parent2 = contextToken.parent;
    if (isImportEqualsDeclaration(parent2)) {
      const lastToken = parent2.getLastToken(sourceFile);
      if (isIdentifier(contextToken) && lastToken !== contextToken) {
        keywordCompletion = 161 /* FromKeyword */;
        isKeywordOnlyCompletion = true;
        return void 0;
      }
      keywordCompletion = contextToken.kind === 156 /* TypeKeyword */ ? void 0 : 156 /* TypeKeyword */;
      return isModuleSpecifierMissingOrEmpty(parent2.moduleReference) ? parent2 : void 0;
    }
    if (couldBeTypeOnlyImportSpecifier(parent2, contextToken) && canCompleteFromNamedBindings(parent2.parent)) {
      return parent2;
    }
    if (isNamedImports(parent2) || isNamespaceImport(parent2)) {
      if (!parent2.parent.isTypeOnly && (contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 102 /* ImportKeyword */ || contextToken.kind === 28 /* CommaToken */)) {
        keywordCompletion = 156 /* TypeKeyword */;
      }
      if (canCompleteFromNamedBindings(parent2)) {
        if (contextToken.kind === 20 /* CloseBraceToken */ || contextToken.kind === 80 /* Identifier */) {
          isKeywordOnlyCompletion = true;
          keywordCompletion = 161 /* FromKeyword */;
        } else {
          return parent2.parent.parent;
        }
      }
      return void 0;
    }
    if (isExportDeclaration(parent2) && contextToken.kind === 42 /* AsteriskToken */ || isNamedExports(parent2) && contextToken.kind === 20 /* CloseBraceToken */) {
      isKeywordOnlyCompletion = true;
      keywordCompletion = 161 /* FromKeyword */;
      return void 0;
    }
    if (isImportKeyword(contextToken) && isSourceFile(parent2)) {
      keywordCompletion = 156 /* TypeKeyword */;
      return contextToken;
    }
    if (isImportKeyword(contextToken) && isImportDeclaration(parent2)) {
      keywordCompletion = 156 /* TypeKeyword */;
      return isModuleSpecifierMissingOrEmpty(parent2.moduleSpecifier) ? parent2 : void 0;
    }
    return void 0;
  }
}
function getSingleLineReplacementSpanForImportCompletionNode(node) {
  var _a;
  if (!node) return void 0;
  const top = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration, isJSDocImportTag)) ?? node;
  const sourceFile = top.getSourceFile();
  if (rangeIsOnSingleLine(top, sourceFile)) {
    return createTextSpanFromNode(top, sourceFile);
  }
  Debug.assert(top.kind !== 102 /* ImportKeyword */ && top.kind !== 276 /* ImportSpecifier */);
  const potentialSplitPoint = top.kind === 272 /* ImportDeclaration */ || top.kind === 351 /* JSDocImportTag */ ? getPotentiallyInvalidImportSpecifier((_a = top.importClause) == null ? void 0 : _a.namedBindings) ?? top.moduleSpecifier : top.moduleReference;
  const withoutModuleSpecifier = {
    pos: top.getFirstToken().getStart(),
    end: potentialSplitPoint.pos
  };
  if (rangeIsOnSingleLine(withoutModuleSpecifier, sourceFile)) {
    return createTextSpanFromRange(withoutModuleSpecifier);
  }
}
function getPotentiallyInvalidImportSpecifier(namedBindings) {
  var _a;
  return find(
    (_a = tryCast(namedBindings, isNamedImports)) == null ? void 0 : _a.elements,
    (e) => {
      var _a2;
      return !e.propertyName && isStringANonContextualKeyword(e.name.text) && ((_a2 = findPrecedingToken(e.name.pos, namedBindings.getSourceFile(), namedBindings)) == null ? void 0 : _a2.kind) !== 28 /* CommaToken */;
    }
  );
}
function couldBeTypeOnlyImportSpecifier(importSpecifier, contextToken) {
  return isImportSpecifier(importSpecifier) && (importSpecifier.isTypeOnly || contextToken === importSpecifier.name && isTypeKeywordTokenOrIdentifier(contextToken));
}
function canCompleteFromNamedBindings(namedBindings) {
  if (!isModuleSpecifierMissingOrEmpty(namedBindings.parent.parent.moduleSpecifier) || namedBindings.parent.name) {
    return false;
  }
  if (isNamedImports(namedBindings)) {
    const invalidNamedImport = getPotentiallyInvalidImportSpecifier(namedBindings);
    const validImports = invalidNamedImport ? namedBindings.elements.indexOf(invalidNamedImport) : namedBindings.elements.length;
    return validImports < 2;
  }
  return true;
}
function isModuleSpecifierMissingOrEmpty(specifier) {
  var _a;
  if (nodeIsMissing(specifier)) return true;
  return !((_a = tryCast(isExternalModuleReference(specifier) ? specifier.expression : specifier, isStringLiteralLike)) == null ? void 0 : _a.text);
}
function getClosestSymbolDeclaration(contextToken, location) {
  if (!contextToken) return;
  let closestDeclaration = findAncestor(contextToken, (node) => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : (isParameter(node) || isTypeParameterDeclaration(node)) && !isIndexSignatureDeclaration(node.parent));
  if (!closestDeclaration) {
    closestDeclaration = findAncestor(location, (node) => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : isVariableDeclaration(node));
  }
  return closestDeclaration;
}
function isInTypeParameterDefault(contextToken) {
  if (!contextToken) {
    return false;
  }
  let node = contextToken;
  let parent2 = contextToken.parent;
  while (parent2) {
    if (isTypeParameterDeclaration(parent2)) {
      return parent2.default === node || node.kind === 64 /* EqualsToken */;
    }
    node = parent2;
    parent2 = parent2.parent;
  }
  return false;
}
function isArrowFunctionBody(node) {
  return node.parent && isArrowFunction(node.parent) && (node.parent.body === node || // const a = () => /**/;
  node.kind === 39 /* EqualsGreaterThanToken */);
}
function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules = /* @__PURE__ */ new Set()) {
  return nonAliasCanBeReferencedAtTypeLocation(symbol) || nonAliasCanBeReferencedAtTypeLocation(skipAlias(symbol.exportSymbol || symbol, checker));
  function nonAliasCanBeReferencedAtTypeLocation(symbol2) {
    return !!(symbol2.flags & 788968 /* Type */) || checker.isUnknownSymbol(symbol2) || !!(symbol2.flags & 1536 /* Module */) && addToSeen(seenModules, symbol2) && checker.getExportsOfModule(symbol2).some((e) => symbolCanBeReferencedAtTypeLocation(e, checker, seenModules));
  }
}
function isDeprecated(symbol, checker) {
  const declarations = skipAlias(symbol, checker).declarations;
  return !!length(declarations) && every(declarations, isDeprecatedDeclaration);
}
function charactersFuzzyMatchInString(identifierString, lowercaseCharacters) {
  if (lowercaseCharacters.length === 0) {
    return true;
  }
  let matchedFirstCharacter = false;
  let prevChar;
  let characterIndex = 0;
  const len = identifierString.length;
  for (let strIndex = 0; strIndex < len; strIndex++) {
    const strChar = identifierString.charCodeAt(strIndex);
    const testChar = lowercaseCharacters.charCodeAt(characterIndex);
    if (strChar === testChar || strChar === toUpperCharCode(testChar)) {
      matchedFirstCharacter || (matchedFirstCharacter = prevChar === void 0 || // Beginning of word
      97 /* a */ <= prevChar && prevChar <= 122 /* z */ && 65 /* A */ <= strChar && strChar <= 90 /* Z */ || // camelCase transition
      prevChar === 95 /* _ */ && strChar !== 95 /* _ */);
      if (matchedFirstCharacter) {
        characterIndex++;
      }
      if (characterIndex === lowercaseCharacters.length) {
        return true;
      }
    }
    prevChar = strChar;
  }
  return false;
}
function toUpperCharCode(charCode) {
  if (97 /* a */ <= charCode && charCode <= 122 /* z */) {
    return charCode - 32;
  }
  return charCode;
}
function isContextualKeywordInAutoImportableExpressionSpace(keyword) {
  return keyword === "abstract" || keyword === "async" || keyword === "await" || keyword === "declare" || keyword === "module" || keyword === "namespace" || keyword === "type" || keyword === "satisfies" || keyword === "as";
}

// src/services/_namespaces/ts.Completions.StringCompletions.ts
var ts_Completions_StringCompletions_exports = {};
__export(ts_Completions_StringCompletions_exports, {
  getStringLiteralCompletionDetails: () => getStringLiteralCompletionDetails,
  getStringLiteralCompletions: () => getStringLiteralCompletions
});

// src/services/stringCompletions.ts
var kindPrecedence = {
  ["directory" /* directory */]: 0,
  ["script" /* scriptElement */]: 1,
  ["external module name" /* externalModuleName */]: 2
};
function createNameAndKindSet() {
  const map2 = /* @__PURE__ */ new Map();
  function add(value) {
    const existing = map2.get(value.name);
    if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value.kind]) {
      map2.set(value.name, value);
    }
  }
  return {
    add,
    has: map2.has.bind(map2),
    values: map2.values.bind(map2)
  };
}
function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences, includeSymbol) {
  if (isInReferenceComment(sourceFile, position)) {
    const entries = getTripleSlashReferenceCompletion(sourceFile, position, program, host, createModuleSpecifierResolutionHost(program, host));
    return entries && convertPathCompletions(entries);
  }
  if (isInString(sourceFile, position, contextToken)) {
    if (!contextToken || !isStringLiteralLike(contextToken)) return void 0;
    const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program, host, preferences);
    return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol);
  }
}
function convertStringLiteralCompletions(completion, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol) {
  if (completion === void 0) {
    return void 0;
  }
  const optionalReplacementSpan = createTextSpanFromStringLiteralLikeContent(contextToken, position);
  switch (completion.kind) {
    case 0 /* Paths */:
      return convertPathCompletions(completion.paths);
    case 1 /* Properties */: {
      const entries = createSortedArray();
      getCompletionEntriesFromSymbols(
        completion.symbols,
        entries,
        contextToken,
        contextToken,
        sourceFile,
        position,
        sourceFile,
        host,
        program,
        99 /* ESNext */,
        log,
        4 /* String */,
        preferences,
        options,
        /*formatContext*/
        void 0,
        /*isTypeOnlyLocation*/
        void 0,
        /*propertyAccessToConvert*/
        void 0,
        /*jsxIdentifierExpected*/
        void 0,
        /*isJsxInitializer*/
        void 0,
        /*importStatementCompletion*/
        void 0,
        /*recommendedCompletion*/
        void 0,
        /*symbolToOriginInfoMap*/
        void 0,
        /*symbolToSortTextMap*/
        void 0,
        /*isJsxIdentifierExpected*/
        void 0,
        /*isRightOfOpenTag*/
        void 0,
        includeSymbol
      );
      return {
        isGlobalCompletion: false,
        isMemberCompletion: true,
        isNewIdentifierLocation: completion.hasIndexSignature,
        optionalReplacementSpan,
        entries,
        defaultCommitCharacters: getDefaultCommitCharacters(completion.hasIndexSignature)
      };
    }
    case 2 /* Types */: {
      const quoteChar = contextToken.kind === 15 /* NoSubstitutionTemplateLiteral */ ? 96 /* backtick */ : startsWith(getTextOfNode(contextToken), "'") ? 39 /* singleQuote */ : 34 /* doubleQuote */;
      const entries = completion.types.map((type) => ({
        name: escapeString(type.value, quoteChar),
        kindModifiers: "" /* none */,
        kind: "string" /* string */,
        sortText: SortText.LocationPriority,
        replacementSpan: getReplacementSpanForContextToken(contextToken, position),
        commitCharacters: []
      }));
      return {
        isGlobalCompletion: false,
        isMemberCompletion: false,
        isNewIdentifierLocation: completion.isNewIdentifier,
        optionalReplacementSpan,
        entries,
        defaultCommitCharacters: getDefaultCommitCharacters(completion.isNewIdentifier)
      };
    }
    default:
      return Debug.assertNever(completion);
  }
}
function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, program, host, cancellationToken, preferences) {
  if (!contextToken || !isStringLiteralLike(contextToken)) return void 0;
  const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program, host, preferences);
  return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, program.getTypeChecker(), cancellationToken);
}
function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) {
  switch (completion.kind) {
    case 0 /* Paths */: {
      const match = find(completion.paths, (p) => p.name === name);
      return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [textPart(name)]);
    }
    case 1 /* Properties */: {
      const match = find(completion.symbols, (s) => s.name === name);
      return match && createCompletionDetailsForSymbol(match, match.name, checker, sourceFile, location, cancellationToken);
    }
    case 2 /* Types */:
      return find(completion.types, (t) => t.value === name) ? createCompletionDetails(name, "" /* none */, "string" /* string */, [textPart(name)]) : void 0;
    default:
      return Debug.assertNever(completion);
  }
}
function convertPathCompletions(pathCompletions) {
  const isGlobalCompletion = false;
  const isNewIdentifierLocation = true;
  const entries = pathCompletions.map(({ name, kind, span, extension }) => ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: SortText.LocationPriority, replacementSpan: span }));
  return {
    isGlobalCompletion,
    isMemberCompletion: false,
    isNewIdentifierLocation,
    entries,
    defaultCommitCharacters: getDefaultCommitCharacters(isNewIdentifierLocation)
  };
}
function kindModifiersFromExtension(extension) {
  switch (extension) {
    case ".d.ts" /* Dts */:
      return ".d.ts" /* dtsModifier */;
    case ".js" /* Js */:
      return ".js" /* jsModifier */;
    case ".json" /* Json */:
      return ".json" /* jsonModifier */;
    case ".jsx" /* Jsx */:
      return ".jsx" /* jsxModifier */;
    case ".ts" /* Ts */:
      return ".ts" /* tsModifier */;
    case ".tsx" /* Tsx */:
      return ".tsx" /* tsxModifier */;
    case ".d.mts" /* Dmts */:
      return ".d.mts" /* dmtsModifier */;
    case ".mjs" /* Mjs */:
      return ".mjs" /* mjsModifier */;
    case ".mts" /* Mts */:
      return ".mts" /* mtsModifier */;
    case ".d.cts" /* Dcts */:
      return ".d.cts" /* dctsModifier */;
    case ".cjs" /* Cjs */:
      return ".cjs" /* cjsModifier */;
    case ".cts" /* Cts */:
      return ".cts" /* ctsModifier */;
    case ".tsbuildinfo" /* TsBuildInfo */:
      return Debug.fail(`Extension ${".tsbuildinfo" /* TsBuildInfo */} is unsupported.`);
    case void 0:
      return "" /* none */;
    default:
      return Debug.assertNever(extension);
  }
}
function getStringLiteralCompletionEntries(sourceFile, node, position, program, host, preferences) {
  const typeChecker = program.getTypeChecker();
  const parent2 = walkUpParentheses(node.parent);
  switch (parent2.kind) {
    case 201 /* LiteralType */: {
      const grandParent = walkUpParentheses(parent2.parent);
      if (grandParent.kind === 205 /* ImportType */) {
        return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, program, host, preferences) };
      }
      return fromUnionableLiteralType(grandParent);
    }
    case 303 /* PropertyAssignment */:
      if (isObjectLiteralExpression(parent2.parent) && parent2.name === node) {
        return stringLiteralCompletionsForObjectLiteral(typeChecker, parent2.parent);
      }
      return fromContextualType() || fromContextualType(0 /* None */);
    case 212 /* ElementAccessExpression */: {
      const { expression, argumentExpression } = parent2;
      if (node === skipParentheses(argumentExpression)) {
        return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression));
      }
      return void 0;
    }
    case 213 /* CallExpression */:
    case 214 /* NewExpression */:
    case 291 /* JsxAttribute */:
      if (!isRequireCallArgument(node) && !isImportCall(parent2)) {
        const argumentInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(parent2.kind === 291 /* JsxAttribute */ ? parent2.parent : node, position, sourceFile, typeChecker);
        return argumentInfo && getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || fromContextualType(0 /* None */);
      }
    // falls through (is `require("")` or `require(""` or `import("")`)
    case 272 /* ImportDeclaration */:
    case 278 /* ExportDeclaration */:
    case 283 /* ExternalModuleReference */:
    case 351 /* JSDocImportTag */:
      return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, program, host, preferences) };
    case 296 /* CaseClause */:
      const tracker = newCaseClauseTracker(typeChecker, parent2.parent.clauses);
      const contextualTypes = fromContextualType();
      if (!contextualTypes) {
        return;
      }
      const literals = contextualTypes.types.filter((literal) => !tracker.hasValue(literal.value));
      return { kind: 2 /* Types */, types: literals, isNewIdentifier: false };
    case 276 /* ImportSpecifier */:
    case 281 /* ExportSpecifier */:
      const specifier = parent2;
      if (specifier.propertyName && node !== specifier.propertyName) {
        return;
      }
      const namedImportsOrExports = specifier.parent;
      const { moduleSpecifier } = namedImportsOrExports.kind === 275 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent;
      if (!moduleSpecifier) return;
      const moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier);
      if (!moduleSpecifierSymbol) return;
      const exports2 = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol);
      const existing = new Set(namedImportsOrExports.elements.map((n) => moduleExportNameTextEscaped(n.propertyName || n.name)));
      const uniques = exports2.filter((e) => e.escapedName !== "default" /* Default */ && !existing.has(e.escapedName));
      return { kind: 1 /* Properties */, symbols: uniques, hasIndexSignature: false };
    default:
      return fromContextualType() || fromContextualType(0 /* None */);
  }
  function fromUnionableLiteralType(grandParent) {
    switch (grandParent.kind) {
      case 233 /* ExpressionWithTypeArguments */:
      case 183 /* TypeReference */: {
        const typeArgument = findAncestor(parent2, (n) => n.parent === grandParent);
        if (typeArgument) {
          return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), isNewIdentifier: false };
        }
        return void 0;
      }
      case 199 /* IndexedAccessType */:
        const { indexType, objectType } = grandParent;
        if (!rangeContainsPosition(indexType, position)) {
          return void 0;
        }
        return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType));
      case 192 /* UnionType */: {
        const result = fromUnionableLiteralType(walkUpParentheses(grandParent.parent));
        if (!result) {
          return void 0;
        }
        const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(grandParent, parent2);
        if (result.kind === 1 /* Properties */) {
          return { kind: 1 /* Properties */, symbols: result.symbols.filter((sym) => !contains(alreadyUsedTypes, sym.name)), hasIndexSignature: result.hasIndexSignature };
        }
        return { kind: 2 /* Types */, types: result.types.filter((t) => !contains(alreadyUsedTypes, t.value)), isNewIdentifier: false };
      }
      default:
        return void 0;
    }
  }
  function fromContextualType(contextFlags = 4 /* Completions */) {
    const types = getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker, contextFlags));
    if (!types.length) {
      return;
    }
    return { kind: 2 /* Types */, types, isNewIdentifier: false };
  }
}
function walkUpParentheses(node) {
  switch (node.kind) {
    case 196 /* ParenthesizedType */:
      return walkUpParenthesizedTypes(node);
    case 217 /* ParenthesizedExpression */:
      return walkUpParenthesizedExpressions(node);
    default:
      return node;
  }
}
function getAlreadyUsedTypesInStringLiteralUnion(union, current) {
  return mapDefined(union.types, (type) => type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : void 0);
}
function getStringLiteralCompletionsFromSignature(call, arg, argumentInfo, checker) {
  let isNewIdentifier = false;
  const uniques = /* @__PURE__ */ new Set();
  const editingArgument = isJsxOpeningLikeElement(call) ? Debug.checkDefined(findAncestor(arg.parent, isJsxAttribute)) : arg;
  const candidates = checker.getCandidateSignaturesForStringLiteralCompletions(call, editingArgument);
  const types = flatMap(candidates, (candidate) => {
    if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return;
    let type = candidate.getTypeParameterAtPosition(argumentInfo.argumentIndex);
    if (isJsxOpeningLikeElement(call)) {
      const propType = checker.getTypeOfPropertyOfType(type, getTextOfJsxAttributeName(editingArgument.name));
      if (propType) {
        type = propType;
      }
    }
    isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */);
    return getStringLiteralTypes(type, uniques);
  });
  return length(types) ? { kind: 2 /* Types */, types, isNewIdentifier } : void 0;
}
function stringLiteralCompletionsFromProperties(type) {
  return type && {
    kind: 1 /* Properties */,
    symbols: filter(type.getApparentProperties(), (prop) => !(prop.valueDeclaration && isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration))),
    hasIndexSignature: hasIndexSignature(type)
  };
}
function stringLiteralCompletionsForObjectLiteral(checker, objectLiteralExpression) {
  const contextualType = checker.getContextualType(objectLiteralExpression);
  if (!contextualType) return void 0;
  const completionsType = checker.getContextualType(objectLiteralExpression, 4 /* Completions */);
  const symbols = getPropertiesForObjectExpression(
    contextualType,
    completionsType,
    objectLiteralExpression,
    checker
  );
  return {
    kind: 1 /* Properties */,
    symbols,
    hasIndexSignature: hasIndexSignature(contextualType)
  };
}
function getStringLiteralTypes(type, uniques = /* @__PURE__ */ new Set()) {
  if (!type) return emptyArray;
  type = skipConstraint(type);
  return type.isUnion() ? flatMap(type.types, (t) => getStringLiteralTypes(t, uniques)) : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && addToSeen(uniques, type.value) ? [type] : emptyArray;
}
function nameAndKind(name, kind, extension) {
  return { name, kind, extension };
}
function directoryResult(name) {
  return nameAndKind(
    name,
    "directory" /* directory */,
    /*extension*/
    void 0
  );
}
function addReplacementSpans(text, textStart, names) {
  const span = getDirectoryFragmentTextSpan(text, textStart);
  const wholeSpan = text.length === 0 ? void 0 : createTextSpan(textStart, text.length);
  return names.map(({ name, kind, extension }) => name.includes(directorySeparator) || name.includes(altDirectorySeparator) ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span });
}
function getStringLiteralCompletionsFromModuleNames(sourceFile, node, program, host, preferences) {
  return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, program, host, preferences));
}
function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, program, host, preferences) {
  const literalValue = normalizeSlashes(node.text);
  const mode = isStringLiteralLike(node) ? program.getModeForUsageLocation(sourceFile, node) : void 0;
  const scriptPath = sourceFile.path;
  const scriptDirectory = getDirectoryPath(scriptPath);
  const compilerOptions = program.getCompilerOptions();
  const typeChecker = program.getTypeChecker();
  const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host);
  const extensionOptions = getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile, typeChecker, preferences, mode);
  return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && !compilerOptions.paths && (isRootedDiskPath(literalValue) || isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, program, host, moduleSpecifierResolutionHost, scriptPath, extensionOptions) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, program, host, moduleSpecifierResolutionHost, extensionOptions);
}
function getExtensionOptions(compilerOptions, referenceKind, importingSourceFile, typeChecker, preferences, resolutionMode) {
  return {
    extensionsToSearch: flatten(getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker)),
    referenceKind,
    importingSourceFile,
    endingPreference: preferences == null ? void 0 : preferences.importModuleSpecifierEnding,
    resolutionMode
  };
}
function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, program, host, moduleSpecifierResolutionHost, scriptPath, extensionOptions) {
  const compilerOptions = program.getCompilerOptions();
  if (compilerOptions.rootDirs) {
    return getCompletionEntriesForDirectoryFragmentWithRootDirs(
      compilerOptions.rootDirs,
      literalValue,
      scriptDirectory,
      extensionOptions,
      program,
      host,
      moduleSpecifierResolutionHost,
      scriptPath
    );
  } else {
    return arrayFrom(getCompletionEntriesForDirectoryFragment(
      literalValue,
      scriptDirectory,
      extensionOptions,
      program,
      host,
      moduleSpecifierResolutionHost,
      /*moduleSpecifierIsRelative*/
      true,
      scriptPath
    ).values());
  }
}
function getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker) {
  const ambientModulesExtensions = !typeChecker ? [] : mapDefined(typeChecker.getAmbientModules(), (module2) => {
    const name = module2.name.slice(1, -1);
    if (!name.startsWith("*.") || name.includes("/")) return;
    return name.slice(1);
  });
  const extensions = [...getSupportedExtensions(compilerOptions), ambientModulesExtensions];
  const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
  return moduleResolutionUsesNodeModules(moduleResolution) ? getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, extensions) : extensions;
}
function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) {
  rootDirs = rootDirs.map((rootDirectory) => ensureTrailingDirectorySeparator(normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory))));
  const relativeDirectory = firstDefined(rootDirs, (rootDirectory) => containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : void 0);
  return deduplicate(
    [...rootDirs.map((rootDirectory) => combinePaths(rootDirectory, relativeDirectory)), scriptDirectory].map((baseDir) => removeTrailingDirectorySeparator(baseDir)),
    equateStringsCaseSensitive,
    compareStringsCaseSensitive
  );
}
function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, exclude) {
  const compilerOptions = program.getCompilerOptions();
  const basePath = compilerOptions.project || host.getCurrentDirectory();
  const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
  const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase);
  return deduplicate(
    flatMap(baseDirectories, (baseDirectory) => arrayFrom(getCompletionEntriesForDirectoryFragment(
      fragment,
      baseDirectory,
      extensionOptions,
      program,
      host,
      moduleSpecifierResolutionHost,
      /*moduleSpecifierIsRelative*/
      true,
      exclude
    ).values())),
    (itemA, itemB) => itemA.name === itemB.name && itemA.kind === itemB.kind && itemA.extension === itemB.extension
  );
}
function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, moduleSpecifierIsRelative, exclude, result = createNameAndKindSet()) {
  var _a;
  if (fragment === void 0) {
    fragment = "";
  }
  fragment = normalizeSlashes(fragment);
  if (!hasTrailingDirectorySeparator(fragment)) {
    fragment = getDirectoryPath(fragment);
  }
  if (fragment === "") {
    fragment = "." + directorySeparator;
  }
  fragment = ensureTrailingDirectorySeparator(fragment);
  const absolutePath = resolvePath(scriptDirectory, fragment);
  const baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath);
  if (!moduleSpecifierIsRelative) {
    const packageJsonPath = findPackageJson(baseDirectory, host);
    if (packageJsonPath) {
      const packageJson = readJson(packageJsonPath, host);
      const typesVersions = packageJson.typesVersions;
      if (typeof typesVersions === "object") {
        const versionPaths = (_a = getPackageJsonTypesVersionsPaths(typesVersions)) == null ? void 0 : _a.paths;
        if (versionPaths) {
          const packageDirectory = getDirectoryPath(packageJsonPath);
          const pathInPackage = absolutePath.slice(ensureTrailingDirectorySeparator(packageDirectory).length);
          if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, versionPaths)) {
            return result;
          }
        }
      }
    }
  }
  const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
  if (!tryDirectoryExists(host, baseDirectory)) return result;
  const files = tryReadDirectory(
    host,
    baseDirectory,
    extensionOptions.extensionsToSearch,
    /*exclude*/
    void 0,
    /*include*/
    ["./*"]
  );
  if (files) {
    for (let filePath of files) {
      filePath = normalizePath(filePath);
      if (exclude && comparePaths(filePath, exclude, scriptDirectory, ignoreCase) === 0 /* EqualTo */) {
        continue;
      }
      const { name, extension } = getFilenameWithExtensionOption(
        getBaseFileName(filePath),
        program,
        extensionOptions,
        /*isExportsOrImportsWildcard*/
        false
      );
      result.add(nameAndKind(name, "script" /* scriptElement */, extension));
    }
  }
  const directories = tryGetDirectories(host, baseDirectory);
  if (directories) {
    for (const directory of directories) {
      const directoryName = getBaseFileName(normalizePath(directory));
      if (directoryName !== "@types") {
        result.add(directoryResult(directoryName));
      }
    }
  }
  return result;
}
function getFilenameWithExtensionOption(name, program, extensionOptions, isExportsOrImportsWildcard) {
  const nonJsResult = ts_moduleSpecifiers_exports.tryGetRealFileNameForNonJsDeclarationFileName(name);
  if (nonJsResult) {
    return { name: nonJsResult, extension: tryGetExtensionFromPath2(nonJsResult) };
  }
  if (extensionOptions.referenceKind === 0 /* Filename */) {
    return { name, extension: tryGetExtensionFromPath2(name) };
  }
  let allowedEndings = ts_moduleSpecifiers_exports.getModuleSpecifierPreferences(
    { importModuleSpecifierEnding: extensionOptions.endingPreference },
    program,
    program.getCompilerOptions(),
    extensionOptions.importingSourceFile
  ).getAllowedEndingsInPreferredOrder(extensionOptions.resolutionMode);
  if (isExportsOrImportsWildcard) {
    allowedEndings = allowedEndings.filter((e) => e !== 0 /* Minimal */ && e !== 1 /* Index */);
  }
  if (allowedEndings[0] === 3 /* TsExtension */) {
    if (fileExtensionIsOneOf(name, supportedTSImplementationExtensions)) {
      return { name, extension: tryGetExtensionFromPath2(name) };
    }
    const outputExtension2 = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, program.getCompilerOptions());
    return outputExtension2 ? { name: changeExtension(name, outputExtension2), extension: outputExtension2 } : { name, extension: tryGetExtensionFromPath2(name) };
  }
  if (!isExportsOrImportsWildcard && (allowedEndings[0] === 0 /* Minimal */ || allowedEndings[0] === 1 /* Index */) && fileExtensionIsOneOf(name, [".js" /* Js */, ".jsx" /* Jsx */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */])) {
    return { name: removeFileExtension(name), extension: tryGetExtensionFromPath2(name) };
  }
  const outputExtension = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, program.getCompilerOptions());
  return outputExtension ? { name: changeExtension(name, outputExtension), extension: outputExtension } : { name, extension: tryGetExtensionFromPath2(name) };
}
function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, paths) {
  const getPatternsForKey = (key) => paths[key];
  const comparePaths2 = (a, b) => {
    const patternA = tryParsePattern(a);
    const patternB = tryParsePattern(b);
    const lengthA = typeof patternA === "object" ? patternA.prefix.length : a.length;
    const lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length;
    return compareValues(lengthB, lengthA);
  };
  return addCompletionEntriesFromPathsOrExportsOrImports(
    result,
    /*isExports*/
    false,
    /*isImports*/
    false,
    fragment,
    baseDirectory,
    extensionOptions,
    program,
    host,
    moduleSpecifierResolutionHost,
    getOwnKeys(paths),
    getPatternsForKey,
    comparePaths2
  );
}
function addCompletionEntriesFromPathsOrExportsOrImports(result, isExports, isImports, fragment, baseDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, keys, getPatternsForKey, comparePaths2) {
  let pathResults = [];
  let matchedPath;
  for (const key of keys) {
    if (key === ".") continue;
    const keyWithoutLeadingDotSlash = key.replace(/^\.\//, "") + ((isExports || isImports) && endsWith(key, "/") ? "*" : "");
    const patterns = getPatternsForKey(key);
    if (patterns) {
      const pathPattern = tryParsePattern(keyWithoutLeadingDotSlash);
      if (!pathPattern) continue;
      const isMatch = typeof pathPattern === "object" && isPatternMatch(pathPattern, fragment);
      const isLongestMatch = isMatch && (matchedPath === void 0 || comparePaths2(keyWithoutLeadingDotSlash, matchedPath) === -1 /* LessThan */);
      if (isLongestMatch) {
        matchedPath = keyWithoutLeadingDotSlash;
        pathResults = pathResults.filter((r) => !r.matchedPattern);
      }
      if (typeof pathPattern === "string" || matchedPath === void 0 || comparePaths2(keyWithoutLeadingDotSlash, matchedPath) !== 1 /* GreaterThan */) {
        pathResults.push({
          matchedPattern: isMatch,
          results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, isExports, isImports, program, host, moduleSpecifierResolutionHost).map(({ name, kind, extension }) => nameAndKind(name, kind, extension))
        });
      }
    }
  }
  pathResults.forEach((pathResult) => pathResult.results.forEach((r) => result.add(r)));
  return matchedPath !== void 0;
}
function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, program, host, moduleSpecifierResolutionHost, extensionOptions) {
  const typeChecker = program.getTypeChecker();
  const compilerOptions = program.getCompilerOptions();
  const { baseUrl, paths } = compilerOptions;
  const result = createNameAndKindSet();
  const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
  if (baseUrl) {
    const absolute = normalizePath(combinePaths(host.getCurrentDirectory(), baseUrl));
    getCompletionEntriesForDirectoryFragment(
      fragment,
      absolute,
      extensionOptions,
      program,
      host,
      moduleSpecifierResolutionHost,
      /*moduleSpecifierIsRelative*/
      false,
      /*exclude*/
      void 0,
      result
    );
  }
  if (paths) {
    const absolute = getPathsBasePath(compilerOptions, host);
    addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, program, host, moduleSpecifierResolutionHost, paths);
  }
  const fragmentDirectory = getFragmentDirectory(fragment);
  for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker)) {
    result.add(nameAndKind(
      ambientName,
      "external module name" /* externalModuleName */,
      /*extension*/
      void 0
    ));
  }
  getCompletionEntriesFromTypings(program, host, moduleSpecifierResolutionHost, scriptPath, fragmentDirectory, extensionOptions, result);
  if (moduleResolutionUsesNodeModules(moduleResolution)) {
    let foundGlobal = false;
    if (fragmentDirectory === void 0) {
      for (const moduleName of enumerateNodeModulesVisibleToScript(host, scriptPath)) {
        const moduleResult = nameAndKind(
          moduleName,
          "external module name" /* externalModuleName */,
          /*extension*/
          void 0
        );
        if (!result.has(moduleResult.name)) {
          foundGlobal = true;
          result.add(moduleResult);
        }
      }
    }
    if (!foundGlobal) {
      const resolvePackageJsonExports = getResolvePackageJsonExports(compilerOptions);
      const resolvePackageJsonImports = getResolvePackageJsonImports(compilerOptions);
      let seenPackageScope = false;
      const importsLookup = (directory) => {
        if (resolvePackageJsonImports && !seenPackageScope) {
          const packageFile = combinePaths(directory, "package.json");
          if (seenPackageScope = tryFileExists(host, packageFile)) {
            const packageJson = readJson(packageFile, host);
            exportsOrImportsLookup(
              packageJson.imports,
              fragment,
              directory,
              /*isExports*/
              false,
              /*isImports*/
              true
            );
          }
        }
      };
      let ancestorLookup = (ancestor) => {
        const nodeModules = combinePaths(ancestor, "node_modules");
        if (tryDirectoryExists(host, nodeModules)) {
          getCompletionEntriesForDirectoryFragment(
            fragment,
            nodeModules,
            extensionOptions,
            program,
            host,
            moduleSpecifierResolutionHost,
            /*moduleSpecifierIsRelative*/
            false,
            /*exclude*/
            void 0,
            result
          );
        }
        importsLookup(ancestor);
      };
      if (fragmentDirectory && resolvePackageJsonExports) {
        const nodeModulesDirectoryOrImportsLookup = ancestorLookup;
        ancestorLookup = (ancestor) => {
          const components = getPathComponents(fragment);
          components.shift();
          let packagePath = components.shift();
          if (!packagePath) {
            return nodeModulesDirectoryOrImportsLookup(ancestor);
          }
          if (startsWith(packagePath, "@")) {
            const subName = components.shift();
            if (!subName) {
              return nodeModulesDirectoryOrImportsLookup(ancestor);
            }
            packagePath = combinePaths(packagePath, subName);
          }
          if (resolvePackageJsonImports && startsWith(packagePath, "#")) {
            return importsLookup(ancestor);
          }
          const packageDirectory = combinePaths(ancestor, "node_modules", packagePath);
          const packageFile = combinePaths(packageDirectory, "package.json");
          if (tryFileExists(host, packageFile)) {
            const packageJson = readJson(packageFile, host);
            const fragmentSubpath = components.join("/") + (components.length && hasTrailingDirectorySeparator(fragment) ? "/" : "");
            exportsOrImportsLookup(
              packageJson.exports,
              fragmentSubpath,
              packageDirectory,
              /*isExports*/
              true,
              /*isImports*/
              false
            );
            return;
          }
          return nodeModulesDirectoryOrImportsLookup(ancestor);
        };
      }
      forEachAncestorDirectoryStoppingAtGlobalCache(host, scriptPath, ancestorLookup);
    }
  }
  return arrayFrom(result.values());
  function exportsOrImportsLookup(lookupTable, fragment2, baseDirectory, isExports, isImports) {
    if (typeof lookupTable !== "object" || lookupTable === null) {
      return;
    }
    const keys = getOwnKeys(lookupTable);
    const conditions = getConditions(compilerOptions, mode);
    addCompletionEntriesFromPathsOrExportsOrImports(
      result,
      isExports,
      isImports,
      fragment2,
      baseDirectory,
      extensionOptions,
      program,
      host,
      moduleSpecifierResolutionHost,
      keys,
      (key) => {
        const pattern = getPatternFromFirstMatchingCondition(lookupTable[key], conditions);
        if (pattern === void 0) {
          return void 0;
        }
        return singleElementArray(endsWith(key, "/") && endsWith(pattern, "/") ? pattern + "*" : pattern);
      },
      comparePatternKeys
    );
  }
}
function getPatternFromFirstMatchingCondition(target, conditions) {
  if (typeof target === "string") {
    return target;
  }
  if (target && typeof target === "object" && !isArray(target)) {
    for (const condition in target) {
      if (condition === "default" || conditions.includes(condition) || isApplicableVersionedTypesKey(conditions, condition)) {
        const pattern = target[condition];
        return getPatternFromFirstMatchingCondition(pattern, conditions);
      }
    }
  }
}
function getFragmentDirectory(fragment) {
  return containsSlash(fragment) ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0;
}
function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, isExports, isImports, program, host, moduleSpecifierResolutionHost) {
  const parsedPath = tryParsePattern(path);
  if (!parsedPath) {
    return emptyArray;
  }
  if (typeof parsedPath === "string") {
    return justPathMappingName(path, "script" /* scriptElement */);
  }
  const remainingFragment = tryRemovePrefix(fragment, parsedPath.prefix);
  if (remainingFragment === void 0) {
    const starIsFullPathComponent = endsWith(path, "/*");
    return starIsFullPathComponent ? justPathMappingName(parsedPath.prefix, "directory" /* directory */) : flatMap(patterns, (pattern) => {
      var _a;
      return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, isExports, isImports, program, host, moduleSpecifierResolutionHost)) == null ? void 0 : _a.map(({ name, ...rest }) => ({ name: parsedPath.prefix + name + parsedPath.suffix, ...rest }));
    });
  }
  return flatMap(patterns, (pattern) => getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, isExports, isImports, program, host, moduleSpecifierResolutionHost));
  function justPathMappingName(name, kind) {
    return startsWith(name, fragment) ? [{ name: removeTrailingDirectorySeparator(name), kind, extension: void 0 }] : emptyArray;
  }
}
function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, isExports, isImports, program, host, moduleSpecifierResolutionHost) {
  if (!host.readDirectory) {
    return void 0;
  }
  const parsed = tryParsePattern(pattern);
  if (parsed === void 0 || isString(parsed)) {
    return void 0;
  }
  const normalizedPrefix = resolvePath(parsed.prefix);
  const normalizedPrefixDirectory = hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : getDirectoryPath(normalizedPrefix);
  const normalizedPrefixBase = hasTrailingDirectorySeparator(parsed.prefix) ? "" : getBaseFileName(normalizedPrefix);
  const fragmentHasPath = containsSlash(fragment);
  const fragmentDirectory = fragmentHasPath ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0;
  const getCommonSourceDirectory2 = () => moduleSpecifierResolutionHost.getCommonSourceDirectory();
  const ignoreCase = !hostUsesCaseSensitiveFileNames(moduleSpecifierResolutionHost);
  const outDir = program.getCompilerOptions().outDir;
  const declarationDir = program.getCompilerOptions().declarationDir;
  const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory;
  const baseDirectory = normalizePath(combinePaths(packageDirectory, expandedPrefixDirectory));
  const possibleInputBaseDirectoryForOutDir = isImports && outDir && getPossibleOriginalInputPathWithoutChangingExt(baseDirectory, ignoreCase, outDir, getCommonSourceDirectory2);
  const possibleInputBaseDirectoryForDeclarationDir = isImports && declarationDir && getPossibleOriginalInputPathWithoutChangingExt(baseDirectory, ignoreCase, declarationDir, getCommonSourceDirectory2);
  const normalizedSuffix = normalizePath(parsed.suffix);
  const declarationExtension = normalizedSuffix && getDeclarationEmitExtensionForPath("_" + normalizedSuffix);
  const inputExtension = normalizedSuffix ? getPossibleOriginalInputExtensionForExtension("_" + normalizedSuffix) : void 0;
  const matchingSuffixes = [
    declarationExtension && changeExtension(normalizedSuffix, declarationExtension),
    ...inputExtension ? inputExtension.map((ext) => changeExtension(normalizedSuffix, ext)) : [],
    normalizedSuffix
  ].filter(isString);
  const includeGlobs = normalizedSuffix ? matchingSuffixes.map((suffix) => "**/*" + suffix) : ["./*"];
  const isExportsOrImportsWildcard = (isExports || isImports) && endsWith(pattern, "/*");
  let matches = getMatchesWithPrefix(baseDirectory);
  if (possibleInputBaseDirectoryForOutDir) {
    matches = concatenate(matches, getMatchesWithPrefix(possibleInputBaseDirectoryForOutDir));
  }
  if (possibleInputBaseDirectoryForDeclarationDir) {
    matches = concatenate(matches, getMatchesWithPrefix(possibleInputBaseDirectoryForDeclarationDir));
  }
  if (!normalizedSuffix) {
    matches = concatenate(matches, getDirectoryMatches(baseDirectory));
    if (possibleInputBaseDirectoryForOutDir) {
      matches = concatenate(matches, getDirectoryMatches(possibleInputBaseDirectoryForOutDir));
    }
    if (possibleInputBaseDirectoryForDeclarationDir) {
      matches = concatenate(matches, getDirectoryMatches(possibleInputBaseDirectoryForDeclarationDir));
    }
  }
  return matches;
  function getMatchesWithPrefix(directory) {
    const completePrefix = fragmentHasPath ? directory : ensureTrailingDirectorySeparator(directory) + normalizedPrefixBase;
    return mapDefined(tryReadDirectory(
      host,
      directory,
      extensionOptions.extensionsToSearch,
      /*exclude*/
      void 0,
      includeGlobs
    ), (match) => {
      const trimmedWithPattern = trimPrefixAndSuffix(match, completePrefix);
      if (trimmedWithPattern) {
        if (containsSlash(trimmedWithPattern)) {
          return directoryResult(getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]);
        }
        const { name, extension } = getFilenameWithExtensionOption(trimmedWithPattern, program, extensionOptions, isExportsOrImportsWildcard);
        return nameAndKind(name, "script" /* scriptElement */, extension);
      }
    });
  }
  function getDirectoryMatches(directoryName) {
    return mapDefined(tryGetDirectories(host, directoryName), (dir) => dir === "node_modules" ? void 0 : directoryResult(dir));
  }
  function trimPrefixAndSuffix(path, prefix) {
    return firstDefined(matchingSuffixes, (suffix) => {
      const inner = withoutStartAndEnd(normalizePath(path), prefix, suffix);
      return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner);
    });
  }
}
function withoutStartAndEnd(s, start, end) {
  return startsWith(s, start) && endsWith(s, end) ? s.slice(start.length, s.length - end.length) : void 0;
}
function removeLeadingDirectorySeparator(path) {
  return path[0] === directorySeparator ? path.slice(1) : path;
}
function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) {
  const ambientModules = checker.getAmbientModules().map((sym) => stripQuotes(sym.name));
  const nonRelativeModuleNames = ambientModules.filter((moduleName) => startsWith(moduleName, fragment) && !moduleName.includes("*"));
  if (fragmentDirectory !== void 0) {
    const moduleNameWithSeparator = ensureTrailingDirectorySeparator(fragmentDirectory);
    return nonRelativeModuleNames.map((nonRelativeModuleName) => removePrefix(nonRelativeModuleName, moduleNameWithSeparator));
  }
  return nonRelativeModuleNames;
}
function getTripleSlashReferenceCompletion(sourceFile, position, program, host, moduleSpecifierResolutionHost) {
  const compilerOptions = program.getCompilerOptions();
  const token = getTokenAtPosition(sourceFile, position);
  const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos);
  const range = commentRanges && find(commentRanges, (commentRange) => position >= commentRange.pos && position <= commentRange.end);
  if (!range) {
    return void 0;
  }
  const text = sourceFile.text.slice(range.pos, position);
  const match = tripleSlashDirectiveFragmentRegex.exec(text);
  if (!match) {
    return void 0;
  }
  const [, prefix, kind, toComplete] = match;
  const scriptPath = getDirectoryPath(sourceFile.path);
  const names = kind === "path" ? getCompletionEntriesForDirectoryFragment(
    toComplete,
    scriptPath,
    getExtensionOptions(compilerOptions, 0 /* Filename */, sourceFile),
    program,
    host,
    moduleSpecifierResolutionHost,
    /*moduleSpecifierIsRelative*/
    true,
    sourceFile.path
  ) : kind === "types" ? getCompletionEntriesFromTypings(program, host, moduleSpecifierResolutionHost, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile)) : Debug.fail();
  return addReplacementSpans(toComplete, range.pos + prefix.length, arrayFrom(names.values()));
}
function getCompletionEntriesFromTypings(program, host, moduleSpecifierResolutionHost, scriptPath, fragmentDirectory, extensionOptions, result = createNameAndKindSet()) {
  const options = program.getCompilerOptions();
  const seen = /* @__PURE__ */ new Map();
  const typeRoots = tryAndIgnoreErrors(() => getEffectiveTypeRoots(options, host)) || emptyArray;
  for (const root of typeRoots) {
    getCompletionEntriesFromDirectories(root);
  }
  for (const packageJson of findPackageJsons(scriptPath, host)) {
    const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types");
    getCompletionEntriesFromDirectories(typesDir);
  }
  return result;
  function getCompletionEntriesFromDirectories(directory) {
    if (!tryDirectoryExists(host, directory)) return;
    for (const typeDirectoryName of tryGetDirectories(host, directory)) {
      const packageName = unmangleScopedPackageName(typeDirectoryName);
      if (options.types && !contains(options.types, packageName)) continue;
      if (fragmentDirectory === void 0) {
        if (!seen.has(packageName)) {
          result.add(nameAndKind(
            packageName,
            "external module name" /* externalModuleName */,
            /*extension*/
            void 0
          ));
          seen.set(packageName, true);
        }
      } else {
        const baseDirectory = combinePaths(directory, typeDirectoryName);
        const remainingFragment = tryRemoveDirectoryPrefix(fragmentDirectory, packageName, hostGetCanonicalFileName(host));
        if (remainingFragment !== void 0) {
          getCompletionEntriesForDirectoryFragment(
            remainingFragment,
            baseDirectory,
            extensionOptions,
            program,
            host,
            moduleSpecifierResolutionHost,
            /*moduleSpecifierIsRelative*/
            false,
            /*exclude*/
            void 0,
            result
          );
        }
      }
    }
  }
}
function enumerateNodeModulesVisibleToScript(host, scriptPath) {
  if (!host.readFile || !host.fileExists) return emptyArray;
  const result = [];
  for (const packageJson of findPackageJsons(scriptPath, host)) {
    const contents = readJson(packageJson, host);
    for (const key of nodeModulesDependencyKeys) {
      const dependencies = contents[key];
      if (!dependencies) continue;
      for (const dep in dependencies) {
        if (hasProperty(dependencies, dep) && !startsWith(dep, "@types/")) {
          result.push(dep);
        }
      }
    }
  }
  return result;
}
function getDirectoryFragmentTextSpan(text, textStart) {
  const index = Math.max(text.lastIndexOf(directorySeparator), text.lastIndexOf(altDirectorySeparator));
  const offset = index !== -1 ? index + 1 : 0;
  const length2 = text.length - offset;
  return length2 === 0 || isIdentifierText(text.substr(offset, length2), 99 /* ESNext */) ? void 0 : createTextSpan(textStart + offset, length2);
}
function isPathRelativeToScript(path) {
  if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) {
    const slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1;
    const slashCharCode = path.charCodeAt(slashIndex);
    return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */;
  }
  return false;
}
var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\s*=\s*(?:'|"))([^\x03"]*)$/;
var nodeModulesDependencyKeys = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
function containsSlash(fragment) {
  return fragment.includes(directorySeparator);
}
function isRequireCallArgument(node) {
  return isCallExpression(node.parent) && firstOrUndefined(node.parent.arguments) === node && isIdentifier(node.parent.expression) && node.parent.expression.escapedText === "require";
}

// src/services/_namespaces/ts.FindAllReferences.ts
var ts_FindAllReferences_exports = {};
__export(ts_FindAllReferences_exports, {
  Core: () => Core,
  DefinitionKind: () => DefinitionKind,
  EntryKind: () => EntryKind,
  ExportKind: () => ExportKind2,
  FindReferencesUse: () => FindReferencesUse,
  ImportExport: () => ImportExport,
  createImportTracker: () => createImportTracker,
  findModuleReferences: () => findModuleReferences,
  findReferenceOrRenameEntries: () => findReferenceOrRenameEntries,
  findReferencedSymbols: () => findReferencedSymbols,
  getContextNode: () => getContextNode,
  getExportInfo: () => getExportInfo,
  getImplementationsAtPosition: () => getImplementationsAtPosition,
  getImportOrExportSymbol: () => getImportOrExportSymbol,
  getReferenceEntriesForNode: () => getReferenceEntriesForNode,
  isContextWithStartAndEndNode: () => isContextWithStartAndEndNode,
  isDeclarationOfSymbol: () => isDeclarationOfSymbol,
  isWriteAccessForReference: () => isWriteAccessForReference,
  toContextSpan: () => toContextSpan,
  toHighlightSpan: () => toHighlightSpan,
  toReferenceEntry: () => toReferenceEntry,
  toRenameLocation: () => toRenameLocation
});

// src/services/importTracker.ts
function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) {
  const allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken);
  return (exportSymbol, exportInfo, isForRename) => {
    const { directImports, indirectUsers } = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken);
    return { indirectUsers, ...getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename) };
  };
}
var ExportKind2 = /* @__PURE__ */ ((ExportKind3) => {
  ExportKind3[ExportKind3["Named"] = 0] = "Named";
  ExportKind3[ExportKind3["Default"] = 1] = "Default";
  ExportKind3[ExportKind3["ExportEquals"] = 2] = "ExportEquals";
  return ExportKind3;
})(ExportKind2 || {});
var ImportExport = /* @__PURE__ */ ((ImportExport2) => {
  ImportExport2[ImportExport2["Import"] = 0] = "Import";
  ImportExport2[ImportExport2["Export"] = 1] = "Export";
  return ImportExport2;
})(ImportExport || {});
function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, { exportingModuleSymbol, exportKind }, checker, cancellationToken) {
  const markSeenDirectImport = nodeSeenTracker();
  const markSeenIndirectUser = nodeSeenTracker();
  const directImports = [];
  const isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports;
  const indirectUserDeclarations = isAvailableThroughGlobal ? void 0 : [];
  handleDirectImports(exportingModuleSymbol);
  return { directImports, indirectUsers: getIndirectUsers() };
  function getIndirectUsers() {
    if (isAvailableThroughGlobal) {
      return sourceFiles;
    }
    if (exportingModuleSymbol.declarations) {
      for (const decl of exportingModuleSymbol.declarations) {
        if (isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) {
          addIndirectUser(decl);
        }
      }
    }
    return indirectUserDeclarations.map(getSourceFileOfNode);
  }
  function handleDirectImports(exportingModuleSymbol2) {
    const theseDirectImports = getDirectImports(exportingModuleSymbol2);
    if (theseDirectImports) {
      for (const direct of theseDirectImports) {
        if (!markSeenDirectImport(direct)) {
          continue;
        }
        if (cancellationToken) cancellationToken.throwIfCancellationRequested();
        switch (direct.kind) {
          case 213 /* CallExpression */:
            if (isImportCall(direct)) {
              handleImportCall(direct);
              break;
            }
            if (!isAvailableThroughGlobal) {
              const parent2 = direct.parent;
              if (exportKind === 2 /* ExportEquals */ && parent2.kind === 260 /* VariableDeclaration */) {
                const { name } = parent2;
                if (name.kind === 80 /* Identifier */) {
                  directImports.push(name);
                  break;
                }
              }
            }
            break;
          case 80 /* Identifier */:
            break;
          // TODO: GH#23879
          case 271 /* ImportEqualsDeclaration */:
            handleNamespaceImport(
              direct,
              direct.name,
              hasSyntacticModifier(direct, 32 /* Export */),
              /*alreadyAddedDirect*/
              false
            );
            break;
          case 272 /* ImportDeclaration */:
          case 351 /* JSDocImportTag */:
            directImports.push(direct);
            const namedBindings = direct.importClause && direct.importClause.namedBindings;
            if (namedBindings && namedBindings.kind === 274 /* NamespaceImport */) {
              handleNamespaceImport(
                direct,
                namedBindings.name,
                /*isReExport*/
                false,
                /*alreadyAddedDirect*/
                true
              );
            } else if (!isAvailableThroughGlobal && isDefaultImport(direct)) {
              addIndirectUser(getSourceFileLikeForImportDeclaration(direct));
            }
            break;
          case 278 /* ExportDeclaration */:
            if (!direct.exportClause) {
              handleDirectImports(getContainingModuleSymbol(direct, checker));
            } else if (direct.exportClause.kind === 280 /* NamespaceExport */) {
              addIndirectUser(
                getSourceFileLikeForImportDeclaration(direct),
                /*addTransitiveDependencies*/
                true
              );
            } else {
              directImports.push(direct);
            }
            break;
          case 205 /* ImportType */:
            if (!isAvailableThroughGlobal && direct.isTypeOf && !direct.qualifier && isExported2(direct)) {
              addIndirectUser(
                direct.getSourceFile(),
                /*addTransitiveDependencies*/
                true
              );
            }
            directImports.push(direct);
            break;
          default:
            Debug.failBadSyntaxKind(direct, "Unexpected import kind.");
        }
      }
    }
  }
  function handleImportCall(importCall) {
    const top = findAncestor(importCall, isAmbientModuleDeclaration) || importCall.getSourceFile();
    addIndirectUser(
      top,
      /** addTransitiveDependencies */
      !!isExported2(
        importCall,
        /*stopAtAmbientModule*/
        true
      )
    );
  }
  function isExported2(node, stopAtAmbientModule = false) {
    return findAncestor(node, (node2) => {
      if (stopAtAmbientModule && isAmbientModuleDeclaration(node2)) return "quit";
      return canHaveModifiers(node2) && some(node2.modifiers, isExportModifier);
    });
  }
  function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) {
    if (exportKind === 2 /* ExportEquals */) {
      if (!alreadyAddedDirect) directImports.push(importDeclaration);
    } else if (!isAvailableThroughGlobal) {
      const sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
      Debug.assert(sourceFileLike.kind === 307 /* SourceFile */ || sourceFileLike.kind === 267 /* ModuleDeclaration */);
      if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
        addIndirectUser(
          sourceFileLike,
          /*addTransitiveDependencies*/
          true
        );
      } else {
        addIndirectUser(sourceFileLike);
      }
    }
  }
  function addIndirectUser(sourceFileLike, addTransitiveDependencies = false) {
    Debug.assert(!isAvailableThroughGlobal);
    const isNew = markSeenIndirectUser(sourceFileLike);
    if (!isNew) return;
    indirectUserDeclarations.push(sourceFileLike);
    if (!addTransitiveDependencies) return;
    const moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol);
    if (!moduleSymbol) return;
    Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */));
    const directImports2 = getDirectImports(moduleSymbol);
    if (directImports2) {
      for (const directImport of directImports2) {
        if (!isImportTypeNode(directImport)) {
          addIndirectUser(
            getSourceFileLikeForImportDeclaration(directImport),
            /*addTransitiveDependencies*/
            true
          );
        }
      }
    }
  }
  function getDirectImports(moduleSymbol) {
    return allDirectImports.get(getSymbolId(moduleSymbol).toString());
  }
}
function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) {
  const importSearches = [];
  const singleReferences = [];
  function addSearch(location, symbol) {
    importSearches.push([location, symbol]);
  }
  if (directImports) {
    for (const decl of directImports) {
      handleImport(decl);
    }
  }
  return { importSearches, singleReferences };
  function handleImport(decl) {
    if (decl.kind === 271 /* ImportEqualsDeclaration */) {
      if (isExternalModuleImportEquals(decl)) {
        handleNamespaceImportLike(decl.name);
      }
      return;
    }
    if (decl.kind === 80 /* Identifier */) {
      handleNamespaceImportLike(decl);
      return;
    }
    if (decl.kind === 205 /* ImportType */) {
      if (decl.qualifier) {
        const firstIdentifier = getFirstIdentifier(decl.qualifier);
        if (firstIdentifier.escapedText === symbolName(exportSymbol)) {
          singleReferences.push(firstIdentifier);
        }
      } else if (exportKind === 2 /* ExportEquals */) {
        singleReferences.push(decl.argument.literal);
      }
      return;
    }
    if (decl.moduleSpecifier.kind !== 11 /* StringLiteral */) {
      return;
    }
    if (decl.kind === 278 /* ExportDeclaration */) {
      if (decl.exportClause && isNamedExports(decl.exportClause)) {
        searchForNamedImport(decl.exportClause);
      }
      return;
    }
    const { name, namedBindings } = decl.importClause || { name: void 0, namedBindings: void 0 };
    if (namedBindings) {
      switch (namedBindings.kind) {
        case 274 /* NamespaceImport */:
          handleNamespaceImportLike(namedBindings.name);
          break;
        case 275 /* NamedImports */:
          if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) {
            searchForNamedImport(namedBindings);
          }
          break;
        default:
          Debug.assertNever(namedBindings);
      }
    }
    if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === symbolEscapedNameNoDefault(exportSymbol))) {
      const defaultImportAlias = checker.getSymbolAtLocation(name);
      addSearch(name, defaultImportAlias);
    }
  }
  function handleNamespaceImportLike(importName) {
    if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) {
      addSearch(importName, checker.getSymbolAtLocation(importName));
    }
  }
  function searchForNamedImport(namedBindings) {
    if (!namedBindings) {
      return;
    }
    for (const element of namedBindings.elements) {
      const { name, propertyName } = element;
      if (!isNameMatch(moduleExportNameTextEscaped(propertyName || name))) {
        continue;
      }
      if (propertyName) {
        singleReferences.push(propertyName);
        if (!isForRename || moduleExportNameTextEscaped(name) === exportSymbol.escapedName) {
          addSearch(name, checker.getSymbolAtLocation(name));
        }
      } else {
        const localSymbol = element.kind === 281 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) : checker.getSymbolAtLocation(name);
        addSearch(name, localSymbol);
      }
    }
  }
  function isNameMatch(name) {
    return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */;
  }
}
function findNamespaceReExports(sourceFileLike, name, checker) {
  const namespaceImportSymbol = checker.getSymbolAtLocation(name);
  return !!forEachPossibleImportOrExportStatement(sourceFileLike, (statement) => {
    if (!isExportDeclaration(statement)) return;
    const { exportClause, moduleSpecifier } = statement;
    return !moduleSpecifier && exportClause && isNamedExports(exportClause) && exportClause.elements.some((element) => checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol);
  });
}
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
  var _a;
  const refs = [];
  const checker = program.getTypeChecker();
  for (const referencingFile of sourceFiles) {
    const searchSourceFile = searchModuleSymbol.valueDeclaration;
    if ((searchSourceFile == null ? void 0 : searchSourceFile.kind) === 307 /* SourceFile */) {
      for (const ref of referencingFile.referencedFiles) {
        if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
          refs.push({ kind: "reference", referencingFile, ref });
        }
      }
      for (const ref of referencingFile.typeReferenceDirectives) {
        const referenced = (_a = program.getResolvedTypeReferenceDirectiveFromTypeReferenceDirective(ref, referencingFile)) == null ? void 0 : _a.resolvedTypeReferenceDirective;
        if (referenced !== void 0 && referenced.resolvedFileName === searchSourceFile.fileName) {
          refs.push({ kind: "reference", referencingFile, ref });
        }
      }
    }
    forEachImport(referencingFile, (importDecl, moduleSpecifier) => {
      const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
      if (moduleSymbol === searchModuleSymbol) {
        refs.push(nodeIsSynthesized(importDecl) ? { kind: "implicit", literal: moduleSpecifier, referencingFile } : { kind: "import", literal: moduleSpecifier });
      }
    });
  }
  return refs;
}
function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
  const map2 = /* @__PURE__ */ new Map();
  for (const sourceFile of sourceFiles) {
    if (cancellationToken) cancellationToken.throwIfCancellationRequested();
    forEachImport(sourceFile, (importDecl, moduleSpecifier) => {
      const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
      if (moduleSymbol) {
        const id = getSymbolId(moduleSymbol).toString();
        let imports = map2.get(id);
        if (!imports) {
          map2.set(id, imports = []);
        }
        imports.push(importDecl);
      }
    });
  }
  return map2;
}
function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
  return forEach(sourceFileLike.kind === 307 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, (statement) => (
    // TODO: GH#18217
    action(statement) || isAmbientModuleDeclaration(statement) && forEach(statement.body && statement.body.statements, action)
  ));
}
function forEachImport(sourceFile, action) {
  if (sourceFile.externalModuleIndicator || sourceFile.imports !== void 0) {
    for (const i of sourceFile.imports) {
      action(importFromModuleSpecifier(i), i);
    }
  } else {
    forEachPossibleImportOrExportStatement(sourceFile, (statement) => {
      switch (statement.kind) {
        case 278 /* ExportDeclaration */:
        case 272 /* ImportDeclaration */: {
          const decl = statement;
          if (decl.moduleSpecifier && isStringLiteral(decl.moduleSpecifier)) {
            action(decl, decl.moduleSpecifier);
          }
          break;
        }
        case 271 /* ImportEqualsDeclaration */: {
          const decl = statement;
          if (isExternalModuleImportEquals(decl)) {
            action(decl, decl.moduleReference.expression);
          }
          break;
        }
      }
    });
  }
}
function getImportOrExportSymbol(node, symbol, checker, comingFromExport) {
  return comingFromExport ? getExport() : getExport() || getImport();
  function getExport() {
    var _a;
    const { parent: parent2 } = node;
    const grandparent = parent2.parent;
    if (symbol.exportSymbol) {
      if (parent2.kind === 211 /* PropertyAccessExpression */) {
        return ((_a = symbol.declarations) == null ? void 0 : _a.some((d) => d === parent2)) && isBinaryExpression(grandparent) ? getSpecialPropertyExport(
          grandparent,
          /*useLhsSymbol*/
          false
        ) : void 0;
      } else {
        return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent2));
      }
    } else {
      const exportNode = getExportNode(parent2, node);
      if (exportNode && hasSyntacticModifier(exportNode, 32 /* Export */)) {
        if (isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) {
          if (comingFromExport) {
            return void 0;
          }
          const lhsSymbol = checker.getSymbolAtLocation(exportNode.name);
          return { kind: 0 /* Import */, symbol: lhsSymbol };
        } else {
          return exportInfo(symbol, getExportKindForDeclaration(exportNode));
        }
      } else if (isNamespaceExport(parent2)) {
        return exportInfo(symbol, 0 /* Named */);
      } else if (isExportAssignment(parent2)) {
        return getExportAssignmentExport(parent2);
      } else if (isExportAssignment(grandparent)) {
        return getExportAssignmentExport(grandparent);
      } else if (isBinaryExpression(parent2)) {
        return getSpecialPropertyExport(
          parent2,
          /*useLhsSymbol*/
          true
        );
      } else if (isBinaryExpression(grandparent)) {
        return getSpecialPropertyExport(
          grandparent,
          /*useLhsSymbol*/
          true
        );
      } else if (isJSDocTypedefTag(parent2) || isJSDocCallbackTag(parent2)) {
        return exportInfo(symbol, 0 /* Named */);
      }
    }
    function getExportAssignmentExport(ex) {
      if (!ex.symbol.parent) return void 0;
      const exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */;
      return { kind: 1 /* Export */, symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind } };
    }
    function getSpecialPropertyExport(node2, useLhsSymbol) {
      let kind;
      switch (getAssignmentDeclarationKind(node2)) {
        case 1 /* ExportsProperty */:
          kind = 0 /* Named */;
          break;
        case 2 /* ModuleExports */:
          kind = 2 /* ExportEquals */;
          break;
        default:
          return void 0;
      }
      const sym = useLhsSymbol ? checker.getSymbolAtLocation(getNameOfAccessExpression(cast(node2.left, isAccessExpression))) : symbol;
      return sym && exportInfo(sym, kind);
    }
  }
  function getImport() {
    const isImport3 = isNodeImport(node);
    if (!isImport3) return void 0;
    let importedSymbol = checker.getImmediateAliasedSymbol(symbol);
    if (!importedSymbol) return void 0;
    importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker);
    if (importedSymbol.escapedName === "export=") {
      importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker);
      if (importedSymbol === void 0) return void 0;
    }
    const importedName = symbolEscapedNameNoDefault(importedSymbol);
    if (importedName === void 0 || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
      return { kind: 0 /* Import */, symbol: importedSymbol };
    }
  }
  function exportInfo(symbol2, kind) {
    const exportInfo2 = getExportInfo(symbol2, kind, checker);
    return exportInfo2 && { kind: 1 /* Export */, symbol: symbol2, exportInfo: exportInfo2 };
  }
  function getExportKindForDeclaration(node2) {
    return hasSyntacticModifier(node2, 2048 /* Default */) ? 1 /* Default */ : 0 /* Named */;
  }
}
function getExportEqualsLocalSymbol(importedSymbol, checker) {
  var _a, _b;
  if (importedSymbol.flags & 2097152 /* Alias */) {
    return checker.getImmediateAliasedSymbol(importedSymbol);
  }
  const decl = Debug.checkDefined(importedSymbol.valueDeclaration);
  if (isExportAssignment(decl)) {
    return (_a = tryCast(decl.expression, canHaveSymbol)) == null ? void 0 : _a.symbol;
  } else if (isBinaryExpression(decl)) {
    return (_b = tryCast(decl.right, canHaveSymbol)) == null ? void 0 : _b.symbol;
  } else if (isSourceFile(decl)) {
    return decl.symbol;
  }
  return void 0;
}
function getExportNode(parent2, node) {
  const declaration = isVariableDeclaration(parent2) ? parent2 : isBindingElement(parent2) ? walkUpBindingElementsAndPatterns(parent2) : void 0;
  if (declaration) {
    return parent2.name !== node ? void 0 : isCatchClause(declaration.parent) ? void 0 : isVariableStatement(declaration.parent.parent) ? declaration.parent.parent : void 0;
  } else {
    return parent2;
  }
}
function isNodeImport(node) {
  const { parent: parent2 } = node;
  switch (parent2.kind) {
    case 271 /* ImportEqualsDeclaration */:
      return parent2.name === node && isExternalModuleImportEquals(parent2);
    case 276 /* ImportSpecifier */:
      return !parent2.propertyName;
    case 273 /* ImportClause */:
    case 274 /* NamespaceImport */:
      Debug.assert(parent2.name === node);
      return true;
    case 208 /* BindingElement */:
      return isInJSFile(node) && isVariableDeclarationInitializedToBareOrAccessedRequire(parent2.parent.parent);
    default:
      return false;
  }
}
function getExportInfo(exportSymbol, exportKind, checker) {
  const moduleSymbol = exportSymbol.parent;
  if (!moduleSymbol) return void 0;
  const exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol);
  return isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol, exportKind } : void 0;
}
function skipExportSpecifierSymbol(symbol, checker) {
  if (symbol.declarations) {
    for (const declaration of symbol.declarations) {
      if (isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) {
        return checker.getExportSpecifierLocalTargetSymbol(declaration) || symbol;
      } else if (isPropertyAccessExpression(declaration) && isModuleExportsAccessExpression(declaration.expression) && !isPrivateIdentifier(declaration.name)) {
        return checker.getSymbolAtLocation(declaration);
      } else if (isShorthandPropertyAssignment(declaration) && isBinaryExpression(declaration.parent.parent) && getAssignmentDeclarationKind(declaration.parent.parent) === 2 /* ModuleExports */) {
        return checker.getExportSpecifierLocalTargetSymbol(declaration.name);
      }
    }
  }
  return symbol;
}
function getContainingModuleSymbol(importer, checker) {
  return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol);
}
function getSourceFileLikeForImportDeclaration(node) {
  if (node.kind === 213 /* CallExpression */ || node.kind === 351 /* JSDocImportTag */) {
    return node.getSourceFile();
  }
  const { parent: parent2 } = node;
  if (parent2.kind === 307 /* SourceFile */) {
    return parent2;
  }
  Debug.assert(parent2.kind === 268 /* ModuleBlock */);
  return cast(parent2.parent, isAmbientModuleDeclaration);
}
function isAmbientModuleDeclaration(node) {
  return node.kind === 267 /* ModuleDeclaration */ && node.name.kind === 11 /* StringLiteral */;
}
function isExternalModuleImportEquals(eq) {
  return eq.moduleReference.kind === 283 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 11 /* StringLiteral */;
}

// src/services/findAllReferences.ts
var DefinitionKind = /* @__PURE__ */ ((DefinitionKind2) => {
  DefinitionKind2[DefinitionKind2["Symbol"] = 0] = "Symbol";
  DefinitionKind2[DefinitionKind2["Label"] = 1] = "Label";
  DefinitionKind2[DefinitionKind2["Keyword"] = 2] = "Keyword";
  DefinitionKind2[DefinitionKind2["This"] = 3] = "This";
  DefinitionKind2[DefinitionKind2["String"] = 4] = "String";
  DefinitionKind2[DefinitionKind2["TripleSlashReference"] = 5] = "TripleSlashReference";
  return DefinitionKind2;
})(DefinitionKind || {});
var EntryKind = /* @__PURE__ */ ((EntryKind2) => {
  EntryKind2[EntryKind2["Span"] = 0] = "Span";
  EntryKind2[EntryKind2["Node"] = 1] = "Node";
  EntryKind2[EntryKind2["StringLiteral"] = 2] = "StringLiteral";
  EntryKind2[EntryKind2["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty";
  EntryKind2[EntryKind2["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal";
  return EntryKind2;
})(EntryKind || {});
function nodeEntry(node, kind = 1 /* Node */) {
  return {
    kind,
    node: node.name || node,
    context: getContextNodeForNodeEntry(node)
  };
}
function isContextWithStartAndEndNode(node) {
  return node && node.kind === void 0;
}
function getContextNodeForNodeEntry(node) {
  if (isDeclaration(node)) {
    return getContextNode(node);
  }
  if (!node.parent) return void 0;
  if (!isDeclaration(node.parent) && !isExportAssignment(node.parent)) {
    if (isInJSFile(node)) {
      const binaryExpression = isBinaryExpression(node.parent) ? node.parent : isAccessExpression(node.parent) && isBinaryExpression(node.parent.parent) && node.parent.parent.left === node.parent ? node.parent.parent : void 0;
      if (binaryExpression && getAssignmentDeclarationKind(binaryExpression) !== 0 /* None */) {
        return getContextNode(binaryExpression);
      }
    }
    if (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) {
      return node.parent.parent;
    } else if (isJsxSelfClosingElement(node.parent) || isLabeledStatement(node.parent) || isBreakOrContinueStatement(node.parent)) {
      return node.parent;
    } else if (isStringLiteralLike(node)) {
      const validImport = tryGetImportFromModuleSpecifier(node);
      if (validImport) {
        const declOrStatement = findAncestor(validImport, (node2) => isDeclaration(node2) || isStatement(node2) || isJSDocTag(node2));
        return isDeclaration(declOrStatement) ? getContextNode(declOrStatement) : declOrStatement;
      }
    }
    const propertyName = findAncestor(node, isComputedPropertyName);
    return propertyName ? getContextNode(propertyName.parent) : void 0;
  }
  if (node.parent.name === node || // node is name of declaration, use parent
  isConstructorDeclaration(node.parent) || isExportAssignment(node.parent) || // Property name of the import export specifier or binding pattern, use parent
  (isImportOrExportSpecifier(node.parent) || isBindingElement(node.parent)) && node.parent.propertyName === node || // Is default export
  node.kind === 90 /* DefaultKeyword */ && hasSyntacticModifier(node.parent, 2080 /* ExportDefault */)) {
    return getContextNode(node.parent);
  }
  return void 0;
}
function getContextNode(node) {
  if (!node) return void 0;
  switch (node.kind) {
    case 260 /* VariableDeclaration */:
      return !isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ? node : isVariableStatement(node.parent.parent) ? node.parent.parent : isForInOrOfStatement(node.parent.parent) ? getContextNode(node.parent.parent) : node.parent;
    case 208 /* BindingElement */:
      return getContextNode(node.parent.parent);
    case 276 /* ImportSpecifier */:
      return node.parent.parent.parent;
    case 281 /* ExportSpecifier */:
    case 274 /* NamespaceImport */:
      return node.parent.parent;
    case 273 /* ImportClause */:
    case 280 /* NamespaceExport */:
      return node.parent;
    case 226 /* BinaryExpression */:
      return isExpressionStatement(node.parent) ? node.parent : node;
    case 250 /* ForOfStatement */:
    case 249 /* ForInStatement */:
      return {
        start: node.initializer,
        end: node.expression
      };
    case 303 /* PropertyAssignment */:
    case 304 /* ShorthandPropertyAssignment */:
      return isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode(
        findAncestor(node.parent, (node2) => isBinaryExpression(node2) || isForInOrOfStatement(node2))
      ) : node;
    case 255 /* SwitchStatement */:
      return {
        start: find(node.getChildren(node.getSourceFile()), (node2) => node2.kind === 109 /* SwitchKeyword */),
        end: node.caseBlock
      };
    default:
      return node;
  }
}
function toContextSpan(textSpan, sourceFile, context) {
  if (!context) return void 0;
  const contextSpan = isContextWithStartAndEndNode(context) ? getTextSpan(context.start, sourceFile, context.end) : getTextSpan(context, sourceFile);
  return contextSpan.start !== textSpan.start || contextSpan.length !== textSpan.length ? { contextSpan } : void 0;
}
var FindReferencesUse = /* @__PURE__ */ ((FindReferencesUse2) => {
  FindReferencesUse2[FindReferencesUse2["Other"] = 0] = "Other";
  FindReferencesUse2[FindReferencesUse2["References"] = 1] = "References";
  FindReferencesUse2[FindReferencesUse2["Rename"] = 2] = "Rename";
  return FindReferencesUse2;
})(FindReferencesUse || {});
function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) {
  const node = getTouchingPropertyName(sourceFile, position);
  const options = { use: 1 /* References */ };
  const referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options);
  const checker = program.getTypeChecker();
  const adjustedNode = Core.getAdjustedNode(node, options);
  const symbol = isDefinitionForReference(adjustedNode) ? checker.getSymbolAtLocation(adjustedNode) : void 0;
  return !referencedSymbols || !referencedSymbols.length ? void 0 : mapDefined(referencedSymbols, ({ definition, references }) => (
    // Only include referenced symbols that have a valid definition.
    definition && {
      definition: checker.runWithCancellationToken(cancellationToken, (checker2) => definitionToReferencedSymbolDefinitionInfo(definition, checker2, node)),
      references: references.map((r) => toReferencedSymbolEntry(r, symbol))
    }
  ));
}
function isDefinitionForReference(node) {
  return node.kind === 90 /* DefaultKeyword */ || !!getDeclarationFromName(node) || isLiteralComputedPropertyDeclarationName(node) || node.kind === 137 /* ConstructorKeyword */ && isConstructorDeclaration(node.parent);
}
function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) {
  const node = getTouchingPropertyName(sourceFile, position);
  let referenceEntries;
  const entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position);
  if (node.parent.kind === 211 /* PropertyAccessExpression */ || node.parent.kind === 208 /* BindingElement */ || node.parent.kind === 212 /* ElementAccessExpression */ || node.kind === 108 /* SuperKeyword */) {
    referenceEntries = entries && [...entries];
  } else if (entries) {
    const queue = createQueue(entries);
    const seenNodes = /* @__PURE__ */ new Set();
    while (!queue.isEmpty()) {
      const entry = queue.dequeue();
      if (!addToSeen(seenNodes, getNodeId(entry.node))) {
        continue;
      }
      referenceEntries = append(referenceEntries, entry);
      const entries2 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos);
      if (entries2) {
        queue.enqueue(...entries2);
      }
    }
  }
  const checker = program.getTypeChecker();
  return map(referenceEntries, (entry) => toImplementationLocation(entry, checker));
}
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
  if (node.kind === 307 /* SourceFile */) {
    return void 0;
  }
  const checker = program.getTypeChecker();
  if (node.parent.kind === 304 /* ShorthandPropertyAssignment */) {
    const result = [];
    Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, (node2) => result.push(nodeEntry(node2)));
    return result;
  } else if (node.kind === 108 /* SuperKeyword */ || isSuperProperty(node.parent)) {
    const symbol = checker.getSymbolAtLocation(node);
    return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)];
  } else {
    return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true, use: 1 /* References */ });
  }
}
function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) {
  return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), (entry) => convertEntry(entry, node, program.getTypeChecker()));
}
function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map((f) => f.fileName))) {
  return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet));
}
function flattenEntries(referenceSymbols) {
  return referenceSymbols && flatMap(referenceSymbols, (r) => r.references);
}
function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) {
  const info = (() => {
    switch (def.type) {
      case 0 /* Symbol */: {
        const { symbol } = def;
        const { displayParts: displayParts2, kind: kind2 } = getDefinitionKindAndDisplayParts(symbol, checker, originalNode);
        const name2 = displayParts2.map((p) => p.text).join("");
        const declaration = symbol.declarations && firstOrUndefined(symbol.declarations);
        const node = declaration ? getNameOfDeclaration(declaration) || declaration : originalNode;
        return {
          ...getFileAndTextSpanFromNode(node),
          name: name2,
          kind: kind2,
          displayParts: displayParts2,
          context: getContextNode(declaration)
        };
      }
      case 1 /* Label */: {
        const { node } = def;
        return { ...getFileAndTextSpanFromNode(node), name: node.text, kind: "label" /* label */, displayParts: [displayPart(node.text, 17 /* text */)] };
      }
      case 2 /* Keyword */: {
        const { node } = def;
        const name2 = tokenToString(node.kind);
        return { ...getFileAndTextSpanFromNode(node), name: name2, kind: "keyword" /* keyword */, displayParts: [{ text: name2, kind: "keyword" /* keyword */ }] };
      }
      case 3 /* This */: {
        const { node } = def;
        const symbol = checker.getSymbolAtLocation(node);
        const displayParts2 = symbol && ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(
          checker,
          symbol,
          node.getSourceFile(),
          getContainerNode(node),
          node
        ).displayParts || [textPart("this")];
        return { ...getFileAndTextSpanFromNode(node), name: "this", kind: "var" /* variableElement */, displayParts: displayParts2 };
      }
      case 4 /* String */: {
        const { node } = def;
        return {
          ...getFileAndTextSpanFromNode(node),
          name: node.text,
          kind: "var" /* variableElement */,
          displayParts: [displayPart(getTextOfNode(node), 8 /* stringLiteral */)]
        };
      }
      case 5 /* TripleSlashReference */: {
        return {
          textSpan: createTextSpanFromRange(def.reference),
          sourceFile: def.file,
          name: def.reference.fileName,
          kind: "string" /* string */,
          displayParts: [displayPart(`"${def.reference.fileName}"`, 8 /* stringLiteral */)]
        };
      }
      default:
        return Debug.assertNever(def);
    }
  })();
  const { sourceFile, textSpan, name, kind, displayParts, context } = info;
  return {
    containerKind: "" /* unknown */,
    containerName: "",
    fileName: sourceFile.fileName,
    kind,
    name,
    textSpan,
    displayParts,
    ...toContextSpan(textSpan, sourceFile, context)
  };
}
function getFileAndTextSpanFromNode(node) {
  const sourceFile = node.getSourceFile();
  return {
    sourceFile,
    textSpan: getTextSpan(isComputedPropertyName(node) ? node.expression : node, sourceFile)
  };
}
function getDefinitionKindAndDisplayParts(symbol, checker, node) {
  const meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol);
  const enclosingDeclaration = symbol.declarations && firstOrUndefined(symbol.declarations) || node;
  const { displayParts, symbolKind } = ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning);
  return { displayParts, kind: symbolKind };
}
function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText, quotePreference) {
  return { ...entryToDocumentSpan(entry), ...providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) };
}
function toReferencedSymbolEntry(entry, symbol) {
  const referenceEntry = toReferenceEntry(entry);
  if (!symbol) return referenceEntry;
  return {
    ...referenceEntry,
    isDefinition: entry.kind !== 0 /* Span */ && isDeclarationOfSymbol(entry.node, symbol)
  };
}
function toReferenceEntry(entry) {
  const documentSpan = entryToDocumentSpan(entry);
  if (entry.kind === 0 /* Span */) {
    return { ...documentSpan, isWriteAccess: false };
  }
  const { kind, node } = entry;
  return {
    ...documentSpan,
    isWriteAccess: isWriteAccessForReference(node),
    isInString: kind === 2 /* StringLiteral */ ? true : void 0
  };
}
function entryToDocumentSpan(entry) {
  if (entry.kind === 0 /* Span */) {
    return { textSpan: entry.textSpan, fileName: entry.fileName };
  } else {
    const sourceFile = entry.node.getSourceFile();
    const textSpan = getTextSpan(entry.node, sourceFile);
    return {
      textSpan,
      fileName: sourceFile.fileName,
      ...toContextSpan(textSpan, sourceFile, entry.context)
    };
  }
}
function getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) {
  if (entry.kind !== 0 /* Span */ && (isIdentifier(originalNode) || isStringLiteralLike(originalNode))) {
    const { node, kind } = entry;
    const parent2 = node.parent;
    const name = originalNode.text;
    const isShorthandAssignment = isShorthandPropertyAssignment(parent2);
    if (isShorthandAssignment || isObjectBindingElementWithoutPropertyName(parent2) && parent2.name === node && parent2.dotDotDotToken === void 0) {
      const prefixColon = { prefixText: name + ": " };
      const suffixColon = { suffixText: ": " + name };
      if (kind === 3 /* SearchedLocalFoundProperty */) {
        return prefixColon;
      }
      if (kind === 4 /* SearchedPropertyFoundLocal */) {
        return suffixColon;
      }
      if (isShorthandAssignment) {
        const grandParent = parent2.parent;
        if (isObjectLiteralExpression(grandParent) && isBinaryExpression(grandParent.parent) && isModuleExportsAccessExpression(grandParent.parent.left)) {
          return prefixColon;
        }
        return suffixColon;
      } else {
        return prefixColon;
      }
    } else if (isImportSpecifier(parent2) && !parent2.propertyName) {
      const originalSymbol = isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode);
      return contains(originalSymbol.declarations, parent2) ? { prefixText: name + " as " } : emptyOptions;
    } else if (isExportSpecifier(parent2) && !parent2.propertyName) {
      return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ? { prefixText: name + " as " } : { suffixText: " as " + name };
    }
  }
  if (entry.kind !== 0 /* Span */ && isNumericLiteral(entry.node) && isAccessExpression(entry.node.parent)) {
    const quote2 = getQuoteFromPreference(quotePreference);
    return { prefixText: quote2, suffixText: quote2 };
  }
  return emptyOptions;
}
function toImplementationLocation(entry, checker) {
  const documentSpan = entryToDocumentSpan(entry);
  if (entry.kind !== 0 /* Span */) {
    const { node } = entry;
    return {
      ...documentSpan,
      ...implementationKindDisplayParts(node, checker)
    };
  } else {
    return { ...documentSpan, kind: "" /* unknown */, displayParts: [] };
  }
}
function implementationKindDisplayParts(node, checker) {
  const symbol = checker.getSymbolAtLocation(isDeclaration(node) && node.name ? node.name : node);
  if (symbol) {
    return getDefinitionKindAndDisplayParts(symbol, checker, node);
  } else if (node.kind === 210 /* ObjectLiteralExpression */) {
    return {
      kind: "interface" /* interfaceElement */,
      displayParts: [punctuationPart(21 /* OpenParenToken */), textPart("object literal"), punctuationPart(22 /* CloseParenToken */)]
    };
  } else if (node.kind === 231 /* ClassExpression */) {
    return {
      kind: "local class" /* localClassElement */,
      displayParts: [punctuationPart(21 /* OpenParenToken */), textPart("anonymous local class"), punctuationPart(22 /* CloseParenToken */)]
    };
  } else {
    return { kind: getNodeKind(node), displayParts: [] };
  }
}
function toHighlightSpan(entry) {
  const documentSpan = entryToDocumentSpan(entry);
  if (entry.kind === 0 /* Span */) {
    return {
      fileName: documentSpan.fileName,
      span: {
        textSpan: documentSpan.textSpan,
        kind: "reference" /* reference */
      }
    };
  }
  const writeAccess = isWriteAccessForReference(entry.node);
  const span = {
    textSpan: documentSpan.textSpan,
    kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */,
    isInString: entry.kind === 2 /* StringLiteral */ ? true : void 0,
    ...documentSpan.contextSpan && { contextSpan: documentSpan.contextSpan }
  };
  return { fileName: documentSpan.fileName, span };
}
function getTextSpan(node, sourceFile, endNode2) {
  let start = node.getStart(sourceFile);
  let end = (endNode2 || node).getEnd();
  if (isStringLiteralLike(node) && end - start > 2) {
    Debug.assert(endNode2 === void 0);
    start += 1;
    end -= 1;
  }
  if ((endNode2 == null ? void 0 : endNode2.kind) === 269 /* CaseBlock */) {
    end = endNode2.getFullStart();
  }
  return createTextSpanFromBounds(start, end);
}
function getTextSpanOfEntry(entry) {
  return entry.kind === 0 /* Span */ ? entry.textSpan : getTextSpan(entry.node, entry.node.getSourceFile());
}
function isWriteAccessForReference(node) {
  const decl = getDeclarationFromName(node);
  return !!decl && declarationIsWriteAccess(decl) || node.kind === 90 /* DefaultKeyword */ || isWriteAccess(node);
}
function isDeclarationOfSymbol(node, target) {
  var _a;
  if (!target) return false;
  const source = getDeclarationFromName(node) || (node.kind === 90 /* DefaultKeyword */ ? node.parent : isLiteralComputedPropertyDeclarationName(node) ? node.parent.parent : node.kind === 137 /* ConstructorKeyword */ && isConstructorDeclaration(node.parent) ? node.parent.parent : void 0);
  const commonjsSource = source && isBinaryExpression(source) ? source.left : void 0;
  return !!(source && ((_a = target.declarations) == null ? void 0 : _a.some((d) => d === source || d === commonjsSource)));
}
function declarationIsWriteAccess(decl) {
  if (!!(decl.flags & 33554432 /* Ambient */)) return true;
  switch (decl.kind) {
    case 226 /* BinaryExpression */:
    case 208 /* BindingElement */:
    case 263 /* ClassDeclaration */:
    case 231 /* ClassExpression */:
    case 90 /* DefaultKeyword */:
    case 266 /* EnumDeclaration */:
    case 306 /* EnumMember */:
    case 281 /* ExportSpecifier */:
    case 273 /* ImportClause */:
    // default import
    case 271 /* ImportEqualsDeclaration */:
    case 276 /* ImportSpecifier */:
    case 264 /* InterfaceDeclaration */:
    case 338 /* JSDocCallbackTag */:
    case 346 /* JSDocTypedefTag */:
    case 291 /* JsxAttribute */:
    case 267 /* ModuleDeclaration */:
    case 270 /* NamespaceExportDeclaration */:
    case 274 /* NamespaceImport */:
    case 280 /* NamespaceExport */:
    case 169 /* Parameter */:
    case 304 /* ShorthandPropertyAssignment */:
    case 265 /* TypeAliasDeclaration */:
    case 168 /* TypeParameter */:
      return true;
    case 303 /* PropertyAssignment */:
      return !isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent);
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
    case 176 /* Constructor */:
    case 174 /* MethodDeclaration */:
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
      return !!decl.body;
    case 260 /* VariableDeclaration */:
    case 172 /* PropertyDeclaration */:
      return !!decl.initializer || isCatchClause(decl.parent);
    case 173 /* MethodSignature */:
    case 171 /* PropertySignature */:
    case 348 /* JSDocPropertyTag */:
    case 341 /* JSDocParameterTag */:
      return false;
    default:
      return Debug.failBadSyntaxKind(decl);
  }
}
var Core;
((Core2) => {
  function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map((f) => f.fileName))) {
    var _a, _b;
    node = getAdjustedNode2(node, options);
    if (isSourceFile(node)) {
      const resolvedRef = ts_GoToDefinition_exports.getReferenceAtPosition(node, position, program);
      if (!(resolvedRef == null ? void 0 : resolvedRef.file)) {
        return void 0;
      }
      const moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol);
      if (moduleSymbol) {
        return getReferencedSymbolsForModule(
          program,
          moduleSymbol,
          /*excludeImportTypeOfExportEquals*/
          false,
          sourceFiles,
          sourceFilesSet
        );
      }
      const fileIncludeReasons = program.getFileIncludeReasons();
      if (!fileIncludeReasons) {
        return void 0;
      }
      return [{
        definition: { type: 5 /* TripleSlashReference */, reference: resolvedRef.reference, file: node },
        references: getReferencesForNonModule(resolvedRef.file, fileIncludeReasons, program) || emptyArray
      }];
    }
    if (!options.implementations) {
      const special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
      if (special) {
        return special;
      }
    }
    const checker = program.getTypeChecker();
    const symbol = checker.getSymbolAtLocation(isConstructorDeclaration(node) && node.parent.name || node);
    if (!symbol) {
      if (!options.implementations && isStringLiteralLike(node)) {
        if (isModuleSpecifierLike(node)) {
          const fileIncludeReasons = program.getFileIncludeReasons();
          const referencedFileName = (_b = (_a = program.getResolvedModuleFromModuleSpecifier(node)) == null ? void 0 : _a.resolvedModule) == null ? void 0 : _b.resolvedFileName;
          const referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : void 0;
          if (referencedFile) {
            return [{ definition: { type: 4 /* String */, node }, references: getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || emptyArray }];
          }
        }
        return getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken);
      }
      return void 0;
    }
    if (symbol.escapedName === "export=" /* ExportEquals */) {
      return getReferencedSymbolsForModule(
        program,
        symbol.parent,
        /*excludeImportTypeOfExportEquals*/
        false,
        sourceFiles,
        sourceFilesSet
      );
    }
    const moduleReferences = getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
    if (moduleReferences && !(symbol.flags & 33554432 /* Transient */)) {
      return moduleReferences;
    }
    const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker);
    const moduleReferencesOfExportTarget = aliasedSymbol && getReferencedSymbolsForModuleIfDeclaredBySourceFile(aliasedSymbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
    const references = getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options);
    return mergeReferences(program, moduleReferences, references, moduleReferencesOfExportTarget);
  }
  Core2.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
  function getAdjustedNode2(node, options) {
    if (options.use === 1 /* References */) {
      node = getAdjustedReferenceLocation(node);
    } else if (options.use === 2 /* Rename */) {
      node = getAdjustedRenameLocation(node);
    }
    return node;
  }
  Core2.getAdjustedNode = getAdjustedNode2;
  function getReferencesForFileName(fileName, program, sourceFiles, sourceFilesSet = new Set(sourceFiles.map((f) => f.fileName))) {
    var _a, _b;
    const moduleSymbol = (_a = program.getSourceFile(fileName)) == null ? void 0 : _a.symbol;
    if (moduleSymbol) {
      return ((_b = getReferencedSymbolsForModule(
        program,
        moduleSymbol,
        /*excludeImportTypeOfExportEquals*/
        false,
        sourceFiles,
        sourceFilesSet
      )[0]) == null ? void 0 : _b.references) || emptyArray;
    }
    const fileIncludeReasons = program.getFileIncludeReasons();
    const referencedFile = program.getSourceFile(fileName);
    return referencedFile && fileIncludeReasons && getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || emptyArray;
  }
  Core2.getReferencesForFileName = getReferencesForFileName;
  function getReferencesForNonModule(referencedFile, refFileMap, program) {
    let entries;
    const references = refFileMap.get(referencedFile.path) || emptyArray;
    for (const ref of references) {
      if (isReferencedFile(ref)) {
        const referencingFile = program.getSourceFileByPath(ref.file);
        const location = getReferencedFileLocation(program, ref);
        if (isReferenceFileLocation(location)) {
          entries = append(entries, {
            kind: 0 /* Span */,
            fileName: referencingFile.fileName,
            textSpan: createTextSpanFromRange(location)
          });
        }
      }
    }
    return entries;
  }
  function getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker) {
    if (node.parent && isNamespaceExportDeclaration(node.parent)) {
      const aliasedSymbol = checker.getAliasedSymbol(symbol);
      const targetSymbol = checker.getMergedSymbol(aliasedSymbol);
      if (aliasedSymbol !== targetSymbol) {
        return targetSymbol;
      }
    }
    return void 0;
  }
  function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
    const moduleSourceFile = symbol.flags & 1536 /* Module */ && symbol.declarations && find(symbol.declarations, isSourceFile);
    if (!moduleSourceFile) return void 0;
    const exportEquals = symbol.exports.get("export=" /* ExportEquals */);
    const moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet);
    if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) return moduleReferences;
    const checker = program.getTypeChecker();
    symbol = skipAlias(exportEquals, checker);
    return mergeReferences(program, moduleReferences, getReferencedSymbolsForSymbol(
      symbol,
      /*node*/
      void 0,
      sourceFiles,
      sourceFilesSet,
      checker,
      cancellationToken,
      options
    ));
  }
  function mergeReferences(program, ...referencesToMerge) {
    let result;
    for (const references of referencesToMerge) {
      if (!references || !references.length) continue;
      if (!result) {
        result = references;
        continue;
      }
      for (const entry of references) {
        if (!entry.definition || entry.definition.type !== 0 /* Symbol */) {
          result.push(entry);
          continue;
        }
        const symbol = entry.definition.symbol;
        const refIndex = findIndex(result, (ref) => !!ref.definition && ref.definition.type === 0 /* Symbol */ && ref.definition.symbol === symbol);
        if (refIndex === -1) {
          result.push(entry);
          continue;
        }
        const reference = result[refIndex];
        result[refIndex] = {
          definition: reference.definition,
          references: reference.references.concat(entry.references).sort((entry1, entry2) => {
            const entry1File = getSourceFileIndexOfEntry(program, entry1);
            const entry2File = getSourceFileIndexOfEntry(program, entry2);
            if (entry1File !== entry2File) {
              return compareValues(entry1File, entry2File);
            }
            const entry1Span = getTextSpanOfEntry(entry1);
            const entry2Span = getTextSpanOfEntry(entry2);
            return entry1Span.start !== entry2Span.start ? compareValues(entry1Span.start, entry2Span.start) : compareValues(entry1Span.length, entry2Span.length);
          })
        };
      }
    }
    return result;
  }
  function getSourceFileIndexOfEntry(program, entry) {
    const sourceFile = entry.kind === 0 /* Span */ ? program.getSourceFile(entry.fileName) : entry.node.getSourceFile();
    return program.getSourceFiles().indexOf(sourceFile);
  }
  function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) {
    Debug.assert(!!symbol.valueDeclaration);
    const references = mapDefined(findModuleReferences(program, sourceFiles, symbol), (reference) => {
      if (reference.kind === "import") {
        const parent2 = reference.literal.parent;
        if (isLiteralTypeNode(parent2)) {
          const importType = cast(parent2.parent, isImportTypeNode);
          if (excludeImportTypeOfExportEquals && !importType.qualifier) {
            return void 0;
          }
        }
        return nodeEntry(reference.literal);
      } else if (reference.kind === "implicit") {
        const range = reference.literal.text !== externalHelpersModuleNameText && forEachChildRecursively(
          reference.referencingFile,
          (n) => !(n.transformFlags & 2 /* ContainsJsx */) ? "skip" : isJsxElement(n) || isJsxSelfClosingElement(n) || isJsxFragment(n) ? n : void 0
        ) || reference.referencingFile.statements[0] || reference.referencingFile;
        return nodeEntry(range);
      } else {
        return {
          kind: 0 /* Span */,
          fileName: reference.referencingFile.fileName,
          textSpan: createTextSpanFromRange(reference.ref)
        };
      }
    });
    if (symbol.declarations) {
      for (const decl of symbol.declarations) {
        switch (decl.kind) {
          case 307 /* SourceFile */:
            break;
          case 267 /* ModuleDeclaration */:
            if (sourceFilesSet.has(decl.getSourceFile().fileName)) {
              references.push(nodeEntry(decl.name));
            }
            break;
          default:
            Debug.assert(!!(symbol.flags & 33554432 /* Transient */), "Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
        }
      }
    }
    const exported = symbol.exports.get("export=" /* ExportEquals */);
    if (exported == null ? void 0 : exported.declarations) {
      for (const decl of exported.declarations) {
        const sourceFile = decl.getSourceFile();
        if (sourceFilesSet.has(sourceFile.fileName)) {
          const node = isBinaryExpression(decl) && isPropertyAccessExpression(decl.left) ? decl.left.expression : isExportAssignment(decl) ? Debug.checkDefined(findChildOfKind(decl, 95 /* ExportKeyword */, sourceFile)) : getNameOfDeclaration(decl) || decl;
          references.push(nodeEntry(node));
        }
      }
    }
    return references.length ? [{ definition: { type: 0 /* Symbol */, symbol }, references }] : emptyArray;
  }
  function isReadonlyTypeOperator(node) {
    return node.kind === 148 /* ReadonlyKeyword */ && isTypeOperatorNode(node.parent) && node.parent.operator === 148 /* ReadonlyKeyword */;
  }
  function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
    if (isTypeKeyword(node.kind)) {
      if (node.kind === 116 /* VoidKeyword */ && isVoidExpression(node.parent)) {
        return void 0;
      }
      if (node.kind === 148 /* ReadonlyKeyword */ && !isReadonlyTypeOperator(node)) {
        return void 0;
      }
      return getAllReferencesForKeyword(
        sourceFiles,
        node.kind,
        cancellationToken,
        node.kind === 148 /* ReadonlyKeyword */ ? isReadonlyTypeOperator : void 0
      );
    }
    if (isImportMeta(node.parent) && node.parent.name === node) {
      return getAllReferencesForImportMeta(sourceFiles, cancellationToken);
    }
    if (isStaticModifier(node) && isClassStaticBlockDeclaration(node.parent)) {
      return [{ definition: { type: 2 /* Keyword */, node }, references: [nodeEntry(node)] }];
    }
    if (isJumpStatementTarget(node)) {
      const labelDefinition = getTargetLabel(node.parent, node.text);
      return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
    } else if (isLabelOfLabeledStatement(node)) {
      return getLabelReferencesInNode(node.parent, node);
    }
    if (isThis(node)) {
      return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
    }
    if (node.kind === 108 /* SuperKeyword */) {
      return getReferencesForSuperKeyword(node);
    }
    return void 0;
  }
  function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
    const symbol = node && skipPastExportOrImportSpecifierOrUnion(
      originalSymbol,
      node,
      checker,
      /*useLocalSymbolForExportSpecifier*/
      !isForRenameWithPrefixAndSuffixText(options)
    ) || originalSymbol;
    const searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
    const result = [];
    const state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
    const exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) || !symbol.declarations ? void 0 : find(symbol.declarations, isExportSpecifier);
    if (exportSpecifier) {
      getReferencesAtExportSpecifier(
        exportSpecifier.name,
        symbol,
        exportSpecifier,
        state.createSearch(
          node,
          originalSymbol,
          /*comingFrom*/
          void 0
        ),
        state,
        /*addReferencesHere*/
        true,
        /*alwaysGetReferences*/
        true
      );
    } else if (node && node.kind === 90 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) {
      addReference(node, symbol, state);
      searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state);
    } else {
      const search = state.createSearch(
        node,
        symbol,
        /*comingFrom*/
        void 0,
        { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }
      );
      getReferencesInContainerOrFiles(symbol, state, search);
    }
    return result;
  }
  function getReferencesInContainerOrFiles(symbol, state, search) {
    const scope = getSymbolScope(symbol);
    if (scope) {
      getReferencesInContainer(
        scope,
        scope.getSourceFile(),
        search,
        state,
        /*addReferencesHere*/
        !(isSourceFile(scope) && !contains(state.sourceFiles, scope))
      );
    } else {
      for (const sourceFile of state.sourceFiles) {
        state.cancellationToken.throwIfCancellationRequested();
        searchForName(sourceFile, search, state);
      }
    }
  }
  function getSpecialSearchKind(node) {
    switch (node.kind) {
      case 176 /* Constructor */:
      case 137 /* ConstructorKeyword */:
        return 1 /* Constructor */;
      case 80 /* Identifier */:
        if (isClassLike(node.parent)) {
          Debug.assert(node.parent.name === node);
          return 2 /* Class */;
        }
      // falls through
      default:
        return 0 /* None */;
    }
  }
  function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) {
    const { parent: parent2 } = node;
    if (isExportSpecifier(parent2) && useLocalSymbolForExportSpecifier) {
      return getLocalSymbolForExportSpecifier(node, symbol, parent2, checker);
    }
    return firstDefined(symbol.declarations, (decl) => {
      if (!decl.parent) {
        if (symbol.flags & 33554432 /* Transient */) return void 0;
        Debug.fail(`Unexpected symbol at ${Debug.formatSyntaxKind(node.kind)}: ${Debug.formatSymbol(symbol)}`);
      }
      return isTypeLiteralNode(decl.parent) && isUnionTypeNode(decl.parent.parent) ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) : void 0;
    });
  }
  let SpecialSearchKind;
  ((SpecialSearchKind2) => {
    SpecialSearchKind2[SpecialSearchKind2["None"] = 0] = "None";
    SpecialSearchKind2[SpecialSearchKind2["Constructor"] = 1] = "Constructor";
    SpecialSearchKind2[SpecialSearchKind2["Class"] = 2] = "Class";
  })(SpecialSearchKind || (SpecialSearchKind = {}));
  function getNonModuleSymbolOfMergedModuleSymbol(symbol) {
    if (!(symbol.flags & (1536 /* Module */ | 33554432 /* Transient */))) return void 0;
    const decl = symbol.declarations && find(symbol.declarations, (d) => !isSourceFile(d) && !isModuleDeclaration(d));
    return decl && decl.symbol;
  }
  class State {
    constructor(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
      this.sourceFiles = sourceFiles;
      this.sourceFilesSet = sourceFilesSet;
      this.specialSearchKind = specialSearchKind;
      this.checker = checker;
      this.cancellationToken = cancellationToken;
      this.searchMeaning = searchMeaning;
      this.options = options;
      this.result = result;
      /** Cache for `explicitlyinheritsFrom`. */
      this.inheritsFromCache = /* @__PURE__ */ new Map();
      /**
       * Type nodes can contain multiple references to the same type. For example:
       *      let x: Foo & (Foo & Bar) = ...
       * Because we are returning the implementation locations and not the identifier locations,
       * duplicate entries would be returned here as each of the type references is part of
       * the same implementation. For that reason, check before we add a new entry.
       */
      this.markSeenContainingTypeReference = nodeSeenTracker();
      /**
       * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once.
       * For example:
       *     // b.ts
       *     export { foo as bar } from "./a";
       *     import { bar } from "./b";
       *
       * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local).
       * But another reference to it may appear in the same source file.
       * See `tests/cases/fourslash/transitiveExportImports3.ts`.
       */
      this.markSeenReExportRHS = nodeSeenTracker();
      this.symbolIdToReferences = [];
      // Source file ID -> symbol ID -> Whether the symbol has been searched for in the source file.
      this.sourceFileToSeenSymbols = [];
    }
    includesSourceFile(sourceFile) {
      return this.sourceFilesSet.has(sourceFile.fileName);
    }
    /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
    getImportSearches(exportSymbol, exportInfo) {
      if (!this.importTracker) this.importTracker = createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken);
      return this.importTracker(exportSymbol, exportInfo, this.options.use === 2 /* Rename */);
    }
    /** @param allSearchSymbols set of additional symbols for use by `includes`. */
    createSearch(location, symbol, comingFrom, searchOptions = {}) {
      const {
        text = stripQuotes(symbolName(getLocalSymbolForExportDefault(symbol) || getNonModuleSymbolOfMergedModuleSymbol(symbol) || symbol)),
        allSearchSymbols = [symbol]
      } = searchOptions;
      const escapedText = escapeLeadingUnderscores(text);
      const parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : void 0;
      return { symbol, comingFrom, text, escapedText, parents, allSearchSymbols, includes: (sym) => contains(allSearchSymbols, sym) };
    }
    /**
     * Callback to add references for a particular searched symbol.
     * This initializes a reference group, so only call this if you will add at least one reference.
     */
    referenceAdder(searchSymbol) {
      const symbolId = getSymbolId(searchSymbol);
      let references = this.symbolIdToReferences[symbolId];
      if (!references) {
        references = this.symbolIdToReferences[symbolId] = [];
        this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references });
      }
      return (node, kind) => references.push(nodeEntry(node, kind));
    }
    /** Add a reference with no associated definition. */
    addStringOrCommentReference(fileName, textSpan) {
      this.result.push({
        definition: void 0,
        references: [{ kind: 0 /* Span */, fileName, textSpan }]
      });
    }
    /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */
    markSearchedSymbols(sourceFile, symbols) {
      const sourceId = getNodeId(sourceFile);
      const seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = /* @__PURE__ */ new Set());
      let anyNewSymbols = false;
      for (const sym of symbols) {
        anyNewSymbols = tryAddToSet(seenSymbols, getSymbolId(sym)) || anyNewSymbols;
      }
      return anyNewSymbols;
    }
  }
  function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) {
    const { importSearches, singleReferences, indirectUsers } = state.getImportSearches(exportSymbol, exportInfo);
    if (singleReferences.length) {
      const addRef = state.referenceAdder(exportSymbol);
      for (const singleRef of singleReferences) {
        if (shouldAddSingleReference(singleRef, state)) addRef(singleRef);
      }
    }
    for (const [importLocation, importSymbol] of importSearches) {
      getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state);
    }
    if (indirectUsers.length) {
      let indirectSearch;
      switch (exportInfo.exportKind) {
        case 0 /* Named */:
          indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */);
          break;
        case 1 /* Default */:
          indirectSearch = state.options.use === 2 /* Rename */ ? void 0 : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" });
          break;
        case 2 /* ExportEquals */:
          break;
      }
      if (indirectSearch) {
        for (const indirectUser of indirectUsers) {
          searchForName(indirectUser, indirectSearch, state);
        }
      }
    }
  }
  function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) {
    const importTracker = createImportTracker(sourceFiles, new Set(sourceFiles.map((f) => f.fileName)), checker, cancellationToken);
    const { importSearches, indirectUsers, singleReferences } = importTracker(
      exportSymbol,
      { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol },
      /*isForRename*/
      false
    );
    for (const [importLocation] of importSearches) {
      cb(importLocation);
    }
    for (const singleReference of singleReferences) {
      if (isIdentifier(singleReference) && isImportTypeNode(singleReference.parent)) {
        cb(singleReference);
      }
    }
    for (const indirectUser of indirectUsers) {
      for (const node of getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName)) {
        const symbol = checker.getSymbolAtLocation(node);
        const hasExportAssignmentDeclaration = some(symbol == null ? void 0 : symbol.declarations, (d) => tryCast(d, isExportAssignment) ? true : false);
        if (isIdentifier(node) && !isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) {
          cb(node);
        }
      }
    }
  }
  Core2.eachExportReference = eachExportReference;
  function shouldAddSingleReference(singleRef, state) {
    if (!hasMatchingMeaning(singleRef, state)) return false;
    if (state.options.use !== 2 /* Rename */) return true;
    if (!isIdentifier(singleRef) && !isImportOrExportSpecifier(singleRef.parent)) return false;
    return !(isImportOrExportSpecifier(singleRef.parent) && moduleExportNameIsDefault(singleRef));
  }
  function searchForImportedSymbol(symbol, state) {
    if (!symbol.declarations) return;
    for (const declaration of symbol.declarations) {
      const exportingFile = declaration.getSourceFile();
      getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile));
    }
  }
  function searchForName(sourceFile, search, state) {
    if (getNameTable(sourceFile).get(search.escapedText) !== void 0) {
      getReferencesInSourceFile(sourceFile, search, state);
    }
  }
  function getPropertySymbolOfDestructuringAssignment(location, checker) {
    return isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) ? checker.getPropertySymbolOfDestructuringAssignment(location) : void 0;
  }
  function getSymbolScope(symbol) {
    const { declarations, flags, parent: parent2, valueDeclaration } = symbol;
    if (valueDeclaration && (valueDeclaration.kind === 218 /* FunctionExpression */ || valueDeclaration.kind === 231 /* ClassExpression */)) {
      return valueDeclaration;
    }
    if (!declarations) {
      return void 0;
    }
    if (flags & (4 /* Property */ | 8192 /* Method */)) {
      const privateDeclaration = find(declarations, (d) => hasEffectiveModifier(d, 2 /* Private */) || isPrivateIdentifierClassElementDeclaration(d));
      if (privateDeclaration) {
        return getAncestor(privateDeclaration, 263 /* ClassDeclaration */);
      }
      return void 0;
    }
    if (declarations.some(isObjectBindingElementWithoutPropertyName)) {
      return void 0;
    }
    const exposedByParent = parent2 && !(symbol.flags & 262144 /* TypeParameter */);
    if (exposedByParent && !(isExternalModuleSymbol(parent2) && !parent2.globalExports)) {
      return void 0;
    }
    let scope;
    for (const declaration of declarations) {
      const container = getContainerNode(declaration);
      if (scope && scope !== container) {
        return void 0;
      }
      if (!container || container.kind === 307 /* SourceFile */ && !isExternalOrCommonJsModule(container)) {
        return void 0;
      }
      scope = container;
      if (isFunctionExpression(scope)) {
        let next;
        while (next = getNextJSDocCommentLocation(scope)) {
          scope = next;
        }
      }
    }
    return exposedByParent ? scope.getSourceFile() : scope;
  }
  function isSymbolReferencedInFile(definition, checker, sourceFile, searchContainer = sourceFile) {
    return eachSymbolReferenceInFile(definition, checker, sourceFile, () => true, searchContainer) || false;
  }
  Core2.isSymbolReferencedInFile = isSymbolReferencedInFile;
  function eachSymbolReferenceInFile(definition, checker, sourceFile, cb, searchContainer = sourceFile) {
    const symbol = isParameterPropertyDeclaration(definition.parent, definition.parent.parent) ? first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) : checker.getSymbolAtLocation(definition);
    if (!symbol) return void 0;
    for (const token of getPossibleSymbolReferenceNodes(sourceFile, symbol.name, searchContainer)) {
      if (!isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue;
      const referenceSymbol = checker.getSymbolAtLocation(token);
      if (referenceSymbol === symbol || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol || isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) {
        const res = cb(token);
        if (res) return res;
      }
    }
  }
  Core2.eachSymbolReferenceInFile = eachSymbolReferenceInFile;
  function getTopMostDeclarationNamesInFile(declarationName, sourceFile) {
    const candidates = filter(getPossibleSymbolReferenceNodes(sourceFile, declarationName), (name) => !!getDeclarationFromName(name));
    return candidates.reduce((topMost, decl) => {
      const depth = getDepth(decl);
      if (!some(topMost.declarationNames) || depth === topMost.depth) {
        topMost.declarationNames.push(decl);
        topMost.depth = depth;
      } else if (depth < topMost.depth) {
        topMost.declarationNames = [decl];
        topMost.depth = depth;
      }
      return topMost;
    }, { depth: Infinity, declarationNames: [] }).declarationNames;
    function getDepth(declaration) {
      let depth = 0;
      while (declaration) {
        declaration = getContainerNode(declaration);
        depth++;
      }
      return depth;
    }
  }
  Core2.getTopMostDeclarationNamesInFile = getTopMostDeclarationNamesInFile;
  function someSignatureUsage(signature, sourceFiles, checker, cb) {
    if (!signature.name || !isIdentifier(signature.name)) return false;
    const symbol = Debug.checkDefined(checker.getSymbolAtLocation(signature.name));
    for (const sourceFile of sourceFiles) {
      for (const name of getPossibleSymbolReferenceNodes(sourceFile, symbol.name)) {
        if (!isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) continue;
        const called = climbPastPropertyAccess(name);
        const call = isCallExpression(called.parent) && called.parent.expression === called ? called.parent : void 0;
        const referenceSymbol = checker.getSymbolAtLocation(name);
        if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some((s) => s === symbol)) {
          if (cb(name, call)) {
            return true;
          }
        }
      }
    }
    return false;
  }
  Core2.someSignatureUsage = someSignatureUsage;
  function getPossibleSymbolReferenceNodes(sourceFile, symbolName2, container = sourceFile) {
    return mapDefined(getPossibleSymbolReferencePositions(sourceFile, symbolName2, container), (pos) => {
      const referenceLocation = getTouchingPropertyName(sourceFile, pos);
      return referenceLocation === sourceFile ? void 0 : referenceLocation;
    });
  }
  function getPossibleSymbolReferencePositions(sourceFile, symbolName2, container = sourceFile) {
    const positions = [];
    if (!symbolName2 || !symbolName2.length) {
      return positions;
    }
    const text = sourceFile.text;
    const sourceLength = text.length;
    const symbolNameLength = symbolName2.length;
    let position = text.indexOf(symbolName2, container.pos);
    while (position >= 0) {
      if (position > container.end) break;
      const endPosition = position + symbolNameLength;
      if ((position === 0 || !isIdentifierPart(text.charCodeAt(position - 1), 99 /* Latest */)) && (endPosition === sourceLength || !isIdentifierPart(text.charCodeAt(endPosition), 99 /* Latest */))) {
        positions.push(position);
      }
      position = text.indexOf(symbolName2, position + symbolNameLength + 1);
    }
    return positions;
  }
  function getLabelReferencesInNode(container, targetLabel) {
    const sourceFile = container.getSourceFile();
    const labelName = targetLabel.text;
    const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), (node) => (
      // Only pick labels that are either the target label, or have a target that is the target label
      node === targetLabel || isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel ? nodeEntry(node) : void 0
    ));
    return [{ definition: { type: 1 /* Label */, node: targetLabel }, references }];
  }
  function isValidReferencePosition(node, searchSymbolName) {
    switch (node.kind) {
      case 81 /* PrivateIdentifier */:
        if (isJSDocMemberName(node.parent)) {
          return true;
        }
      // falls through I guess
      case 80 /* Identifier */:
        return node.text.length === searchSymbolName.length;
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 11 /* StringLiteral */: {
        const str = node;
        return str.text.length === searchSymbolName.length && (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node || isImportOrExportSpecifier(node.parent));
      }
      case 9 /* NumericLiteral */:
        return isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length;
      case 90 /* DefaultKeyword */:
        return "default".length === searchSymbolName.length;
      default:
        return false;
    }
  }
  function getAllReferencesForImportMeta(sourceFiles, cancellationToken) {
    const references = flatMap(sourceFiles, (sourceFile) => {
      cancellationToken.throwIfCancellationRequested();
      return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "meta", sourceFile), (node) => {
        const parent2 = node.parent;
        if (isImportMeta(parent2)) {
          return nodeEntry(parent2);
        }
      });
    });
    return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references }] : void 0;
  }
  function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken, filter2) {
    const references = flatMap(sourceFiles, (sourceFile) => {
      cancellationToken.throwIfCancellationRequested();
      return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, tokenToString(keywordKind), sourceFile), (referenceLocation) => {
        if (referenceLocation.kind === keywordKind && (!filter2 || filter2(referenceLocation))) {
          return nodeEntry(referenceLocation);
        }
      });
    });
    return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references }] : void 0;
  }
  function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere = true) {
    state.cancellationToken.throwIfCancellationRequested();
    return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere);
  }
  function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) {
    if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) {
      return;
    }
    for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container)) {
      getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
    }
  }
  function hasMatchingMeaning(referenceLocation, state) {
    return !!(getMeaningFromLocation(referenceLocation) & state.searchMeaning);
  }
  function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
    const referenceLocation = getTouchingPropertyName(sourceFile, position);
    if (!isValidReferencePosition(referenceLocation, search.text)) {
      if (!state.options.implementations && (state.options.findInStrings && isInString(sourceFile, position) || state.options.findInComments && isInNonReferenceComment(sourceFile, position))) {
        state.addStringOrCommentReference(sourceFile.fileName, createTextSpan(position, search.text.length));
      }
      return;
    }
    if (!hasMatchingMeaning(referenceLocation, state)) return;
    let referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
    if (!referenceSymbol) {
      return;
    }
    const parent2 = referenceLocation.parent;
    if (isImportSpecifier(parent2) && parent2.propertyName === referenceLocation) {
      return;
    }
    if (isExportSpecifier(parent2)) {
      Debug.assert(referenceLocation.kind === 80 /* Identifier */ || referenceLocation.kind === 11 /* StringLiteral */);
      getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent2, search, state, addReferencesHere);
      return;
    }
    if (isJSDocPropertyLikeTag(parent2) && parent2.isNameFirst && parent2.typeExpression && isJSDocTypeLiteral(parent2.typeExpression.type) && parent2.typeExpression.type.jsDocPropertyTags && length(parent2.typeExpression.type.jsDocPropertyTags)) {
      getReferencesAtJSDocTypeLiteral(parent2.typeExpression.type.jsDocPropertyTags, referenceLocation, search, state);
      return;
    }
    const relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state);
    if (!relatedSymbol) {
      getReferenceForShorthandProperty(referenceSymbol, search, state);
      return;
    }
    switch (state.specialSearchKind) {
      case 0 /* None */:
        if (addReferencesHere) addReference(referenceLocation, relatedSymbol, state);
        break;
      case 1 /* Constructor */:
        addConstructorReferences(referenceLocation, sourceFile, search, state);
        break;
      case 2 /* Class */:
        addClassStaticThisReferences(referenceLocation, search, state);
        break;
      default:
        Debug.assertNever(state.specialSearchKind);
    }
    if (isInJSFile(referenceLocation) && isBindingElement(referenceLocation.parent) && isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent)) {
      referenceSymbol = referenceLocation.parent.symbol;
      if (!referenceSymbol) return;
    }
    getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
  }
  function getReferencesAtJSDocTypeLiteral(jsDocPropertyTags, referenceLocation, search, state) {
    const addRef = state.referenceAdder(search.symbol);
    addReference(referenceLocation, search.symbol, state);
    forEach(jsDocPropertyTags, (propTag) => {
      if (isQualifiedName(propTag.name)) {
        addRef(propTag.name.left);
      }
    });
  }
  function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) {
    Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled");
    const { parent: parent2, propertyName, name } = exportSpecifier;
    const exportDeclaration = parent2.parent;
    const localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
    if (!alwaysGetReferences && !search.includes(localSymbol)) {
      return;
    }
    if (!propertyName) {
      if (!(state.options.use === 2 /* Rename */ && moduleExportNameIsDefault(name))) {
        addRef();
      }
    } else if (referenceLocation === propertyName) {
      if (!exportDeclaration.moduleSpecifier) {
        addRef();
      }
      if (addReferencesHere && state.options.use !== 2 /* Rename */ && state.markSeenReExportRHS(name)) {
        addReference(name, Debug.checkDefined(exportSpecifier.symbol), state);
      }
    } else {
      if (state.markSeenReExportRHS(referenceLocation)) {
        addRef();
      }
    }
    if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) {
      const isDefaultExport = moduleExportNameIsDefault(referenceLocation) || moduleExportNameIsDefault(exportSpecifier.name);
      const exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */;
      const exportSymbol = Debug.checkDefined(exportSpecifier.symbol);
      const exportInfo = getExportInfo(exportSymbol, exportKind, state.checker);
      if (exportInfo) {
        searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
      }
    }
    if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) {
      const imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
      if (imported) searchForImportedSymbol(imported, state);
    }
    function addRef() {
      if (addReferencesHere) addReference(referenceLocation, localSymbol, state);
    }
  }
  function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) {
    return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol;
  }
  function isExportSpecifierAlias(referenceLocation, exportSpecifier) {
    const { parent: parent2, propertyName, name } = exportSpecifier;
    Debug.assert(propertyName === referenceLocation || name === referenceLocation);
    if (propertyName) {
      return propertyName === referenceLocation;
    } else {
      return !parent2.parent.moduleSpecifier;
    }
  }
  function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) {
    const importOrExport = getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */);
    if (!importOrExport) return;
    const { symbol } = importOrExport;
    if (importOrExport.kind === 0 /* Import */) {
      if (!isForRenameWithPrefixAndSuffixText(state.options)) {
        searchForImportedSymbol(symbol, state);
      }
    } else {
      searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
    }
  }
  function getReferenceForShorthandProperty({ flags, valueDeclaration }, search, state) {
    const shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
    const name = valueDeclaration && getNameOfDeclaration(valueDeclaration);
    if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) {
      addReference(name, shorthandValueSymbol, state);
    }
  }
  function addReference(referenceLocation, relatedSymbol, state) {
    const { kind, symbol } = "kind" in relatedSymbol ? relatedSymbol : { kind: void 0, symbol: relatedSymbol };
    if (state.options.use === 2 /* Rename */ && referenceLocation.kind === 90 /* DefaultKeyword */) {
      return;
    }
    const addRef = state.referenceAdder(symbol);
    if (state.options.implementations) {
      addImplementationReferences(referenceLocation, addRef, state);
    } else {
      addRef(referenceLocation, kind);
    }
  }
  function addConstructorReferences(referenceLocation, sourceFile, search, state) {
    if (isNewExpressionTarget(referenceLocation)) {
      addReference(referenceLocation, search.symbol, state);
    }
    const pusher = () => state.referenceAdder(search.symbol);
    if (isClassLike(referenceLocation.parent)) {
      Debug.assert(referenceLocation.kind === 90 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation);
      findOwnConstructorReferences(search.symbol, sourceFile, pusher());
    } else {
      const classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
      if (classExtending) {
        findSuperConstructorAccesses(classExtending, pusher());
        findInheritedConstructorReferences(classExtending, state);
      }
    }
  }
  function addClassStaticThisReferences(referenceLocation, search, state) {
    addReference(referenceLocation, search.symbol, state);
    const classLike = referenceLocation.parent;
    if (state.options.use === 2 /* Rename */ || !isClassLike(classLike)) return;
    Debug.assert(classLike.name === referenceLocation);
    const addRef = state.referenceAdder(search.symbol);
    for (const member of classLike.members) {
      if (!(isMethodOrAccessor(member) && isStatic(member))) {
        continue;
      }
      if (member.body) {
        member.body.forEachChild(function cb(node) {
          if (node.kind === 110 /* ThisKeyword */) {
            addRef(node);
          } else if (!isFunctionLike(node) && !isClassLike(node)) {
            node.forEachChild(cb);
          }
        });
      }
    }
  }
  function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
    const constructorSymbol = getClassConstructorSymbol(classSymbol);
    if (constructorSymbol && constructorSymbol.declarations) {
      for (const decl of constructorSymbol.declarations) {
        const ctrKeyword = findChildOfKind(decl, 137 /* ConstructorKeyword */, sourceFile);
        Debug.assert(decl.kind === 176 /* Constructor */ && !!ctrKeyword);
        addNode(ctrKeyword);
      }
    }
    if (classSymbol.exports) {
      classSymbol.exports.forEach((member) => {
        const decl = member.valueDeclaration;
        if (decl && decl.kind === 174 /* MethodDeclaration */) {
          const body = decl.body;
          if (body) {
            forEachDescendantOfKind(body, 110 /* ThisKeyword */, (thisKeyword) => {
              if (isNewExpressionTarget(thisKeyword)) {
                addNode(thisKeyword);
              }
            });
          }
        }
      });
    }
  }
  function getClassConstructorSymbol(classSymbol) {
    return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */);
  }
  function findSuperConstructorAccesses(classDeclaration, addNode) {
    const constructor = getClassConstructorSymbol(classDeclaration.symbol);
    if (!(constructor && constructor.declarations)) {
      return;
    }
    for (const decl of constructor.declarations) {
      Debug.assert(decl.kind === 176 /* Constructor */);
      const body = decl.body;
      if (body) {
        forEachDescendantOfKind(body, 108 /* SuperKeyword */, (node) => {
          if (isCallExpressionTarget(node)) {
            addNode(node);
          }
        });
      }
    }
  }
  function hasOwnConstructor(classDeclaration) {
    return !!getClassConstructorSymbol(classDeclaration.symbol);
  }
  function findInheritedConstructorReferences(classDeclaration, state) {
    if (hasOwnConstructor(classDeclaration)) return;
    const classSymbol = classDeclaration.symbol;
    const search = state.createSearch(
      /*location*/
      void 0,
      classSymbol,
      /*comingFrom*/
      void 0
    );
    getReferencesInContainerOrFiles(classSymbol, state, search);
  }
  function addImplementationReferences(refNode, addReference2, state) {
    if (isDeclarationName(refNode) && isImplementation(refNode.parent)) {
      addReference2(refNode);
      return;
    }
    if (refNode.kind !== 80 /* Identifier */) {
      return;
    }
    if (refNode.parent.kind === 304 /* ShorthandPropertyAssignment */) {
      getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference2);
    }
    const containingNode = getContainingNodeIfInHeritageClause(refNode);
    if (containingNode) {
      addReference2(containingNode);
      return;
    }
    const typeNode = findAncestor(refNode, (a) => !isQualifiedName(a.parent) && !isTypeNode(a.parent) && !isTypeElement(a.parent));
    const typeHavingNode = typeNode.parent;
    if (hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) {
      if (hasInitializer(typeHavingNode)) {
        addIfImplementation(typeHavingNode.initializer);
      } else if (isFunctionLike(typeHavingNode) && typeHavingNode.body) {
        const body = typeHavingNode.body;
        if (body.kind === 241 /* Block */) {
          forEachReturnStatement(body, (returnStatement) => {
            if (returnStatement.expression) addIfImplementation(returnStatement.expression);
          });
        } else {
          addIfImplementation(body);
        }
      } else if (isAssertionExpression(typeHavingNode)) {
        addIfImplementation(typeHavingNode.expression);
      }
    }
    function addIfImplementation(e) {
      if (isImplementationExpression(e)) addReference2(e);
    }
  }
  function getContainingNodeIfInHeritageClause(node) {
    return isIdentifier(node) || isPropertyAccessExpression(node) ? getContainingNodeIfInHeritageClause(node.parent) : isExpressionWithTypeArguments(node) ? tryCast(node.parent.parent, or(isClassLike, isInterfaceDeclaration)) : void 0;
  }
  function isImplementationExpression(node) {
    switch (node.kind) {
      case 217 /* ParenthesizedExpression */:
        return isImplementationExpression(node.expression);
      case 219 /* ArrowFunction */:
      case 218 /* FunctionExpression */:
      case 210 /* ObjectLiteralExpression */:
      case 231 /* ClassExpression */:
      case 209 /* ArrayLiteralExpression */:
        return true;
      default:
        return false;
    }
  }
  function explicitlyInheritsFrom(symbol, parent2, cachedResults, checker) {
    if (symbol === parent2) {
      return true;
    }
    const key = getSymbolId(symbol) + "," + getSymbolId(parent2);
    const cached = cachedResults.get(key);
    if (cached !== void 0) {
      return cached;
    }
    cachedResults.set(key, false);
    const inherits = !!symbol.declarations && symbol.declarations.some(
      (declaration) => getAllSuperTypeNodes(declaration).some((typeReference) => {
        const type = checker.getTypeAtLocation(typeReference);
        return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent2, cachedResults, checker);
      })
    );
    cachedResults.set(key, inherits);
    return inherits;
  }
  function getReferencesForSuperKeyword(superKeyword) {
    let searchSpaceNode = getSuperContainer(
      superKeyword,
      /*stopOnFunctions*/
      false
    );
    if (!searchSpaceNode) {
      return void 0;
    }
    let staticFlag = 256 /* Static */;
    switch (searchSpaceNode.kind) {
      case 172 /* PropertyDeclaration */:
      case 171 /* PropertySignature */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
      case 176 /* Constructor */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        staticFlag &= getSyntacticModifierFlags(searchSpaceNode);
        searchSpaceNode = searchSpaceNode.parent;
        break;
      default:
        return void 0;
    }
    const sourceFile = searchSpaceNode.getSourceFile();
    const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), (node) => {
      if (node.kind !== 108 /* SuperKeyword */) {
        return;
      }
      const container = getSuperContainer(
        node,
        /*stopOnFunctions*/
        false
      );
      return container && isStatic(container) === !!staticFlag && container.parent.symbol === searchSpaceNode.symbol ? nodeEntry(node) : void 0;
    });
    return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references }];
  }
  function isParameterName(node) {
    return node.kind === 80 /* Identifier */ && node.parent.kind === 169 /* Parameter */ && node.parent.name === node;
  }
  function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
    let searchSpaceNode = getThisContainer(
      thisOrSuperKeyword,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    let staticFlag = 256 /* Static */;
    switch (searchSpaceNode.kind) {
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        if (isObjectLiteralMethod(searchSpaceNode)) {
          staticFlag &= getSyntacticModifierFlags(searchSpaceNode);
          searchSpaceNode = searchSpaceNode.parent;
          break;
        }
      // falls through
      case 172 /* PropertyDeclaration */:
      case 171 /* PropertySignature */:
      case 176 /* Constructor */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        staticFlag &= getSyntacticModifierFlags(searchSpaceNode);
        searchSpaceNode = searchSpaceNode.parent;
        break;
      case 307 /* SourceFile */:
        if (isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
          return void 0;
        }
      // falls through
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
        break;
      // Computed properties in classes are not handled here because references to this are illegal,
      // so there is no point finding references to them.
      default:
        return void 0;
    }
    const references = flatMap(searchSpaceNode.kind === 307 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], (sourceFile) => {
      cancellationToken.throwIfCancellationRequested();
      return getPossibleSymbolReferenceNodes(sourceFile, "this", isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter((node) => {
        if (!isThis(node)) {
          return false;
        }
        const container = getThisContainer(
          node,
          /*includeArrowFunctions*/
          false,
          /*includeClassComputedPropertyName*/
          false
        );
        if (!canHaveSymbol(container)) return false;
        switch (searchSpaceNode.kind) {
          case 218 /* FunctionExpression */:
          case 262 /* FunctionDeclaration */:
            return searchSpaceNode.symbol === container.symbol;
          case 174 /* MethodDeclaration */:
          case 173 /* MethodSignature */:
            return isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol;
          case 231 /* ClassExpression */:
          case 263 /* ClassDeclaration */:
          case 210 /* ObjectLiteralExpression */:
            return container.parent && canHaveSymbol(container.parent) && searchSpaceNode.symbol === container.parent.symbol && isStatic(container) === !!staticFlag;
          case 307 /* SourceFile */:
            return container.kind === 307 /* SourceFile */ && !isExternalModule(container) && !isParameterName(node);
        }
      });
    }).map((n) => nodeEntry(n));
    const thisParameter = firstDefined(references, (r) => isParameter(r.node.parent) ? r.node : void 0);
    return [{
      definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword },
      references
    }];
  }
  function getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken) {
    const type = getContextualTypeFromParentOrAncestorTypeNode(node, checker);
    const references = flatMap(sourceFiles, (sourceFile) => {
      cancellationToken.throwIfCancellationRequested();
      return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), (ref) => {
        if (isStringLiteralLike(ref) && ref.text === node.text) {
          if (type) {
            const refType = getContextualTypeFromParentOrAncestorTypeNode(ref, checker);
            if (type !== checker.getStringType() && (type === refType || isStringLiteralPropertyReference(ref, checker))) {
              return nodeEntry(ref, 2 /* StringLiteral */);
            }
          } else {
            return isNoSubstitutionTemplateLiteral(ref) && !rangeIsOnSingleLine(ref, sourceFile) ? void 0 : nodeEntry(ref, 2 /* StringLiteral */);
          }
        }
      });
    });
    return [{
      definition: { type: 4 /* String */, node },
      references
    }];
  }
  function isStringLiteralPropertyReference(node, checker) {
    if (isPropertySignature(node.parent)) {
      return checker.getPropertyOfType(checker.getTypeAtLocation(node.parent.parent), node.text);
    }
  }
  function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) {
    const result = [];
    forEachRelatedSymbol(
      symbol,
      location,
      checker,
      isForRename,
      !(isForRename && providePrefixAndSuffixText),
      (sym, root, base) => {
        if (base) {
          if (isStaticSymbol(symbol) !== isStaticSymbol(base)) {
            base = void 0;
          }
        }
        result.push(base || root || sym);
      },
      // when try to find implementation, implementations is true, and not allowed to find base class
      /*allowBaseTypes*/
      () => !implementations
    );
    return result;
  }
  function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) {
    const containingObjectLiteralElement = getContainingObjectLiteralElement(location);
    if (containingObjectLiteralElement) {
      const shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent);
      if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) {
        return cbSymbol(
          shorthandValueSymbol,
          /*rootSymbol*/
          void 0,
          /*baseSymbol*/
          void 0,
          3 /* SearchedLocalFoundProperty */
        );
      }
      const contextualType = checker.getContextualType(containingObjectLiteralElement.parent);
      const res2 = contextualType && firstDefined(
        getPropertySymbolsFromContextualType(
          containingObjectLiteralElement,
          checker,
          contextualType,
          /*unionSymbolOk*/
          true
        ),
        (sym) => fromRoot(sym, 4 /* SearchedPropertyFoundLocal */)
      );
      if (res2) return res2;
      const propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker);
      const res1 = propertySymbol && cbSymbol(
        propertySymbol,
        /*rootSymbol*/
        void 0,
        /*baseSymbol*/
        void 0,
        4 /* SearchedPropertyFoundLocal */
      );
      if (res1) return res1;
      const res22 = shorthandValueSymbol && cbSymbol(
        shorthandValueSymbol,
        /*rootSymbol*/
        void 0,
        /*baseSymbol*/
        void 0,
        3 /* SearchedLocalFoundProperty */
      );
      if (res22) return res22;
    }
    const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(location, symbol, checker);
    if (aliasedSymbol) {
      const res2 = cbSymbol(
        aliasedSymbol,
        /*rootSymbol*/
        void 0,
        /*baseSymbol*/
        void 0,
        1 /* Node */
      );
      if (res2) return res2;
    }
    const res = fromRoot(symbol);
    if (res) return res;
    if (symbol.valueDeclaration && isParameterPropertyDeclaration(symbol.valueDeclaration, symbol.valueDeclaration.parent)) {
      const paramProps = checker.getSymbolsOfParameterPropertyDeclaration(cast(symbol.valueDeclaration, isParameter), symbol.name);
      Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */));
      return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]);
    }
    const exportSpecifier = getDeclarationOfKind(symbol, 281 /* ExportSpecifier */);
    if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) {
      const localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
      if (localSymbol) {
        const res2 = cbSymbol(
          localSymbol,
          /*rootSymbol*/
          void 0,
          /*baseSymbol*/
          void 0,
          1 /* Node */
        );
        if (res2) return res2;
      }
    }
    if (!isForRenamePopulateSearchSymbolSet) {
      let bindingElementPropertySymbol;
      if (onlyIncludeBindingElementAtReferenceLocation) {
        bindingElementPropertySymbol = isObjectBindingElementWithoutPropertyName(location.parent) ? getPropertySymbolFromBindingElement(checker, location.parent) : void 0;
      } else {
        bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
      }
      return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */);
    }
    Debug.assert(isForRenamePopulateSearchSymbolSet);
    const includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation;
    if (includeOriginalSymbolOfBindingElement) {
      const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
      return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */);
    }
    function fromRoot(sym, kind) {
      return firstDefined(checker.getRootSymbols(sym), (rootSymbol) => cbSymbol(
        sym,
        rootSymbol,
        /*baseSymbol*/
        void 0,
        kind
      ) || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) ? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, (base) => cbSymbol(sym, rootSymbol, base, kind)) : void 0));
    }
    function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol2, checker2) {
      const bindingElement = getDeclarationOfKind(symbol2, 208 /* BindingElement */);
      if (bindingElement && isObjectBindingElementWithoutPropertyName(bindingElement)) {
        return getPropertySymbolFromBindingElement(checker2, bindingElement);
      }
    }
  }
  function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) {
    const seen = /* @__PURE__ */ new Set();
    return recur(symbol);
    function recur(symbol2) {
      if (!(symbol2.flags & (32 /* Class */ | 64 /* Interface */)) || !addToSeen(seen, symbol2)) return;
      return firstDefined(symbol2.declarations, (declaration) => firstDefined(getAllSuperTypeNodes(declaration), (typeReference) => {
        const type = checker.getTypeAtLocation(typeReference);
        const propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName);
        return type && propertySymbol && (firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol));
      }));
    }
  }
  function isStaticSymbol(symbol) {
    if (!symbol.valueDeclaration) return false;
    const modifierFlags = getEffectiveModifierFlags(symbol.valueDeclaration);
    return !!(modifierFlags & 256 /* Static */);
  }
  function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) {
    const { checker } = state;
    return forEachRelatedSymbol(
      referenceSymbol,
      referenceLocation,
      checker,
      /*isForRenamePopulateSearchSymbolSet*/
      false,
      /*onlyIncludeBindingElementAtReferenceLocation*/
      state.options.use !== 2 /* Rename */ || !!state.options.providePrefixAndSuffixTextForRename,
      (sym, rootSymbol, baseSymbol, kind) => {
        if (baseSymbol) {
          if (isStaticSymbol(referenceSymbol) !== isStaticSymbol(baseSymbol)) {
            baseSymbol = void 0;
          }
        }
        return search.includes(baseSymbol || rootSymbol || sym) ? { symbol: rootSymbol && !(getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind } : void 0;
      },
      /*allowBaseTypes*/
      (rootSymbol) => !(search.parents && !search.parents.some((parent2) => explicitlyInheritsFrom(rootSymbol.parent, parent2, state.inheritsFromCache, checker)))
    );
  }
  function getIntersectingMeaningFromDeclarations(node, symbol) {
    let meaning = getMeaningFromLocation(node);
    const { declarations } = symbol;
    if (declarations) {
      let lastIterationMeaning;
      do {
        lastIterationMeaning = meaning;
        for (const declaration of declarations) {
          const declarationMeaning = getMeaningFromDeclaration(declaration);
          if (declarationMeaning & meaning) {
            meaning |= declarationMeaning;
          }
        }
      } while (meaning !== lastIterationMeaning);
    }
    return meaning;
  }
  Core2.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations;
  function isImplementation(node) {
    return !!(node.flags & 33554432 /* Ambient */) ? !(isInterfaceDeclaration(node) || isTypeAliasDeclaration(node)) : isVariableLike(node) ? hasInitializer(node) : isFunctionLikeDeclaration(node) ? !!node.body : isClassLike(node) || isModuleOrEnumDeclaration(node);
  }
  function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference2) {
    const refSymbol = checker.getSymbolAtLocation(node);
    const shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration);
    if (shorthandSymbol) {
      for (const declaration of shorthandSymbol.getDeclarations()) {
        if (getMeaningFromDeclaration(declaration) & 1 /* Value */) {
          addReference2(declaration);
        }
      }
    }
  }
  Core2.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment;
  function forEachDescendantOfKind(node, kind, action) {
    forEachChild(node, (child) => {
      if (child.kind === kind) {
        action(child);
      }
      forEachDescendantOfKind(child, kind, action);
    });
  }
  function tryGetClassByExtendingIdentifier(node) {
    return tryGetClassExtendingExpressionWithTypeArguments(climbPastPropertyAccess(node).parent);
  }
  function getParentSymbolsOfPropertyAccess(location, symbol, checker) {
    const propertyAccessExpression = isRightSideOfPropertyAccess(location) ? location.parent : void 0;
    const lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression);
    const res = mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? void 0 : [lhsType]), (t) => t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : void 0);
    return res.length === 0 ? void 0 : res;
  }
  function isForRenameWithPrefixAndSuffixText(options) {
    return options.use === 2 /* Rename */ && options.providePrefixAndSuffixTextForRename;
  }
})(Core || (Core = {}));

// src/services/_namespaces/ts.GoToDefinition.ts
var ts_GoToDefinition_exports = {};
__export(ts_GoToDefinition_exports, {
  createDefinitionInfo: () => createDefinitionInfo,
  getDefinitionAndBoundSpan: () => getDefinitionAndBoundSpan,
  getDefinitionAtPosition: () => getDefinitionAtPosition,
  getReferenceAtPosition: () => getReferenceAtPosition,
  getTypeDefinitionAtPosition: () => getTypeDefinitionAtPosition
});

// src/services/goToDefinition.ts
function getDefinitionAtPosition(program, sourceFile, position, searchOtherFilesOnly, stopAtAlias) {
  var _a;
  const resolvedRef = getReferenceAtPosition(sourceFile, position, program);
  const fileReferenceDefinition = resolvedRef && [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.fileName, resolvedRef.unverified)] || emptyArray;
  if (resolvedRef == null ? void 0 : resolvedRef.file) {
    return fileReferenceDefinition;
  }
  const node = getTouchingPropertyName(sourceFile, position);
  if (node === sourceFile) {
    return void 0;
  }
  const { parent: parent2 } = node;
  const typeChecker = program.getTypeChecker();
  if (node.kind === 164 /* OverrideKeyword */ || isIdentifier(node) && isJSDocOverrideTag(parent2) && parent2.tagName === node) {
    return getDefinitionFromOverriddenMember(typeChecker, node) || emptyArray;
  }
  if (isJumpStatementTarget(node)) {
    const label = getTargetLabel(node.parent, node.text);
    return label ? [createDefinitionInfoFromName(
      typeChecker,
      label,
      "label" /* label */,
      node.text,
      /*containerName*/
      void 0
    )] : void 0;
  }
  switch (node.kind) {
    case 107 /* ReturnKeyword */:
      const functionDeclaration = findAncestor(node.parent, (n) => isClassStaticBlockDeclaration(n) ? "quit" : isFunctionLikeDeclaration(n));
      return functionDeclaration ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : void 0;
    case 90 /* DefaultKeyword */:
      if (!isDefaultClause(node.parent)) {
        break;
      }
    // falls through
    case 84 /* CaseKeyword */:
      const switchStatement = findAncestor(node.parent, isSwitchStatement);
      if (switchStatement) {
        return [createDefinitionInfoFromSwitch(switchStatement, sourceFile)];
      }
      break;
  }
  if (node.kind === 135 /* AwaitKeyword */) {
    const functionDeclaration = findAncestor(node, (n) => isFunctionLikeDeclaration(n));
    const isAsyncFunction2 = functionDeclaration && some(functionDeclaration.modifiers, (node2) => node2.kind === 134 /* AsyncKeyword */);
    return isAsyncFunction2 ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : void 0;
  }
  if (node.kind === 127 /* YieldKeyword */) {
    const functionDeclaration = findAncestor(node, (n) => isFunctionLikeDeclaration(n));
    const isGeneratorFunction = functionDeclaration && functionDeclaration.asteriskToken;
    return isGeneratorFunction ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : void 0;
  }
  if (isStaticModifier(node) && isClassStaticBlockDeclaration(node.parent)) {
    const classDecl = node.parent.parent;
    const { symbol: symbol2, failedAliasResolution: failedAliasResolution2 } = getSymbol(classDecl, typeChecker, stopAtAlias);
    const staticBlocks = filter(classDecl.members, isClassStaticBlockDeclaration);
    const containerName = symbol2 ? typeChecker.symbolToString(symbol2, classDecl) : "";
    const sourceFile2 = node.getSourceFile();
    return map(staticBlocks, (staticBlock) => {
      let { pos } = moveRangePastModifiers(staticBlock);
      pos = skipTrivia(sourceFile2.text, pos);
      return createDefinitionInfoFromName(
        typeChecker,
        staticBlock,
        "constructor" /* constructorImplementationElement */,
        "static {}",
        containerName,
        /*unverified*/
        false,
        failedAliasResolution2,
        { start: pos, length: "static".length }
      );
    });
  }
  let { symbol, failedAliasResolution } = getSymbol(node, typeChecker, stopAtAlias);
  let fallbackNode = node;
  if (searchOtherFilesOnly && failedAliasResolution) {
    const importDeclaration = forEach([node, ...(symbol == null ? void 0 : symbol.declarations) || emptyArray], (n) => findAncestor(n, isAnyImportOrBareOrAccessedRequire));
    const moduleSpecifier = importDeclaration && tryGetModuleSpecifierFromDeclaration(importDeclaration);
    if (moduleSpecifier) {
      ({ symbol, failedAliasResolution } = getSymbol(moduleSpecifier, typeChecker, stopAtAlias));
      fallbackNode = moduleSpecifier;
    }
  }
  if (!symbol && isModuleSpecifierLike(fallbackNode)) {
    const ref = (_a = program.getResolvedModuleFromModuleSpecifier(fallbackNode, sourceFile)) == null ? void 0 : _a.resolvedModule;
    if (ref) {
      return [{
        name: fallbackNode.text,
        fileName: ref.resolvedFileName,
        containerName: void 0,
        containerKind: void 0,
        kind: "script" /* scriptElement */,
        textSpan: createTextSpan(0, 0),
        failedAliasResolution,
        isAmbient: isDeclarationFileName(ref.resolvedFileName),
        unverified: fallbackNode !== node
      }];
    }
  }
  if (!symbol) {
    return concatenate(fileReferenceDefinition, getDefinitionInfoForIndexSignatures(node, typeChecker));
  }
  if (searchOtherFilesOnly && every(symbol.declarations, (d) => d.getSourceFile().fileName === sourceFile.fileName)) return void 0;
  const calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
  if (calledDeclaration && !(isJsxOpeningLikeElement(node.parent) && isJsxConstructorLike(calledDeclaration))) {
    const sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration, failedAliasResolution);
    let declarationFilter = (d) => d !== calledDeclaration;
    if (typeChecker.getRootSymbols(symbol).some((s) => symbolMatchesSignature(s, calledDeclaration))) {
      if (!isConstructorDeclaration(calledDeclaration)) return [sigInfo];
      declarationFilter = (d) => d !== calledDeclaration && (isClassDeclaration(d) || isClassExpression(d));
    }
    const defs = getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, declarationFilter) || emptyArray;
    return node.kind === 108 /* SuperKeyword */ ? [sigInfo, ...defs] : [...defs, sigInfo];
  }
  if (node.parent.kind === 304 /* ShorthandPropertyAssignment */) {
    const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration);
    const definitions = (shorthandSymbol == null ? void 0 : shorthandSymbol.declarations) ? shorthandSymbol.declarations.map((decl) => createDefinitionInfo(
      decl,
      typeChecker,
      shorthandSymbol,
      node,
      /*unverified*/
      false,
      failedAliasResolution
    )) : emptyArray;
    return concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node));
  }
  if (isPropertyName(node) && isBindingElement(parent2) && isObjectBindingPattern(parent2.parent) && node === (parent2.propertyName || parent2.name)) {
    const name = getNameFromPropertyName(node);
    const type = typeChecker.getTypeAtLocation(parent2.parent);
    return name === void 0 ? emptyArray : flatMap(type.isUnion() ? type.types : [type], (t) => {
      const prop = t.getProperty(name);
      return prop && getDefinitionFromSymbol(typeChecker, prop, node);
    });
  }
  const objectLiteralElementDefinition = getDefinitionFromObjectLiteralElement(typeChecker, node);
  return concatenate(fileReferenceDefinition, objectLiteralElementDefinition.length ? objectLiteralElementDefinition : getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution));
}
function symbolMatchesSignature(s, calledDeclaration) {
  var _a;
  return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent || isAssignmentExpression(calledDeclaration.parent) || !isCallLikeExpression(calledDeclaration.parent) && s === ((_a = tryCast(calledDeclaration.parent, canHaveSymbol)) == null ? void 0 : _a.symbol);
}
function getDefinitionFromObjectLiteralElement(typeChecker, node) {
  const element = getContainingObjectLiteralElement(node);
  if (element) {
    const contextualType = element && typeChecker.getContextualType(element.parent);
    if (contextualType) {
      return flatMap(getPropertySymbolsFromContextualType(
        element,
        typeChecker,
        contextualType,
        /*unionSymbolOk*/
        false
      ), (propertySymbol) => getDefinitionFromSymbol(typeChecker, propertySymbol, node));
    }
  }
  return emptyArray;
}
function getDefinitionFromOverriddenMember(typeChecker, node) {
  const classElement = findAncestor(node, isClassElement);
  if (!(classElement && classElement.name)) return;
  const baseDeclaration = findAncestor(classElement, isClassLike);
  if (!baseDeclaration) return;
  const baseTypeNode = getEffectiveBaseTypeNode(baseDeclaration);
  if (!baseTypeNode) return;
  const expression = skipParentheses(baseTypeNode.expression);
  const base = isClassExpression(expression) ? expression.symbol : typeChecker.getSymbolAtLocation(expression);
  if (!base) return;
  const name = unescapeLeadingUnderscores(getTextOfPropertyName(classElement.name));
  const symbol = hasStaticModifier(classElement) ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbol(base), name) : typeChecker.getPropertyOfType(typeChecker.getDeclaredTypeOfSymbol(base), name);
  if (!symbol) return;
  return getDefinitionFromSymbol(typeChecker, symbol, node);
}
function getReferenceAtPosition(sourceFile, position, program) {
  var _a, _b;
  const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
  if (referencePath) {
    const file = program.getSourceFileFromReference(sourceFile, referencePath);
    return file && { reference: referencePath, fileName: file.fileName, file, unverified: false };
  }
  const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
  if (typeReferenceDirective) {
    const reference = (_a = program.getResolvedTypeReferenceDirectiveFromTypeReferenceDirective(typeReferenceDirective, sourceFile)) == null ? void 0 : _a.resolvedTypeReferenceDirective;
    const file = reference && program.getSourceFile(reference.resolvedFileName);
    return file && { reference: typeReferenceDirective, fileName: file.fileName, file, unverified: false };
  }
  const libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position);
  if (libReferenceDirective) {
    const file = program.getLibFileFromReference(libReferenceDirective);
    return file && { reference: libReferenceDirective, fileName: file.fileName, file, unverified: false };
  }
  if (sourceFile.imports.length || sourceFile.moduleAugmentations.length) {
    const node = getTouchingToken(sourceFile, position);
    let resolution;
    if (isModuleSpecifierLike(node) && isExternalModuleNameRelative(node.text) && (resolution = program.getResolvedModuleFromModuleSpecifier(node, sourceFile))) {
      const verifiedFileName = (_b = resolution.resolvedModule) == null ? void 0 : _b.resolvedFileName;
      const fileName = verifiedFileName || resolvePath(getDirectoryPath(sourceFile.fileName), node.text);
      return {
        file: program.getSourceFile(fileName),
        fileName,
        reference: {
          pos: node.getStart(),
          end: node.getEnd(),
          fileName: node.text
        },
        unverified: !verifiedFileName
      };
    }
  }
  return void 0;
}
var typesWithUnwrappedTypeArguments = /* @__PURE__ */ new Set([
  "Array",
  "ArrayLike",
  "ReadonlyArray",
  "Promise",
  "PromiseLike",
  "Iterable",
  "IterableIterator",
  "AsyncIterable",
  "Set",
  "WeakSet",
  "ReadonlySet",
  "Map",
  "WeakMap",
  "ReadonlyMap",
  "Partial",
  "Required",
  "Readonly",
  "Pick",
  "Omit"
]);
function shouldUnwrapFirstTypeArgumentTypeDefinitionFromTypeReference(typeChecker, type) {
  const referenceName = type.symbol.name;
  if (!typesWithUnwrappedTypeArguments.has(referenceName)) {
    return false;
  }
  const globalType = typeChecker.resolveName(
    referenceName,
    /*location*/
    void 0,
    788968 /* Type */,
    /*excludeGlobals*/
    false
  );
  return !!globalType && globalType === type.target.symbol;
}
function shouldUnwrapFirstTypeArgumentTypeDefinitionFromAlias(typeChecker, type) {
  if (!type.aliasSymbol) {
    return false;
  }
  const referenceName = type.aliasSymbol.name;
  if (!typesWithUnwrappedTypeArguments.has(referenceName)) {
    return false;
  }
  const globalType = typeChecker.resolveName(
    referenceName,
    /*location*/
    void 0,
    788968 /* Type */,
    /*excludeGlobals*/
    false
  );
  return !!globalType && globalType === type.aliasSymbol;
}
function getFirstTypeArgumentDefinitions(typeChecker, type, node, failedAliasResolution) {
  var _a, _b;
  if (!!(getObjectFlags(type) & 4 /* Reference */) && shouldUnwrapFirstTypeArgumentTypeDefinitionFromTypeReference(typeChecker, type)) {
    return definitionFromType(typeChecker.getTypeArguments(type)[0], typeChecker, node, failedAliasResolution);
  }
  if (shouldUnwrapFirstTypeArgumentTypeDefinitionFromAlias(typeChecker, type) && type.aliasTypeArguments) {
    return definitionFromType(type.aliasTypeArguments[0], typeChecker, node, failedAliasResolution);
  }
  if (getObjectFlags(type) & 32 /* Mapped */ && type.target && shouldUnwrapFirstTypeArgumentTypeDefinitionFromAlias(typeChecker, type.target)) {
    const declaration = (_b = (_a = type.aliasSymbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b[0];
    if (declaration && isTypeAliasDeclaration(declaration) && isTypeReferenceNode(declaration.type) && declaration.type.typeArguments) {
      return definitionFromType(typeChecker.getTypeAtLocation(declaration.type.typeArguments[0]), typeChecker, node, failedAliasResolution);
    }
  }
  return [];
}
function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) {
  const node = getTouchingPropertyName(sourceFile, position);
  if (node === sourceFile) {
    return void 0;
  }
  if (isImportMeta(node.parent) && node.parent.name === node) {
    return definitionFromType(
      typeChecker.getTypeAtLocation(node.parent),
      typeChecker,
      node.parent,
      /*failedAliasResolution*/
      false
    );
  }
  const { symbol, failedAliasResolution } = getSymbol(
    node,
    typeChecker,
    /*stopAtAlias*/
    false
  );
  if (!symbol) return void 0;
  const typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node);
  const returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker);
  const fromReturnType = returnType && definitionFromType(returnType, typeChecker, node, failedAliasResolution);
  const [resolvedType, typeDefinitions] = fromReturnType && fromReturnType.length !== 0 ? [returnType, fromReturnType] : [typeAtLocation, definitionFromType(typeAtLocation, typeChecker, node, failedAliasResolution)];
  return typeDefinitions.length ? [...getFirstTypeArgumentDefinitions(typeChecker, resolvedType, node, failedAliasResolution), ...typeDefinitions] : !(symbol.flags & 111551 /* Value */) && symbol.flags & 788968 /* Type */ ? getDefinitionFromSymbol(typeChecker, skipAlias(symbol, typeChecker), node, failedAliasResolution) : void 0;
}
function definitionFromType(type, checker, node, failedAliasResolution) {
  return flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], (t) => t.symbol && getDefinitionFromSymbol(checker, t.symbol, node, failedAliasResolution));
}
function tryGetReturnTypeOfFunction(symbol, type, checker) {
  if (type.symbol === symbol || // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}`
  symbol.valueDeclaration && type.symbol && isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) {
    const sigs = type.getCallSignatures();
    if (sigs.length === 1) return checker.getReturnTypeOfSignature(first(sigs));
  }
  return void 0;
}
function getDefinitionAndBoundSpan(program, sourceFile, position) {
  const definitions = getDefinitionAtPosition(program, sourceFile, position);
  if (!definitions || definitions.length === 0) {
    return void 0;
  }
  const comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position) || findReferenceInPosition(sourceFile.libReferenceDirectives, position);
  if (comment) {
    return { definitions, textSpan: createTextSpanFromRange(comment) };
  }
  const node = getTouchingPropertyName(sourceFile, position);
  const textSpan = createTextSpan(node.getStart(), node.getWidth());
  return { definitions, textSpan };
}
function getDefinitionInfoForIndexSignatures(node, checker) {
  return mapDefined(checker.getIndexInfosAtLocation(node), (info) => info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration));
}
function getSymbol(node, checker, stopAtAlias) {
  const symbol = checker.getSymbolAtLocation(node);
  let failedAliasResolution = false;
  if ((symbol == null ? void 0 : symbol.declarations) && symbol.flags & 2097152 /* Alias */ && !stopAtAlias && shouldSkipAlias(node, symbol.declarations[0])) {
    const aliased = checker.getAliasedSymbol(symbol);
    if (aliased.declarations) {
      return { symbol: aliased };
    } else {
      failedAliasResolution = true;
    }
  }
  return { symbol, failedAliasResolution };
}
function shouldSkipAlias(node, declaration) {
  if (node.kind !== 80 /* Identifier */ && (node.kind !== 11 /* StringLiteral */ || !isImportOrExportSpecifier(node.parent))) {
    return false;
  }
  if (node.parent === declaration) {
    return true;
  }
  if (declaration.kind === 274 /* NamespaceImport */) {
    return false;
  }
  return true;
}
function isExpandoDeclaration(node) {
  if (!isAssignmentDeclaration(node)) return false;
  const containingAssignment = findAncestor(node, (p) => {
    if (isAssignmentExpression(p)) return true;
    if (!isAssignmentDeclaration(p)) return "quit";
    return false;
  });
  return !!containingAssignment && getAssignmentDeclarationKind(containingAssignment) === 5 /* Property */;
}
function getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, declarationFilter) {
  const filteredDeclarations = declarationFilter !== void 0 ? filter(symbol.declarations, declarationFilter) : symbol.declarations;
  const signatureDefinition = !declarationFilter && (getConstructSignatureDefinition() || getCallSignatureDefinition());
  if (signatureDefinition) {
    return signatureDefinition;
  }
  const withoutExpandos = filter(filteredDeclarations, (d) => !isExpandoDeclaration(d));
  const results = some(withoutExpandos) ? withoutExpandos : filteredDeclarations;
  return map(results, (declaration) => createDefinitionInfo(
    declaration,
    typeChecker,
    symbol,
    node,
    /*unverified*/
    false,
    failedAliasResolution
  ));
  function getConstructSignatureDefinition() {
    if (symbol.flags & 32 /* Class */ && !(symbol.flags & (16 /* Function */ | 3 /* Variable */)) && (isNewExpressionTarget(node) || node.kind === 137 /* ConstructorKeyword */)) {
      const cls = find(filteredDeclarations, isClassLike);
      return cls && getSignatureDefinition(
        cls.members,
        /*selectConstructors*/
        true
      );
    }
  }
  function getCallSignatureDefinition() {
    return isCallOrNewExpressionTarget(node) || isNameOfFunctionDeclaration(node) ? getSignatureDefinition(
      filteredDeclarations,
      /*selectConstructors*/
      false
    ) : void 0;
  }
  function getSignatureDefinition(signatureDeclarations, selectConstructors) {
    if (!signatureDeclarations) {
      return void 0;
    }
    const declarations = signatureDeclarations.filter(selectConstructors ? isConstructorDeclaration : isFunctionLike);
    const declarationsWithBody = declarations.filter((d) => !!d.body);
    return declarations.length ? declarationsWithBody.length !== 0 ? declarationsWithBody.map((x) => createDefinitionInfo(x, typeChecker, symbol, node)) : [createDefinitionInfo(
      last(declarations),
      typeChecker,
      symbol,
      node,
      /*unverified*/
      false,
      failedAliasResolution
    )] : void 0;
  }
}
function createDefinitionInfo(declaration, checker, symbol, node, unverified, failedAliasResolution) {
  const symbolName2 = checker.symbolToString(symbol);
  const symbolKind = ts_SymbolDisplay_exports.getSymbolKind(checker, symbol, node);
  const containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : "";
  return createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName2, containerName, unverified, failedAliasResolution);
}
function createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName2, containerName, unverified, failedAliasResolution, textSpan) {
  const sourceFile = declaration.getSourceFile();
  if (!textSpan) {
    const name = getNameOfDeclaration(declaration) || declaration;
    textSpan = createTextSpanFromNode(name, sourceFile);
  }
  return {
    fileName: sourceFile.fileName,
    textSpan,
    kind: symbolKind,
    name: symbolName2,
    containerKind: void 0,
    // TODO: GH#18217
    containerName,
    ...ts_FindAllReferences_exports.toContextSpan(
      textSpan,
      sourceFile,
      ts_FindAllReferences_exports.getContextNode(declaration)
    ),
    isLocal: !isDefinitionVisible(checker, declaration),
    isAmbient: !!(declaration.flags & 33554432 /* Ambient */),
    unverified,
    failedAliasResolution
  };
}
function createDefinitionInfoFromSwitch(statement, sourceFile) {
  const keyword = ts_FindAllReferences_exports.getContextNode(statement);
  const textSpan = createTextSpanFromNode(isContextWithStartAndEndNode(keyword) ? keyword.start : keyword, sourceFile);
  return {
    fileName: sourceFile.fileName,
    textSpan,
    kind: "keyword" /* keyword */,
    name: "switch",
    containerKind: void 0,
    containerName: "",
    ...ts_FindAllReferences_exports.toContextSpan(textSpan, sourceFile, keyword),
    isLocal: true,
    isAmbient: false,
    unverified: false,
    failedAliasResolution: void 0
  };
}
function isDefinitionVisible(checker, declaration) {
  if (checker.isDeclarationVisible(declaration)) return true;
  if (!declaration.parent) return false;
  if (hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) return isDefinitionVisible(checker, declaration.parent);
  switch (declaration.kind) {
    case 172 /* PropertyDeclaration */:
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
    case 174 /* MethodDeclaration */:
      if (hasEffectiveModifier(declaration, 2 /* Private */)) return false;
    // Public properties/methods are visible if its parents are visible, so:
    // falls through
    case 176 /* Constructor */:
    case 303 /* PropertyAssignment */:
    case 304 /* ShorthandPropertyAssignment */:
    case 210 /* ObjectLiteralExpression */:
    case 231 /* ClassExpression */:
    case 219 /* ArrowFunction */:
    case 218 /* FunctionExpression */:
      return isDefinitionVisible(checker, declaration.parent);
    default:
      return false;
  }
}
function createDefinitionFromSignatureDeclaration(typeChecker, decl, failedAliasResolution) {
  return createDefinitionInfo(
    decl,
    typeChecker,
    decl.symbol,
    decl,
    /*unverified*/
    false,
    failedAliasResolution
  );
}
function findReferenceInPosition(refs, pos) {
  return find(refs, (ref) => textRangeContainsPositionInclusive(ref, pos));
}
function getDefinitionInfoForFileReference(name, targetFileName, unverified) {
  return {
    fileName: targetFileName,
    textSpan: createTextSpanFromBounds(0, 0),
    kind: "script" /* scriptElement */,
    name,
    containerName: void 0,
    containerKind: void 0,
    // TODO: GH#18217
    unverified
  };
}
function getAncestorCallLikeExpression(node) {
  const target = findAncestor(node, (n) => !isRightSideOfPropertyAccess(n));
  const callLike = target == null ? void 0 : target.parent;
  return callLike && isCallLikeExpression(callLike) && getInvokedExpression(callLike) === target ? callLike : void 0;
}
function tryGetSignatureDeclaration(typeChecker, node) {
  const callLike = getAncestorCallLikeExpression(node);
  const signature = callLike && typeChecker.getResolvedSignature(callLike);
  return tryCast(signature && signature.declaration, (d) => isFunctionLike(d) && !isFunctionTypeNode(d));
}
function isJsxConstructorLike(node) {
  switch (node.kind) {
    case 176 /* Constructor */:
    case 185 /* ConstructorType */:
    case 179 /* CallSignature */:
    case 180 /* ConstructSignature */:
      return true;
    default:
      return false;
  }
}

// src/services/_namespaces/ts.InlayHints.ts
var ts_InlayHints_exports = {};
__export(ts_InlayHints_exports, {
  provideInlayHints: () => provideInlayHints
});

// src/services/inlayHints.ts
var leadingParameterNameCommentRegexFactory = (name) => {
  return new RegExp(`^\\s?/\\*\\*?\\s?${name}\\s?\\*\\/\\s?$`);
};
function shouldShowParameterNameHints(preferences) {
  return preferences.includeInlayParameterNameHints === "literals" || preferences.includeInlayParameterNameHints === "all";
}
function shouldShowLiteralParameterNameHintsOnly(preferences) {
  return preferences.includeInlayParameterNameHints === "literals";
}
function shouldUseInteractiveInlayHints(preferences) {
  return preferences.interactiveInlayHints === true;
}
function provideInlayHints(context) {
  const { file, program, span, cancellationToken, preferences } = context;
  const sourceFileText = file.text;
  const compilerOptions = program.getCompilerOptions();
  const quotePreference = getQuotePreference(file, preferences);
  const checker = program.getTypeChecker();
  const result = [];
  visitor(file);
  return result;
  function visitor(node) {
    if (!node || node.getFullWidth() === 0) {
      return;
    }
    switch (node.kind) {
      case 267 /* ModuleDeclaration */:
      case 263 /* ClassDeclaration */:
      case 264 /* InterfaceDeclaration */:
      case 262 /* FunctionDeclaration */:
      case 231 /* ClassExpression */:
      case 218 /* FunctionExpression */:
      case 174 /* MethodDeclaration */:
      case 219 /* ArrowFunction */:
        cancellationToken.throwIfCancellationRequested();
    }
    if (!textSpanIntersectsWith(span, node.pos, node.getFullWidth())) {
      return;
    }
    if (isTypeNode(node) && !isExpressionWithTypeArguments(node)) {
      return;
    }
    if (preferences.includeInlayVariableTypeHints && isVariableDeclaration(node)) {
      visitVariableLikeDeclaration(node);
    } else if (preferences.includeInlayPropertyDeclarationTypeHints && isPropertyDeclaration(node)) {
      visitVariableLikeDeclaration(node);
    } else if (preferences.includeInlayEnumMemberValueHints && isEnumMember(node)) {
      visitEnumMember(node);
    } else if (shouldShowParameterNameHints(preferences) && (isCallExpression(node) || isNewExpression(node))) {
      visitCallOrNewExpression(node);
    } else {
      if (preferences.includeInlayFunctionParameterTypeHints && isFunctionLikeDeclaration(node) && hasContextSensitiveParameters(node)) {
        visitFunctionLikeForParameterType(node);
      }
      if (preferences.includeInlayFunctionLikeReturnTypeHints && isSignatureSupportingReturnAnnotation(node)) {
        visitFunctionDeclarationLikeForReturnType(node);
      }
    }
    return forEachChild(node, visitor);
  }
  function isSignatureSupportingReturnAnnotation(node) {
    return isArrowFunction(node) || isFunctionExpression(node) || isFunctionDeclaration(node) || isMethodDeclaration(node) || isGetAccessorDeclaration(node);
  }
  function addParameterHints(text, parameter, position, isFirstVariadicArgument) {
    let hintText = `${isFirstVariadicArgument ? "..." : ""}${text}`;
    let displayParts;
    if (shouldUseInteractiveInlayHints(preferences)) {
      displayParts = [getNodeDisplayPart(hintText, parameter), { text: ":" }];
      hintText = "";
    } else {
      hintText += ":";
    }
    result.push({
      text: hintText,
      position,
      kind: "Parameter" /* Parameter */,
      whitespaceAfter: true,
      displayParts
    });
  }
  function addTypeHints(hintText, position) {
    result.push({
      text: typeof hintText === "string" ? `: ${hintText}` : "",
      displayParts: typeof hintText === "string" ? void 0 : [{ text: ": " }, ...hintText],
      position,
      kind: "Type" /* Type */,
      whitespaceBefore: true
    });
  }
  function addEnumMemberValueHints(text, position) {
    result.push({
      text: `= ${text}`,
      position,
      kind: "Enum" /* Enum */,
      whitespaceBefore: true
    });
  }
  function visitEnumMember(member) {
    if (member.initializer) {
      return;
    }
    const enumValue = checker.getConstantValue(member);
    if (enumValue !== void 0) {
      addEnumMemberValueHints(enumValue.toString(), member.end);
    }
  }
  function isModuleReferenceType(type) {
    return type.symbol && type.symbol.flags & 1536 /* Module */;
  }
  function visitVariableLikeDeclaration(decl) {
    if (decl.initializer === void 0 && !(isPropertyDeclaration(decl) && !(checker.getTypeAtLocation(decl).flags & 1 /* Any */)) || isBindingPattern(decl.name) || isVariableDeclaration(decl) && !isHintableDeclaration(decl)) {
      return;
    }
    const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(decl);
    if (effectiveTypeAnnotation) {
      return;
    }
    const declarationType = checker.getTypeAtLocation(decl);
    if (isModuleReferenceType(declarationType)) {
      return;
    }
    const hintParts = typeToInlayHintParts(declarationType);
    if (hintParts) {
      const hintText = typeof hintParts === "string" ? hintParts : hintParts.map((part) => part.text).join("");
      const isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && equateStringsCaseInsensitive(decl.name.getText(), hintText);
      if (isVariableNameMatchesType) {
        return;
      }
      addTypeHints(hintParts, decl.name.end);
    }
  }
  function visitCallOrNewExpression(expr) {
    const args = expr.arguments;
    if (!args || !args.length) {
      return;
    }
    const signature = checker.getResolvedSignature(expr);
    if (signature === void 0) return;
    let signatureParamPos = 0;
    for (const originalArg of args) {
      const arg = skipParentheses(originalArg);
      if (shouldShowLiteralParameterNameHintsOnly(preferences) && !isHintableLiteral(arg)) {
        signatureParamPos++;
        continue;
      }
      let spreadArgs = 0;
      if (isSpreadElement(arg)) {
        const spreadType = checker.getTypeAtLocation(arg.expression);
        if (checker.isTupleType(spreadType)) {
          const { elementFlags, fixedLength } = spreadType.target;
          if (fixedLength === 0) {
            continue;
          }
          const firstOptionalIndex = findIndex(elementFlags, (f) => !(f & 1 /* Required */));
          const requiredArgs = firstOptionalIndex < 0 ? fixedLength : firstOptionalIndex;
          if (requiredArgs > 0) {
            spreadArgs = firstOptionalIndex < 0 ? fixedLength : firstOptionalIndex;
          }
        }
      }
      const identifierInfo = checker.getParameterIdentifierInfoAtPosition(signature, signatureParamPos);
      signatureParamPos = signatureParamPos + (spreadArgs || 1);
      if (identifierInfo) {
        const { parameter, parameterName, isRestParameter: isFirstVariadicArgument } = identifierInfo;
        const isParameterNameNotSameAsArgument = preferences.includeInlayParameterNameHintsWhenArgumentMatchesName || !identifierOrAccessExpressionPostfixMatchesParameterName(arg, parameterName);
        if (!isParameterNameNotSameAsArgument && !isFirstVariadicArgument) {
          continue;
        }
        const name = unescapeLeadingUnderscores(parameterName);
        if (leadingCommentsContainsParameterName(arg, name)) {
          continue;
        }
        addParameterHints(name, parameter, originalArg.getStart(), isFirstVariadicArgument);
      }
    }
  }
  function identifierOrAccessExpressionPostfixMatchesParameterName(expr, parameterName) {
    if (isIdentifier(expr)) {
      return expr.text === parameterName;
    }
    if (isPropertyAccessExpression(expr)) {
      return expr.name.text === parameterName;
    }
    return false;
  }
  function leadingCommentsContainsParameterName(node, name) {
    if (!isIdentifierText(name, getEmitScriptTarget(compilerOptions), getLanguageVariant(file.scriptKind))) {
      return false;
    }
    const ranges = getLeadingCommentRanges(sourceFileText, node.pos);
    if (!(ranges == null ? void 0 : ranges.length)) {
      return false;
    }
    const regex = leadingParameterNameCommentRegexFactory(name);
    return some(ranges, (range) => regex.test(sourceFileText.substring(range.pos, range.end)));
  }
  function isHintableLiteral(node) {
    switch (node.kind) {
      case 224 /* PrefixUnaryExpression */: {
        const operand = node.operand;
        return isLiteralExpression(operand) || isIdentifier(operand) && isInfinityOrNaNString(operand.escapedText);
      }
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 106 /* NullKeyword */:
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 228 /* TemplateExpression */:
        return true;
      case 80 /* Identifier */: {
        const name = node.escapedText;
        return isUndefined(name) || isInfinityOrNaNString(name);
      }
    }
    return isLiteralExpression(node);
  }
  function visitFunctionDeclarationLikeForReturnType(decl) {
    if (isArrowFunction(decl)) {
      if (!findChildOfKind(decl, 21 /* OpenParenToken */, file)) {
        return;
      }
    }
    const effectiveTypeAnnotation = getEffectiveReturnTypeNode(decl);
    if (effectiveTypeAnnotation || !decl.body) {
      return;
    }
    const signature = checker.getSignatureFromDeclaration(decl);
    if (!signature) {
      return;
    }
    const typePredicate = checker.getTypePredicateOfSignature(signature);
    if (typePredicate == null ? void 0 : typePredicate.type) {
      const hintParts2 = typePredicateToInlayHintParts(typePredicate);
      if (hintParts2) {
        addTypeHints(hintParts2, getTypeAnnotationPosition(decl));
        return;
      }
    }
    const returnType = checker.getReturnTypeOfSignature(signature);
    if (isModuleReferenceType(returnType)) {
      return;
    }
    const hintParts = typeToInlayHintParts(returnType);
    if (hintParts) {
      addTypeHints(hintParts, getTypeAnnotationPosition(decl));
    }
  }
  function getTypeAnnotationPosition(decl) {
    const closeParenToken = findChildOfKind(decl, 22 /* CloseParenToken */, file);
    if (closeParenToken) {
      return closeParenToken.end;
    }
    return decl.parameters.end;
  }
  function visitFunctionLikeForParameterType(node) {
    const signature = checker.getSignatureFromDeclaration(node);
    if (!signature) {
      return;
    }
    for (let i = 0; i < node.parameters.length && i < signature.parameters.length; ++i) {
      const param = node.parameters[i];
      if (!isHintableDeclaration(param)) {
        continue;
      }
      const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(param);
      if (effectiveTypeAnnotation) {
        continue;
      }
      const typeHints = getParameterDeclarationTypeHints(signature.parameters[i]);
      if (!typeHints) {
        continue;
      }
      addTypeHints(typeHints, param.questionToken ? param.questionToken.end : param.name.end);
    }
  }
  function getParameterDeclarationTypeHints(symbol) {
    const valueDeclaration = symbol.valueDeclaration;
    if (!valueDeclaration || !isParameter(valueDeclaration)) {
      return void 0;
    }
    const signatureParamType = checker.getTypeOfSymbolAtLocation(symbol, valueDeclaration);
    if (isModuleReferenceType(signatureParamType)) {
      return void 0;
    }
    return typeToInlayHintParts(signatureParamType);
  }
  function printTypeInSingleLine(type) {
    const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
    const printer = createPrinterWithRemoveComments();
    return usingSingleLineStringWriter((writer) => {
      const typeNode = checker.typeToTypeNode(
        type,
        /*enclosingDeclaration*/
        void 0,
        flags
      );
      Debug.assertIsDefined(typeNode, "should always get typenode");
      printer.writeNode(
        4 /* Unspecified */,
        typeNode,
        /*sourceFile*/
        file,
        writer
      );
    });
  }
  function printTypePredicateInSingleLine(typePredicate) {
    const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
    const printer = createPrinterWithRemoveComments();
    return usingSingleLineStringWriter((writer) => {
      const typePredicateNode = checker.typePredicateToTypePredicateNode(
        typePredicate,
        /*enclosingDeclaration*/
        void 0,
        flags
      );
      Debug.assertIsDefined(typePredicateNode, "should always get typePredicateNode");
      printer.writeNode(
        4 /* Unspecified */,
        typePredicateNode,
        /*sourceFile*/
        file,
        writer
      );
    });
  }
  function typeToInlayHintParts(type) {
    if (!shouldUseInteractiveInlayHints(preferences)) {
      return printTypeInSingleLine(type);
    }
    const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
    const typeNode = checker.typeToTypeNode(
      type,
      /*enclosingDeclaration*/
      void 0,
      flags
    );
    Debug.assertIsDefined(typeNode, "should always get typeNode");
    return getInlayHintDisplayParts(typeNode);
  }
  function typePredicateToInlayHintParts(typePredicate) {
    if (!shouldUseInteractiveInlayHints(preferences)) {
      return printTypePredicateInSingleLine(typePredicate);
    }
    const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
    const typeNode = checker.typePredicateToTypePredicateNode(
      typePredicate,
      /*enclosingDeclaration*/
      void 0,
      flags
    );
    Debug.assertIsDefined(typeNode, "should always get typenode");
    return getInlayHintDisplayParts(typeNode);
  }
  function getInlayHintDisplayParts(node) {
    const parts = [];
    visitForDisplayParts(node);
    return parts;
    function visitForDisplayParts(node2) {
      var _a, _b;
      if (!node2) {
        return;
      }
      const tokenString = tokenToString(node2.kind);
      if (tokenString) {
        parts.push({ text: tokenString });
        return;
      }
      if (isLiteralExpression(node2)) {
        parts.push({ text: getLiteralText2(node2) });
        return;
      }
      switch (node2.kind) {
        case 80 /* Identifier */:
          Debug.assertNode(node2, isIdentifier);
          const identifierText = idText(node2);
          const name = node2.symbol && node2.symbol.declarations && node2.symbol.declarations.length && getNameOfDeclaration(node2.symbol.declarations[0]);
          if (name) {
            parts.push(getNodeDisplayPart(identifierText, name));
          } else {
            parts.push({ text: identifierText });
          }
          break;
        case 166 /* QualifiedName */:
          Debug.assertNode(node2, isQualifiedName);
          visitForDisplayParts(node2.left);
          parts.push({ text: "." });
          visitForDisplayParts(node2.right);
          break;
        case 182 /* TypePredicate */:
          Debug.assertNode(node2, isTypePredicateNode);
          if (node2.assertsModifier) {
            parts.push({ text: "asserts " });
          }
          visitForDisplayParts(node2.parameterName);
          if (node2.type) {
            parts.push({ text: " is " });
            visitForDisplayParts(node2.type);
          }
          break;
        case 183 /* TypeReference */:
          Debug.assertNode(node2, isTypeReferenceNode);
          visitForDisplayParts(node2.typeName);
          if (node2.typeArguments) {
            parts.push({ text: "<" });
            visitDisplayPartList(node2.typeArguments, ", ");
            parts.push({ text: ">" });
          }
          break;
        case 168 /* TypeParameter */:
          Debug.assertNode(node2, isTypeParameterDeclaration);
          if (node2.modifiers) {
            visitDisplayPartList(node2.modifiers, " ");
          }
          visitForDisplayParts(node2.name);
          if (node2.constraint) {
            parts.push({ text: " extends " });
            visitForDisplayParts(node2.constraint);
          }
          if (node2.default) {
            parts.push({ text: " = " });
            visitForDisplayParts(node2.default);
          }
          break;
        case 169 /* Parameter */:
          Debug.assertNode(node2, isParameter);
          if (node2.modifiers) {
            visitDisplayPartList(node2.modifiers, " ");
          }
          if (node2.dotDotDotToken) {
            parts.push({ text: "..." });
          }
          visitForDisplayParts(node2.name);
          if (node2.questionToken) {
            parts.push({ text: "?" });
          }
          if (node2.type) {
            parts.push({ text: ": " });
            visitForDisplayParts(node2.type);
          }
          break;
        case 185 /* ConstructorType */:
          Debug.assertNode(node2, isConstructorTypeNode);
          parts.push({ text: "new " });
          visitParametersAndTypeParameters(node2);
          parts.push({ text: " => " });
          visitForDisplayParts(node2.type);
          break;
        case 186 /* TypeQuery */:
          Debug.assertNode(node2, isTypeQueryNode);
          parts.push({ text: "typeof " });
          visitForDisplayParts(node2.exprName);
          if (node2.typeArguments) {
            parts.push({ text: "<" });
            visitDisplayPartList(node2.typeArguments, ", ");
            parts.push({ text: ">" });
          }
          break;
        case 187 /* TypeLiteral */:
          Debug.assertNode(node2, isTypeLiteralNode);
          parts.push({ text: "{" });
          if (node2.members.length) {
            parts.push({ text: " " });
            visitDisplayPartList(node2.members, "; ");
            parts.push({ text: " " });
          }
          parts.push({ text: "}" });
          break;
        case 188 /* ArrayType */:
          Debug.assertNode(node2, isArrayTypeNode);
          visitForDisplayParts(node2.elementType);
          parts.push({ text: "[]" });
          break;
        case 189 /* TupleType */:
          Debug.assertNode(node2, isTupleTypeNode);
          parts.push({ text: "[" });
          visitDisplayPartList(node2.elements, ", ");
          parts.push({ text: "]" });
          break;
        case 202 /* NamedTupleMember */:
          Debug.assertNode(node2, isNamedTupleMember);
          if (node2.dotDotDotToken) {
            parts.push({ text: "..." });
          }
          visitForDisplayParts(node2.name);
          if (node2.questionToken) {
            parts.push({ text: "?" });
          }
          parts.push({ text: ": " });
          visitForDisplayParts(node2.type);
          break;
        case 190 /* OptionalType */:
          Debug.assertNode(node2, isOptionalTypeNode);
          visitForDisplayParts(node2.type);
          parts.push({ text: "?" });
          break;
        case 191 /* RestType */:
          Debug.assertNode(node2, isRestTypeNode);
          parts.push({ text: "..." });
          visitForDisplayParts(node2.type);
          break;
        case 192 /* UnionType */:
          Debug.assertNode(node2, isUnionTypeNode);
          visitDisplayPartList(node2.types, " | ");
          break;
        case 193 /* IntersectionType */:
          Debug.assertNode(node2, isIntersectionTypeNode);
          visitDisplayPartList(node2.types, " & ");
          break;
        case 194 /* ConditionalType */:
          Debug.assertNode(node2, isConditionalTypeNode);
          visitForDisplayParts(node2.checkType);
          parts.push({ text: " extends " });
          visitForDisplayParts(node2.extendsType);
          parts.push({ text: " ? " });
          visitForDisplayParts(node2.trueType);
          parts.push({ text: " : " });
          visitForDisplayParts(node2.falseType);
          break;
        case 195 /* InferType */:
          Debug.assertNode(node2, isInferTypeNode);
          parts.push({ text: "infer " });
          visitForDisplayParts(node2.typeParameter);
          break;
        case 196 /* ParenthesizedType */:
          Debug.assertNode(node2, isParenthesizedTypeNode);
          parts.push({ text: "(" });
          visitForDisplayParts(node2.type);
          parts.push({ text: ")" });
          break;
        case 198 /* TypeOperator */:
          Debug.assertNode(node2, isTypeOperatorNode);
          parts.push({ text: `${tokenToString(node2.operator)} ` });
          visitForDisplayParts(node2.type);
          break;
        case 199 /* IndexedAccessType */:
          Debug.assertNode(node2, isIndexedAccessTypeNode);
          visitForDisplayParts(node2.objectType);
          parts.push({ text: "[" });
          visitForDisplayParts(node2.indexType);
          parts.push({ text: "]" });
          break;
        case 200 /* MappedType */:
          Debug.assertNode(node2, isMappedTypeNode);
          parts.push({ text: "{ " });
          if (node2.readonlyToken) {
            if (node2.readonlyToken.kind === 40 /* PlusToken */) {
              parts.push({ text: "+" });
            } else if (node2.readonlyToken.kind === 41 /* MinusToken */) {
              parts.push({ text: "-" });
            }
            parts.push({ text: "readonly " });
          }
          parts.push({ text: "[" });
          visitForDisplayParts(node2.typeParameter);
          if (node2.nameType) {
            parts.push({ text: " as " });
            visitForDisplayParts(node2.nameType);
          }
          parts.push({ text: "]" });
          if (node2.questionToken) {
            if (node2.questionToken.kind === 40 /* PlusToken */) {
              parts.push({ text: "+" });
            } else if (node2.questionToken.kind === 41 /* MinusToken */) {
              parts.push({ text: "-" });
            }
            parts.push({ text: "?" });
          }
          parts.push({ text: ": " });
          if (node2.type) {
            visitForDisplayParts(node2.type);
          }
          parts.push({ text: "; }" });
          break;
        case 201 /* LiteralType */:
          Debug.assertNode(node2, isLiteralTypeNode);
          visitForDisplayParts(node2.literal);
          break;
        case 184 /* FunctionType */:
          Debug.assertNode(node2, isFunctionTypeNode);
          visitParametersAndTypeParameters(node2);
          parts.push({ text: " => " });
          visitForDisplayParts(node2.type);
          break;
        case 205 /* ImportType */:
          Debug.assertNode(node2, isImportTypeNode);
          if (node2.isTypeOf) {
            parts.push({ text: "typeof " });
          }
          parts.push({ text: "import(" });
          visitForDisplayParts(node2.argument);
          if (node2.assertions) {
            parts.push({ text: ", { assert: " });
            visitDisplayPartList(node2.assertions.assertClause.elements, ", ");
            parts.push({ text: " }" });
          }
          parts.push({ text: ")" });
          if (node2.qualifier) {
            parts.push({ text: "." });
            visitForDisplayParts(node2.qualifier);
          }
          if (node2.typeArguments) {
            parts.push({ text: "<" });
            visitDisplayPartList(node2.typeArguments, ", ");
            parts.push({ text: ">" });
          }
          break;
        case 171 /* PropertySignature */:
          Debug.assertNode(node2, isPropertySignature);
          if ((_a = node2.modifiers) == null ? void 0 : _a.length) {
            visitDisplayPartList(node2.modifiers, " ");
            parts.push({ text: " " });
          }
          visitForDisplayParts(node2.name);
          if (node2.questionToken) {
            parts.push({ text: "?" });
          }
          if (node2.type) {
            parts.push({ text: ": " });
            visitForDisplayParts(node2.type);
          }
          break;
        case 181 /* IndexSignature */:
          Debug.assertNode(node2, isIndexSignatureDeclaration);
          parts.push({ text: "[" });
          visitDisplayPartList(node2.parameters, ", ");
          parts.push({ text: "]" });
          if (node2.type) {
            parts.push({ text: ": " });
            visitForDisplayParts(node2.type);
          }
          break;
        case 173 /* MethodSignature */:
          Debug.assertNode(node2, isMethodSignature);
          if ((_b = node2.modifiers) == null ? void 0 : _b.length) {
            visitDisplayPartList(node2.modifiers, " ");
            parts.push({ text: " " });
          }
          visitForDisplayParts(node2.name);
          if (node2.questionToken) {
            parts.push({ text: "?" });
          }
          visitParametersAndTypeParameters(node2);
          if (node2.type) {
            parts.push({ text: ": " });
            visitForDisplayParts(node2.type);
          }
          break;
        case 179 /* CallSignature */:
          Debug.assertNode(node2, isCallSignatureDeclaration);
          visitParametersAndTypeParameters(node2);
          if (node2.type) {
            parts.push({ text: ": " });
            visitForDisplayParts(node2.type);
          }
          break;
        case 207 /* ArrayBindingPattern */:
          Debug.assertNode(node2, isArrayBindingPattern);
          parts.push({ text: "[" });
          visitDisplayPartList(node2.elements, ", ");
          parts.push({ text: "]" });
          break;
        case 206 /* ObjectBindingPattern */:
          Debug.assertNode(node2, isObjectBindingPattern);
          parts.push({ text: "{" });
          if (node2.elements.length) {
            parts.push({ text: " " });
            visitDisplayPartList(node2.elements, ", ");
            parts.push({ text: " " });
          }
          parts.push({ text: "}" });
          break;
        case 208 /* BindingElement */:
          Debug.assertNode(node2, isBindingElement);
          visitForDisplayParts(node2.name);
          break;
        case 224 /* PrefixUnaryExpression */:
          Debug.assertNode(node2, isPrefixUnaryExpression);
          parts.push({ text: tokenToString(node2.operator) });
          visitForDisplayParts(node2.operand);
          break;
        case 203 /* TemplateLiteralType */:
          Debug.assertNode(node2, isTemplateLiteralTypeNode);
          visitForDisplayParts(node2.head);
          node2.templateSpans.forEach(visitForDisplayParts);
          break;
        case 16 /* TemplateHead */:
          Debug.assertNode(node2, isTemplateHead);
          parts.push({ text: getLiteralText2(node2) });
          break;
        case 204 /* TemplateLiteralTypeSpan */:
          Debug.assertNode(node2, isTemplateLiteralTypeSpan);
          visitForDisplayParts(node2.type);
          visitForDisplayParts(node2.literal);
          break;
        case 17 /* TemplateMiddle */:
          Debug.assertNode(node2, isTemplateMiddle);
          parts.push({ text: getLiteralText2(node2) });
          break;
        case 18 /* TemplateTail */:
          Debug.assertNode(node2, isTemplateTail);
          parts.push({ text: getLiteralText2(node2) });
          break;
        case 197 /* ThisType */:
          Debug.assertNode(node2, isThisTypeNode);
          parts.push({ text: "this" });
          break;
        default:
          Debug.failBadSyntaxKind(node2);
      }
    }
    function visitParametersAndTypeParameters(signatureDeclaration) {
      if (signatureDeclaration.typeParameters) {
        parts.push({ text: "<" });
        visitDisplayPartList(signatureDeclaration.typeParameters, ", ");
        parts.push({ text: ">" });
      }
      parts.push({ text: "(" });
      visitDisplayPartList(signatureDeclaration.parameters, ", ");
      parts.push({ text: ")" });
    }
    function visitDisplayPartList(nodes, separator) {
      nodes.forEach((node2, index) => {
        if (index > 0) {
          parts.push({ text: separator });
        }
        visitForDisplayParts(node2);
      });
    }
    function getLiteralText2(node2) {
      switch (node2.kind) {
        case 11 /* StringLiteral */:
          return quotePreference === 0 /* Single */ ? `'${escapeString(node2.text, 39 /* singleQuote */)}'` : `"${escapeString(node2.text, 34 /* doubleQuote */)}"`;
        case 16 /* TemplateHead */:
        case 17 /* TemplateMiddle */:
        case 18 /* TemplateTail */: {
          const rawText = node2.rawText ?? escapeTemplateSubstitution(escapeString(node2.text, 96 /* backtick */));
          switch (node2.kind) {
            case 16 /* TemplateHead */:
              return "`" + rawText + "${";
            case 17 /* TemplateMiddle */:
              return "}" + rawText + "${";
            case 18 /* TemplateTail */:
              return "}" + rawText + "`";
          }
        }
      }
      return node2.text;
    }
  }
  function isUndefined(name) {
    return name === "undefined";
  }
  function isHintableDeclaration(node) {
    if ((isPartOfParameterDeclaration(node) || isVariableDeclaration(node) && isVarConst(node)) && node.initializer) {
      const initializer = skipParentheses(node.initializer);
      return !(isHintableLiteral(initializer) || isNewExpression(initializer) || isObjectLiteralExpression(initializer) || isAssertionExpression(initializer));
    }
    return true;
  }
  function getNodeDisplayPart(text, node) {
    const sourceFile = node.getSourceFile();
    return {
      text,
      span: createTextSpanFromNode(node, sourceFile),
      file: sourceFile.fileName
    };
  }
}

// src/services/_namespaces/ts.JsDoc.ts
var ts_JsDoc_exports = {};
__export(ts_JsDoc_exports, {
  getDocCommentTemplateAtPosition: () => getDocCommentTemplateAtPosition,
  getJSDocParameterNameCompletionDetails: () => getJSDocParameterNameCompletionDetails,
  getJSDocParameterNameCompletions: () => getJSDocParameterNameCompletions,
  getJSDocTagCompletionDetails: () => getJSDocTagCompletionDetails,
  getJSDocTagCompletions: () => getJSDocTagCompletions,
  getJSDocTagNameCompletionDetails: () => getJSDocTagNameCompletionDetails,
  getJSDocTagNameCompletions: () => getJSDocTagNameCompletions,
  getJsDocCommentsFromDeclarations: () => getJsDocCommentsFromDeclarations,
  getJsDocTagsFromDeclarations: () => getJsDocTagsFromDeclarations
});

// src/services/jsDoc.ts
var jsDocTagNames = [
  "abstract",
  "access",
  "alias",
  "argument",
  "async",
  "augments",
  "author",
  "borrows",
  "callback",
  "class",
  "classdesc",
  "constant",
  "constructor",
  "constructs",
  "copyright",
  "default",
  "deprecated",
  "description",
  "emits",
  "enum",
  "event",
  "example",
  "exports",
  "extends",
  "external",
  "field",
  "file",
  "fileoverview",
  "fires",
  "function",
  "generator",
  "global",
  "hideconstructor",
  "host",
  "ignore",
  "implements",
  "import",
  "inheritdoc",
  "inner",
  "instance",
  "interface",
  "kind",
  "lends",
  "license",
  "link",
  "linkcode",
  "linkplain",
  "listens",
  "member",
  "memberof",
  "method",
  "mixes",
  "module",
  "name",
  "namespace",
  "overload",
  "override",
  "package",
  "param",
  "private",
  "prop",
  "property",
  "protected",
  "public",
  "readonly",
  "requires",
  "returns",
  "satisfies",
  "see",
  "since",
  "static",
  "summary",
  "template",
  "this",
  "throws",
  "todo",
  "tutorial",
  "type",
  "typedef",
  "var",
  "variation",
  "version",
  "virtual",
  "yields"
];
var jsDocTagNameCompletionEntries;
var jsDocTagCompletionEntries;
function getJsDocCommentsFromDeclarations(declarations, checker) {
  const parts = [];
  forEachUnique(declarations, (declaration) => {
    for (const jsdoc of getCommentHavingNodes(declaration)) {
      const inheritDoc = isJSDoc(jsdoc) && jsdoc.tags && find(jsdoc.tags, (t) => t.kind === 327 /* JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc"));
      if (jsdoc.comment === void 0 && !inheritDoc || isJSDoc(jsdoc) && declaration.kind !== 346 /* JSDocTypedefTag */ && declaration.kind !== 338 /* JSDocCallbackTag */ && jsdoc.tags && jsdoc.tags.some((t) => t.kind === 346 /* JSDocTypedefTag */ || t.kind === 338 /* JSDocCallbackTag */) && !jsdoc.tags.some((t) => t.kind === 341 /* JSDocParameterTag */ || t.kind === 342 /* JSDocReturnTag */)) {
        continue;
      }
      let newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : [];
      if (inheritDoc && inheritDoc.comment) {
        newparts = newparts.concat(getDisplayPartsFromComment(inheritDoc.comment, checker));
      }
      if (!contains(parts, newparts, isIdenticalListOfDisplayParts)) {
        parts.push(newparts);
      }
    }
  });
  return flatten(intersperse(parts, [lineBreakPart()]));
}
function isIdenticalListOfDisplayParts(parts1, parts2) {
  return arrayIsEqualTo(parts1, parts2, (p1, p2) => p1.kind === p2.kind && p1.text === p2.text);
}
function getCommentHavingNodes(declaration) {
  switch (declaration.kind) {
    case 341 /* JSDocParameterTag */:
    case 348 /* JSDocPropertyTag */:
      return [declaration];
    case 338 /* JSDocCallbackTag */:
    case 346 /* JSDocTypedefTag */:
      return [declaration, declaration.parent];
    case 323 /* JSDocSignature */:
      if (isJSDocOverloadTag(declaration.parent)) {
        return [declaration.parent.parent];
      }
    // falls through
    default:
      return getJSDocCommentsAndTags(declaration);
  }
}
function getJsDocTagsFromDeclarations(declarations, checker) {
  const infos = [];
  forEachUnique(declarations, (declaration) => {
    const tags = getJSDocTags(declaration);
    if (tags.some((t) => t.kind === 346 /* JSDocTypedefTag */ || t.kind === 338 /* JSDocCallbackTag */) && !tags.some((t) => t.kind === 341 /* JSDocParameterTag */ || t.kind === 342 /* JSDocReturnTag */)) {
      return;
    }
    for (const tag of tags) {
      infos.push({ name: tag.tagName.text, text: getCommentDisplayParts(tag, checker) });
      infos.push(...getJSDocPropertyTagsInfo(tryGetJSDocPropertyTags(tag), checker));
    }
  });
  return infos;
}
function getJSDocPropertyTagsInfo(nodes, checker) {
  return flatMap(nodes, (propTag) => concatenate([{ name: propTag.tagName.text, text: getCommentDisplayParts(propTag, checker) }], getJSDocPropertyTagsInfo(tryGetJSDocPropertyTags(propTag), checker)));
}
function tryGetJSDocPropertyTags(node) {
  return isJSDocPropertyLikeTag(node) && node.isNameFirst && node.typeExpression && isJSDocTypeLiteral(node.typeExpression.type) ? node.typeExpression.type.jsDocPropertyTags : void 0;
}
function getDisplayPartsFromComment(comment, checker) {
  if (typeof comment === "string") {
    return [textPart(comment)];
  }
  return flatMap(
    comment,
    (node) => node.kind === 321 /* JSDocText */ ? [textPart(node.text)] : buildLinkParts(node, checker)
  );
}
function getCommentDisplayParts(tag, checker) {
  const { comment, kind } = tag;
  const namePart = getTagNameDisplayPart(kind);
  switch (kind) {
    case 349 /* JSDocThrowsTag */:
      const typeExpression = tag.typeExpression;
      return typeExpression ? withNode(typeExpression) : comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker);
    case 329 /* JSDocImplementsTag */:
      return withNode(tag.class);
    case 328 /* JSDocAugmentsTag */:
      return withNode(tag.class);
    case 345 /* JSDocTemplateTag */:
      const templateTag = tag;
      const displayParts = [];
      if (templateTag.constraint) {
        displayParts.push(textPart(templateTag.constraint.getText()));
      }
      if (length(templateTag.typeParameters)) {
        if (length(displayParts)) {
          displayParts.push(spacePart());
        }
        const lastTypeParameter = templateTag.typeParameters[templateTag.typeParameters.length - 1];
        forEach(templateTag.typeParameters, (tp) => {
          displayParts.push(namePart(tp.getText()));
          if (lastTypeParameter !== tp) {
            displayParts.push(...[punctuationPart(28 /* CommaToken */), spacePart()]);
          }
        });
      }
      if (comment) {
        displayParts.push(...[spacePart(), ...getDisplayPartsFromComment(comment, checker)]);
      }
      return displayParts;
    case 344 /* JSDocTypeTag */:
    case 350 /* JSDocSatisfiesTag */:
      return withNode(tag.typeExpression);
    case 346 /* JSDocTypedefTag */:
    case 338 /* JSDocCallbackTag */:
    case 348 /* JSDocPropertyTag */:
    case 341 /* JSDocParameterTag */:
    case 347 /* JSDocSeeTag */:
      const { name } = tag;
      return name ? withNode(name) : comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker);
    default:
      return comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker);
  }
  function withNode(node) {
    return addComment(node.getText());
  }
  function addComment(s) {
    if (comment) {
      if (s.match(/^https?$/)) {
        return [textPart(s), ...getDisplayPartsFromComment(comment, checker)];
      } else {
        return [namePart(s), spacePart(), ...getDisplayPartsFromComment(comment, checker)];
      }
    } else {
      return [textPart(s)];
    }
  }
}
function getTagNameDisplayPart(kind) {
  switch (kind) {
    case 341 /* JSDocParameterTag */:
      return parameterNamePart;
    case 348 /* JSDocPropertyTag */:
      return propertyNamePart;
    case 345 /* JSDocTemplateTag */:
      return typeParameterNamePart;
    case 346 /* JSDocTypedefTag */:
    case 338 /* JSDocCallbackTag */:
      return typeAliasNamePart;
    default:
      return textPart;
  }
}
function getJSDocTagNameCompletions() {
  return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = map(jsDocTagNames, (tagName) => {
    return {
      name: tagName,
      kind: "keyword" /* keyword */,
      kindModifiers: "",
      sortText: ts_Completions_exports.SortText.LocationPriority
    };
  }));
}
var getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails;
function getJSDocTagCompletions() {
  return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = map(jsDocTagNames, (tagName) => {
    return {
      name: `@${tagName}`,
      kind: "keyword" /* keyword */,
      kindModifiers: "",
      sortText: ts_Completions_exports.SortText.LocationPriority
    };
  }));
}
function getJSDocTagCompletionDetails(name) {
  return {
    name,
    kind: "" /* unknown */,
    // TODO: should have its own kind?
    kindModifiers: "",
    displayParts: [textPart(name)],
    documentation: emptyArray,
    tags: void 0,
    codeActions: void 0
  };
}
function getJSDocParameterNameCompletions(tag) {
  if (!isIdentifier(tag.name)) {
    return emptyArray;
  }
  const nameThusFar = tag.name.text;
  const jsdoc = tag.parent;
  const fn = jsdoc.parent;
  if (!isFunctionLike(fn)) return [];
  return mapDefined(fn.parameters, (param) => {
    if (!isIdentifier(param.name)) return void 0;
    const name = param.name.text;
    if (jsdoc.tags.some((t) => t !== tag && isJSDocParameterTag(t) && isIdentifier(t.name) && t.name.escapedText === name) || nameThusFar !== void 0 && !startsWith(name, nameThusFar)) {
      return void 0;
    }
    return { name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: ts_Completions_exports.SortText.LocationPriority };
  });
}
function getJSDocParameterNameCompletionDetails(name) {
  return {
    name,
    kind: "parameter" /* parameterElement */,
    kindModifiers: "",
    displayParts: [textPart(name)],
    documentation: emptyArray,
    tags: void 0,
    codeActions: void 0
  };
}
function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) {
  const tokenAtPos = getTokenAtPosition(sourceFile, position);
  const existingDocComment = findAncestor(tokenAtPos, isJSDoc);
  if (existingDocComment && (existingDocComment.comment !== void 0 || length(existingDocComment.tags))) {
    return void 0;
  }
  const tokenStart = tokenAtPos.getStart(sourceFile);
  if (!existingDocComment && tokenStart < position) {
    return void 0;
  }
  const commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options);
  if (!commentOwnerInfo) {
    return void 0;
  }
  const { commentOwner, parameters, hasReturn: hasReturn2 } = commentOwnerInfo;
  const commentOwnerJsDoc = hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? commentOwner.jsDoc : void 0;
  const lastJsDoc = lastOrUndefined(commentOwnerJsDoc);
  if (commentOwner.getStart(sourceFile) < position || lastJsDoc && existingDocComment && lastJsDoc !== existingDocComment) {
    return void 0;
  }
  const indentationStr = getIndentationStringAtPosition(sourceFile, position);
  const isJavaScriptFile = hasJSFileExtension(sourceFile.fileName);
  const tags = (parameters ? parameterDocComments(parameters || [], isJavaScriptFile, indentationStr, newLine) : "") + (hasReturn2 ? returnsDocComment(indentationStr, newLine) : "");
  const openComment = "/**";
  const closeComment = " */";
  const hasTag = length(getJSDocTags(commentOwner)) > 0;
  if (tags && !hasTag) {
    const preamble = openComment + newLine + indentationStr + " * ";
    const endLine = tokenStart === position ? newLine + indentationStr : "";
    const result = preamble + newLine + tags + indentationStr + closeComment + endLine;
    return { newText: result, caretOffset: preamble.length };
  }
  return { newText: openComment + closeComment, caretOffset: 3 };
}
function getIndentationStringAtPosition(sourceFile, position) {
  const { text } = sourceFile;
  const lineStart = getLineStartPositionForPosition(position, sourceFile);
  let pos = lineStart;
  for (; pos <= position && isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) ;
  return text.slice(lineStart, pos);
}
function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) {
  return parameters.map(({ name, dotDotDotToken }, i) => {
    const paramName = name.kind === 80 /* Identifier */ ? name.text : "param" + i;
    const type = isJavaScriptFile ? dotDotDotToken ? "{...any} " : "{any} " : "";
    return `${indentationStr} * @param ${type}${paramName}${newLine}`;
  }).join("");
}
function returnsDocComment(indentationStr, newLine) {
  return `${indentationStr} * @returns${newLine}`;
}
function getCommentOwnerInfo(tokenAtPos, options) {
  return forEachAncestor(tokenAtPos, (n) => getCommentOwnerInfoWorker(n, options));
}
function getCommentOwnerInfoWorker(commentOwner, options) {
  switch (commentOwner.kind) {
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
    case 174 /* MethodDeclaration */:
    case 176 /* Constructor */:
    case 173 /* MethodSignature */:
    case 219 /* ArrowFunction */:
      const host = commentOwner;
      return { commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) };
    case 303 /* PropertyAssignment */:
      return getCommentOwnerInfoWorker(commentOwner.initializer, options);
    case 263 /* ClassDeclaration */:
    case 264 /* InterfaceDeclaration */:
    case 266 /* EnumDeclaration */:
    case 306 /* EnumMember */:
    case 265 /* TypeAliasDeclaration */:
      return { commentOwner };
    case 171 /* PropertySignature */: {
      const host2 = commentOwner;
      return host2.type && isFunctionTypeNode(host2.type) ? { commentOwner, parameters: host2.type.parameters, hasReturn: hasReturn(host2.type, options) } : { commentOwner };
    }
    case 243 /* VariableStatement */: {
      const varStatement = commentOwner;
      const varDeclarations = varStatement.declarationList.declarations;
      const host2 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : void 0;
      return host2 ? { commentOwner, parameters: host2.parameters, hasReturn: hasReturn(host2, options) } : { commentOwner };
    }
    case 307 /* SourceFile */:
      return "quit";
    case 267 /* ModuleDeclaration */:
      return commentOwner.parent.kind === 267 /* ModuleDeclaration */ ? void 0 : { commentOwner };
    case 244 /* ExpressionStatement */:
      return getCommentOwnerInfoWorker(commentOwner.expression, options);
    case 226 /* BinaryExpression */: {
      const be = commentOwner;
      if (getAssignmentDeclarationKind(be) === 0 /* None */) {
        return "quit";
      }
      return isFunctionLike(be.right) ? { commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner };
    }
    case 172 /* PropertyDeclaration */:
      const init = commentOwner.initializer;
      if (init && (isFunctionExpression(init) || isArrowFunction(init))) {
        return { commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) };
      }
  }
}
function hasReturn(node, options) {
  return !!(options == null ? void 0 : options.generateReturnInDocTemplate) && (isFunctionTypeNode(node) || isArrowFunction(node) && isExpression(node.body) || isFunctionLikeDeclaration(node) && node.body && isBlock(node.body) && !!forEachReturnStatement(node.body, (n) => n));
}
function getRightHandSideOfAssignment(rightHandSide) {
  while (rightHandSide.kind === 217 /* ParenthesizedExpression */) {
    rightHandSide = rightHandSide.expression;
  }
  switch (rightHandSide.kind) {
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
      return rightHandSide;
    case 231 /* ClassExpression */:
      return find(rightHandSide.members, isConstructorDeclaration);
  }
}

// src/services/_namespaces/ts.MapCode.ts
var ts_MapCode_exports = {};
__export(ts_MapCode_exports, {
  mapCode: () => mapCode
});

// src/services/mapCode.ts
function mapCode(sourceFile, contents, focusLocations, host, formatContext, preferences) {
  return ts_textChanges_exports.ChangeTracker.with(
    { host, formatContext, preferences },
    (changeTracker) => {
      const parsed = contents.map((c) => parse(sourceFile, c));
      const flattenedLocations = focusLocations && flatten(focusLocations);
      for (const nodes of parsed) {
        placeNodeGroup(
          sourceFile,
          changeTracker,
          nodes,
          flattenedLocations
        );
      }
    }
  );
}
function parse(sourceFile, content) {
  const nodeKinds = [
    {
      parse: () => createSourceFile(
        "__mapcode_content_nodes.ts",
        content,
        sourceFile.languageVersion,
        /*setParentNodes*/
        true,
        sourceFile.scriptKind
      ),
      body: (sf) => sf.statements
    },
    {
      parse: () => createSourceFile(
        "__mapcode_class_content_nodes.ts",
        `class __class {
${content}
}`,
        sourceFile.languageVersion,
        /*setParentNodes*/
        true,
        sourceFile.scriptKind
      ),
      body: (cw) => cw.statements[0].members
    }
  ];
  const parsedNodes = [];
  for (const { parse: parse2, body: body2 } of nodeKinds) {
    const sourceFile2 = parse2();
    const bod = body2(sourceFile2);
    if (bod.length && sourceFile2.parseDiagnostics.length === 0) {
      return bod;
    } else if (bod.length) {
      parsedNodes.push({ sourceFile: sourceFile2, body: bod });
    }
  }
  parsedNodes.sort(
    (a, b) => a.sourceFile.parseDiagnostics.length - b.sourceFile.parseDiagnostics.length
  );
  const { body } = parsedNodes[0];
  return body;
}
function placeNodeGroup(originalFile, changeTracker, changes, focusLocations) {
  if (isClassElement(changes[0]) || isTypeElement(changes[0])) {
    placeClassNodeGroup(
      originalFile,
      changeTracker,
      changes,
      focusLocations
    );
  } else {
    placeStatements(
      originalFile,
      changeTracker,
      changes,
      focusLocations
    );
  }
}
function placeClassNodeGroup(originalFile, changeTracker, changes, focusLocations) {
  let classOrInterface;
  if (!focusLocations || !focusLocations.length) {
    classOrInterface = find(originalFile.statements, or(isClassLike, isInterfaceDeclaration));
  } else {
    classOrInterface = forEach(focusLocations, (location) => findAncestor(
      getTokenAtPosition(originalFile, location.start),
      or(isClassLike, isInterfaceDeclaration)
    ));
  }
  if (!classOrInterface) {
    return;
  }
  const firstMatch = classOrInterface.members.find((member) => changes.some((change) => matchNode(change, member)));
  if (firstMatch) {
    const lastMatch = findLast(
      classOrInterface.members,
      (member) => changes.some((change) => matchNode(change, member))
    );
    forEach(changes, wipeNode);
    changeTracker.replaceNodeRangeWithNodes(
      originalFile,
      firstMatch,
      lastMatch,
      changes
    );
    return;
  }
  forEach(changes, wipeNode);
  changeTracker.insertNodesAfter(
    originalFile,
    classOrInterface.members[classOrInterface.members.length - 1],
    changes
  );
}
function placeStatements(originalFile, changeTracker, changes, focusLocations) {
  if (!(focusLocations == null ? void 0 : focusLocations.length)) {
    changeTracker.insertNodesAtEndOfFile(
      originalFile,
      changes,
      /*blankLineBetween*/
      false
    );
    return;
  }
  for (const location of focusLocations) {
    const scope = findAncestor(
      getTokenAtPosition(originalFile, location.start),
      (block) => or(isBlock, isSourceFile)(block) && some(block.statements, (origStmt) => changes.some((newStmt) => matchNode(newStmt, origStmt)))
    );
    if (scope) {
      const start = scope.statements.find((stmt) => changes.some((node) => matchNode(node, stmt)));
      if (start) {
        const end = findLast(scope.statements, (stmt) => changes.some((node) => matchNode(node, stmt)));
        forEach(changes, wipeNode);
        changeTracker.replaceNodeRangeWithNodes(
          originalFile,
          start,
          end,
          changes
        );
        return;
      }
    }
  }
  let scopeStatements = originalFile.statements;
  for (const location of focusLocations) {
    const block = findAncestor(
      getTokenAtPosition(originalFile, location.start),
      isBlock
    );
    if (block) {
      scopeStatements = block.statements;
      break;
    }
  }
  forEach(changes, wipeNode);
  changeTracker.insertNodesAfter(
    originalFile,
    scopeStatements[scopeStatements.length - 1],
    changes
  );
}
function matchNode(a, b) {
  var _a, _b, _c, _d, _e, _f;
  if (a.kind !== b.kind) {
    return false;
  }
  if (a.kind === 176 /* Constructor */) {
    return a.kind === b.kind;
  }
  if (isNamedDeclaration(a) && isNamedDeclaration(b)) {
    return a.name.getText() === b.name.getText();
  }
  if (isIfStatement(a) && isIfStatement(b)) {
    return a.expression.getText() === b.expression.getText();
  }
  if (isWhileStatement(a) && isWhileStatement(b)) {
    return a.expression.getText() === b.expression.getText();
  }
  if (isForStatement(a) && isForStatement(b)) {
    return ((_a = a.initializer) == null ? void 0 : _a.getText()) === ((_b = b.initializer) == null ? void 0 : _b.getText()) && ((_c = a.incrementor) == null ? void 0 : _c.getText()) === ((_d = b.incrementor) == null ? void 0 : _d.getText()) && ((_e = a.condition) == null ? void 0 : _e.getText()) === ((_f = b.condition) == null ? void 0 : _f.getText());
  }
  if (isForInOrOfStatement(a) && isForInOrOfStatement(b)) {
    return a.expression.getText() === b.expression.getText() && a.initializer.getText() === b.initializer.getText();
  }
  if (isLabeledStatement(a) && isLabeledStatement(b)) {
    return a.label.getText() === b.label.getText();
  }
  if (a.getText() === b.getText()) {
    return true;
  }
  return false;
}
function wipeNode(node) {
  resetNodePositions(node);
  node.parent = void 0;
}
function resetNodePositions(node) {
  node.pos = -1;
  node.end = -1;
  node.forEachChild(resetNodePositions);
}

// src/services/_namespaces/ts.OrganizeImports.ts
var ts_OrganizeImports_exports = {};
__export(ts_OrganizeImports_exports, {
  compareImportsOrRequireStatements: () => compareImportsOrRequireStatements,
  compareModuleSpecifiers: () => compareModuleSpecifiers2,
  getImportDeclarationInsertionIndex: () => getImportDeclarationInsertionIndex,
  getImportSpecifierInsertionIndex: () => getImportSpecifierInsertionIndex,
  getNamedImportSpecifierComparerWithDetection: () => getNamedImportSpecifierComparerWithDetection,
  getOrganizeImportsStringComparerWithDetection: () => getOrganizeImportsStringComparerWithDetection,
  organizeImports: () => organizeImports,
  testCoalesceExports: () => testCoalesceExports,
  testCoalesceImports: () => testCoalesceImports
});

// src/services/organizeImports.ts
function organizeImports(sourceFile, formatContext, host, program, preferences, mode) {
  const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext({ host, formatContext, preferences });
  const shouldSort = mode === "SortAndCombine" /* SortAndCombine */ || mode === "All" /* All */;
  const shouldCombine = shouldSort;
  const shouldRemove = mode === "RemoveUnused" /* RemoveUnused */ || mode === "All" /* All */;
  const topLevelImportDecls = sourceFile.statements.filter(isImportDeclaration);
  const topLevelImportGroupDecls = groupByNewlineContiguous(sourceFile, topLevelImportDecls);
  const { comparersToTest, typeOrdersToTest } = getDetectionLists(preferences);
  const defaultComparer = comparersToTest[0];
  const comparer = {
    moduleSpecifierComparer: typeof preferences.organizeImportsIgnoreCase === "boolean" ? defaultComparer : void 0,
    namedImportComparer: typeof preferences.organizeImportsIgnoreCase === "boolean" ? defaultComparer : void 0,
    typeOrder: preferences.organizeImportsTypeOrder
  };
  if (typeof preferences.organizeImportsIgnoreCase !== "boolean") {
    ({ comparer: comparer.moduleSpecifierComparer } = detectModuleSpecifierCaseBySort(topLevelImportGroupDecls, comparersToTest));
  }
  if (!comparer.typeOrder || typeof preferences.organizeImportsIgnoreCase !== "boolean") {
    const namedImportSort = detectNamedImportOrganizationBySort(topLevelImportDecls, comparersToTest, typeOrdersToTest);
    if (namedImportSort) {
      const { namedImportComparer, typeOrder } = namedImportSort;
      comparer.namedImportComparer = comparer.namedImportComparer ?? namedImportComparer;
      comparer.typeOrder = comparer.typeOrder ?? typeOrder;
    }
  }
  topLevelImportGroupDecls.forEach((importGroupDecl) => organizeImportsWorker(importGroupDecl, comparer));
  if (mode !== "RemoveUnused" /* RemoveUnused */) {
    getTopLevelExportGroups(sourceFile).forEach((exportGroupDecl) => organizeExportsWorker(exportGroupDecl, comparer.namedImportComparer));
  }
  for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) {
    if (!ambientModule.body) continue;
    const ambientModuleImportGroupDecls = groupByNewlineContiguous(sourceFile, ambientModule.body.statements.filter(isImportDeclaration));
    ambientModuleImportGroupDecls.forEach((importGroupDecl) => organizeImportsWorker(importGroupDecl, comparer));
    if (mode !== "RemoveUnused" /* RemoveUnused */) {
      const ambientModuleExportDecls = ambientModule.body.statements.filter(isExportDeclaration);
      organizeExportsWorker(ambientModuleExportDecls, comparer.namedImportComparer);
    }
  }
  return changeTracker.getChanges();
  function organizeDeclsWorker(oldImportDecls, coalesce) {
    if (length(oldImportDecls) === 0) {
      return;
    }
    setEmitFlags(oldImportDecls[0], 1024 /* NoLeadingComments */);
    const oldImportGroups = shouldCombine ? group(oldImportDecls, (importDecl) => getExternalModuleName2(importDecl.moduleSpecifier)) : [oldImportDecls];
    const sortedImportGroups = shouldSort ? toSorted(oldImportGroups, (group1, group2) => compareModuleSpecifiersWorker(group1[0].moduleSpecifier, group2[0].moduleSpecifier, comparer.moduleSpecifierComparer ?? defaultComparer)) : oldImportGroups;
    const newImportDecls = flatMap(sortedImportGroups, (importGroup) => getExternalModuleName2(importGroup[0].moduleSpecifier) || importGroup[0].moduleSpecifier === void 0 ? coalesce(importGroup) : importGroup);
    if (newImportDecls.length === 0) {
      changeTracker.deleteNodes(
        sourceFile,
        oldImportDecls,
        {
          leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude,
          trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include
        },
        /*hasTrailingComment*/
        true
      );
    } else {
      const replaceOptions = {
        leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude,
        // Leave header comment in place
        trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include,
        suffix: getNewLineOrDefaultFromHost(host, formatContext.options)
      };
      changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions);
      const hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions);
      changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), {
        trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include
      }, hasTrailingComment);
    }
  }
  function organizeImportsWorker(oldImportDecls, comparer2) {
    const detectedModuleCaseComparer = comparer2.moduleSpecifierComparer ?? defaultComparer;
    const detectedNamedImportCaseComparer = comparer2.namedImportComparer ?? defaultComparer;
    const detectedTypeOrder = comparer2.typeOrder ?? "last";
    const specifierComparer = getNamedImportSpecifierComparer({ organizeImportsTypeOrder: detectedTypeOrder }, detectedNamedImportCaseComparer);
    const processImportsOfSameModuleSpecifier = (importGroup) => {
      if (shouldRemove) importGroup = removeUnusedImports(importGroup, sourceFile, program);
      if (shouldCombine) importGroup = coalesceImportsWorker(importGroup, detectedModuleCaseComparer, specifierComparer, sourceFile);
      if (shouldSort) importGroup = toSorted(importGroup, (s1, s2) => compareImportsOrRequireStatements(s1, s2, detectedModuleCaseComparer));
      return importGroup;
    };
    organizeDeclsWorker(oldImportDecls, processImportsOfSameModuleSpecifier);
  }
  function organizeExportsWorker(oldExportDecls, specifierCaseComparer) {
    const useComparer = getNamedImportSpecifierComparer(preferences, specifierCaseComparer);
    organizeDeclsWorker(oldExportDecls, (group2) => coalesceExportsWorker(group2, useComparer));
  }
}
function getDetectionLists(preferences) {
  return {
    comparersToTest: typeof preferences.organizeImportsIgnoreCase === "boolean" ? [getOrganizeImportsStringComparer(preferences, preferences.organizeImportsIgnoreCase)] : [getOrganizeImportsStringComparer(
      preferences,
      /*ignoreCase*/
      true
    ), getOrganizeImportsStringComparer(
      preferences,
      /*ignoreCase*/
      false
    )],
    typeOrdersToTest: preferences.organizeImportsTypeOrder ? [preferences.organizeImportsTypeOrder] : ["last", "inline", "first"]
  };
}
function groupByNewlineContiguous(sourceFile, decls) {
  const scanner2 = createScanner(
    sourceFile.languageVersion,
    /*skipTrivia*/
    false,
    sourceFile.languageVariant
  );
  const group2 = [];
  let groupIndex = 0;
  for (const decl of decls) {
    if (group2[groupIndex] && isNewGroup(sourceFile, decl, scanner2)) {
      groupIndex++;
    }
    if (!group2[groupIndex]) {
      group2[groupIndex] = [];
    }
    group2[groupIndex].push(decl);
  }
  return group2;
}
function isNewGroup(sourceFile, decl, scanner2) {
  const startPos = decl.getFullStart();
  const endPos = decl.getStart();
  scanner2.setText(sourceFile.text, startPos, endPos - startPos);
  let numberOfNewLines = 0;
  while (scanner2.getTokenStart() < endPos) {
    const tokenKind = scanner2.scan();
    if (tokenKind === 4 /* NewLineTrivia */) {
      numberOfNewLines++;
      if (numberOfNewLines >= 2) {
        return true;
      }
    }
  }
  return false;
}
function getTopLevelExportGroups(sourceFile) {
  const topLevelExportGroups = [];
  const statements = sourceFile.statements;
  const len = length(statements);
  let i = 0;
  let groupIndex = 0;
  while (i < len) {
    if (isExportDeclaration(statements[i])) {
      if (topLevelExportGroups[groupIndex] === void 0) {
        topLevelExportGroups[groupIndex] = [];
      }
      const exportDecl = statements[i];
      if (exportDecl.moduleSpecifier) {
        topLevelExportGroups[groupIndex].push(exportDecl);
        i++;
      } else {
        while (i < len && isExportDeclaration(statements[i])) {
          topLevelExportGroups[groupIndex].push(statements[i++]);
        }
        groupIndex++;
      }
    } else {
      i++;
    }
  }
  return flatMap(topLevelExportGroups, (exportGroupDecls) => groupByNewlineContiguous(sourceFile, exportGroupDecls));
}
function removeUnusedImports(oldImports, sourceFile, program) {
  const typeChecker = program.getTypeChecker();
  const compilerOptions = program.getCompilerOptions();
  const jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
  const jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile);
  const jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
  const usedImports = [];
  for (const importDecl of oldImports) {
    const { importClause, moduleSpecifier } = importDecl;
    if (!importClause) {
      usedImports.push(importDecl);
      continue;
    }
    let { name, namedBindings } = importClause;
    if (name && !isDeclarationUsed(name)) {
      name = void 0;
    }
    if (namedBindings) {
      if (isNamespaceImport(namedBindings)) {
        if (!isDeclarationUsed(namedBindings.name)) {
          namedBindings = void 0;
        }
      } else {
        const newElements = namedBindings.elements.filter((e) => isDeclarationUsed(e.name));
        if (newElements.length < namedBindings.elements.length) {
          namedBindings = newElements.length ? factory.updateNamedImports(namedBindings, newElements) : void 0;
        }
      }
    }
    if (name || namedBindings) {
      usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
    } else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) {
      if (sourceFile.isDeclarationFile) {
        usedImports.push(factory.createImportDeclaration(
          importDecl.modifiers,
          /*importClause*/
          void 0,
          moduleSpecifier,
          /*attributes*/
          void 0
        ));
      } else {
        usedImports.push(importDecl);
      }
    }
  }
  return usedImports;
  function isDeclarationUsed(identifier) {
    return jsxElementsPresent && (identifier.text === jsxNamespace || jsxFragmentFactory && identifier.text === jsxFragmentFactory) && jsxModeNeedsExplicitImport(compilerOptions.jsx) || ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
  }
}
function getExternalModuleName2(specifier) {
  return specifier !== void 0 && isStringLiteralLike(specifier) ? specifier.text : void 0;
}
function getCategorizedImports(importGroup) {
  let importWithoutClause;
  const typeOnlyImports = { defaultImports: [], namespaceImports: [], namedImports: [] };
  const regularImports = { defaultImports: [], namespaceImports: [], namedImports: [] };
  for (const importDeclaration of importGroup) {
    if (importDeclaration.importClause === void 0) {
      importWithoutClause = importWithoutClause || importDeclaration;
      continue;
    }
    const group2 = importDeclaration.importClause.isTypeOnly ? typeOnlyImports : regularImports;
    const { name, namedBindings } = importDeclaration.importClause;
    if (name) {
      group2.defaultImports.push(importDeclaration);
    }
    if (namedBindings) {
      if (isNamespaceImport(namedBindings)) {
        group2.namespaceImports.push(importDeclaration);
      } else {
        group2.namedImports.push(importDeclaration);
      }
    }
  }
  return {
    importWithoutClause,
    typeOnlyImports,
    regularImports
  };
}
function coalesceImportsWorker(importGroup, comparer, specifierComparer, sourceFile) {
  if (importGroup.length === 0) {
    return importGroup;
  }
  const importGroupsByAttributes = groupBy(importGroup, (decl) => {
    if (decl.attributes) {
      let attrs = decl.attributes.token + " ";
      for (const x of toSorted(decl.attributes.elements, (x2, y) => compareStringsCaseSensitive(x2.name.text, y.name.text))) {
        attrs += x.name.text + ":";
        attrs += isStringLiteralLike(x.value) ? `"${x.value.text}"` : x.value.getText() + " ";
      }
      return attrs;
    }
    return "";
  });
  const coalescedImports = [];
  for (const attribute in importGroupsByAttributes) {
    const importGroupSameAttrs = importGroupsByAttributes[attribute];
    const { importWithoutClause, typeOnlyImports, regularImports } = getCategorizedImports(importGroupSameAttrs);
    if (importWithoutClause) {
      coalescedImports.push(importWithoutClause);
    }
    for (const group2 of [regularImports, typeOnlyImports]) {
      const isTypeOnly = group2 === typeOnlyImports;
      const { defaultImports, namespaceImports, namedImports } = group2;
      if (!isTypeOnly && defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) {
        const defaultImport = defaultImports[0];
        coalescedImports.push(
          updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)
        );
        continue;
      }
      const sortedNamespaceImports = toSorted(namespaceImports, (i1, i2) => comparer(i1.importClause.namedBindings.name.text, i2.importClause.namedBindings.name.text));
      for (const namespaceImport of sortedNamespaceImports) {
        coalescedImports.push(
          updateImportDeclarationAndClause(
            namespaceImport,
            /*name*/
            void 0,
            namespaceImport.importClause.namedBindings
          )
        );
      }
      const firstDefaultImport = firstOrUndefined(defaultImports);
      const firstNamedImport = firstOrUndefined(namedImports);
      const importDecl = firstDefaultImport ?? firstNamedImport;
      if (!importDecl) {
        continue;
      }
      let newDefaultImport;
      const newImportSpecifiers = [];
      if (defaultImports.length === 1) {
        newDefaultImport = defaultImports[0].importClause.name;
      } else {
        for (const defaultImport of defaultImports) {
          newImportSpecifiers.push(
            factory.createImportSpecifier(
              /*isTypeOnly*/
              false,
              factory.createIdentifier("default"),
              defaultImport.importClause.name
            )
          );
        }
      }
      newImportSpecifiers.push(...getNewImportSpecifiers(namedImports));
      const sortedImportSpecifiers = factory.createNodeArray(
        toSorted(newImportSpecifiers, specifierComparer),
        firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings.elements.hasTrailingComma
      );
      const newNamedImports = sortedImportSpecifiers.length === 0 ? newDefaultImport ? void 0 : factory.createNamedImports(emptyArray) : firstNamedImport ? factory.updateNamedImports(firstNamedImport.importClause.namedBindings, sortedImportSpecifiers) : factory.createNamedImports(sortedImportSpecifiers);
      if (sourceFile && newNamedImports && (firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings) && !rangeIsOnSingleLine(firstNamedImport.importClause.namedBindings, sourceFile)) {
        setEmitFlags(newNamedImports, 2 /* MultiLine */);
      }
      if (isTypeOnly && newDefaultImport && newNamedImports) {
        coalescedImports.push(
          updateImportDeclarationAndClause(
            importDecl,
            newDefaultImport,
            /*namedBindings*/
            void 0
          )
        );
        coalescedImports.push(
          updateImportDeclarationAndClause(
            firstNamedImport ?? importDecl,
            /*name*/
            void 0,
            newNamedImports
          )
        );
      } else {
        coalescedImports.push(
          updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)
        );
      }
    }
  }
  return coalescedImports;
}
function coalesceExportsWorker(exportGroup, specifierComparer) {
  if (exportGroup.length === 0) {
    return exportGroup;
  }
  const { exportWithoutClause, namedExports, typeOnlyExports } = getCategorizedExports(exportGroup);
  const coalescedExports = [];
  if (exportWithoutClause) {
    coalescedExports.push(exportWithoutClause);
  }
  for (const exportGroup2 of [namedExports, typeOnlyExports]) {
    if (exportGroup2.length === 0) {
      continue;
    }
    const newExportSpecifiers = [];
    newExportSpecifiers.push(...flatMap(exportGroup2, (i) => i.exportClause && isNamedExports(i.exportClause) ? i.exportClause.elements : emptyArray));
    const sortedExportSpecifiers = toSorted(newExportSpecifiers, specifierComparer);
    const exportDecl = exportGroup2[0];
    coalescedExports.push(
      factory.updateExportDeclaration(
        exportDecl,
        exportDecl.modifiers,
        exportDecl.isTypeOnly,
        exportDecl.exportClause && (isNamedExports(exportDecl.exportClause) ? factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)),
        exportDecl.moduleSpecifier,
        exportDecl.attributes
      )
    );
  }
  return coalescedExports;
  function getCategorizedExports(exportGroup2) {
    let exportWithoutClause2;
    const namedExports2 = [];
    const typeOnlyExports2 = [];
    for (const exportDeclaration of exportGroup2) {
      if (exportDeclaration.exportClause === void 0) {
        exportWithoutClause2 = exportWithoutClause2 || exportDeclaration;
      } else if (exportDeclaration.isTypeOnly) {
        typeOnlyExports2.push(exportDeclaration);
      } else {
        namedExports2.push(exportDeclaration);
      }
    }
    return {
      exportWithoutClause: exportWithoutClause2,
      namedExports: namedExports2,
      typeOnlyExports: typeOnlyExports2
    };
  }
}
function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
  return factory.updateImportDeclaration(
    importDeclaration,
    importDeclaration.modifiers,
    factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings),
    // TODO: GH#18217
    importDeclaration.moduleSpecifier,
    importDeclaration.attributes
  );
}
function compareImportOrExportSpecifiers(s1, s2, comparer, preferences) {
  switch (preferences == null ? void 0 : preferences.organizeImportsTypeOrder) {
    case "first":
      return compareBooleans(s2.isTypeOnly, s1.isTypeOnly) || comparer(s1.name.text, s2.name.text);
    case "inline":
      return comparer(s1.name.text, s2.name.text);
    default:
      return compareBooleans(s1.isTypeOnly, s2.isTypeOnly) || comparer(s1.name.text, s2.name.text);
  }
}
function compareModuleSpecifiersWorker(m1, m2, comparer) {
  const name1 = m1 === void 0 ? void 0 : getExternalModuleName2(m1);
  const name2 = m2 === void 0 ? void 0 : getExternalModuleName2(m2);
  return compareBooleans(name1 === void 0, name2 === void 0) || compareBooleans(isExternalModuleNameRelative(name1), isExternalModuleNameRelative(name2)) || comparer(name1, name2);
}
function getModuleNamesFromDecls(decls) {
  return decls.map((s) => getExternalModuleName2(getModuleSpecifierExpression(s)) || "");
}
function getModuleSpecifierExpression(declaration) {
  var _a;
  switch (declaration.kind) {
    case 271 /* ImportEqualsDeclaration */:
      return (_a = tryCast(declaration.moduleReference, isExternalModuleReference)) == null ? void 0 : _a.expression;
    case 272 /* ImportDeclaration */:
      return declaration.moduleSpecifier;
    case 243 /* VariableStatement */:
      return declaration.declarationList.declarations[0].initializer.arguments[0];
  }
}
function hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier) {
  const moduleSpecifierText = isStringLiteral(moduleSpecifier) && moduleSpecifier.text;
  return isString(moduleSpecifierText) && some(sourceFile.moduleAugmentations, (moduleName) => isStringLiteral(moduleName) && moduleName.text === moduleSpecifierText);
}
function getNewImportSpecifiers(namedImports) {
  return flatMap(namedImports, (namedImport) => map(tryGetNamedBindingElements(namedImport), (importSpecifier) => importSpecifier.name && importSpecifier.propertyName && moduleExportNameTextEscaped(importSpecifier.name) === moduleExportNameTextEscaped(importSpecifier.propertyName) ? factory.updateImportSpecifier(
    importSpecifier,
    importSpecifier.isTypeOnly,
    /*propertyName*/
    void 0,
    importSpecifier.name
  ) : importSpecifier));
}
function tryGetNamedBindingElements(namedImport) {
  var _a;
  return ((_a = namedImport.importClause) == null ? void 0 : _a.namedBindings) && isNamedImports(namedImport.importClause.namedBindings) ? namedImport.importClause.namedBindings.elements : void 0;
}
function detectModuleSpecifierCaseBySort(importDeclsByGroup, comparersToTest) {
  const moduleSpecifiersByGroup = [];
  importDeclsByGroup.forEach((importGroup) => {
    moduleSpecifiersByGroup.push(getModuleNamesFromDecls(importGroup));
  });
  return detectCaseSensitivityBySort(moduleSpecifiersByGroup, comparersToTest);
}
function detectNamedImportOrganizationBySort(originalGroups, comparersToTest, typesToTest) {
  let bothNamedImports = false;
  const importDeclsWithNamed = originalGroups.filter((i) => {
    var _a, _b;
    const namedImports = (_b = tryCast((_a = i.importClause) == null ? void 0 : _a.namedBindings, isNamedImports)) == null ? void 0 : _b.elements;
    if (!(namedImports == null ? void 0 : namedImports.length)) return false;
    if (!bothNamedImports && namedImports.some((n) => n.isTypeOnly) && namedImports.some((n) => !n.isTypeOnly)) {
      bothNamedImports = true;
    }
    return true;
  });
  if (importDeclsWithNamed.length === 0) return;
  const namedImportsByDecl = importDeclsWithNamed.map((importDecl) => {
    var _a, _b;
    return (_b = tryCast((_a = importDecl.importClause) == null ? void 0 : _a.namedBindings, isNamedImports)) == null ? void 0 : _b.elements;
  }).filter((elements) => elements !== void 0);
  if (!bothNamedImports || typesToTest.length === 0) {
    const sortState = detectCaseSensitivityBySort(namedImportsByDecl.map((i) => i.map((n) => n.name.text)), comparersToTest);
    return {
      namedImportComparer: sortState.comparer,
      typeOrder: typesToTest.length === 1 ? typesToTest[0] : void 0,
      isSorted: sortState.isSorted
    };
  }
  const bestDiff = { first: Infinity, last: Infinity, inline: Infinity };
  const bestComparer = { first: comparersToTest[0], last: comparersToTest[0], inline: comparersToTest[0] };
  for (const curComparer of comparersToTest) {
    const currDiff = { first: 0, last: 0, inline: 0 };
    for (const importDecl of namedImportsByDecl) {
      for (const typeOrder of typesToTest) {
        currDiff[typeOrder] = (currDiff[typeOrder] ?? 0) + measureSortedness(importDecl, (n1, n2) => compareImportOrExportSpecifiers(n1, n2, curComparer, { organizeImportsTypeOrder: typeOrder }));
      }
    }
    for (const key of typesToTest) {
      const typeOrder = key;
      if (currDiff[typeOrder] < bestDiff[typeOrder]) {
        bestDiff[typeOrder] = currDiff[typeOrder];
        bestComparer[typeOrder] = curComparer;
      }
    }
  }
  outer: for (const bestKey of typesToTest) {
    const bestTypeOrder = bestKey;
    for (const testKey of typesToTest) {
      const testTypeOrder = testKey;
      if (bestDiff[testTypeOrder] < bestDiff[bestTypeOrder]) continue outer;
    }
    return { namedImportComparer: bestComparer[bestTypeOrder], typeOrder: bestTypeOrder, isSorted: bestDiff[bestTypeOrder] === 0 };
  }
  return { namedImportComparer: bestComparer.last, typeOrder: "last", isSorted: bestDiff.last === 0 };
}
function measureSortedness(arr, comparer) {
  let i = 0;
  for (let j = 0; j < arr.length - 1; j++) {
    if (comparer(arr[j], arr[j + 1]) > 0) {
      i++;
    }
  }
  return i;
}
function detectCaseSensitivityBySort(originalGroups, comparersToTest) {
  let bestComparer;
  let bestDiff = Infinity;
  for (const curComparer of comparersToTest) {
    let diffOfCurrentComparer = 0;
    for (const listToSort of originalGroups) {
      if (listToSort.length <= 1) continue;
      const diff = measureSortedness(listToSort, curComparer);
      diffOfCurrentComparer += diff;
    }
    if (diffOfCurrentComparer < bestDiff) {
      bestDiff = diffOfCurrentComparer;
      bestComparer = curComparer;
    }
  }
  return {
    comparer: bestComparer ?? comparersToTest[0],
    isSorted: bestDiff === 0
  };
}
function compareImportKind(s1, s2) {
  return compareValues(getImportKindOrder(s1), getImportKindOrder(s2));
}
function getImportKindOrder(s1) {
  var _a;
  switch (s1.kind) {
    case 272 /* ImportDeclaration */:
      if (!s1.importClause) return 0;
      if (s1.importClause.isTypeOnly) return 1;
      if (((_a = s1.importClause.namedBindings) == null ? void 0 : _a.kind) === 274 /* NamespaceImport */) return 2;
      if (s1.importClause.name) return 3;
      return 4;
    case 271 /* ImportEqualsDeclaration */:
      return 5;
    case 243 /* VariableStatement */:
      return 6;
  }
}
function getOrganizeImportsOrdinalStringComparer(ignoreCase) {
  return ignoreCase ? compareStringsCaseInsensitiveEslintCompatible : compareStringsCaseSensitive;
}
function getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) {
  const resolvedLocale = getOrganizeImportsLocale(preferences);
  const caseFirst = preferences.organizeImportsCaseFirst ?? false;
  const numeric = preferences.organizeImportsNumericCollation ?? false;
  const accents = preferences.organizeImportsAccentCollation ?? true;
  const sensitivity = ignoreCase ? accents ? "accent" : "base" : accents ? "variant" : "case";
  const collator = new Intl.Collator(resolvedLocale, {
    usage: "sort",
    caseFirst: caseFirst || "false",
    sensitivity,
    numeric
  });
  return collator.compare;
}
function getOrganizeImportsLocale(preferences) {
  let locale = preferences.organizeImportsLocale;
  if (locale === "auto") locale = getUILocale();
  if (locale === void 0) locale = "en";
  const supportedLocales = Intl.Collator.supportedLocalesOf(locale);
  const resolvedLocale = supportedLocales.length ? supportedLocales[0] : "en";
  return resolvedLocale;
}
function getOrganizeImportsStringComparer(preferences, ignoreCase) {
  const collation = preferences.organizeImportsCollation ?? "ordinal";
  return collation === "unicode" ? getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) : getOrganizeImportsOrdinalStringComparer(ignoreCase);
}
function getOrganizeImportsStringComparerWithDetection(originalImportDecls, preferences) {
  return detectModuleSpecifierCaseBySort([originalImportDecls], getDetectionLists(preferences).comparersToTest);
}
function getNamedImportSpecifierComparer(preferences, comparer) {
  const stringComparer = comparer ?? getOrganizeImportsOrdinalStringComparer(!!preferences.organizeImportsIgnoreCase);
  return (s1, s2) => compareImportOrExportSpecifiers(s1, s2, stringComparer, preferences);
}
function getNamedImportSpecifierComparerWithDetection(importDecl, preferences, sourceFile) {
  const { comparersToTest, typeOrdersToTest } = getDetectionLists(preferences);
  const detectFromDecl = detectNamedImportOrganizationBySort([importDecl], comparersToTest, typeOrdersToTest);
  let specifierComparer = getNamedImportSpecifierComparer(preferences, comparersToTest[0]);
  let isSorted;
  if (typeof preferences.organizeImportsIgnoreCase !== "boolean" || !preferences.organizeImportsTypeOrder) {
    if (detectFromDecl) {
      const { namedImportComparer, typeOrder, isSorted: isDetectedSorted } = detectFromDecl;
      isSorted = isDetectedSorted;
      specifierComparer = getNamedImportSpecifierComparer({ organizeImportsTypeOrder: typeOrder }, namedImportComparer);
    } else if (sourceFile) {
      const detectFromFile = detectNamedImportOrganizationBySort(sourceFile.statements.filter(isImportDeclaration), comparersToTest, typeOrdersToTest);
      if (detectFromFile) {
        const { namedImportComparer, typeOrder, isSorted: isDetectedSorted } = detectFromFile;
        isSorted = isDetectedSorted;
        specifierComparer = getNamedImportSpecifierComparer({ organizeImportsTypeOrder: typeOrder }, namedImportComparer);
      }
    }
  }
  return { specifierComparer, isSorted };
}
function getImportDeclarationInsertionIndex(sortedImports, newImport, comparer) {
  const index = binarySearch(sortedImports, newImport, identity, (a, b) => compareImportsOrRequireStatements(a, b, comparer));
  return index < 0 ? ~index : index;
}
function getImportSpecifierInsertionIndex(sortedImports, newImport, comparer) {
  const index = binarySearch(sortedImports, newImport, identity, comparer);
  return index < 0 ? ~index : index;
}
function compareImportsOrRequireStatements(s1, s2, comparer) {
  return compareModuleSpecifiersWorker(getModuleSpecifierExpression(s1), getModuleSpecifierExpression(s2), comparer) || compareImportKind(s1, s2);
}
function testCoalesceImports(importGroup, ignoreCase, sourceFile, preferences) {
  const comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase);
  const specifierComparer = getNamedImportSpecifierComparer({ organizeImportsTypeOrder: preferences == null ? void 0 : preferences.organizeImportsTypeOrder }, comparer);
  return coalesceImportsWorker(importGroup, comparer, specifierComparer, sourceFile);
}
function testCoalesceExports(exportGroup, ignoreCase, preferences) {
  const comparer = (s1, s2) => compareImportOrExportSpecifiers(s1, s2, getOrganizeImportsOrdinalStringComparer(ignoreCase), { organizeImportsTypeOrder: (preferences == null ? void 0 : preferences.organizeImportsTypeOrder) ?? "last" });
  return coalesceExportsWorker(exportGroup, comparer);
}
function compareModuleSpecifiers2(m1, m2, ignoreCase) {
  const comparer = getOrganizeImportsOrdinalStringComparer(!!ignoreCase);
  return compareModuleSpecifiersWorker(m1, m2, comparer);
}

// src/services/_namespaces/ts.OutliningElementsCollector.ts
var ts_OutliningElementsCollector_exports = {};
__export(ts_OutliningElementsCollector_exports, {
  collectElements: () => collectElements
});

// src/services/outliningElementsCollector.ts
function collectElements(sourceFile, cancellationToken) {
  const res = [];
  addNodeOutliningSpans(sourceFile, cancellationToken, res);
  addRegionOutliningSpans(sourceFile, res);
  res.sort((span1, span2) => span1.textSpan.start - span2.textSpan.start);
  return res;
}
function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
  let depthRemaining = 40;
  let current = 0;
  const statements = [...sourceFile.statements, sourceFile.endOfFileToken];
  const n = statements.length;
  while (current < n) {
    while (current < n && !isAnyImportSyntax(statements[current])) {
      visitNode3(statements[current]);
      current++;
    }
    if (current === n) break;
    const firstImport = current;
    while (current < n && isAnyImportSyntax(statements[current])) {
      visitNode3(statements[current]);
      current++;
    }
    const lastImport = current - 1;
    if (lastImport !== firstImport) {
      out.push(createOutliningSpanFromBounds(findChildOfKind(statements[firstImport], 102 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
    }
  }
  function visitNode3(n2) {
    var _a;
    if (depthRemaining === 0) return;
    cancellationToken.throwIfCancellationRequested();
    if (isDeclaration(n2) || isVariableStatement(n2) || isReturnStatement(n2) || isCallOrNewExpression(n2) || n2.kind === 1 /* EndOfFileToken */) {
      addOutliningForLeadingCommentsForNode(n2, sourceFile, cancellationToken, out);
    }
    if (isFunctionLike(n2) && isBinaryExpression(n2.parent) && isPropertyAccessExpression(n2.parent.left)) {
      addOutliningForLeadingCommentsForNode(n2.parent.left, sourceFile, cancellationToken, out);
    }
    if (isBlock(n2) || isModuleBlock(n2)) {
      addOutliningForLeadingCommentsForPos(n2.statements.end, sourceFile, cancellationToken, out);
    }
    if (isClassLike(n2) || isInterfaceDeclaration(n2)) {
      addOutliningForLeadingCommentsForPos(n2.members.end, sourceFile, cancellationToken, out);
    }
    const span = getOutliningSpanForNode(n2, sourceFile);
    if (span) out.push(span);
    depthRemaining--;
    if (isCallExpression(n2)) {
      depthRemaining++;
      visitNode3(n2.expression);
      depthRemaining--;
      n2.arguments.forEach(visitNode3);
      (_a = n2.typeArguments) == null ? void 0 : _a.forEach(visitNode3);
    } else if (isIfStatement(n2) && n2.elseStatement && isIfStatement(n2.elseStatement)) {
      visitNode3(n2.expression);
      visitNode3(n2.thenStatement);
      depthRemaining++;
      visitNode3(n2.elseStatement);
      depthRemaining--;
    } else {
      n2.forEachChild(visitNode3);
    }
    depthRemaining++;
  }
}
function addRegionOutliningSpans(sourceFile, out) {
  const regions = [];
  const lineStarts = sourceFile.getLineStarts();
  for (const currentLineStart of lineStarts) {
    const lineEnd = sourceFile.getLineEndOfPosition(currentLineStart);
    const lineText = sourceFile.text.substring(currentLineStart, lineEnd);
    const result = parseRegionDelimiter(lineText);
    if (!result || isInComment(sourceFile, currentLineStart)) {
      continue;
    }
    if (result.isStart) {
      const span = createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
      regions.push(createOutliningSpan(
        span,
        "region" /* Region */,
        span,
        /*autoCollapse*/
        false,
        result.name || "#region"
      ));
    } else {
      const region = regions.pop();
      if (region) {
        region.textSpan.length = lineEnd - region.textSpan.start;
        region.hintSpan.length = lineEnd - region.textSpan.start;
        out.push(region);
      }
    }
  }
}
var regionDelimiterRegExp = /^#(end)?region(.*)\r?$/;
function parseRegionDelimiter(lineText) {
  lineText = lineText.trimStart();
  if (!startsWith(lineText, "//")) {
    return null;
  }
  lineText = lineText.slice(2).trim();
  const result = regionDelimiterRegExp.exec(lineText);
  if (result) {
    return { isStart: !result[1], name: result[2].trim() };
  }
  return void 0;
}
function addOutliningForLeadingCommentsForPos(pos, sourceFile, cancellationToken, out) {
  const comments = getLeadingCommentRanges(sourceFile.text, pos);
  if (!comments) return;
  let firstSingleLineCommentStart = -1;
  let lastSingleLineCommentEnd = -1;
  let singleLineCommentCount = 0;
  const sourceText = sourceFile.getFullText();
  for (const { kind, pos: pos2, end } of comments) {
    cancellationToken.throwIfCancellationRequested();
    switch (kind) {
      case 2 /* SingleLineCommentTrivia */:
        const commentText = sourceText.slice(pos2, end);
        if (parseRegionDelimiter(commentText)) {
          combineAndAddMultipleSingleLineComments();
          singleLineCommentCount = 0;
          break;
        }
        if (singleLineCommentCount === 0) {
          firstSingleLineCommentStart = pos2;
        }
        lastSingleLineCommentEnd = end;
        singleLineCommentCount++;
        break;
      case 3 /* MultiLineCommentTrivia */:
        combineAndAddMultipleSingleLineComments();
        out.push(createOutliningSpanFromBounds(pos2, end, "comment" /* Comment */));
        singleLineCommentCount = 0;
        break;
      default:
        Debug.assertNever(kind);
    }
  }
  combineAndAddMultipleSingleLineComments();
  function combineAndAddMultipleSingleLineComments() {
    if (singleLineCommentCount > 1) {
      out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
    }
  }
}
function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) {
  if (isJsxText(n)) return;
  addOutliningForLeadingCommentsForPos(n.pos, sourceFile, cancellationToken, out);
}
function createOutliningSpanFromBounds(pos, end, kind) {
  return createOutliningSpan(createTextSpanFromBounds(pos, end), kind);
}
function getOutliningSpanForNode(n, sourceFile) {
  switch (n.kind) {
    case 241 /* Block */:
      if (isFunctionLike(n.parent)) {
        return functionSpan(n.parent, n, sourceFile);
      }
      switch (n.parent.kind) {
        case 246 /* DoStatement */:
        case 249 /* ForInStatement */:
        case 250 /* ForOfStatement */:
        case 248 /* ForStatement */:
        case 245 /* IfStatement */:
        case 247 /* WhileStatement */:
        case 254 /* WithStatement */:
        case 299 /* CatchClause */:
          return spanForNode(n.parent);
        case 258 /* TryStatement */:
          const tryStatement = n.parent;
          if (tryStatement.tryBlock === n) {
            return spanForNode(n.parent);
          } else if (tryStatement.finallyBlock === n) {
            const node = findChildOfKind(tryStatement, 98 /* FinallyKeyword */, sourceFile);
            if (node) return spanForNode(node);
          }
        // falls through
        default:
          return createOutliningSpan(createTextSpanFromNode(n, sourceFile), "code" /* Code */);
      }
    case 268 /* ModuleBlock */:
      return spanForNode(n.parent);
    case 263 /* ClassDeclaration */:
    case 231 /* ClassExpression */:
    case 264 /* InterfaceDeclaration */:
    case 266 /* EnumDeclaration */:
    case 269 /* CaseBlock */:
    case 187 /* TypeLiteral */:
    case 206 /* ObjectBindingPattern */:
      return spanForNode(n);
    case 189 /* TupleType */:
      return spanForNode(
        n,
        /*autoCollapse*/
        false,
        /*useFullStart*/
        !isTupleTypeNode(n.parent),
        23 /* OpenBracketToken */
      );
    case 296 /* CaseClause */:
    case 297 /* DefaultClause */:
      return spanForNodeArray(n.statements);
    case 210 /* ObjectLiteralExpression */:
      return spanForObjectOrArrayLiteral(n);
    case 209 /* ArrayLiteralExpression */:
      return spanForObjectOrArrayLiteral(n, 23 /* OpenBracketToken */);
    case 284 /* JsxElement */:
      return spanForJSXElement(n);
    case 288 /* JsxFragment */:
      return spanForJSXFragment(n);
    case 285 /* JsxSelfClosingElement */:
    case 286 /* JsxOpeningElement */:
      return spanForJSXAttributes(n.attributes);
    case 228 /* TemplateExpression */:
    case 15 /* NoSubstitutionTemplateLiteral */:
      return spanForTemplateLiteral(n);
    case 207 /* ArrayBindingPattern */:
      return spanForNode(
        n,
        /*autoCollapse*/
        false,
        /*useFullStart*/
        !isBindingElement(n.parent),
        23 /* OpenBracketToken */
      );
    case 219 /* ArrowFunction */:
      return spanForArrowFunction(n);
    case 213 /* CallExpression */:
      return spanForCallExpression(n);
    case 217 /* ParenthesizedExpression */:
      return spanForParenthesizedExpression(n);
    case 275 /* NamedImports */:
    case 279 /* NamedExports */:
    case 300 /* ImportAttributes */:
      return spanForImportExportElements(n);
  }
  function spanForImportExportElements(node) {
    if (!node.elements.length) {
      return void 0;
    }
    const openToken = findChildOfKind(node, 19 /* OpenBraceToken */, sourceFile);
    const closeToken = findChildOfKind(node, 20 /* CloseBraceToken */, sourceFile);
    if (!openToken || !closeToken || positionsAreOnSameLine(openToken.pos, closeToken.pos, sourceFile)) {
      return void 0;
    }
    return spanBetweenTokens(
      openToken,
      closeToken,
      node,
      sourceFile,
      /*autoCollapse*/
      false,
      /*useFullStart*/
      false
    );
  }
  function spanForCallExpression(node) {
    if (!node.arguments.length) {
      return void 0;
    }
    const openToken = findChildOfKind(node, 21 /* OpenParenToken */, sourceFile);
    const closeToken = findChildOfKind(node, 22 /* CloseParenToken */, sourceFile);
    if (!openToken || !closeToken || positionsAreOnSameLine(openToken.pos, closeToken.pos, sourceFile)) {
      return void 0;
    }
    return spanBetweenTokens(
      openToken,
      closeToken,
      node,
      sourceFile,
      /*autoCollapse*/
      false,
      /*useFullStart*/
      true
    );
  }
  function spanForArrowFunction(node) {
    if (isBlock(node.body) || isParenthesizedExpression(node.body) || positionsAreOnSameLine(node.body.getFullStart(), node.body.getEnd(), sourceFile)) {
      return void 0;
    }
    const textSpan = createTextSpanFromBounds(node.body.getFullStart(), node.body.getEnd());
    return createOutliningSpan(textSpan, "code" /* Code */, createTextSpanFromNode(node));
  }
  function spanForJSXElement(node) {
    const textSpan = createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd());
    const tagName = node.openingElement.tagName.getText(sourceFile);
    const bannerText = "<" + tagName + ">...</" + tagName + ">";
    return createOutliningSpan(
      textSpan,
      "code" /* Code */,
      textSpan,
      /*autoCollapse*/
      false,
      bannerText
    );
  }
  function spanForJSXFragment(node) {
    const textSpan = createTextSpanFromBounds(node.openingFragment.getStart(sourceFile), node.closingFragment.getEnd());
    const bannerText = "<>...</>";
    return createOutliningSpan(
      textSpan,
      "code" /* Code */,
      textSpan,
      /*autoCollapse*/
      false,
      bannerText
    );
  }
  function spanForJSXAttributes(node) {
    if (node.properties.length === 0) {
      return void 0;
    }
    return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */);
  }
  function spanForTemplateLiteral(node) {
    if (node.kind === 15 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) {
      return void 0;
    }
    return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */);
  }
  function spanForObjectOrArrayLiteral(node, open = 19 /* OpenBraceToken */) {
    return spanForNode(
      node,
      /*autoCollapse*/
      false,
      /*useFullStart*/
      !isArrayLiteralExpression(node.parent) && !isCallExpression(node.parent),
      open
    );
  }
  function spanForNode(hintSpanNode, autoCollapse = false, useFullStart = true, open = 19 /* OpenBraceToken */, close = open === 19 /* OpenBraceToken */ ? 20 /* CloseBraceToken */ : 24 /* CloseBracketToken */) {
    const openToken = findChildOfKind(n, open, sourceFile);
    const closeToken = findChildOfKind(n, close, sourceFile);
    return openToken && closeToken && spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart);
  }
  function spanForNodeArray(nodeArray) {
    return nodeArray.length ? createOutliningSpan(createTextSpanFromRange(nodeArray), "code" /* Code */) : void 0;
  }
  function spanForParenthesizedExpression(node) {
    if (positionsAreOnSameLine(node.getStart(), node.getEnd(), sourceFile)) return void 0;
    const textSpan = createTextSpanFromBounds(node.getStart(), node.getEnd());
    return createOutliningSpan(textSpan, "code" /* Code */, createTextSpanFromNode(node));
  }
}
function functionSpan(node, body, sourceFile) {
  const openToken = tryGetFunctionOpenToken(node, body, sourceFile);
  const closeToken = findChildOfKind(body, 20 /* CloseBraceToken */, sourceFile);
  return openToken && closeToken && spanBetweenTokens(
    openToken,
    closeToken,
    node,
    sourceFile,
    /*autoCollapse*/
    node.kind !== 219 /* ArrowFunction */
  );
}
function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse = false, useFullStart = true) {
  const textSpan = createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
  return createOutliningSpan(textSpan, "code" /* Code */, createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
}
function createOutliningSpan(textSpan, kind, hintSpan = textSpan, autoCollapse = false, bannerText = "...") {
  return { textSpan, kind, hintSpan, bannerText, autoCollapse };
}
function tryGetFunctionOpenToken(node, body, sourceFile) {
  if (isNodeArrayMultiLine(node.parameters, sourceFile)) {
    const openParenToken = findChildOfKind(node, 21 /* OpenParenToken */, sourceFile);
    if (openParenToken) {
      return openParenToken;
    }
  }
  return findChildOfKind(body, 19 /* OpenBraceToken */, sourceFile);
}

// src/services/_namespaces/ts.Rename.ts
var ts_Rename_exports = {};
__export(ts_Rename_exports, {
  getRenameInfo: () => getRenameInfo,
  nodeIsEligibleForRename: () => nodeIsEligibleForRename
});

// src/services/rename.ts
function getRenameInfo(program, sourceFile, position, preferences) {
  const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position));
  if (nodeIsEligibleForRename(node)) {
    const renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, preferences);
    if (renameInfo) {
      return renameInfo;
    }
  }
  return getRenameInfoError(Diagnostics.You_cannot_rename_this_element);
}
function getRenameInfoForNode(node, typeChecker, sourceFile, program, preferences) {
  const symbol = typeChecker.getSymbolAtLocation(node);
  if (!symbol) {
    if (isStringLiteralLike(node)) {
      const type = getContextualTypeFromParentOrAncestorTypeNode(node, typeChecker);
      if (type && (type.flags & 128 /* StringLiteral */ || type.flags & 1048576 /* Union */ && every(type.types, (type2) => !!(type2.flags & 128 /* StringLiteral */)))) {
        return getRenameInfoSuccess(node.text, node.text, "string" /* string */, "", node, sourceFile);
      }
    } else if (isLabelName(node)) {
      const name = getTextOfNode(node);
      return getRenameInfoSuccess(name, name, "label" /* label */, "" /* none */, node, sourceFile);
    }
    return void 0;
  }
  const { declarations } = symbol;
  if (!declarations || declarations.length === 0) return;
  if (declarations.some((declaration) => isDefinedInLibraryFile(program, declaration))) {
    return getRenameInfoError(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
  }
  if (isIdentifier(node) && node.escapedText === "default" && symbol.parent && symbol.parent.flags & 1536 /* Module */) {
    return void 0;
  }
  if (isStringLiteralLike(node) && tryGetImportFromModuleSpecifier(node)) {
    return preferences.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : void 0;
  }
  const wouldRenameNodeModules = wouldRenameInOtherNodeModules(sourceFile, symbol, typeChecker, preferences);
  if (wouldRenameNodeModules) {
    return getRenameInfoError(wouldRenameNodeModules);
  }
  const kind = ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, node);
  const specifierName = isImportOrExportSpecifierName(node) || isStringOrNumericLiteralLike(node) && node.parent.kind === 167 /* ComputedPropertyName */ ? stripQuotes(getTextOfIdentifierOrLiteral(node)) : void 0;
  const displayName = specifierName || typeChecker.symbolToString(symbol);
  const fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol);
  return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol), node, sourceFile);
}
function isDefinedInLibraryFile(program, declaration) {
  const sourceFile = declaration.getSourceFile();
  return program.isSourceFileDefaultLibrary(sourceFile) && fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */);
}
function wouldRenameInOtherNodeModules(originalFile, symbol, checker, preferences) {
  if (!preferences.providePrefixAndSuffixTextForRename && symbol.flags & 2097152 /* Alias */) {
    const importSpecifier = symbol.declarations && find(symbol.declarations, (decl) => isImportSpecifier(decl));
    if (importSpecifier && !importSpecifier.propertyName) {
      symbol = checker.getAliasedSymbol(symbol);
    }
  }
  const { declarations } = symbol;
  if (!declarations) {
    return void 0;
  }
  const originalPackage = getPackagePathComponents(originalFile.path);
  if (originalPackage === void 0) {
    if (some(declarations, (declaration) => isInsideNodeModules(declaration.getSourceFile().path))) {
      return Diagnostics.You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder;
    } else {
      return void 0;
    }
  }
  for (const declaration of declarations) {
    const declPackage = getPackagePathComponents(declaration.getSourceFile().path);
    if (declPackage) {
      const length2 = Math.min(originalPackage.length, declPackage.length);
      for (let i = 0; i <= length2; i++) {
        if (compareStringsCaseSensitive(originalPackage[i], declPackage[i]) !== 0 /* EqualTo */) {
          return Diagnostics.You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder;
        }
      }
    }
  }
  return void 0;
}
function getPackagePathComponents(filePath) {
  const components = getPathComponents(filePath);
  const nodeModulesIdx = components.lastIndexOf("node_modules");
  if (nodeModulesIdx === -1) {
    return void 0;
  }
  return components.slice(0, nodeModulesIdx + 2);
}
function getRenameInfoForModule(node, sourceFile, moduleSymbol) {
  if (!isExternalModuleNameRelative(node.text)) {
    return getRenameInfoError(Diagnostics.You_cannot_rename_a_module_via_a_global_import);
  }
  const moduleSourceFile = moduleSymbol.declarations && find(moduleSymbol.declarations, isSourceFile);
  if (!moduleSourceFile) return void 0;
  const withoutIndex = endsWith(node.text, "/index") || endsWith(node.text, "/index.js") ? void 0 : tryRemoveSuffix(removeFileExtension(moduleSourceFile.fileName), "/index");
  const fileName = withoutIndex === void 0 ? moduleSourceFile.fileName : withoutIndex;
  const kind = withoutIndex === void 0 ? "module" /* moduleElement */ : "directory" /* directory */;
  const indexAfterLastSlash = node.text.lastIndexOf("/") + 1;
  const triggerSpan = createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash);
  return {
    canRename: true,
    fileToRename: fileName,
    kind,
    displayName: fileName,
    fullDisplayName: node.text,
    kindModifiers: "" /* none */,
    triggerSpan
  };
}
function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
  return {
    canRename: true,
    fileToRename: void 0,
    kind,
    displayName,
    fullDisplayName,
    kindModifiers,
    triggerSpan: createTriggerSpanForNode(node, sourceFile)
  };
}
function getRenameInfoError(diagnostic) {
  return { canRename: false, localizedErrorMessage: getLocaleSpecificMessage(diagnostic) };
}
function createTriggerSpanForNode(node, sourceFile) {
  let start = node.getStart(sourceFile);
  let width = node.getWidth(sourceFile);
  if (isStringLiteralLike(node)) {
    start += 1;
    width -= 2;
  }
  return createTextSpan(start, width);
}
function nodeIsEligibleForRename(node) {
  switch (node.kind) {
    case 80 /* Identifier */:
    case 81 /* PrivateIdentifier */:
    case 11 /* StringLiteral */:
    case 15 /* NoSubstitutionTemplateLiteral */:
    case 110 /* ThisKeyword */:
      return true;
    case 9 /* NumericLiteral */:
      return isLiteralNameOfPropertyDeclarationOrIndexAccess(node);
    default:
      return false;
  }
}

// src/services/_namespaces/ts.SignatureHelp.ts
var ts_SignatureHelp_exports = {};
__export(ts_SignatureHelp_exports, {
  getArgumentInfoForCompletions: () => getArgumentInfoForCompletions,
  getSignatureHelpItems: () => getSignatureHelpItems
});

// src/services/signatureHelp.ts
function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) {
  const typeChecker = program.getTypeChecker();
  const startingToken = findTokenOnLeftOfPosition(sourceFile, position);
  if (!startingToken) {
    return void 0;
  }
  const onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped";
  if (onlyUseSyntacticOwners && (isInString(sourceFile, position, startingToken) || isInComment(sourceFile, position))) {
    return void 0;
  }
  const isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked";
  const argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked);
  if (!argumentInfo) return void 0;
  cancellationToken.throwIfCancellationRequested();
  const candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners);
  cancellationToken.throwIfCancellationRequested();
  if (!candidateInfo) {
    return isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : void 0;
  }
  return typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2) => candidateInfo.kind === 0 /* Candidate */ ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker2) : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker2));
}
function getCandidateOrTypeInfo({ invocation, argumentCount }, checker, sourceFile, startingToken, onlyUseSyntacticOwners) {
  switch (invocation.kind) {
    case 0 /* Call */: {
      if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) {
        return void 0;
      }
      const candidates = [];
      const resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount);
      return candidates.length === 0 ? void 0 : { kind: 0 /* Candidate */, candidates, resolvedSignature };
    }
    case 1 /* TypeArgs */: {
      const { called } = invocation;
      if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, isIdentifier(called) ? called.parent : called)) {
        return void 0;
      }
      const candidates = getPossibleGenericSignatures(called, argumentCount, checker);
      if (candidates.length !== 0) return { kind: 0 /* Candidate */, candidates, resolvedSignature: first(candidates) };
      const symbol = checker.getSymbolAtLocation(called);
      return symbol && { kind: 1 /* Type */, symbol };
    }
    case 2 /* Contextual */:
      return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature };
    default:
      return Debug.assertNever(invocation);
  }
}
function isSyntacticOwner(startingToken, node, sourceFile) {
  if (!isCallOrNewExpression(node)) return false;
  const invocationChildren = node.getChildren(sourceFile);
  switch (startingToken.kind) {
    case 21 /* OpenParenToken */:
      return contains(invocationChildren, startingToken);
    case 28 /* CommaToken */: {
      const containingList = findContainingList(startingToken);
      return !!containingList && contains(invocationChildren, containingList);
    }
    case 30 /* LessThanToken */:
      return containsPrecedingToken(startingToken, sourceFile, node.expression);
    default:
      return false;
  }
}
function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) {
  if (argumentInfo.invocation.kind === 2 /* Contextual */) return void 0;
  const expression = getExpressionFromInvocation(argumentInfo.invocation);
  const name = isPropertyAccessExpression(expression) ? expression.name.text : void 0;
  const typeChecker = program.getTypeChecker();
  return name === void 0 ? void 0 : firstDefined(program.getSourceFiles(), (sourceFile) => firstDefined(sourceFile.getNamedDeclarations().get(name), (declaration) => {
    const type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration);
    const callSignatures = type && type.getCallSignatures();
    if (callSignatures && callSignatures.length) {
      return typeChecker.runWithCancellationToken(
        cancellationToken,
        (typeChecker2) => createSignatureHelpItems(
          callSignatures,
          callSignatures[0],
          argumentInfo,
          sourceFile,
          typeChecker2,
          /*useFullPrefix*/
          true
        )
      );
    }
  }));
}
function containsPrecedingToken(startingToken, sourceFile, container) {
  const pos = startingToken.getFullStart();
  let currentParent = startingToken.parent;
  while (currentParent) {
    const precedingToken = findPrecedingToken(
      pos,
      sourceFile,
      currentParent,
      /*excludeJsdoc*/
      true
    );
    if (precedingToken) {
      return rangeContainsRange(container, precedingToken);
    }
    currentParent = currentParent.parent;
  }
  return Debug.fail("Could not find preceding token");
}
function getArgumentInfoForCompletions(node, position, sourceFile, checker) {
  const info = getImmediatelyContainingArgumentInfo(node, position, sourceFile, checker);
  return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? void 0 : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex };
}
function getArgumentOrParameterListInfo(node, position, sourceFile, checker) {
  const info = getArgumentOrParameterListAndIndex(node, sourceFile, checker);
  if (!info) return void 0;
  const { list, argumentIndex } = info;
  const argumentCount = getArgumentCount(checker, list);
  const argumentsSpan = getApplicableSpanForArguments(list, sourceFile);
  return { list, argumentIndex, argumentCount, argumentsSpan };
}
function getArgumentOrParameterListAndIndex(node, sourceFile, checker) {
  if (node.kind === 30 /* LessThanToken */ || node.kind === 21 /* OpenParenToken */) {
    return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 };
  } else {
    const list = findContainingList(node);
    return list && { list, argumentIndex: getArgumentIndex(checker, list, node) };
  }
}
function getImmediatelyContainingArgumentInfo(node, position, sourceFile, checker) {
  const { parent: parent2 } = node;
  if (isCallOrNewExpression(parent2)) {
    const invocation = parent2;
    const info = getArgumentOrParameterListInfo(node, position, sourceFile, checker);
    if (!info) return void 0;
    const { list, argumentIndex, argumentCount, argumentsSpan } = info;
    const isTypeParameterList = !!parent2.typeArguments && parent2.typeArguments.pos === list.pos;
    return { isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan, argumentIndex, argumentCount };
  } else if (isNoSubstitutionTemplateLiteral(node) && isTaggedTemplateExpression(parent2)) {
    if (isInsideTemplateLiteral(node, position, sourceFile)) {
      return getArgumentListInfoForTemplate(
        parent2,
        /*argumentIndex*/
        0,
        sourceFile
      );
    }
    return void 0;
  } else if (isTemplateHead(node) && parent2.parent.kind === 215 /* TaggedTemplateExpression */) {
    const templateExpression = parent2;
    const tagExpression = templateExpression.parent;
    Debug.assert(templateExpression.kind === 228 /* TemplateExpression */);
    const argumentIndex = isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1;
    return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
  } else if (isTemplateSpan(parent2) && isTaggedTemplateExpression(parent2.parent.parent)) {
    const templateSpan = parent2;
    const tagExpression = parent2.parent.parent;
    if (isTemplateTail(node) && !isInsideTemplateLiteral(node, position, sourceFile)) {
      return void 0;
    }
    const spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan);
    const argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile);
    return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
  } else if (isJsxOpeningLikeElement(parent2)) {
    const attributeSpanStart = parent2.attributes.pos;
    const attributeSpanEnd = skipTrivia(
      sourceFile.text,
      parent2.attributes.end,
      /*stopAfterLineBreak*/
      false
    );
    return {
      isTypeParameterList: false,
      invocation: { kind: 0 /* Call */, node: parent2 },
      argumentsSpan: createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart),
      argumentIndex: 0,
      argumentCount: 1
    };
  } else {
    const typeArgInfo = getPossibleTypeArgumentsInfo(node, sourceFile);
    if (typeArgInfo) {
      const { called, nTypeArguments } = typeArgInfo;
      const invocation = { kind: 1 /* TypeArgs */, called };
      const argumentsSpan = createTextSpanFromBounds(called.getStart(sourceFile), node.end);
      return { isTypeParameterList: true, invocation, argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 };
    }
    return void 0;
  }
}
function getImmediatelyContainingArgumentOrContextualParameterInfo(node, position, sourceFile, checker) {
  return tryGetParameterInfo(node, position, sourceFile, checker) || getImmediatelyContainingArgumentInfo(node, position, sourceFile, checker);
}
function getHighestBinary(b) {
  return isBinaryExpression(b.parent) ? getHighestBinary(b.parent) : b;
}
function countBinaryExpressionParameters(b) {
  return isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2;
}
function tryGetParameterInfo(startingToken, position, sourceFile, checker) {
  const node = getAdjustedNode(startingToken);
  if (node === void 0) return void 0;
  const info = getContextualSignatureLocationInfo(node, sourceFile, position, checker);
  if (info === void 0) return void 0;
  const { contextualType, argumentIndex, argumentCount, argumentsSpan } = info;
  const nonNullableContextualType = contextualType.getNonNullableType();
  const symbol = nonNullableContextualType.symbol;
  if (symbol === void 0) return void 0;
  const signature = lastOrUndefined(nonNullableContextualType.getCallSignatures());
  if (signature === void 0) return void 0;
  const invocation = { kind: 2 /* Contextual */, signature, node: startingToken, symbol: chooseBetterSymbol(symbol) };
  return { isTypeParameterList: false, invocation, argumentsSpan, argumentIndex, argumentCount };
}
function getAdjustedNode(node) {
  switch (node.kind) {
    case 21 /* OpenParenToken */:
    case 28 /* CommaToken */:
      return node;
    default:
      return findAncestor(node.parent, (n) => isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit");
  }
}
function getContextualSignatureLocationInfo(node, sourceFile, position, checker) {
  const { parent: parent2 } = node;
  switch (parent2.kind) {
    case 217 /* ParenthesizedExpression */:
    case 174 /* MethodDeclaration */:
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
      const info = getArgumentOrParameterListInfo(node, position, sourceFile, checker);
      if (!info) return void 0;
      const { argumentIndex, argumentCount, argumentsSpan } = info;
      const contextualType = isMethodDeclaration(parent2) ? checker.getContextualTypeForObjectLiteralElement(parent2) : checker.getContextualType(parent2);
      return contextualType && { contextualType, argumentIndex, argumentCount, argumentsSpan };
    case 226 /* BinaryExpression */: {
      const highestBinary = getHighestBinary(parent2);
      const contextualType2 = checker.getContextualType(highestBinary);
      const argumentIndex2 = node.kind === 21 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent2) - 1;
      const argumentCount2 = countBinaryExpressionParameters(highestBinary);
      return contextualType2 && { contextualType: contextualType2, argumentIndex: argumentIndex2, argumentCount: argumentCount2, argumentsSpan: createTextSpanFromNode(parent2) };
    }
    default:
      return void 0;
  }
}
function chooseBetterSymbol(s) {
  return s.name === "__type" /* Type */ ? firstDefined(s.declarations, (d) => {
    var _a;
    return isFunctionTypeNode(d) ? (_a = tryCast(d.parent, canHaveSymbol)) == null ? void 0 : _a.symbol : void 0;
  }) || s : s;
}
function getSpreadElementCount(node, checker) {
  const spreadType = checker.getTypeAtLocation(node.expression);
  if (checker.isTupleType(spreadType)) {
    const { elementFlags, fixedLength } = spreadType.target;
    if (fixedLength === 0) {
      return 0;
    }
    const firstOptionalIndex = findIndex(elementFlags, (f) => !(f & 1 /* Required */));
    return firstOptionalIndex < 0 ? fixedLength : firstOptionalIndex;
  }
  return 0;
}
function getArgumentIndex(checker, argumentsList, node) {
  return getArgumentIndexOrCount(checker, argumentsList, node);
}
function getArgumentCount(checker, argumentsList) {
  return getArgumentIndexOrCount(
    checker,
    argumentsList,
    /*node*/
    void 0
  );
}
function getArgumentIndexOrCount(checker, argumentsList, node) {
  const args = argumentsList.getChildren();
  let argumentIndex = 0;
  let skipComma = false;
  for (const child of args) {
    if (node && child === node) {
      if (!skipComma && child.kind === 28 /* CommaToken */) {
        argumentIndex++;
      }
      return argumentIndex;
    }
    if (isSpreadElement(child)) {
      argumentIndex += getSpreadElementCount(child, checker);
      skipComma = true;
      continue;
    }
    if (child.kind !== 28 /* CommaToken */) {
      argumentIndex++;
      skipComma = true;
      continue;
    }
    if (skipComma) {
      skipComma = false;
      continue;
    }
    argumentIndex++;
  }
  if (node) {
    return argumentIndex;
  }
  return args.length && last(args).kind === 28 /* CommaToken */ ? argumentIndex + 1 : argumentIndex;
}
function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) {
  Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node.");
  if (isTemplateLiteralToken(node)) {
    if (isInsideTemplateLiteral(node, position, sourceFile)) {
      return 0;
    }
    return spanIndex + 2;
  }
  return spanIndex + 1;
}
function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) {
  const argumentCount = isNoSubstitutionTemplateLiteral(tagExpression.template) ? 1 : tagExpression.template.templateSpans.length + 1;
  if (argumentIndex !== 0) {
    Debug.assertLessThan(argumentIndex, argumentCount);
  }
  return {
    isTypeParameterList: false,
    invocation: { kind: 0 /* Call */, node: tagExpression },
    argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile),
    argumentIndex,
    argumentCount
  };
}
function getApplicableSpanForArguments(argumentsList, sourceFile) {
  const applicableSpanStart = argumentsList.getFullStart();
  const applicableSpanEnd = skipTrivia(
    sourceFile.text,
    argumentsList.getEnd(),
    /*stopAfterLineBreak*/
    false
  );
  return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) {
  const template = taggedTemplate.template;
  const applicableSpanStart = template.getStart();
  let applicableSpanEnd = template.getEnd();
  if (template.kind === 228 /* TemplateExpression */) {
    const lastSpan = last(template.templateSpans);
    if (lastSpan.literal.getFullWidth() === 0) {
      applicableSpanEnd = skipTrivia(
        sourceFile.text,
        applicableSpanEnd,
        /*stopAfterLineBreak*/
        false
      );
    }
  }
  return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) {
  for (let n = node; !isSourceFile(n) && (isManuallyInvoked || !isBlock(n)); n = n.parent) {
    Debug.assert(rangeContainsRange(n.parent, n), "Not a subspan", () => `Child: ${Debug.formatSyntaxKind(n.kind)}, parent: ${Debug.formatSyntaxKind(n.parent.kind)}`);
    const argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker);
    if (argumentInfo) {
      return argumentInfo;
    }
  }
  return void 0;
}
function getChildListThatStartsWithOpenerToken(parent2, openerToken, sourceFile) {
  const children = parent2.getChildren(sourceFile);
  const indexOfOpenerToken = children.indexOf(openerToken);
  Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1);
  return children[indexOfOpenerToken + 1];
}
function getExpressionFromInvocation(invocation) {
  return invocation.kind === 0 /* Call */ ? getInvokedExpression(invocation.node) : invocation.called;
}
function getEnclosingDeclarationFromInvocation(invocation) {
  return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
}
var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
function createSignatureHelpItems(candidates, resolvedSignature, { isTypeParameterList, argumentCount, argumentsSpan: applicableSpan, invocation, argumentIndex }, sourceFile, typeChecker, useFullPrefix) {
  var _a;
  const enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation);
  const callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)) || useFullPrefix && ((_a = resolvedSignature.declaration) == null ? void 0 : _a.symbol);
  const callTargetDisplayParts = callTargetSymbol ? symbolToDisplayParts(
    typeChecker,
    callTargetSymbol,
    useFullPrefix ? sourceFile : void 0,
    /*meaning*/
    void 0
  ) : emptyArray;
  const items = map(candidates, (candidateSignature) => getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile));
  let selectedItemIndex = 0;
  let itemsSeen = 0;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (candidates[i] === resolvedSignature) {
      selectedItemIndex = itemsSeen;
      if (item.length > 1) {
        let count = 0;
        for (const i2 of item) {
          if (i2.isVariadic || i2.parameters.length >= argumentCount) {
            selectedItemIndex = itemsSeen + count;
            break;
          }
          count++;
        }
      }
    }
    itemsSeen += item.length;
  }
  Debug.assert(selectedItemIndex !== -1);
  const help = { items: flatMapToMutable(items, identity), applicableSpan, selectedItemIndex, argumentIndex, argumentCount };
  const selected = help.items[selectedItemIndex];
  if (selected.isVariadic) {
    const firstRest = findIndex(selected.parameters, (p) => !!p.isRest);
    if (-1 < firstRest && firstRest < selected.parameters.length - 1) {
      help.argumentIndex = selected.parameters.length;
    } else {
      help.argumentIndex = Math.min(help.argumentIndex, selected.parameters.length - 1);
    }
  }
  return help;
}
function createTypeHelpItems(symbol, { argumentCount, argumentsSpan: applicableSpan, invocation, argumentIndex }, sourceFile, checker) {
  const typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
  if (!typeParameters) return void 0;
  const items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)];
  return { items, applicableSpan, selectedItemIndex: 0, argumentIndex, argumentCount };
}
function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) {
  const typeSymbolDisplay = symbolToDisplayParts(checker, symbol);
  const printer = createPrinterWithRemoveComments();
  const parameters = typeParameters.map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer));
  const documentation = symbol.getDocumentationComment(checker);
  const tags = symbol.getJsDocTags(checker);
  const prefixDisplayParts = [...typeSymbolDisplay, punctuationPart(30 /* LessThanToken */)];
  return { isVariadic: false, prefixDisplayParts, suffixDisplayParts: [punctuationPart(32 /* GreaterThanToken */)], separatorDisplayParts, parameters, documentation, tags };
}
var separatorDisplayParts = [punctuationPart(28 /* CommaToken */), spacePart()];
function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) {
  const infos = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile);
  return map(infos, ({ isVariadic, parameters, prefix, suffix }) => {
    const prefixDisplayParts = [...callTargetDisplayParts, ...prefix];
    const suffixDisplayParts = [...suffix, ...returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)];
    const documentation = candidateSignature.getDocumentationComment(checker);
    const tags = candidateSignature.getJsDocTags();
    return { isVariadic, prefixDisplayParts, suffixDisplayParts, separatorDisplayParts, parameters, documentation, tags };
  });
}
function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) {
  return mapToDisplayParts((writer) => {
    writer.writePunctuation(":");
    writer.writeSpace(" ");
    const predicate = checker.getTypePredicateOfSignature(candidateSignature);
    if (predicate) {
      checker.writeTypePredicate(
        predicate,
        enclosingDeclaration,
        /*flags*/
        void 0,
        writer
      );
    } else {
      checker.writeType(
        checker.getReturnTypeOfSignature(candidateSignature),
        enclosingDeclaration,
        /*flags*/
        void 0,
        writer
      );
    }
  });
}
function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
  const typeParameters = (candidateSignature.target || candidateSignature).typeParameters;
  const printer = createPrinterWithRemoveComments();
  const parameters = (typeParameters || emptyArray).map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer));
  const thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : [];
  return checker.getExpandedParameters(candidateSignature).map((paramList) => {
    const params = factory.createNodeArray([...thisParameter, ...map(paramList, (param) => checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags))]);
    const parameterParts = mapToDisplayParts((writer) => {
      printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer);
    });
    return { isVariadic: false, parameters, prefix: [punctuationPart(30 /* LessThanToken */)], suffix: [punctuationPart(32 /* GreaterThanToken */), ...parameterParts] };
  });
}
function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
  const printer = createPrinterWithRemoveComments();
  const typeParameterParts = mapToDisplayParts((writer) => {
    if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
      const args = factory.createNodeArray(candidateSignature.typeParameters.map((p) => checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags)));
      printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer);
    }
  });
  const lists = checker.getExpandedParameters(candidateSignature);
  const isVariadic = !checker.hasEffectiveRestParameter(candidateSignature) ? (_) => false : lists.length === 1 ? (_) => true : (pList) => {
    var _a;
    return !!(pList.length && ((_a = tryCast(pList[pList.length - 1], isTransientSymbol)) == null ? void 0 : _a.links.checkFlags) & 32768 /* RestParameter */);
  };
  return lists.map((parameterList) => ({
    isVariadic: isVariadic(parameterList),
    parameters: parameterList.map((p) => createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer)),
    prefix: [...typeParameterParts, punctuationPart(21 /* OpenParenToken */)],
    suffix: [punctuationPart(22 /* CloseParenToken */)]
  }));
}
function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) {
  const displayParts = mapToDisplayParts((writer) => {
    const param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags);
    printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
  });
  const isOptional = checker.isOptionalParameter(parameter.valueDeclaration);
  const isRest = isTransientSymbol(parameter) && !!(parameter.links.checkFlags & 32768 /* RestParameter */);
  return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts, isOptional, isRest };
}
function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) {
  const displayParts = mapToDisplayParts((writer) => {
    const param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags);
    printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
  });
  return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts, isOptional: false, isRest: false };
}

// src/services/_namespaces/ts.SmartSelectionRange.ts
var ts_SmartSelectionRange_exports = {};
__export(ts_SmartSelectionRange_exports, {
  getSmartSelectionRange: () => getSmartSelectionRange
});

// src/services/smartSelection.ts
function getSmartSelectionRange(pos, sourceFile) {
  var _a, _b;
  let selectionRange = {
    textSpan: createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd())
  };
  let parentNode = sourceFile;
  outer:
    while (true) {
      const children = getSelectionChildren(parentNode);
      if (!children.length) break;
      for (let i = 0; i < children.length; i++) {
        const prevNode = children[i - 1];
        const node = children[i];
        const nextNode = children[i + 1];
        if (getTokenPosOfNode(
          node,
          sourceFile,
          /*includeJsDoc*/
          true
        ) > pos) {
          break outer;
        }
        const comment = singleOrUndefined(getTrailingCommentRanges(sourceFile.text, node.end));
        if (comment && comment.kind === 2 /* SingleLineCommentTrivia */) {
          pushSelectionCommentRange(comment.pos, comment.end);
        }
        if (positionShouldSnapToNode(sourceFile, pos, node)) {
          if (isFunctionBody(node) && isFunctionLikeDeclaration(parentNode) && !positionsAreOnSameLine(node.getStart(sourceFile), node.getEnd(), sourceFile)) {
            pushSelectionRange(node.getStart(sourceFile), node.getEnd());
          }
          if (isBlock(node) || isTemplateSpan(node) || isTemplateHead(node) || isTemplateTail(node) || prevNode && isTemplateHead(prevNode) || isVariableDeclarationList(node) && isVariableStatement(parentNode) || isSyntaxList(node) && isVariableDeclarationList(parentNode) || isVariableDeclaration(node) && isSyntaxList(parentNode) && children.length === 1 || isJSDocTypeExpression(node) || isJSDocSignature(node) || isJSDocTypeLiteral(node)) {
            parentNode = node;
            break;
          }
          if (isTemplateSpan(parentNode) && nextNode && isTemplateMiddleOrTemplateTail(nextNode)) {
            const start2 = node.getFullStart() - "${".length;
            const end2 = nextNode.getStart() + "}".length;
            pushSelectionRange(start2, end2);
          }
          const isBetweenMultiLineBookends = isSyntaxList(node) && isListOpener(prevNode) && isListCloser(nextNode) && !positionsAreOnSameLine(prevNode.getStart(), nextNode.getStart(), sourceFile);
          let start = isBetweenMultiLineBookends ? prevNode.getEnd() : node.getStart();
          const end = isBetweenMultiLineBookends ? nextNode.getStart() : getEndPos(sourceFile, node);
          if (hasJSDocNodes(node) && ((_a = node.jsDoc) == null ? void 0 : _a.length)) {
            pushSelectionRange(first(node.jsDoc).getStart(), end);
          }
          if (isSyntaxList(node)) {
            const firstChild = node.getChildren()[0];
            if (firstChild && hasJSDocNodes(firstChild) && ((_b = firstChild.jsDoc) == null ? void 0 : _b.length) && firstChild.getStart() !== node.pos) {
              start = Math.min(start, first(firstChild.jsDoc).getStart());
            }
          }
          pushSelectionRange(start, end);
          if (isStringLiteral(node) || isTemplateLiteral(node)) {
            pushSelectionRange(start + 1, end - 1);
          }
          parentNode = node;
          break;
        }
        if (i === children.length - 1) {
          break outer;
        }
      }
    }
  return selectionRange;
  function pushSelectionRange(start, end) {
    if (start !== end) {
      const textSpan = createTextSpanFromBounds(start, end);
      if (!selectionRange || // Skip ranges that are identical to the parent
      !textSpansEqual(textSpan, selectionRange.textSpan) && // Skip ranges that don't contain the original position
      textSpanIntersectsWithPosition(textSpan, pos)) {
        selectionRange = { textSpan, ...selectionRange && { parent: selectionRange } };
      }
    }
  }
  function pushSelectionCommentRange(start, end) {
    pushSelectionRange(start, end);
    let pos2 = start;
    while (sourceFile.text.charCodeAt(pos2) === 47 /* slash */) {
      pos2++;
    }
    pushSelectionRange(pos2, end);
  }
}
function positionShouldSnapToNode(sourceFile, pos, node) {
  Debug.assert(node.pos <= pos);
  if (pos < node.end) {
    return true;
  }
  const nodeEnd = node.getEnd();
  if (nodeEnd === pos) {
    return getTouchingPropertyName(sourceFile, pos).pos < node.end;
  }
  return false;
}
var isImport2 = or(isImportDeclaration, isImportEqualsDeclaration);
function getSelectionChildren(node) {
  var _a;
  if (isSourceFile(node)) {
    return groupChildren(node.getChildAt(0).getChildren(), isImport2);
  }
  if (isMappedTypeNode(node)) {
    const [openBraceToken, ...children] = node.getChildren();
    const closeBraceToken = Debug.checkDefined(children.pop());
    Debug.assertEqual(openBraceToken.kind, 19 /* OpenBraceToken */);
    Debug.assertEqual(closeBraceToken.kind, 20 /* CloseBraceToken */);
    const groupedWithPlusMinusTokens = groupChildren(children, (child) => child === node.readonlyToken || child.kind === 148 /* ReadonlyKeyword */ || child === node.questionToken || child.kind === 58 /* QuestionToken */);
    const groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, ({ kind }) => kind === 23 /* OpenBracketToken */ || kind === 168 /* TypeParameter */ || kind === 24 /* CloseBracketToken */);
    return [
      openBraceToken,
      // Pivot on `:`
      createSyntaxList2(splitChildren(groupedWithBrackets, ({ kind }) => kind === 59 /* ColonToken */)),
      closeBraceToken
    ];
  }
  if (isPropertySignature(node)) {
    const children = groupChildren(node.getChildren(), (child) => child === node.name || contains(node.modifiers, child));
    const firstJSDocChild = ((_a = children[0]) == null ? void 0 : _a.kind) === 320 /* JSDoc */ ? children[0] : void 0;
    const withJSDocSeparated = firstJSDocChild ? children.slice(1) : children;
    const splittedChildren = splitChildren(withJSDocSeparated, ({ kind }) => kind === 59 /* ColonToken */);
    return firstJSDocChild ? [firstJSDocChild, createSyntaxList2(splittedChildren)] : splittedChildren;
  }
  if (isParameter(node)) {
    const groupedDotDotDotAndName = groupChildren(node.getChildren(), (child) => child === node.dotDotDotToken || child === node.name);
    const groupedWithQuestionToken = groupChildren(groupedDotDotDotAndName, (child) => child === groupedDotDotDotAndName[0] || child === node.questionToken);
    return splitChildren(groupedWithQuestionToken, ({ kind }) => kind === 64 /* EqualsToken */);
  }
  if (isBindingElement(node)) {
    return splitChildren(node.getChildren(), ({ kind }) => kind === 64 /* EqualsToken */);
  }
  return node.getChildren();
}
function groupChildren(children, groupOn) {
  const result = [];
  let group2;
  for (const child of children) {
    if (groupOn(child)) {
      group2 = group2 || [];
      group2.push(child);
    } else {
      if (group2) {
        result.push(createSyntaxList2(group2));
        group2 = void 0;
      }
      result.push(child);
    }
  }
  if (group2) {
    result.push(createSyntaxList2(group2));
  }
  return result;
}
function splitChildren(children, pivotOn, separateTrailingSemicolon = true) {
  if (children.length < 2) {
    return children;
  }
  const splitTokenIndex = findIndex(children, pivotOn);
  if (splitTokenIndex === -1) {
    return children;
  }
  const leftChildren = children.slice(0, splitTokenIndex);
  const splitToken = children[splitTokenIndex];
  const lastToken = last(children);
  const separateLastToken = separateTrailingSemicolon && lastToken.kind === 27 /* SemicolonToken */;
  const rightChildren = children.slice(splitTokenIndex + 1, separateLastToken ? children.length - 1 : void 0);
  const result = compact([
    leftChildren.length ? createSyntaxList2(leftChildren) : void 0,
    splitToken,
    rightChildren.length ? createSyntaxList2(rightChildren) : void 0
  ]);
  return separateLastToken ? result.concat(lastToken) : result;
}
function createSyntaxList2(children) {
  Debug.assertGreaterThanOrEqual(children.length, 1);
  return setTextRangePosEnd(parseNodeFactory.createSyntaxList(children), children[0].pos, last(children).end);
}
function isListOpener(token) {
  const kind = token && token.kind;
  return kind === 19 /* OpenBraceToken */ || kind === 23 /* OpenBracketToken */ || kind === 21 /* OpenParenToken */ || kind === 286 /* JsxOpeningElement */;
}
function isListCloser(token) {
  const kind = token && token.kind;
  return kind === 20 /* CloseBraceToken */ || kind === 24 /* CloseBracketToken */ || kind === 22 /* CloseParenToken */ || kind === 287 /* JsxClosingElement */;
}
function getEndPos(sourceFile, node) {
  switch (node.kind) {
    case 341 /* JSDocParameterTag */:
    case 338 /* JSDocCallbackTag */:
    case 348 /* JSDocPropertyTag */:
    case 346 /* JSDocTypedefTag */:
    case 343 /* JSDocThisTag */:
      return sourceFile.getLineEndOfPosition(node.getStart());
    default:
      return node.getEnd();
  }
}

// src/services/_namespaces/ts.SymbolDisplay.ts
var ts_SymbolDisplay_exports = {};
__export(ts_SymbolDisplay_exports, {
  getSymbolDisplayPartsDocumentationAndSymbolKind: () => getSymbolDisplayPartsDocumentationAndSymbolKind,
  getSymbolKind: () => getSymbolKind,
  getSymbolModifiers: () => getSymbolModifiers
});

// src/services/symbolDisplay.ts
var symbolDisplayNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
function getSymbolKind(typeChecker, symbol, location) {
  const result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location);
  if (result !== "" /* unknown */) {
    return result;
  }
  const flags = getCombinedLocalAndExportSymbolFlags(symbol);
  if (flags & 32 /* Class */) {
    return getDeclarationOfKind(symbol, 231 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */;
  }
  if (flags & 384 /* Enum */) return "enum" /* enumElement */;
  if (flags & 524288 /* TypeAlias */) return "type" /* typeElement */;
  if (flags & 64 /* Interface */) return "interface" /* interfaceElement */;
  if (flags & 262144 /* TypeParameter */) return "type parameter" /* typeParameterElement */;
  if (flags & 8 /* EnumMember */) return "enum member" /* enumMemberElement */;
  if (flags & 2097152 /* Alias */) return "alias" /* alias */;
  if (flags & 1536 /* Module */) return "module" /* moduleElement */;
  return result;
}
function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) {
  const roots = typeChecker.getRootSymbols(symbol);
  if (roots.length === 1 && first(roots).flags & 8192 /* Method */ && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) {
    return "method" /* memberFunctionElement */;
  }
  if (typeChecker.isUndefinedSymbol(symbol)) {
    return "var" /* variableElement */;
  }
  if (typeChecker.isArgumentsSymbol(symbol)) {
    return "local var" /* localVariableElement */;
  }
  if (location.kind === 110 /* ThisKeyword */ && isExpression(location) || isThisInTypeQuery(location)) {
    return "parameter" /* parameterElement */;
  }
  const flags = getCombinedLocalAndExportSymbolFlags(symbol);
  if (flags & 3 /* Variable */) {
    if (isFirstDeclarationOfSymbolParameter(symbol)) {
      return "parameter" /* parameterElement */;
    } else if (symbol.valueDeclaration && isVarConst(symbol.valueDeclaration)) {
      return "const" /* constElement */;
    } else if (symbol.valueDeclaration && isVarUsing(symbol.valueDeclaration)) {
      return "using" /* variableUsingElement */;
    } else if (symbol.valueDeclaration && isVarAwaitUsing(symbol.valueDeclaration)) {
      return "await using" /* variableAwaitUsingElement */;
    } else if (forEach(symbol.declarations, isLet)) {
      return "let" /* letElement */;
    }
    return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */;
  }
  if (flags & 16 /* Function */) return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */;
  if (flags & 32768 /* GetAccessor */) return "getter" /* memberGetAccessorElement */;
  if (flags & 65536 /* SetAccessor */) return "setter" /* memberSetAccessorElement */;
  if (flags & 8192 /* Method */) return "method" /* memberFunctionElement */;
  if (flags & 16384 /* Constructor */) return "constructor" /* constructorImplementationElement */;
  if (flags & 131072 /* Signature */) return "index" /* indexSignatureElement */;
  if (flags & 4 /* Property */) {
    if (flags & 33554432 /* Transient */ && symbol.links.checkFlags & 6 /* Synthetic */) {
      const unionPropertyKind = forEach(typeChecker.getRootSymbols(symbol), (rootSymbol) => {
        const rootSymbolFlags = rootSymbol.getFlags();
        if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) {
          return "property" /* memberVariableElement */;
        }
      });
      if (!unionPropertyKind) {
        const typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location);
        if (typeOfUnionProperty.getCallSignatures().length) {
          return "method" /* memberFunctionElement */;
        }
        return "property" /* memberVariableElement */;
      }
      return unionPropertyKind;
    }
    return "property" /* memberVariableElement */;
  }
  return "" /* unknown */;
}
function getNormalizedSymbolModifiers(symbol) {
  if (symbol.declarations && symbol.declarations.length) {
    const [declaration, ...declarations] = symbol.declarations;
    const excludeFlags = length(declarations) && isDeprecatedDeclaration(declaration) && some(declarations, (d) => !isDeprecatedDeclaration(d)) ? 65536 /* Deprecated */ : 0 /* None */;
    const modifiers = getNodeModifiers(declaration, excludeFlags);
    if (modifiers) {
      return modifiers.split(",");
    }
  }
  return [];
}
function getSymbolModifiers(typeChecker, symbol) {
  if (!symbol) {
    return "" /* none */;
  }
  const modifiers = new Set(getNormalizedSymbolModifiers(symbol));
  if (symbol.flags & 2097152 /* Alias */) {
    const resolvedSymbol = typeChecker.getAliasedSymbol(symbol);
    if (resolvedSymbol !== symbol) {
      forEach(getNormalizedSymbolModifiers(resolvedSymbol), (modifier) => {
        modifiers.add(modifier);
      });
    }
  }
  if (symbol.flags & 16777216 /* Optional */) {
    modifiers.add("optional" /* optionalModifier */);
  }
  return modifiers.size > 0 ? arrayFrom(modifiers.values()).join(",") : "" /* none */;
}
function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symbol, sourceFile, enclosingDeclaration, location, type, semanticMeaning, alias) {
  var _a;
  const displayParts = [];
  let documentation = [];
  let tags = [];
  const symbolFlags = getCombinedLocalAndExportSymbolFlags(symbol);
  let symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */;
  let hasAddedSymbolInfo = false;
  const isThisExpression = location.kind === 110 /* ThisKeyword */ && isInExpressionContext(location) || isThisInTypeQuery(location);
  let documentationFromAlias;
  let tagsFromAlias;
  let hasMultipleSignatures = false;
  if (location.kind === 110 /* ThisKeyword */ && !isThisExpression) {
    return { displayParts: [keywordPart(110 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: void 0 };
  }
  if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) {
    if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) {
      const declaration = find(symbol.declarations, (declaration2) => declaration2.name === location);
      if (declaration) {
        switch (declaration.kind) {
          case 177 /* GetAccessor */:
            symbolKind = "getter" /* memberGetAccessorElement */;
            break;
          case 178 /* SetAccessor */:
            symbolKind = "setter" /* memberSetAccessorElement */;
            break;
          case 172 /* PropertyDeclaration */:
            symbolKind = "accessor" /* memberAccessorVariableElement */;
            break;
          default:
            Debug.assertNever(declaration);
        }
      } else {
        symbolKind = "property" /* memberVariableElement */;
      }
    }
    let signature;
    type ?? (type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location));
    if (location.parent && location.parent.kind === 211 /* PropertyAccessExpression */) {
      const right = location.parent.name;
      if (right === location || right && right.getFullWidth() === 0) {
        location = location.parent;
      }
    }
    let callExpressionLike;
    if (isCallOrNewExpression(location)) {
      callExpressionLike = location;
    } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) {
      callExpressionLike = location.parent;
    } else if (location.parent && (isJsxOpeningLikeElement(location.parent) || isTaggedTemplateExpression(location.parent)) && isFunctionLike(symbol.valueDeclaration)) {
      callExpressionLike = location.parent;
    }
    if (callExpressionLike) {
      signature = typeChecker.getResolvedSignature(callExpressionLike);
      const useConstructSignatures = callExpressionLike.kind === 214 /* NewExpression */ || isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 108 /* SuperKeyword */;
      const allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures();
      if (signature && !contains(allSignatures, signature.target) && !contains(allSignatures, signature)) {
        signature = allSignatures.length ? allSignatures[0] : void 0;
      }
      if (signature) {
        if (useConstructSignatures && symbolFlags & 32 /* Class */) {
          symbolKind = "constructor" /* constructorImplementationElement */;
          addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
        } else if (symbolFlags & 2097152 /* Alias */) {
          symbolKind = "alias" /* alias */;
          pushSymbolKind(symbolKind);
          displayParts.push(spacePart());
          if (useConstructSignatures) {
            if (signature.flags & 4 /* Abstract */) {
              displayParts.push(keywordPart(128 /* AbstractKeyword */));
              displayParts.push(spacePart());
            }
            displayParts.push(keywordPart(105 /* NewKeyword */));
            displayParts.push(spacePart());
          }
          addFullSymbolName(symbol);
        } else {
          addPrefixForAnyFunctionOrVar(symbol, symbolKind);
        }
        switch (symbolKind) {
          case "JSX attribute" /* jsxAttribute */:
          case "property" /* memberVariableElement */:
          case "var" /* variableElement */:
          case "const" /* constElement */:
          case "let" /* letElement */:
          case "parameter" /* parameterElement */:
          case "local var" /* localVariableElement */:
            displayParts.push(punctuationPart(59 /* ColonToken */));
            displayParts.push(spacePart());
            if (!(getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) {
              addRange(displayParts, symbolToDisplayParts(
                typeChecker,
                type.symbol,
                enclosingDeclaration,
                /*meaning*/
                void 0,
                4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */
              ));
              displayParts.push(lineBreakPart());
            }
            if (useConstructSignatures) {
              if (signature.flags & 4 /* Abstract */) {
                displayParts.push(keywordPart(128 /* AbstractKeyword */));
                displayParts.push(spacePart());
              }
              displayParts.push(keywordPart(105 /* NewKeyword */));
              displayParts.push(spacePart());
            }
            addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */);
            break;
          default:
            addSignatureDisplayParts(signature, allSignatures);
        }
        hasAddedSymbolInfo = true;
        hasMultipleSignatures = allSignatures.length > 1;
      }
    } else if (isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */) || // name of function declaration
    location.kind === 137 /* ConstructorKeyword */ && location.parent.kind === 176 /* Constructor */) {
      const functionDeclaration = location.parent;
      const locationIsSymbolDeclaration = symbol.declarations && find(symbol.declarations, (declaration) => declaration === (location.kind === 137 /* ConstructorKeyword */ ? functionDeclaration.parent : functionDeclaration));
      if (locationIsSymbolDeclaration) {
        const allSignatures = functionDeclaration.kind === 176 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures();
        if (!typeChecker.isImplementationOfOverload(functionDeclaration)) {
          signature = typeChecker.getSignatureFromDeclaration(functionDeclaration);
        } else {
          signature = allSignatures[0];
        }
        if (functionDeclaration.kind === 176 /* Constructor */) {
          symbolKind = "constructor" /* constructorImplementationElement */;
          addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
        } else {
          addPrefixForAnyFunctionOrVar(
            functionDeclaration.kind === 179 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol,
            symbolKind
          );
        }
        if (signature) {
          addSignatureDisplayParts(signature, allSignatures);
        }
        hasAddedSymbolInfo = true;
        hasMultipleSignatures = allSignatures.length > 1;
      }
    }
  }
  if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) {
    addAliasPrefixIfNecessary();
    if (getDeclarationOfKind(symbol, 231 /* ClassExpression */)) {
      pushSymbolKind("local class" /* localClassElement */);
    } else {
      displayParts.push(keywordPart(86 /* ClassKeyword */));
    }
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
    writeTypeParametersOfSymbol(symbol, sourceFile);
  }
  if (symbolFlags & 64 /* Interface */ && semanticMeaning & 2 /* Type */) {
    prefixNextMeaning();
    displayParts.push(keywordPart(120 /* InterfaceKeyword */));
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
    writeTypeParametersOfSymbol(symbol, sourceFile);
  }
  if (symbolFlags & 524288 /* TypeAlias */ && semanticMeaning & 2 /* Type */) {
    prefixNextMeaning();
    displayParts.push(keywordPart(156 /* TypeKeyword */));
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
    writeTypeParametersOfSymbol(symbol, sourceFile);
    displayParts.push(spacePart());
    displayParts.push(operatorPart(64 /* EqualsToken */));
    displayParts.push(spacePart());
    addRange(displayParts, typeToDisplayParts(typeChecker, location.parent && isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */));
  }
  if (symbolFlags & 384 /* Enum */) {
    prefixNextMeaning();
    if (some(symbol.declarations, (d) => isEnumDeclaration(d) && isEnumConst(d))) {
      displayParts.push(keywordPart(87 /* ConstKeyword */));
      displayParts.push(spacePart());
    }
    displayParts.push(keywordPart(94 /* EnumKeyword */));
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
  }
  if (symbolFlags & 1536 /* Module */ && !isThisExpression) {
    prefixNextMeaning();
    const declaration = getDeclarationOfKind(symbol, 267 /* ModuleDeclaration */);
    const isNamespace = declaration && declaration.name && declaration.name.kind === 80 /* Identifier */;
    displayParts.push(keywordPart(isNamespace ? 145 /* NamespaceKeyword */ : 144 /* ModuleKeyword */));
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
  }
  if (symbolFlags & 262144 /* TypeParameter */ && semanticMeaning & 2 /* Type */) {
    prefixNextMeaning();
    displayParts.push(punctuationPart(21 /* OpenParenToken */));
    displayParts.push(textPart("type parameter"));
    displayParts.push(punctuationPart(22 /* CloseParenToken */));
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
    if (symbol.parent) {
      addInPrefix();
      addFullSymbolName(symbol.parent, enclosingDeclaration);
      writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration);
    } else {
      const decl = getDeclarationOfKind(symbol, 168 /* TypeParameter */);
      if (decl === void 0) return Debug.fail();
      const declaration = decl.parent;
      if (declaration) {
        if (isFunctionLike(declaration)) {
          addInPrefix();
          const signature = typeChecker.getSignatureFromDeclaration(declaration);
          if (declaration.kind === 180 /* ConstructSignature */) {
            displayParts.push(keywordPart(105 /* NewKeyword */));
            displayParts.push(spacePart());
          } else if (declaration.kind !== 179 /* CallSignature */ && declaration.name) {
            addFullSymbolName(declaration.symbol);
          }
          addRange(displayParts, signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */));
        } else if (isTypeAliasDeclaration(declaration)) {
          addInPrefix();
          displayParts.push(keywordPart(156 /* TypeKeyword */));
          displayParts.push(spacePart());
          addFullSymbolName(declaration.symbol);
          writeTypeParametersOfSymbol(declaration.symbol, sourceFile);
        }
      }
    }
  }
  if (symbolFlags & 8 /* EnumMember */) {
    symbolKind = "enum member" /* enumMemberElement */;
    addPrefixForAnyFunctionOrVar(symbol, "enum member");
    const declaration = (_a = symbol.declarations) == null ? void 0 : _a[0];
    if ((declaration == null ? void 0 : declaration.kind) === 306 /* EnumMember */) {
      const constantValue = typeChecker.getConstantValue(declaration);
      if (constantValue !== void 0) {
        displayParts.push(spacePart());
        displayParts.push(operatorPart(64 /* EqualsToken */));
        displayParts.push(spacePart());
        displayParts.push(displayPart(getTextOfConstantValue(constantValue), typeof constantValue === "number" ? 7 /* numericLiteral */ : 8 /* stringLiteral */));
      }
    }
  }
  if (symbol.flags & 2097152 /* Alias */) {
    prefixNextMeaning();
    if (!hasAddedSymbolInfo || documentation.length === 0 && tags.length === 0) {
      const resolvedSymbol = typeChecker.getAliasedSymbol(symbol);
      if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) {
        const resolvedNode = resolvedSymbol.declarations[0];
        const declarationName = getNameOfDeclaration(resolvedNode);
        if (declarationName && !hasAddedSymbolInfo) {
          const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 128 /* Ambient */);
          const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration;
          const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKindWorker(
            typeChecker,
            resolvedSymbol,
            getSourceFileOfNode(resolvedNode),
            enclosingDeclaration,
            declarationName,
            type,
            semanticMeaning,
            shouldUseAliasName ? symbol : resolvedSymbol
          );
          displayParts.push(...resolvedInfo.displayParts);
          displayParts.push(lineBreakPart());
          documentationFromAlias = resolvedInfo.documentation;
          tagsFromAlias = resolvedInfo.tags;
        } else {
          documentationFromAlias = resolvedSymbol.getContextualDocumentationComment(resolvedNode, typeChecker);
          tagsFromAlias = resolvedSymbol.getJsDocTags(typeChecker);
        }
      }
    }
    if (symbol.declarations) {
      switch (symbol.declarations[0].kind) {
        case 270 /* NamespaceExportDeclaration */:
          displayParts.push(keywordPart(95 /* ExportKeyword */));
          displayParts.push(spacePart());
          displayParts.push(keywordPart(145 /* NamespaceKeyword */));
          break;
        case 277 /* ExportAssignment */:
          displayParts.push(keywordPart(95 /* ExportKeyword */));
          displayParts.push(spacePart());
          displayParts.push(keywordPart(symbol.declarations[0].isExportEquals ? 64 /* EqualsToken */ : 90 /* DefaultKeyword */));
          break;
        case 281 /* ExportSpecifier */:
          displayParts.push(keywordPart(95 /* ExportKeyword */));
          break;
        default:
          displayParts.push(keywordPart(102 /* ImportKeyword */));
      }
    }
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
    forEach(symbol.declarations, (declaration) => {
      if (declaration.kind === 271 /* ImportEqualsDeclaration */) {
        const importEqualsDeclaration = declaration;
        if (isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) {
          displayParts.push(spacePart());
          displayParts.push(operatorPart(64 /* EqualsToken */));
          displayParts.push(spacePart());
          displayParts.push(keywordPart(149 /* RequireKeyword */));
          displayParts.push(punctuationPart(21 /* OpenParenToken */));
          displayParts.push(displayPart(getTextOfNode(getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), 8 /* stringLiteral */));
          displayParts.push(punctuationPart(22 /* CloseParenToken */));
        } else {
          const internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference);
          if (internalAliasSymbol) {
            displayParts.push(spacePart());
            displayParts.push(operatorPart(64 /* EqualsToken */));
            displayParts.push(spacePart());
            addFullSymbolName(internalAliasSymbol, enclosingDeclaration);
          }
        }
        return true;
      }
    });
  }
  if (!hasAddedSymbolInfo) {
    if (symbolKind !== "" /* unknown */) {
      if (type) {
        if (isThisExpression) {
          prefixNextMeaning();
          displayParts.push(keywordPart(110 /* ThisKeyword */));
        } else {
          addPrefixForAnyFunctionOrVar(symbol, symbolKind);
        }
        if (symbolKind === "property" /* memberVariableElement */ || symbolKind === "accessor" /* memberAccessorVariableElement */ || symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || symbolKind === "index" /* indexSignatureElement */ || symbolKind === "using" /* variableUsingElement */ || symbolKind === "await using" /* variableAwaitUsingElement */ || isThisExpression) {
          displayParts.push(punctuationPart(59 /* ColonToken */));
          displayParts.push(spacePart());
          if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */ && symbolKind !== "index" /* indexSignatureElement */) {
            const typeParameterParts = mapToDisplayParts((writer) => {
              const param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration, symbolDisplayNodeBuilderFlags);
              getPrinter().writeNode(4 /* Unspecified */, param, getSourceFileOfNode(getParseTreeNode(enclosingDeclaration)), writer);
            });
            addRange(displayParts, typeParameterParts);
          } else {
            addRange(displayParts, typeToDisplayParts(typeChecker, type, enclosingDeclaration));
          }
          if (isTransientSymbol(symbol) && symbol.links.target && isTransientSymbol(symbol.links.target) && symbol.links.target.links.tupleLabelDeclaration) {
            const labelDecl = symbol.links.target.links.tupleLabelDeclaration;
            Debug.assertNode(labelDecl.name, isIdentifier);
            displayParts.push(spacePart());
            displayParts.push(punctuationPart(21 /* OpenParenToken */));
            displayParts.push(textPart(idText(labelDecl.name)));
            displayParts.push(punctuationPart(22 /* CloseParenToken */));
          }
        } else if (symbolFlags & 16 /* Function */ || symbolFlags & 8192 /* Method */ || symbolFlags & 16384 /* Constructor */ || symbolFlags & 131072 /* Signature */ || symbolFlags & 98304 /* Accessor */ || symbolKind === "method" /* memberFunctionElement */) {
          const allSignatures = type.getNonNullableType().getCallSignatures();
          if (allSignatures.length) {
            addSignatureDisplayParts(allSignatures[0], allSignatures);
            hasMultipleSignatures = allSignatures.length > 1;
          }
        }
      }
    } else {
      symbolKind = getSymbolKind(typeChecker, symbol, location);
    }
  }
  if (documentation.length === 0 && !hasMultipleSignatures) {
    documentation = symbol.getContextualDocumentationComment(enclosingDeclaration, typeChecker);
  }
  if (documentation.length === 0 && symbolFlags & 4 /* Property */) {
    if (symbol.parent && symbol.declarations && forEach(symbol.parent.declarations, (declaration) => declaration.kind === 307 /* SourceFile */)) {
      for (const declaration of symbol.declarations) {
        if (!declaration.parent || declaration.parent.kind !== 226 /* BinaryExpression */) {
          continue;
        }
        const rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right);
        if (!rhsSymbol) {
          continue;
        }
        documentation = rhsSymbol.getDocumentationComment(typeChecker);
        tags = rhsSymbol.getJsDocTags(typeChecker);
        if (documentation.length > 0) {
          break;
        }
      }
    }
  }
  if (documentation.length === 0 && isIdentifier(location) && symbol.valueDeclaration && isBindingElement(symbol.valueDeclaration)) {
    const declaration = symbol.valueDeclaration;
    const parent2 = declaration.parent;
    const name = declaration.propertyName || declaration.name;
    if (isIdentifier(name) && isObjectBindingPattern(parent2)) {
      const propertyName = getTextOfIdentifierOrLiteral(name);
      const objectType = typeChecker.getTypeAtLocation(parent2);
      documentation = firstDefined(objectType.isUnion() ? objectType.types : [objectType], (t) => {
        const prop = t.getProperty(propertyName);
        return prop ? prop.getDocumentationComment(typeChecker) : void 0;
      }) || emptyArray;
    }
  }
  if (tags.length === 0 && !hasMultipleSignatures) {
    tags = symbol.getContextualJsDocTags(enclosingDeclaration, typeChecker);
  }
  if (documentation.length === 0 && documentationFromAlias) {
    documentation = documentationFromAlias;
  }
  if (tags.length === 0 && tagsFromAlias) {
    tags = tagsFromAlias;
  }
  return { displayParts, documentation, symbolKind, tags: tags.length === 0 ? void 0 : tags };
  function getPrinter() {
    return createPrinterWithRemoveComments();
  }
  function prefixNextMeaning() {
    if (displayParts.length) {
      displayParts.push(lineBreakPart());
    }
    addAliasPrefixIfNecessary();
  }
  function addAliasPrefixIfNecessary() {
    if (alias) {
      pushSymbolKind("alias" /* alias */);
      displayParts.push(spacePart());
    }
  }
  function addInPrefix() {
    displayParts.push(spacePart());
    displayParts.push(keywordPart(103 /* InKeyword */));
    displayParts.push(spacePart());
  }
  function addFullSymbolName(symbolToDisplay, enclosingDeclaration2) {
    let indexInfos;
    if (alias && symbolToDisplay === symbol) {
      symbolToDisplay = alias;
    }
    if (symbolKind === "index" /* indexSignatureElement */) {
      indexInfos = typeChecker.getIndexInfosOfIndexSymbol(symbolToDisplay);
    }
    let fullSymbolDisplayParts = [];
    if (symbolToDisplay.flags & 131072 /* Signature */ && indexInfos) {
      if (symbolToDisplay.parent) {
        fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbolToDisplay.parent);
      }
      fullSymbolDisplayParts.push(punctuationPart(23 /* OpenBracketToken */));
      indexInfos.forEach((info, i) => {
        fullSymbolDisplayParts.push(...typeToDisplayParts(typeChecker, info.keyType));
        if (i !== indexInfos.length - 1) {
          fullSymbolDisplayParts.push(spacePart());
          fullSymbolDisplayParts.push(punctuationPart(52 /* BarToken */));
          fullSymbolDisplayParts.push(spacePart());
        }
      });
      fullSymbolDisplayParts.push(punctuationPart(24 /* CloseBracketToken */));
    } else {
      fullSymbolDisplayParts = symbolToDisplayParts(
        typeChecker,
        symbolToDisplay,
        enclosingDeclaration2 || sourceFile,
        /*meaning*/
        void 0,
        1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */
      );
    }
    addRange(displayParts, fullSymbolDisplayParts);
    if (symbol.flags & 16777216 /* Optional */) {
      displayParts.push(punctuationPart(58 /* QuestionToken */));
    }
  }
  function addPrefixForAnyFunctionOrVar(symbol2, symbolKind2) {
    prefixNextMeaning();
    if (symbolKind2) {
      pushSymbolKind(symbolKind2);
      if (symbol2 && !some(symbol2.declarations, (d) => isArrowFunction(d) || (isFunctionExpression(d) || isClassExpression(d)) && !d.name)) {
        displayParts.push(spacePart());
        addFullSymbolName(symbol2);
      }
    }
  }
  function pushSymbolKind(symbolKind2) {
    switch (symbolKind2) {
      case "var" /* variableElement */:
      case "function" /* functionElement */:
      case "let" /* letElement */:
      case "const" /* constElement */:
      case "constructor" /* constructorImplementationElement */:
      case "using" /* variableUsingElement */:
      case "await using" /* variableAwaitUsingElement */:
        displayParts.push(textOrKeywordPart(symbolKind2));
        return;
      default:
        displayParts.push(punctuationPart(21 /* OpenParenToken */));
        displayParts.push(textOrKeywordPart(symbolKind2));
        displayParts.push(punctuationPart(22 /* CloseParenToken */));
        return;
    }
  }
  function addSignatureDisplayParts(signature, allSignatures, flags = 0 /* None */) {
    addRange(displayParts, signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */));
    if (allSignatures.length > 1) {
      displayParts.push(spacePart());
      displayParts.push(punctuationPart(21 /* OpenParenToken */));
      displayParts.push(operatorPart(40 /* PlusToken */));
      displayParts.push(displayPart((allSignatures.length - 1).toString(), 7 /* numericLiteral */));
      displayParts.push(spacePart());
      displayParts.push(textPart(allSignatures.length === 2 ? "overload" : "overloads"));
      displayParts.push(punctuationPart(22 /* CloseParenToken */));
    }
    documentation = signature.getDocumentationComment(typeChecker);
    tags = signature.getJsDocTags();
    if (allSignatures.length > 1 && documentation.length === 0 && tags.length === 0) {
      documentation = allSignatures[0].getDocumentationComment(typeChecker);
      tags = allSignatures[0].getJsDocTags().filter((tag) => tag.name !== "deprecated");
    }
  }
  function writeTypeParametersOfSymbol(symbol2, enclosingDeclaration2) {
    const typeParameterParts = mapToDisplayParts((writer) => {
      const params = typeChecker.symbolToTypeParameterDeclarations(symbol2, enclosingDeclaration2, symbolDisplayNodeBuilderFlags);
      getPrinter().writeList(53776 /* TypeParameters */, params, getSourceFileOfNode(getParseTreeNode(enclosingDeclaration2)), writer);
    });
    addRange(displayParts, typeParameterParts);
  }
}
function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning = getMeaningFromLocation(location), alias) {
  return getSymbolDisplayPartsDocumentationAndSymbolKindWorker(
    typeChecker,
    symbol,
    sourceFile,
    enclosingDeclaration,
    location,
    /*type*/
    void 0,
    semanticMeaning,
    alias
  );
}
function isLocalVariableOrFunction(symbol) {
  if (symbol.parent) {
    return false;
  }
  return forEach(symbol.declarations, (declaration) => {
    if (declaration.kind === 218 /* FunctionExpression */) {
      return true;
    }
    if (declaration.kind !== 260 /* VariableDeclaration */ && declaration.kind !== 262 /* FunctionDeclaration */) {
      return false;
    }
    for (let parent2 = declaration.parent; !isFunctionBlock(parent2); parent2 = parent2.parent) {
      if (parent2.kind === 307 /* SourceFile */ || parent2.kind === 268 /* ModuleBlock */) {
        return false;
      }
    }
    return true;
  });
}

// src/services/_namespaces/ts.textChanges.ts
var ts_textChanges_exports = {};
__export(ts_textChanges_exports, {
  ChangeTracker: () => ChangeTracker,
  LeadingTriviaOption: () => LeadingTriviaOption,
  TrailingTriviaOption: () => TrailingTriviaOption,
  applyChanges: () => applyChanges,
  assignPositionsToNode: () => assignPositionsToNode,
  createWriter: () => createWriter,
  deleteNode: () => deleteNode,
  getAdjustedEndPosition: () => getAdjustedEndPosition,
  isThisTypeAnnotatable: () => isThisTypeAnnotatable,
  isValidLocationToAddComment: () => isValidLocationToAddComment
});

// src/services/textChanges.ts
function getPos2(n) {
  const result = n.__pos;
  Debug.assert(typeof result === "number");
  return result;
}
function setPos(n, pos) {
  Debug.assert(typeof pos === "number");
  n.__pos = pos;
}
function getEnd(n) {
  const result = n.__end;
  Debug.assert(typeof result === "number");
  return result;
}
function setEnd(n, end) {
  Debug.assert(typeof end === "number");
  n.__end = end;
}
var LeadingTriviaOption = /* @__PURE__ */ ((LeadingTriviaOption2) => {
  LeadingTriviaOption2[LeadingTriviaOption2["Exclude"] = 0] = "Exclude";
  LeadingTriviaOption2[LeadingTriviaOption2["IncludeAll"] = 1] = "IncludeAll";
  LeadingTriviaOption2[LeadingTriviaOption2["JSDoc"] = 2] = "JSDoc";
  LeadingTriviaOption2[LeadingTriviaOption2["StartLine"] = 3] = "StartLine";
  return LeadingTriviaOption2;
})(LeadingTriviaOption || {});
var TrailingTriviaOption = /* @__PURE__ */ ((TrailingTriviaOption2) => {
  TrailingTriviaOption2[TrailingTriviaOption2["Exclude"] = 0] = "Exclude";
  TrailingTriviaOption2[TrailingTriviaOption2["ExcludeWhitespace"] = 1] = "ExcludeWhitespace";
  TrailingTriviaOption2[TrailingTriviaOption2["Include"] = 2] = "Include";
  return TrailingTriviaOption2;
})(TrailingTriviaOption || {});
function skipWhitespacesAndLineBreaks(text, start) {
  return skipTrivia(
    text,
    start,
    /*stopAfterLineBreak*/
    false,
    /*stopAtComments*/
    true
  );
}
function hasCommentsBeforeLineBreak(text, start) {
  let i = start;
  while (i < text.length) {
    const ch = text.charCodeAt(i);
    if (isWhiteSpaceSingleLine(ch)) {
      i++;
      continue;
    }
    return ch === 47 /* slash */;
  }
  return false;
}
var useNonAdjustedPositions = {
  leadingTriviaOption: 0 /* Exclude */,
  trailingTriviaOption: 0 /* Exclude */
};
function getAdjustedRange(sourceFile, startNode2, endNode2, options) {
  return { pos: getAdjustedStartPosition(sourceFile, startNode2, options), end: getAdjustedEndPosition(sourceFile, endNode2, options) };
}
function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment = false) {
  var _a, _b;
  const { leadingTriviaOption } = options;
  if (leadingTriviaOption === 0 /* Exclude */) {
    return node.getStart(sourceFile);
  }
  if (leadingTriviaOption === 3 /* StartLine */) {
    const startPos = node.getStart(sourceFile);
    const pos = getLineStartPositionForPosition(startPos, sourceFile);
    return rangeContainsPosition(node, pos) ? pos : startPos;
  }
  if (leadingTriviaOption === 2 /* JSDoc */) {
    const JSDocComments = getJSDocCommentRanges(node, sourceFile.text);
    if (JSDocComments == null ? void 0 : JSDocComments.length) {
      return getLineStartPositionForPosition(JSDocComments[0].pos, sourceFile);
    }
  }
  const fullStart = node.getFullStart();
  const start = node.getStart(sourceFile);
  if (fullStart === start) {
    return start;
  }
  const fullStartLine = getLineStartPositionForPosition(fullStart, sourceFile);
  const startLine = getLineStartPositionForPosition(start, sourceFile);
  if (startLine === fullStartLine) {
    return leadingTriviaOption === 1 /* IncludeAll */ ? fullStart : start;
  }
  if (hasTrailingComment) {
    const comment = ((_a = getLeadingCommentRanges(sourceFile.text, fullStart)) == null ? void 0 : _a[0]) || ((_b = getTrailingCommentRanges(sourceFile.text, fullStart)) == null ? void 0 : _b[0]);
    if (comment) {
      return skipTrivia(
        sourceFile.text,
        comment.end,
        /*stopAfterLineBreak*/
        true,
        /*stopAtComments*/
        true
      );
    }
  }
  const nextLineStart = fullStart > 0 ? 1 : 0;
  let adjustedStartPosition = getStartPositionOfLine(getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile);
  adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition);
  return getStartPositionOfLine(getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
}
function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) {
  const { end } = node;
  const { trailingTriviaOption } = options;
  if (trailingTriviaOption === 2 /* Include */) {
    const comments = getTrailingCommentRanges(sourceFile.text, end);
    if (comments) {
      const nodeEndLine = getLineOfLocalPosition(sourceFile, node.end);
      for (const comment of comments) {
        if (comment.kind === 2 /* SingleLineCommentTrivia */ || getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) {
          break;
        }
        const commentEndLine = getLineOfLocalPosition(sourceFile, comment.end);
        if (commentEndLine > nodeEndLine) {
          return skipTrivia(
            sourceFile.text,
            comment.end,
            /*stopAfterLineBreak*/
            true,
            /*stopAtComments*/
            true
          );
        }
      }
    }
  }
  return void 0;
}
function getAdjustedEndPosition(sourceFile, node, options) {
  var _a;
  const { end } = node;
  const { trailingTriviaOption } = options;
  if (trailingTriviaOption === 0 /* Exclude */) {
    return end;
  }
  if (trailingTriviaOption === 1 /* ExcludeWhitespace */) {
    const comments = concatenate(getTrailingCommentRanges(sourceFile.text, end), getLeadingCommentRanges(sourceFile.text, end));
    const realEnd = (_a = comments == null ? void 0 : comments[comments.length - 1]) == null ? void 0 : _a.end;
    if (realEnd) {
      return realEnd;
    }
    return end;
  }
  const multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options);
  if (multilineEndPosition) {
    return multilineEndPosition;
  }
  const newEnd = skipTrivia(
    sourceFile.text,
    end,
    /*stopAfterLineBreak*/
    true
  );
  return newEnd !== end && (trailingTriviaOption === 2 /* Include */ || isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd : end;
}
function isSeparator(node, candidate) {
  return !!candidate && !!node.parent && (candidate.kind === 28 /* CommaToken */ || candidate.kind === 27 /* SemicolonToken */ && node.parent.kind === 210 /* ObjectLiteralExpression */);
}
function isThisTypeAnnotatable(containingFunction) {
  return isFunctionExpression(containingFunction) || isFunctionDeclaration(containingFunction);
}
var ChangeTracker = class _ChangeTracker {
  /** Public for tests only. Other callers should use `ChangeTracker.with`. */
  constructor(newLineCharacter, formatContext) {
    this.newLineCharacter = newLineCharacter;
    this.formatContext = formatContext;
    this.changes = [];
    this.classesWithNodesInsertedAtStart = /* @__PURE__ */ new Map();
    // Set<ClassDeclaration> implemented as Map<node id, ClassDeclaration>
    this.deletedNodes = [];
  }
  static fromContext(context) {
    return new _ChangeTracker(getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext);
  }
  static with(context, cb) {
    const tracker = _ChangeTracker.fromContext(context);
    cb(tracker);
    return tracker.getChanges();
  }
  pushRaw(sourceFile, change) {
    Debug.assertEqual(sourceFile.fileName, change.fileName);
    for (const c of change.textChanges) {
      this.changes.push({
        kind: 3 /* Text */,
        sourceFile,
        text: c.newText,
        range: createTextRangeFromSpan(c.span)
      });
    }
  }
  deleteRange(sourceFile, range) {
    this.changes.push({ kind: 0 /* Remove */, sourceFile, range });
  }
  delete(sourceFile, node) {
    this.deletedNodes.push({ sourceFile, node });
  }
  /** Stop! Consider using `delete` instead, which has logic for deleting nodes from delimited lists. */
  deleteNode(sourceFile, node, options = { leadingTriviaOption: 1 /* IncludeAll */ }) {
    this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options));
  }
  deleteNodes(sourceFile, nodes, options = { leadingTriviaOption: 1 /* IncludeAll */ }, hasTrailingComment) {
    for (const node of nodes) {
      const pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment);
      const end = getAdjustedEndPosition(sourceFile, node, options);
      this.deleteRange(sourceFile, { pos, end });
      hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options);
    }
  }
  deleteModifier(sourceFile, modifier) {
    this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: skipTrivia(
      sourceFile.text,
      modifier.end,
      /*stopAfterLineBreak*/
      true
    ) });
  }
  deleteNodeRange(sourceFile, startNode2, endNode2, options = { leadingTriviaOption: 1 /* IncludeAll */ }) {
    const startPosition = getAdjustedStartPosition(sourceFile, startNode2, options);
    const endPosition = getAdjustedEndPosition(sourceFile, endNode2, options);
    this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
  }
  deleteNodeRangeExcludingEnd(sourceFile, startNode2, afterEndNode, options = { leadingTriviaOption: 1 /* IncludeAll */ }) {
    const startPosition = getAdjustedStartPosition(sourceFile, startNode2, options);
    const endPosition = afterEndNode === void 0 ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
    this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
  }
  replaceRange(sourceFile, range, newNode, options = {}) {
    this.changes.push({ kind: 1 /* ReplaceWithSingleNode */, sourceFile, range, options, node: newNode });
  }
  replaceNode(sourceFile, oldNode, newNode, options = useNonAdjustedPositions) {
    this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
  }
  replaceNodeRange(sourceFile, startNode2, endNode2, newNode, options = useNonAdjustedPositions) {
    this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode2, endNode2, options), newNode, options);
  }
  replaceRangeWithNodes(sourceFile, range, newNodes, options = {}) {
    this.changes.push({ kind: 2 /* ReplaceWithMultipleNodes */, sourceFile, range, options, nodes: newNodes });
  }
  replaceNodeWithNodes(sourceFile, oldNode, newNodes, options = useNonAdjustedPositions) {
    this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
  }
  replaceNodeWithText(sourceFile, oldNode, text) {
    this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
  }
  replaceNodeRangeWithNodes(sourceFile, startNode2, endNode2, newNodes, options = useNonAdjustedPositions) {
    this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode2, endNode2, options), newNodes, options);
  }
  nodeHasTrailingComment(sourceFile, oldNode, configurableEnd = useNonAdjustedPositions) {
    return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd);
  }
  nextCommaToken(sourceFile, node) {
    const next = findNextToken(node, node.parent, sourceFile);
    return next && next.kind === 28 /* CommaToken */ ? next : void 0;
  }
  replacePropertyAssignment(sourceFile, oldNode, newNode) {
    const suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : "," + this.newLineCharacter;
    this.replaceNode(sourceFile, oldNode, newNode, { suffix });
  }
  insertNodeAt(sourceFile, pos, newNode, options = {}) {
    this.replaceRange(sourceFile, createRange(pos), newNode, options);
  }
  insertNodesAt(sourceFile, pos, newNodes, options = {}) {
    this.replaceRangeWithNodes(sourceFile, createRange(pos), newNodes, options);
  }
  insertNodeAtTopOfFile(sourceFile, newNode, blankLineBetween) {
    this.insertAtTopOfFile(sourceFile, newNode, blankLineBetween);
  }
  insertNodesAtTopOfFile(sourceFile, newNodes, blankLineBetween) {
    this.insertAtTopOfFile(sourceFile, newNodes, blankLineBetween);
  }
  insertAtTopOfFile(sourceFile, insert, blankLineBetween) {
    const pos = getInsertionPositionAtSourceFileTop(sourceFile);
    const options = {
      prefix: pos === 0 ? void 0 : this.newLineCharacter,
      suffix: (isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : "")
    };
    if (isArray(insert)) {
      this.insertNodesAt(sourceFile, pos, insert, options);
    } else {
      this.insertNodeAt(sourceFile, pos, insert, options);
    }
  }
  insertNodesAtEndOfFile(sourceFile, newNodes, blankLineBetween) {
    this.insertAtEndOfFile(sourceFile, newNodes, blankLineBetween);
  }
  insertAtEndOfFile(sourceFile, insert, blankLineBetween) {
    const pos = sourceFile.end + 1;
    const options = {
      prefix: this.newLineCharacter,
      suffix: this.newLineCharacter + (blankLineBetween ? this.newLineCharacter : "")
    };
    this.insertNodesAt(sourceFile, pos, insert, options);
  }
  insertStatementsInNewFile(fileName, statements, oldFile) {
    if (!this.newFileChanges) {
      this.newFileChanges = createMultiMap();
    }
    this.newFileChanges.add(fileName, { oldFile, statements });
  }
  insertFirstParameter(sourceFile, parameters, newParam) {
    const p0 = firstOrUndefined(parameters);
    if (p0) {
      this.insertNodeBefore(sourceFile, p0, newParam);
    } else {
      this.insertNodeAt(sourceFile, parameters.pos, newParam);
    }
  }
  insertNodeBefore(sourceFile, before, newNode, blankLineBetween = false, options = {}) {
    this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween));
  }
  insertNodesBefore(sourceFile, before, newNodes, blankLineBetween = false, options = {}) {
    this.insertNodesAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNodes, this.getOptionsForInsertNodeBefore(before, first(newNodes), blankLineBetween));
  }
  insertModifierAt(sourceFile, pos, modifier, options = {}) {
    this.insertNodeAt(sourceFile, pos, factory.createToken(modifier), options);
  }
  insertModifierBefore(sourceFile, modifier, before) {
    return this.insertModifierAt(sourceFile, before.getStart(sourceFile), modifier, { suffix: " " });
  }
  insertCommentBeforeLine(sourceFile, lineNumber, position, commentText) {
    const lineStartPosition = getStartPositionOfLine(lineNumber, sourceFile);
    const startPosition = getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition);
    const insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition);
    const token = getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position);
    const indent3 = sourceFile.text.slice(lineStartPosition, startPosition);
    const text = `${insertAtLineStart ? "" : this.newLineCharacter}//${commentText}${this.newLineCharacter}${indent3}`;
    this.insertText(sourceFile, token.getStart(sourceFile), text);
  }
  insertJsdocCommentBefore(sourceFile, node, tag) {
    const fnStart = node.getStart(sourceFile);
    if (node.jsDoc) {
      for (const jsdoc of node.jsDoc) {
        this.deleteRange(sourceFile, {
          pos: getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile),
          end: getAdjustedEndPosition(
            sourceFile,
            jsdoc,
            /*options*/
            {}
          )
        });
      }
    }
    const startPosition = getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1);
    const indent3 = sourceFile.text.slice(startPosition, fnStart);
    this.insertNodeAt(sourceFile, fnStart, tag, { suffix: this.newLineCharacter + indent3 });
  }
  createJSDocText(sourceFile, node) {
    const comments = flatMap(node.jsDoc, (jsDoc2) => isString(jsDoc2.comment) ? factory.createJSDocText(jsDoc2.comment) : jsDoc2.comment);
    const jsDoc = singleOrUndefined(node.jsDoc);
    return jsDoc && positionsAreOnSameLine(jsDoc.pos, jsDoc.end, sourceFile) && length(comments) === 0 ? void 0 : factory.createNodeArray(intersperse(comments, factory.createJSDocText("\n")));
  }
  replaceJSDocComment(sourceFile, node, tags) {
    this.insertJsdocCommentBefore(sourceFile, updateJSDocHost(node), factory.createJSDocComment(this.createJSDocText(sourceFile, node), factory.createNodeArray(tags)));
  }
  addJSDocTags(sourceFile, parent2, newTags) {
    const oldTags = flatMapToMutable(parent2.jsDoc, (j) => j.tags);
    const unmergedNewTags = newTags.filter(
      (newTag) => !oldTags.some((tag, i) => {
        const merged = tryMergeJsdocTags(tag, newTag);
        if (merged) oldTags[i] = merged;
        return !!merged;
      })
    );
    this.replaceJSDocComment(sourceFile, parent2, [...oldTags, ...unmergedNewTags]);
  }
  filterJSDocTags(sourceFile, parent2, predicate) {
    this.replaceJSDocComment(sourceFile, parent2, filter(flatMapToMutable(parent2.jsDoc, (j) => j.tags), predicate));
  }
  replaceRangeWithText(sourceFile, range, text) {
    this.changes.push({ kind: 3 /* Text */, sourceFile, range, text });
  }
  insertText(sourceFile, pos, text) {
    this.replaceRangeWithText(sourceFile, createRange(pos), text);
  }
  /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */
  tryInsertTypeAnnotation(sourceFile, node, type) {
    let endNode2;
    if (isFunctionLike(node)) {
      endNode2 = findChildOfKind(node, 22 /* CloseParenToken */, sourceFile);
      if (!endNode2) {
        if (!isArrowFunction(node)) return false;
        endNode2 = first(node.parameters);
      }
    } else {
      endNode2 = (node.kind === 260 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken) ?? node.name;
    }
    this.insertNodeAt(sourceFile, endNode2.end, type, { prefix: ": " });
    return true;
  }
  tryInsertThisTypeAnnotation(sourceFile, node, type) {
    const start = findChildOfKind(node, 21 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1;
    const suffix = node.parameters.length ? ", " : "";
    this.insertNodeAt(sourceFile, start, type, { prefix: "this: ", suffix });
  }
  insertTypeParameters(sourceFile, node, typeParameters) {
    const start = (findChildOfKind(node, 21 /* OpenParenToken */, sourceFile) || first(node.parameters)).getStart(sourceFile);
    this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">", joiner: ", " });
  }
  getOptionsForInsertNodeBefore(before, inserted, blankLineBetween) {
    if (isStatement(before) || isClassElement(before)) {
      return { suffix: blankLineBetween ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter };
    } else if (isVariableDeclaration(before)) {
      return { suffix: ", " };
    } else if (isParameter(before)) {
      return isParameter(inserted) ? { suffix: ", " } : {};
    } else if (isStringLiteral(before) && isImportDeclaration(before.parent) || isNamedImports(before)) {
      return { suffix: ", " };
    } else if (isImportSpecifier(before)) {
      return { suffix: "," + (blankLineBetween ? this.newLineCharacter : " ") };
    }
    return Debug.failBadSyntaxKind(before);
  }
  insertNodeAtConstructorStart(sourceFile, ctr, newStatement) {
    const firstStatement = firstOrUndefined(ctr.body.statements);
    if (!firstStatement || !ctr.body.multiLine) {
      this.replaceConstructorBody(sourceFile, ctr, [newStatement, ...ctr.body.statements]);
    } else {
      this.insertNodeBefore(sourceFile, firstStatement, newStatement);
    }
  }
  insertNodeAtConstructorStartAfterSuperCall(sourceFile, ctr, newStatement) {
    const superCallStatement = find(ctr.body.statements, (stmt) => isExpressionStatement(stmt) && isSuperCall(stmt.expression));
    if (!superCallStatement || !ctr.body.multiLine) {
      this.replaceConstructorBody(sourceFile, ctr, [...ctr.body.statements, newStatement]);
    } else {
      this.insertNodeAfter(sourceFile, superCallStatement, newStatement);
    }
  }
  insertNodeAtConstructorEnd(sourceFile, ctr, newStatement) {
    const lastStatement = lastOrUndefined(ctr.body.statements);
    if (!lastStatement || !ctr.body.multiLine) {
      this.replaceConstructorBody(sourceFile, ctr, [...ctr.body.statements, newStatement]);
    } else {
      this.insertNodeAfter(sourceFile, lastStatement, newStatement);
    }
  }
  replaceConstructorBody(sourceFile, ctr, statements) {
    this.replaceNode(sourceFile, ctr.body, factory.createBlock(
      statements,
      /*multiLine*/
      true
    ));
  }
  insertNodeAtEndOfScope(sourceFile, scope, newNode) {
    const pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
    this.insertNodeAt(sourceFile, pos, newNode, {
      prefix: isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
      suffix: this.newLineCharacter
    });
  }
  insertMemberAtStart(sourceFile, node, newElement) {
    this.insertNodeAtStartWorker(sourceFile, node, newElement);
  }
  insertNodeAtObjectStart(sourceFile, obj, newElement) {
    this.insertNodeAtStartWorker(sourceFile, obj, newElement);
  }
  insertNodeAtStartWorker(sourceFile, node, newElement) {
    const indentation = this.guessIndentationFromExistingMembers(sourceFile, node) ?? this.computeIndentationForNewMember(sourceFile, node);
    this.insertNodeAt(sourceFile, getMembersOrProperties(node).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, node, indentation));
  }
  /**
   * Tries to guess the indentation from the existing members of a class/interface/object. All members must be on
   * new lines and must share the same indentation.
   */
  guessIndentationFromExistingMembers(sourceFile, node) {
    let indentation;
    let lastRange = node;
    for (const member of getMembersOrProperties(node)) {
      if (rangeStartPositionsAreOnSameLine(lastRange, member, sourceFile)) {
        return void 0;
      }
      const memberStart = member.getStart(sourceFile);
      const memberIndentation = ts_formatting_exports.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(memberStart, sourceFile), memberStart, sourceFile, this.formatContext.options);
      if (indentation === void 0) {
        indentation = memberIndentation;
      } else if (memberIndentation !== indentation) {
        return void 0;
      }
      lastRange = member;
    }
    return indentation;
  }
  computeIndentationForNewMember(sourceFile, node) {
    const nodeStart = node.getStart(sourceFile);
    return ts_formatting_exports.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(nodeStart, sourceFile), nodeStart, sourceFile, this.formatContext.options) + (this.formatContext.options.indentSize ?? 4);
  }
  getInsertNodeAtStartInsertOptions(sourceFile, node, indentation) {
    const members = getMembersOrProperties(node);
    const isEmpty = members.length === 0;
    const isFirstInsertion = !this.classesWithNodesInsertedAtStart.has(getNodeId(node));
    if (isFirstInsertion) {
      this.classesWithNodesInsertedAtStart.set(getNodeId(node), { node, sourceFile });
    }
    const insertTrailingComma = isObjectLiteralExpression(node) && (!isJsonSourceFile(sourceFile) || !isEmpty);
    const insertLeadingComma = isObjectLiteralExpression(node) && isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion;
    return {
      indentation,
      prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter,
      suffix: insertTrailingComma ? "," : isInterfaceDeclaration(node) && isEmpty ? ";" : ""
    };
  }
  insertNodeAfterComma(sourceFile, after, newNode) {
    const endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode);
    this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
  }
  insertNodeAfter(sourceFile, after, newNode) {
    const endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
    this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
  }
  insertNodeAtEndOfList(sourceFile, list, newNode) {
    this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " });
  }
  insertNodesAfter(sourceFile, after, newNodes) {
    const endPosition = this.insertNodeAfterWorker(sourceFile, after, first(newNodes));
    this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after));
  }
  insertNodeAfterWorker(sourceFile, after, newNode) {
    if (needSemicolonBetween(after, newNode)) {
      if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) {
        this.replaceRange(sourceFile, createRange(after.end), factory.createToken(27 /* SemicolonToken */));
      }
    }
    const endPosition = getAdjustedEndPosition(sourceFile, after, {});
    return endPosition;
  }
  getInsertNodeAfterOptions(sourceFile, after) {
    const options = this.getInsertNodeAfterOptionsWorker(after);
    return {
      ...options,
      prefix: after.end === sourceFile.end && isStatement(after) ? options.prefix ? `
${options.prefix}` : "\n" : options.prefix
    };
  }
  getInsertNodeAfterOptionsWorker(node) {
    switch (node.kind) {
      case 263 /* ClassDeclaration */:
      case 267 /* ModuleDeclaration */:
        return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
      case 260 /* VariableDeclaration */:
      case 11 /* StringLiteral */:
      case 80 /* Identifier */:
        return { prefix: ", " };
      case 303 /* PropertyAssignment */:
        return { suffix: "," + this.newLineCharacter };
      case 95 /* ExportKeyword */:
        return { prefix: " " };
      case 169 /* Parameter */:
        return {};
      default:
        Debug.assert(isStatement(node) || isClassOrTypeElement(node));
        return { suffix: this.newLineCharacter };
    }
  }
  insertName(sourceFile, node, name) {
    Debug.assert(!node.name);
    if (node.kind === 219 /* ArrowFunction */) {
      const arrow = findChildOfKind(node, 39 /* EqualsGreaterThanToken */, sourceFile);
      const lparen = findChildOfKind(node, 21 /* OpenParenToken */, sourceFile);
      if (lparen) {
        this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [factory.createToken(100 /* FunctionKeyword */), factory.createIdentifier(name)], { joiner: " " });
        deleteNode(this, sourceFile, arrow);
      } else {
        this.insertText(sourceFile, first(node.parameters).getStart(sourceFile), `function ${name}(`);
        this.replaceRange(sourceFile, arrow, factory.createToken(22 /* CloseParenToken */));
      }
      if (node.body.kind !== 241 /* Block */) {
        this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [factory.createToken(19 /* OpenBraceToken */), factory.createToken(107 /* ReturnKeyword */)], { joiner: " ", suffix: " " });
        this.insertNodesAt(sourceFile, node.body.end, [factory.createToken(27 /* SemicolonToken */), factory.createToken(20 /* CloseBraceToken */)], { joiner: " " });
      }
    } else {
      const pos = findChildOfKind(node, node.kind === 218 /* FunctionExpression */ ? 100 /* FunctionKeyword */ : 86 /* ClassKeyword */, sourceFile).end;
      this.insertNodeAt(sourceFile, pos, factory.createIdentifier(name), { prefix: " " });
    }
  }
  insertExportModifier(sourceFile, node) {
    this.insertText(sourceFile, node.getStart(sourceFile), "export ");
  }
  insertImportSpecifierAtIndex(sourceFile, importSpecifier, namedImports, index) {
    const prevSpecifier = namedImports.elements[index - 1];
    if (prevSpecifier) {
      this.insertNodeInListAfter(sourceFile, prevSpecifier, importSpecifier);
    } else {
      this.insertNodeBefore(
        sourceFile,
        namedImports.elements[0],
        importSpecifier,
        !positionsAreOnSameLine(namedImports.elements[0].getStart(), namedImports.parent.parent.getStart(), sourceFile)
      );
    }
  }
  /**
   * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
   * i.e. arguments in arguments lists, parameters in parameter lists etc.
   * Note that separators are part of the node in statements and class elements.
   */
  insertNodeInListAfter(sourceFile, after, newNode, containingList = ts_formatting_exports.SmartIndenter.getContainingList(after, sourceFile)) {
    if (!containingList) {
      Debug.fail("node is not a list element");
      return;
    }
    const index = indexOfNode(containingList, after);
    if (index < 0) {
      return;
    }
    const end = after.getEnd();
    if (index !== containingList.length - 1) {
      const nextToken = getTokenAtPosition(sourceFile, after.end);
      if (nextToken && isSeparator(after, nextToken)) {
        const nextNode = containingList[index + 1];
        const startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart());
        const suffix = `${tokenToString(nextToken.kind)}${sourceFile.text.substring(nextToken.end, startPos)}`;
        this.insertNodesAt(sourceFile, startPos, [newNode], { suffix });
      }
    } else {
      const afterStart = after.getStart(sourceFile);
      const afterStartLinePosition = getLineStartPositionForPosition(afterStart, sourceFile);
      let separator;
      let multilineList = false;
      if (containingList.length === 1) {
        separator = 28 /* CommaToken */;
      } else {
        const tokenBeforeInsertPosition = findPrecedingToken(after.pos, sourceFile);
        separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 28 /* CommaToken */;
        const afterMinusOneStartLinePosition = getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile);
        multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition;
      }
      if (hasCommentsBeforeLineBreak(sourceFile.text, after.end) || !positionsAreOnSameLine(containingList.pos, containingList.end, sourceFile)) {
        multilineList = true;
      }
      if (multilineList) {
        this.replaceRange(sourceFile, createRange(end), factory.createToken(separator));
        const indentation = ts_formatting_exports.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options);
        let insertPos = skipTrivia(
          sourceFile.text,
          end,
          /*stopAfterLineBreak*/
          true,
          /*stopAtComments*/
          false
        );
        while (insertPos !== end && isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) {
          insertPos--;
        }
        this.replaceRange(sourceFile, createRange(insertPos), newNode, { indentation, prefix: this.newLineCharacter });
      } else {
        this.replaceRange(sourceFile, createRange(end), newNode, { prefix: `${tokenToString(separator)} ` });
      }
    }
  }
  parenthesizeExpression(sourceFile, expression) {
    this.replaceRange(sourceFile, rangeOfNode(expression), factory.createParenthesizedExpression(expression));
  }
  finishClassesWithNodesInsertedAtStart() {
    this.classesWithNodesInsertedAtStart.forEach(({ node, sourceFile }) => {
      const [openBraceEnd, closeBraceEnd] = getClassOrObjectBraceEnds(node, sourceFile);
      if (openBraceEnd !== void 0 && closeBraceEnd !== void 0) {
        const isEmpty = getMembersOrProperties(node).length === 0;
        const isSingleLine = positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile);
        if (isEmpty && isSingleLine && openBraceEnd !== closeBraceEnd - 1) {
          this.deleteRange(sourceFile, createRange(openBraceEnd, closeBraceEnd - 1));
        }
        if (isSingleLine) {
          this.insertText(sourceFile, closeBraceEnd - 1, this.newLineCharacter);
        }
      }
    });
  }
  finishDeleteDeclarations() {
    const deletedNodesInLists = /* @__PURE__ */ new Set();
    for (const { sourceFile, node } of this.deletedNodes) {
      if (!this.deletedNodes.some((d) => d.sourceFile === sourceFile && rangeContainsRangeExclusive(d.node, node))) {
        if (isArray(node)) {
          this.deleteRange(sourceFile, rangeOfTypeParameters(sourceFile, node));
        } else {
          deleteDeclaration.deleteDeclaration(this, deletedNodesInLists, sourceFile, node);
        }
      }
    }
    deletedNodesInLists.forEach((node) => {
      const sourceFile = node.getSourceFile();
      const list = ts_formatting_exports.SmartIndenter.getContainingList(node, sourceFile);
      if (node !== last(list)) return;
      const lastNonDeletedIndex = findLastIndex(list, (n) => !deletedNodesInLists.has(n), list.length - 2);
      if (lastNonDeletedIndex !== -1) {
        this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) });
      }
    });
  }
  /**
   * Note: after calling this, the TextChanges object must be discarded!
   * @param validate only for tests
   *    The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions,
   *    so we can only call this once and can't get the non-formatted text separately.
   */
  getChanges(validate) {
    this.finishDeleteDeclarations();
    this.finishClassesWithNodesInsertedAtStart();
    const changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
    if (this.newFileChanges) {
      this.newFileChanges.forEach((insertions, fileName) => {
        changes.push(changesToText.newFileChanges(fileName, insertions, this.newLineCharacter, this.formatContext));
      });
    }
    return changes;
  }
  createNewFile(oldFile, fileName, statements) {
    this.insertStatementsInNewFile(fileName, statements, oldFile);
  }
};
function updateJSDocHost(parent2) {
  if (parent2.kind !== 219 /* ArrowFunction */) {
    return parent2;
  }
  const jsDocNode = parent2.parent.kind === 172 /* PropertyDeclaration */ ? parent2.parent : parent2.parent.parent;
  jsDocNode.jsDoc = parent2.jsDoc;
  return jsDocNode;
}
function tryMergeJsdocTags(oldTag, newTag) {
  if (oldTag.kind !== newTag.kind) {
    return void 0;
  }
  switch (oldTag.kind) {
    case 341 /* JSDocParameterTag */: {
      const oldParam = oldTag;
      const newParam = newTag;
      return isIdentifier(oldParam.name) && isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? factory.createJSDocParameterTag(
        /*tagName*/
        void 0,
        newParam.name,
        /*isBracketed*/
        false,
        newParam.typeExpression,
        newParam.isNameFirst,
        oldParam.comment
      ) : void 0;
    }
    case 342 /* JSDocReturnTag */:
      return factory.createJSDocReturnTag(
        /*tagName*/
        void 0,
        newTag.typeExpression,
        oldTag.comment
      );
    case 344 /* JSDocTypeTag */:
      return factory.createJSDocTypeTag(
        /*tagName*/
        void 0,
        newTag.typeExpression,
        oldTag.comment
      );
  }
}
function startPositionToDeleteNodeInList(sourceFile, node) {
  return skipTrivia(
    sourceFile.text,
    getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: 1 /* IncludeAll */ }),
    /*stopAfterLineBreak*/
    false,
    /*stopAtComments*/
    true
  );
}
function endPositionToDeleteNodeInList(sourceFile, node, prevNode, nextNode) {
  const end = startPositionToDeleteNodeInList(sourceFile, nextNode);
  if (prevNode === void 0 || positionsAreOnSameLine(getAdjustedEndPosition(sourceFile, node, {}), end, sourceFile)) {
    return end;
  }
  const token = findPrecedingToken(nextNode.getStart(sourceFile), sourceFile);
  if (isSeparator(node, token)) {
    const prevToken = findPrecedingToken(node.getStart(sourceFile), sourceFile);
    if (isSeparator(prevNode, prevToken)) {
      const pos = skipTrivia(
        sourceFile.text,
        token.getEnd(),
        /*stopAfterLineBreak*/
        true,
        /*stopAtComments*/
        true
      );
      if (positionsAreOnSameLine(prevToken.getStart(sourceFile), token.getStart(sourceFile), sourceFile)) {
        return isLineBreak(sourceFile.text.charCodeAt(pos - 1)) ? pos - 1 : pos;
      }
      if (isLineBreak(sourceFile.text.charCodeAt(pos))) {
        return pos;
      }
    }
  }
  return end;
}
function getClassOrObjectBraceEnds(cls, sourceFile) {
  const open = findChildOfKind(cls, 19 /* OpenBraceToken */, sourceFile);
  const close = findChildOfKind(cls, 20 /* CloseBraceToken */, sourceFile);
  return [open == null ? void 0 : open.end, close == null ? void 0 : close.end];
}
function getMembersOrProperties(node) {
  return isObjectLiteralExpression(node) ? node.properties : node.members;
}
var changesToText;
((changesToText2) => {
  function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) {
    return mapDefined(group(changes, (c) => c.sourceFile.path), (changesInFile) => {
      const sourceFile = changesInFile[0].sourceFile;
      const normalized = toSorted(changesInFile, (a, b) => a.range.pos - b.range.pos || a.range.end - b.range.end);
      for (let i = 0; i < normalized.length - 1; i++) {
        Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", () => `${JSON.stringify(normalized[i].range)} and ${JSON.stringify(normalized[i + 1].range)}`);
      }
      const textChanges2 = mapDefined(normalized, (c) => {
        const span = createTextSpanFromRange(c.range);
        const targetSourceFile = c.kind === 1 /* ReplaceWithSingleNode */ ? getSourceFileOfNode(getOriginalNode(c.node)) ?? c.sourceFile : c.kind === 2 /* ReplaceWithMultipleNodes */ ? getSourceFileOfNode(getOriginalNode(c.nodes[0])) ?? c.sourceFile : c.sourceFile;
        const newText = computeNewText(c, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate);
        if (span.length === newText.length && stringContainsAt(targetSourceFile.text, newText, span.start)) {
          return void 0;
        }
        return createTextChange(span, newText);
      });
      return textChanges2.length > 0 ? { fileName: sourceFile.fileName, textChanges: textChanges2 } : void 0;
    });
  }
  changesToText2.getTextChangesFromChanges = getTextChangesFromChanges;
  function newFileChanges(fileName, insertions, newLineCharacter, formatContext) {
    const text = newFileChangesWorker(getScriptKindFromFileName(fileName), insertions, newLineCharacter, formatContext);
    return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true };
  }
  changesToText2.newFileChanges = newFileChanges;
  function newFileChangesWorker(scriptKind, insertions, newLineCharacter, formatContext) {
    const nonFormattedText = flatMap(insertions, (insertion) => insertion.statements.map((s) => s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, insertion.oldFile, newLineCharacter).text)).join(newLineCharacter);
    const sourceFile = createSourceFile(
      "any file name",
      nonFormattedText,
      { languageVersion: 99 /* ESNext */, jsDocParsingMode: 1 /* ParseNone */ },
      /*setParentNodes*/
      true,
      scriptKind
    );
    const changes = ts_formatting_exports.formatDocument(sourceFile, formatContext);
    return applyChanges(nonFormattedText, changes) + newLineCharacter;
  }
  changesToText2.newFileChangesWorker = newFileChangesWorker;
  function computeNewText(change, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate) {
    var _a;
    if (change.kind === 0 /* Remove */) {
      return "";
    }
    if (change.kind === 3 /* Text */) {
      return change.text;
    }
    const { options = {}, range: { pos } } = change;
    const format = (n) => getFormattedTextOfNode(n, targetSourceFile, sourceFile, pos, options, newLineCharacter, formatContext, validate);
    const text = change.kind === 2 /* ReplaceWithMultipleNodes */ ? change.nodes.map((n) => removeSuffix(format(n), newLineCharacter)).join(((_a = change.options) == null ? void 0 : _a.joiner) || newLineCharacter) : format(change.node);
    const noIndent = options.indentation !== void 0 || getLineStartPositionForPosition(pos, targetSourceFile) === pos ? text : text.replace(/^\s+/, "");
    return (options.prefix || "") + noIndent + (!options.suffix || endsWith(noIndent, options.suffix) ? "" : options.suffix);
  }
  function getFormattedTextOfNode(nodeIn, targetSourceFile, sourceFile, pos, { indentation, prefix, delta }, newLineCharacter, formatContext, validate) {
    const { node, text } = getNonformattedText(nodeIn, targetSourceFile, newLineCharacter);
    if (validate) validate(node, text);
    const formatOptions = getFormatCodeSettingsForWriting(formatContext, targetSourceFile);
    const initialIndentation = indentation !== void 0 ? indentation : ts_formatting_exports.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, targetSourceFile) === pos);
    if (delta === void 0) {
      delta = ts_formatting_exports.SmartIndenter.shouldIndentChildNode(formatOptions, nodeIn) ? formatOptions.indentSize || 0 : 0;
    }
    const file = {
      text,
      getLineAndCharacterOfPosition(pos2) {
        return getLineAndCharacterOfPosition(this, pos2);
      }
    };
    const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, targetSourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions });
    return applyChanges(text, changes);
  }
  function getNonformattedText(node, sourceFile, newLineCharacter) {
    const writer = createWriter(newLineCharacter);
    const newLine = getNewLineKind(newLineCharacter);
    createPrinter({
      newLine,
      neverAsciiEscape: true,
      preserveSourceNewlines: true,
      terminateUnterminatedLiterals: true
    }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer);
    return { text: writer.getText(), node: assignPositionsToNode(node) };
  }
  changesToText2.getNonformattedText = getNonformattedText;
})(changesToText || (changesToText = {}));
function applyChanges(text, changes) {
  for (let i = changes.length - 1; i >= 0; i--) {
    const { span, newText } = changes[i];
    text = `${text.substring(0, span.start)}${newText}${text.substring(textSpanEnd(span))}`;
  }
  return text;
}
function isTrivia2(s) {
  return skipTrivia(s, 0) === s.length;
}
var textChangesTransformationContext = {
  ...nullTransformationContext,
  factory: createNodeFactory(
    nullTransformationContext.factory.flags | 1 /* NoParenthesizerRules */,
    nullTransformationContext.factory.baseFactory
  )
};
function assignPositionsToNode(node) {
  const visited = visitEachChild(node, assignPositionsToNode, textChangesTransformationContext, assignPositionsToNodeArray, assignPositionsToNode);
  const newNode = nodeIsSynthesized(visited) ? visited : Object.create(visited);
  setTextRangePosEnd(newNode, getPos2(node), getEnd(node));
  return newNode;
}
function assignPositionsToNodeArray(nodes, visitor, test, start, count) {
  const visited = visitNodes2(nodes, visitor, test, start, count);
  if (!visited) {
    return visited;
  }
  Debug.assert(nodes);
  const nodeArray = visited === nodes ? factory.createNodeArray(visited.slice(0)) : visited;
  setTextRangePosEnd(nodeArray, getPos2(nodes), getEnd(nodes));
  return nodeArray;
}
function createWriter(newLine) {
  let lastNonTriviaPosition = 0;
  const writer = createTextWriter(newLine);
  const onBeforeEmitNode = (node) => {
    if (node) {
      setPos(node, lastNonTriviaPosition);
    }
  };
  const onAfterEmitNode = (node) => {
    if (node) {
      setEnd(node, lastNonTriviaPosition);
    }
  };
  const onBeforeEmitNodeArray = (nodes) => {
    if (nodes) {
      setPos(nodes, lastNonTriviaPosition);
    }
  };
  const onAfterEmitNodeArray = (nodes) => {
    if (nodes) {
      setEnd(nodes, lastNonTriviaPosition);
    }
  };
  const onBeforeEmitToken = (node) => {
    if (node) {
      setPos(node, lastNonTriviaPosition);
    }
  };
  const onAfterEmitToken = (node) => {
    if (node) {
      setEnd(node, lastNonTriviaPosition);
    }
  };
  function setLastNonTriviaPosition(s, force) {
    if (force || !isTrivia2(s)) {
      lastNonTriviaPosition = writer.getTextPos();
      let i = 0;
      while (isWhiteSpaceLike(s.charCodeAt(s.length - i - 1))) {
        i++;
      }
      lastNonTriviaPosition -= i;
    }
  }
  function write(s) {
    writer.write(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeComment(s) {
    writer.writeComment(s);
  }
  function writeKeyword(s) {
    writer.writeKeyword(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeOperator(s) {
    writer.writeOperator(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writePunctuation(s) {
    writer.writePunctuation(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeTrailingSemicolon(s) {
    writer.writeTrailingSemicolon(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeParameter(s) {
    writer.writeParameter(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeProperty(s) {
    writer.writeProperty(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeSpace(s) {
    writer.writeSpace(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeStringLiteral(s) {
    writer.writeStringLiteral(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeSymbol(s, sym) {
    writer.writeSymbol(s, sym);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeLine(force) {
    writer.writeLine(force);
  }
  function increaseIndent() {
    writer.increaseIndent();
  }
  function decreaseIndent() {
    writer.decreaseIndent();
  }
  function getText() {
    return writer.getText();
  }
  function rawWrite(s) {
    writer.rawWrite(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeLiteral(s) {
    writer.writeLiteral(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      true
    );
  }
  function getTextPos() {
    return writer.getTextPos();
  }
  function getLine() {
    return writer.getLine();
  }
  function getColumn() {
    return writer.getColumn();
  }
  function getIndent() {
    return writer.getIndent();
  }
  function isAtStartOfLine() {
    return writer.isAtStartOfLine();
  }
  function clear2() {
    writer.clear();
    lastNonTriviaPosition = 0;
  }
  return {
    onBeforeEmitNode,
    onAfterEmitNode,
    onBeforeEmitNodeArray,
    onAfterEmitNodeArray,
    onBeforeEmitToken,
    onAfterEmitToken,
    write,
    writeComment,
    writeKeyword,
    writeOperator,
    writePunctuation,
    writeTrailingSemicolon,
    writeParameter,
    writeProperty,
    writeSpace,
    writeStringLiteral,
    writeSymbol,
    writeLine,
    increaseIndent,
    decreaseIndent,
    getText,
    rawWrite,
    writeLiteral,
    getTextPos,
    getLine,
    getColumn,
    getIndent,
    isAtStartOfLine,
    hasTrailingComment: () => writer.hasTrailingComment(),
    hasTrailingWhitespace: () => writer.hasTrailingWhitespace(),
    clear: clear2
  };
}
function getInsertionPositionAtSourceFileTop(sourceFile) {
  let lastPrologue;
  for (const node of sourceFile.statements) {
    if (isPrologueDirective(node)) {
      lastPrologue = node;
    } else {
      break;
    }
  }
  let position = 0;
  const text = sourceFile.text;
  if (lastPrologue) {
    position = lastPrologue.end;
    advancePastLineBreak();
    return position;
  }
  const shebang = getShebang(text);
  if (shebang !== void 0) {
    position = shebang.length;
    advancePastLineBreak();
  }
  const ranges = getLeadingCommentRanges(text, position);
  if (!ranges) return position;
  let lastComment;
  let firstNodeLine;
  for (const range of ranges) {
    if (range.kind === 3 /* MultiLineCommentTrivia */) {
      if (isPinnedComment(text, range.pos)) {
        lastComment = { range, pinnedOrTripleSlash: true };
        continue;
      }
    } else if (isRecognizedTripleSlashComment(text, range.pos, range.end)) {
      lastComment = { range, pinnedOrTripleSlash: true };
      continue;
    }
    if (lastComment) {
      if (lastComment.pinnedOrTripleSlash) break;
      const commentLine = sourceFile.getLineAndCharacterOfPosition(range.pos).line;
      const lastCommentEndLine = sourceFile.getLineAndCharacterOfPosition(lastComment.range.end).line;
      if (commentLine >= lastCommentEndLine + 2) break;
    }
    if (sourceFile.statements.length) {
      if (firstNodeLine === void 0) firstNodeLine = sourceFile.getLineAndCharacterOfPosition(sourceFile.statements[0].getStart()).line;
      const commentEndLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
      if (firstNodeLine < commentEndLine + 2) break;
    }
    lastComment = { range, pinnedOrTripleSlash: false };
  }
  if (lastComment) {
    position = lastComment.range.end;
    advancePastLineBreak();
  }
  return position;
  function advancePastLineBreak() {
    if (position < text.length) {
      const charCode = text.charCodeAt(position);
      if (isLineBreak(charCode)) {
        position++;
        if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) {
          position++;
        }
      }
    }
  }
}
function isValidLocationToAddComment(sourceFile, position) {
  return !isInComment(sourceFile, position) && !isInString(sourceFile, position) && !isInTemplateString(sourceFile, position) && !isInJSXText(sourceFile, position);
}
function needSemicolonBetween(a, b) {
  return (isPropertySignature(a) || isPropertyDeclaration(a)) && isClassOrTypeElement(b) && b.name.kind === 167 /* ComputedPropertyName */ || isStatementButNotDeclaration(a) && isStatementButNotDeclaration(b);
}
var deleteDeclaration;
((_deleteDeclaration) => {
  function deleteDeclaration2(changes, deletedNodesInLists, sourceFile, node) {
    switch (node.kind) {
      case 169 /* Parameter */: {
        const oldFunction = node.parent;
        if (isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && !findChildOfKind(oldFunction, 21 /* OpenParenToken */, sourceFile)) {
          changes.replaceNodeWithText(sourceFile, node, "()");
        } else {
          deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
        }
        break;
      }
      case 272 /* ImportDeclaration */:
      case 271 /* ImportEqualsDeclaration */:
        const isFirstImport = sourceFile.imports.length && node === first(sourceFile.imports).parent || node === find(sourceFile.statements, isAnyImportSyntax);
        deleteNode(changes, sourceFile, node, {
          leadingTriviaOption: isFirstImport ? 0 /* Exclude */ : hasJSDocNodes(node) ? 2 /* JSDoc */ : 3 /* StartLine */
        });
        break;
      case 208 /* BindingElement */:
        const pattern = node.parent;
        const preserveComma = pattern.kind === 207 /* ArrayBindingPattern */ && node !== last(pattern.elements);
        if (preserveComma) {
          deleteNode(changes, sourceFile, node);
        } else {
          deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
        }
        break;
      case 260 /* VariableDeclaration */:
        deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node);
        break;
      case 168 /* TypeParameter */:
        deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
        break;
      case 276 /* ImportSpecifier */:
        const namedImports = node.parent;
        if (namedImports.elements.length === 1) {
          deleteImportBinding(changes, sourceFile, namedImports);
        } else {
          deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
        }
        break;
      case 274 /* NamespaceImport */:
        deleteImportBinding(changes, sourceFile, node);
        break;
      case 27 /* SemicolonToken */:
        deleteNode(changes, sourceFile, node, { trailingTriviaOption: 0 /* Exclude */ });
        break;
      case 100 /* FunctionKeyword */:
        deleteNode(changes, sourceFile, node, { leadingTriviaOption: 0 /* Exclude */ });
        break;
      case 263 /* ClassDeclaration */:
      case 262 /* FunctionDeclaration */:
        deleteNode(changes, sourceFile, node, { leadingTriviaOption: hasJSDocNodes(node) ? 2 /* JSDoc */ : 3 /* StartLine */ });
        break;
      default:
        if (!node.parent) {
          deleteNode(changes, sourceFile, node);
        } else if (isImportClause(node.parent) && node.parent.name === node) {
          deleteDefaultImport(changes, sourceFile, node.parent);
        } else if (isCallExpression(node.parent) && contains(node.parent.arguments, node)) {
          deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
        } else {
          deleteNode(changes, sourceFile, node);
        }
    }
  }
  _deleteDeclaration.deleteDeclaration = deleteDeclaration2;
  function deleteDefaultImport(changes, sourceFile, importClause) {
    if (!importClause.namedBindings) {
      deleteNode(changes, sourceFile, importClause.parent);
    } else {
      const start = importClause.name.getStart(sourceFile);
      const nextToken = getTokenAtPosition(sourceFile, importClause.name.end);
      if (nextToken && nextToken.kind === 28 /* CommaToken */) {
        const end = skipTrivia(
          sourceFile.text,
          nextToken.end,
          /*stopAfterLineBreak*/
          false,
          /*stopAtComments*/
          true
        );
        changes.deleteRange(sourceFile, { pos: start, end });
      } else {
        deleteNode(changes, sourceFile, importClause.name);
      }
    }
  }
  function deleteImportBinding(changes, sourceFile, node) {
    if (node.parent.name) {
      const previousToken = Debug.checkDefined(getTokenAtPosition(sourceFile, node.pos - 1));
      changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end });
    } else {
      const importDecl = getAncestor(node, 272 /* ImportDeclaration */);
      deleteNode(changes, sourceFile, importDecl);
    }
  }
  function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) {
    const { parent: parent2 } = node;
    if (parent2.kind === 299 /* CatchClause */) {
      changes.deleteNodeRange(sourceFile, findChildOfKind(parent2, 21 /* OpenParenToken */, sourceFile), findChildOfKind(parent2, 22 /* CloseParenToken */, sourceFile));
      return;
    }
    if (parent2.declarations.length !== 1) {
      deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
      return;
    }
    const gp = parent2.parent;
    switch (gp.kind) {
      case 250 /* ForOfStatement */:
      case 249 /* ForInStatement */:
        changes.replaceNode(sourceFile, node, factory.createObjectLiteralExpression());
        break;
      case 248 /* ForStatement */:
        deleteNode(changes, sourceFile, parent2);
        break;
      case 243 /* VariableStatement */:
        deleteNode(changes, sourceFile, gp, { leadingTriviaOption: hasJSDocNodes(gp) ? 2 /* JSDoc */ : 3 /* StartLine */ });
        break;
      default:
        Debug.assertNever(gp);
    }
  }
})(deleteDeclaration || (deleteDeclaration = {}));
function deleteNode(changes, sourceFile, node, options = { leadingTriviaOption: 1 /* IncludeAll */ }) {
  const startPosition = getAdjustedStartPosition(sourceFile, node, options);
  const endPosition = getAdjustedEndPosition(sourceFile, node, options);
  changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) {
  const containingList = Debug.checkDefined(ts_formatting_exports.SmartIndenter.getContainingList(node, sourceFile));
  const index = indexOfNode(containingList, node);
  Debug.assert(index !== -1);
  if (containingList.length === 1) {
    deleteNode(changes, sourceFile, node);
    return;
  }
  Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice");
  deletedNodesInLists.add(node);
  changes.deleteRange(sourceFile, {
    pos: startPositionToDeleteNodeInList(sourceFile, node),
    end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : endPositionToDeleteNodeInList(sourceFile, node, containingList[index - 1], containingList[index + 1])
  });
}

// src/services/_namespaces/ts.formatting.ts
var ts_formatting_exports = {};
__export(ts_formatting_exports, {
  FormattingContext: () => FormattingContext,
  FormattingRequestKind: () => FormattingRequestKind,
  RuleAction: () => RuleAction,
  RuleFlags: () => RuleFlags,
  SmartIndenter: () => SmartIndenter,
  anyContext: () => anyContext,
  createTextRangeWithKind: () => createTextRangeWithKind,
  formatDocument: () => formatDocument,
  formatNodeGivenIndentation: () => formatNodeGivenIndentation,
  formatOnClosingCurly: () => formatOnClosingCurly,
  formatOnEnter: () => formatOnEnter,
  formatOnOpeningCurly: () => formatOnOpeningCurly,
  formatOnSemicolon: () => formatOnSemicolon,
  formatSelection: () => formatSelection,
  getAllRules: () => getAllRules,
  getFormatContext: () => getFormatContext,
  getFormattingScanner: () => getFormattingScanner,
  getIndentationString: () => getIndentationString,
  getRangeOfEnclosingComment: () => getRangeOfEnclosingComment
});

// src/services/formatting/formattingContext.ts
var FormattingRequestKind = /* @__PURE__ */ ((FormattingRequestKind2) => {
  FormattingRequestKind2[FormattingRequestKind2["FormatDocument"] = 0] = "FormatDocument";
  FormattingRequestKind2[FormattingRequestKind2["FormatSelection"] = 1] = "FormatSelection";
  FormattingRequestKind2[FormattingRequestKind2["FormatOnEnter"] = 2] = "FormatOnEnter";
  FormattingRequestKind2[FormattingRequestKind2["FormatOnSemicolon"] = 3] = "FormatOnSemicolon";
  FormattingRequestKind2[FormattingRequestKind2["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace";
  FormattingRequestKind2[FormattingRequestKind2["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace";
  return FormattingRequestKind2;
})(FormattingRequestKind || {});
var FormattingContext = class {
  constructor(sourceFile, formattingRequestKind, options) {
    this.sourceFile = sourceFile;
    this.formattingRequestKind = formattingRequestKind;
    this.options = options;
  }
  updateContext(currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) {
    this.currentTokenSpan = Debug.checkDefined(currentRange);
    this.currentTokenParent = Debug.checkDefined(currentTokenParent);
    this.nextTokenSpan = Debug.checkDefined(nextRange);
    this.nextTokenParent = Debug.checkDefined(nextTokenParent);
    this.contextNode = Debug.checkDefined(commonParent);
    this.contextNodeAllOnSameLine = void 0;
    this.nextNodeAllOnSameLine = void 0;
    this.tokensAreOnSameLine = void 0;
    this.contextNodeBlockIsOnOneLine = void 0;
    this.nextNodeBlockIsOnOneLine = void 0;
  }
  ContextNodeAllOnSameLine() {
    if (this.contextNodeAllOnSameLine === void 0) {
      this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode);
    }
    return this.contextNodeAllOnSameLine;
  }
  NextNodeAllOnSameLine() {
    if (this.nextNodeAllOnSameLine === void 0) {
      this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent);
    }
    return this.nextNodeAllOnSameLine;
  }
  TokensAreOnSameLine() {
    if (this.tokensAreOnSameLine === void 0) {
      const startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line;
      const endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line;
      this.tokensAreOnSameLine = startLine === endLine;
    }
    return this.tokensAreOnSameLine;
  }
  ContextNodeBlockIsOnOneLine() {
    if (this.contextNodeBlockIsOnOneLine === void 0) {
      this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode);
    }
    return this.contextNodeBlockIsOnOneLine;
  }
  NextNodeBlockIsOnOneLine() {
    if (this.nextNodeBlockIsOnOneLine === void 0) {
      this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent);
    }
    return this.nextNodeBlockIsOnOneLine;
  }
  NodeIsOnOneLine(node) {
    const startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line;
    const endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
    return startLine === endLine;
  }
  BlockIsOnOneLine(node) {
    const openBrace = findChildOfKind(node, 19 /* OpenBraceToken */, this.sourceFile);
    const closeBrace = findChildOfKind(node, 20 /* CloseBraceToken */, this.sourceFile);
    if (openBrace && closeBrace) {
      const startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line;
      const endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line;
      return startLine === endLine;
    }
    return false;
  }
};

// src/services/formatting/formattingScanner.ts
var standardScanner = createScanner(
  99 /* Latest */,
  /*skipTrivia*/
  false,
  0 /* Standard */
);
var jsxScanner = createScanner(
  99 /* Latest */,
  /*skipTrivia*/
  false,
  1 /* JSX */
);
function getFormattingScanner(text, languageVariant, startPos, endPos, cb) {
  const scanner2 = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner;
  scanner2.setText(text);
  scanner2.resetTokenState(startPos);
  let wasNewLine = true;
  let leadingTrivia;
  let trailingTrivia;
  let savedPos;
  let lastScanAction;
  let lastTokenInfo;
  const res = cb({
    advance,
    readTokenInfo,
    readEOFTokenRange,
    isOnToken,
    isOnEOF,
    getCurrentLeadingTrivia: () => leadingTrivia,
    lastTrailingTriviaWasNewLine: () => wasNewLine,
    skipToEndOf,
    skipToStartOf,
    getTokenFullStart: () => (lastTokenInfo == null ? void 0 : lastTokenInfo.token.pos) ?? scanner2.getTokenStart(),
    getStartPos: () => (lastTokenInfo == null ? void 0 : lastTokenInfo.token.pos) ?? scanner2.getTokenStart()
  });
  lastTokenInfo = void 0;
  scanner2.setText(void 0);
  return res;
  function advance() {
    lastTokenInfo = void 0;
    const isStarted = scanner2.getTokenFullStart() !== startPos;
    if (isStarted) {
      wasNewLine = !!trailingTrivia && last(trailingTrivia).kind === 4 /* NewLineTrivia */;
    } else {
      scanner2.scan();
    }
    leadingTrivia = void 0;
    trailingTrivia = void 0;
    let pos = scanner2.getTokenFullStart();
    while (pos < endPos) {
      const t = scanner2.getToken();
      if (!isTrivia(t)) {
        break;
      }
      scanner2.scan();
      const item = {
        pos,
        end: scanner2.getTokenFullStart(),
        kind: t
      };
      pos = scanner2.getTokenFullStart();
      leadingTrivia = append(leadingTrivia, item);
    }
    savedPos = scanner2.getTokenFullStart();
  }
  function shouldRescanGreaterThanToken(node) {
    switch (node.kind) {
      case 34 /* GreaterThanEqualsToken */:
      case 72 /* GreaterThanGreaterThanEqualsToken */:
      case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
      case 50 /* GreaterThanGreaterThanGreaterThanToken */:
      case 49 /* GreaterThanGreaterThanToken */:
        return true;
    }
    return false;
  }
  function shouldRescanJsxIdentifier(node) {
    if (node.parent) {
      switch (node.parent.kind) {
        case 291 /* JsxAttribute */:
        case 286 /* JsxOpeningElement */:
        case 287 /* JsxClosingElement */:
        case 285 /* JsxSelfClosingElement */:
          return isKeyword(node.kind) || node.kind === 80 /* Identifier */;
      }
    }
    return false;
  }
  function shouldRescanJsxText(node) {
    return isJsxText(node) || isJsxElement(node) && (lastTokenInfo == null ? void 0 : lastTokenInfo.token.kind) === 12 /* JsxText */;
  }
  function shouldRescanSlashToken(container) {
    return container.kind === 14 /* RegularExpressionLiteral */;
  }
  function shouldRescanTemplateToken(container) {
    return container.kind === 17 /* TemplateMiddle */ || container.kind === 18 /* TemplateTail */;
  }
  function shouldRescanJsxAttributeValue(node) {
    return node.parent && isJsxAttribute(node.parent) && node.parent.initializer === node;
  }
  function startsWithSlashToken(t) {
    return t === 44 /* SlashToken */ || t === 69 /* SlashEqualsToken */;
  }
  function readTokenInfo(n) {
    Debug.assert(isOnToken());
    const expectedScanAction = shouldRescanGreaterThanToken(n) ? 1 /* RescanGreaterThanToken */ : shouldRescanSlashToken(n) ? 2 /* RescanSlashToken */ : shouldRescanTemplateToken(n) ? 3 /* RescanTemplateToken */ : shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ : shouldRescanJsxText(n) ? 5 /* RescanJsxText */ : shouldRescanJsxAttributeValue(n) ? 6 /* RescanJsxAttributeValue */ : 0 /* Scan */;
    if (lastTokenInfo && expectedScanAction === lastScanAction) {
      return fixTokenKind(lastTokenInfo, n);
    }
    if (scanner2.getTokenFullStart() !== savedPos) {
      Debug.assert(lastTokenInfo !== void 0);
      scanner2.resetTokenState(savedPos);
      scanner2.scan();
    }
    let currentToken = getNextToken(n, expectedScanAction);
    const token = createTextRangeWithKind(
      scanner2.getTokenFullStart(),
      scanner2.getTokenEnd(),
      currentToken
    );
    if (trailingTrivia) {
      trailingTrivia = void 0;
    }
    while (scanner2.getTokenFullStart() < endPos) {
      currentToken = scanner2.scan();
      if (!isTrivia(currentToken)) {
        break;
      }
      const trivia = createTextRangeWithKind(
        scanner2.getTokenFullStart(),
        scanner2.getTokenEnd(),
        currentToken
      );
      if (!trailingTrivia) {
        trailingTrivia = [];
      }
      trailingTrivia.push(trivia);
      if (currentToken === 4 /* NewLineTrivia */) {
        scanner2.scan();
        break;
      }
    }
    lastTokenInfo = { leadingTrivia, trailingTrivia, token };
    return fixTokenKind(lastTokenInfo, n);
  }
  function getNextToken(n, expectedScanAction) {
    const token = scanner2.getToken();
    lastScanAction = 0 /* Scan */;
    switch (expectedScanAction) {
      case 1 /* RescanGreaterThanToken */:
        if (token === 32 /* GreaterThanToken */) {
          lastScanAction = 1 /* RescanGreaterThanToken */;
          const newToken = scanner2.reScanGreaterToken();
          Debug.assert(n.kind === newToken);
          return newToken;
        }
        break;
      case 2 /* RescanSlashToken */:
        if (startsWithSlashToken(token)) {
          lastScanAction = 2 /* RescanSlashToken */;
          const newToken = scanner2.reScanSlashToken();
          Debug.assert(n.kind === newToken);
          return newToken;
        }
        break;
      case 3 /* RescanTemplateToken */:
        if (token === 20 /* CloseBraceToken */) {
          lastScanAction = 3 /* RescanTemplateToken */;
          return scanner2.reScanTemplateToken(
            /*isTaggedTemplate*/
            false
          );
        }
        break;
      case 4 /* RescanJsxIdentifier */:
        lastScanAction = 4 /* RescanJsxIdentifier */;
        return scanner2.scanJsxIdentifier();
      case 5 /* RescanJsxText */:
        lastScanAction = 5 /* RescanJsxText */;
        return scanner2.reScanJsxToken(
          /*allowMultilineJsxText*/
          false
        );
      case 6 /* RescanJsxAttributeValue */:
        lastScanAction = 6 /* RescanJsxAttributeValue */;
        return scanner2.reScanJsxAttributeValue();
      case 0 /* Scan */:
        break;
      default:
        Debug.assertNever(expectedScanAction);
    }
    return token;
  }
  function readEOFTokenRange() {
    Debug.assert(isOnEOF());
    return createTextRangeWithKind(scanner2.getTokenFullStart(), scanner2.getTokenEnd(), 1 /* EndOfFileToken */);
  }
  function isOnToken() {
    const current = lastTokenInfo ? lastTokenInfo.token.kind : scanner2.getToken();
    return current !== 1 /* EndOfFileToken */ && !isTrivia(current);
  }
  function isOnEOF() {
    const current = lastTokenInfo ? lastTokenInfo.token.kind : scanner2.getToken();
    return current === 1 /* EndOfFileToken */;
  }
  function fixTokenKind(tokenInfo, container) {
    if (isToken(container) && tokenInfo.token.kind !== container.kind) {
      tokenInfo.token.kind = container.kind;
    }
    return tokenInfo;
  }
  function skipToEndOf(node) {
    scanner2.resetTokenState(node.end);
    savedPos = scanner2.getTokenFullStart();
    lastScanAction = void 0;
    lastTokenInfo = void 0;
    wasNewLine = false;
    leadingTrivia = void 0;
    trailingTrivia = void 0;
  }
  function skipToStartOf(node) {
    scanner2.resetTokenState(node.pos);
    savedPos = scanner2.getTokenFullStart();
    lastScanAction = void 0;
    lastTokenInfo = void 0;
    wasNewLine = false;
    leadingTrivia = void 0;
    trailingTrivia = void 0;
  }
}

// src/services/formatting/rule.ts
var anyContext = emptyArray;
var RuleAction = /* @__PURE__ */ ((RuleAction2) => {
  RuleAction2[RuleAction2["None"] = 0] = "None";
  RuleAction2[RuleAction2["StopProcessingSpaceActions"] = 1] = "StopProcessingSpaceActions";
  RuleAction2[RuleAction2["StopProcessingTokenActions"] = 2] = "StopProcessingTokenActions";
  RuleAction2[RuleAction2["InsertSpace"] = 4] = "InsertSpace";
  RuleAction2[RuleAction2["InsertNewLine"] = 8] = "InsertNewLine";
  RuleAction2[RuleAction2["DeleteSpace"] = 16] = "DeleteSpace";
  RuleAction2[RuleAction2["DeleteToken"] = 32] = "DeleteToken";
  RuleAction2[RuleAction2["InsertTrailingSemicolon"] = 64] = "InsertTrailingSemicolon";
  RuleAction2[RuleAction2["StopAction"] = 3] = "StopAction";
  RuleAction2[RuleAction2["ModifySpaceAction"] = 28] = "ModifySpaceAction";
  RuleAction2[RuleAction2["ModifyTokenAction"] = 96] = "ModifyTokenAction";
  return RuleAction2;
})(RuleAction || {});
var RuleFlags = /* @__PURE__ */ ((RuleFlags2) => {
  RuleFlags2[RuleFlags2["None"] = 0] = "None";
  RuleFlags2[RuleFlags2["CanDeleteNewLines"] = 1] = "CanDeleteNewLines";
  return RuleFlags2;
})(RuleFlags || {});

// src/services/formatting/rules.ts
function getAllRules() {
  const allTokens = [];
  for (let token = 0 /* FirstToken */; token <= 165 /* LastToken */; token++) {
    if (token !== 1 /* EndOfFileToken */) {
      allTokens.push(token);
    }
  }
  function anyTokenExcept(...tokens) {
    return { tokens: allTokens.filter((t) => !tokens.some((t2) => t2 === t)), isSpecific: false };
  }
  const anyToken = { tokens: allTokens, isSpecific: false };
  const anyTokenIncludingMultilineComments = tokenRangeFrom([...allTokens, 3 /* MultiLineCommentTrivia */]);
  const anyTokenIncludingEOF = tokenRangeFrom([...allTokens, 1 /* EndOfFileToken */]);
  const keywords = tokenRangeFromRange(83 /* FirstKeyword */, 165 /* LastKeyword */);
  const binaryOperators = tokenRangeFromRange(30 /* FirstBinaryOperator */, 79 /* LastBinaryOperator */);
  const binaryKeywordOperators = [
    103 /* InKeyword */,
    104 /* InstanceOfKeyword */,
    165 /* OfKeyword */,
    130 /* AsKeyword */,
    142 /* IsKeyword */,
    152 /* SatisfiesKeyword */
  ];
  const unaryPrefixOperators = [46 /* PlusPlusToken */, 47 /* MinusMinusToken */, 55 /* TildeToken */, 54 /* ExclamationToken */];
  const unaryPrefixExpressions = [
    9 /* NumericLiteral */,
    10 /* BigIntLiteral */,
    80 /* Identifier */,
    21 /* OpenParenToken */,
    23 /* OpenBracketToken */,
    19 /* OpenBraceToken */,
    110 /* ThisKeyword */,
    105 /* NewKeyword */
  ];
  const unaryPreincrementExpressions = [80 /* Identifier */, 21 /* OpenParenToken */, 110 /* ThisKeyword */, 105 /* NewKeyword */];
  const unaryPostincrementExpressions = [80 /* Identifier */, 22 /* CloseParenToken */, 24 /* CloseBracketToken */, 105 /* NewKeyword */];
  const unaryPredecrementExpressions = [80 /* Identifier */, 21 /* OpenParenToken */, 110 /* ThisKeyword */, 105 /* NewKeyword */];
  const unaryPostdecrementExpressions = [80 /* Identifier */, 22 /* CloseParenToken */, 24 /* CloseBracketToken */, 105 /* NewKeyword */];
  const comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */];
  const typeNames = [80 /* Identifier */, ...typeKeywords];
  const functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments;
  const typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([80 /* Identifier */, 32 /* GreaterThanToken */, 3 /* MultiLineCommentTrivia */, 86 /* ClassKeyword */, 95 /* ExportKeyword */, 102 /* ImportKeyword */]);
  const controlOpenBraceLeftTokenRange = tokenRangeFrom([22 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 92 /* DoKeyword */, 113 /* TryKeyword */, 98 /* FinallyKeyword */, 93 /* ElseKeyword */, 85 /* CatchKeyword */]);
  const highPriorityCommonRules = [
    // Leave comments alone
    rule("IgnoreBeforeComment", anyToken, comments, anyContext, 1 /* StopProcessingSpaceActions */),
    rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, anyContext, 1 /* StopProcessingSpaceActions */),
    rule("NotSpaceBeforeColon", anyToken, 59 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */),
    rule("SpaceAfterColon", 59 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNextTokenParentNotJsxNamespacedName], 4 /* InsertSpace */),
    rule("NoSpaceBeforeQuestionMark", anyToken, 58 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */),
    // insert space after '?' only when it is used in conditional operator
    rule("SpaceAfterQuestionMarkInConditionalOperator", 58 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */),
    // in other cases there should be no space between '?' and next token
    rule("NoSpaceAfterQuestionMark", 58 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isNonOptionalPropertyContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeDot", anyToken, [25 /* DotToken */, 29 /* QuestionDotToken */], [isNonJsxSameLineTokenContext, isNotPropertyAccessOnIntegerLiteral], 16 /* DeleteSpace */),
    rule("NoSpaceAfterDot", [25 /* DotToken */, 29 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBetweenImportParenInImportType", 102 /* ImportKeyword */, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */),
    // Special handling of unary operators.
    // Prefix operators generally shouldn't have a space between
    // them and their target unary expression.
    rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterUnaryPreincrementOperator", 46 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterUnaryPredecrementOperator", 47 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 46 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 47 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */),
    // More unary operator special-casing.
    // DevDiv 181814: Be careful when removing leading whitespace
    // around unary operators.  Examples:
    //      1 - -2  --X--> 1--2
    //      a + ++b --X--> a+++b
    rule("SpaceAfterPostincrementWhenFollowedByAdd", 46 /* PlusPlusToken */, 40 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterAddWhenFollowedByUnaryPlus", 40 /* PlusToken */, 40 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterAddWhenFollowedByPreincrement", 40 /* PlusToken */, 46 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 47 /* MinusMinusToken */, 41 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 41 /* MinusToken */, 41 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterSubtractWhenFollowedByPredecrement", 41 /* MinusToken */, 47 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterCloseBrace", 20 /* CloseBraceToken */, [28 /* CommaToken */, 27 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // For functions and control block place } on a new line [multi-line rule]
    rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 20 /* CloseBraceToken */, [isMultilineBlockContext], 8 /* InsertNewLine */),
    // Space/new line after }.
    rule("SpaceAfterCloseBrace", 20 /* CloseBraceToken */, anyTokenExcept(22 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 4 /* InsertSpace */),
    // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied
    // Also should not apply to })
    rule("SpaceBetweenCloseBraceAndElse", 20 /* CloseBraceToken */, 93 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBetweenCloseBraceAndWhile", 20 /* CloseBraceToken */, 117 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */),
    // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];'
    rule("SpaceAfterConditionalClosingParen", 22 /* CloseParenToken */, 23 /* OpenBracketToken */, [isControlDeclContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenFunctionKeywordAndStar", 100 /* FunctionKeyword */, 42 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 16 /* DeleteSpace */),
    rule("SpaceAfterStarInGeneratorDeclaration", 42 /* AsteriskToken */, 80 /* Identifier */, [isFunctionDeclarationOrFunctionExpressionContext], 4 /* InsertSpace */),
    rule("SpaceAfterFunctionInFuncDecl", 100 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 4 /* InsertSpace */),
    // Insert new line after { and before } in multi-line contexts.
    rule("NewLineAfterOpenBraceInBlockContext", 19 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 8 /* InsertNewLine */),
    // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token.
    // Though, we do extra check on the context to make sure we are dealing with get/set node. Example:
    //      get x() {}
    //      set x(val) {}
    rule("SpaceAfterGetSetInMember", [139 /* GetKeyword */, 153 /* SetKeyword */], 80 /* Identifier */, [isFunctionDeclContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenYieldKeywordAndStar", 127 /* YieldKeyword */, 42 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 16 /* DeleteSpace */),
    rule("SpaceBetweenYieldOrYieldStarAndOperand", [127 /* YieldKeyword */, 42 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 4 /* InsertSpace */),
    rule("NoSpaceBetweenReturnAndSemicolon", 107 /* ReturnKeyword */, 27 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("SpaceAfterCertainKeywords", [115 /* VarKeyword */, 111 /* ThrowKeyword */, 105 /* NewKeyword */, 91 /* DeleteKeyword */, 107 /* ReturnKeyword */, 114 /* TypeOfKeyword */, 135 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceAfterLetConstInVariableDeclaration", [121 /* LetKeyword */, 87 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 4 /* InsertSpace */),
    rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 16 /* DeleteSpace */),
    // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options.
    rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterVoidOperator", 116 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */),
    // Async-await
    rule("SpaceBetweenAsyncAndOpenParen", 134 /* AsyncKeyword */, 21 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBetweenAsyncAndFunctionKeyword", 134 /* AsyncKeyword */, [100 /* FunctionKeyword */, 80 /* Identifier */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    // Template string
    rule("NoSpaceBetweenTagAndTemplateString", [80 /* Identifier */, 22 /* CloseParenToken */], [15 /* NoSubstitutionTemplateLiteral */, 16 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // JSX opening elements
    rule("SpaceBeforeJsxAttribute", anyToken, 80 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 44 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 44 /* SlashToken */, 32 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 64 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterEqualInJsxAttribute", 64 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeJsxNamespaceColon", 80 /* Identifier */, 59 /* ColonToken */, [isNextTokenParentJsxNamespacedName], 16 /* DeleteSpace */),
    rule("NoSpaceAfterJsxNamespaceColon", 59 /* ColonToken */, 80 /* Identifier */, [isNextTokenParentJsxNamespacedName], 16 /* DeleteSpace */),
    // TypeScript-specific rules
    // Use of module as a function call. e.g.: import m2 = module("m2");
    rule("NoSpaceAfterModuleImport", [144 /* ModuleKeyword */, 149 /* RequireKeyword */], 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Add a space around certain TypeScript keywords
    rule(
      "SpaceAfterCertainTypeScriptKeywords",
      [
        128 /* AbstractKeyword */,
        129 /* AccessorKeyword */,
        86 /* ClassKeyword */,
        138 /* DeclareKeyword */,
        90 /* DefaultKeyword */,
        94 /* EnumKeyword */,
        95 /* ExportKeyword */,
        96 /* ExtendsKeyword */,
        139 /* GetKeyword */,
        119 /* ImplementsKeyword */,
        102 /* ImportKeyword */,
        120 /* InterfaceKeyword */,
        144 /* ModuleKeyword */,
        145 /* NamespaceKeyword */,
        123 /* PrivateKeyword */,
        125 /* PublicKeyword */,
        124 /* ProtectedKeyword */,
        148 /* ReadonlyKeyword */,
        153 /* SetKeyword */,
        126 /* StaticKeyword */,
        156 /* TypeKeyword */,
        161 /* FromKeyword */,
        143 /* KeyOfKeyword */,
        140 /* InferKeyword */
      ],
      anyToken,
      [isNonJsxSameLineTokenContext],
      4 /* InsertSpace */
    ),
    rule(
      "SpaceBeforeCertainTypeScriptKeywords",
      anyToken,
      [96 /* ExtendsKeyword */, 119 /* ImplementsKeyword */, 161 /* FromKeyword */],
      [isNonJsxSameLineTokenContext],
      4 /* InsertSpace */
    ),
    // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" {
    rule("SpaceAfterModuleName", 11 /* StringLiteral */, 19 /* OpenBraceToken */, [isModuleDeclContext], 4 /* InsertSpace */),
    // Lambda expressions
    rule("SpaceBeforeArrow", anyToken, 39 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceAfterArrow", 39 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    // Optional parameters and let args
    rule("NoSpaceAfterEllipsis", 26 /* DotDotDotToken */, 80 /* Identifier */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterOptionalParameters", 58 /* QuestionToken */, [22 /* CloseParenToken */, 28 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
    // Remove spaces in empty interface literals. e.g.: x: {}
    rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 16 /* DeleteSpace */),
    // generics and type assertions
    rule("NoSpaceBeforeOpenAngularBracket", typeNames, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
    rule("NoSpaceBetweenCloseParenAndAngularBracket", 22 /* CloseParenToken */, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterOpenAngularBracket", 30 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeCloseAngularBracket", anyToken, 32 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterCloseAngularBracket", 32 /* GreaterThanToken */, [21 /* OpenParenToken */, 23 /* OpenBracketToken */, 32 /* GreaterThanToken */, 28 /* CommaToken */], [
      isNonJsxSameLineTokenContext,
      isTypeArgumentOrParameterOrAssertionContext,
      isNotFunctionDeclContext,
      /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/
      isNonTypeAssertionContext
    ], 16 /* DeleteSpace */),
    // decorators
    rule("SpaceBeforeAt", [22 /* CloseParenToken */, 80 /* Identifier */], 60 /* AtToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterAt", 60 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Insert space after @ in decorator
    rule(
      "SpaceAfterDecorator",
      anyToken,
      [
        128 /* AbstractKeyword */,
        80 /* Identifier */,
        95 /* ExportKeyword */,
        90 /* DefaultKeyword */,
        86 /* ClassKeyword */,
        126 /* StaticKeyword */,
        125 /* PublicKeyword */,
        123 /* PrivateKeyword */,
        124 /* ProtectedKeyword */,
        139 /* GetKeyword */,
        153 /* SetKeyword */,
        23 /* OpenBracketToken */,
        42 /* AsteriskToken */
      ],
      [isEndOfDecoratorContextOnSameLine],
      4 /* InsertSpace */
    ),
    rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 54 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterNewKeywordOnConstructorSignature", 105 /* NewKeyword */, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 16 /* DeleteSpace */),
    rule("SpaceLessThanAndNonJSXTypeAnnotation", 30 /* LessThanToken */, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */)
  ];
  const userConfigurableRules = [
    // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses
    rule("SpaceAfterConstructor", 137 /* ConstructorKeyword */, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterConstructor", 137 /* ConstructorKeyword */, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("SpaceAfterComma", 28 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket, isNextTokenNotCloseParen], 4 /* InsertSpace */),
    rule("NoSpaceAfterComma", 28 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 16 /* DeleteSpace */),
    // Insert space after function keyword for anonymous functions
    rule("SpaceAfterAnonymousFunctionKeyword", [100 /* FunctionKeyword */, 42 /* AsteriskToken */], 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterAnonymousFunctionKeyword", [100 /* FunctionKeyword */, 42 /* AsteriskToken */], 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 16 /* DeleteSpace */),
    // Insert space after keywords in control flow statements
    rule("SpaceAfterKeywordInControl", keywords, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterKeywordInControl", keywords, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 16 /* DeleteSpace */),
    // Insert space after opening and before closing nonempty parenthesis
    rule("SpaceAfterOpenParen", 21 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBeforeCloseParen", anyToken, 22 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBetweenOpenParens", 21 /* OpenParenToken */, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenParens", 21 /* OpenParenToken */, 22 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterOpenParen", 21 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeCloseParen", anyToken, 22 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Insert space after opening and before closing nonempty brackets
    rule("SpaceAfterOpenBracket", 23 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBeforeCloseBracket", anyToken, 24 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenBrackets", 23 /* OpenBracketToken */, 24 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterOpenBracket", 23 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeCloseBracket", anyToken, 24 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}.
    rule("SpaceAfterOpenBrace", 19 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */),
    rule("SpaceBeforeCloseBrace", anyToken, 20 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterOpenBrace", 19 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeCloseBrace", anyToken, 20 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Insert a space after opening and before closing empty brace brackets
    rule("SpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces")], 4 /* InsertSpace */),
    rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Insert space after opening and before closing template string braces
    rule("SpaceAfterTemplateHeadAndMiddle", [16 /* TemplateHead */, 17 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxTextContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
    rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [17 /* TemplateMiddle */, 18 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterTemplateHeadAndMiddle", [16 /* TemplateHead */, 17 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxTextContext], 16 /* DeleteSpace */, 1 /* CanDeleteNewLines */),
    rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [17 /* TemplateMiddle */, 18 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // No space after { and before } in JSX expression
    rule("SpaceAfterOpenBraceInJsxExpression", 19 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */),
    rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 20 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterOpenBraceInJsxExpression", 19 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 20 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */),
    // Insert space after semicolon in for statement
    rule("SpaceAfterSemicolonInFor", 27 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterSemicolonInFor", 27 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 16 /* DeleteSpace */),
    // Insert space before and after binary operators
    rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */),
    rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 4 /* InsertSpace */),
    rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 16 /* DeleteSpace */),
    // Open Brace braces after control block
    rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
    // Open Brace braces after function
    // TypeScript: Function can have return types, which can be made of tons of different token kinds
    rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
    // Open Brace braces after TypeScript module/class/interface
    rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
    rule("SpaceAfterTypeAssertion", 32 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterTypeAssertion", 32 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 16 /* DeleteSpace */),
    rule("SpaceBeforeTypeAnnotation", anyToken, [58 /* QuestionToken */, 59 /* ColonToken */], [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 4 /* InsertSpace */),
    rule("NoSpaceBeforeTypeAnnotation", anyToken, [58 /* QuestionToken */, 59 /* ColonToken */], [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 16 /* DeleteSpace */),
    rule("NoOptionalSemicolon", 27 /* SemicolonToken */, anyTokenIncludingEOF, [optionEquals("semicolons", "remove" /* Remove */), isSemicolonDeletionContext], 32 /* DeleteToken */),
    rule("OptionalSemicolon", anyToken, anyTokenIncludingEOF, [optionEquals("semicolons", "insert" /* Insert */), isSemicolonInsertionContext], 64 /* InsertTrailingSemicolon */)
  ];
  const lowPriorityCommonRules = [
    // Space after keyword but not before ; or : or ?
    rule("NoSpaceBeforeSemicolon", anyToken, 27 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
    rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
    rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
    rule("NoSpaceBeforeComma", anyToken, 28 /* CommaToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // No space before and after indexer `x[]`
    rule("NoSpaceBeforeOpenBracket", anyTokenExcept(134 /* AsyncKeyword */, 84 /* CaseKeyword */), 23 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterCloseBracket", 24 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 16 /* DeleteSpace */),
    rule("SpaceAfterSemicolon", 27 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    // Remove extra space between for and await
    rule("SpaceBetweenForAndAwaitKeyword", 99 /* ForKeyword */, 135 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    // Remove extra spaces between ... and type name in tuple spread
    rule("SpaceBetweenDotDotDotAndTypeName", 26 /* DotDotDotToken */, typeNames, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Add a space between statements. All keywords except (do,else,case) has open/close parens after them.
    // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any]
    rule(
      "SpaceBetweenStatements",
      [22 /* CloseParenToken */, 92 /* DoKeyword */, 93 /* ElseKeyword */, 84 /* CaseKeyword */],
      anyToken,
      [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext],
      4 /* InsertSpace */
    ),
    // This low-pri rule takes care of "try {", "catch {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter.
    rule("SpaceAfterTryCatchFinally", [113 /* TryKeyword */, 85 /* CatchKeyword */, 98 /* FinallyKeyword */], 19 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */)
  ];
  return [
    ...highPriorityCommonRules,
    ...userConfigurableRules,
    ...lowPriorityCommonRules
  ];
}
function rule(debugName, left, right, context, action, flags = 0 /* None */) {
  return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName, context, action, flags } };
}
function tokenRangeFrom(tokens) {
  return { tokens, isSpecific: true };
}
function toTokenRange(arg) {
  return typeof arg === "number" ? tokenRangeFrom([arg]) : isArray(arg) ? tokenRangeFrom(arg) : arg;
}
function tokenRangeFromRange(from, to, except = []) {
  const tokens = [];
  for (let token = from; token <= to; token++) {
    if (!contains(except, token)) {
      tokens.push(token);
    }
  }
  return tokenRangeFrom(tokens);
}
function optionEquals(optionName, optionValue) {
  return (context) => context.options && context.options[optionName] === optionValue;
}
function isOptionEnabled(optionName) {
  return (context) => context.options && hasProperty(context.options, optionName) && !!context.options[optionName];
}
function isOptionDisabled(optionName) {
  return (context) => context.options && hasProperty(context.options, optionName) && !context.options[optionName];
}
function isOptionDisabledOrUndefined(optionName) {
  return (context) => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName];
}
function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) {
  return (context) => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName] || context.TokensAreOnSameLine();
}
function isOptionEnabledOrUndefined(optionName) {
  return (context) => !context.options || !hasProperty(context.options, optionName) || !!context.options[optionName];
}
function isForContext(context) {
  return context.contextNode.kind === 248 /* ForStatement */;
}
function isNotForContext(context) {
  return !isForContext(context);
}
function isBinaryOpContext(context) {
  switch (context.contextNode.kind) {
    case 226 /* BinaryExpression */:
      return context.contextNode.operatorToken.kind !== 28 /* CommaToken */;
    case 227 /* ConditionalExpression */:
    case 194 /* ConditionalType */:
    case 234 /* AsExpression */:
    case 281 /* ExportSpecifier */:
    case 276 /* ImportSpecifier */:
    case 182 /* TypePredicate */:
    case 192 /* UnionType */:
    case 193 /* IntersectionType */:
    case 238 /* SatisfiesExpression */:
      return true;
    // equals in binding elements: function foo([[x, y] = [1, 2]])
    case 208 /* BindingElement */:
    // equals in type X = ...
    // falls through
    case 265 /* TypeAliasDeclaration */:
    // equal in import a = module('a');
    // falls through
    case 271 /* ImportEqualsDeclaration */:
    // equal in export = 1
    // falls through
    case 277 /* ExportAssignment */:
    // equal in let a = 0
    // falls through
    case 260 /* VariableDeclaration */:
    // equal in p = 0
    // falls through
    case 169 /* Parameter */:
    case 306 /* EnumMember */:
    case 172 /* PropertyDeclaration */:
    case 171 /* PropertySignature */:
      return context.currentTokenSpan.kind === 64 /* EqualsToken */ || context.nextTokenSpan.kind === 64 /* EqualsToken */;
    // "in" keyword in for (let x in []) { }
    case 249 /* ForInStatement */:
    // "in" keyword in [P in keyof T]: T[P]
    // falls through
    case 168 /* TypeParameter */:
      return context.currentTokenSpan.kind === 103 /* InKeyword */ || context.nextTokenSpan.kind === 103 /* InKeyword */ || context.currentTokenSpan.kind === 64 /* EqualsToken */ || context.nextTokenSpan.kind === 64 /* EqualsToken */;
    // Technically, "of" is not a binary operator, but format it the same way as "in"
    case 250 /* ForOfStatement */:
      return context.currentTokenSpan.kind === 165 /* OfKeyword */ || context.nextTokenSpan.kind === 165 /* OfKeyword */;
  }
  return false;
}
function isNotBinaryOpContext(context) {
  return !isBinaryOpContext(context);
}
function isNotTypeAnnotationContext(context) {
  return !isTypeAnnotationContext(context);
}
function isTypeAnnotationContext(context) {
  const contextKind = context.contextNode.kind;
  return contextKind === 172 /* PropertyDeclaration */ || contextKind === 171 /* PropertySignature */ || contextKind === 169 /* Parameter */ || contextKind === 260 /* VariableDeclaration */ || isFunctionLikeKind(contextKind);
}
function isOptionalPropertyContext(context) {
  return isPropertyDeclaration(context.contextNode) && context.contextNode.questionToken;
}
function isNonOptionalPropertyContext(context) {
  return !isOptionalPropertyContext(context);
}
function isConditionalOperatorContext(context) {
  return context.contextNode.kind === 227 /* ConditionalExpression */ || context.contextNode.kind === 194 /* ConditionalType */;
}
function isSameLineTokenOrBeforeBlockContext(context) {
  return context.TokensAreOnSameLine() || isBeforeBlockContext(context);
}
function isBraceWrappedContext(context) {
  return context.contextNode.kind === 206 /* ObjectBindingPattern */ || context.contextNode.kind === 200 /* MappedType */ || isSingleLineBlockContext(context);
}
function isBeforeMultilineBlockContext(context) {
  return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine());
}
function isMultilineBlockContext(context) {
  return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
}
function isSingleLineBlockContext(context) {
  return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
}
function isBlockContext(context) {
  return nodeIsBlockContext(context.contextNode);
}
function isBeforeBlockContext(context) {
  return nodeIsBlockContext(context.nextTokenParent);
}
function nodeIsBlockContext(node) {
  if (nodeIsTypeScriptDeclWithBlockContext(node)) {
    return true;
  }
  switch (node.kind) {
    case 241 /* Block */:
    case 269 /* CaseBlock */:
    case 210 /* ObjectLiteralExpression */:
    case 268 /* ModuleBlock */:
      return true;
  }
  return false;
}
function isFunctionDeclContext(context) {
  switch (context.contextNode.kind) {
    case 262 /* FunctionDeclaration */:
    case 174 /* MethodDeclaration */:
    case 173 /* MethodSignature */:
    // case SyntaxKind.MemberFunctionDeclaration:
    // falls through
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
    // case SyntaxKind.MethodSignature:
    // falls through
    case 179 /* CallSignature */:
    case 218 /* FunctionExpression */:
    case 176 /* Constructor */:
    case 219 /* ArrowFunction */:
    // case SyntaxKind.ConstructorDeclaration:
    // case SyntaxKind.SimpleArrowFunctionExpression:
    // case SyntaxKind.ParenthesizedArrowFunctionExpression:
    // falls through
    case 264 /* InterfaceDeclaration */:
      return true;
  }
  return false;
}
function isNotFunctionDeclContext(context) {
  return !isFunctionDeclContext(context);
}
function isFunctionDeclarationOrFunctionExpressionContext(context) {
  return context.contextNode.kind === 262 /* FunctionDeclaration */ || context.contextNode.kind === 218 /* FunctionExpression */;
}
function isTypeScriptDeclWithBlockContext(context) {
  return nodeIsTypeScriptDeclWithBlockContext(context.contextNode);
}
function nodeIsTypeScriptDeclWithBlockContext(node) {
  switch (node.kind) {
    case 263 /* ClassDeclaration */:
    case 231 /* ClassExpression */:
    case 264 /* InterfaceDeclaration */:
    case 266 /* EnumDeclaration */:
    case 187 /* TypeLiteral */:
    case 267 /* ModuleDeclaration */:
    case 278 /* ExportDeclaration */:
    case 279 /* NamedExports */:
    case 272 /* ImportDeclaration */:
    case 275 /* NamedImports */:
      return true;
  }
  return false;
}
function isAfterCodeBlockContext(context) {
  switch (context.currentTokenParent.kind) {
    case 263 /* ClassDeclaration */:
    case 267 /* ModuleDeclaration */:
    case 266 /* EnumDeclaration */:
    case 299 /* CatchClause */:
    case 268 /* ModuleBlock */:
    case 255 /* SwitchStatement */:
      return true;
    case 241 /* Block */: {
      const blockParent = context.currentTokenParent.parent;
      if (!blockParent || blockParent.kind !== 219 /* ArrowFunction */ && blockParent.kind !== 218 /* FunctionExpression */) {
        return true;
      }
    }
  }
  return false;
}
function isControlDeclContext(context) {
  switch (context.contextNode.kind) {
    case 245 /* IfStatement */:
    case 255 /* SwitchStatement */:
    case 248 /* ForStatement */:
    case 249 /* ForInStatement */:
    case 250 /* ForOfStatement */:
    case 247 /* WhileStatement */:
    case 258 /* TryStatement */:
    case 246 /* DoStatement */:
    case 254 /* WithStatement */:
    // TODO
    // case SyntaxKind.ElseClause:
    // falls through
    case 299 /* CatchClause */:
      return true;
    default:
      return false;
  }
}
function isObjectContext(context) {
  return context.contextNode.kind === 210 /* ObjectLiteralExpression */;
}
function isFunctionCallContext(context) {
  return context.contextNode.kind === 213 /* CallExpression */;
}
function isNewContext(context) {
  return context.contextNode.kind === 214 /* NewExpression */;
}
function isFunctionCallOrNewContext(context) {
  return isFunctionCallContext(context) || isNewContext(context);
}
function isPreviousTokenNotComma(context) {
  return context.currentTokenSpan.kind !== 28 /* CommaToken */;
}
function isNextTokenNotCloseBracket(context) {
  return context.nextTokenSpan.kind !== 24 /* CloseBracketToken */;
}
function isNextTokenNotCloseParen(context) {
  return context.nextTokenSpan.kind !== 22 /* CloseParenToken */;
}
function isArrowFunctionContext(context) {
  return context.contextNode.kind === 219 /* ArrowFunction */;
}
function isImportTypeContext(context) {
  return context.contextNode.kind === 205 /* ImportType */;
}
function isNonJsxSameLineTokenContext(context) {
  return context.TokensAreOnSameLine() && context.contextNode.kind !== 12 /* JsxText */;
}
function isNonJsxTextContext(context) {
  return context.contextNode.kind !== 12 /* JsxText */;
}
function isNonJsxElementOrFragmentContext(context) {
  return context.contextNode.kind !== 284 /* JsxElement */ && context.contextNode.kind !== 288 /* JsxFragment */;
}
function isJsxExpressionContext(context) {
  return context.contextNode.kind === 294 /* JsxExpression */ || context.contextNode.kind === 293 /* JsxSpreadAttribute */;
}
function isNextTokenParentJsxAttribute(context) {
  return context.nextTokenParent.kind === 291 /* JsxAttribute */ || context.nextTokenParent.kind === 295 /* JsxNamespacedName */ && context.nextTokenParent.parent.kind === 291 /* JsxAttribute */;
}
function isJsxAttributeContext(context) {
  return context.contextNode.kind === 291 /* JsxAttribute */;
}
function isNextTokenParentNotJsxNamespacedName(context) {
  return context.nextTokenParent.kind !== 295 /* JsxNamespacedName */;
}
function isNextTokenParentJsxNamespacedName(context) {
  return context.nextTokenParent.kind === 295 /* JsxNamespacedName */;
}
function isJsxSelfClosingElementContext(context) {
  return context.contextNode.kind === 285 /* JsxSelfClosingElement */;
}
function isNotBeforeBlockInFunctionDeclarationContext(context) {
  return !isFunctionDeclContext(context) && !isBeforeBlockContext(context);
}
function isEndOfDecoratorContextOnSameLine(context) {
  return context.TokensAreOnSameLine() && hasDecorators(context.contextNode) && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent);
}
function nodeIsInDecoratorContext(node) {
  while (node && isExpression(node)) {
    node = node.parent;
  }
  return node && node.kind === 170 /* Decorator */;
}
function isStartOfVariableDeclarationList(context) {
  return context.currentTokenParent.kind === 261 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
}
function isNotFormatOnEnter(context) {
  return context.formattingRequestKind !== 2 /* FormatOnEnter */;
}
function isModuleDeclContext(context) {
  return context.contextNode.kind === 267 /* ModuleDeclaration */;
}
function isObjectTypeContext(context) {
  return context.contextNode.kind === 187 /* TypeLiteral */;
}
function isConstructorSignatureContext(context) {
  return context.contextNode.kind === 180 /* ConstructSignature */;
}
function isTypeArgumentOrParameterOrAssertion(token, parent2) {
  if (token.kind !== 30 /* LessThanToken */ && token.kind !== 32 /* GreaterThanToken */) {
    return false;
  }
  switch (parent2.kind) {
    case 183 /* TypeReference */:
    case 216 /* TypeAssertionExpression */:
    case 265 /* TypeAliasDeclaration */:
    case 263 /* ClassDeclaration */:
    case 231 /* ClassExpression */:
    case 264 /* InterfaceDeclaration */:
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
    case 174 /* MethodDeclaration */:
    case 173 /* MethodSignature */:
    case 179 /* CallSignature */:
    case 180 /* ConstructSignature */:
    case 213 /* CallExpression */:
    case 214 /* NewExpression */:
    case 233 /* ExpressionWithTypeArguments */:
      return true;
    default:
      return false;
  }
}
function isTypeArgumentOrParameterOrAssertionContext(context) {
  return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent);
}
function isTypeAssertionContext(context) {
  return context.contextNode.kind === 216 /* TypeAssertionExpression */;
}
function isNonTypeAssertionContext(context) {
  return !isTypeAssertionContext(context);
}
function isVoidOpContext(context) {
  return context.currentTokenSpan.kind === 116 /* VoidKeyword */ && context.currentTokenParent.kind === 222 /* VoidExpression */;
}
function isYieldOrYieldStarWithOperand(context) {
  return context.contextNode.kind === 229 /* YieldExpression */ && context.contextNode.expression !== void 0;
}
function isNonNullAssertionContext(context) {
  return context.contextNode.kind === 235 /* NonNullExpression */;
}
function isNotStatementConditionContext(context) {
  return !isStatementConditionContext(context);
}
function isStatementConditionContext(context) {
  switch (context.contextNode.kind) {
    case 245 /* IfStatement */:
    case 248 /* ForStatement */:
    case 249 /* ForInStatement */:
    case 250 /* ForOfStatement */:
    case 246 /* DoStatement */:
    case 247 /* WhileStatement */:
      return true;
    default:
      return false;
  }
}
function isSemicolonDeletionContext(context) {
  let nextTokenKind = context.nextTokenSpan.kind;
  let nextTokenStart = context.nextTokenSpan.pos;
  if (isTrivia(nextTokenKind)) {
    const nextRealToken = context.nextTokenParent === context.currentTokenParent ? findNextToken(
      context.currentTokenParent,
      findAncestor(context.currentTokenParent, (a) => !a.parent),
      context.sourceFile
    ) : context.nextTokenParent.getFirstToken(context.sourceFile);
    if (!nextRealToken) {
      return true;
    }
    nextTokenKind = nextRealToken.kind;
    nextTokenStart = nextRealToken.getStart(context.sourceFile);
  }
  const startLine = context.sourceFile.getLineAndCharacterOfPosition(context.currentTokenSpan.pos).line;
  const endLine = context.sourceFile.getLineAndCharacterOfPosition(nextTokenStart).line;
  if (startLine === endLine) {
    return nextTokenKind === 20 /* CloseBraceToken */ || nextTokenKind === 1 /* EndOfFileToken */;
  }
  if (nextTokenKind === 27 /* SemicolonToken */ && context.currentTokenSpan.kind === 27 /* SemicolonToken */) {
    return true;
  }
  if (nextTokenKind === 240 /* SemicolonClassElement */ || nextTokenKind === 27 /* SemicolonToken */) {
    return false;
  }
  if (context.contextNode.kind === 264 /* InterfaceDeclaration */ || context.contextNode.kind === 265 /* TypeAliasDeclaration */) {
    return !isPropertySignature(context.currentTokenParent) || !!context.currentTokenParent.type || nextTokenKind !== 21 /* OpenParenToken */;
  }
  if (isPropertyDeclaration(context.currentTokenParent)) {
    return !context.currentTokenParent.initializer;
  }
  return context.currentTokenParent.kind !== 248 /* ForStatement */ && context.currentTokenParent.kind !== 242 /* EmptyStatement */ && context.currentTokenParent.kind !== 240 /* SemicolonClassElement */ && nextTokenKind !== 23 /* OpenBracketToken */ && nextTokenKind !== 21 /* OpenParenToken */ && nextTokenKind !== 40 /* PlusToken */ && nextTokenKind !== 41 /* MinusToken */ && nextTokenKind !== 44 /* SlashToken */ && nextTokenKind !== 14 /* RegularExpressionLiteral */ && nextTokenKind !== 28 /* CommaToken */ && nextTokenKind !== 228 /* TemplateExpression */ && nextTokenKind !== 16 /* TemplateHead */ && nextTokenKind !== 15 /* NoSubstitutionTemplateLiteral */ && nextTokenKind !== 25 /* DotToken */;
}
function isSemicolonInsertionContext(context) {
  return positionIsASICandidate(context.currentTokenSpan.end, context.currentTokenParent, context.sourceFile);
}
function isNotPropertyAccessOnIntegerLiteral(context) {
  return !isPropertyAccessExpression(context.contextNode) || !isNumericLiteral(context.contextNode.expression) || context.contextNode.expression.getText().includes(".");
}

// src/services/formatting/rulesMap.ts
function getFormatContext(options, host) {
  return { options, getRules: getRulesMap(), host };
}
var rulesMapCache;
function getRulesMap() {
  if (rulesMapCache === void 0) {
    rulesMapCache = createRulesMap(getAllRules());
  }
  return rulesMapCache;
}
function getRuleActionExclusion(ruleAction) {
  let mask2 = 0 /* None */;
  if (ruleAction & 1 /* StopProcessingSpaceActions */) {
    mask2 |= 28 /* ModifySpaceAction */;
  }
  if (ruleAction & 2 /* StopProcessingTokenActions */) {
    mask2 |= 96 /* ModifyTokenAction */;
  }
  if (ruleAction & 28 /* ModifySpaceAction */) {
    mask2 |= 28 /* ModifySpaceAction */;
  }
  if (ruleAction & 96 /* ModifyTokenAction */) {
    mask2 |= 96 /* ModifyTokenAction */;
  }
  return mask2;
}
function createRulesMap(rules) {
  const map2 = buildMap(rules);
  return (context) => {
    const bucket = map2[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)];
    if (bucket) {
      const rules2 = [];
      let ruleActionMask = 0;
      for (const rule2 of bucket) {
        const acceptRuleActions = ~getRuleActionExclusion(ruleActionMask);
        if (rule2.action & acceptRuleActions && every(rule2.context, (c) => c(context))) {
          rules2.push(rule2);
          ruleActionMask |= rule2.action;
        }
      }
      if (rules2.length) {
        return rules2;
      }
    }
  };
}
function buildMap(rules) {
  const map2 = new Array(mapRowLength * mapRowLength);
  const rulesBucketConstructionStateList = new Array(map2.length);
  for (const rule2 of rules) {
    const specificRule = rule2.leftTokenRange.isSpecific && rule2.rightTokenRange.isSpecific;
    for (const left of rule2.leftTokenRange.tokens) {
      for (const right of rule2.rightTokenRange.tokens) {
        const index = getRuleBucketIndex(left, right);
        let rulesBucket = map2[index];
        if (rulesBucket === void 0) {
          rulesBucket = map2[index] = [];
        }
        addRule(rulesBucket, rule2.rule, specificRule, rulesBucketConstructionStateList, index);
      }
    }
  }
  return map2;
}
function getRuleBucketIndex(row, column) {
  Debug.assert(row <= 165 /* LastKeyword */ && column <= 165 /* LastKeyword */, "Must compute formatting context from tokens");
  return row * mapRowLength + column;
}
var maskBitSize = 5;
var mask = 31;
var mapRowLength = 165 /* LastToken */ + 1;
var RulesPosition = ((RulesPosition2) => {
  RulesPosition2[RulesPosition2["StopRulesSpecific"] = 0] = "StopRulesSpecific";
  RulesPosition2[RulesPosition2["StopRulesAny"] = maskBitSize * 1] = "StopRulesAny";
  RulesPosition2[RulesPosition2["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific";
  RulesPosition2[RulesPosition2["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny";
  RulesPosition2[RulesPosition2["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific";
  RulesPosition2[RulesPosition2["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny";
  return RulesPosition2;
})(RulesPosition || {});
function addRule(rules, rule2, specificTokens, constructionState, rulesBucketIndex) {
  const position = rule2.action & 3 /* StopAction */ ? specificTokens ? 0 /* StopRulesSpecific */ : RulesPosition.StopRulesAny : rule2.context !== anyContext ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny;
  const state = constructionState[rulesBucketIndex] || 0;
  rules.splice(getInsertionIndex(state, position), 0, rule2);
  constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position);
}
function getInsertionIndex(indexBitmap, maskPosition) {
  let index = 0;
  for (let pos = 0; pos <= maskPosition; pos += maskBitSize) {
    index += indexBitmap & mask;
    indexBitmap >>= maskBitSize;
  }
  return index;
}
function increaseInsertionIndex(indexBitmap, maskPosition) {
  const value = (indexBitmap >> maskPosition & mask) + 1;
  Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules.");
  return indexBitmap & ~(mask << maskPosition) | value << maskPosition;
}

// src/services/formatting/formatting.ts
function createTextRangeWithKind(pos, end, kind) {
  const textRangeWithKind = { pos, end, kind };
  if (Debug.isDebugging) {
    Object.defineProperty(textRangeWithKind, "__debugKind", {
      get: () => Debug.formatSyntaxKind(kind)
    });
  }
  return textRangeWithKind;
}
function formatOnEnter(position, sourceFile, formatContext) {
  const line = sourceFile.getLineAndCharacterOfPosition(position).line;
  if (line === 0) {
    return [];
  }
  let endOfFormatSpan = getEndLinePosition(line, sourceFile);
  while (isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) {
    endOfFormatSpan--;
  }
  if (isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
    endOfFormatSpan--;
  }
  const span = {
    // get start position for the previous line
    pos: getStartPositionOfLine(line - 1, sourceFile),
    // end value is exclusive so add 1 to the result
    end: endOfFormatSpan + 1
  };
  return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */);
}
function formatOnSemicolon(position, sourceFile, formatContext) {
  const semicolon = findImmediatelyPrecedingTokenOfKind(position, 27 /* SemicolonToken */, sourceFile);
  return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */);
}
function formatOnOpeningCurly(position, sourceFile, formatContext) {
  const openingCurly = findImmediatelyPrecedingTokenOfKind(position, 19 /* OpenBraceToken */, sourceFile);
  if (!openingCurly) {
    return [];
  }
  const curlyBraceRange = openingCurly.parent;
  const outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange);
  const textRange = {
    pos: getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile),
    // TODO: GH#18217
    end: position
  };
  return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */);
}
function formatOnClosingCurly(position, sourceFile, formatContext) {
  const precedingToken = findImmediatelyPrecedingTokenOfKind(position, 20 /* CloseBraceToken */, sourceFile);
  return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */);
}
function formatDocument(sourceFile, formatContext) {
  const span = {
    pos: 0,
    end: sourceFile.text.length
  };
  return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */);
}
function formatSelection(start, end, sourceFile, formatContext) {
  const span = {
    pos: getLineStartPositionForPosition(start, sourceFile),
    end
  };
  return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */);
}
function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) {
  const precedingToken = findPrecedingToken(end, sourceFile);
  return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? precedingToken : void 0;
}
function findOutermostNodeWithinListLevel(node) {
  let current = node;
  while (current && current.parent && current.parent.end === node.end && !isListElement(current.parent, current)) {
    current = current.parent;
  }
  return current;
}
function isListElement(parent2, node) {
  switch (parent2.kind) {
    case 263 /* ClassDeclaration */:
    case 264 /* InterfaceDeclaration */:
      return rangeContainsRange(parent2.members, node);
    case 267 /* ModuleDeclaration */:
      const body = parent2.body;
      return !!body && body.kind === 268 /* ModuleBlock */ && rangeContainsRange(body.statements, node);
    case 307 /* SourceFile */:
    case 241 /* Block */:
    case 268 /* ModuleBlock */:
      return rangeContainsRange(parent2.statements, node);
    case 299 /* CatchClause */:
      return rangeContainsRange(parent2.block.statements, node);
  }
  return false;
}
function findEnclosingNode(range, sourceFile) {
  return find2(sourceFile);
  function find2(n) {
    const candidate = forEachChild(n, (c) => startEndContainsRange(c.getStart(sourceFile), c.end, range) && c);
    if (candidate) {
      const result = find2(candidate);
      if (result) {
        return result;
      }
    }
    return n;
  }
}
function prepareRangeContainsErrorFunction(errors, originalRange) {
  if (!errors.length) {
    return rangeHasNoErrors;
  }
  const sorted = errors.filter((d) => rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length)).sort((e1, e2) => e1.start - e2.start);
  if (!sorted.length) {
    return rangeHasNoErrors;
  }
  let index = 0;
  return (r) => {
    while (true) {
      if (index >= sorted.length) {
        return false;
      }
      const error2 = sorted[index];
      if (r.end <= error2.start) {
        return false;
      }
      if (startEndOverlapsWithStartEnd(r.pos, r.end, error2.start, error2.start + error2.length)) {
        return true;
      }
      index++;
    }
  };
  function rangeHasNoErrors() {
    return false;
  }
}
function getScanStartPosition(enclosingNode, originalRange, sourceFile) {
  const start = enclosingNode.getStart(sourceFile);
  if (start === originalRange.pos && enclosingNode.end === originalRange.end) {
    return start;
  }
  const precedingToken = findPrecedingToken(originalRange.pos, sourceFile);
  if (!precedingToken) {
    return enclosingNode.pos;
  }
  if (precedingToken.end >= originalRange.pos) {
    return enclosingNode.pos;
  }
  return precedingToken.end;
}
function getOwnOrInheritedDelta(n, options, sourceFile) {
  let previousLine = -1 /* Unknown */;
  let child;
  while (n) {
    const line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line;
    if (previousLine !== -1 /* Unknown */ && line !== previousLine) {
      break;
    }
    if (SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) {
      return options.indentSize;
    }
    previousLine = line;
    child = n;
    n = n.parent;
  }
  return 0;
}
function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) {
  const range = { pos: node.pos, end: node.end };
  return getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, (scanner2) => formatSpanWorker(
    range,
    node,
    initialIndentation,
    delta,
    scanner2,
    formatContext,
    1 /* FormatSelection */,
    (_) => false,
    // assume that node does not have any errors
    sourceFileLike
  ));
}
function formatNodeLines(node, sourceFile, formatContext, requestKind) {
  if (!node) {
    return [];
  }
  const span = {
    pos: getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile),
    end: node.end
  };
  return formatSpan(span, sourceFile, formatContext, requestKind);
}
function formatSpan(originalRange, sourceFile, formatContext, requestKind) {
  const enclosingNode = findEnclosingNode(originalRange, sourceFile);
  return getFormattingScanner(
    sourceFile.text,
    sourceFile.languageVariant,
    getScanStartPosition(enclosingNode, originalRange, sourceFile),
    originalRange.end,
    (scanner2) => formatSpanWorker(
      originalRange,
      enclosingNode,
      SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options),
      getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile),
      scanner2,
      formatContext,
      requestKind,
      prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange),
      sourceFile
    )
  );
}
function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, { options, getRules, host }, requestKind, rangeContainsError, sourceFile) {
  var _a;
  const formattingContext = new FormattingContext(sourceFile, requestKind, options);
  let previousRangeTriviaEnd;
  let previousRange;
  let previousParent;
  let previousRangeStartLine;
  let lastIndentedLine;
  let indentationOnLastIndentedLine = -1 /* Unknown */;
  const edits = [];
  formattingScanner.advance();
  if (formattingScanner.isOnToken()) {
    const startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line;
    let undecoratedStartLine = startLine;
    if (hasDecorators(enclosingNode)) {
      undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line;
    }
    processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
  }
  const remainingTrivia = formattingScanner.getCurrentLeadingTrivia();
  if (remainingTrivia) {
    const indentation = SmartIndenter.nodeWillIndentChild(
      options,
      enclosingNode,
      /*child*/
      void 0,
      sourceFile,
      /*indentByDefault*/
      false
    ) ? initialIndentation + options.indentSize : initialIndentation;
    indentTriviaItems(
      remainingTrivia,
      indentation,
      /*indentNextTokenOrTrivia*/
      true,
      (item) => {
        processRange(
          item,
          sourceFile.getLineAndCharacterOfPosition(item.pos),
          enclosingNode,
          enclosingNode,
          /*dynamicIndentation*/
          void 0
        );
        insertIndentation(
          item.pos,
          indentation,
          /*lineAdded*/
          false
        );
      }
    );
    if (options.trimTrailingWhitespace !== false) {
      trimTrailingWhitespacesForRemainingRange(remainingTrivia);
    }
  }
  if (previousRange && formattingScanner.getTokenFullStart() >= originalRange.end) {
    const tokenInfo = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : void 0;
    if (tokenInfo && tokenInfo.pos === previousRangeTriviaEnd) {
      const parent2 = ((_a = findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)) == null ? void 0 : _a.parent) || previousParent;
      processPair(
        tokenInfo,
        sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line,
        parent2,
        previousRange,
        previousRangeStartLine,
        previousParent,
        parent2,
        /*dynamicIndentation*/
        void 0
      );
    }
  }
  return edits;
  function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) {
    if (rangeOverlapsWithStartEnd(range, startPos, endPos) || rangeContainsStartEnd(range, startPos, endPos)) {
      if (inheritedIndentation !== -1 /* Unknown */) {
        return inheritedIndentation;
      }
    } else {
      const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
      const startLinePosition = getLineStartPositionForPosition(startPos, sourceFile);
      const column = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options);
      if (startLine !== parentStartLine || startPos === column) {
        const baseIndentSize = SmartIndenter.getBaseIndentation(options);
        return baseIndentSize > column ? baseIndentSize : column;
      }
    }
    return -1 /* Unknown */;
  }
  function computeIndentation(node, startLine, inheritedIndentation, parent2, parentDynamicIndentation, effectiveParentStartLine) {
    const delta2 = SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
    if (effectiveParentStartLine === startLine) {
      return {
        indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(),
        delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta2)
      };
    } else if (inheritedIndentation === -1 /* Unknown */) {
      if (node.kind === 21 /* OpenParenToken */ && startLine === lastIndentedLine) {
        return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) };
      } else if (SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent2, node, startLine, sourceFile) || SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent2, node, startLine, sourceFile) || SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent2, node, startLine, sourceFile)) {
        return { indentation: parentDynamicIndentation.getIndentation(), delta: delta2 };
      } else {
        return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta2 };
      }
    } else {
      return { indentation: inheritedIndentation, delta: delta2 };
    }
  }
  function getFirstNonDecoratorTokenOfNode(node) {
    if (canHaveModifiers(node)) {
      const modifier = find(node.modifiers, isModifier, findIndex(node.modifiers, isDecorator));
      if (modifier) return modifier.kind;
    }
    switch (node.kind) {
      case 263 /* ClassDeclaration */:
        return 86 /* ClassKeyword */;
      case 264 /* InterfaceDeclaration */:
        return 120 /* InterfaceKeyword */;
      case 262 /* FunctionDeclaration */:
        return 100 /* FunctionKeyword */;
      case 266 /* EnumDeclaration */:
        return 266 /* EnumDeclaration */;
      case 177 /* GetAccessor */:
        return 139 /* GetKeyword */;
      case 178 /* SetAccessor */:
        return 153 /* SetKeyword */;
      case 174 /* MethodDeclaration */:
        if (node.asteriskToken) {
          return 42 /* AsteriskToken */;
        }
      // falls through
      case 172 /* PropertyDeclaration */:
      case 169 /* Parameter */:
        const name = getNameOfDeclaration(node);
        if (name) {
          return name.kind;
        }
    }
  }
  function getDynamicIndentation(node, nodeStartLine, indentation, delta2) {
    return {
      getIndentationForComment: (kind, tokenIndentation, container) => {
        switch (kind) {
          // preceding comment to the token that closes the indentation scope inherits the indentation from the scope
          // ..  {
          //     // comment
          // }
          case 20 /* CloseBraceToken */:
          case 24 /* CloseBracketToken */:
          case 22 /* CloseParenToken */:
            return indentation + getDelta(container);
        }
        return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation;
      },
      // if list end token is LessThanToken '>' then its delta should be explicitly suppressed
      // so that LessThanToken as a binary operator can still be indented.
      // foo.then
      //     <
      //         number,
      //         string,
      //     >();
      // vs
      // var a = xValue
      //     > yValue;
      getIndentationForToken: (line, kind, container, suppressDelta) => !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation,
      getIndentation: () => indentation,
      getDelta,
      recomputeIndentation: (lineAdded, parent2) => {
        if (SmartIndenter.shouldIndentChildNode(options, parent2, node, sourceFile)) {
          indentation += lineAdded ? options.indentSize : -options.indentSize;
          delta2 = SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
        }
      }
    };
    function shouldAddDelta(line, kind, container) {
      switch (kind) {
        // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent
        case 19 /* OpenBraceToken */:
        case 20 /* CloseBraceToken */:
        case 22 /* CloseParenToken */:
        case 93 /* ElseKeyword */:
        case 117 /* WhileKeyword */:
        case 60 /* AtToken */:
          return false;
        case 44 /* SlashToken */:
        case 32 /* GreaterThanToken */:
          switch (container.kind) {
            case 286 /* JsxOpeningElement */:
            case 287 /* JsxClosingElement */:
            case 285 /* JsxSelfClosingElement */:
              return false;
          }
          break;
        case 23 /* OpenBracketToken */:
        case 24 /* CloseBracketToken */:
          if (container.kind !== 200 /* MappedType */) {
            return false;
          }
          break;
      }
      return nodeStartLine !== line && !(hasDecorators(node) && kind === getFirstNonDecoratorTokenOfNode(node));
    }
    function getDelta(child) {
      return SmartIndenter.nodeWillIndentChild(
        options,
        node,
        child,
        sourceFile,
        /*indentByDefault*/
        true
      ) ? delta2 : 0;
    }
  }
  function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta2) {
    if (!rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) {
      return;
    }
    const nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta2);
    let childContextNode = contextNode;
    forEachChild(
      node,
      (child) => {
        processChildNode(
          child,
          /*inheritedIndentation*/
          -1 /* Unknown */,
          node,
          nodeDynamicIndentation,
          nodeStartLine,
          undecoratedNodeStartLine,
          /*isListItem*/
          false
        );
      },
      (nodes) => {
        processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation);
      }
    );
    while (formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) {
      const tokenInfo = formattingScanner.readTokenInfo(node);
      if (tokenInfo.token.end > Math.min(node.end, originalRange.end)) {
        break;
      }
      consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node);
    }
    function processChildNode(child, inheritedIndentation, parent2, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) {
      Debug.assert(!nodeIsSynthesized(child));
      if (nodeIsMissing(child) || isGrammarError(parent2, child)) {
        return inheritedIndentation;
      }
      const childStartPos = child.getStart(sourceFile);
      const childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line;
      let undecoratedChildStartLine = childStartLine;
      if (hasDecorators(child)) {
        undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(getNonDecoratorTokenPosOfNode(child, sourceFile)).line;
      }
      let childIndentationAmount = -1 /* Unknown */;
      if (isListItem && rangeContainsRange(originalRange, parent2)) {
        childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation);
        if (childIndentationAmount !== -1 /* Unknown */) {
          inheritedIndentation = childIndentationAmount;
        }
      }
      if (!rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) {
        if (child.end < originalRange.pos) {
          formattingScanner.skipToEndOf(child);
        }
        return inheritedIndentation;
      }
      if (child.getFullWidth() === 0) {
        return inheritedIndentation;
      }
      while (formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) {
        const tokenInfo = formattingScanner.readTokenInfo(node);
        if (tokenInfo.token.end > originalRange.end) {
          return inheritedIndentation;
        }
        if (tokenInfo.token.end > childStartPos) {
          if (tokenInfo.token.pos > childStartPos) {
            formattingScanner.skipToStartOf(child);
          }
          break;
        }
        consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node);
      }
      if (!formattingScanner.isOnToken() || formattingScanner.getTokenFullStart() >= originalRange.end) {
        return inheritedIndentation;
      }
      if (isToken(child)) {
        const tokenInfo = formattingScanner.readTokenInfo(child);
        if (child.kind !== 12 /* JsxText */) {
          Debug.assert(tokenInfo.token.end === child.end, "Token end is child end");
          consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
          return inheritedIndentation;
        }
      }
      const effectiveParentStartLine = child.kind === 170 /* Decorator */ ? childStartLine : undecoratedParentStartLine;
      const childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine);
      processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta);
      childContextNode = node;
      if (isFirstListItem && parent2.kind === 209 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) {
        inheritedIndentation = childIndentation.indentation;
      }
      return inheritedIndentation;
    }
    function processChildNodes(nodes, parent2, parentStartLine, parentDynamicIndentation) {
      Debug.assert(isNodeArray(nodes));
      Debug.assert(!nodeIsSynthesized(nodes));
      const listStartToken = getOpenTokenForList(parent2, nodes);
      let listDynamicIndentation = parentDynamicIndentation;
      let startLine = parentStartLine;
      if (!rangeOverlapsWithStartEnd(originalRange, nodes.pos, nodes.end)) {
        if (nodes.end < originalRange.pos) {
          formattingScanner.skipToEndOf(nodes);
        }
        return;
      }
      if (listStartToken !== 0 /* Unknown */) {
        while (formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) {
          const tokenInfo = formattingScanner.readTokenInfo(parent2);
          if (tokenInfo.token.end > nodes.pos) {
            break;
          } else if (tokenInfo.token.kind === listStartToken) {
            startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
            consumeTokenAndAdvanceScanner(tokenInfo, parent2, parentDynamicIndentation, parent2);
            let indentationOnListStartToken;
            if (indentationOnLastIndentedLine !== -1 /* Unknown */) {
              indentationOnListStartToken = indentationOnLastIndentedLine;
            } else {
              const startLinePosition = getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile);
              indentationOnListStartToken = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options);
            }
            listDynamicIndentation = getDynamicIndentation(parent2, parentStartLine, indentationOnListStartToken, options.indentSize);
          } else {
            consumeTokenAndAdvanceScanner(tokenInfo, parent2, parentDynamicIndentation, parent2);
          }
        }
      }
      let inheritedIndentation = -1 /* Unknown */;
      for (let i = 0; i < nodes.length; i++) {
        const child = nodes[i];
        inheritedIndentation = processChildNode(
          child,
          inheritedIndentation,
          node,
          listDynamicIndentation,
          startLine,
          startLine,
          /*isListItem*/
          true,
          /*isFirstListItem*/
          i === 0
        );
      }
      const listEndToken = getCloseTokenForOpenToken(listStartToken);
      if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) {
        let tokenInfo = formattingScanner.readTokenInfo(parent2);
        if (tokenInfo.token.kind === 28 /* CommaToken */) {
          consumeTokenAndAdvanceScanner(tokenInfo, parent2, listDynamicIndentation, parent2);
          tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent2) : void 0;
        }
        if (tokenInfo && tokenInfo.token.kind === listEndToken && rangeContainsRange(parent2, tokenInfo.token)) {
          consumeTokenAndAdvanceScanner(
            tokenInfo,
            parent2,
            listDynamicIndentation,
            parent2,
            /*isListEndToken*/
            true
          );
        }
      }
    }
    function consumeTokenAndAdvanceScanner(currentTokenInfo, parent2, dynamicIndentation, container, isListEndToken) {
      Debug.assert(rangeContainsRange(parent2, currentTokenInfo.token));
      const lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine();
      let indentToken = false;
      if (currentTokenInfo.leadingTrivia) {
        processTrivia(currentTokenInfo.leadingTrivia, parent2, childContextNode, dynamicIndentation);
      }
      let lineAction = 0 /* None */;
      const isTokenInRange = rangeContainsRange(originalRange, currentTokenInfo.token);
      const tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos);
      if (isTokenInRange) {
        const rangeHasError = rangeContainsError(currentTokenInfo.token);
        const savePreviousRange = previousRange;
        lineAction = processRange(currentTokenInfo.token, tokenStart, parent2, childContextNode, dynamicIndentation);
        if (!rangeHasError) {
          if (lineAction === 0 /* None */) {
            const prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line;
            indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine;
          } else {
            indentToken = lineAction === 1 /* LineAdded */;
          }
        }
      }
      if (currentTokenInfo.trailingTrivia) {
        previousRangeTriviaEnd = last(currentTokenInfo.trailingTrivia).end;
        processTrivia(currentTokenInfo.trailingTrivia, parent2, childContextNode, dynamicIndentation);
      }
      if (indentToken) {
        const tokenIndentation = isTokenInRange && !rangeContainsError(currentTokenInfo.token) ? dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) : -1 /* Unknown */;
        let indentNextTokenOrTrivia = true;
        if (currentTokenInfo.leadingTrivia) {
          const commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
          indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation, indentNextTokenOrTrivia, (item) => insertIndentation(
            item.pos,
            commentIndentation,
            /*lineAdded*/
            false
          ));
        }
        if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) {
          insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */);
          lastIndentedLine = tokenStart.line;
          indentationOnLastIndentedLine = tokenIndentation;
        }
      }
      formattingScanner.advance();
      childContextNode = parent2;
    }
  }
  function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) {
    for (const triviaItem of trivia) {
      const triviaInRange = rangeContainsRange(originalRange, triviaItem);
      switch (triviaItem.kind) {
        case 3 /* MultiLineCommentTrivia */:
          if (triviaInRange) {
            indentMultilineComment(
              triviaItem,
              commentIndentation,
              /*firstLineIsIndented*/
              !indentNextTokenOrTrivia
            );
          }
          indentNextTokenOrTrivia = false;
          break;
        case 2 /* SingleLineCommentTrivia */:
          if (indentNextTokenOrTrivia && triviaInRange) {
            indentSingleLine(triviaItem);
          }
          indentNextTokenOrTrivia = false;
          break;
        case 4 /* NewLineTrivia */:
          indentNextTokenOrTrivia = true;
          break;
      }
    }
    return indentNextTokenOrTrivia;
  }
  function processTrivia(trivia, parent2, contextNode, dynamicIndentation) {
    for (const triviaItem of trivia) {
      if (isComment(triviaItem.kind) && rangeContainsRange(originalRange, triviaItem)) {
        const triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos);
        processRange(triviaItem, triviaItemStart, parent2, contextNode, dynamicIndentation);
      }
    }
  }
  function processRange(range, rangeStart, parent2, contextNode, dynamicIndentation) {
    const rangeHasError = rangeContainsError(range);
    let lineAction = 0 /* None */;
    if (!rangeHasError) {
      if (!previousRange) {
        const originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos);
        trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line);
      } else {
        lineAction = processPair(range, rangeStart.line, parent2, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation);
      }
    }
    previousRange = range;
    previousRangeTriviaEnd = range.end;
    previousParent = parent2;
    previousRangeStartLine = rangeStart.line;
    return lineAction;
  }
  function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent2, contextNode, dynamicIndentation) {
    formattingContext.updateContext(previousItem, previousParent2, currentItem, currentParent, contextNode);
    const rules = getRules(formattingContext);
    let trimTrailingWhitespaces = formattingContext.options.trimTrailingWhitespace !== false;
    let lineAction = 0 /* None */;
    if (rules) {
      forEachRight(rules, (rule2) => {
        lineAction = applyRuleEdits(rule2, previousItem, previousStartLine, currentItem, currentStartLine);
        if (dynamicIndentation) {
          switch (lineAction) {
            case 2 /* LineRemoved */:
              if (currentParent.getStart(sourceFile) === currentItem.pos) {
                dynamicIndentation.recomputeIndentation(
                  /*lineAddedByFormatting*/
                  false,
                  contextNode
                );
              }
              break;
            case 1 /* LineAdded */:
              if (currentParent.getStart(sourceFile) === currentItem.pos) {
                dynamicIndentation.recomputeIndentation(
                  /*lineAddedByFormatting*/
                  true,
                  contextNode
                );
              }
              break;
            default:
              Debug.assert(lineAction === 0 /* None */);
          }
        }
        trimTrailingWhitespaces = trimTrailingWhitespaces && !(rule2.action & 16 /* DeleteSpace */) && rule2.flags !== 1 /* CanDeleteNewLines */;
      });
    } else {
      trimTrailingWhitespaces = trimTrailingWhitespaces && currentItem.kind !== 1 /* EndOfFileToken */;
    }
    if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) {
      trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem);
    }
    return lineAction;
  }
  function insertIndentation(pos, indentation, lineAdded) {
    const indentationString = getIndentationString(indentation, options);
    if (lineAdded) {
      recordReplace(pos, 0, indentationString);
    } else {
      const tokenStart = sourceFile.getLineAndCharacterOfPosition(pos);
      const startLinePosition = getStartPositionOfLine(tokenStart.line, sourceFile);
      if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) {
        recordReplace(startLinePosition, tokenStart.character, indentationString);
      }
    }
  }
  function characterToColumn(startLinePosition, characterInLine) {
    let column = 0;
    for (let i = 0; i < characterInLine; i++) {
      if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) {
        column += options.tabSize - column % options.tabSize;
      } else {
        column++;
      }
    }
    return column;
  }
  function indentationIsDifferent(indentationString, startLinePosition) {
    return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length);
  }
  function indentMultilineComment(commentRange, indentation, firstLineIsIndented, indentFinalLine = true) {
    let startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line;
    const endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line;
    if (startLine === endLine) {
      if (!firstLineIsIndented) {
        insertIndentation(
          commentRange.pos,
          indentation,
          /*lineAdded*/
          false
        );
      }
      return;
    }
    const parts = [];
    let startPos = commentRange.pos;
    for (let line = startLine; line < endLine; line++) {
      const endOfLine = getEndLinePosition(line, sourceFile);
      parts.push({ pos: startPos, end: endOfLine });
      startPos = getStartPositionOfLine(line + 1, sourceFile);
    }
    if (indentFinalLine) {
      parts.push({ pos: startPos, end: commentRange.end });
    }
    if (parts.length === 0) return;
    const startLinePos = getStartPositionOfLine(startLine, sourceFile);
    const nonWhitespaceColumnInFirstPart = SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options);
    let startIndex = 0;
    if (firstLineIsIndented) {
      startIndex = 1;
      startLine++;
    }
    const delta2 = indentation - nonWhitespaceColumnInFirstPart.column;
    for (let i = startIndex; i < parts.length; i++, startLine++) {
      const startLinePos2 = getStartPositionOfLine(startLine, sourceFile);
      const nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart : SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options);
      const newIndentation = nonWhitespaceCharacterAndColumn.column + delta2;
      if (newIndentation > 0) {
        const indentationString = getIndentationString(newIndentation, options);
        recordReplace(startLinePos2, nonWhitespaceCharacterAndColumn.character, indentationString);
      } else {
        recordDelete(startLinePos2, nonWhitespaceCharacterAndColumn.character);
      }
    }
  }
  function trimTrailingWhitespacesForLines(line1, line2, range) {
    for (let line = line1; line < line2; line++) {
      const lineStartPosition = getStartPositionOfLine(line, sourceFile);
      const lineEndPosition = getEndLinePosition(line, sourceFile);
      if (range && (isComment(range.kind) || isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) {
        continue;
      }
      const whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition);
      if (whitespaceStart !== -1) {
        Debug.assert(whitespaceStart === lineStartPosition || !isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(whitespaceStart - 1)));
        recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart);
      }
    }
  }
  function getTrailingWhitespaceStartPosition(start, end) {
    let pos = end;
    while (pos >= start && isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) {
      pos--;
    }
    if (pos !== end) {
      return pos + 1;
    }
    return -1;
  }
  function trimTrailingWhitespacesForRemainingRange(trivias) {
    let startPos = previousRange ? previousRange.end : originalRange.pos;
    for (const trivia of trivias) {
      if (isComment(trivia.kind)) {
        if (startPos < trivia.pos) {
          trimTrailingWitespacesForPositions(startPos, trivia.pos - 1, previousRange);
        }
        startPos = trivia.end + 1;
      }
    }
    if (startPos < originalRange.end) {
      trimTrailingWitespacesForPositions(startPos, originalRange.end, previousRange);
    }
  }
  function trimTrailingWitespacesForPositions(startPos, endPos, previousRange2) {
    const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
    const endLine = sourceFile.getLineAndCharacterOfPosition(endPos).line;
    trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange2);
  }
  function recordDelete(start, len) {
    if (len) {
      edits.push(createTextChangeFromStartLength(start, len, ""));
    }
  }
  function recordReplace(start, len, newText) {
    if (len || newText) {
      edits.push(createTextChangeFromStartLength(start, len, newText));
    }
  }
  function recordInsert(start, text) {
    if (text) {
      edits.push(createTextChangeFromStartLength(start, 0, text));
    }
  }
  function applyRuleEdits(rule2, previousRange2, previousStartLine, currentRange, currentStartLine) {
    const onLaterLine = currentStartLine !== previousStartLine;
    switch (rule2.action) {
      case 1 /* StopProcessingSpaceActions */:
        return 0 /* None */;
      case 16 /* DeleteSpace */:
        if (previousRange2.end !== currentRange.pos) {
          recordDelete(previousRange2.end, currentRange.pos - previousRange2.end);
          return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
        }
        break;
      case 32 /* DeleteToken */:
        recordDelete(previousRange2.pos, previousRange2.end - previousRange2.pos);
        break;
      case 8 /* InsertNewLine */:
        if (rule2.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
          return 0 /* None */;
        }
        const lineDelta = currentStartLine - previousStartLine;
        if (lineDelta !== 1) {
          recordReplace(previousRange2.end, currentRange.pos - previousRange2.end, getNewLineOrDefaultFromHost(host, options));
          return onLaterLine ? 0 /* None */ : 1 /* LineAdded */;
        }
        break;
      case 4 /* InsertSpace */:
        if (rule2.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
          return 0 /* None */;
        }
        const posDelta = currentRange.pos - previousRange2.end;
        if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange2.end) !== 32 /* space */) {
          recordReplace(previousRange2.end, currentRange.pos - previousRange2.end, " ");
          return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
        }
        break;
      case 64 /* InsertTrailingSemicolon */:
        recordInsert(previousRange2.end, ";");
    }
    return 0 /* None */;
  }
}
function getRangeOfEnclosingComment(sourceFile, position, precedingToken, tokenAtPosition = getTokenAtPosition(sourceFile, position)) {
  const jsdoc = findAncestor(tokenAtPosition, isJSDoc);
  if (jsdoc) tokenAtPosition = jsdoc.parent;
  const tokenStart = tokenAtPosition.getStart(sourceFile);
  if (tokenStart <= position && position < tokenAtPosition.getEnd()) {
    return void 0;
  }
  precedingToken = precedingToken === null ? void 0 : precedingToken === void 0 ? findPrecedingToken(position, sourceFile) : precedingToken;
  const trailingRangesOfPreviousToken = precedingToken && getTrailingCommentRanges(sourceFile.text, precedingToken.end);
  const leadingCommentRangesOfNextToken = getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile);
  const commentRanges = concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken);
  return commentRanges && find(commentRanges, (range) => rangeContainsPositionExclusive(range, position) || // The end marker of a single-line comment does not include the newline character.
  // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position):
  //
  //    // asdf   ^\n
  //
  // But for closed multi-line comments, we don't want to be inside the comment in the following case:
  //
  //    /* asdf */^
  //
  // However, unterminated multi-line comments *do* contain their end.
  //
  // Internally, we represent the end of the comment at the newline and closing '/', respectively.
  //
  position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()));
}
function getOpenTokenForList(node, list) {
  switch (node.kind) {
    case 176 /* Constructor */:
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
    case 174 /* MethodDeclaration */:
    case 173 /* MethodSignature */:
    case 219 /* ArrowFunction */:
    case 179 /* CallSignature */:
    case 180 /* ConstructSignature */:
    case 184 /* FunctionType */:
    case 185 /* ConstructorType */:
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
      if (node.typeParameters === list) {
        return 30 /* LessThanToken */;
      } else if (node.parameters === list) {
        return 21 /* OpenParenToken */;
      }
      break;
    case 213 /* CallExpression */:
    case 214 /* NewExpression */:
      if (node.typeArguments === list) {
        return 30 /* LessThanToken */;
      } else if (node.arguments === list) {
        return 21 /* OpenParenToken */;
      }
      break;
    case 263 /* ClassDeclaration */:
    case 231 /* ClassExpression */:
    case 264 /* InterfaceDeclaration */:
    case 265 /* TypeAliasDeclaration */:
      if (node.typeParameters === list) {
        return 30 /* LessThanToken */;
      }
      break;
    case 183 /* TypeReference */:
    case 215 /* TaggedTemplateExpression */:
    case 186 /* TypeQuery */:
    case 233 /* ExpressionWithTypeArguments */:
    case 205 /* ImportType */:
      if (node.typeArguments === list) {
        return 30 /* LessThanToken */;
      }
      break;
    case 187 /* TypeLiteral */:
      return 19 /* OpenBraceToken */;
  }
  return 0 /* Unknown */;
}
function getCloseTokenForOpenToken(kind) {
  switch (kind) {
    case 21 /* OpenParenToken */:
      return 22 /* CloseParenToken */;
    case 30 /* LessThanToken */:
      return 32 /* GreaterThanToken */;
    case 19 /* OpenBraceToken */:
      return 20 /* CloseBraceToken */;
  }
  return 0 /* Unknown */;
}
var internedSizes;
var internedTabsIndentation;
var internedSpacesIndentation;
function getIndentationString(indentation, options) {
  const resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize);
  if (resetInternedStrings) {
    internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize };
    internedTabsIndentation = internedSpacesIndentation = void 0;
  }
  if (!options.convertTabsToSpaces) {
    const tabs = Math.floor(indentation / options.tabSize);
    const spaces = indentation - tabs * options.tabSize;
    let tabString;
    if (!internedTabsIndentation) {
      internedTabsIndentation = [];
    }
    if (internedTabsIndentation[tabs] === void 0) {
      internedTabsIndentation[tabs] = tabString = repeatString("	", tabs);
    } else {
      tabString = internedTabsIndentation[tabs];
    }
    return spaces ? tabString + repeatString(" ", spaces) : tabString;
  } else {
    let spacesString;
    const quotient = Math.floor(indentation / options.indentSize);
    const remainder = indentation % options.indentSize;
    if (!internedSpacesIndentation) {
      internedSpacesIndentation = [];
    }
    if (internedSpacesIndentation[quotient] === void 0) {
      spacesString = repeatString(" ", options.indentSize * quotient);
      internedSpacesIndentation[quotient] = spacesString;
    } else {
      spacesString = internedSpacesIndentation[quotient];
    }
    return remainder ? spacesString + repeatString(" ", remainder) : spacesString;
  }
}

// src/services/formatting/smartIndenter.ts
var SmartIndenter;
((SmartIndenter2) => {
  let Value;
  ((Value2) => {
    Value2[Value2["Unknown"] = -1] = "Unknown";
  })(Value || (Value = {}));
  function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace = false) {
    if (position > sourceFile.text.length) {
      return getBaseIndentation(options);
    }
    if (options.indentStyle === 0 /* None */) {
      return 0;
    }
    const precedingToken = findPrecedingToken(
      position,
      sourceFile,
      /*startNode*/
      void 0,
      /*excludeJsdoc*/
      true
    );
    const enclosingCommentRange = getRangeOfEnclosingComment(sourceFile, position, precedingToken || null);
    if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) {
      return getCommentIndent(sourceFile, position, options, enclosingCommentRange);
    }
    if (!precedingToken) {
      return getBaseIndentation(options);
    }
    const precedingTokenIsLiteral = isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind);
    if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) {
      return 0;
    }
    const lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
    const currentToken = getTokenAtPosition(sourceFile, position);
    const isObjectLiteral = currentToken.kind === 19 /* OpenBraceToken */ && currentToken.parent.kind === 210 /* ObjectLiteralExpression */;
    if (options.indentStyle === 1 /* Block */ || isObjectLiteral) {
      return getBlockIndent(sourceFile, position, options);
    }
    if (precedingToken.kind === 28 /* CommaToken */ && precedingToken.parent.kind !== 226 /* BinaryExpression */) {
      const actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options);
      if (actualIndentation !== -1 /* Unknown */) {
        return actualIndentation;
      }
    }
    const containerList = getListByPosition(position, precedingToken.parent, sourceFile);
    if (containerList && !rangeContainsRange(containerList, precedingToken)) {
      const useTheSameBaseIndentation = [218 /* FunctionExpression */, 219 /* ArrowFunction */].includes(currentToken.parent.kind);
      const indentSize = useTheSameBaseIndentation ? 0 : options.indentSize;
      return getActualIndentationForListStartLine(containerList, sourceFile, options) + indentSize;
    }
    return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options);
  }
  SmartIndenter2.getIndentation = getIndentation;
  function getCommentIndent(sourceFile, position, options, enclosingCommentRange) {
    const previousLine = getLineAndCharacterOfPosition(sourceFile, position).line - 1;
    const commentStartLine = getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line;
    Debug.assert(commentStartLine >= 0);
    if (previousLine <= commentStartLine) {
      return findFirstNonWhitespaceColumn(getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options);
    }
    const startPositionOfLine = getStartPositionOfLine(previousLine, sourceFile);
    const { column, character } = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options);
    if (column === 0) {
      return column;
    }
    const firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character);
    return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column;
  }
  function getBlockIndent(sourceFile, position, options) {
    let current = position;
    while (current > 0) {
      const char = sourceFile.text.charCodeAt(current);
      if (!isWhiteSpaceLike(char)) {
        break;
      }
      current--;
    }
    const lineStart = getLineStartPositionForPosition(current, sourceFile);
    return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options);
  }
  function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) {
    let previous;
    let current = precedingToken;
    while (current) {
      if (positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(
        options,
        current,
        previous,
        sourceFile,
        /*isNextChild*/
        true
      )) {
        const currentStart = getStartLineAndCharacterForNode(current, sourceFile);
        const nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile);
        const indentationDelta = nextTokenKind !== 0 /* Unknown */ ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 : lineAtPosition !== currentStart.line ? options.indentSize : 0;
        return getIndentationForNodeWorker(
          current,
          currentStart,
          /*ignoreActualIndentationRange*/
          void 0,
          indentationDelta,
          sourceFile,
          /*isNextChild*/
          true,
          options
        );
      }
      const actualIndentation = getActualIndentationForListItem(
        current,
        sourceFile,
        options,
        /*listIndentsChild*/
        true
      );
      if (actualIndentation !== -1 /* Unknown */) {
        return actualIndentation;
      }
      previous = current;
      current = current.parent;
    }
    return getBaseIndentation(options);
  }
  function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) {
    const start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
    return getIndentationForNodeWorker(
      n,
      start,
      ignoreActualIndentationRange,
      /*indentationDelta*/
      0,
      sourceFile,
      /*isNextChild*/
      false,
      options
    );
  }
  SmartIndenter2.getIndentationForNode = getIndentationForNode;
  function getBaseIndentation(options) {
    return options.baseIndentSize || 0;
  }
  SmartIndenter2.getBaseIndentation = getBaseIndentation;
  function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) {
    var _a;
    let parent2 = current.parent;
    while (parent2) {
      let useActualIndentation = true;
      if (ignoreActualIndentationRange) {
        const start = current.getStart(sourceFile);
        useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end;
      }
      const containingListOrParentStart = getContainingListOrParentStart(parent2, current, sourceFile);
      const parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent2, current, currentStart.line, sourceFile);
      if (useActualIndentation) {
        const firstListChild = (_a = getContainingList(current, sourceFile)) == null ? void 0 : _a[0];
        const listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line;
        let actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild);
        if (actualIndentation !== -1 /* Unknown */) {
          return actualIndentation + indentationDelta;
        }
        actualIndentation = getActualIndentationForNode(current, parent2, currentStart, parentAndChildShareLine, sourceFile, options);
        if (actualIndentation !== -1 /* Unknown */) {
          return actualIndentation + indentationDelta;
        }
      }
      if (shouldIndentChildNode(options, parent2, current, sourceFile, isNextChild) && !parentAndChildShareLine) {
        indentationDelta += options.indentSize;
      }
      const useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent2, current, currentStart.line, sourceFile);
      current = parent2;
      parent2 = current.parent;
      currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart;
    }
    return indentationDelta + getBaseIndentation(options);
  }
  function getContainingListOrParentStart(parent2, child, sourceFile) {
    const containingList = getContainingList(child, sourceFile);
    const startPos = containingList ? containingList.pos : parent2.getStart(sourceFile);
    return sourceFile.getLineAndCharacterOfPosition(startPos);
  }
  function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) {
    const commaItemInfo = findListItemInfo(commaToken);
    if (commaItemInfo && commaItemInfo.listItemIndex > 0) {
      return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options);
    } else {
      return -1 /* Unknown */;
    }
  }
  function getActualIndentationForNode(current, parent2, currentLineAndChar, parentAndChildShareLine, sourceFile, options) {
    const useActualIndentation = (isDeclaration(current) || isStatementButNotDeclaration(current)) && (parent2.kind === 307 /* SourceFile */ || !parentAndChildShareLine);
    if (!useActualIndentation) {
      return -1 /* Unknown */;
    }
    return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options);
  }
  let NextTokenKind;
  ((NextTokenKind2) => {
    NextTokenKind2[NextTokenKind2["Unknown"] = 0] = "Unknown";
    NextTokenKind2[NextTokenKind2["OpenBrace"] = 1] = "OpenBrace";
    NextTokenKind2[NextTokenKind2["CloseBrace"] = 2] = "CloseBrace";
  })(NextTokenKind || (NextTokenKind = {}));
  function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
    const nextToken = findNextToken(precedingToken, current, sourceFile);
    if (!nextToken) {
      return 0 /* Unknown */;
    }
    if (nextToken.kind === 19 /* OpenBraceToken */) {
      return 1 /* OpenBrace */;
    } else if (nextToken.kind === 20 /* CloseBraceToken */) {
      const nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line;
      return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */;
    }
    return 0 /* Unknown */;
  }
  function getStartLineAndCharacterForNode(n, sourceFile) {
    return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
  }
  function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent2, child, childStartLine, sourceFile) {
    if (!(isCallExpression(parent2) && contains(parent2.arguments, child))) {
      return false;
    }
    const expressionOfCallExpressionEnd = parent2.expression.getEnd();
    const expressionOfCallExpressionEndLine = getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line;
    return expressionOfCallExpressionEndLine === childStartLine;
  }
  SmartIndenter2.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled;
  function childStartsOnTheSameLineWithElseInIfStatement(parent2, child, childStartLine, sourceFile) {
    if (parent2.kind === 245 /* IfStatement */ && parent2.elseStatement === child) {
      const elseKeyword = findChildOfKind(parent2, 93 /* ElseKeyword */, sourceFile);
      Debug.assert(elseKeyword !== void 0);
      const elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line;
      return elseKeywordStartLine === childStartLine;
    }
    return false;
  }
  SmartIndenter2.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement;
  function childIsUnindentedBranchOfConditionalExpression(parent2, child, childStartLine, sourceFile) {
    if (isConditionalExpression(parent2) && (child === parent2.whenTrue || child === parent2.whenFalse)) {
      const conditionEndLine = getLineAndCharacterOfPosition(sourceFile, parent2.condition.end).line;
      if (child === parent2.whenTrue) {
        return childStartLine === conditionEndLine;
      } else {
        const trueStartLine = getStartLineAndCharacterForNode(parent2.whenTrue, sourceFile).line;
        const trueEndLine = getLineAndCharacterOfPosition(sourceFile, parent2.whenTrue.end).line;
        return conditionEndLine === trueStartLine && trueEndLine === childStartLine;
      }
    }
    return false;
  }
  SmartIndenter2.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression;
  function argumentStartsOnSameLineAsPreviousArgument(parent2, child, childStartLine, sourceFile) {
    if (isCallOrNewExpression(parent2)) {
      if (!parent2.arguments) return false;
      const currentNode = find(parent2.arguments, (arg) => arg.pos === child.pos);
      if (!currentNode) return false;
      const currentIndex = parent2.arguments.indexOf(currentNode);
      if (currentIndex === 0) return false;
      const previousNode = parent2.arguments[currentIndex - 1];
      const lineOfPreviousNode = getLineAndCharacterOfPosition(sourceFile, previousNode.getEnd()).line;
      if (childStartLine === lineOfPreviousNode) {
        return true;
      }
    }
    return false;
  }
  SmartIndenter2.argumentStartsOnSameLineAsPreviousArgument = argumentStartsOnSameLineAsPreviousArgument;
  function getContainingList(node, sourceFile) {
    return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile);
  }
  SmartIndenter2.getContainingList = getContainingList;
  function getListByPosition(pos, node, sourceFile) {
    return node && getListByRange(pos, pos, node, sourceFile);
  }
  function getListByRange(start, end, node, sourceFile) {
    switch (node.kind) {
      case 183 /* TypeReference */:
        return getList(node.typeArguments);
      case 210 /* ObjectLiteralExpression */:
        return getList(node.properties);
      case 209 /* ArrayLiteralExpression */:
        return getList(node.elements);
      case 187 /* TypeLiteral */:
        return getList(node.members);
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
      case 179 /* CallSignature */:
      case 176 /* Constructor */:
      case 185 /* ConstructorType */:
      case 180 /* ConstructSignature */:
        return getList(node.typeParameters) || getList(node.parameters);
      case 177 /* GetAccessor */:
        return getList(node.parameters);
      case 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
      case 264 /* InterfaceDeclaration */:
      case 265 /* TypeAliasDeclaration */:
      case 345 /* JSDocTemplateTag */:
        return getList(node.typeParameters);
      case 214 /* NewExpression */:
      case 213 /* CallExpression */:
        return getList(node.typeArguments) || getList(node.arguments);
      case 261 /* VariableDeclarationList */:
        return getList(node.declarations);
      case 275 /* NamedImports */:
      case 279 /* NamedExports */:
        return getList(node.elements);
      case 206 /* ObjectBindingPattern */:
      case 207 /* ArrayBindingPattern */:
        return getList(node.elements);
    }
    function getList(list) {
      return list && rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : void 0;
    }
  }
  function getVisualListRange(node, list, sourceFile) {
    const children = node.getChildren(sourceFile);
    for (let i = 1; i < children.length - 1; i++) {
      if (children[i].pos === list.pos && children[i].end === list.end) {
        return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) };
      }
    }
    return list;
  }
  function getActualIndentationForListStartLine(list, sourceFile, options) {
    if (!list) {
      return -1 /* Unknown */;
    }
    return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options);
  }
  function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) {
    if (node.parent && node.parent.kind === 261 /* VariableDeclarationList */) {
      return -1 /* Unknown */;
    }
    const containingList = getContainingList(node, sourceFile);
    if (containingList) {
      const index = containingList.indexOf(node);
      if (index !== -1) {
        const result = deriveActualIndentationFromList(containingList, index, sourceFile, options);
        if (result !== -1 /* Unknown */) {
          return result;
        }
      }
      return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0);
    }
    return -1 /* Unknown */;
  }
  function deriveActualIndentationFromList(list, index, sourceFile, options) {
    Debug.assert(index >= 0 && index < list.length);
    const node = list[index];
    let lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile);
    for (let i = index - 1; i >= 0; i--) {
      if (list[i].kind === 28 /* CommaToken */) {
        continue;
      }
      const prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line;
      if (prevEndLine !== lineAndCharacter.line) {
        return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options);
      }
      lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile);
    }
    return -1 /* Unknown */;
  }
  function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) {
    const lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0);
    return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options);
  }
  function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) {
    let character = 0;
    let column = 0;
    for (let pos = startPos; pos < endPos; pos++) {
      const ch = sourceFile.text.charCodeAt(pos);
      if (!isWhiteSpaceSingleLine(ch)) {
        break;
      }
      if (ch === 9 /* tab */) {
        column += options.tabSize + column % options.tabSize;
      } else {
        column++;
      }
      character++;
    }
    return { column, character };
  }
  SmartIndenter2.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn;
  function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) {
    return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column;
  }
  SmartIndenter2.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn;
  function nodeWillIndentChild(settings, parent2, child, sourceFile, indentByDefault) {
    const childKind = child ? child.kind : 0 /* Unknown */;
    switch (parent2.kind) {
      case 244 /* ExpressionStatement */:
      case 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
      case 264 /* InterfaceDeclaration */:
      case 266 /* EnumDeclaration */:
      case 265 /* TypeAliasDeclaration */:
      case 209 /* ArrayLiteralExpression */:
      case 241 /* Block */:
      case 268 /* ModuleBlock */:
      case 210 /* ObjectLiteralExpression */:
      case 187 /* TypeLiteral */:
      case 200 /* MappedType */:
      case 189 /* TupleType */:
      case 217 /* ParenthesizedExpression */:
      case 211 /* PropertyAccessExpression */:
      case 213 /* CallExpression */:
      case 214 /* NewExpression */:
      case 243 /* VariableStatement */:
      case 277 /* ExportAssignment */:
      case 253 /* ReturnStatement */:
      case 227 /* ConditionalExpression */:
      case 207 /* ArrayBindingPattern */:
      case 206 /* ObjectBindingPattern */:
      case 286 /* JsxOpeningElement */:
      case 289 /* JsxOpeningFragment */:
      case 285 /* JsxSelfClosingElement */:
      case 294 /* JsxExpression */:
      case 173 /* MethodSignature */:
      case 179 /* CallSignature */:
      case 180 /* ConstructSignature */:
      case 169 /* Parameter */:
      case 184 /* FunctionType */:
      case 185 /* ConstructorType */:
      case 196 /* ParenthesizedType */:
      case 215 /* TaggedTemplateExpression */:
      case 223 /* AwaitExpression */:
      case 279 /* NamedExports */:
      case 275 /* NamedImports */:
      case 281 /* ExportSpecifier */:
      case 276 /* ImportSpecifier */:
      case 172 /* PropertyDeclaration */:
      case 296 /* CaseClause */:
      case 297 /* DefaultClause */:
        return true;
      case 269 /* CaseBlock */:
        return settings.indentSwitchCase ?? true;
      case 260 /* VariableDeclaration */:
      case 303 /* PropertyAssignment */:
      case 226 /* BinaryExpression */:
        if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 210 /* ObjectLiteralExpression */) {
          return rangeIsOnOneLine(sourceFile, child);
        }
        if (parent2.kind === 226 /* BinaryExpression */ && sourceFile && child && childKind === 284 /* JsxElement */) {
          const parentStartLine = sourceFile.getLineAndCharacterOfPosition(skipTrivia(sourceFile.text, parent2.pos)).line;
          const childStartLine = sourceFile.getLineAndCharacterOfPosition(skipTrivia(sourceFile.text, child.pos)).line;
          return parentStartLine !== childStartLine;
        }
        if (parent2.kind !== 226 /* BinaryExpression */) {
          return true;
        }
        break;
      case 246 /* DoStatement */:
      case 247 /* WhileStatement */:
      case 249 /* ForInStatement */:
      case 250 /* ForOfStatement */:
      case 248 /* ForStatement */:
      case 245 /* IfStatement */:
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
      case 174 /* MethodDeclaration */:
      case 176 /* Constructor */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        return childKind !== 241 /* Block */;
      case 219 /* ArrowFunction */:
        if (sourceFile && childKind === 217 /* ParenthesizedExpression */) {
          return rangeIsOnOneLine(sourceFile, child);
        }
        return childKind !== 241 /* Block */;
      case 278 /* ExportDeclaration */:
        return childKind !== 279 /* NamedExports */;
      case 272 /* ImportDeclaration */:
        return childKind !== 273 /* ImportClause */ || !!child.namedBindings && child.namedBindings.kind !== 275 /* NamedImports */;
      case 284 /* JsxElement */:
        return childKind !== 287 /* JsxClosingElement */;
      case 288 /* JsxFragment */:
        return childKind !== 290 /* JsxClosingFragment */;
      case 193 /* IntersectionType */:
      case 192 /* UnionType */:
      case 238 /* SatisfiesExpression */:
        if (childKind === 187 /* TypeLiteral */ || childKind === 189 /* TupleType */ || childKind === 200 /* MappedType */) {
          return false;
        }
        break;
    }
    return indentByDefault;
  }
  SmartIndenter2.nodeWillIndentChild = nodeWillIndentChild;
  function isControlFlowEndingStatement(kind, parent2) {
    switch (kind) {
      case 253 /* ReturnStatement */:
      case 257 /* ThrowStatement */:
      case 251 /* ContinueStatement */:
      case 252 /* BreakStatement */:
        return parent2.kind !== 241 /* Block */;
      default:
        return false;
    }
  }
  function shouldIndentChildNode(settings, parent2, child, sourceFile, isNextChild = false) {
    return nodeWillIndentChild(
      settings,
      parent2,
      child,
      sourceFile,
      /*indentByDefault*/
      false
    ) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent2));
  }
  SmartIndenter2.shouldIndentChildNode = shouldIndentChildNode;
  function rangeIsOnOneLine(sourceFile, range) {
    const rangeStart = skipTrivia(sourceFile.text, range.pos);
    const startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line;
    const endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
    return startLine === endLine;
  }
})(SmartIndenter || (SmartIndenter = {}));

// src/services/_namespaces/ts.preparePasteEdits.ts
var ts_preparePasteEdits_exports = {};
__export(ts_preparePasteEdits_exports, {
  preparePasteEdits: () => preparePasteEdits
});

// src/services/preparePasteEdits.ts
function preparePasteEdits(sourceFile, copiedFromRange, checker) {
  let shouldProvidePasteEdits = false;
  copiedFromRange.forEach((range) => {
    const enclosingNode = findAncestor(
      getTokenAtPosition(sourceFile, range.pos),
      (ancestorNode) => rangeContainsRange(ancestorNode, range)
    );
    if (!enclosingNode) return;
    forEachChild(enclosingNode, function checkNameResolution(node) {
      var _a;
      if (shouldProvidePasteEdits) return;
      if (isIdentifier(node) && rangeContainsPosition(range, node.getStart(sourceFile))) {
        const resolvedSymbol = checker.resolveName(
          node.text,
          node,
          -1 /* All */,
          /*excludeGlobals*/
          false
        );
        if (resolvedSymbol && resolvedSymbol.declarations) {
          for (const decl of resolvedSymbol.declarations) {
            if (isInImport(decl) || !!(node.text && sourceFile.symbol && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(node.escapedText)))) {
              shouldProvidePasteEdits = true;
              return;
            }
          }
        }
      }
      node.forEachChild(checkNameResolution);
    });
    if (shouldProvidePasteEdits) return;
  });
  return shouldProvidePasteEdits;
}

// src/services/_namespaces/ts.PasteEdits.ts
var ts_PasteEdits_exports = {};
__export(ts_PasteEdits_exports, {
  pasteEditsProvider: () => pasteEditsProvider
});

// src/services/pasteEdits.ts
var fixId55 = "providePostPasteEdits";
function pasteEditsProvider(targetFile, pastedText, pasteLocations, copiedFrom, host, preferences, formatContext, cancellationToken) {
  const changes = ts_textChanges_exports.ChangeTracker.with({ host, formatContext, preferences }, (changeTracker) => pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, preferences, formatContext, cancellationToken, changeTracker));
  return { edits: changes, fixId: fixId55 };
}
function pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, preferences, formatContext, cancellationToken, changes) {
  let actualPastedText;
  if (pastedText.length !== pasteLocations.length) {
    actualPastedText = pastedText.length === 1 ? pastedText[0] : pastedText.join(getNewLineOrDefaultFromHost(formatContext.host, formatContext.options));
  }
  const statements = [];
  let newText = targetFile.text;
  for (let i = pasteLocations.length - 1; i >= 0; i--) {
    const { pos, end } = pasteLocations[i];
    newText = actualPastedText ? newText.slice(0, pos) + actualPastedText + newText.slice(end) : newText.slice(0, pos) + pastedText[i] + newText.slice(end);
  }
  let importAdder;
  Debug.checkDefined(host.runWithTemporaryFileUpdate).call(host, targetFile.fileName, newText, (updatedProgram, originalProgram, updatedFile) => {
    importAdder = ts_codefix_exports.createImportAdder(updatedFile, updatedProgram, preferences, host);
    if (copiedFrom == null ? void 0 : copiedFrom.range) {
      Debug.assert(copiedFrom.range.length === pastedText.length);
      copiedFrom.range.forEach((copy) => {
        const statementsInSourceFile = copiedFrom.file.statements;
        const startNodeIndex = findIndex(statementsInSourceFile, (s) => s.end > copy.pos);
        if (startNodeIndex === -1) return void 0;
        let endNodeIndex = findIndex(statementsInSourceFile, (s) => s.end >= copy.end, startNodeIndex);
        if (endNodeIndex !== -1 && copy.end <= statementsInSourceFile[endNodeIndex].getStart()) {
          endNodeIndex--;
        }
        statements.push(...statementsInSourceFile.slice(startNodeIndex, endNodeIndex === -1 ? statementsInSourceFile.length : endNodeIndex + 1));
      });
      Debug.assertIsDefined(originalProgram, "no original program found");
      const originalProgramTypeChecker = originalProgram.getTypeChecker();
      const usageInfoRange = getUsageInfoRangeForPasteEdits(copiedFrom);
      const usage = getUsageInfo(copiedFrom.file, statements, originalProgramTypeChecker, getExistingLocals(updatedFile, statements, originalProgramTypeChecker), usageInfoRange);
      const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFile.fileName, originalProgram, host, !!copiedFrom.file.commonJsModuleIndicator);
      addExportsInOldFile(copiedFrom.file, usage.targetFileImportsFromOldFile, changes, useEsModuleSyntax);
      addTargetFileImports(copiedFrom.file, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, originalProgramTypeChecker, updatedProgram, importAdder);
    } else {
      const context = {
        sourceFile: updatedFile,
        program: originalProgram,
        cancellationToken,
        host,
        preferences,
        formatContext
      };
      let offset = 0;
      pasteLocations.forEach((location, i) => {
        const oldTextLength = location.end - location.pos;
        const textToBePasted = actualPastedText ?? pastedText[i];
        const startPos = location.pos + offset;
        const endPos = startPos + textToBePasted.length;
        const range = { pos: startPos, end: endPos };
        offset += textToBePasted.length - oldTextLength;
        const enclosingNode = findAncestor(
          getTokenAtPosition(context.sourceFile, range.pos),
          (ancestorNode) => rangeContainsRange(ancestorNode, range)
        );
        if (!enclosingNode) return;
        forEachChild(enclosingNode, function importUnresolvedIdentifiers(node) {
          const isImportCandidate = isIdentifier(node) && rangeContainsPosition(range, node.getStart(updatedFile)) && !(updatedProgram == null ? void 0 : updatedProgram.getTypeChecker().resolveName(
            node.text,
            node,
            -1 /* All */,
            /*excludeGlobals*/
            false
          ));
          if (isImportCandidate) {
            return importAdder.addImportForUnresolvedIdentifier(
              context,
              node,
              /*useAutoImportProvider*/
              true
            );
          }
          node.forEachChild(importUnresolvedIdentifiers);
        });
      });
    }
    importAdder.writeFixes(changes, getQuotePreference(copiedFrom ? copiedFrom.file : targetFile, preferences));
  });
  if (!importAdder.hasFixes()) {
    return;
  }
  pasteLocations.forEach((paste, i) => {
    changes.replaceRangeWithText(
      targetFile,
      { pos: paste.pos, end: paste.end },
      actualPastedText ?? pastedText[i]
    );
  });
}
function getUsageInfoRangeForPasteEdits({ file: sourceFile, range }) {
  const pos = range[0].pos;
  const end = range[range.length - 1].end;
  const startToken = getTokenAtPosition(sourceFile, pos);
  const endToken = findTokenOnLeftOfPosition(sourceFile, pos) ?? getTokenAtPosition(sourceFile, end);
  return {
    pos: isIdentifier(startToken) && pos <= startToken.getStart(sourceFile) ? startToken.getFullStart() : pos,
    end: isIdentifier(endToken) && end === endToken.getEnd() ? ts_textChanges_exports.getAdjustedEndPosition(sourceFile, endToken, {}) : end
  };
}

// src/server/_namespaces/ts.ts
var ts_exports2 = {};
__export(ts_exports2, {
  ANONYMOUS: () => ANONYMOUS,
  AccessFlags: () => AccessFlags,
  AssertionLevel: () => AssertionLevel,
  AssignmentDeclarationKind: () => AssignmentDeclarationKind,
  AssignmentKind: () => AssignmentKind,
  Associativity: () => Associativity,
  BreakpointResolver: () => ts_BreakpointResolver_exports,
  BuilderFileEmit: () => BuilderFileEmit,
  BuilderProgramKind: () => BuilderProgramKind,
  BuilderState: () => BuilderState,
  CallHierarchy: () => ts_CallHierarchy_exports,
  CharacterCodes: () => CharacterCodes,
  CheckFlags: () => CheckFlags,
  CheckMode: () => CheckMode,
  ClassificationType: () => ClassificationType,
  ClassificationTypeNames: () => ClassificationTypeNames,
  CommentDirectiveType: () => CommentDirectiveType,
  Comparison: () => Comparison,
  CompletionInfoFlags: () => CompletionInfoFlags,
  CompletionTriggerKind: () => CompletionTriggerKind,
  Completions: () => ts_Completions_exports,
  ContainerFlags: () => ContainerFlags,
  ContextFlags: () => ContextFlags,
  Debug: () => Debug,
  DiagnosticCategory: () => DiagnosticCategory,
  Diagnostics: () => Diagnostics,
  DocumentHighlights: () => DocumentHighlights,
  ElementFlags: () => ElementFlags,
  EmitFlags: () => EmitFlags,
  EmitHint: () => EmitHint,
  EmitOnly: () => EmitOnly,
  EndOfLineState: () => EndOfLineState,
  ExitStatus: () => ExitStatus,
  ExportKind: () => ExportKind,
  Extension: () => Extension,
  ExternalEmitHelpers: () => ExternalEmitHelpers,
  FileIncludeKind: () => FileIncludeKind,
  FilePreprocessingDiagnosticsKind: () => FilePreprocessingDiagnosticsKind,
  FileSystemEntryKind: () => FileSystemEntryKind,
  FileWatcherEventKind: () => FileWatcherEventKind,
  FindAllReferences: () => ts_FindAllReferences_exports,
  FlattenLevel: () => FlattenLevel,
  FlowFlags: () => FlowFlags,
  ForegroundColorEscapeSequences: () => ForegroundColorEscapeSequences,
  FunctionFlags: () => FunctionFlags,
  GeneratedIdentifierFlags: () => GeneratedIdentifierFlags,
  GetLiteralTextFlags: () => GetLiteralTextFlags,
  GoToDefinition: () => ts_GoToDefinition_exports,
  HighlightSpanKind: () => HighlightSpanKind,
  IdentifierNameMap: () => IdentifierNameMap,
  ImportKind: () => ImportKind,
  ImportsNotUsedAsValues: () => ImportsNotUsedAsValues,
  IndentStyle: () => IndentStyle,
  IndexFlags: () => IndexFlags,
  IndexKind: () => IndexKind,
  InferenceFlags: () => InferenceFlags,
  InferencePriority: () => InferencePriority,
  InlayHintKind: () => InlayHintKind2,
  InlayHints: () => ts_InlayHints_exports,
  InternalEmitFlags: () => InternalEmitFlags,
  InternalNodeBuilderFlags: () => InternalNodeBuilderFlags,
  InternalSymbolName: () => InternalSymbolName,
  IntersectionFlags: () => IntersectionFlags,
  InvalidatedProjectKind: () => InvalidatedProjectKind,
  JSDocParsingMode: () => JSDocParsingMode,
  JsDoc: () => ts_JsDoc_exports,
  JsTyping: () => ts_JsTyping_exports,
  JsxEmit: () => JsxEmit,
  JsxFlags: () => JsxFlags,
  JsxReferenceKind: () => JsxReferenceKind,
  LanguageFeatureMinimumTarget: () => LanguageFeatureMinimumTarget,
  LanguageServiceMode: () => LanguageServiceMode,
  LanguageVariant: () => LanguageVariant,
  LexicalEnvironmentFlags: () => LexicalEnvironmentFlags,
  ListFormat: () => ListFormat,
  LogLevel: () => LogLevel,
  MapCode: () => ts_MapCode_exports,
  MemberOverrideStatus: () => MemberOverrideStatus,
  ModifierFlags: () => ModifierFlags,
  ModuleDetectionKind: () => ModuleDetectionKind,
  ModuleInstanceState: () => ModuleInstanceState,
  ModuleKind: () => ModuleKind,
  ModuleResolutionKind: () => ModuleResolutionKind,
  ModuleSpecifierEnding: () => ModuleSpecifierEnding,
  NavigateTo: () => ts_NavigateTo_exports,
  NavigationBar: () => ts_NavigationBar_exports,
  NewLineKind: () => NewLineKind,
  NodeBuilderFlags: () => NodeBuilderFlags,
  NodeCheckFlags: () => NodeCheckFlags,
  NodeFactoryFlags: () => NodeFactoryFlags,
  NodeFlags: () => NodeFlags,
  NodeResolutionFeatures: () => NodeResolutionFeatures,
  ObjectFlags: () => ObjectFlags,
  OperationCanceledException: () => OperationCanceledException,
  OperatorPrecedence: () => OperatorPrecedence,
  OrganizeImports: () => ts_OrganizeImports_exports,
  OrganizeImportsMode: () => OrganizeImportsMode,
  OuterExpressionKinds: () => OuterExpressionKinds,
  OutliningElementsCollector: () => ts_OutliningElementsCollector_exports,
  OutliningSpanKind: () => OutliningSpanKind,
  OutputFileType: () => OutputFileType,
  PackageJsonAutoImportPreference: () => PackageJsonAutoImportPreference,
  PackageJsonDependencyGroup: () => PackageJsonDependencyGroup,
  PatternMatchKind: () => PatternMatchKind,
  PollingInterval: () => PollingInterval,
  PollingWatchKind: () => PollingWatchKind,
  PragmaKindFlags: () => PragmaKindFlags,
  PredicateSemantics: () => PredicateSemantics,
  PreparePasteEdits: () => ts_preparePasteEdits_exports,
  PrivateIdentifierKind: () => PrivateIdentifierKind,
  ProcessLevel: () => ProcessLevel,
  ProgramUpdateLevel: () => ProgramUpdateLevel,
  QuotePreference: () => QuotePreference,
  RegularExpressionFlags: () => RegularExpressionFlags,
  RelationComparisonResult: () => RelationComparisonResult,
  Rename: () => ts_Rename_exports,
  ScriptElementKind: () => ScriptElementKind,
  ScriptElementKindModifier: () => ScriptElementKindModifier,
  ScriptKind: () => ScriptKind,
  ScriptSnapshot: () => ScriptSnapshot,
  ScriptTarget: () => ScriptTarget,
  SemanticClassificationFormat: () => SemanticClassificationFormat,
  SemanticMeaning: () => SemanticMeaning,
  SemicolonPreference: () => SemicolonPreference,
  SignatureCheckMode: () => SignatureCheckMode,
  SignatureFlags: () => SignatureFlags,
  SignatureHelp: () => ts_SignatureHelp_exports,
  SignatureInfo: () => SignatureInfo,
  SignatureKind: () => SignatureKind,
  SmartSelectionRange: () => ts_SmartSelectionRange_exports,
  SnippetKind: () => SnippetKind,
  StatisticType: () => StatisticType,
  StructureIsReused: () => StructureIsReused,
  SymbolAccessibility: () => SymbolAccessibility,
  SymbolDisplay: () => ts_SymbolDisplay_exports,
  SymbolDisplayPartKind: () => SymbolDisplayPartKind,
  SymbolFlags: () => SymbolFlags,
  SymbolFormatFlags: () => SymbolFormatFlags,
  SyntaxKind: () => SyntaxKind,
  Ternary: () => Ternary,
  ThrottledCancellationToken: () => ThrottledCancellationToken,
  TokenClass: () => TokenClass,
  TokenFlags: () => TokenFlags,
  TransformFlags: () => TransformFlags,
  TypeFacts: () => TypeFacts,
  TypeFlags: () => TypeFlags,
  TypeFormatFlags: () => TypeFormatFlags,
  TypeMapKind: () => TypeMapKind,
  TypePredicateKind: () => TypePredicateKind,
  TypeReferenceSerializationKind: () => TypeReferenceSerializationKind,
  UnionReduction: () => UnionReduction,
  UpToDateStatusType: () => UpToDateStatusType,
  VarianceFlags: () => VarianceFlags,
  Version: () => Version,
  VersionRange: () => VersionRange,
  WatchDirectoryFlags: () => WatchDirectoryFlags,
  WatchDirectoryKind: () => WatchDirectoryKind,
  WatchFileKind: () => WatchFileKind,
  WatchLogLevel: () => WatchLogLevel,
  WatchType: () => WatchType,
  accessPrivateIdentifier: () => accessPrivateIdentifier,
  addEmitFlags: () => addEmitFlags,
  addEmitHelper: () => addEmitHelper,
  addEmitHelpers: () => addEmitHelpers,
  addInternalEmitFlags: () => addInternalEmitFlags,
  addNodeFactoryPatcher: () => addNodeFactoryPatcher,
  addObjectAllocatorPatcher: () => addObjectAllocatorPatcher,
  addRange: () => addRange,
  addRelatedInfo: () => addRelatedInfo,
  addSyntheticLeadingComment: () => addSyntheticLeadingComment,
  addSyntheticTrailingComment: () => addSyntheticTrailingComment,
  addToSeen: () => addToSeen,
  advancedAsyncSuperHelper: () => advancedAsyncSuperHelper,
  affectsDeclarationPathOptionDeclarations: () => affectsDeclarationPathOptionDeclarations,
  affectsEmitOptionDeclarations: () => affectsEmitOptionDeclarations,
  allKeysStartWithDot: () => allKeysStartWithDot,
  altDirectorySeparator: () => altDirectorySeparator,
  and: () => and,
  append: () => append,
  appendIfUnique: () => appendIfUnique,
  arrayFrom: () => arrayFrom,
  arrayIsEqualTo: () => arrayIsEqualTo,
  arrayIsHomogeneous: () => arrayIsHomogeneous,
  arrayOf: () => arrayOf,
  arrayReverseIterator: () => arrayReverseIterator,
  arrayToMap: () => arrayToMap,
  arrayToMultiMap: () => arrayToMultiMap,
  arrayToNumericMap: () => arrayToNumericMap,
  assertType: () => assertType,
  assign: () => assign,
  asyncSuperHelper: () => asyncSuperHelper,
  attachFileToDiagnostics: () => attachFileToDiagnostics,
  base64decode: () => base64decode,
  base64encode: () => base64encode,
  binarySearch: () => binarySearch,
  binarySearchKey: () => binarySearchKey,
  bindSourceFile: () => bindSourceFile,
  breakIntoCharacterSpans: () => breakIntoCharacterSpans,
  breakIntoWordSpans: () => breakIntoWordSpans,
  buildLinkParts: () => buildLinkParts,
  buildOpts: () => buildOpts,
  buildOverload: () => buildOverload,
  bundlerModuleNameResolver: () => bundlerModuleNameResolver,
  canBeConvertedToAsync: () => canBeConvertedToAsync,
  canHaveDecorators: () => canHaveDecorators,
  canHaveExportModifier: () => canHaveExportModifier,
  canHaveFlowNode: () => canHaveFlowNode,
  canHaveIllegalDecorators: () => canHaveIllegalDecorators,
  canHaveIllegalModifiers: () => canHaveIllegalModifiers,
  canHaveIllegalType: () => canHaveIllegalType,
  canHaveIllegalTypeParameters: () => canHaveIllegalTypeParameters,
  canHaveJSDoc: () => canHaveJSDoc,
  canHaveLocals: () => canHaveLocals,
  canHaveModifiers: () => canHaveModifiers,
  canHaveModuleSpecifier: () => canHaveModuleSpecifier,
  canHaveSymbol: () => canHaveSymbol,
  canIncludeBindAndCheckDiagnostics: () => canIncludeBindAndCheckDiagnostics,
  canJsonReportNoInputFiles: () => canJsonReportNoInputFiles,
  canProduceDiagnostics: () => canProduceDiagnostics,
  canUsePropertyAccess: () => canUsePropertyAccess,
  canWatchAffectingLocation: () => canWatchAffectingLocation,
  canWatchAtTypes: () => canWatchAtTypes,
  canWatchDirectoryOrFile: () => canWatchDirectoryOrFile,
  canWatchDirectoryOrFilePath: () => canWatchDirectoryOrFilePath,
  cartesianProduct: () => cartesianProduct,
  cast: () => cast,
  chainBundle: () => chainBundle,
  chainDiagnosticMessages: () => chainDiagnosticMessages,
  changeAnyExtension: () => changeAnyExtension,
  changeCompilerHostLikeToUseCache: () => changeCompilerHostLikeToUseCache,
  changeExtension: () => changeExtension,
  changeFullExtension: () => changeFullExtension,
  changesAffectModuleResolution: () => changesAffectModuleResolution,
  changesAffectingProgramStructure: () => changesAffectingProgramStructure,
  characterCodeToRegularExpressionFlag: () => characterCodeToRegularExpressionFlag,
  childIsDecorated: () => childIsDecorated,
  classElementOrClassElementParameterIsDecorated: () => classElementOrClassElementParameterIsDecorated,
  classHasClassThisAssignment: () => classHasClassThisAssignment,
  classHasDeclaredOrExplicitlyAssignedName: () => classHasDeclaredOrExplicitlyAssignedName,
  classHasExplicitlyAssignedName: () => classHasExplicitlyAssignedName,
  classOrConstructorParameterIsDecorated: () => classOrConstructorParameterIsDecorated,
  classicNameResolver: () => classicNameResolver,
  classifier: () => ts_classifier_exports,
  cleanExtendedConfigCache: () => cleanExtendedConfigCache,
  clear: () => clear,
  clearMap: () => clearMap,
  clearSharedExtendedConfigFileWatcher: () => clearSharedExtendedConfigFileWatcher,
  climbPastPropertyAccess: () => climbPastPropertyAccess,
  clone: () => clone,
  cloneCompilerOptions: () => cloneCompilerOptions,
  closeFileWatcher: () => closeFileWatcher,
  closeFileWatcherOf: () => closeFileWatcherOf,
  codefix: () => ts_codefix_exports,
  collapseTextChangeRangesAcrossMultipleVersions: () => collapseTextChangeRangesAcrossMultipleVersions,
  collectExternalModuleInfo: () => collectExternalModuleInfo,
  combine: () => combine,
  combinePaths: () => combinePaths,
  commandLineOptionOfCustomType: () => commandLineOptionOfCustomType,
  commentPragmas: () => commentPragmas,
  commonOptionsWithBuild: () => commonOptionsWithBuild,
  compact: () => compact,
  compareBooleans: () => compareBooleans,
  compareDataObjects: () => compareDataObjects,
  compareDiagnostics: () => compareDiagnostics,
  compareEmitHelpers: () => compareEmitHelpers,
  compareNumberOfDirectorySeparators: () => compareNumberOfDirectorySeparators,
  comparePaths: () => comparePaths,
  comparePathsCaseInsensitive: () => comparePathsCaseInsensitive,
  comparePathsCaseSensitive: () => comparePathsCaseSensitive,
  comparePatternKeys: () => comparePatternKeys,
  compareProperties: () => compareProperties,
  compareStringsCaseInsensitive: () => compareStringsCaseInsensitive,
  compareStringsCaseInsensitiveEslintCompatible: () => compareStringsCaseInsensitiveEslintCompatible,
  compareStringsCaseSensitive: () => compareStringsCaseSensitive,
  compareStringsCaseSensitiveUI: () => compareStringsCaseSensitiveUI,
  compareTextSpans: () => compareTextSpans,
  compareValues: () => compareValues,
  compilerOptionsAffectDeclarationPath: () => compilerOptionsAffectDeclarationPath,
  compilerOptionsAffectEmit: () => compilerOptionsAffectEmit,
  compilerOptionsAffectSemanticDiagnostics: () => compilerOptionsAffectSemanticDiagnostics,
  compilerOptionsDidYouMeanDiagnostics: () => compilerOptionsDidYouMeanDiagnostics,
  compilerOptionsIndicateEsModules: () => compilerOptionsIndicateEsModules,
  computeCommonSourceDirectoryOfFilenames: () => computeCommonSourceDirectoryOfFilenames,
  computeLineAndCharacterOfPosition: () => computeLineAndCharacterOfPosition,
  computeLineOfPosition: () => computeLineOfPosition,
  computeLineStarts: () => computeLineStarts,
  computePositionOfLineAndCharacter: () => computePositionOfLineAndCharacter,
  computeSignatureWithDiagnostics: () => computeSignatureWithDiagnostics,
  computeSuggestionDiagnostics: () => computeSuggestionDiagnostics,
  computedOptions: () => computedOptions,
  concatenate: () => concatenate,
  concatenateDiagnosticMessageChains: () => concatenateDiagnosticMessageChains,
  consumesNodeCoreModules: () => consumesNodeCoreModules,
  contains: () => contains,
  containsIgnoredPath: () => containsIgnoredPath,
  containsObjectRestOrSpread: () => containsObjectRestOrSpread,
  containsParseError: () => containsParseError,
  containsPath: () => containsPath,
  convertCompilerOptionsForTelemetry: () => convertCompilerOptionsForTelemetry,
  convertCompilerOptionsFromJson: () => convertCompilerOptionsFromJson,
  convertJsonOption: () => convertJsonOption,
  convertToBase64: () => convertToBase64,
  convertToJson: () => convertToJson,
  convertToObject: () => convertToObject,
  convertToOptionsWithAbsolutePaths: () => convertToOptionsWithAbsolutePaths,
  convertToRelativePath: () => convertToRelativePath,
  convertToTSConfig: () => convertToTSConfig,
  convertTypeAcquisitionFromJson: () => convertTypeAcquisitionFromJson,
  copyComments: () => copyComments,
  copyEntries: () => copyEntries,
  copyLeadingComments: () => copyLeadingComments,
  copyProperties: () => copyProperties,
  copyTrailingAsLeadingComments: () => copyTrailingAsLeadingComments,
  copyTrailingComments: () => copyTrailingComments,
  couldStartTrivia: () => couldStartTrivia,
  countWhere: () => countWhere,
  createAbstractBuilder: () => createAbstractBuilder,
  createAccessorPropertyBackingField: () => createAccessorPropertyBackingField,
  createAccessorPropertyGetRedirector: () => createAccessorPropertyGetRedirector,
  createAccessorPropertySetRedirector: () => createAccessorPropertySetRedirector,
  createBaseNodeFactory: () => createBaseNodeFactory,
  createBinaryExpressionTrampoline: () => createBinaryExpressionTrampoline,
  createBuilderProgram: () => createBuilderProgram,
  createBuilderProgramUsingIncrementalBuildInfo: () => createBuilderProgramUsingIncrementalBuildInfo,
  createBuilderStatusReporter: () => createBuilderStatusReporter,
  createCacheableExportInfoMap: () => createCacheableExportInfoMap,
  createCachedDirectoryStructureHost: () => createCachedDirectoryStructureHost,
  createClassifier: () => createClassifier,
  createCommentDirectivesMap: () => createCommentDirectivesMap,
  createCompilerDiagnostic: () => createCompilerDiagnostic,
  createCompilerDiagnosticForInvalidCustomType: () => createCompilerDiagnosticForInvalidCustomType,
  createCompilerDiagnosticFromMessageChain: () => createCompilerDiagnosticFromMessageChain,
  createCompilerHost: () => createCompilerHost,
  createCompilerHostFromProgramHost: () => createCompilerHostFromProgramHost,
  createCompilerHostWorker: () => createCompilerHostWorker,
  createDetachedDiagnostic: () => createDetachedDiagnostic,
  createDiagnosticCollection: () => createDiagnosticCollection,
  createDiagnosticForFileFromMessageChain: () => createDiagnosticForFileFromMessageChain,
  createDiagnosticForNode: () => createDiagnosticForNode,
  createDiagnosticForNodeArray: () => createDiagnosticForNodeArray,
  createDiagnosticForNodeArrayFromMessageChain: () => createDiagnosticForNodeArrayFromMessageChain,
  createDiagnosticForNodeFromMessageChain: () => createDiagnosticForNodeFromMessageChain,
  createDiagnosticForNodeInSourceFile: () => createDiagnosticForNodeInSourceFile,
  createDiagnosticForRange: () => createDiagnosticForRange,
  createDiagnosticMessageChainFromDiagnostic: () => createDiagnosticMessageChainFromDiagnostic,
  createDiagnosticReporter: () => createDiagnosticReporter,
  createDocumentPositionMapper: () => createDocumentPositionMapper,
  createDocumentRegistry: () => createDocumentRegistry,
  createDocumentRegistryInternal: () => createDocumentRegistryInternal,
  createEmitAndSemanticDiagnosticsBuilderProgram: () => createEmitAndSemanticDiagnosticsBuilderProgram,
  createEmitHelperFactory: () => createEmitHelperFactory,
  createEmptyExports: () => createEmptyExports,
  createEvaluator: () => createEvaluator,
  createExpressionForJsxElement: () => createExpressionForJsxElement,
  createExpressionForJsxFragment: () => createExpressionForJsxFragment,
  createExpressionForObjectLiteralElementLike: () => createExpressionForObjectLiteralElementLike,
  createExpressionForPropertyName: () => createExpressionForPropertyName,
  createExpressionFromEntityName: () => createExpressionFromEntityName,
  createExternalHelpersImportDeclarationIfNeeded: () => createExternalHelpersImportDeclarationIfNeeded,
  createFileDiagnostic: () => createFileDiagnostic,
  createFileDiagnosticFromMessageChain: () => createFileDiagnosticFromMessageChain,
  createFlowNode: () => createFlowNode,
  createForOfBindingStatement: () => createForOfBindingStatement,
  createFutureSourceFile: () => createFutureSourceFile,
  createGetCanonicalFileName: () => createGetCanonicalFileName,
  createGetIsolatedDeclarationErrors: () => createGetIsolatedDeclarationErrors,
  createGetSourceFile: () => createGetSourceFile,
  createGetSymbolAccessibilityDiagnosticForNode: () => createGetSymbolAccessibilityDiagnosticForNode,
  createGetSymbolAccessibilityDiagnosticForNodeName: () => createGetSymbolAccessibilityDiagnosticForNodeName,
  createGetSymbolWalker: () => createGetSymbolWalker,
  createIncrementalCompilerHost: () => createIncrementalCompilerHost,
  createIncrementalProgram: () => createIncrementalProgram,
  createJsxFactoryExpression: () => createJsxFactoryExpression,
  createLanguageService: () => createLanguageService,
  createLanguageServiceSourceFile: () => createLanguageServiceSourceFile,
  createMemberAccessForPropertyName: () => createMemberAccessForPropertyName,
  createModeAwareCache: () => createModeAwareCache,
  createModeAwareCacheKey: () => createModeAwareCacheKey,
  createModeMismatchDetails: () => createModeMismatchDetails,
  createModuleNotFoundChain: () => createModuleNotFoundChain,
  createModuleResolutionCache: () => createModuleResolutionCache,
  createModuleResolutionLoader: () => createModuleResolutionLoader,
  createModuleResolutionLoaderUsingGlobalCache: () => createModuleResolutionLoaderUsingGlobalCache,
  createModuleSpecifierResolutionHost: () => createModuleSpecifierResolutionHost,
  createMultiMap: () => createMultiMap,
  createNameResolver: () => createNameResolver,
  createNodeConverters: () => createNodeConverters,
  createNodeFactory: () => createNodeFactory,
  createOptionNameMap: () => createOptionNameMap,
  createOverload: () => createOverload,
  createPackageJsonImportFilter: () => createPackageJsonImportFilter,
  createPackageJsonInfo: () => createPackageJsonInfo,
  createParenthesizerRules: () => createParenthesizerRules,
  createPatternMatcher: () => createPatternMatcher,
  createPrinter: () => createPrinter,
  createPrinterWithDefaults: () => createPrinterWithDefaults,
  createPrinterWithRemoveComments: () => createPrinterWithRemoveComments,
  createPrinterWithRemoveCommentsNeverAsciiEscape: () => createPrinterWithRemoveCommentsNeverAsciiEscape,
  createPrinterWithRemoveCommentsOmitTrailingSemicolon: () => createPrinterWithRemoveCommentsOmitTrailingSemicolon,
  createProgram: () => createProgram,
  createProgramHost: () => createProgramHost,
  createPropertyNameNodeForIdentifierOrLiteral: () => createPropertyNameNodeForIdentifierOrLiteral,
  createQueue: () => createQueue,
  createRange: () => createRange,
  createRedirectedBuilderProgram: () => createRedirectedBuilderProgram,
  createResolutionCache: () => createResolutionCache,
  createRuntimeTypeSerializer: () => createRuntimeTypeSerializer,
  createScanner: () => createScanner,
  createSemanticDiagnosticsBuilderProgram: () => createSemanticDiagnosticsBuilderProgram,
  createSet: () => createSet,
  createSolutionBuilder: () => createSolutionBuilder,
  createSolutionBuilderHost: () => createSolutionBuilderHost,
  createSolutionBuilderWithWatch: () => createSolutionBuilderWithWatch,
  createSolutionBuilderWithWatchHost: () => createSolutionBuilderWithWatchHost,
  createSortedArray: () => createSortedArray,
  createSourceFile: () => createSourceFile,
  createSourceMapGenerator: () => createSourceMapGenerator,
  createSourceMapSource: () => createSourceMapSource,
  createSuperAccessVariableStatement: () => createSuperAccessVariableStatement,
  createSymbolTable: () => createSymbolTable,
  createSymlinkCache: () => createSymlinkCache,
  createSyntacticTypeNodeBuilder: () => createSyntacticTypeNodeBuilder,
  createSystemWatchFunctions: () => createSystemWatchFunctions,
  createTextChange: () => createTextChange,
  createTextChangeFromStartLength: () => createTextChangeFromStartLength,
  createTextChangeRange: () => createTextChangeRange,
  createTextRangeFromNode: () => createTextRangeFromNode,
  createTextRangeFromSpan: () => createTextRangeFromSpan,
  createTextSpan: () => createTextSpan,
  createTextSpanFromBounds: () => createTextSpanFromBounds,
  createTextSpanFromNode: () => createTextSpanFromNode,
  createTextSpanFromRange: () => createTextSpanFromRange,
  createTextSpanFromStringLiteralLikeContent: () => createTextSpanFromStringLiteralLikeContent,
  createTextWriter: () => createTextWriter,
  createTokenRange: () => createTokenRange,
  createTypeChecker: () => createTypeChecker,
  createTypeReferenceDirectiveResolutionCache: () => createTypeReferenceDirectiveResolutionCache,
  createTypeReferenceResolutionLoader: () => createTypeReferenceResolutionLoader,
  createWatchCompilerHost: () => createWatchCompilerHost2,
  createWatchCompilerHostOfConfigFile: () => createWatchCompilerHostOfConfigFile,
  createWatchCompilerHostOfFilesAndCompilerOptions: () => createWatchCompilerHostOfFilesAndCompilerOptions,
  createWatchFactory: () => createWatchFactory,
  createWatchHost: () => createWatchHost,
  createWatchProgram: () => createWatchProgram,
  createWatchStatusReporter: () => createWatchStatusReporter,
  createWriteFileMeasuringIO: () => createWriteFileMeasuringIO,
  declarationNameToString: () => declarationNameToString,
  decodeMappings: () => decodeMappings,
  decodedTextSpanIntersectsWith: () => decodedTextSpanIntersectsWith,
  deduplicate: () => deduplicate,
  defaultInitCompilerOptions: () => defaultInitCompilerOptions,
  defaultMaximumTruncationLength: () => defaultMaximumTruncationLength,
  diagnosticCategoryName: () => diagnosticCategoryName,
  diagnosticToString: () => diagnosticToString,
  diagnosticsEqualityComparer: () => diagnosticsEqualityComparer,
  directoryProbablyExists: () => directoryProbablyExists,
  directorySeparator: () => directorySeparator,
  displayPart: () => displayPart,
  displayPartsToString: () => displayPartsToString,
  disposeEmitNodes: () => disposeEmitNodes,
  documentSpansEqual: () => documentSpansEqual,
  dumpTracingLegend: () => dumpTracingLegend,
  elementAt: () => elementAt,
  elideNodes: () => elideNodes,
  emitDetachedComments: () => emitDetachedComments,
  emitFiles: () => emitFiles,
  emitFilesAndReportErrors: () => emitFilesAndReportErrors,
  emitFilesAndReportErrorsAndGetExitStatus: () => emitFilesAndReportErrorsAndGetExitStatus,
  emitModuleKindIsNonNodeESM: () => emitModuleKindIsNonNodeESM,
  emitNewLineBeforeLeadingCommentOfPosition: () => emitNewLineBeforeLeadingCommentOfPosition,
  emitResolverSkipsTypeChecking: () => emitResolverSkipsTypeChecking,
  emitSkippedWithNoDiagnostics: () => emitSkippedWithNoDiagnostics,
  emptyArray: () => emptyArray,
  emptyFileSystemEntries: () => emptyFileSystemEntries,
  emptyMap: () => emptyMap,
  emptyOptions: () => emptyOptions,
  endsWith: () => endsWith,
  ensurePathIsNonModuleName: () => ensurePathIsNonModuleName,
  ensureScriptKind: () => ensureScriptKind,
  ensureTrailingDirectorySeparator: () => ensureTrailingDirectorySeparator,
  entityNameToString: () => entityNameToString,
  enumerateInsertsAndDeletes: () => enumerateInsertsAndDeletes,
  equalOwnProperties: () => equalOwnProperties,
  equateStringsCaseInsensitive: () => equateStringsCaseInsensitive,
  equateStringsCaseSensitive: () => equateStringsCaseSensitive,
  equateValues: () => equateValues,
  escapeJsxAttributeString: () => escapeJsxAttributeString,
  escapeLeadingUnderscores: () => escapeLeadingUnderscores,
  escapeNonAsciiString: () => escapeNonAsciiString,
  escapeSnippetText: () => escapeSnippetText,
  escapeString: () => escapeString,
  escapeTemplateSubstitution: () => escapeTemplateSubstitution,
  evaluatorResult: () => evaluatorResult,
  every: () => every,
  exclusivelyPrefixedNodeCoreModules: () => exclusivelyPrefixedNodeCoreModules,
  executeCommandLine: () => executeCommandLine,
  expandPreOrPostfixIncrementOrDecrementExpression: () => expandPreOrPostfixIncrementOrDecrementExpression,
  explainFiles: () => explainFiles,
  explainIfFileIsRedirectAndImpliedFormat: () => explainIfFileIsRedirectAndImpliedFormat,
  exportAssignmentIsAlias: () => exportAssignmentIsAlias,
  expressionResultIsUnused: () => expressionResultIsUnused,
  extend: () => extend,
  extensionFromPath: () => extensionFromPath,
  extensionIsTS: () => extensionIsTS,
  extensionsNotSupportingExtensionlessResolution: () => extensionsNotSupportingExtensionlessResolution,
  externalHelpersModuleNameText: () => externalHelpersModuleNameText,
  factory: () => factory,
  fileExtensionIs: () => fileExtensionIs,
  fileExtensionIsOneOf: () => fileExtensionIsOneOf,
  fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics,
  fileShouldUseJavaScriptRequire: () => fileShouldUseJavaScriptRequire,
  filter: () => filter,
  filterMutate: () => filterMutate,
  filterSemanticDiagnostics: () => filterSemanticDiagnostics,
  find: () => find,
  findAncestor: () => findAncestor,
  findBestPatternMatch: () => findBestPatternMatch,
  findChildOfKind: () => findChildOfKind,
  findComputedPropertyNameCacheAssignment: () => findComputedPropertyNameCacheAssignment,
  findConfigFile: () => findConfigFile,
  findConstructorDeclaration: () => findConstructorDeclaration,
  findContainingList: () => findContainingList,
  findDiagnosticForNode: () => findDiagnosticForNode,
  findFirstNonJsxWhitespaceToken: () => findFirstNonJsxWhitespaceToken,
  findIndex: () => findIndex,
  findLast: () => findLast,
  findLastIndex: () => findLastIndex,
  findListItemInfo: () => findListItemInfo,
  findModifier: () => findModifier,
  findNextToken: () => findNextToken,
  findPackageJson: () => findPackageJson,
  findPackageJsons: () => findPackageJsons,
  findPrecedingMatchingToken: () => findPrecedingMatchingToken,
  findPrecedingToken: () => findPrecedingToken,
  findSuperStatementIndexPath: () => findSuperStatementIndexPath,
  findTokenOnLeftOfPosition: () => findTokenOnLeftOfPosition,
  findUseStrictPrologue: () => findUseStrictPrologue,
  first: () => first,
  firstDefined: () => firstDefined,
  firstDefinedIterator: () => firstDefinedIterator,
  firstIterator: () => firstIterator,
  firstOrOnly: () => firstOrOnly,
  firstOrUndefined: () => firstOrUndefined,
  firstOrUndefinedIterator: () => firstOrUndefinedIterator,
  fixupCompilerOptions: () => fixupCompilerOptions,
  flatMap: () => flatMap,
  flatMapIterator: () => flatMapIterator,
  flatMapToMutable: () => flatMapToMutable,
  flatten: () => flatten,
  flattenCommaList: () => flattenCommaList,
  flattenDestructuringAssignment: () => flattenDestructuringAssignment,
  flattenDestructuringBinding: () => flattenDestructuringBinding,
  flattenDiagnosticMessageText: () => flattenDiagnosticMessageText,
  forEach: () => forEach,
  forEachAncestor: () => forEachAncestor,
  forEachAncestorDirectory: () => forEachAncestorDirectory,
  forEachAncestorDirectoryStoppingAtGlobalCache: () => forEachAncestorDirectoryStoppingAtGlobalCache,
  forEachChild: () => forEachChild,
  forEachChildRecursively: () => forEachChildRecursively,
  forEachDynamicImportOrRequireCall: () => forEachDynamicImportOrRequireCall,
  forEachEmittedFile: () => forEachEmittedFile,
  forEachEnclosingBlockScopeContainer: () => forEachEnclosingBlockScopeContainer,
  forEachEntry: () => forEachEntry,
  forEachExternalModuleToImportFrom: () => forEachExternalModuleToImportFrom,
  forEachImportClauseDeclaration: () => forEachImportClauseDeclaration,
  forEachKey: () => forEachKey,
  forEachLeadingCommentRange: () => forEachLeadingCommentRange,
  forEachNameInAccessChainWalkingLeft: () => forEachNameInAccessChainWalkingLeft,
  forEachNameOfDefaultExport: () => forEachNameOfDefaultExport,
  forEachPropertyAssignment: () => forEachPropertyAssignment,
  forEachResolvedProjectReference: () => forEachResolvedProjectReference,
  forEachReturnStatement: () => forEachReturnStatement,
  forEachRight: () => forEachRight,
  forEachTrailingCommentRange: () => forEachTrailingCommentRange,
  forEachTsConfigPropArray: () => forEachTsConfigPropArray,
  forEachUnique: () => forEachUnique,
  forEachYieldExpression: () => forEachYieldExpression,
  formatColorAndReset: () => formatColorAndReset,
  formatDiagnostic: () => formatDiagnostic,
  formatDiagnostics: () => formatDiagnostics,
  formatDiagnosticsWithColorAndContext: () => formatDiagnosticsWithColorAndContext,
  formatGeneratedName: () => formatGeneratedName,
  formatGeneratedNamePart: () => formatGeneratedNamePart,
  formatLocation: () => formatLocation,
  formatMessage: () => formatMessage,
  formatStringFromArgs: () => formatStringFromArgs,
  formatting: () => ts_formatting_exports,
  generateDjb2Hash: () => generateDjb2Hash,
  generateTSConfig: () => generateTSConfig,
  getAdjustedReferenceLocation: () => getAdjustedReferenceLocation,
  getAdjustedRenameLocation: () => getAdjustedRenameLocation,
  getAliasDeclarationFromName: () => getAliasDeclarationFromName,
  getAllAccessorDeclarations: () => getAllAccessorDeclarations,
  getAllDecoratorsOfClass: () => getAllDecoratorsOfClass,
  getAllDecoratorsOfClassElement: () => getAllDecoratorsOfClassElement,
  getAllJSDocTags: () => getAllJSDocTags,
  getAllJSDocTagsOfKind: () => getAllJSDocTagsOfKind,
  getAllKeys: () => getAllKeys,
  getAllProjectOutputs: () => getAllProjectOutputs,
  getAllSuperTypeNodes: () => getAllSuperTypeNodes,
  getAllowImportingTsExtensions: () => getAllowImportingTsExtensions,
  getAllowJSCompilerOption: () => getAllowJSCompilerOption,
  getAllowSyntheticDefaultImports: () => getAllowSyntheticDefaultImports,
  getAncestor: () => getAncestor,
  getAnyExtensionFromPath: () => getAnyExtensionFromPath,
  getAreDeclarationMapsEnabled: () => getAreDeclarationMapsEnabled,
  getAssignedExpandoInitializer: () => getAssignedExpandoInitializer,
  getAssignedName: () => getAssignedName,
  getAssignmentDeclarationKind: () => getAssignmentDeclarationKind,
  getAssignmentDeclarationPropertyA