import {
  AccessFlags,
  addRange,
  addRelatedInfo,
  addSyntheticLeadingComment,
  and,
  append,
  appendIfUnique,
  arrayFrom,
  arrayIsEqualTo,
  arrayIsHomogeneous,
  arrayOf,
  arrayToMultiMap,
  AssignmentDeclarationKind,
  AssignmentKind,
  binarySearch,
  bindSourceFile,
  canHaveDecorators,
  canHaveExportModifier,
  canHaveFlowNode,
  canHaveIllegalDecorators,
  canHaveIllegalModifiers,
  canHaveJSDoc,
  canHaveLocals,
  canHaveModifiers,
  canHaveModuleSpecifier,
  canHaveSymbol,
  canIncludeBindAndCheckDiagnostics,
  canUsePropertyAccess,
  cartesianProduct,
  cast,
  chainDiagnosticMessages,
  CharacterCodes,
  CheckFlags,
  classElementOrClassElementParameterIsDecorated,
  classOrConstructorParameterIsDecorated,
  clear,
  compareDiagnostics,
  comparePaths,
  compareValues,
  Comparison,
  concatenate,
  concatenateDiagnosticMessageChains,
  contains,
  containsParseError,
  ContextFlags,
  copyEntries,
  countWhere,
  createBinaryExpressionTrampoline,
  createCompilerDiagnostic,
  createDetachedDiagnostic,
  createDiagnosticCollection,
  createDiagnosticForFileFromMessageChain,
  createDiagnosticForNode,
  createDiagnosticForNodeArray,
  createDiagnosticForNodeArrayFromMessageChain,
  createDiagnosticForNodeFromMessageChain,
  createDiagnosticMessageChainFromDiagnostic,
  createEmptyExports,
  createEvaluator,
  createFileDiagnostic,
  createFlowNode,
  createGetSymbolWalker,
  createModeAwareCacheKey,
  createModeMismatchDetails,
  createModuleNotFoundChain,
  createMultiMap,
  createNameResolver,
  createPrinterWithDefaults,
  createPrinterWithRemoveComments,
  createPrinterWithRemoveCommentsNeverAsciiEscape,
  createPrinterWithRemoveCommentsOmitTrailingSemicolon,
  createPropertyNameNodeForIdentifierOrLiteral,
  createScanner,
  createSymbolTable,
  createSyntacticTypeNodeBuilder,
  createTextWriter,
  Debug,
  declarationNameToString,
  deduplicate,
  defaultMaximumTruncationLength,
  DiagnosticCategory,
  Diagnostics,
  ElementFlags,
  EmitFlags,
  EmitHint,
  emitModuleKindIsNonNodeESM,
  emptyArray,
  endsWith,
  entityNameToString,
  equateValues,
  escapeLeadingUnderscores,
  escapeString,
  evaluatorResult,
  every,
  exportAssignmentIsAlias,
  expressionResultIsUnused,
  Extension,
  ExternalEmitHelpers,
  externalHelpersModuleNameText,
  factory,
  fileExtensionIs,
  fileExtensionIsOneOf,
  filter,
  find,
  findAncestor,
  findBestPatternMatch,
  findConstructorDeclaration,
  findIndex,
  findLast,
  findLastIndex,
  findUseStrictPrologue,
  first,
  firstDefined,
  firstIterator,
  firstOrUndefined,
  firstOrUndefinedIterator,
  flatMap,
  flatten,
  FlowFlags,
  forEach,
  forEachChild,
  forEachChildRecursively,
  forEachEnclosingBlockScopeContainer,
  forEachEntry,
  forEachKey,
  forEachReturnStatement,
  forEachYieldExpression,
  formatMessage,
  FunctionFlags,
  getAliasDeclarationFromName,
  getAllJSDocTags,
  getAllowSyntheticDefaultImports,
  getAncestor,
  getAssignedExpandoInitializer,
  getAssignmentDeclarationKind,
  getAssignmentDeclarationPropertyAccessKind,
  getAssignmentTargetKind,
  getCanonicalDiagnostic,
  getCheckFlags,
  getClassExtendsHeritageElement,
  getClassLikeDeclarationOfSymbol,
  getCombinedLocalAndExportSymbolFlags,
  getCombinedModifierFlags,
  getCombinedNodeFlags,
  getContainingClass,
  getContainingClassExcludingClassDecorators,
  getContainingClassStaticBlock,
  getContainingFunction,
  getContainingFunctionOrClassStaticBlock,
  getDeclarationModifierFlagsFromSymbol,
  getDeclarationOfKind,
  getDeclarationsOfKind,
  getDeclaredExpandoInitializer,
  getDecorators,
  getDirectoryPath,
  getEffectiveBaseTypeNode,
  getEffectiveConstraintOfTypeParameter,
  getEffectiveContainerForJSDocTemplateTag,
  getEffectiveImplementsTypeNodes,
  getEffectiveInitializer,
  getEffectiveJSDocHost,
  getEffectiveModifierFlags,
  getEffectiveReturnTypeNode,
  getEffectiveSetAccessorTypeAnnotationNode,
  getEffectiveTypeAnnotationNode,
  getEffectiveTypeParameterDeclarations,
  getElementOrPropertyAccessName,
  getEmitDeclarations,
  getEmitFlags,
  getEmitModuleKind,
  getEmitModuleResolutionKind,
  getEmitScriptTarget,
  getEmitStandardClassFields,
  getEnclosingBlockScopeContainer,
  getEnclosingContainer,
  getEntityNameFromTypeNode,
  getErrorSpanForNode,
  getEscapedTextOfIdentifierOrLiteral,
  getEscapedTextOfJsxAttributeName,
  getEscapedTextOfJsxNamespacedName,
  getESModuleInterop,
  getExpandoInitializer,
  getExportAssignmentExpression,
  getExternalModuleImportEqualsDeclarationExpression,
  getExternalModuleName,
  getExternalModuleRequireArgument,
  getFirstConstructorWithBody,
  getFirstIdentifier,
  getFunctionFlags,
  getHostSignatureFromJSDoc,
  getIdentifierGeneratedImportReference,
  getIdentifierTypeArguments,
  getImmediatelyInvokedFunctionExpression,
  getInitializerOfBinaryExpression,
  getInterfaceBaseTypeNodes,
  getInvokedExpression,
  getIsolatedModules,
  getJSDocClassTag,
  getJSDocDeprecatedTag,
  getJSDocEnumTag,
  getJSDocHost,
  getJSDocOverloadTags,
  getJSDocParameterTags,
  getJSDocRoot,
  getJSDocSatisfiesExpressionType,
  getJSDocTags,
  getJSDocThisTag,
  getJSDocType,
  getJSDocTypeAssertionType,
  getJSDocTypeParameterDeclarations,
  getJSDocTypeTag,
  getJSXImplicitImportBase,
  getJSXRuntimeImport,
  getJSXTransformEnabled,
  getLeftmostAccessExpression,
  getLineAndCharacterOfPosition,
  getMembersOfDeclaration,
  getModifiers,
  getModuleInstanceState,
  getNameFromImportAttribute,
  getNameFromIndexInfo,
  getNameOfDeclaration,
  getNameOfExpando,
  getNamespaceDeclarationNode,
  getNewTargetContainer,
  getNonAugmentationDeclaration,
  getNonModifierTokenPosOfNode,
  getNormalizedAbsolutePath,
  getObjectFlags,
  getOriginalNode,
  getOrUpdate,
  getParameterSymbolFromJSDoc,
  getParseTreeNode,
  getPropertyAssignmentAliasLikeExpression,
  getPropertyNameForPropertyNameNode,
  getPropertyNameFromType,
  getResolutionDiagnostic,
  getResolutionModeOverride,
  getResolveJsonModule,
  getRestParameterElementType,
  getRootDeclaration,
  getScriptTargetFeatures,
  getSelectedEffectiveModifierFlags,
  getSemanticJsxChildren,
  getSetAccessorValueParameter,
  getSingleVariableOfVariableStatement,
  getSourceFileOfModule,
  getSourceFileOfNode,
  getSpanOfTokenAtPosition,
  getSpellingSuggestion,
  getStrictOptionValue,
  getSuperContainer,
  getSymbolNameForPrivateIdentifier,
  getTextOfIdentifierOrLiteral,
  getTextOfJSDocComment,
  getTextOfJsxAttributeName,
  getTextOfNode,
  getTextOfPropertyName,
  getThisContainer,
  getThisParameter,
  getTrailingSemicolonDeferringWriter,
  getTypeParameterFromJsDoc,
  getUseDefineForClassFields,
  group,
  hasAbstractModifier,
  hasAccessorModifier,
  hasAmbientModifier,
  hasContextSensitiveParameters,
  hasDecorators,
  hasDynamicName,
  hasEffectiveModifier,
  hasEffectiveModifiers,
  hasEffectiveReadonlyModifier,
  hasExtension,
  hasInferredType,
  hasInitializer,
  hasJSDocNodes,
  hasJSDocParameterTags,
  hasJsonModuleEmitEnabled,
  hasOnlyExpressionInitializer,
  hasOverrideModifier,
  hasPossibleExternalModuleReference,
  hasQuestionToken,
  hasResolutionModeOverride,
  hasRestParameter,
  hasScopeMarker,
  hasStaticModifier,
  hasSyntacticModifier,
  hasSyntacticModifiers,
  hasType,
  identifierToKeywordKind,
  idText,
  IndexFlags,
  IndexKind,
  indexOfNode,
  indicesOf,
  InferenceFlags,
  InferencePriority,
  InternalNodeBuilderFlags,
  InternalSymbolName,
  IntersectionFlags,
  intrinsicTagNameToString,
  introducesArgumentsExoticObject,
  isAccessExpression,
  isAccessor,
  isAliasableExpression,
  isAmbientModule,
  isArray,
  isArrayBindingPattern,
  isArrayLiteralExpression,
  isArrowFunction,
  isAssertionExpression,
  isAssignmentDeclaration,
  isAssignmentExpression,
  isAssignmentOperator,
  isAssignmentPattern,
  isAssignmentTarget,
  isAutoAccessorPropertyDeclaration,
  isAwaitExpression,
  isBinaryExpression,
  isBinaryLogicalOperator,
  isBindableObjectDefinePropertyCall,
  isBindableStaticElementAccessExpression,
  isBindableStaticNameExpression,
  isBindingElement,
  isBindingElementOfBareOrAccessedRequire,
  isBindingPattern,
  isBlock,
  isBlockOrCatchScoped,
  isBlockScopedContainerTopLevel,
  isBooleanLiteral,
  isCallChain,
  isCallExpression,
  isCallLikeExpression,
  isCallLikeOrFunctionLikeExpression,
  isCallOrNewExpression,
  isCallSignatureDeclaration,
  isCatchClause,
  isCatchClauseVariableDeclaration,
  isCatchClauseVariableDeclarationOrBindingElement,
  isCheckJsEnabledForFile,
  isClassDeclaration,
  isClassElement,
  isClassExpression,
  isClassInstanceProperty,
  isClassLike,
  isClassStaticBlockDeclaration,
  isCommaSequence,
  isCommonJsExportedExpression,
  isCommonJsExportPropertyAssignment,
  isCompoundAssignment,
  isComputedNonLiteralName,
  isComputedPropertyName,
  isConditionalTypeNode,
  isConstAssertion,
  isConstructorDeclaration,
  isConstructorTypeNode,
  isConstructSignatureDeclaration,
  isConstTypeReference,
  isDeclaration,
  isDeclarationFileName,
  isDeclarationName,
  isDeclarationReadonly,
  isDecorator,
  isDefaultedExpandoInitializer,
  isDeleteTarget,
  isDottedName,
  isDynamicName,
  isEffectiveExternalModule,
  isElementAccessExpression,
  isEntityName,
  isEntityNameExpression,
  isEnumConst,
  isEnumDeclaration,
  isEnumMember,
  isExclusivelyTypeOnlyImportOrExport,
  isExpandoPropertyDeclaration,
  isExportAssignment,
  isExportDeclaration,
  isExportsIdentifier,
  isExportSpecifier,
  isExpression,
  isExpressionNode,
  isExpressionOfOptionalChainRoot,
  isExpressionStatement,
  isExpressionWithTypeArguments,
  isExpressionWithTypeArgumentsInClassExtendsClause,
  isExternalModule,
  isExternalModuleAugmentation,
  isExternalModuleImportEqualsDeclaration,
  isExternalModuleIndicator,
  isExternalModuleNameRelative,
  isExternalModuleReference,
  isExternalModuleSymbol,
  isExternalOrCommonJsModule,
  isForInOrOfStatement,
  isForInStatement,
  isForOfStatement,
  isForStatement,
  isFunctionDeclaration,
  isFunctionExpression,
  isFunctionExpressionOrArrowFunction,
  isFunctionLike,
  isFunctionLikeDeclaration,
  isFunctionLikeOrClassStaticBlockDeclaration,
  isFunctionOrModuleBlock,
  isFunctionTypeNode,
  isGeneratedIdentifier,
  isGetAccessor,
  isGetAccessorDeclaration,
  isGetOrSetAccessorDeclaration,
  isGlobalScopeAugmentation,
  isGlobalSourceFile,
  isHeritageClause,
  isIdentifier,
  isIdentifierText,
  isIdentifierTypePredicate,
  isIdentifierTypeReference,
  isIfStatement,
  isImportAttributes,
  isImportCall,
  isImportClause,
  isImportDeclaration,
  isImportEqualsDeclaration,
  isImportKeyword,
  isImportOrExportSpecifier,
  isImportSpecifier,
  isImportTypeNode,
  isInCompoundLikeAssignment,
  isIndexedAccessTypeNode,
  isInExpressionContext,
  isInfinityOrNaNString,
  isInitializedProperty,
  isInJSDoc,
  isInJSFile,
  isInJsonFile,
  isInstanceOfExpression,
  isInterfaceDeclaration,
  isInternalModuleImportEqualsDeclaration,
  isInTopLevelContext,
  isIntrinsicJsxName,
  isInTypeQuery,
  isIterationStatement,
  isJSDocAllType,
  isJSDocAugmentsTag,
  isJSDocCallbackTag,
  isJSDocConstructSignature,
  isJSDocFunctionType,
  isJSDocImportTag,
  isJSDocIndexSignature,
  isJSDocLinkLike,
  isJSDocMemberName,
  isJSDocNameReference,
  isJSDocNode,
  isJSDocNonNullableType,
  isJSDocNullableType,
  isJSDocOptionalParameter,
  isJSDocOptionalType,
  isJSDocOverloadTag,
  isJSDocParameterTag,
  isJSDocPropertyLikeTag,
  isJSDocPropertyTag,
  isJSDocSatisfiesExpression,
  isJSDocSatisfiesTag,
  isJSDocSignature,
  isJSDocTemplateTag,
  isJSDocThisTag,
  isJSDocTypeAlias,
  isJSDocTypeAssertion,
  isJSDocTypedefTag,
  isJSDocTypeExpression,
  isJSDocTypeLiteral,
  isJSDocUnknownType,
  isJSDocVariadicType,
  isJsonSourceFile,
  isJsxAttribute,
  isJsxAttributeLike,
  isJsxAttributes,
  isJsxElement,
  isJsxNamespacedName,
  isJsxOpeningElement,
  isJsxOpeningFragment,
  isJsxOpeningLikeElement,
  isJsxSelfClosingElement,
  isJsxSpreadAttribute,
  isJSXTagName,
  isKnownSymbol,
  isLateVisibilityPaintedStatement,
  isLeftHandSideExpression,
  isLineBreak,
  isLiteralComputedPropertyDeclarationName,
  isLiteralExpression,
  isLiteralExpressionOfObject,
  isLiteralImportTypeNode,
  isLiteralTypeNode,
  isLogicalOrCoalescingBinaryExpression,
  isLogicalOrCoalescingBinaryOperator,
  isMappedTypeNode,
  isMetaProperty,
  isMethodDeclaration,
  isMethodSignature,
  isModifier,
  isModuleBlock,
  isModuleDeclaration,
  isModuleExportsAccessExpression,
  isModuleIdentifier,
  isModuleOrEnumDeclaration,
  isModuleWithStringLiteralName,
  isNamedDeclaration,
  isNamedEvaluationSource,
  isNamedExports,
  isNamedTupleMember,
  isNamespaceExport,
  isNamespaceExportDeclaration,
  isNamespaceReexportDeclaration,
  isNewExpression,
  isNodeDescendantOf,
  isNonNullAccess,
  isNonNullExpression,
  isNumericLiteral,
  isNumericLiteralName,
  isObjectBindingPattern,
  isObjectLiteralElementLike,
  isObjectLiteralExpression,
  isObjectLiteralMethod,
  isObjectLiteralOrClassExpressionMethodOrAccessor,
  isOmittedExpression,
  isOptionalChain,
  isOptionalChainRoot,
  isOptionalDeclaration,
  isOptionalJSDocPropertyLikeTag,
  isOptionalTypeNode,
  isOutermostOptionalChain,
  isParameter,
  isParameterPropertyDeclaration,
  isParenthesizedExpression,
  isParenthesizedTypeNode,
  isPartOfParameterDeclaration,
  isPartOfTypeNode,
  isPartOfTypeQuery,
  isPlainJsFile,
  isPrefixUnaryExpression,
  isPrivateIdentifier,
  isPrivateIdentifierClassElementDeclaration,
  isPrivateIdentifierPropertyAccessExpression,
  isPropertyAccessEntityNameExpression,
  isPropertyAccessExpression,
  isPropertyAccessOrQualifiedName,
  isPropertyAccessOrQualifiedNameOrImportTypeNode,
  isPropertyAssignment,
  isPropertyDeclaration,
  isPropertyName,
  isPropertyNameLiteral,
  isPropertySignature,
  isPrototypeAccess,
  isPrototypePropertyAssignment,
  isPushOrUnshiftIdentifier,
  isQualifiedName,
  isRequireCall,
  isRestParameter,
  isRestTypeNode,
  isRightSideOfAccessExpression,
  isRightSideOfInstanceofExpression,
  isRightSideOfQualifiedNameOrPropertyAccess,
  isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName,
  isSameEntityName,
  isSatisfiesExpression,
  isSetAccessor,
  isSetAccessorDeclaration,
  isShorthandAmbientModuleSymbol,
  isShorthandPropertyAssignment,
  isSideEffectImport,
  isSingleOrDoubleQuote,
  isSourceFile,
  isSourceFileJS,
  isSpreadAssignment,
  isSpreadElement,
  isStatement,
  isStatementWithLocals,
  isStatic,
  isString,
  isStringANonContextualKeyword,
  isStringLiteral,
  isStringLiteralLike,
  isStringOrNumericLiteralLike,
  isSuperCall,
  isSuperProperty,
  isTaggedTemplateExpression,
  isTemplateSpan,
  isThisContainerOrFunctionBlock,
  isThisIdentifier,
  isThisInitializedDeclaration,
  isThisInitializedObjectBindingExpression,
  isThisInTypeQuery,
  isThisProperty,
  isThisTypeNode,
  isThisTypeParameter,
  isThisTypePredicate,
  isTransientSymbol,
  isTupleTypeNode,
  isTypeAlias,
  isTypeAliasDeclaration,
  isTypeDeclaration,
  isTypeLiteralNode,
  isTypeNode,
  isTypeNodeKind,
  isTypeOfExpression,
  isTypeOnlyImportDeclaration,
  isTypeOnlyImportOrExportDeclaration,
  isTypeOperatorNode,
  isTypeParameterDeclaration,
  isTypePredicateNode,
  isTypeQueryNode,
  isTypeReferenceNode,
  isTypeReferenceType,
  isTypeUsableAsPropertyName,
  isUMDExportSymbol,
  isValidBigIntString,
  isValidESSymbolDeclaration,
  isValidTypeOnlyAliasUseSite,
  isValueSignatureDeclaration,
  isVariableDeclaration,
  isVariableDeclarationInitializedToBareOrAccessedRequire,
  isVariableDeclarationInVariableStatement,
  isVariableDeclarationList,
  isVariableLike,
  isVariableLikeOrAccessor,
  isVariableStatement,
  isWriteAccess,
  isWriteOnlyAccess,
  JsxEmit,
  JsxFlags,
  JsxReferenceKind,
  LanguageFeatureMinimumTarget,
  last,
  lastOrUndefined,
  length,
  map,
  mapDefined,
  maybeBind,
  MemberOverrideStatus,
  minAndMax,
  ModifierFlags,
  modifiersToFlags,
  modifierToFlag,
  moduleExportNameIsDefault,
  moduleExportNameTextEscaped,
  moduleExportNameTextUnescaped,
  ModuleInstanceState,
  ModuleKind,
  ModuleResolutionKind,
  needsScopeMarker,
  NodeBuilderFlags,
  nodeCanBeDecorated,
  NodeCheckFlags,
  NodeFlags,
  nodeHasName,
  nodeIsMissing,
  nodeIsPresent,
  nodeIsSynthesized,
  nodeStartsNewLexicalEnvironment,
  not,
  noTruncationMaximumTruncationLength,
  objectAllocator,
  ObjectFlags,
  or,
  orderedRemoveItemAt,
  OuterExpressionKinds,
  parameterIsThisKeyword,
  parseIsolatedEntityName,
  parseNodeFactory,
  parsePseudoBigInt,
  parseValidBigInt,
  pathIsRelative,
  PredicateSemantics,
  pseudoBigIntToString,
  pushIfUnique,
  rangeEquals,
  rangeOfNode,
  rangeOfTypeParameters,
  reduceLeft,
  RelationComparisonResult,
  relativeComplement,
  removeExtension,
  removePrefix,
  replaceElement,
  resolutionExtensionIsTSOrJson,
  resolvingEmptyArray,
  sameMap,
  scanTokenAtPosition,
  ScriptKind,
  ScriptTarget,
  setCommentRange as setCommentRangeWorker,
  setEmitFlags,
  setIdentifierTypeArguments,
  setNodeFlags,
  setOriginalNode,
  setParent,
  setSyntheticLeadingComments,
  setTextRange as setTextRangeWorker,
  setTextRangePosEnd,
  setValueDeclaration,
  shouldAllowImportingTsExtension,
  shouldPreserveConstEnums,
  SignatureFlags,
  SignatureKind,
  singleElementArray,
  skipOuterExpressions,
  skipParentheses,
  skipTrivia,
  skipTypeChecking,
  skipTypeParentheses,
  some,
  startsWith,
  stripQuotes,
  SymbolAccessibility,
  SymbolFlags,
  SymbolFormatFlags,
  symbolName,
  SyntaxKind,
  Ternary,
  textRangeContainsPositionInclusive,
  textSpanContainsPosition,
  textSpanEnd,
  TokenFlags,
  tokenToString,
  tracing,
  tryAddToSet,
  tryCast,
  tryExtractTSExtension,
  tryGetClassImplementingOrExtendingExpressionWithTypeArguments,
  tryGetExtensionFromPath,
  tryGetJSDocSatisfiesTypeNode,
  tryGetModuleSpecifierFromDeclaration,
  tryGetPropertyAccessOrIdentifierToString,
  TypeFlags,
  TypeFormatFlags,
  TypeMapKind,
  TypePredicateKind,
  TypeReferenceSerializationKind,
  unescapeLeadingUnderscores,
  UnionReduction,
  usingSingleLineStringWriter,
  VarianceFlags,
  visitEachChild as visitEachChildWorker,
  visitNode,
  visitNodes,
  walkUpBindingElementsAndPatterns,
  walkUpOuterExpressions,
  walkUpParenthesizedExpressions,
  walkUpParenthesizedTypes,
  walkUpParenthesizedTypesAndGetParentAndChild
} from "./_namespaces/ts.js";
import * as moduleSpecifiers from "./_namespaces/ts.moduleSpecifiers.js";
import * as performance from "./_namespaces/ts.performance.js";
const ambientModuleSymbolRegex = /^".+"$/;
const anon = "(anonymous)";
var ReferenceHint = /* @__PURE__ */ ((ReferenceHint2) => {
  ReferenceHint2[ReferenceHint2["Unspecified"] = 0] = "Unspecified";
  ReferenceHint2[ReferenceHint2["Identifier"] = 1] = "Identifier";
  ReferenceHint2[ReferenceHint2["Property"] = 2] = "Property";
  ReferenceHint2[ReferenceHint2["ExportAssignment"] = 3] = "ExportAssignment";
  ReferenceHint2[ReferenceHint2["Jsx"] = 4] = "Jsx";
  ReferenceHint2[ReferenceHint2["AsyncFunction"] = 5] = "AsyncFunction";
  ReferenceHint2[ReferenceHint2["ExportImportEquals"] = 6] = "ExportImportEquals";
  ReferenceHint2[ReferenceHint2["ExportSpecifier"] = 7] = "ExportSpecifier";
  ReferenceHint2[ReferenceHint2["Decorator"] = 8] = "Decorator";
  return ReferenceHint2;
})(ReferenceHint || {});
let nextSymbolId = 1;
let nextNodeId = 1;
let nextMergeId = 1;
let nextFlowId = 1;
var IterationUse = /* @__PURE__ */ ((IterationUse2) => {
  IterationUse2[IterationUse2["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
  IterationUse2[IterationUse2["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
  IterationUse2[IterationUse2["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
  IterationUse2[IterationUse2["ForOfFlag"] = 8] = "ForOfFlag";
  IterationUse2[IterationUse2["YieldStarFlag"] = 16] = "YieldStarFlag";
  IterationUse2[IterationUse2["SpreadFlag"] = 32] = "SpreadFlag";
  IterationUse2[IterationUse2["DestructuringFlag"] = 64] = "DestructuringFlag";
  IterationUse2[IterationUse2["PossiblyOutOfBounds"] = 128] = "PossiblyOutOfBounds";
  IterationUse2[IterationUse2["Element"] = 1 /* AllowsSyncIterablesFlag */] = "Element";
  IterationUse2[IterationUse2["Spread"] = 33] = "Spread";
  IterationUse2[IterationUse2["Destructuring"] = 65] = "Destructuring";
  IterationUse2[IterationUse2["ForOf"] = 13] = "ForOf";
  IterationUse2[IterationUse2["ForAwaitOf"] = 15] = "ForAwaitOf";
  IterationUse2[IterationUse2["YieldStar"] = 17] = "YieldStar";
  IterationUse2[IterationUse2["AsyncYieldStar"] = 19] = "AsyncYieldStar";
  IterationUse2[IterationUse2["GeneratorReturnType"] = 1 /* AllowsSyncIterablesFlag */] = "GeneratorReturnType";
  IterationUse2[IterationUse2["AsyncGeneratorReturnType"] = 2 /* AllowsAsyncIterablesFlag */] = "AsyncGeneratorReturnType";
  return IterationUse2;
})(IterationUse || {});
var IterationTypeKind = /* @__PURE__ */ ((IterationTypeKind2) => {
  IterationTypeKind2[IterationTypeKind2["Yield"] = 0] = "Yield";
  IterationTypeKind2[IterationTypeKind2["Return"] = 1] = "Return";
  IterationTypeKind2[IterationTypeKind2["Next"] = 2] = "Next";
  return IterationTypeKind2;
})(IterationTypeKind || {});
var WideningKind = /* @__PURE__ */ ((WideningKind2) => {
  WideningKind2[WideningKind2["Normal"] = 0] = "Normal";
  WideningKind2[WideningKind2["FunctionReturn"] = 1] = "FunctionReturn";
  WideningKind2[WideningKind2["GeneratorNext"] = 2] = "GeneratorNext";
  WideningKind2[WideningKind2["GeneratorYield"] = 3] = "GeneratorYield";
  return WideningKind2;
})(WideningKind || {});
export var TypeFacts = /* @__PURE__ */ ((TypeFacts2) => {
  TypeFacts2[TypeFacts2["None"] = 0] = "None";
  TypeFacts2[TypeFacts2["TypeofEQString"] = 1] = "TypeofEQString";
  TypeFacts2[TypeFacts2["TypeofEQNumber"] = 2] = "TypeofEQNumber";
  TypeFacts2[TypeFacts2["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
  TypeFacts2[TypeFacts2["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
  TypeFacts2[TypeFacts2["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
  TypeFacts2[TypeFacts2["TypeofEQObject"] = 32] = "TypeofEQObject";
  TypeFacts2[TypeFacts2["TypeofEQFunction"] = 64] = "TypeofEQFunction";
  TypeFacts2[TypeFacts2["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
  TypeFacts2[TypeFacts2["TypeofNEString"] = 256] = "TypeofNEString";
  TypeFacts2[TypeFacts2["TypeofNENumber"] = 512] = "TypeofNENumber";
  TypeFacts2[TypeFacts2["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
  TypeFacts2[TypeFacts2["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
  TypeFacts2[TypeFacts2["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
  TypeFacts2[TypeFacts2["TypeofNEObject"] = 8192] = "TypeofNEObject";
  TypeFacts2[TypeFacts2["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
  TypeFacts2[TypeFacts2["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
  TypeFacts2[TypeFacts2["EQUndefined"] = 65536] = "EQUndefined";
  TypeFacts2[TypeFacts2["EQNull"] = 131072] = "EQNull";
  TypeFacts2[TypeFacts2["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
  TypeFacts2[TypeFacts2["NEUndefined"] = 524288] = "NEUndefined";
  TypeFacts2[TypeFacts2["NENull"] = 1048576] = "NENull";
  TypeFacts2[TypeFacts2["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
  TypeFacts2[TypeFacts2["Truthy"] = 4194304] = "Truthy";
  TypeFacts2[TypeFacts2["Falsy"] = 8388608] = "Falsy";
  TypeFacts2[TypeFacts2["IsUndefined"] = 16777216] = "IsUndefined";
  TypeFacts2[TypeFacts2["IsNull"] = 33554432] = "IsNull";
  TypeFacts2[TypeFacts2["IsUndefinedOrNull"] = 50331648] = "IsUndefinedOrNull";
  TypeFacts2[TypeFacts2["All"] = 134217727] = "All";
  TypeFacts2[TypeFacts2["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
  TypeFacts2[TypeFacts2["BaseStringFacts"] = 12582401] = "BaseStringFacts";
  TypeFacts2[TypeFacts2["StringStrictFacts"] = 16317953] = "StringStrictFacts";
  TypeFacts2[TypeFacts2["StringFacts"] = 16776705] = "StringFacts";
  TypeFacts2[TypeFacts2["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
  TypeFacts2[TypeFacts2["EmptyStringFacts"] = 12582401 /* BaseStringFacts */] = "EmptyStringFacts";
  TypeFacts2[TypeFacts2["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
  TypeFacts2[TypeFacts2["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
  TypeFacts2[TypeFacts2["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
  TypeFacts2[TypeFacts2["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
  TypeFacts2[TypeFacts2["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
  TypeFacts2[TypeFacts2["NumberFacts"] = 16776450] = "NumberFacts";
  TypeFacts2[TypeFacts2["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
  TypeFacts2[TypeFacts2["ZeroNumberFacts"] = 12582146 /* BaseNumberFacts */] = "ZeroNumberFacts";
  TypeFacts2[TypeFacts2["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
  TypeFacts2[TypeFacts2["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
  TypeFacts2[TypeFacts2["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
  TypeFacts2[TypeFacts2["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
  TypeFacts2[TypeFacts2["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
  TypeFacts2[TypeFacts2["BigIntFacts"] = 16775940] = "BigIntFacts";
  TypeFacts2[TypeFacts2["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
  TypeFacts2[TypeFacts2["ZeroBigIntFacts"] = 12581636 /* BaseBigIntFacts */] = "ZeroBigIntFacts";
  TypeFacts2[TypeFacts2["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
  TypeFacts2[TypeFacts2["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
  TypeFacts2[TypeFacts2["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
  TypeFacts2[TypeFacts2["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
  TypeFacts2[TypeFacts2["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
  TypeFacts2[TypeFacts2["BooleanFacts"] = 16774920] = "BooleanFacts";
  TypeFacts2[TypeFacts2["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
  TypeFacts2[TypeFacts2["FalseFacts"] = 12580616 /* BaseBooleanFacts */] = "FalseFacts";
  TypeFacts2[TypeFacts2["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
  TypeFacts2[TypeFacts2["TrueFacts"] = 16774920] = "TrueFacts";
  TypeFacts2[TypeFacts2["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
  TypeFacts2[TypeFacts2["SymbolFacts"] = 16772880] = "SymbolFacts";
  TypeFacts2[TypeFacts2["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
  TypeFacts2[TypeFacts2["ObjectFacts"] = 16736160] = "ObjectFacts";
  TypeFacts2[TypeFacts2["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
  TypeFacts2[TypeFacts2["FunctionFacts"] = 16728e3] = "FunctionFacts";
  TypeFacts2[TypeFacts2["VoidFacts"] = 9830144] = "VoidFacts";
  TypeFacts2[TypeFacts2["UndefinedFacts"] = 26607360] = "UndefinedFacts";
  TypeFacts2[TypeFacts2["NullFacts"] = 42917664] = "NullFacts";
  TypeFacts2[TypeFacts2["EmptyObjectStrictFacts"] = 83427327] = "EmptyObjectStrictFacts";
  TypeFacts2[TypeFacts2["EmptyObjectFacts"] = 83886079] = "EmptyObjectFacts";
  TypeFacts2[TypeFacts2["UnknownFacts"] = 83886079] = "UnknownFacts";
  TypeFacts2[TypeFacts2["AllTypeofNE"] = 556800] = "AllTypeofNE";
  TypeFacts2[TypeFacts2["OrFactsMask"] = 8256] = "OrFactsMask";
  TypeFacts2[TypeFacts2["AndFactsMask"] = 134209471] = "AndFactsMask";
  return TypeFacts2;
})(TypeFacts || {});
const typeofNEFacts = new Map(Object.entries({
  string: 256 /* TypeofNEString */,
  number: 512 /* TypeofNENumber */,
  bigint: 1024 /* TypeofNEBigInt */,
  boolean: 2048 /* TypeofNEBoolean */,
  symbol: 4096 /* TypeofNESymbol */,
  undefined: 524288 /* NEUndefined */,
  object: 8192 /* TypeofNEObject */,
  function: 16384 /* TypeofNEFunction */
}));
var TypeSystemPropertyName = /* @__PURE__ */ ((TypeSystemPropertyName2) => {
  TypeSystemPropertyName2[TypeSystemPropertyName2["Type"] = 0] = "Type";
  TypeSystemPropertyName2[TypeSystemPropertyName2["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
  TypeSystemPropertyName2[TypeSystemPropertyName2["DeclaredType"] = 2] = "DeclaredType";
  TypeSystemPropertyName2[TypeSystemPropertyName2["ResolvedReturnType"] = 3] = "ResolvedReturnType";
  TypeSystemPropertyName2[TypeSystemPropertyName2["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
  TypeSystemPropertyName2[TypeSystemPropertyName2["ResolvedTypeArguments"] = 5] = "ResolvedTypeArguments";
  TypeSystemPropertyName2[TypeSystemPropertyName2["ResolvedBaseTypes"] = 6] = "ResolvedBaseTypes";
  TypeSystemPropertyName2[TypeSystemPropertyName2["WriteType"] = 7] = "WriteType";
  TypeSystemPropertyName2[TypeSystemPropertyName2["ParameterInitializerContainsUndefined"] = 8] = "ParameterInitializerContainsUndefined";
  return TypeSystemPropertyName2;
})(TypeSystemPropertyName || {});
export var CheckMode = /* @__PURE__ */ ((CheckMode2) => {
  CheckMode2[CheckMode2["Normal"] = 0] = "Normal";
  CheckMode2[CheckMode2["Contextual"] = 1] = "Contextual";
  CheckMode2[CheckMode2["Inferential"] = 2] = "Inferential";
  CheckMode2[CheckMode2["SkipContextSensitive"] = 4] = "SkipContextSensitive";
  CheckMode2[CheckMode2["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
  CheckMode2[CheckMode2["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
  CheckMode2[CheckMode2["RestBindingElement"] = 32] = "RestBindingElement";
  CheckMode2[CheckMode2["TypeOnly"] = 64] = "TypeOnly";
  return CheckMode2;
})(CheckMode || {});
export var SignatureCheckMode = /* @__PURE__ */ ((SignatureCheckMode2) => {
  SignatureCheckMode2[SignatureCheckMode2["None"] = 0] = "None";
  SignatureCheckMode2[SignatureCheckMode2["BivariantCallback"] = 1] = "BivariantCallback";
  SignatureCheckMode2[SignatureCheckMode2["StrictCallback"] = 2] = "StrictCallback";
  SignatureCheckMode2[SignatureCheckMode2["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
  SignatureCheckMode2[SignatureCheckMode2["StrictArity"] = 8] = "StrictArity";
  SignatureCheckMode2[SignatureCheckMode2["StrictTopSignature"] = 16] = "StrictTopSignature";
  SignatureCheckMode2[SignatureCheckMode2["Callback"] = 3] = "Callback";
  return SignatureCheckMode2;
})(SignatureCheckMode || {});
var IntersectionState = /* @__PURE__ */ ((IntersectionState2) => {
  IntersectionState2[IntersectionState2["None"] = 0] = "None";
  IntersectionState2[IntersectionState2["Source"] = 1] = "Source";
  IntersectionState2[IntersectionState2["Target"] = 2] = "Target";
  return IntersectionState2;
})(IntersectionState || {});
var RecursionFlags = /* @__PURE__ */ ((RecursionFlags2) => {
  RecursionFlags2[RecursionFlags2["None"] = 0] = "None";
  RecursionFlags2[RecursionFlags2["Source"] = 1] = "Source";
  RecursionFlags2[RecursionFlags2["Target"] = 2] = "Target";
  RecursionFlags2[RecursionFlags2["Both"] = 3] = "Both";
  return RecursionFlags2;
})(RecursionFlags || {});
var MappedTypeModifiers = /* @__PURE__ */ ((MappedTypeModifiers2) => {
  MappedTypeModifiers2[MappedTypeModifiers2["IncludeReadonly"] = 1] = "IncludeReadonly";
  MappedTypeModifiers2[MappedTypeModifiers2["ExcludeReadonly"] = 2] = "ExcludeReadonly";
  MappedTypeModifiers2[MappedTypeModifiers2["IncludeOptional"] = 4] = "IncludeOptional";
  MappedTypeModifiers2[MappedTypeModifiers2["ExcludeOptional"] = 8] = "ExcludeOptional";
  return MappedTypeModifiers2;
})(MappedTypeModifiers || {});
var MappedTypeNameTypeKind = /* @__PURE__ */ ((MappedTypeNameTypeKind2) => {
  MappedTypeNameTypeKind2[MappedTypeNameTypeKind2["None"] = 0] = "None";
  MappedTypeNameTypeKind2[MappedTypeNameTypeKind2["Filtering"] = 1] = "Filtering";
  MappedTypeNameTypeKind2[MappedTypeNameTypeKind2["Remapping"] = 2] = "Remapping";
  return MappedTypeNameTypeKind2;
})(MappedTypeNameTypeKind || {});
var ExpandingFlags = /* @__PURE__ */ ((ExpandingFlags2) => {
  ExpandingFlags2[ExpandingFlags2["None"] = 0] = "None";
  ExpandingFlags2[ExpandingFlags2["Source"] = 1] = "Source";
  ExpandingFlags2[ExpandingFlags2["Target"] = 2] = "Target";
  ExpandingFlags2[ExpandingFlags2["Both"] = 3] = "Both";
  return ExpandingFlags2;
})(ExpandingFlags || {});
var MembersOrExportsResolutionKind = /* @__PURE__ */ ((MembersOrExportsResolutionKind2) => {
  MembersOrExportsResolutionKind2["resolvedExports"] = "resolvedExports";
  MembersOrExportsResolutionKind2["resolvedMembers"] = "resolvedMembers";
  return MembersOrExportsResolutionKind2;
})(MembersOrExportsResolutionKind || {});
var UnusedKind = /* @__PURE__ */ ((UnusedKind2) => {
  UnusedKind2[UnusedKind2["Local"] = 0] = "Local";
  UnusedKind2[UnusedKind2["Parameter"] = 1] = "Parameter";
  return UnusedKind2;
})(UnusedKind || {});
const isNotOverloadAndNotAccessor = and(isNotOverload, isNotAccessor);
var DeclarationMeaning = /* @__PURE__ */ ((DeclarationMeaning2) => {
  DeclarationMeaning2[DeclarationMeaning2["GetAccessor"] = 1] = "GetAccessor";
  DeclarationMeaning2[DeclarationMeaning2["SetAccessor"] = 2] = "SetAccessor";
  DeclarationMeaning2[DeclarationMeaning2["PropertyAssignment"] = 4] = "PropertyAssignment";
  DeclarationMeaning2[DeclarationMeaning2["Method"] = 8] = "Method";
  DeclarationMeaning2[DeclarationMeaning2["PrivateStatic"] = 16] = "PrivateStatic";
  DeclarationMeaning2[DeclarationMeaning2["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
  DeclarationMeaning2[DeclarationMeaning2["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
  return DeclarationMeaning2;
})(DeclarationMeaning || {});
var DeclarationSpaces = /* @__PURE__ */ ((DeclarationSpaces2) => {
  DeclarationSpaces2[DeclarationSpaces2["None"] = 0] = "None";
  DeclarationSpaces2[DeclarationSpaces2["ExportValue"] = 1] = "ExportValue";
  DeclarationSpaces2[DeclarationSpaces2["ExportType"] = 2] = "ExportType";
  DeclarationSpaces2[DeclarationSpaces2["ExportNamespace"] = 4] = "ExportNamespace";
  return DeclarationSpaces2;
})(DeclarationSpaces || {});
var MinArgumentCountFlags = /* @__PURE__ */ ((MinArgumentCountFlags2) => {
  MinArgumentCountFlags2[MinArgumentCountFlags2["None"] = 0] = "None";
  MinArgumentCountFlags2[MinArgumentCountFlags2["StrongArityForUntypedJS"] = 1] = "StrongArityForUntypedJS";
  MinArgumentCountFlags2[MinArgumentCountFlags2["VoidIsNonOptional"] = 2] = "VoidIsNonOptional";
  return MinArgumentCountFlags2;
})(MinArgumentCountFlags || {});
var IntrinsicTypeKind = /* @__PURE__ */ ((IntrinsicTypeKind2) => {
  IntrinsicTypeKind2[IntrinsicTypeKind2["Uppercase"] = 0] = "Uppercase";
  IntrinsicTypeKind2[IntrinsicTypeKind2["Lowercase"] = 1] = "Lowercase";
  IntrinsicTypeKind2[IntrinsicTypeKind2["Capitalize"] = 2] = "Capitalize";
  IntrinsicTypeKind2[IntrinsicTypeKind2["Uncapitalize"] = 3] = "Uncapitalize";
  IntrinsicTypeKind2[IntrinsicTypeKind2["NoInfer"] = 4] = "NoInfer";
  return IntrinsicTypeKind2;
})(IntrinsicTypeKind || {});
const intrinsicTypeKinds = new Map(Object.entries({
  Uppercase: 0 /* Uppercase */,
  Lowercase: 1 /* Lowercase */,
  Capitalize: 2 /* Capitalize */,
  Uncapitalize: 3 /* Uncapitalize */,
  NoInfer: 4 /* NoInfer */
}));
const SymbolLinks = class {
};
function NodeLinks() {
  this.flags = NodeCheckFlags.None;
}
export function getNodeId(node) {
  if (!node.id) {
    node.id = nextNodeId;
    nextNodeId++;
  }
  return node.id;
}
export function getSymbolId(symbol) {
  if (!symbol.id) {
    symbol.id = nextSymbolId;
    nextSymbolId++;
  }
  return symbol.id;
}
export function isInstantiatedModule(node, preserveConstEnums) {
  const moduleState = getModuleInstanceState(node);
  return moduleState === ModuleInstanceState.Instantiated || preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly;
}
export function createTypeChecker(host) {
  var deferredDiagnosticsCallbacks = [];
  var addLazyDiagnostic = (arg) => {
    deferredDiagnosticsCallbacks.push(arg);
  };
  var cancellationToken;
  var scanner;
  var Symbol2 = objectAllocator.getSymbolConstructor();
  var Type2 = objectAllocator.getTypeConstructor();
  var Signature2 = objectAllocator.getSignatureConstructor();
  var typeCount = 0;
  var symbolCount = 0;
  var totalInstantiationCount = 0;
  var instantiationCount = 0;
  var instantiationDepth = 0;
  var inlineLevel = 0;
  var currentNode;
  var varianceTypeParameter;
  var isInferencePartiallyBlocked = false;
  var emptySymbols = createSymbolTable();
  var arrayVariances = [VarianceFlags.Covariant];
  var compilerOptions = host.getCompilerOptions();
  var languageVersion = getEmitScriptTarget(compilerOptions);
  var moduleKind = getEmitModuleKind(compilerOptions);
  var legacyDecorators = !!compilerOptions.experimentalDecorators;
  var useDefineForClassFields = getUseDefineForClassFields(compilerOptions);
  var emitStandardClassFields = getEmitStandardClassFields(compilerOptions);
  var allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions);
  var strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks");
  var strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes");
  var strictBindCallApply = getStrictOptionValue(compilerOptions, "strictBindCallApply");
  var strictPropertyInitialization = getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
  var strictBuiltinIteratorReturn = getStrictOptionValue(compilerOptions, "strictBuiltinIteratorReturn");
  var noImplicitAny = getStrictOptionValue(compilerOptions, "noImplicitAny");
  var noImplicitThis = getStrictOptionValue(compilerOptions, "noImplicitThis");
  var useUnknownInCatchVariables = getStrictOptionValue(compilerOptions, "useUnknownInCatchVariables");
  var exactOptionalPropertyTypes = compilerOptions.exactOptionalPropertyTypes;
  var noUncheckedSideEffectImports = !!compilerOptions.noUncheckedSideEffectImports;
  var checkBinaryExpression = createCheckBinaryExpression();
  var emitResolver = createResolver();
  var nodeBuilder = createNodeBuilder();
  var syntacticNodeBuilder = createSyntacticTypeNodeBuilder(compilerOptions, {
    isEntityNameVisible,
    isExpandoFunctionDeclaration,
    getAllAccessorDeclarations: getAllAccessorDeclarationsForDeclaration,
    requiresAddingImplicitUndefined,
    isUndefinedIdentifierExpression(node) {
      Debug.assert(isExpressionNode(node));
      return getSymbolAtLocation(node) === undefinedSymbol;
    },
    isDefinitelyReferenceToGlobalSymbolObject
  });
  var evaluate = createEvaluator({
    evaluateElementAccessExpression,
    evaluateEntityNameExpression
  });
  var globals = createSymbolTable();
  var undefinedSymbol = createSymbol(SymbolFlags.Property, "undefined");
  undefinedSymbol.declarations = [];
  var globalThisSymbol = createSymbol(SymbolFlags.Module, "globalThis", CheckFlags.Readonly);
  globalThisSymbol.exports = globals;
  globalThisSymbol.declarations = [];
  globals.set(globalThisSymbol.escapedName, globalThisSymbol);
  var argumentsSymbol = createSymbol(SymbolFlags.Property, "arguments");
  var requireSymbol = createSymbol(SymbolFlags.Property, "require");
  var isolatedModulesLikeFlagName = compilerOptions.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules";
  var canCollectSymbolAliasAccessabilityData = !compilerOptions.verbatimModuleSyntax;
  var apparentArgumentCount;
  var lastGetCombinedNodeFlagsNode;
  var lastGetCombinedNodeFlagsResult = NodeFlags.None;
  var lastGetCombinedModifierFlagsNode;
  var lastGetCombinedModifierFlagsResult = ModifierFlags.None;
  var resolveName = createNameResolver({
    compilerOptions,
    requireSymbol,
    argumentsSymbol,
    globals,
    getSymbolOfDeclaration,
    error,
    getRequiresScopeChangeCache,
    setRequiresScopeChangeCache,
    lookup: getSymbol,
    onPropertyWithInvalidInitializer: checkAndReportErrorForInvalidInitializer,
    onFailedToResolveSymbol,
    onSuccessfullyResolvedSymbol
  });
  var resolveNameForSymbolSuggestion = createNameResolver({
    compilerOptions,
    requireSymbol,
    argumentsSymbol,
    globals,
    getSymbolOfDeclaration,
    error,
    getRequiresScopeChangeCache,
    setRequiresScopeChangeCache,
    lookup: getSuggestionForSymbolNameLookup
  });
  const checker = {
    getNodeCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.nodeCount, 0),
    getIdentifierCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.identifierCount, 0),
    getSymbolCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.symbolCount, symbolCount),
    getTypeCount: () => typeCount,
    getInstantiationCount: () => totalInstantiationCount,
    getRelationCacheSizes: () => ({
      assignable: assignableRelation.size,
      identity: identityRelation.size,
      subtype: subtypeRelation.size,
      strictSubtype: strictSubtypeRelation.size
    }),
    isUndefinedSymbol: (symbol) => symbol === undefinedSymbol,
    isArgumentsSymbol: (symbol) => symbol === argumentsSymbol,
    isUnknownSymbol: (symbol) => symbol === unknownSymbol,
    getMergedSymbol,
    symbolIsValue,
    getDiagnostics,
    getGlobalDiagnostics,
    getRecursionIdentity,
    getUnmatchedProperties,
    getTypeOfSymbolAtLocation: (symbol, locationIn) => {
      const location = getParseTreeNode(locationIn);
      return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
    },
    getTypeOfSymbol,
    getSymbolsOfParameterPropertyDeclaration: (parameterIn, parameterName) => {
      const parameter = getParseTreeNode(parameterIn, isParameter);
      if (parameter === void 0) return Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
      Debug.assert(isParameterPropertyDeclaration(parameter, parameter.parent));
      return getSymbolsOfParameterPropertyDeclaration(parameter, escapeLeadingUnderscores(parameterName));
    },
    getDeclaredTypeOfSymbol,
    getPropertiesOfType,
    getPropertyOfType: (type, name) => getPropertyOfType(type, escapeLeadingUnderscores(name)),
    getPrivateIdentifierPropertyOfType: (leftType, name, location) => {
      const node = getParseTreeNode(location);
      if (!node) {
        return void 0;
      }
      const propName = escapeLeadingUnderscores(name);
      const lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
      return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : void 0;
    },
    getTypeOfPropertyOfType: (type, name) => getTypeOfPropertyOfType(type, escapeLeadingUnderscores(name)),
    getIndexInfoOfType: (type, kind) => getIndexInfoOfType(type, kind === IndexKind.String ? stringType : numberType),
    getIndexInfosOfType,
    getIndexInfosOfIndexSymbol,
    getSignaturesOfType,
    getIndexTypeOfType: (type, kind) => getIndexTypeOfType(type, kind === IndexKind.String ? stringType : numberType),
    getIndexType: (type) => getIndexType(type),
    getBaseTypes,
    getBaseTypeOfLiteralType,
    getWidenedType,
    getWidenedLiteralType,
    getTypeFromTypeNode: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isTypeNode);
      return node ? getTypeFromTypeNode(node) : errorType;
    },
    getParameterType: getTypeAtPosition,
    getParameterIdentifierInfoAtPosition,
    getPromisedTypeOfPromise,
    getAwaitedType: (type) => getAwaitedType(type),
    getReturnTypeOfSignature,
    isNullableType,
    getNullableType,
    getNonNullableType,
    getNonOptionalType: removeOptionalTypeMarker,
    getTypeArguments,
    typeToTypeNode: nodeBuilder.typeToTypeNode,
    typePredicateToTypePredicateNode: nodeBuilder.typePredicateToTypePredicateNode,
    indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
    signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
    symbolToEntityName: nodeBuilder.symbolToEntityName,
    symbolToExpression: nodeBuilder.symbolToExpression,
    symbolToNode: nodeBuilder.symbolToNode,
    symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
    symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
    typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
    getSymbolsInScope: (locationIn, meaning) => {
      const location = getParseTreeNode(locationIn);
      return location ? getSymbolsInScope(location, meaning) : [];
    },
    getSymbolAtLocation: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getSymbolAtLocation(
        node,
        /*ignoreErrors*/
        true
      ) : void 0;
    },
    getIndexInfosAtLocation: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getIndexInfosAtLocation(node) : void 0;
    },
    getShorthandAssignmentValueSymbol: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getShorthandAssignmentValueSymbol(node) : void 0;
    },
    getExportSpecifierLocalTargetSymbol: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isExportSpecifier);
      return node ? getExportSpecifierLocalTargetSymbol(node) : void 0;
    },
    getExportSymbolOfSymbol(symbol) {
      return getMergedSymbol(symbol.exportSymbol || symbol);
    },
    getTypeAtLocation: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getTypeOfNode(node) : errorType;
    },
    getTypeOfAssignmentPattern: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isAssignmentPattern);
      return node && getTypeOfAssignmentPattern(node) || errorType;
    },
    getPropertySymbolOfDestructuringAssignment: (locationIn) => {
      const location = getParseTreeNode(locationIn, isIdentifier);
      return location ? getPropertySymbolOfDestructuringAssignment(location) : void 0;
    },
    signatureToString: (signature, enclosingDeclaration, flags, kind) => {
      return signatureToString(signature, getParseTreeNode(enclosingDeclaration), flags, kind);
    },
    typeToString: (type, enclosingDeclaration, flags) => {
      return typeToString(type, getParseTreeNode(enclosingDeclaration), flags);
    },
    symbolToString: (symbol, enclosingDeclaration, meaning, flags) => {
      return symbolToString(symbol, getParseTreeNode(enclosingDeclaration), meaning, flags);
    },
    typePredicateToString: (predicate, enclosingDeclaration, flags) => {
      return typePredicateToString(predicate, getParseTreeNode(enclosingDeclaration), flags);
    },
    writeSignature: (signature, enclosingDeclaration, flags, kind, writer) => {
      return signatureToString(signature, getParseTreeNode(enclosingDeclaration), flags, kind, writer);
    },
    writeType: (type, enclosingDeclaration, flags, writer) => {
      return typeToString(type, getParseTreeNode(enclosingDeclaration), flags, writer);
    },
    writeSymbol: (symbol, enclosingDeclaration, meaning, flags, writer) => {
      return symbolToString(symbol, getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
    },
    writeTypePredicate: (predicate, enclosingDeclaration, flags, writer) => {
      return typePredicateToString(predicate, getParseTreeNode(enclosingDeclaration), flags, writer);
    },
    getAugmentedPropertiesOfType,
    getRootSymbols,
    getSymbolOfExpando,
    getContextualType: (nodeIn, contextFlags) => {
      const node = getParseTreeNode(nodeIn, isExpression);
      if (!node) {
        return void 0;
      }
      if (contextFlags & ContextFlags.Completions) {
        return runWithInferenceBlockedFromSourceNode(node, () => getContextualType(node, contextFlags));
      }
      return getContextualType(node, contextFlags);
    },
    getContextualTypeForObjectLiteralElement: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isObjectLiteralElementLike);
      return node ? getContextualTypeForObjectLiteralElement(
        node,
        /*contextFlags*/
        void 0
      ) : void 0;
    },
    getContextualTypeForArgumentAtIndex: (nodeIn, argIndex) => {
      const node = getParseTreeNode(nodeIn, isCallLikeExpression);
      return node && getContextualTypeForArgumentAtIndex(node, argIndex);
    },
    getContextualTypeForJsxAttribute: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isJsxAttributeLike);
      return node && getContextualTypeForJsxAttribute(
        node,
        /*contextFlags*/
        void 0
      );
    },
    isContextSensitive,
    getTypeOfPropertyOfContextualType,
    getFullyQualifiedName,
    getResolvedSignature: (node, candidatesOutArray, argumentCount) => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */),
    getCandidateSignaturesForStringLiteralCompletions,
    getResolvedSignatureForSignatureHelp: (node, candidatesOutArray, argumentCount) => runWithoutResolvedSignatureCaching(node, () => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */)),
    getExpandedParameters,
    hasEffectiveRestParameter,
    containsArgumentsReference,
    getConstantValue: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, canHaveConstantValue);
      return node ? getConstantValue(node) : void 0;
    },
    isValidPropertyAccess: (nodeIn, propertyName) => {
      const node = getParseTreeNode(nodeIn, isPropertyAccessOrQualifiedNameOrImportTypeNode);
      return !!node && isValidPropertyAccess(node, escapeLeadingUnderscores(propertyName));
    },
    isValidPropertyAccessForCompletions: (nodeIn, type, property) => {
      const node = getParseTreeNode(nodeIn, isPropertyAccessExpression);
      return !!node && isValidPropertyAccessForCompletions(node, type, property);
    },
    getSignatureFromDeclaration: (declarationIn) => {
      const declaration = getParseTreeNode(declarationIn, isFunctionLike);
      return declaration ? getSignatureFromDeclaration(declaration) : void 0;
    },
    isImplementationOfOverload: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isFunctionLike);
      return node ? isImplementationOfOverload(node) : void 0;
    },
    getImmediateAliasedSymbol,
    getAliasedSymbol: resolveAlias,
    getEmitResolver,
    requiresAddingImplicitUndefined,
    getExportsOfModule: getExportsOfModuleAsArray,
    getExportsAndPropertiesOfModule,
    forEachExportAndPropertyOfModule,
    getSymbolWalker: createGetSymbolWalker(
      getRestTypeOfSignature,
      getTypePredicateOfSignature,
      getReturnTypeOfSignature,
      getBaseTypes,
      resolveStructuredTypeMembers,
      getTypeOfSymbol,
      getResolvedSymbol,
      getConstraintOfTypeParameter,
      getFirstIdentifier,
      getTypeArguments
    ),
    getAmbientModules,
    getJsxIntrinsicTagNamesAt,
    isOptionalParameter: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isParameter);
      return node ? isOptionalParameter(node) : false;
    },
    tryGetMemberInModuleExports: (name, symbol) => tryGetMemberInModuleExports(escapeLeadingUnderscores(name), symbol),
    tryGetMemberInModuleExportsAndProperties: (name, symbol) => tryGetMemberInModuleExportsAndProperties(escapeLeadingUnderscores(name), symbol),
    tryFindAmbientModule: (moduleName) => tryFindAmbientModule(
      moduleName,
      /*withAugmentations*/
      true
    ),
    getApparentType,
    getUnionType,
    isTypeAssignableTo,
    createAnonymousType,
    createSignature,
    createSymbol,
    createIndexInfo,
    getAnyType: () => anyType,
    getStringType: () => stringType,
    getStringLiteralType,
    getNumberType: () => numberType,
    getNumberLiteralType,
    getBigIntType: () => bigintType,
    getBigIntLiteralType,
    createPromiseType,
    createArrayType,
    getElementTypeOfArrayType,
    getBooleanType: () => booleanType,
    getFalseType: (fresh) => fresh ? falseType : regularFalseType,
    getTrueType: (fresh) => fresh ? trueType : regularTrueType,
    getVoidType: () => voidType,
    getUndefinedType: () => undefinedType,
    getNullType: () => nullType,
    getESSymbolType: () => esSymbolType,
    getNeverType: () => neverType,
    getOptionalType: () => optionalType,
    getPromiseType: () => getGlobalPromiseType(
      /*reportErrors*/
      false
    ),
    getPromiseLikeType: () => getGlobalPromiseLikeType(
      /*reportErrors*/
      false
    ),
    getAnyAsyncIterableType: () => {
      const type = getGlobalAsyncIterableType(
        /*reportErrors*/
        false
      );
      if (type === emptyGenericType) return void 0;
      return createTypeReference(type, [anyType, anyType, anyType]);
    },
    isSymbolAccessible,
    isArrayType,
    isTupleType,
    isArrayLikeType,
    isEmptyAnonymousObjectType,
    isTypeInvalidDueToUnionDiscriminant,
    getExactOptionalProperties,
    getAllPossiblePropertiesOfTypes,
    getSuggestedSymbolForNonexistentProperty,
    getSuggestedSymbolForNonexistentJSXAttribute,
    getSuggestedSymbolForNonexistentSymbol: (location, name, meaning) => getSuggestedSymbolForNonexistentSymbol(location, escapeLeadingUnderscores(name), meaning),
    getSuggestedSymbolForNonexistentModule,
    getSuggestedSymbolForNonexistentClassMember,
    getBaseConstraintOfType,
    getDefaultFromTypeParameter: (type) => type && type.flags & TypeFlags.TypeParameter ? getDefaultFromTypeParameter(type) : void 0,
    resolveName(name, location, meaning, excludeGlobals) {
      return resolveName(
        location,
        escapeLeadingUnderscores(name),
        meaning,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false,
        excludeGlobals
      );
    },
    getJsxNamespace: (n) => unescapeLeadingUnderscores(getJsxNamespace(n)),
    getJsxFragmentFactory: (n) => {
      const jsxFragmentFactory = getJsxFragmentFactoryEntity(n);
      return jsxFragmentFactory && unescapeLeadingUnderscores(getFirstIdentifier(jsxFragmentFactory).escapedText);
    },
    getAccessibleSymbolChain,
    getTypePredicateOfSignature,
    resolveExternalModuleName: (moduleSpecifierIn) => {
      const moduleSpecifier = getParseTreeNode(moduleSpecifierIn, isExpression);
      return moduleSpecifier && resolveExternalModuleName(
        moduleSpecifier,
        moduleSpecifier,
        /*ignoreErrors*/
        true
      );
    },
    resolveExternalModuleSymbol,
    tryGetThisTypeAt: (nodeIn, includeGlobalThis, container) => {
      const node = getParseTreeNode(nodeIn);
      return node && tryGetThisTypeAt(node, includeGlobalThis, container);
    },
    getTypeArgumentConstraint: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isTypeNode);
      return node && getTypeArgumentConstraint(node);
    },
    getSuggestionDiagnostics: (fileIn, ct) => {
      const file = getParseTreeNode(fileIn, isSourceFile) || Debug.fail("Could not determine parsed source file.");
      if (skipTypeChecking(file, compilerOptions, host)) {
        return emptyArray;
      }
      let diagnostics2;
      try {
        cancellationToken = ct;
        checkSourceFileWithEagerDiagnostics(file);
        Debug.assert(!!(getNodeLinks(file).flags & NodeCheckFlags.TypeChecked));
        diagnostics2 = addRange(diagnostics2, suggestionDiagnostics.getDiagnostics(file.fileName));
        checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), (containingNode, kind, diag) => {
          if (!containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & NodeFlags.Ambient))) {
            (diagnostics2 || (diagnostics2 = [])).push({ ...diag, category: DiagnosticCategory.Suggestion });
          }
        });
        return diagnostics2 || emptyArray;
      } finally {
        cancellationToken = void 0;
      }
    },
    runWithCancellationToken: (token, callback) => {
      try {
        cancellationToken = token;
        return callback(checker);
      } finally {
        cancellationToken = void 0;
      }
    },
    getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
    isDeclarationVisible,
    isPropertyAccessible,
    getTypeOnlyAliasDeclaration,
    getMemberOverrideModifierStatus,
    isTypeParameterPossiblyReferenced,
    typeHasCallOrConstructSignatures,
    getSymbolFlags
  };
  function getCandidateSignaturesForStringLiteralCompletions(call, editingArgument) {
    const candidatesSet = /* @__PURE__ */ new Set();
    const candidates = [];
    runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignatureWorker(
      call,
      candidates,
      /*argumentCount*/
      void 0,
      0 /* Normal */
    ));
    for (const candidate of candidates) {
      candidatesSet.add(candidate);
    }
    candidates.length = 0;
    runWithoutResolvedSignatureCaching(editingArgument, () => getResolvedSignatureWorker(
      call,
      candidates,
      /*argumentCount*/
      void 0,
      0 /* Normal */
    ));
    for (const candidate of candidates) {
      candidatesSet.add(candidate);
    }
    return arrayFrom(candidatesSet);
  }
  function runWithoutResolvedSignatureCaching(node, fn) {
    node = findAncestor(node, isCallLikeOrFunctionLikeExpression);
    if (node) {
      const cachedResolvedSignatures = [];
      const cachedTypes2 = [];
      while (node) {
        const nodeLinks2 = getNodeLinks(node);
        cachedResolvedSignatures.push([nodeLinks2, nodeLinks2.resolvedSignature]);
        nodeLinks2.resolvedSignature = void 0;
        if (isFunctionExpressionOrArrowFunction(node)) {
          const symbolLinks2 = getSymbolLinks(getSymbolOfDeclaration(node));
          const type = symbolLinks2.type;
          cachedTypes2.push([symbolLinks2, type]);
          symbolLinks2.type = void 0;
        }
        node = findAncestor(node.parent, isCallLikeOrFunctionLikeExpression);
      }
      const result = fn();
      for (const [nodeLinks2, resolvedSignature] of cachedResolvedSignatures) {
        nodeLinks2.resolvedSignature = resolvedSignature;
      }
      for (const [symbolLinks2, type] of cachedTypes2) {
        symbolLinks2.type = type;
      }
      return result;
    }
    return fn();
  }
  function runWithInferenceBlockedFromSourceNode(node, fn) {
    const containingCall = findAncestor(node, isCallLikeExpression);
    if (containingCall) {
      let toMarkSkip = node;
      do {
        getNodeLinks(toMarkSkip).skipDirectInference = true;
        toMarkSkip = toMarkSkip.parent;
      } while (toMarkSkip && toMarkSkip !== containingCall);
    }
    isInferencePartiallyBlocked = true;
    const result = runWithoutResolvedSignatureCaching(node, fn);
    isInferencePartiallyBlocked = false;
    if (containingCall) {
      let toMarkSkip = node;
      do {
        getNodeLinks(toMarkSkip).skipDirectInference = void 0;
        toMarkSkip = toMarkSkip.parent;
      } while (toMarkSkip && toMarkSkip !== containingCall);
    }
    return result;
  }
  function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
    const node = getParseTreeNode(nodeIn, isCallLikeExpression);
    apparentArgumentCount = argumentCount;
    const res = !node ? void 0 : getResolvedSignature(node, candidatesOutArray, checkMode);
    apparentArgumentCount = void 0;
    return res;
  }
  var tupleTypes = /* @__PURE__ */ new Map();
  var unionTypes = /* @__PURE__ */ new Map();
  var unionOfUnionTypes = /* @__PURE__ */ new Map();
  var intersectionTypes = /* @__PURE__ */ new Map();
  var stringLiteralTypes = /* @__PURE__ */ new Map();
  var numberLiteralTypes = /* @__PURE__ */ new Map();
  var bigIntLiteralTypes = /* @__PURE__ */ new Map();
  var enumLiteralTypes = /* @__PURE__ */ new Map();
  var indexedAccessTypes = /* @__PURE__ */ new Map();
  var templateLiteralTypes = /* @__PURE__ */ new Map();
  var stringMappingTypes = /* @__PURE__ */ new Map();
  var substitutionTypes = /* @__PURE__ */ new Map();
  var subtypeReductionCache = /* @__PURE__ */ new Map();
  var decoratorContextOverrideTypeCache = /* @__PURE__ */ new Map();
  var cachedTypes = /* @__PURE__ */ new Map();
  var evolvingArrayTypes = [];
  var undefinedProperties = /* @__PURE__ */ new Map();
  var markerTypes = /* @__PURE__ */ new Set();
  var unknownSymbol = createSymbol(SymbolFlags.Property, "unknown");
  var resolvingSymbol = createSymbol(0, InternalSymbolName.Resolving);
  var unresolvedSymbols = /* @__PURE__ */ new Map();
  var errorTypes = /* @__PURE__ */ new Map();
  var seenIntrinsicNames = /* @__PURE__ */ new Set();
  var anyType = createIntrinsicType(TypeFlags.Any, "any");
  var autoType = createIntrinsicType(TypeFlags.Any, "any", ObjectFlags.NonInferrableType, "auto");
  var wildcardType = createIntrinsicType(
    TypeFlags.Any,
    "any",
    /*objectFlags*/
    void 0,
    "wildcard"
  );
  var blockedStringType = createIntrinsicType(
    TypeFlags.Any,
    "any",
    /*objectFlags*/
    void 0,
    "blocked string"
  );
  var errorType = createIntrinsicType(TypeFlags.Any, "error");
  var unresolvedType = createIntrinsicType(TypeFlags.Any, "unresolved");
  var nonInferrableAnyType = createIntrinsicType(TypeFlags.Any, "any", ObjectFlags.ContainsWideningType, "non-inferrable");
  var intrinsicMarkerType = createIntrinsicType(TypeFlags.Any, "intrinsic");
  var unknownType = createIntrinsicType(TypeFlags.Unknown, "unknown");
  var undefinedType = createIntrinsicType(TypeFlags.Undefined, "undefined");
  var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(TypeFlags.Undefined, "undefined", ObjectFlags.ContainsWideningType, "widening");
  var missingType = createIntrinsicType(
    TypeFlags.Undefined,
    "undefined",
    /*objectFlags*/
    void 0,
    "missing"
  );
  var undefinedOrMissingType = exactOptionalPropertyTypes ? missingType : undefinedType;
  var optionalType = createIntrinsicType(
    TypeFlags.Undefined,
    "undefined",
    /*objectFlags*/
    void 0,
    "optional"
  );
  var nullType = createIntrinsicType(TypeFlags.Null, "null");
  var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(TypeFlags.Null, "null", ObjectFlags.ContainsWideningType, "widening");
  var stringType = createIntrinsicType(TypeFlags.String, "string");
  var numberType = createIntrinsicType(TypeFlags.Number, "number");
  var bigintType = createIntrinsicType(TypeFlags.BigInt, "bigint");
  var falseType = createIntrinsicType(
    TypeFlags.BooleanLiteral,
    "false",
    /*objectFlags*/
    void 0,
    "fresh"
  );
  var regularFalseType = createIntrinsicType(TypeFlags.BooleanLiteral, "false");
  var trueType = createIntrinsicType(
    TypeFlags.BooleanLiteral,
    "true",
    /*objectFlags*/
    void 0,
    "fresh"
  );
  var regularTrueType = createIntrinsicType(TypeFlags.BooleanLiteral, "true");
  trueType.regularType = regularTrueType;
  trueType.freshType = trueType;
  regularTrueType.regularType = regularTrueType;
  regularTrueType.freshType = trueType;
  falseType.regularType = regularFalseType;
  falseType.freshType = falseType;
  regularFalseType.regularType = regularFalseType;
  regularFalseType.freshType = falseType;
  var booleanType = getUnionType([regularFalseType, regularTrueType]);
  var esSymbolType = createIntrinsicType(TypeFlags.ESSymbol, "symbol");
  var voidType = createIntrinsicType(TypeFlags.Void, "void");
  var neverType = createIntrinsicType(TypeFlags.Never, "never");
  var silentNeverType = createIntrinsicType(TypeFlags.Never, "never", ObjectFlags.NonInferrableType, "silent");
  var implicitNeverType = createIntrinsicType(
    TypeFlags.Never,
    "never",
    /*objectFlags*/
    void 0,
    "implicit"
  );
  var unreachableNeverType = createIntrinsicType(
    TypeFlags.Never,
    "never",
    /*objectFlags*/
    void 0,
    "unreachable"
  );
  var nonPrimitiveType = createIntrinsicType(TypeFlags.NonPrimitive, "object");
  var stringOrNumberType = getUnionType([stringType, numberType]);
  var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
  var numberOrBigIntType = getUnionType([numberType, bigintType]);
  var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]);
  var numericStringType = getTemplateLiteralType(["", ""], [numberType]);
  var restrictiveMapper = makeFunctionTypeMapper((t) => t.flags & TypeFlags.TypeParameter ? getRestrictiveTypeParameter(t) : t, () => "(restrictive mapper)");
  var permissiveMapper = makeFunctionTypeMapper((t) => t.flags & TypeFlags.TypeParameter ? wildcardType : t, () => "(permissive mapper)");
  var uniqueLiteralType = createIntrinsicType(
    TypeFlags.Never,
    "never",
    /*objectFlags*/
    void 0,
    "unique literal"
  );
  var uniqueLiteralMapper = makeFunctionTypeMapper((t) => t.flags & TypeFlags.TypeParameter ? uniqueLiteralType : t, () => "(unique literal mapper)");
  var outofbandVarianceMarkerHandler;
  var reportUnreliableMapper = makeFunctionTypeMapper((t) => {
    if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) {
      outofbandVarianceMarkerHandler(
        /*onlyUnreliable*/
        true
      );
    }
    return t;
  }, () => "(unmeasurable reporter)");
  var reportUnmeasurableMapper = makeFunctionTypeMapper((t) => {
    if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) {
      outofbandVarianceMarkerHandler(
        /*onlyUnreliable*/
        false
      );
    }
    return t;
  }, () => "(unreliable reporter)");
  var emptyObjectType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var emptyJsxObjectType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  emptyJsxObjectType.objectFlags |= ObjectFlags.JsxAttributes;
  var emptyTypeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, InternalSymbolName.Type);
  emptyTypeLiteralSymbol.members = createSymbolTable();
  var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, emptyArray);
  var unknownEmptyObjectType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, unknownEmptyObjectType]) : unknownType;
  var emptyGenericType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  emptyGenericType.instantiations = /* @__PURE__ */ new Map();
  var anyFunctionType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  anyFunctionType.objectFlags |= ObjectFlags.NonInferrableType;
  var noConstraintType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var circularConstraintType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var resolvingDefaultType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var markerSuperType = createTypeParameter();
  var markerSubType = createTypeParameter();
  markerSubType.constraint = markerSuperType;
  var markerOtherType = createTypeParameter();
  var markerSuperTypeForCheck = createTypeParameter();
  var markerSubTypeForCheck = createTypeParameter();
  markerSubTypeForCheck.constraint = markerSuperTypeForCheck;
  var noTypePredicate = createTypePredicate(TypePredicateKind.Identifier, "<<unresolved>>", 0, anyType);
  var anySignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    anyType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    SignatureFlags.None
  );
  var unknownSignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    errorType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    SignatureFlags.None
  );
  var resolvingSignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    anyType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    SignatureFlags.None
  );
  var silentNeverSignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    silentNeverType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    SignatureFlags.None
  );
  var enumNumberIndexInfo = createIndexInfo(
    numberType,
    stringType,
    /*isReadonly*/
    true
  );
  var iterationTypesCache = /* @__PURE__ */ new Map();
  var noIterationTypes = {
    get yieldType() {
      return Debug.fail("Not supported");
    },
    get returnType() {
      return Debug.fail("Not supported");
    },
    get nextType() {
      return Debug.fail("Not supported");
    }
  };
  var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
  var asyncIterationTypesResolver = {
    iterableCacheKey: "iterationTypesOfAsyncIterable",
    iteratorCacheKey: "iterationTypesOfAsyncIterator",
    iteratorSymbolName: "asyncIterator",
    getGlobalIteratorType: getGlobalAsyncIteratorType,
    getGlobalIterableType: getGlobalAsyncIterableType,
    getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
    getGlobalIteratorObjectType: getGlobalAsyncIteratorObjectType,
    getGlobalGeneratorType: getGlobalAsyncGeneratorType,
    getGlobalBuiltinIteratorTypes: getGlobalBuiltinAsyncIteratorTypes,
    resolveIterationType: (type, errorNode) => getAwaitedType(type, errorNode, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member),
    mustHaveANextMethodDiagnostic: Diagnostics.An_async_iterator_must_have_a_next_method,
    mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
    mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property
  };
  var syncIterationTypesResolver = {
    iterableCacheKey: "iterationTypesOfIterable",
    iteratorCacheKey: "iterationTypesOfIterator",
    iteratorSymbolName: "iterator",
    getGlobalIteratorType,
    getGlobalIterableType,
    getGlobalIterableIteratorType,
    getGlobalIteratorObjectType,
    getGlobalGeneratorType,
    getGlobalBuiltinIteratorTypes,
    resolveIterationType: (type, _errorNode) => type,
    mustHaveANextMethodDiagnostic: Diagnostics.An_iterator_must_have_a_next_method,
    mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
    mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property
  };
  var amalgamatedDuplicates;
  var reverseMappedCache = /* @__PURE__ */ new Map();
  var reverseHomomorphicMappedCache = /* @__PURE__ */ new Map();
  var ambientModulesCache;
  var patternAmbientModules;
  var patternAmbientModuleAugmentations;
  var globalObjectType;
  var globalFunctionType;
  var globalCallableFunctionType;
  var globalNewableFunctionType;
  var globalArrayType;
  var globalReadonlyArrayType;
  var globalStringType;
  var globalNumberType;
  var globalBooleanType;
  var globalRegExpType;
  var globalThisType;
  var anyArrayType;
  var autoArrayType;
  var anyReadonlyArrayType;
  var deferredGlobalNonNullableTypeAlias;
  var deferredGlobalESSymbolConstructorSymbol;
  var deferredGlobalESSymbolConstructorTypeSymbol;
  var deferredGlobalESSymbolType;
  var deferredGlobalTypedPropertyDescriptorType;
  var deferredGlobalPromiseType;
  var deferredGlobalPromiseLikeType;
  var deferredGlobalPromiseConstructorSymbol;
  var deferredGlobalPromiseConstructorLikeType;
  var deferredGlobalIterableType;
  var deferredGlobalIteratorType;
  var deferredGlobalIterableIteratorType;
  var deferredGlobalIteratorObjectType;
  var deferredGlobalGeneratorType;
  var deferredGlobalIteratorYieldResultType;
  var deferredGlobalIteratorReturnResultType;
  var deferredGlobalAsyncIterableType;
  var deferredGlobalAsyncIteratorType;
  var deferredGlobalAsyncIterableIteratorType;
  var deferredGlobalBuiltinIteratorTypes;
  var deferredGlobalBuiltinAsyncIteratorTypes;
  var deferredGlobalAsyncIteratorObjectType;
  var deferredGlobalAsyncGeneratorType;
  var deferredGlobalTemplateStringsArrayType;
  var deferredGlobalImportMetaType;
  var deferredGlobalImportMetaExpressionType;
  var deferredGlobalImportCallOptionsType;
  var deferredGlobalImportAttributesType;
  var deferredGlobalDisposableType;
  var deferredGlobalAsyncDisposableType;
  var deferredGlobalExtractSymbol;
  var deferredGlobalOmitSymbol;
  var deferredGlobalAwaitedSymbol;
  var deferredGlobalBigIntType;
  var deferredGlobalNaNSymbol;
  var deferredGlobalRecordSymbol;
  var deferredGlobalClassDecoratorContextType;
  var deferredGlobalClassMethodDecoratorContextType;
  var deferredGlobalClassGetterDecoratorContextType;
  var deferredGlobalClassSetterDecoratorContextType;
  var deferredGlobalClassAccessorDecoratorContextType;
  var deferredGlobalClassAccessorDecoratorTargetType;
  var deferredGlobalClassAccessorDecoratorResultType;
  var deferredGlobalClassFieldDecoratorContextType;
  var allPotentiallyUnusedIdentifiers = /* @__PURE__ */ new Map();
  var flowLoopStart = 0;
  var flowLoopCount = 0;
  var sharedFlowCount = 0;
  var flowAnalysisDisabled = false;
  var flowInvocationCount = 0;
  var lastFlowNode;
  var lastFlowNodeReachable;
  var flowTypeCache;
  var contextualTypeNodes = [];
  var contextualTypes = [];
  var contextualIsCache = [];
  var contextualTypeCount = 0;
  var contextualBindingPatterns = [];
  var inferenceContextNodes = [];
  var inferenceContexts = [];
  var inferenceContextCount = 0;
  var emptyStringType = getStringLiteralType("");
  var zeroType = getNumberLiteralType(0);
  var zeroBigIntType = getBigIntLiteralType({ negative: false, base10Value: "0" });
  var resolutionTargets = [];
  var resolutionResults = [];
  var resolutionPropertyNames = [];
  var resolutionStart = 0;
  var inVarianceComputation = false;
  var suggestionCount = 0;
  var maximumSuggestionCount = 10;
  var mergedSymbols = [];
  var symbolLinks = [];
  var nodeLinks = [];
  var flowLoopCaches = [];
  var flowLoopNodes = [];
  var flowLoopKeys = [];
  var flowLoopTypes = [];
  var sharedFlowNodes = [];
  var sharedFlowTypes = [];
  var flowNodeReachable = [];
  var flowNodePostSuper = [];
  var potentialThisCollisions = [];
  var potentialNewTargetCollisions = [];
  var potentialWeakMapSetCollisions = [];
  var potentialReflectCollisions = [];
  var potentialUnusedRenamedBindingElementsInTypes = [];
  var awaitedTypeStack = [];
  var reverseMappedSourceStack = [];
  var reverseMappedTargetStack = [];
  var reverseExpandingFlags = 0 /* None */;
  var diagnostics = createDiagnosticCollection();
  var suggestionDiagnostics = createDiagnosticCollection();
  var typeofType = createTypeofType();
  var _jsxNamespace;
  var _jsxFactoryEntity;
  var subtypeRelation = /* @__PURE__ */ new Map();
  var strictSubtypeRelation = /* @__PURE__ */ new Map();
  var assignableRelation = /* @__PURE__ */ new Map();
  var comparableRelation = /* @__PURE__ */ new Map();
  var identityRelation = /* @__PURE__ */ new Map();
  var enumRelation = /* @__PURE__ */ new Map();
  var suggestedExtensions = [
    [".mts", ".mjs"],
    [".ts", ".js"],
    [".cts", ".cjs"],
    [".mjs", ".mjs"],
    [".js", ".js"],
    [".cjs", ".cjs"],
    [".tsx", compilerOptions.jsx === JsxEmit.Preserve ? ".jsx" : ".js"],
    [".jsx", ".jsx"],
    [".json", ".json"]
  ];
  initializeTypeChecker();
  return checker;
  function isDefinitelyReferenceToGlobalSymbolObject(node) {
    if (!isPropertyAccessExpression(node)) return false;
    if (!isIdentifier(node.name)) return false;
    if (!isPropertyAccessExpression(node.expression) && !isIdentifier(node.expression)) return false;
    if (isIdentifier(node.expression)) {
      return idText(node.expression) === "Symbol" && getResolvedSymbol(node.expression) === (getGlobalSymbol(
        "Symbol",
        SymbolFlags.Value | SymbolFlags.ExportValue,
        /*diagnostic*/
        void 0
      ) || unknownSymbol);
    }
    if (!isIdentifier(node.expression.expression)) return false;
    return idText(node.expression.name) === "Symbol" && idText(node.expression.expression) === "globalThis" && getResolvedSymbol(node.expression.expression) === globalThisSymbol;
  }
  function getCachedType(key) {
    return key ? cachedTypes.get(key) : void 0;
  }
  function setCachedType(key, type) {
    if (key) cachedTypes.set(key, type);
    return type;
  }
  function getJsxNamespace(location) {
    if (location) {
      const file = getSourceFileOfNode(location);
      if (file) {
        if (isJsxOpeningFragment(location)) {
          if (file.localJsxFragmentNamespace) {
            return file.localJsxFragmentNamespace;
          }
          const jsxFragmentPragma = file.pragmas.get("jsxfrag");
          if (jsxFragmentPragma) {
            const chosenPragma = isArray(jsxFragmentPragma) ? jsxFragmentPragma[0] : jsxFragmentPragma;
            file.localJsxFragmentFactory = parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
            visitNode(file.localJsxFragmentFactory, markAsSynthetic, isEntityName);
            if (file.localJsxFragmentFactory) {
              return file.localJsxFragmentNamespace = getFirstIdentifier(file.localJsxFragmentFactory).escapedText;
            }
          }
          const entity = getJsxFragmentFactoryEntity(location);
          if (entity) {
            file.localJsxFragmentFactory = entity;
            return file.localJsxFragmentNamespace = getFirstIdentifier(entity).escapedText;
          }
        } else {
          const localJsxNamespace = getLocalJsxNamespace(file);
          if (localJsxNamespace) {
            return file.localJsxNamespace = localJsxNamespace;
          }
        }
      }
    }
    if (!_jsxNamespace) {
      _jsxNamespace = "React";
      if (compilerOptions.jsxFactory) {
        _jsxFactoryEntity = parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
        visitNode(_jsxFactoryEntity, markAsSynthetic);
        if (_jsxFactoryEntity) {
          _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText;
        }
      } else if (compilerOptions.reactNamespace) {
        _jsxNamespace = escapeLeadingUnderscores(compilerOptions.reactNamespace);
      }
    }
    if (!_jsxFactoryEntity) {
      _jsxFactoryEntity = factory.createQualifiedName(factory.createIdentifier(unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
    }
    return _jsxNamespace;
  }
  function getLocalJsxNamespace(file) {
    if (file.localJsxNamespace) {
      return file.localJsxNamespace;
    }
    const jsxPragma = file.pragmas.get("jsx");
    if (jsxPragma) {
      const chosenPragma = isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
      file.localJsxFactory = parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
      visitNode(file.localJsxFactory, markAsSynthetic, isEntityName);
      if (file.localJsxFactory) {
        return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
      }
    }
  }
  function markAsSynthetic(node) {
    setTextRangePosEnd(node, -1, -1);
    return visitEachChildWorker(
      node,
      markAsSynthetic,
      /*context*/
      void 0
    );
  }
  function getEmitResolver(sourceFile, cancellationToken2, skipDiagnostics) {
    if (!skipDiagnostics) getDiagnostics(sourceFile, cancellationToken2);
    return emitResolver;
  }
  function lookupOrIssueError(location, message, ...args) {
    const diagnostic = location ? createDiagnosticForNode(location, message, ...args) : createCompilerDiagnostic(message, ...args);
    const existing = diagnostics.lookup(diagnostic);
    if (existing) {
      return existing;
    } else {
      diagnostics.add(diagnostic);
      return diagnostic;
    }
  }
  function errorSkippedOn(key, location, message, ...args) {
    const diagnostic = error(location, message, ...args);
    diagnostic.skippedOn = key;
    return diagnostic;
  }
  function createError(location, message, ...args) {
    return location ? createDiagnosticForNode(location, message, ...args) : createCompilerDiagnostic(message, ...args);
  }
  function error(location, message, ...args) {
    const diagnostic = createError(location, message, ...args);
    diagnostics.add(diagnostic);
    return diagnostic;
  }
  function addErrorOrSuggestion(isError, diagnostic) {
    if (isError) {
      diagnostics.add(diagnostic);
    } else {
      suggestionDiagnostics.add({ ...diagnostic, category: DiagnosticCategory.Suggestion });
    }
  }
  function errorOrSuggestion(isError, location, message, ...args) {
    if (location.pos < 0 || location.end < 0) {
      if (!isError) {
        return;
      }
      const file = getSourceFileOfNode(location);
      addErrorOrSuggestion(isError, "message" in message ? createFileDiagnostic(file, 0, 0, message, ...args) : createDiagnosticForFileFromMessageChain(file, message));
      return;
    }
    addErrorOrSuggestion(isError, "message" in message ? createDiagnosticForNode(location, message, ...args) : createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(location), location, message));
  }
  function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, ...args) {
    const diagnostic = error(location, message, ...args);
    if (maybeMissingAwait) {
      const related = createDiagnosticForNode(location, Diagnostics.Did_you_forget_to_use_await);
      addRelatedInfo(diagnostic, related);
    }
    return diagnostic;
  }
  function addDeprecatedSuggestionWorker(declarations, diagnostic) {
    const deprecatedTag = Array.isArray(declarations) ? forEach(declarations, getJSDocDeprecatedTag) : getJSDocDeprecatedTag(declarations);
    if (deprecatedTag) {
      addRelatedInfo(
        diagnostic,
        createDiagnosticForNode(deprecatedTag, Diagnostics.The_declaration_was_marked_as_deprecated_here)
      );
    }
    suggestionDiagnostics.add(diagnostic);
    return diagnostic;
  }
  function isDeprecatedSymbol(symbol) {
    const parentSymbol = getParentOfSymbol(symbol);
    if (parentSymbol && length(symbol.declarations) > 1) {
      return parentSymbol.flags & SymbolFlags.Interface ? some(symbol.declarations, isDeprecatedDeclaration) : every(symbol.declarations, isDeprecatedDeclaration);
    }
    return !!symbol.valueDeclaration && isDeprecatedDeclaration(symbol.valueDeclaration) || length(symbol.declarations) && every(symbol.declarations, isDeprecatedDeclaration);
  }
  function isDeprecatedDeclaration(declaration) {
    return !!(getCombinedNodeFlagsCached(declaration) & NodeFlags.Deprecated);
  }
  function addDeprecatedSuggestion(location, declarations, deprecatedEntity) {
    const diagnostic = createDiagnosticForNode(location, Diagnostics._0_is_deprecated, deprecatedEntity);
    return addDeprecatedSuggestionWorker(declarations, diagnostic);
  }
  function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) {
    const diagnostic = deprecatedEntity ? createDiagnosticForNode(location, Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) : createDiagnosticForNode(location, Diagnostics._0_is_deprecated, signatureString);
    return addDeprecatedSuggestionWorker(declaration, diagnostic);
  }
  function createSymbol(flags, name, checkFlags) {
    symbolCount++;
    const symbol = new Symbol2(flags | SymbolFlags.Transient, name);
    symbol.links = new SymbolLinks();
    symbol.links.checkFlags = checkFlags || CheckFlags.None;
    return symbol;
  }
  function createParameter(name, type) {
    const symbol = createSymbol(SymbolFlags.FunctionScopedVariable, name);
    symbol.links.type = type;
    return symbol;
  }
  function createProperty(name, type) {
    const symbol = createSymbol(SymbolFlags.Property, name);
    symbol.links.type = type;
    return symbol;
  }
  function getExcludedSymbolFlags(flags) {
    let result = 0;
    if (flags & SymbolFlags.BlockScopedVariable) result |= SymbolFlags.BlockScopedVariableExcludes;
    if (flags & SymbolFlags.FunctionScopedVariable) result |= SymbolFlags.FunctionScopedVariableExcludes;
    if (flags & SymbolFlags.Property) result |= SymbolFlags.PropertyExcludes;
    if (flags & SymbolFlags.EnumMember) result |= SymbolFlags.EnumMemberExcludes;
    if (flags & SymbolFlags.Function) result |= SymbolFlags.FunctionExcludes;
    if (flags & SymbolFlags.Class) result |= SymbolFlags.ClassExcludes;
    if (flags & SymbolFlags.Interface) result |= SymbolFlags.InterfaceExcludes;
    if (flags & SymbolFlags.RegularEnum) result |= SymbolFlags.RegularEnumExcludes;
    if (flags & SymbolFlags.ConstEnum) result |= SymbolFlags.ConstEnumExcludes;
    if (flags & SymbolFlags.ValueModule) result |= SymbolFlags.ValueModuleExcludes;
    if (flags & SymbolFlags.Method) result |= SymbolFlags.MethodExcludes;
    if (flags & SymbolFlags.GetAccessor) result |= SymbolFlags.GetAccessorExcludes;
    if (flags & SymbolFlags.SetAccessor) result |= SymbolFlags.SetAccessorExcludes;
    if (flags & SymbolFlags.TypeParameter) result |= SymbolFlags.TypeParameterExcludes;
    if (flags & SymbolFlags.TypeAlias) result |= SymbolFlags.TypeAliasExcludes;
    if (flags & SymbolFlags.Alias) result |= SymbolFlags.AliasExcludes;
    return result;
  }
  function recordMergedSymbol(target, source) {
    if (!source.mergeId) {
      source.mergeId = nextMergeId;
      nextMergeId++;
    }
    mergedSymbols[source.mergeId] = target;
  }
  function cloneSymbol(symbol) {
    const result = createSymbol(symbol.flags, symbol.escapedName);
    result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
    result.parent = symbol.parent;
    if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration;
    if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true;
    if (symbol.members) result.members = new Map(symbol.members);
    if (symbol.exports) result.exports = new Map(symbol.exports);
    recordMergedSymbol(result, symbol);
    return result;
  }
  function mergeSymbol(target, source, unidirectional = false) {
    if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & SymbolFlags.Assignment) {
      if (source === target) {
        return target;
      }
      if (!(target.flags & SymbolFlags.Transient)) {
        const resolvedTarget = resolveSymbol(target);
        if (resolvedTarget === unknownSymbol) {
          return source;
        }
        if (!(resolvedTarget.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | resolvedTarget.flags) & SymbolFlags.Assignment) {
          target = cloneSymbol(resolvedTarget);
        } else {
          reportMergeSymbolError(target, source);
          return source;
        }
      }
      if (source.flags & SymbolFlags.ValueModule && target.flags & SymbolFlags.ValueModule && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
        target.constEnumOnlyModule = false;
      }
      target.flags |= source.flags;
      if (source.valueDeclaration) {
        setValueDeclaration(target, source.valueDeclaration);
      }
      addRange(target.declarations, source.declarations);
      if (source.members) {
        if (!target.members) target.members = createSymbolTable();
        mergeSymbolTable(target.members, source.members, unidirectional);
      }
      if (source.exports) {
        if (!target.exports) target.exports = createSymbolTable();
        mergeSymbolTable(target.exports, source.exports, unidirectional, target);
      }
      if (!unidirectional) {
        recordMergedSymbol(target, source);
      }
    } else if (target.flags & SymbolFlags.NamespaceModule) {
      if (target !== globalThisSymbol) {
        error(
          source.declarations && getNameOfDeclaration(source.declarations[0]),
          Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity,
          symbolToString(target)
        );
      }
    } else {
      reportMergeSymbolError(target, source);
    }
    return target;
    function reportMergeSymbolError(target2, source2) {
      const isEitherEnum = !!(target2.flags & SymbolFlags.Enum || source2.flags & SymbolFlags.Enum);
      const isEitherBlockScoped = !!(target2.flags & SymbolFlags.BlockScopedVariable || source2.flags & SymbolFlags.BlockScopedVariable);
      const message = isEitherEnum ? Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations : isEitherBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0;
      const sourceSymbolFile = source2.declarations && getSourceFileOfNode(source2.declarations[0]);
      const targetSymbolFile = target2.declarations && getSourceFileOfNode(target2.declarations[0]);
      const isSourcePlainJs = isPlainJsFile(sourceSymbolFile, compilerOptions.checkJs);
      const isTargetPlainJs = isPlainJsFile(targetSymbolFile, compilerOptions.checkJs);
      const symbolName2 = symbolToString(source2);
      if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
        const firstFile = comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === Comparison.LessThan ? sourceSymbolFile : targetSymbolFile;
        const secondFile = firstFile === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
        const filesDuplicates = getOrUpdate(amalgamatedDuplicates, `${firstFile.path}|${secondFile.path}`, () => ({ firstFile, secondFile, conflictingSymbols: /* @__PURE__ */ new Map() }));
        const conflictingSymbolInfo = getOrUpdate(filesDuplicates.conflictingSymbols, symbolName2, () => ({ isBlockScoped: isEitherBlockScoped, firstFileLocations: [], secondFileLocations: [] }));
        if (!isSourcePlainJs) addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source2);
        if (!isTargetPlainJs) addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target2);
      } else {
        if (!isSourcePlainJs) addDuplicateDeclarationErrorsForSymbols(source2, message, symbolName2, target2);
        if (!isTargetPlainJs) addDuplicateDeclarationErrorsForSymbols(target2, message, symbolName2, source2);
      }
    }
    function addDuplicateLocations(locs, symbol) {
      if (symbol.declarations) {
        for (const decl of symbol.declarations) {
          pushIfUnique(locs, decl);
        }
      }
    }
  }
  function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName2, source) {
    forEach(target.declarations, (node) => {
      addDuplicateDeclarationError(node, message, symbolName2, source.declarations);
    });
  }
  function addDuplicateDeclarationError(node, message, symbolName2, relatedNodes) {
    const errorNode = (getExpandoInitializer(
      node,
      /*isPrototypeAssignment*/
      false
    ) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node;
    const err = lookupOrIssueError(errorNode, message, symbolName2);
    for (const relatedNode of relatedNodes || emptyArray) {
      const adjustedNode = (getExpandoInitializer(
        relatedNode,
        /*isPrototypeAssignment*/
        false
      ) ? getNameOfExpando(relatedNode) : getNameOfDeclaration(relatedNode)) || relatedNode;
      if (adjustedNode === errorNode) continue;
      err.relatedInformation = err.relatedInformation || [];
      const leadingMessage = createDiagnosticForNode(adjustedNode, Diagnostics._0_was_also_declared_here, symbolName2);
      const followOnMessage = createDiagnosticForNode(adjustedNode, Diagnostics.and_here);
      if (length(err.relatedInformation) >= 5 || some(err.relatedInformation, (r) => compareDiagnostics(r, followOnMessage) === Comparison.EqualTo || compareDiagnostics(r, leadingMessage) === Comparison.EqualTo)) continue;
      addRelatedInfo(err, !length(err.relatedInformation) ? leadingMessage : followOnMessage);
    }
  }
  function combineSymbolTables(first2, second) {
    if (!first2?.size) return second;
    if (!second?.size) return first2;
    const combined = createSymbolTable();
    mergeSymbolTable(combined, first2);
    mergeSymbolTable(combined, second);
    return combined;
  }
  function mergeSymbolTable(target, source, unidirectional = false, mergedParent) {
    source.forEach((sourceSymbol, id) => {
      const targetSymbol = target.get(id);
      const merged = targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : getMergedSymbol(sourceSymbol);
      if (mergedParent && targetSymbol) {
        merged.parent = mergedParent;
      }
      target.set(id, merged);
    });
  }
  function mergeModuleAugmentation(moduleName) {
    const moduleAugmentation = moduleName.parent;
    if (moduleAugmentation.symbol.declarations?.[0] !== moduleAugmentation) {
      Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
      return;
    }
    if (isGlobalScopeAugmentation(moduleAugmentation)) {
      mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
    } else {
      const moduleNotFoundError = !(moduleName.parent.parent.flags & NodeFlags.Ambient) ? Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : void 0;
      let mainModule = resolveExternalModuleNameWorker(
        moduleName,
        moduleName,
        moduleNotFoundError,
        /*ignoreErrors*/
        false,
        /*isForAugmentation*/
        true
      );
      if (!mainModule) {
        return;
      }
      mainModule = resolveExternalModuleSymbol(mainModule);
      if (mainModule.flags & SymbolFlags.Namespace) {
        if (some(patternAmbientModules, (module) => mainModule === module.symbol)) {
          const merged = mergeSymbol(
            moduleAugmentation.symbol,
            mainModule,
            /*unidirectional*/
            true
          );
          if (!patternAmbientModuleAugmentations) {
            patternAmbientModuleAugmentations = /* @__PURE__ */ new Map();
          }
          patternAmbientModuleAugmentations.set(moduleName.text, merged);
        } else {
          if (mainModule.exports?.get(InternalSymbolName.ExportStar) && moduleAugmentation.symbol.exports?.size) {
            const resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule, "resolvedExports" /* resolvedExports */);
            for (const [key, value] of arrayFrom(moduleAugmentation.symbol.exports.entries())) {
              if (resolvedExports.has(key) && !mainModule.exports.has(key)) {
                mergeSymbol(resolvedExports.get(key), value);
              }
            }
          }
          mergeSymbol(mainModule, moduleAugmentation.symbol);
        }
      } else {
        error(moduleName, Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
      }
    }
  }
  function addUndefinedToGlobalsOrErrorOnRedeclaration() {
    const name = undefinedSymbol.escapedName;
    const targetSymbol = globals.get(name);
    if (targetSymbol) {
      forEach(targetSymbol.declarations, (declaration) => {
        if (!isTypeDeclaration(declaration)) {
          diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, unescapeLeadingUnderscores(name)));
        }
      });
    } else {
      globals.set(name, undefinedSymbol);
    }
  }
  function getSymbolLinks(symbol) {
    if (symbol.flags & SymbolFlags.Transient) return symbol.links;
    const id = getSymbolId(symbol);
    return symbolLinks[id] ??= new SymbolLinks();
  }
  function getNodeLinks(node) {
    const nodeId = getNodeId(node);
    return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
  }
  function getSymbol(symbols, name, meaning) {
    if (meaning) {
      const symbol = getMergedSymbol(symbols.get(name));
      if (symbol) {
        if (symbol.flags & meaning) {
          return symbol;
        }
        if (symbol.flags & SymbolFlags.Alias) {
          const targetFlags = getSymbolFlags(symbol);
          if (targetFlags & meaning) {
            return symbol;
          }
        }
      }
    }
  }
  function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
    const constructorDeclaration = parameter.parent;
    const classDeclaration = parameter.parent.parent;
    const parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, SymbolFlags.Value);
    const propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, SymbolFlags.Value);
    if (parameterSymbol && propertySymbol) {
      return [parameterSymbol, propertySymbol];
    }
    return Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
  }
  function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
    const declarationFile = getSourceFileOfNode(declaration);
    const useFile = getSourceFileOfNode(usage);
    const declContainer = getEnclosingBlockScopeContainer(declaration);
    if (declarationFile !== useFile) {
      if (moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator) || !compilerOptions.outFile || isInTypeQuery(usage) || declaration.flags & NodeFlags.Ambient) {
        return true;
      }
      if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
        return true;
      }
      const sourceFiles = host.getSourceFiles();
      return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
    }
    if (!!(usage.flags & NodeFlags.JSDoc) || isInTypeQuery(usage) || isInAmbientOrTypeNode(usage)) {
      return true;
    }
    if (declaration.pos <= usage.pos && !(isPropertyDeclaration(declaration) && isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) {
      if (declaration.kind === SyntaxKind.BindingElement) {
        const errorBindingElement = getAncestor(usage, SyntaxKind.BindingElement);
        if (errorBindingElement) {
          return findAncestor(errorBindingElement, isBindingElement) !== findAncestor(declaration, isBindingElement) || declaration.pos < errorBindingElement.pos;
        }
        return isBlockScopedNameDeclaredBeforeUse(getAncestor(declaration, SyntaxKind.VariableDeclaration), usage);
      } else if (declaration.kind === SyntaxKind.VariableDeclaration) {
        return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
      } else if (isClassLike(declaration)) {
        const container = findAncestor(usage, (n) => n === declaration ? "quit" : isComputedPropertyName(n) ? n.parent.parent === declaration : !legacyDecorators && isDecorator(n) && (n.parent === declaration || isMethodDeclaration(n.parent) && n.parent.parent === declaration || isGetOrSetAccessorDeclaration(n.parent) && n.parent.parent === declaration || isPropertyDeclaration(n.parent) && n.parent.parent === declaration || isParameter(n.parent) && n.parent.parent.parent === declaration));
        if (!container) {
          return true;
        }
        if (!legacyDecorators && isDecorator(container)) {
          return !!findAncestor(usage, (n) => n === container ? "quit" : isFunctionLike(n) && !getImmediatelyInvokedFunctionExpression(n));
        }
        return false;
      } else if (isPropertyDeclaration(declaration)) {
        return !isPropertyImmediatelyReferencedWithinDeclaration(
          declaration,
          usage,
          /*stopAtAnyPropertyDeclaration*/
          false
        );
      } else if (isParameterPropertyDeclaration(declaration, declaration.parent)) {
        return !(emitStandardClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration));
      }
      return true;
    }
    if (usage.parent.kind === SyntaxKind.ExportSpecifier || usage.parent.kind === SyntaxKind.ExportAssignment && usage.parent.isExportEquals) {
      return true;
    }
    if (usage.kind === SyntaxKind.ExportAssignment && usage.isExportEquals) {
      return true;
    }
    if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
      if (emitStandardClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) {
        return !isPropertyImmediatelyReferencedWithinDeclaration(
          declaration,
          usage,
          /*stopAtAnyPropertyDeclaration*/
          true
        );
      } else {
        return true;
      }
    }
    return false;
    function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration2, usage2) {
      switch (declaration2.parent.parent.kind) {
        case SyntaxKind.VariableStatement:
        case SyntaxKind.ForStatement:
        case SyntaxKind.ForOfStatement:
          if (isSameScopeDescendentOf(usage2, declaration2, declContainer)) {
            return true;
          }
          break;
      }
      const grandparent = declaration2.parent.parent;
      return isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage2, grandparent.expression, declContainer);
    }
    function isUsedInFunctionOrInstanceProperty(usage2, declaration2) {
      return !!findAncestor(usage2, (current) => {
        if (current === declContainer) {
          return "quit";
        }
        if (isFunctionLike(current)) {
          return true;
        }
        if (isClassStaticBlockDeclaration(current)) {
          return declaration2.pos < usage2.pos;
        }
        const propertyDeclaration = tryCast(current.parent, isPropertyDeclaration);
        if (propertyDeclaration) {
          const initializerOfProperty = propertyDeclaration.initializer === current;
          if (initializerOfProperty) {
            if (isStatic(current.parent)) {
              if (declaration2.kind === SyntaxKind.MethodDeclaration) {
                return true;
              }
              if (isPropertyDeclaration(declaration2) && getContainingClass(usage2) === getContainingClass(declaration2)) {
                const propName = declaration2.name;
                if (isIdentifier(propName) || isPrivateIdentifier(propName)) {
                  const type = getTypeOfSymbol(getSymbolOfDeclaration(declaration2));
                  const staticBlocks = filter(declaration2.parent.members, isClassStaticBlockDeclaration);
                  if (isPropertyInitializedInStaticBlocks(propName, type, staticBlocks, declaration2.parent.pos, current.pos)) {
                    return true;
                  }
                }
              }
            } else {
              const isDeclarationInstanceProperty = declaration2.kind === SyntaxKind.PropertyDeclaration && !isStatic(declaration2);
              if (!isDeclarationInstanceProperty || getContainingClass(usage2) !== getContainingClass(declaration2)) {
                return true;
              }
            }
          }
        }
        return false;
      });
    }
    function isPropertyImmediatelyReferencedWithinDeclaration(declaration2, usage2, stopAtAnyPropertyDeclaration) {
      if (usage2.end > declaration2.end) {
        return false;
      }
      const ancestorChangingReferenceScope = findAncestor(usage2, (node) => {
        if (node === declaration2) {
          return "quit";
        }
        switch (node.kind) {
          case SyntaxKind.ArrowFunction:
            return true;
          case SyntaxKind.PropertyDeclaration:
            return stopAtAnyPropertyDeclaration && (isPropertyDeclaration(declaration2) && node.parent === declaration2.parent || isParameterPropertyDeclaration(declaration2, declaration2.parent) && node.parent === declaration2.parent.parent) ? "quit" : true;
          case SyntaxKind.Block:
            switch (node.parent.kind) {
              case SyntaxKind.GetAccessor:
              case SyntaxKind.MethodDeclaration:
              case SyntaxKind.SetAccessor:
                return true;
              default:
                return false;
            }
          default:
            return false;
        }
      });
      return ancestorChangingReferenceScope === void 0;
    }
  }
  function getRequiresScopeChangeCache(node) {
    return getNodeLinks(node).declarationRequiresScopeChange;
  }
  function setRequiresScopeChangeCache(node, value) {
    getNodeLinks(node).declarationRequiresScopeChange = value;
  }
  function checkAndReportErrorForInvalidInitializer(errorLocation, name, propertyWithInvalidInitializer, result) {
    if (!emitStandardClassFields) {
      if (errorLocation && !result && checkAndReportErrorForMissingPrefix(errorLocation, name, name)) {
        return true;
      }
      error(
        errorLocation,
        errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor,
        declarationNameToString(propertyWithInvalidInitializer.name),
        diagnosticName(name)
      );
      return true;
    }
    return false;
  }
  function onFailedToResolveSymbol(errorLocation, nameArg, meaning, nameNotFoundMessage) {
    const name = isString(nameArg) ? nameArg : nameArg.escapedText;
    addLazyDiagnostic(() => {
      if (!errorLocation || errorLocation.parent.kind !== SyntaxKind.JSDocLink && !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
        let suggestion;
        let suggestedLib;
        if (nameArg) {
          suggestedLib = getSuggestedLibForNonExistentName(nameArg);
          if (suggestedLib) {
            error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib);
          }
        }
        if (!suggestedLib && suggestionCount < maximumSuggestionCount) {
          suggestion = getSuggestedSymbolForNonexistentSymbol(errorLocation, name, meaning);
          const isGlobalScopeAugmentationDeclaration = suggestion?.valueDeclaration && isAmbientModule(suggestion.valueDeclaration) && isGlobalScopeAugmentation(suggestion.valueDeclaration);
          if (isGlobalScopeAugmentationDeclaration) {
            suggestion = void 0;
          }
          if (suggestion) {
            const suggestionName = symbolToString(suggestion);
            const isUncheckedJS = isUncheckedJSSuggestion(
              errorLocation,
              suggestion,
              /*excludeClasses*/
              false
            );
            const message = meaning === SymbolFlags.Namespace || nameArg && typeof nameArg !== "string" && nodeIsSynthesized(nameArg) ? Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 : isUncheckedJS ? Diagnostics.Could_not_find_name_0_Did_you_mean_1 : Diagnostics.Cannot_find_name_0_Did_you_mean_1;
            const diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName);
            diagnostic.canonicalHead = getCanonicalDiagnostic(nameNotFoundMessage, diagnosticName(nameArg));
            addErrorOrSuggestion(!isUncheckedJS, diagnostic);
            if (suggestion.valueDeclaration) {
              addRelatedInfo(
                diagnostic,
                createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName)
              );
            }
          }
        }
        if (!suggestion && !suggestedLib && nameArg) {
          error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
        }
        suggestionCount++;
      }
    });
  }
  function onSuccessfullyResolvedSymbol(errorLocation, result, meaning, lastLocation, associatedDeclarationForContainingInitializerOrBindingName, withinDeferredContext) {
    addLazyDiagnostic(() => {
      const name = result.escapedName;
      const isInExternalModule = lastLocation && isSourceFile(lastLocation) && isExternalOrCommonJsModule(lastLocation);
      if (errorLocation && (meaning & SymbolFlags.BlockScopedVariable || (meaning & SymbolFlags.Class || meaning & SymbolFlags.Enum) && (meaning & SymbolFlags.Value) === SymbolFlags.Value)) {
        const exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
        if (exportOrLocalSymbol.flags & SymbolFlags.BlockScopedVariable || exportOrLocalSymbol.flags & SymbolFlags.Class || exportOrLocalSymbol.flags & SymbolFlags.Enum) {
          checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
        }
      }
      if (isInExternalModule && (meaning & SymbolFlags.Value) === SymbolFlags.Value && !(errorLocation.flags & NodeFlags.JSDoc)) {
        const merged = getMergedSymbol(result);
        if (length(merged.declarations) && every(merged.declarations, (d) => isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) {
          errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name));
        }
      }
      if (associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & SymbolFlags.Value) === SymbolFlags.Value) {
        const candidate = getMergedSymbol(getLateBoundSymbol(result));
        const root = getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
        if (candidate === getSymbolOfDeclaration(associatedDeclarationForContainingInitializerOrBindingName)) {
          error(errorLocation, Diagnostics.Parameter_0_cannot_reference_itself, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
        } else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && getSymbol(root.parent.locals, candidate.escapedName, meaning) === candidate) {
          error(errorLocation, Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), declarationNameToString(errorLocation));
        }
      }
      if (errorLocation && meaning & SymbolFlags.Value && result.flags & SymbolFlags.Alias && !(result.flags & SymbolFlags.Value) && !isValidTypeOnlyAliasUseSite(errorLocation)) {
        const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, SymbolFlags.Value);
        if (typeOnlyDeclaration) {
          const message = typeOnlyDeclaration.kind === SyntaxKind.ExportSpecifier || typeOnlyDeclaration.kind === SyntaxKind.ExportDeclaration || typeOnlyDeclaration.kind === SyntaxKind.NamespaceExport ? Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type : Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
          const unescapedName = unescapeLeadingUnderscores(name);
          addTypeOnlyDeclarationRelatedInfo(
            error(errorLocation, message, unescapedName),
            typeOnlyDeclaration,
            unescapedName
          );
        }
      }
      if (compilerOptions.isolatedModules && result && isInExternalModule && (meaning & SymbolFlags.Value) === SymbolFlags.Value) {
        const isGlobal = getSymbol(globals, name, meaning) === result;
        const nonValueSymbol = isGlobal && isSourceFile(lastLocation) && lastLocation.locals && getSymbol(lastLocation.locals, name, ~SymbolFlags.Value);
        if (nonValueSymbol) {
          const importDecl = nonValueSymbol.declarations?.find((d) => d.kind === SyntaxKind.ImportSpecifier || d.kind === SyntaxKind.ImportClause || d.kind === SyntaxKind.NamespaceImport || d.kind === SyntaxKind.ImportEqualsDeclaration);
          if (importDecl && !isTypeOnlyImportDeclaration(importDecl)) {
            error(importDecl, Diagnostics.Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_when_isolatedModules_is_enabled, unescapeLeadingUnderscores(name));
          }
        }
      }
    });
  }
  function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) {
    if (!typeOnlyDeclaration) return diagnostic;
    return addRelatedInfo(
      diagnostic,
      createDiagnosticForNode(
        typeOnlyDeclaration,
        typeOnlyDeclaration.kind === SyntaxKind.ExportSpecifier || typeOnlyDeclaration.kind === SyntaxKind.ExportDeclaration || typeOnlyDeclaration.kind === SyntaxKind.NamespaceExport ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here,
        unescapedName
      )
    );
  }
  function diagnosticName(nameArg) {
    return isString(nameArg) ? unescapeLeadingUnderscores(nameArg) : declarationNameToString(nameArg);
  }
  function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
    if (!isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
      return false;
    }
    const container = getThisContainer(
      errorLocation,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    let location = container;
    while (location) {
      if (isClassLike(location.parent)) {
        const classSymbol = getSymbolOfDeclaration(location.parent);
        if (!classSymbol) {
          break;
        }
        const constructorType = getTypeOfSymbol(classSymbol);
        if (getPropertyOfType(constructorType, name)) {
          error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
          return true;
        }
        if (location === container && !isStatic(location)) {
          const instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType;
          if (getPropertyOfType(instanceType, name)) {
            error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
            return true;
          }
        }
      }
      location = location.parent;
    }
    return false;
  }
  function checkAndReportErrorForExtendingInterface(errorLocation) {
    const expression = getEntityNameForExtendingInterface(errorLocation);
    if (expression && resolveEntityName(
      expression,
      SymbolFlags.Interface,
      /*ignoreErrors*/
      true
    )) {
      error(errorLocation, Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, getTextOfNode(expression));
      return true;
    }
    return false;
  }
  function getEntityNameForExtendingInterface(node) {
    switch (node.kind) {
      case SyntaxKind.Identifier:
      case SyntaxKind.PropertyAccessExpression:
        return node.parent ? getEntityNameForExtendingInterface(node.parent) : void 0;
      case SyntaxKind.ExpressionWithTypeArguments:
        if (isEntityNameExpression(node.expression)) {
          return node.expression;
        }
      // falls through
      default:
        return void 0;
    }
  }
  function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
    const namespaceMeaning = SymbolFlags.Namespace | (isInJSFile(errorLocation) ? SymbolFlags.Value : 0);
    if (meaning === namespaceMeaning) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        SymbolFlags.Type & ~namespaceMeaning,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      const parent = errorLocation.parent;
      if (symbol) {
        if (isQualifiedName(parent)) {
          Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
          const propName = parent.right.escapedText;
          const propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
          if (propType) {
            error(
              parent,
              Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1,
              unescapeLeadingUnderscores(name),
              unescapeLeadingUnderscores(propName)
            );
            return true;
          }
        }
        error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, unescapeLeadingUnderscores(name));
        return true;
      }
    }
    return false;
  }
  function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
    if (meaning & (SymbolFlags.Type & ~SymbolFlags.Namespace)) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        ~SymbolFlags.Type & SymbolFlags.Value,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      if (symbol && !(symbol.flags & SymbolFlags.Namespace)) {
        error(errorLocation, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, unescapeLeadingUnderscores(name));
        return true;
      }
    }
    return false;
  }
  function isPrimitiveTypeName(name) {
    return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
  }
  function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
    if (isPrimitiveTypeName(name) && errorLocation.parent.kind === SyntaxKind.ExportSpecifier) {
      error(errorLocation, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
      return true;
    }
    return false;
  }
  function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
    if (meaning & SymbolFlags.Value) {
      if (isPrimitiveTypeName(name)) {
        const grandparent = errorLocation.parent.parent;
        if (grandparent && grandparent.parent && isHeritageClause(grandparent)) {
          const heritageKind = grandparent.token;
          const containerKind = grandparent.parent.kind;
          if (containerKind === SyntaxKind.InterfaceDeclaration && heritageKind === SyntaxKind.ExtendsKeyword) {
            error(errorLocation, Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types, unescapeLeadingUnderscores(name));
          } else if (containerKind === SyntaxKind.ClassDeclaration && heritageKind === SyntaxKind.ExtendsKeyword) {
            error(errorLocation, Diagnostics.A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values, unescapeLeadingUnderscores(name));
          } else if (containerKind === SyntaxKind.ClassDeclaration && heritageKind === SyntaxKind.ImplementsKeyword) {
            error(errorLocation, Diagnostics.A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types, unescapeLeadingUnderscores(name));
          }
        } else {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, unescapeLeadingUnderscores(name));
        }
        return true;
      }
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        SymbolFlags.Type & ~SymbolFlags.Value,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      const allFlags = symbol && getSymbolFlags(symbol);
      if (symbol && allFlags !== void 0 && !(allFlags & SymbolFlags.Value)) {
        const rawName = unescapeLeadingUnderscores(name);
        if (isES2015OrLaterConstructorName(name)) {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName);
        } else if (maybeMappedType(errorLocation, symbol)) {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0, rawName, rawName === "K" ? "P" : "K");
        } else {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, rawName);
        }
        return true;
      }
    }
    return false;
  }
  function maybeMappedType(node, symbol) {
    const container = findAncestor(node.parent, (n) => isComputedPropertyName(n) || isPropertySignature(n) ? false : isTypeLiteralNode(n) || "quit");
    if (container && container.members.length === 1) {
      const type = getDeclaredTypeOfSymbol(symbol);
      return !!(type.flags & TypeFlags.Union) && allTypesAssignableToKind(
        type,
        TypeFlags.StringOrNumberLiteral,
        /*strict*/
        true
      );
    }
    return false;
  }
  function isES2015OrLaterConstructorName(n) {
    switch (n) {
      case "Promise":
      case "Symbol":
      case "Map":
      case "WeakMap":
      case "Set":
      case "WeakSet":
        return true;
    }
    return false;
  }
  function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) {
    if (meaning & (SymbolFlags.Value & ~SymbolFlags.Type)) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        SymbolFlags.NamespaceModule,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      if (symbol) {
        error(
          errorLocation,
          Diagnostics.Cannot_use_namespace_0_as_a_value,
          unescapeLeadingUnderscores(name)
        );
        return true;
      }
    } else if (meaning & (SymbolFlags.Type & ~SymbolFlags.Value)) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        SymbolFlags.Module,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      if (symbol) {
        error(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_type, unescapeLeadingUnderscores(name));
        return true;
      }
    }
    return false;
  }
  function checkResolvedBlockScopedVariable(result, errorLocation) {
    Debug.assert(!!(result.flags & SymbolFlags.BlockScopedVariable || result.flags & SymbolFlags.Class || result.flags & SymbolFlags.Enum));
    if (result.flags & (SymbolFlags.Function | SymbolFlags.FunctionScopedVariable | SymbolFlags.Assignment) && result.flags & SymbolFlags.Class) {
      return;
    }
    const declaration = result.declarations?.find(
      (d) => isBlockOrCatchScoped(d) || isClassLike(d) || d.kind === SyntaxKind.EnumDeclaration
    );
    if (declaration === void 0) return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
    if (!(declaration.flags & NodeFlags.Ambient) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
      let diagnosticMessage;
      const declarationName = declarationNameToString(getNameOfDeclaration(declaration));
      if (result.flags & SymbolFlags.BlockScopedVariable) {
        diagnosticMessage = error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
      } else if (result.flags & SymbolFlags.Class) {
        diagnosticMessage = error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationName);
      } else if (result.flags & SymbolFlags.RegularEnum) {
        diagnosticMessage = error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName);
      } else {
        Debug.assert(!!(result.flags & SymbolFlags.ConstEnum));
        if (getIsolatedModules(compilerOptions)) {
          diagnosticMessage = error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName);
        }
      }
      if (diagnosticMessage) {
        addRelatedInfo(diagnosticMessage, createDiagnosticForNode(declaration, Diagnostics._0_is_declared_here, declarationName));
      }
    }
  }
  function isSameScopeDescendentOf(initial, parent, stopAt) {
    return !!parent && !!findAncestor(initial, (n) => n === parent || (n === stopAt || isFunctionLike(n) && (!getImmediatelyInvokedFunctionExpression(n) || getFunctionFlags(n) & FunctionFlags.AsyncGenerator) ? "quit" : false));
  }
  function getAnyImportSyntax(node) {
    switch (node.kind) {
      case SyntaxKind.ImportEqualsDeclaration:
        return node;
      case SyntaxKind.ImportClause:
        return node.parent;
      case SyntaxKind.NamespaceImport:
        return node.parent.parent;
      case SyntaxKind.ImportSpecifier:
        return node.parent.parent.parent;
      default:
        return void 0;
    }
  }
  function getDeclarationOfAliasSymbol(symbol) {
    return symbol.declarations && findLast(symbol.declarations, isAliasSymbolDeclaration);
  }
  function isAliasSymbolDeclaration(node) {
    return node.kind === SyntaxKind.ImportEqualsDeclaration || node.kind === SyntaxKind.NamespaceExportDeclaration || node.kind === SyntaxKind.ImportClause && !!node.name || node.kind === SyntaxKind.NamespaceImport || node.kind === SyntaxKind.NamespaceExport || node.kind === SyntaxKind.ImportSpecifier || node.kind === SyntaxKind.ExportSpecifier || node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) || isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports && exportAssignmentIsAlias(node) || isAccessExpression(node) && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === SyntaxKind.EqualsToken && isAliasableOrJsExpression(node.parent.right) || node.kind === SyntaxKind.ShorthandPropertyAssignment || node.kind === SyntaxKind.PropertyAssignment && isAliasableOrJsExpression(node.initializer) || node.kind === SyntaxKind.VariableDeclaration && isVariableDeclarationInitializedToBareOrAccessedRequire(node) || node.kind === SyntaxKind.BindingElement && isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent);
  }
  function isAliasableOrJsExpression(e) {
    return isAliasableExpression(e) || isFunctionExpression(e) && isJSConstructor(e);
  }
  function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
    const commonJSPropertyAccess = getCommonJSPropertyAccess(node);
    if (commonJSPropertyAccess) {
      const name = getLeftmostAccessExpression(commonJSPropertyAccess.expression).arguments[0];
      return isIdentifier(commonJSPropertyAccess.name) ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : void 0;
    }
    if (isVariableDeclaration(node) || node.moduleReference.kind === SyntaxKind.ExternalModuleReference) {
      const immediate = resolveExternalModuleName(
        node,
        getExternalModuleRequireArgument(node) || getExternalModuleImportEqualsDeclarationExpression(node)
      );
      const resolved2 = resolveExternalModuleSymbol(immediate);
      markSymbolOfAliasDeclarationIfTypeOnly(
        node,
        immediate,
        resolved2,
        /*overwriteEmpty*/
        false
      );
      return resolved2;
    }
    const resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
    checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
    return resolved;
  }
  function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
    if (markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    ) && !node.isTypeOnly) {
      const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfDeclaration(node));
      const isExport = typeOnlyDeclaration.kind === SyntaxKind.ExportSpecifier || typeOnlyDeclaration.kind === SyntaxKind.ExportDeclaration;
      const message = isExport ? Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type : Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
      const relatedMessage = isExport ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here;
      const name = typeOnlyDeclaration.kind === SyntaxKind.ExportDeclaration ? "*" : moduleExportNameTextUnescaped(typeOnlyDeclaration.name);
      addRelatedInfo(error(node.moduleReference, message), createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
    }
  }
  function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
    const exportValue = moduleSymbol.exports.get(InternalSymbolName.ExportEquals);
    const exportSymbol = exportValue ? getPropertyOfType(
      getTypeOfSymbol(exportValue),
      name,
      /*skipObjectFunctionPropertyAugment*/
      true
    ) : moduleSymbol.exports.get(name);
    const resolved = resolveSymbol(exportSymbol, dontResolveAlias);
    markSymbolOfAliasDeclarationIfTypeOnly(
      sourceNode,
      exportSymbol,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function isSyntacticDefault(node) {
    return isExportAssignment(node) && !node.isExportEquals || hasSyntacticModifier(node, ModifierFlags.Default) || isExportSpecifier(node) || isNamespaceExport(node);
  }
  function getEmitSyntaxForModuleSpecifierExpression(usage) {
    return isStringLiteralLike(usage) ? host.getEmitSyntaxForUsageLocation(getSourceFileOfNode(usage), usage) : void 0;
  }
  function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) {
    return usageMode === ModuleKind.ESNext && targetMode === ModuleKind.CommonJS;
  }
  function isOnlyImportableAsDefault(usage) {
    if (ModuleKind.Node16 <= moduleKind && moduleKind <= ModuleKind.NodeNext) {
      const usageMode = getEmitSyntaxForModuleSpecifierExpression(usage);
      return usageMode === ModuleKind.ESNext && endsWith(usage.text, Extension.Json);
    }
    return false;
  }
  function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) {
    const usageMode = file && getEmitSyntaxForModuleSpecifierExpression(usage);
    if (file && usageMode !== void 0) {
      const targetMode = host.getImpliedNodeFormatForEmit(file);
      if (usageMode === ModuleKind.ESNext && targetMode === ModuleKind.CommonJS && ModuleKind.Node16 <= moduleKind && moduleKind <= ModuleKind.NodeNext) {
        return true;
      }
      if (usageMode === ModuleKind.ESNext && targetMode === ModuleKind.ESNext) {
        return false;
      }
    }
    if (!allowSyntheticDefaultImports) {
      return false;
    }
    if (!file || file.isDeclarationFile) {
      const defaultExportSymbol = resolveExportByName(
        moduleSymbol,
        InternalSymbolName.Default,
        /*sourceNode*/
        void 0,
        /*dontResolveAlias*/
        true
      );
      if (defaultExportSymbol && some(defaultExportSymbol.declarations, isSyntacticDefault)) {
        return false;
      }
      if (resolveExportByName(
        moduleSymbol,
        escapeLeadingUnderscores("__esModule"),
        /*sourceNode*/
        void 0,
        dontResolveAlias
      )) {
        return false;
      }
      return true;
    }
    if (!isSourceFileJS(file)) {
      return hasExportAssignmentSymbol(moduleSymbol);
    }
    return typeof file.externalModuleIndicator !== "object" && !resolveExportByName(
      moduleSymbol,
      escapeLeadingUnderscores("__esModule"),
      /*sourceNode*/
      void 0,
      dontResolveAlias
    );
  }
  function getTargetOfImportClause(node, dontResolveAlias) {
    const moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
    if (moduleSymbol) {
      return getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias);
    }
  }
  function getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias) {
    let exportDefaultSymbol;
    if (isShorthandAmbientModuleSymbol(moduleSymbol)) {
      exportDefaultSymbol = moduleSymbol;
    } else {
      exportDefaultSymbol = resolveExportByName(moduleSymbol, InternalSymbolName.Default, node, dontResolveAlias);
    }
    const file = moduleSymbol.declarations?.find(isSourceFile);
    const specifier = getModuleSpecifierForImportOrExport(node);
    if (!specifier) {
      return exportDefaultSymbol;
    }
    const hasDefaultOnly = isOnlyImportableAsDefault(specifier);
    const hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, specifier);
    if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) {
      if (hasExportAssignmentSymbol(moduleSymbol) && !allowSyntheticDefaultImports) {
        const compilerOptionName = moduleKind >= ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
        const exportEqualsSymbol = moduleSymbol.exports.get(InternalSymbolName.ExportEquals);
        const exportAssignment = exportEqualsSymbol.valueDeclaration;
        const err = error(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
        if (exportAssignment) {
          addRelatedInfo(
            err,
            createDiagnosticForNode(
              exportAssignment,
              Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag,
              compilerOptionName
            )
          );
        }
      } else if (isImportClause(node)) {
        reportNonDefaultExport(moduleSymbol, node);
      } else {
        errorNoModuleMemberSymbol(moduleSymbol, moduleSymbol, node, isImportOrExportSpecifier(node) && node.propertyName || node.name);
      }
    } else if (hasSyntheticDefault || hasDefaultOnly) {
      const resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
      markSymbolOfAliasDeclarationIfTypeOnly(
        node,
        moduleSymbol,
        resolved,
        /*overwriteEmpty*/
        false
      );
      return resolved;
    }
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      exportDefaultSymbol,
      /*finalTarget*/
      void 0,
      /*overwriteEmpty*/
      false
    );
    return exportDefaultSymbol;
  }
  function getModuleSpecifierForImportOrExport(node) {
    switch (node.kind) {
      case SyntaxKind.ImportClause:
        return node.parent.moduleSpecifier;
      case SyntaxKind.ImportEqualsDeclaration:
        return isExternalModuleReference(node.moduleReference) ? node.moduleReference.expression : void 0;
      case SyntaxKind.NamespaceImport:
        return node.parent.parent.moduleSpecifier;
      case SyntaxKind.ImportSpecifier:
        return node.parent.parent.parent.moduleSpecifier;
      case SyntaxKind.ExportSpecifier:
        return node.parent.parent.moduleSpecifier;
      default:
        return Debug.assertNever(node);
    }
  }
  function reportNonDefaultExport(moduleSymbol, node) {
    if (moduleSymbol.exports?.has(node.symbol.escapedName)) {
      error(
        node.name,
        Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead,
        symbolToString(moduleSymbol),
        symbolToString(node.symbol)
      );
    } else {
      const diagnostic = error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
      const exportStar = moduleSymbol.exports?.get(InternalSymbolName.ExportStar);
      if (exportStar) {
        const defaultExport = exportStar.declarations?.find(
          (decl) => !!(isExportDeclaration(decl) && decl.moduleSpecifier && resolveExternalModuleName(decl, decl.moduleSpecifier)?.exports?.has(InternalSymbolName.Default))
        );
        if (defaultExport) {
          addRelatedInfo(diagnostic, createDiagnosticForNode(defaultExport, Diagnostics.export_Asterisk_does_not_re_export_a_default));
        }
      }
    }
  }
  function getTargetOfNamespaceImport(node, dontResolveAlias) {
    const moduleSpecifier = node.parent.parent.moduleSpecifier;
    const immediate = resolveExternalModuleName(node, moduleSpecifier);
    const resolved = resolveESModuleSymbol(
      immediate,
      moduleSpecifier,
      dontResolveAlias,
      /*suppressInteropError*/
      false
    );
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      immediate,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getTargetOfNamespaceExport(node, dontResolveAlias) {
    const moduleSpecifier = node.parent.moduleSpecifier;
    const immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
    const resolved = moduleSpecifier && resolveESModuleSymbol(
      immediate,
      moduleSpecifier,
      dontResolveAlias,
      /*suppressInteropError*/
      false
    );
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      immediate,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
    if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
      return unknownSymbol;
    }
    if (valueSymbol.flags & (SymbolFlags.Type | SymbolFlags.Namespace)) {
      return valueSymbol;
    }
    const result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
    Debug.assert(valueSymbol.declarations || typeSymbol.declarations);
    result.declarations = deduplicate(concatenate(valueSymbol.declarations, typeSymbol.declarations), equateValues);
    result.parent = valueSymbol.parent || typeSymbol.parent;
    if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration;
    if (typeSymbol.members) result.members = new Map(typeSymbol.members);
    if (valueSymbol.exports) result.exports = new Map(valueSymbol.exports);
    return result;
  }
  function getExportOfModule(symbol, nameText, specifier, dontResolveAlias) {
    if (symbol.flags & SymbolFlags.Module) {
      const exportSymbol = getExportsOfSymbol(symbol).get(nameText);
      const resolved = resolveSymbol(exportSymbol, dontResolveAlias);
      const exportStarDeclaration = getSymbolLinks(symbol).typeOnlyExportStarMap?.get(nameText);
      markSymbolOfAliasDeclarationIfTypeOnly(
        specifier,
        exportSymbol,
        resolved,
        /*overwriteEmpty*/
        false,
        exportStarDeclaration,
        nameText
      );
      return resolved;
    }
  }
  function getPropertyOfVariable(symbol, name) {
    if (symbol.flags & SymbolFlags.Variable) {
      const typeAnnotation = symbol.valueDeclaration.type;
      if (typeAnnotation) {
        return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
      }
    }
  }
  function getExternalModuleMember(node, specifier, dontResolveAlias = false) {
    const moduleSpecifier = getExternalModuleRequireArgument(node) || node.moduleSpecifier;
    const moduleSymbol = resolveExternalModuleName(node, moduleSpecifier);
    const name = !isPropertyAccessExpression(specifier) && specifier.propertyName || specifier.name;
    if (!isIdentifier(name) && name.kind !== SyntaxKind.StringLiteral) {
      return void 0;
    }
    const nameText = moduleExportNameTextEscaped(name);
    const suppressInteropError = nameText === InternalSymbolName.Default && allowSyntheticDefaultImports;
    const targetSymbol = resolveESModuleSymbol(
      moduleSymbol,
      moduleSpecifier,
      /*dontResolveAlias*/
      false,
      suppressInteropError
    );
    if (targetSymbol) {
      if (nameText || name.kind === SyntaxKind.StringLiteral) {
        if (isShorthandAmbientModuleSymbol(moduleSymbol)) {
          return moduleSymbol;
        }
        let symbolFromVariable;
        if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get(InternalSymbolName.ExportEquals)) {
          symbolFromVariable = getPropertyOfType(
            getTypeOfSymbol(targetSymbol),
            nameText,
            /*skipObjectFunctionPropertyAugment*/
            true
          );
        } else {
          symbolFromVariable = getPropertyOfVariable(targetSymbol, nameText);
        }
        symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
        let symbolFromModule = getExportOfModule(targetSymbol, nameText, specifier, dontResolveAlias);
        if (symbolFromModule === void 0 && nameText === InternalSymbolName.Default) {
          const file = moduleSymbol.declarations?.find(isSourceFile);
          if (isOnlyImportableAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) {
            symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
          }
        }
        const symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable;
        if (!symbol) {
          errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name);
        }
        return symbol;
      }
    }
  }
  function errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name) {
    const moduleName = getFullyQualifiedName(moduleSymbol, node);
    const declarationName = declarationNameToString(name);
    const suggestion = isIdentifier(name) ? getSuggestedSymbolForNonexistentModule(name, targetSymbol) : void 0;
    if (suggestion !== void 0) {
      const suggestionName = symbolToString(suggestion);
      const diagnostic = error(name, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
      if (suggestion.valueDeclaration) {
        addRelatedInfo(diagnostic, createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName));
      }
    } else {
      if (moduleSymbol.exports?.has(InternalSymbolName.Default)) {
        error(
          name,
          Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead,
          moduleName,
          declarationName
        );
      } else {
        reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
      }
    }
  }
  function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
    const localSymbol = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)?.locals?.get(moduleExportNameTextEscaped(name));
    const exports = moduleSymbol.exports;
    if (localSymbol) {
      const exportedEqualsSymbol = exports?.get(InternalSymbolName.ExportEquals);
      if (exportedEqualsSymbol) {
        getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
      } else {
        const exportedSymbol = exports ? find(symbolsToArray(exports), (symbol) => !!getSymbolIfSameReference(symbol, localSymbol)) : void 0;
        const diagnostic = exportedSymbol ? error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
        if (localSymbol.declarations) {
          addRelatedInfo(diagnostic, ...map(localSymbol.declarations, (decl, index) => createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName)));
        }
      }
    } else {
      error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
    }
  }
  function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
    if (moduleKind >= ModuleKind.ES2015) {
      const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_a_default_import : Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
      error(name, message, declarationName);
    } else {
      if (isInJSFile(node)) {
        const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
        error(name, message, declarationName);
      } else {
        const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
        error(name, message, declarationName, declarationName, moduleName);
      }
    }
  }
  function getTargetOfImportSpecifier(node, dontResolveAlias) {
    if (isImportSpecifier(node) && moduleExportNameIsDefault(node.propertyName || node.name)) {
      const specifier = getModuleSpecifierForImportOrExport(node);
      const moduleSymbol = specifier && resolveExternalModuleName(node, specifier);
      if (moduleSymbol) {
        return getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias);
      }
    }
    const root = isBindingElement(node) ? getRootDeclaration(node) : node.parent.parent.parent;
    const commonJSPropertyAccess = getCommonJSPropertyAccess(root);
    const resolved = getExternalModuleMember(root, commonJSPropertyAccess || node, dontResolveAlias);
    const name = node.propertyName || node.name;
    if (commonJSPropertyAccess && resolved && isIdentifier(name)) {
      return resolveSymbol(getPropertyOfType(getTypeOfSymbol(resolved), name.escapedText), dontResolveAlias);
    }
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getCommonJSPropertyAccess(node) {
    if (isVariableDeclaration(node) && node.initializer && isPropertyAccessExpression(node.initializer)) {
      return node.initializer;
    }
  }
  function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
    if (canHaveSymbol(node.parent)) {
      const resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
      markSymbolOfAliasDeclarationIfTypeOnly(
        node,
        /*immediateTarget*/
        void 0,
        resolved,
        /*overwriteEmpty*/
        false
      );
      return resolved;
    }
  }
  function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
    const name = node.propertyName || node.name;
    if (moduleExportNameIsDefault(name)) {
      const specifier = getModuleSpecifierForImportOrExport(node);
      const moduleSymbol = specifier && resolveExternalModuleName(node, specifier);
      if (moduleSymbol) {
        return getTargetofModuleDefault(moduleSymbol, node, !!dontResolveAlias);
      }
    }
    const resolved = node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : name.kind === SyntaxKind.StringLiteral ? void 0 : (
      // Skip for invalid syntax like this: export { "x" }
      resolveEntityName(
        name,
        meaning,
        /*ignoreErrors*/
        false,
        dontResolveAlias
      )
    );
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getTargetOfExportAssignment(node, dontResolveAlias) {
    const expression = isExportAssignment(node) ? node.expression : node.right;
    const resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
    if (isClassExpression(expression)) {
      return checkExpressionCached(expression).symbol;
    }
    if (!isEntityName(expression) && !isEntityNameExpression(expression)) {
      return void 0;
    }
    const aliasLike = resolveEntityName(
      expression,
      SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace,
      /*ignoreErrors*/
      true,
      dontResolveAlias
    );
    if (aliasLike) {
      return aliasLike;
    }
    checkExpressionCached(expression);
    return getNodeLinks(expression).resolvedSymbol;
  }
  function getTargetOfAccessExpression(node, dontRecursivelyResolve) {
    if (!(isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === SyntaxKind.EqualsToken)) {
      return void 0;
    }
    return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
  }
  function getTargetOfAliasDeclaration(node, dontRecursivelyResolve = false) {
    switch (node.kind) {
      case SyntaxKind.ImportEqualsDeclaration:
      case SyntaxKind.VariableDeclaration:
        return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
      case SyntaxKind.ImportClause:
        return getTargetOfImportClause(node, dontRecursivelyResolve);
      case SyntaxKind.NamespaceImport:
        return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
      case SyntaxKind.NamespaceExport:
        return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
      case SyntaxKind.ImportSpecifier:
      case SyntaxKind.BindingElement:
        return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
      case SyntaxKind.ExportSpecifier:
        return getTargetOfExportSpecifier(node, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, dontRecursivelyResolve);
      case SyntaxKind.ExportAssignment:
      case SyntaxKind.BinaryExpression:
        return getTargetOfExportAssignment(node, dontRecursivelyResolve);
      case SyntaxKind.NamespaceExportDeclaration:
        return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
      case SyntaxKind.ShorthandPropertyAssignment:
        return resolveEntityName(
          node.name,
          SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace,
          /*ignoreErrors*/
          true,
          dontRecursivelyResolve
        );
      case SyntaxKind.PropertyAssignment:
        return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve);
      case SyntaxKind.ElementAccessExpression:
      case SyntaxKind.PropertyAccessExpression:
        return getTargetOfAccessExpression(node, dontRecursivelyResolve);
      default:
        return Debug.fail();
    }
  }
  function isNonLocalAlias(symbol, excludes = SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace) {
    if (!symbol) return false;
    return (symbol.flags & (SymbolFlags.Alias | excludes)) === SymbolFlags.Alias || !!(symbol.flags & SymbolFlags.Alias && symbol.flags & SymbolFlags.Assignment);
  }
  function resolveSymbol(symbol, dontResolveAlias) {
    return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
  }
  function resolveAlias(symbol) {
    Debug.assert((symbol.flags & SymbolFlags.Alias) !== 0, "Should only get Alias here.");
    const links = getSymbolLinks(symbol);
    if (!links.aliasTarget) {
      links.aliasTarget = resolvingSymbol;
      const node = getDeclarationOfAliasSymbol(symbol);
      if (!node) return Debug.fail();
      const target = getTargetOfAliasDeclaration(node);
      if (links.aliasTarget === resolvingSymbol) {
        links.aliasTarget = target || unknownSymbol;
      } else {
        error(node, Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
      }
    } else if (links.aliasTarget === resolvingSymbol) {
      links.aliasTarget = unknownSymbol;
    }
    return links.aliasTarget;
  }
  function tryResolveAlias(symbol) {
    const links = getSymbolLinks(symbol);
    if (links.aliasTarget !== resolvingSymbol) {
      return resolveAlias(symbol);
    }
    return void 0;
  }
  function getSymbolFlags(symbol, excludeTypeOnlyMeanings, excludeLocalMeanings) {
    const typeOnlyDeclaration = excludeTypeOnlyMeanings && getTypeOnlyAliasDeclaration(symbol);
    const typeOnlyDeclarationIsExportStar = typeOnlyDeclaration && isExportDeclaration(typeOnlyDeclaration);
    const typeOnlyResolution = typeOnlyDeclaration && (typeOnlyDeclarationIsExportStar ? resolveExternalModuleName(
      typeOnlyDeclaration.moduleSpecifier,
      typeOnlyDeclaration.moduleSpecifier,
      /*ignoreErrors*/
      true
    ) : resolveAlias(typeOnlyDeclaration.symbol));
    const typeOnlyExportStarTargets = typeOnlyDeclarationIsExportStar && typeOnlyResolution ? getExportsOfModule(typeOnlyResolution) : void 0;
    let flags = excludeLocalMeanings ? SymbolFlags.None : symbol.flags;
    let seenSymbols;
    while (symbol.flags & SymbolFlags.Alias) {
      const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol));
      if (!typeOnlyDeclarationIsExportStar && target === typeOnlyResolution || typeOnlyExportStarTargets?.get(target.escapedName) === target) {
        break;
      }
      if (target === unknownSymbol) {
        return SymbolFlags.All;
      }
      if (target === symbol || seenSymbols?.has(target)) {
        break;
      }
      if (target.flags & SymbolFlags.Alias) {
        if (seenSymbols) {
          seenSymbols.add(target);
        } else {
          seenSymbols = /* @__PURE__ */ new Set([symbol, target]);
        }
      }
      flags |= target.flags;
      symbol = target;
    }
    return flags;
  }
  function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty, exportStarDeclaration, exportStarName) {
    if (!aliasDeclaration || isPropertyAccessExpression(aliasDeclaration)) return false;
    const sourceSymbol = getSymbolOfDeclaration(aliasDeclaration);
    if (isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
      const links2 = getSymbolLinks(sourceSymbol);
      links2.typeOnlyDeclaration = aliasDeclaration;
      return true;
    }
    if (exportStarDeclaration) {
      const links2 = getSymbolLinks(sourceSymbol);
      links2.typeOnlyDeclaration = exportStarDeclaration;
      if (sourceSymbol.escapedName !== exportStarName) {
        links2.typeOnlyExportStarName = exportStarName;
      }
      return true;
    }
    const links = getSymbolLinks(sourceSymbol);
    return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty) || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
  }
  function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
    if (target && (aliasDeclarationLinks.typeOnlyDeclaration === void 0 || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
      const exportSymbol = target.exports?.get(InternalSymbolName.ExportEquals) ?? target;
      const typeOnly = exportSymbol.declarations && find(exportSymbol.declarations, isTypeOnlyImportOrExportDeclaration);
      aliasDeclarationLinks.typeOnlyDeclaration = typeOnly ?? getSymbolLinks(exportSymbol).typeOnlyDeclaration ?? false;
    }
    return !!aliasDeclarationLinks.typeOnlyDeclaration;
  }
  function getTypeOnlyAliasDeclaration(symbol, include) {
    if (!(symbol.flags & SymbolFlags.Alias)) {
      return void 0;
    }
    const links = getSymbolLinks(symbol);
    if (links.typeOnlyDeclaration === void 0) {
      links.typeOnlyDeclaration = false;
      const resolved = resolveSymbol(symbol);
      markSymbolOfAliasDeclarationIfTypeOnly(
        symbol.declarations?.[0],
        getDeclarationOfAliasSymbol(symbol) && getImmediateAliasedSymbol(symbol),
        resolved,
        /*overwriteEmpty*/
        true
      );
    }
    if (include === void 0) {
      return links.typeOnlyDeclaration || void 0;
    }
    if (links.typeOnlyDeclaration) {
      const resolved = links.typeOnlyDeclaration.kind === SyntaxKind.ExportDeclaration ? resolveSymbol(getExportsOfModule(links.typeOnlyDeclaration.symbol.parent).get(links.typeOnlyExportStarName || symbol.escapedName)) : resolveAlias(links.typeOnlyDeclaration.symbol);
      return getSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0;
    }
    return void 0;
  }
  function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
    if (entityName.kind === SyntaxKind.Identifier && isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
      entityName = entityName.parent;
    }
    if (entityName.kind === SyntaxKind.Identifier || entityName.parent.kind === SyntaxKind.QualifiedName) {
      return resolveEntityName(
        entityName,
        SymbolFlags.Namespace,
        /*ignoreErrors*/
        false,
        dontResolveAlias
      );
    } else {
      Debug.assert(entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration);
      return resolveEntityName(
        entityName,
        SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace,
        /*ignoreErrors*/
        false,
        dontResolveAlias
      );
    }
  }
  function getFullyQualifiedName(symbol, containingLocation) {
    return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(
      symbol,
      containingLocation,
      /*meaning*/
      void 0,
      SymbolFormatFlags.DoNotIncludeSymbolChain | SymbolFormatFlags.AllowAnyNodeKind
    );
  }
  function getContainingQualifiedNameNode(node) {
    while (isQualifiedName(node.parent)) {
      node = node.parent;
    }
    return node;
  }
  function tryGetQualifiedNameAsValue(node) {
    let left = getFirstIdentifier(node);
    let symbol = resolveName(
      left,
      left,
      SymbolFlags.Value,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
    if (!symbol) {
      return void 0;
    }
    while (isQualifiedName(left.parent)) {
      const type = getTypeOfSymbol(symbol);
      symbol = getPropertyOfType(type, left.parent.right.escapedText);
      if (!symbol) {
        return void 0;
      }
      left = left.parent;
    }
    return symbol;
  }
  function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
    if (nodeIsMissing(name)) {
      return void 0;
    }
    const namespaceMeaning = SymbolFlags.Namespace | (isInJSFile(name) ? meaning & SymbolFlags.Value : 0);
    let symbol;
    if (name.kind === SyntaxKind.Identifier) {
      const message = meaning === namespaceMeaning || nodeIsSynthesized(name) ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name));
      const symbolFromJSPrototype = isInJSFile(name) && !nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : void 0;
      symbol = getMergedSymbol(resolveName(
        location || name,
        name,
        meaning,
        ignoreErrors || symbolFromJSPrototype ? void 0 : message,
        /*isUse*/
        true,
        /*excludeGlobals*/
        false
      ));
      if (!symbol) {
        return getMergedSymbol(symbolFromJSPrototype);
      }
    } else if (name.kind === SyntaxKind.QualifiedName || name.kind === SyntaxKind.PropertyAccessExpression) {
      const left = name.kind === SyntaxKind.QualifiedName ? name.left : name.expression;
      const right = name.kind === SyntaxKind.QualifiedName ? name.right : name.name;
      let namespace = resolveEntityName(
        left,
        namespaceMeaning,
        ignoreErrors,
        /*dontResolveAlias*/
        false,
        location
      );
      if (!namespace || nodeIsMissing(right)) {
        return void 0;
      } else if (namespace === unknownSymbol) {
        return namespace;
      }
      if (namespace.valueDeclaration && isInJSFile(namespace.valueDeclaration) && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Bundler && isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && isCommonJsRequire(namespace.valueDeclaration.initializer)) {
        const moduleName = namespace.valueDeclaration.initializer.arguments[0];
        const moduleSym = resolveExternalModuleName(moduleName, moduleName);
        if (moduleSym) {
          const resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
          if (resolvedModuleSymbol) {
            namespace = resolvedModuleSymbol;
          }
        }
      }
      symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
      if (!symbol && namespace.flags & SymbolFlags.Alias) {
        symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(resolveAlias(namespace)), right.escapedText, meaning));
      }
      if (!symbol) {
        if (!ignoreErrors) {
          const namespaceName = getFullyQualifiedName(namespace);
          const declarationName = declarationNameToString(right);
          const suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace);
          if (suggestionForNonexistentModule) {
            error(right, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule));
            return void 0;
          }
          const containingQualifiedName = isQualifiedName(name) && getContainingQualifiedNameNode(name);
          const canSuggestTypeof = globalObjectType && meaning & SymbolFlags.Type && containingQualifiedName && !isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName);
          if (canSuggestTypeof) {
            error(
              containingQualifiedName,
              Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0,
              entityNameToString(containingQualifiedName)
            );
            return void 0;
          }
          if (meaning & SymbolFlags.Namespace && isQualifiedName(name.parent)) {
            const exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, SymbolFlags.Type));
            if (exportedTypeSymbol) {
              error(
                name.parent.right,
                Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1,
                symbolToString(exportedTypeSymbol),
                unescapeLeadingUnderscores(name.parent.right.escapedText)
              );
              return void 0;
            }
          }
          error(right, Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName);
        }
        return void 0;
      }
    } else {
      Debug.assertNever(name, "Unknown entity name kind.");
    }
    if (!nodeIsSynthesized(name) && isEntityName(name) && (symbol.flags & SymbolFlags.Alias || name.parent.kind === SyntaxKind.ExportAssignment)) {
      markSymbolOfAliasDeclarationIfTypeOnly(
        getAliasDeclarationFromName(name),
        symbol,
        /*finalTarget*/
        void 0,
        /*overwriteEmpty*/
        true
      );
    }
    return symbol.flags & meaning || dontResolveAlias ? symbol : resolveAlias(symbol);
  }
  function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
    if (isJSDocTypeReference(name.parent)) {
      const secondaryLocation = getAssignmentDeclarationLocation(name.parent);
      if (secondaryLocation) {
        return resolveName(
          secondaryLocation,
          name,
          meaning,
          /*nameNotFoundMessage*/
          void 0,
          /*isUse*/
          true
        );
      }
    }
  }
  function getAssignmentDeclarationLocation(node) {
    const typeAlias = findAncestor(node, (node2) => !(isJSDocNode(node2) || node2.flags & NodeFlags.JSDoc) ? "quit" : isJSDocTypeAlias(node2));
    if (typeAlias) {
      return;
    }
    const host2 = getJSDocHost(node);
    if (host2 && isExpressionStatement(host2) && isPrototypePropertyAssignment(host2.expression)) {
      const symbol = getSymbolOfDeclaration(host2.expression.left);
      if (symbol) {
        return getDeclarationOfJSPrototypeContainer(symbol);
      }
    }
    if (host2 && isFunctionExpression(host2) && isPrototypePropertyAssignment(host2.parent) && isExpressionStatement(host2.parent.parent)) {
      const symbol = getSymbolOfDeclaration(host2.parent.left);
      if (symbol) {
        return getDeclarationOfJSPrototypeContainer(symbol);
      }
    }
    if (host2 && (isObjectLiteralMethod(host2) || isPropertyAssignment(host2)) && isBinaryExpression(host2.parent.parent) && getAssignmentDeclarationKind(host2.parent.parent) === AssignmentDeclarationKind.Prototype) {
      const symbol = getSymbolOfDeclaration(host2.parent.parent.left);
      if (symbol) {
        return getDeclarationOfJSPrototypeContainer(symbol);
      }
    }
    const sig = getEffectiveJSDocHost(node);
    if (sig && isFunctionLike(sig)) {
      const symbol = getSymbolOfDeclaration(sig);
      return symbol && symbol.valueDeclaration;
    }
  }
  function getDeclarationOfJSPrototypeContainer(symbol) {
    const decl = symbol.parent.valueDeclaration;
    if (!decl) {
      return void 0;
    }
    const initializer = isAssignmentDeclaration(decl) ? getAssignedExpandoInitializer(decl) : hasOnlyExpressionInitializer(decl) ? getDeclaredExpandoInitializer(decl) : void 0;
    return initializer || decl;
  }
  function getExpandoSymbol(symbol) {
    const decl = symbol.valueDeclaration;
    if (!decl || !isInJSFile(decl) || symbol.flags & SymbolFlags.TypeAlias || getExpandoInitializer(
      decl,
      /*isPrototypeAssignment*/
      false
    )) {
      return void 0;
    }
    const init = isVariableDeclaration(decl) ? getDeclaredExpandoInitializer(decl) : getAssignedExpandoInitializer(decl);
    if (init) {
      const initSymbol = getSymbolOfNode(init);
      if (initSymbol) {
        return mergeJSSymbols(initSymbol, symbol);
      }
    }
  }
  function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
    const isClassic = getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Classic;
    const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
    return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? void 0 : errorMessage, ignoreErrors);
  }
  function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, ignoreErrors = false, isForAugmentation = false) {
    return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, !ignoreErrors ? moduleReferenceExpression : void 0, isForAugmentation) : void 0;
  }
  function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) {
    if (errorNode && startsWith(moduleReference, "@types/")) {
      const diag = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
      const withoutAtTypePrefix = removePrefix(moduleReference, "@types/");
      error(errorNode, diag, withoutAtTypePrefix, moduleReference);
    }
    const ambientModule = tryFindAmbientModule(
      moduleReference,
      /*withAugmentations*/
      true
    );
    if (ambientModule) {
      return ambientModule;
    }
    const currentSourceFile = getSourceFileOfNode(location);
    const contextSpecifier = isStringLiteralLike(location) ? location : (isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : void 0)?.name || (isLiteralImportTypeNode(location) ? location : void 0)?.argument.literal || (isInJSFile(location) && isJSDocImportTag(location) ? location.moduleSpecifier : void 0) || (isVariableDeclaration(location) && location.initializer && isRequireCall(
      location.initializer,
      /*requireStringLiteralLikeArgument*/
      true
    ) ? location.initializer.arguments[0] : void 0) || findAncestor(location, isImportCall)?.arguments[0] || findAncestor(location, isImportDeclaration)?.moduleSpecifier || findAncestor(location, isExternalModuleImportEqualsDeclaration)?.moduleReference.expression || findAncestor(location, isExportDeclaration)?.moduleSpecifier;
    const mode = contextSpecifier && isStringLiteralLike(contextSpecifier) ? host.getModeForUsageLocation(currentSourceFile, contextSpecifier) : host.getDefaultResolutionModeForFile(currentSourceFile);
    const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions);
    const resolvedModule = host.getResolvedModule(currentSourceFile, moduleReference, mode)?.resolvedModule;
    const resolutionDiagnostic = errorNode && resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule, currentSourceFile);
    const sourceFile = resolvedModule && (!resolutionDiagnostic || resolutionDiagnostic === Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set) && host.getSourceFile(resolvedModule.resolvedFileName);
    if (sourceFile) {
      if (resolutionDiagnostic) {
        error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
      }
      if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) {
        const importOrExport = findAncestor(location, isImportDeclaration)?.importClause || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration));
        if (errorNode && importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) {
          error(
            errorNode,
            Diagnostics.A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead,
            getSuggestedImportSource(Debug.checkDefined(tryExtractTSExtension(moduleReference)))
          );
        }
      } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) {
        const importOrExport = findAncestor(location, isImportDeclaration)?.importClause || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration));
        if (errorNode && !(importOrExport?.isTypeOnly || findAncestor(location, isImportTypeNode))) {
          const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference));
          error(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension);
        }
      }
      if (sourceFile.symbol) {
        if (errorNode && resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
          errorOnImplicitAnyModule(
            /*isError*/
            false,
            errorNode,
            currentSourceFile,
            mode,
            resolvedModule,
            moduleReference
          );
        }
        if (errorNode && (moduleResolutionKind === ModuleResolutionKind.Node16 || moduleResolutionKind === ModuleResolutionKind.NodeNext)) {
          const isSyncImport = currentSourceFile.impliedNodeFormat === ModuleKind.CommonJS && !findAncestor(location, isImportCall) || !!findAncestor(location, isImportEqualsDeclaration);
          const overrideHost = findAncestor(location, (l) => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l) || isJSDocImportTag(l));
          if (isSyncImport && sourceFile.impliedNodeFormat === ModuleKind.ESNext && !hasResolutionModeOverride(overrideHost)) {
            if (findAncestor(location, isImportEqualsDeclaration)) {
              error(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference);
            } else {
              let diagnosticDetails;
              const ext = tryGetExtensionFromPath(currentSourceFile.fileName);
              if (ext === Extension.Ts || ext === Extension.Js || ext === Extension.Tsx || ext === Extension.Jsx) {
                diagnosticDetails = createModeMismatchDetails(currentSourceFile);
              }
              diagnostics.add(createDiagnosticForNodeFromMessageChain(
                getSourceFileOfNode(errorNode),
                errorNode,
                chainDiagnosticMessages(
                  diagnosticDetails,
                  Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead,
                  moduleReference
                )
              ));
            }
          }
        }
        return getMergedSymbol(sourceFile.symbol);
      }
      if (errorNode && moduleNotFoundError && !isSideEffectImport(errorNode)) {
        error(errorNode, Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
      }
      return void 0;
    }
    if (patternAmbientModules) {
      const pattern = findBestPatternMatch(patternAmbientModules, (_) => _.pattern, moduleReference);
      if (pattern) {
        const augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
        if (augmentation) {
          return getMergedSymbol(augmentation);
        }
        return getMergedSymbol(pattern.symbol);
      }
    }
    if (!errorNode) {
      return void 0;
    }
    if (resolvedModule && !resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === void 0 || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
      if (isForAugmentation) {
        const diag = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
        error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
      } else {
        errorOnImplicitAnyModule(
          /*isError*/
          noImplicitAny && !!moduleNotFoundError,
          errorNode,
          currentSourceFile,
          mode,
          resolvedModule,
          moduleReference
        );
      }
      return void 0;
    }
    if (moduleNotFoundError) {
      if (resolvedModule) {
        const redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
        if (redirect) {
          error(errorNode, Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
          return void 0;
        }
      }
      if (resolutionDiagnostic) {
        error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
      } else {
        const isExtensionlessRelativePathImport = pathIsRelative(moduleReference) && !hasExtension(moduleReference);
        const resolutionIsNode16OrNext = moduleResolutionKind === ModuleResolutionKind.Node16 || moduleResolutionKind === ModuleResolutionKind.NodeNext;
        if (!getResolveJsonModule(compilerOptions) && fileExtensionIs(moduleReference, Extension.Json) && moduleResolutionKind !== ModuleResolutionKind.Classic && hasJsonModuleEmitEnabled(compilerOptions)) {
          error(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
        } else if (mode === ModuleKind.ESNext && resolutionIsNode16OrNext && isExtensionlessRelativePathImport) {
          const absoluteRef = getNormalizedAbsolutePath(moduleReference, getDirectoryPath(currentSourceFile.path));
          const suggestedExt = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))?.[1];
          if (suggestedExt) {
            error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt);
          } else {
            error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path);
          }
        } else {
          if (host.getResolvedModule(currentSourceFile, moduleReference, mode)?.alternateResult) {
            const errorInfo = createModuleNotFoundChain(currentSourceFile, host, moduleReference, mode, moduleReference);
            errorOrSuggestion(
              /*isError*/
              true,
              errorNode,
              chainDiagnosticMessages(errorInfo, moduleNotFoundError, moduleReference)
            );
          } else {
            error(errorNode, moduleNotFoundError, moduleReference);
          }
        }
      }
    }
    return void 0;
    function getSuggestedImportSource(tsExtension) {
      const importSourceWithoutExtension = removeExtension(moduleReference, tsExtension);
      if (emitModuleKindIsNonNodeESM(moduleKind) || mode === ModuleKind.ESNext) {
        const preferTs = isDeclarationFileName(moduleReference) && shouldAllowImportingTsExtension(compilerOptions);
        const ext = tsExtension === Extension.Mts || tsExtension === Extension.Dmts ? preferTs ? ".mts" : ".mjs" : tsExtension === Extension.Cts || tsExtension === Extension.Dmts ? preferTs ? ".cts" : ".cjs" : preferTs ? ".ts" : ".js";
        return importSourceWithoutExtension + ext;
      }
      return importSourceWithoutExtension;
    }
  }
  function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId, resolvedFileName }, moduleReference) {
    if (isSideEffectImport(errorNode)) {
      return;
    }
    let errorInfo;
    if (!isExternalModuleNameRelative(moduleReference) && packageId) {
      errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name);
    }
    errorOrSuggestion(
      isError,
      errorNode,
      chainDiagnosticMessages(
        errorInfo,
        Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type,
        moduleReference,
        resolvedFileName
      )
    );
  }
  function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
    if (moduleSymbol?.exports) {
      const exportEquals = resolveSymbol(moduleSymbol.exports.get(InternalSymbolName.ExportEquals), dontResolveAlias);
      const exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
      return getMergedSymbol(exported) || moduleSymbol;
    }
    return void 0;
  }
  function getCommonJsExportEquals(exported, moduleSymbol) {
    if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & SymbolFlags.Alias) {
      return exported;
    }
    const links = getSymbolLinks(exported);
    if (links.cjsExportMerged) {
      return links.cjsExportMerged;
    }
    const merged = exported.flags & SymbolFlags.Transient ? exported : cloneSymbol(exported);
    merged.flags = merged.flags | SymbolFlags.ValueModule;
    if (merged.exports === void 0) {
      merged.exports = createSymbolTable();
    }
    moduleSymbol.exports.forEach((s, name) => {
      if (name === InternalSymbolName.ExportEquals) return;
      merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
    });
    if (merged === exported) {
      getSymbolLinks(merged).resolvedExports = void 0;
      getSymbolLinks(merged).resolvedMembers = void 0;
    }
    getSymbolLinks(merged).cjsExportMerged = merged;
    return links.cjsExportMerged = merged;
  }
  function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
    const symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
    if (!dontResolveAlias && symbol) {
      if (!suppressInteropError && !(symbol.flags & (SymbolFlags.Module | SymbolFlags.Variable)) && !getDeclarationOfKind(symbol, SyntaxKind.SourceFile)) {
        const compilerOptionName = moduleKind >= ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
        error(referencingLocation, Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName);
        return symbol;
      }
      const referenceParent = referencingLocation.parent;
      if (isImportDeclaration(referenceParent) && getNamespaceDeclarationNode(referenceParent) || isImportCall(referenceParent)) {
        const reference = isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier;
        const type = getTypeOfSymbol(symbol);
        const defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference);
        if (defaultOnlyType) {
          return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent);
        }
        const targetFile = moduleSymbol?.declarations?.find(isSourceFile);
        const isEsmCjsRef = targetFile && isESMFormatImportImportingCommonjsFormatFile(getEmitSyntaxForModuleSpecifierExpression(reference), host.getImpliedNodeFormatForEmit(targetFile));
        if (getESModuleInterop(compilerOptions) || isEsmCjsRef) {
          let sigs = getSignaturesOfStructuredType(type, SignatureKind.Call);
          if (!sigs || !sigs.length) {
            sigs = getSignaturesOfStructuredType(type, SignatureKind.Construct);
          }
          if (sigs && sigs.length || getPropertyOfType(
            type,
            InternalSymbolName.Default,
            /*skipObjectFunctionPropertyAugment*/
            true
          ) || isEsmCjsRef) {
            const moduleType = type.flags & TypeFlags.StructuredType ? getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference) : createDefaultPropertyWrapperForModule(symbol, symbol.parent);
            return cloneTypeAsModuleType(symbol, moduleType, referenceParent);
          }
        }
      }
    }
    return symbol;
  }
  function cloneTypeAsModuleType(symbol, moduleType, referenceParent) {
    const result = createSymbol(symbol.flags, symbol.escapedName);
    result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
    result.parent = symbol.parent;
    result.links.target = symbol;
    result.links.originatingImport = referenceParent;
    if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration;
    if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true;
    if (symbol.members) result.members = new Map(symbol.members);
    if (symbol.exports) result.exports = new Map(symbol.exports);
    const resolvedModuleType = resolveStructuredTypeMembers(moduleType);
    result.links.type = createAnonymousType(result, resolvedModuleType.members, emptyArray, emptyArray, resolvedModuleType.indexInfos);
    return result;
  }
  function hasExportAssignmentSymbol(moduleSymbol) {
    return moduleSymbol.exports.get(InternalSymbolName.ExportEquals) !== void 0;
  }
  function getExportsOfModuleAsArray(moduleSymbol) {
    return symbolsToArray(getExportsOfModule(moduleSymbol));
  }
  function getExportsAndPropertiesOfModule(moduleSymbol) {
    const exports = getExportsOfModuleAsArray(moduleSymbol);
    const exportEquals = resolveExternalModuleSymbol(moduleSymbol);
    if (exportEquals !== moduleSymbol) {
      const type = getTypeOfSymbol(exportEquals);
      if (shouldTreatPropertiesOfExternalModuleAsExports(type)) {
        addRange(exports, getPropertiesOfType(type));
      }
    }
    return exports;
  }
  function forEachExportAndPropertyOfModule(moduleSymbol, cb) {
    const exports = getExportsOfModule(moduleSymbol);
    exports.forEach((symbol, key) => {
      if (!isReservedMemberName(key)) {
        cb(symbol, key);
      }
    });
    const exportEquals = resolveExternalModuleSymbol(moduleSymbol);
    if (exportEquals !== moduleSymbol) {
      const type = getTypeOfSymbol(exportEquals);
      if (shouldTreatPropertiesOfExternalModuleAsExports(type)) {
        forEachPropertyOfType(type, (symbol, escapedName) => {
          cb(symbol, escapedName);
        });
      }
    }
  }
  function tryGetMemberInModuleExports(memberName, moduleSymbol) {
    const symbolTable = getExportsOfModule(moduleSymbol);
    if (symbolTable) {
      return symbolTable.get(memberName);
    }
  }
  function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
    const symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
    if (symbol) {
      return symbol;
    }
    const exportEquals = resolveExternalModuleSymbol(moduleSymbol);
    if (exportEquals === moduleSymbol) {
      return void 0;
    }
    const type = getTypeOfSymbol(exportEquals);
    return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : void 0;
  }
  function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) {
    return !(resolvedExternalModuleType.flags & TypeFlags.Primitive || getObjectFlags(resolvedExternalModuleType) & ObjectFlags.Class || // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path
    isArrayType(resolvedExternalModuleType) || isTupleType(resolvedExternalModuleType));
  }
  function getExportsOfSymbol(symbol) {
    return symbol.flags & SymbolFlags.LateBindingContainer ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : symbol.flags & SymbolFlags.Module ? getExportsOfModule(symbol) : symbol.exports || emptySymbols;
  }
  function getExportsOfModule(moduleSymbol) {
    const links = getSymbolLinks(moduleSymbol);
    if (!links.resolvedExports) {
      const { exports, typeOnlyExportStarMap } = getExportsOfModuleWorker(moduleSymbol);
      links.resolvedExports = exports;
      links.typeOnlyExportStarMap = typeOnlyExportStarMap;
    }
    return links.resolvedExports;
  }
  function extendExportSymbols(target, source, lookupTable, exportNode) {
    if (!source) return;
    source.forEach((sourceSymbol, id) => {
      if (id === InternalSymbolName.Default) return;
      const targetSymbol = target.get(id);
      if (!targetSymbol) {
        target.set(id, sourceSymbol);
        if (lookupTable && exportNode) {
          lookupTable.set(id, {
            specifierText: getTextOfNode(exportNode.moduleSpecifier)
          });
        }
      } else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
        const collisionTracker = lookupTable.get(id);
        if (!collisionTracker.exportsWithDuplicate) {
          collisionTracker.exportsWithDuplicate = [exportNode];
        } else {
          collisionTracker.exportsWithDuplicate.push(exportNode);
        }
      }
    });
  }
  function getExportsOfModuleWorker(moduleSymbol) {
    const visitedSymbols = [];
    let typeOnlyExportStarMap;
    const nonTypeOnlyNames = /* @__PURE__ */ new Set();
    moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
    const exports = visit(moduleSymbol) || emptySymbols;
    if (typeOnlyExportStarMap) {
      nonTypeOnlyNames.forEach((name) => typeOnlyExportStarMap.delete(name));
    }
    return {
      exports,
      typeOnlyExportStarMap
    };
    function visit(symbol, exportStar, isTypeOnly) {
      if (!isTypeOnly && symbol?.exports) {
        symbol.exports.forEach((_, name) => nonTypeOnlyNames.add(name));
      }
      if (!(symbol && symbol.exports && pushIfUnique(visitedSymbols, symbol))) {
        return;
      }
      const symbols = new Map(symbol.exports);
      const exportStars = symbol.exports.get(InternalSymbolName.ExportStar);
      if (exportStars) {
        const nestedSymbols = createSymbolTable();
        const lookupTable = /* @__PURE__ */ new Map();
        if (exportStars.declarations) {
          for (const node of exportStars.declarations) {
            const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
            const exportedSymbols = visit(resolvedModule, node, isTypeOnly || node.isTypeOnly);
            extendExportSymbols(
              nestedSymbols,
              exportedSymbols,
              lookupTable,
              node
            );
          }
        }
        lookupTable.forEach(({ exportsWithDuplicate }, id) => {
          if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
            return;
          }
          for (const node of exportsWithDuplicate) {
            diagnostics.add(createDiagnosticForNode(
              node,
              Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity,
              lookupTable.get(id).specifierText,
              unescapeLeadingUnderscores(id)
            ));
          }
        });
        extendExportSymbols(symbols, nestedSymbols);
      }
      if (exportStar?.isTypeOnly) {
        typeOnlyExportStarMap ??= /* @__PURE__ */ new Map();
        symbols.forEach(
          (_, escapedName) => typeOnlyExportStarMap.set(
            escapedName,
            exportStar
          )
        );
      }
      return symbols;
    }
  }
  function getMergedSymbol(symbol) {
    let merged;
    return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
  }
  function getSymbolOfDeclaration(node) {
    return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
  }
  function getSymbolOfNode(node) {
    return canHaveSymbol(node) ? getSymbolOfDeclaration(node) : void 0;
  }
  function getParentOfSymbol(symbol) {
    return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
  }
  function getFunctionExpressionParentSymbolOrSymbol(symbol) {
    return symbol.valueDeclaration?.kind === SyntaxKind.ArrowFunction || symbol.valueDeclaration?.kind === SyntaxKind.FunctionExpression ? getSymbolOfNode(symbol.valueDeclaration.parent) || symbol : symbol;
  }
  function getAlternativeContainingModules(symbol, enclosingDeclaration) {
    const containingFile = getSourceFileOfNode(enclosingDeclaration);
    const id = getNodeId(containingFile);
    const links = getSymbolLinks(symbol);
    let results;
    if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
      return results;
    }
    if (containingFile && containingFile.imports) {
      for (const importRef of containingFile.imports) {
        if (nodeIsSynthesized(importRef)) continue;
        const resolvedModule = resolveExternalModuleName(
          enclosingDeclaration,
          importRef,
          /*ignoreErrors*/
          true
        );
        if (!resolvedModule) continue;
        const ref = getAliasForSymbolInContainer(resolvedModule, symbol);
        if (!ref) continue;
        results = append(results, resolvedModule);
      }
      if (length(results)) {
        (links.extendedContainersByFile || (links.extendedContainersByFile = /* @__PURE__ */ new Map())).set(id, results);
        return results;
      }
    }
    if (links.extendedContainers) {
      return links.extendedContainers;
    }
    const otherFiles = host.getSourceFiles();
    for (const file of otherFiles) {
      if (!isExternalModule(file)) continue;
      const sym = getSymbolOfDeclaration(file);
      const ref = getAliasForSymbolInContainer(sym, symbol);
      if (!ref) continue;
      results = append(results, sym);
    }
    return links.extendedContainers = results || emptyArray;
  }
  function getContainersOfSymbol(symbol, enclosingDeclaration, meaning) {
    const container = getParentOfSymbol(symbol);
    if (container && !(symbol.flags & SymbolFlags.TypeParameter)) {
      return getWithAlternativeContainers(container);
    }
    const candidates = mapDefined(symbol.declarations, (d) => {
      if (!isAmbientModule(d) && d.parent) {
        if (hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
          return getSymbolOfDeclaration(d.parent);
        }
        if (isModuleBlock(d.parent) && d.parent.parent && resolveExternalModuleSymbol(getSymbolOfDeclaration(d.parent.parent)) === symbol) {
          return getSymbolOfDeclaration(d.parent.parent);
        }
      }
      if (isClassExpression(d) && isBinaryExpression(d.parent) && d.parent.operatorToken.kind === SyntaxKind.EqualsToken && isAccessExpression(d.parent.left) && isEntityNameExpression(d.parent.left.expression)) {
        if (isModuleExportsAccessExpression(d.parent.left) || isExportsIdentifier(d.parent.left.expression)) {
          return getSymbolOfDeclaration(getSourceFileOfNode(d));
        }
        checkExpressionCached(d.parent.left.expression);
        return getNodeLinks(d.parent.left.expression).resolvedSymbol;
      }
    });
    if (!length(candidates)) {
      return void 0;
    }
    const containers = mapDefined(candidates, (candidate) => getAliasForSymbolInContainer(candidate, symbol) ? candidate : void 0);
    let bestContainers = [];
    let alternativeContainers = [];
    for (const container2 of containers) {
      const [bestMatch, ...rest] = getWithAlternativeContainers(container2);
      bestContainers = append(bestContainers, bestMatch);
      alternativeContainers = addRange(alternativeContainers, rest);
    }
    return concatenate(bestContainers, alternativeContainers);
    function getWithAlternativeContainers(container2) {
      const additionalContainers = mapDefined(container2.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
      const reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
      const objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container2, meaning);
      if (enclosingDeclaration && container2.flags & getQualifiedLeftMeaning(meaning) && getAccessibleSymbolChain(
        container2,
        enclosingDeclaration,
        SymbolFlags.Namespace,
        /*useOnlyExternalAliasing*/
        false
      )) {
        return append(concatenate(concatenate([container2], additionalContainers), reexportContainers), objectLiteralContainer);
      }
      const firstVariableMatch = !(container2.flags & getQualifiedLeftMeaning(meaning)) && container2.flags & SymbolFlags.Type && getDeclaredTypeOfSymbol(container2).flags & TypeFlags.Object && meaning === SymbolFlags.Value ? forEachSymbolTableInScope(enclosingDeclaration, (t) => {
        return forEachEntry(t, (s) => {
          if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container2)) {
            return s;
          }
        });
      }) : void 0;
      let res = firstVariableMatch ? [firstVariableMatch, ...additionalContainers, container2] : [...additionalContainers, container2];
      res = append(res, objectLiteralContainer);
      res = addRange(res, reexportContainers);
      return res;
    }
    function fileSymbolIfFileSymbolExportEqualsContainer(d) {
      return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
    }
  }
  function getVariableDeclarationOfObjectLiteral(symbol, meaning) {
    const firstDecl = !!length(symbol.declarations) && first(symbol.declarations);
    if (meaning & SymbolFlags.Value && firstDecl && firstDecl.parent && isVariableDeclaration(firstDecl.parent)) {
      if (isObjectLiteralExpression(firstDecl) && firstDecl === firstDecl.parent.initializer || isTypeLiteralNode(firstDecl) && firstDecl === firstDecl.parent.type) {
        return getSymbolOfDeclaration(firstDecl.parent);
      }
    }
  }
  function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
    const fileSymbol = getExternalModuleContainer(d);
    const exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get(InternalSymbolName.ExportEquals);
    return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : void 0;
  }
  function getAliasForSymbolInContainer(container, symbol) {
    if (container === getParentOfSymbol(symbol)) {
      return symbol;
    }
    const exportEquals = container.exports && container.exports.get(InternalSymbolName.ExportEquals);
    if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
      return container;
    }
    const exports = getExportsOfSymbol(container);
    const quick = exports.get(symbol.escapedName);
    if (quick && getSymbolIfSameReference(quick, symbol)) {
      return quick;
    }
    return forEachEntry(exports, (exported) => {
      if (getSymbolIfSameReference(exported, symbol)) {
        return exported;
      }
    });
  }
  function getSymbolIfSameReference(s1, s2) {
    if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
      return s1;
    }
  }
  function getExportSymbolOfValueSymbolIfExported(symbol) {
    return getMergedSymbol(symbol && (symbol.flags & SymbolFlags.ExportValue) !== 0 && symbol.exportSymbol || symbol);
  }
  function symbolIsValue(symbol, includeTypeOnlyMembers) {
    return !!(symbol.flags & SymbolFlags.Value || symbol.flags & SymbolFlags.Alias && getSymbolFlags(symbol, !includeTypeOnlyMembers) & SymbolFlags.Value);
  }
  function createType(flags) {
    const result = new Type2(checker, flags);
    typeCount++;
    result.id = typeCount;
    tracing?.recordType(result);
    return result;
  }
  function createTypeWithSymbol(flags, symbol) {
    const result = createType(flags);
    result.symbol = symbol;
    return result;
  }
  function createOriginType(flags) {
    return new Type2(checker, flags);
  }
  function createIntrinsicType(kind, intrinsicName, objectFlags = ObjectFlags.None, debugIntrinsicName) {
    checkIntrinsicName(intrinsicName, debugIntrinsicName);
    const type = createType(kind);
    type.intrinsicName = intrinsicName;
    type.debugIntrinsicName = debugIntrinsicName;
    type.objectFlags = objectFlags | ObjectFlags.CouldContainTypeVariablesComputed | ObjectFlags.IsGenericTypeComputed | ObjectFlags.IsUnknownLikeUnionComputed | ObjectFlags.IsNeverIntersectionComputed;
    return type;
  }
  function checkIntrinsicName(name, debug) {
    const key = `${name},${debug ?? ""}`;
    if (seenIntrinsicNames.has(key)) {
      Debug.fail(`Duplicate intrinsic type name ${name}${debug ? ` (${debug})` : ""}; you may need to pass a name to createIntrinsicType.`);
    }
    seenIntrinsicNames.add(key);
  }
  function createObjectType(objectFlags, symbol) {
    const type = createTypeWithSymbol(TypeFlags.Object, symbol);
    type.objectFlags = objectFlags;
    type.members = void 0;
    type.properties = void 0;
    type.callSignatures = void 0;
    type.constructSignatures = void 0;
    type.indexInfos = void 0;
    return type;
  }
  function createTypeofType() {
    return getUnionType(arrayFrom(typeofNEFacts.keys(), getStringLiteralType));
  }
  function createTypeParameter(symbol) {
    return createTypeWithSymbol(TypeFlags.TypeParameter, symbol);
  }
  function isReservedMemberName(name) {
    return name.charCodeAt(0) === CharacterCodes._ && name.charCodeAt(1) === CharacterCodes._ && name.charCodeAt(2) !== CharacterCodes._ && name.charCodeAt(2) !== CharacterCodes.at && name.charCodeAt(2) !== CharacterCodes.hash;
  }
  function getNamedMembers(members) {
    let result;
    members.forEach((symbol, id) => {
      if (isNamedMember(symbol, id)) {
        (result || (result = [])).push(symbol);
      }
    });
    return result || emptyArray;
  }
  function isNamedMember(member, escapedName) {
    return !isReservedMemberName(escapedName) && symbolIsValue(member);
  }
  function getNamedOrIndexSignatureMembers(members) {
    const result = getNamedMembers(members);
    const index = getIndexSymbolFromSymbolTable(members);
    return index ? concatenate(result, [index]) : result;
  }
  function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos) {
    const resolved = type;
    resolved.members = members;
    resolved.properties = emptyArray;
    resolved.callSignatures = callSignatures;
    resolved.constructSignatures = constructSignatures;
    resolved.indexInfos = indexInfos;
    if (members !== emptySymbols) resolved.properties = getNamedMembers(members);
    return resolved;
  }
  function createAnonymousType(symbol, members, callSignatures, constructSignatures, indexInfos) {
    return setStructuredTypeMembers(createObjectType(ObjectFlags.Anonymous, symbol), members, callSignatures, constructSignatures, indexInfos);
  }
  function getResolvedTypeWithoutAbstractConstructSignatures(type) {
    if (type.constructSignatures.length === 0) return type;
    if (type.objectTypeWithoutAbstractConstructSignatures) return type.objectTypeWithoutAbstractConstructSignatures;
    const constructSignatures = filter(type.constructSignatures, (signature) => !(signature.flags & SignatureFlags.Abstract));
    if (type.constructSignatures === constructSignatures) return type;
    const typeCopy = createAnonymousType(
      type.symbol,
      type.members,
      type.callSignatures,
      some(constructSignatures) ? constructSignatures : emptyArray,
      type.indexInfos
    );
    type.objectTypeWithoutAbstractConstructSignatures = typeCopy;
    typeCopy.objectTypeWithoutAbstractConstructSignatures = typeCopy;
    return typeCopy;
  }
  function forEachSymbolTableInScope(enclosingDeclaration, callback) {
    let result;
    for (let location = enclosingDeclaration; location; location = location.parent) {
      if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) {
        if (result = callback(
          location.locals,
          /*ignoreQualification*/
          void 0,
          /*isLocalNameLookup*/
          true,
          location
        )) {
          return result;
        }
      }
      switch (location.kind) {
        case SyntaxKind.SourceFile:
          if (!isExternalOrCommonJsModule(location)) {
            break;
          }
        // falls through
        case SyntaxKind.ModuleDeclaration:
          const sym = getSymbolOfDeclaration(location);
          if (result = callback(
            sym?.exports || emptySymbols,
            /*ignoreQualification*/
            void 0,
            /*isLocalNameLookup*/
            true,
            location
          )) {
            return result;
          }
          break;
        case SyntaxKind.ClassDeclaration:
        case SyntaxKind.ClassExpression:
        case SyntaxKind.InterfaceDeclaration:
          let table;
          (getSymbolOfDeclaration(location).members || emptySymbols).forEach((memberSymbol, key) => {
            if (memberSymbol.flags & (SymbolFlags.Type & ~SymbolFlags.Assignment)) {
              (table || (table = createSymbolTable())).set(key, memberSymbol);
            }
          });
          if (table && (result = callback(
            table,
            /*ignoreQualification*/
            void 0,
            /*isLocalNameLookup*/
            false,
            location
          ))) {
            return result;
          }
          break;
      }
    }
    return callback(
      globals,
      /*ignoreQualification*/
      void 0,
      /*isLocalNameLookup*/
      true
    );
  }
  function getQualifiedLeftMeaning(rightMeaning) {
    return rightMeaning === SymbolFlags.Value ? SymbolFlags.Value : SymbolFlags.Namespace;
  }
  function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap = /* @__PURE__ */ new Map()) {
    if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
      return void 0;
    }
    const links = getSymbolLinks(symbol);
    const cache = links.accessibleChainCache ||= /* @__PURE__ */ new Map();
    const firstRelevantLocation = forEachSymbolTableInScope(enclosingDeclaration, (_, __, ___, node) => node);
    const key = `${useOnlyExternalAliasing ? 0 : 1}|${firstRelevantLocation && getNodeId(firstRelevantLocation)}|${meaning}`;
    if (cache.has(key)) {
      return cache.get(key);
    }
    const id = getSymbolId(symbol);
    let visitedSymbolTables = visitedSymbolTablesMap.get(id);
    if (!visitedSymbolTables) {
      visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
    }
    const result = forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
    cache.set(key, result);
    return result;
    function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) {
      if (!pushIfUnique(visitedSymbolTables, symbols)) {
        return void 0;
      }
      const result2 = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup);
      visitedSymbolTables.pop();
      return result2;
    }
    function canQualifySymbol(symbolFromSymbolTable, meaning2) {
      return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning2) || // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
      !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning2), useOnlyExternalAliasing, visitedSymbolTablesMap);
    }
    function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
      return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) && // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
      // and if symbolFromSymbolTable or alias resolution matches the symbol,
      // check the symbol can be qualified, it is only then this symbol is accessible
      !some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
    }
    function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) {
      if (isAccessible(
        symbols.get(symbol.escapedName),
        /*resolvedAliasSymbol*/
        void 0,
        ignoreQualification
      )) {
        return [symbol];
      }
      const result2 = forEachEntry(symbols, (symbolFromSymbolTable) => {
        if (symbolFromSymbolTable.flags & SymbolFlags.Alias && symbolFromSymbolTable.escapedName !== InternalSymbolName.ExportEquals && symbolFromSymbolTable.escapedName !== InternalSymbolName.Default && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && isExternalModule(getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || some(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) && (isLocalNameLookup ? !some(symbolFromSymbolTable.declarations, isNamespaceReexportDeclaration) : true) && (ignoreQualification || !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier))) {
          const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
          const candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
          if (candidate) {
            return candidate;
          }
        }
        if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
          if (isAccessible(
            getMergedSymbol(symbolFromSymbolTable.exportSymbol),
            /*resolvedAliasSymbol*/
            void 0,
            ignoreQualification
          )) {
            return [symbol];
          }
        }
      });
      return result2 || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : void 0);
    }
    function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
      if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
        return [symbolFromSymbolTable];
      }
      const candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
      const accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(
        candidateTable,
        /*ignoreQualification*/
        true
      );
      if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
        return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
      }
    }
  }
  function needsQualification(symbol, enclosingDeclaration, meaning) {
    let qualify = false;
    forEachSymbolTableInScope(enclosingDeclaration, (symbolTable) => {
      let symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
      if (!symbolFromSymbolTable) {
        return false;
      }
      if (symbolFromSymbolTable === symbol) {
        return true;
      }
      const shouldResolveAlias = symbolFromSymbolTable.flags & SymbolFlags.Alias && !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier);
      symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
      const flags = shouldResolveAlias ? getSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags;
      if (flags & meaning) {
        qualify = true;
        return true;
      }
      return false;
    });
    return qualify;
  }
  function isPropertyOrMethodDeclarationSymbol(symbol) {
    if (symbol.declarations && symbol.declarations.length) {
      for (const declaration of symbol.declarations) {
        switch (declaration.kind) {
          case SyntaxKind.PropertyDeclaration:
          case SyntaxKind.MethodDeclaration:
          case SyntaxKind.GetAccessor:
          case SyntaxKind.SetAccessor:
            continue;
          default:
            return false;
        }
      }
      return true;
    }
    return false;
  }
  function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
    const access = isSymbolAccessibleWorker(
      typeSymbol,
      enclosingDeclaration,
      SymbolFlags.Type,
      /*shouldComputeAliasesToMakeVisible*/
      false,
      /*allowModules*/
      true
    );
    return access.accessibility === SymbolAccessibility.Accessible;
  }
  function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
    const access = isSymbolAccessibleWorker(
      typeSymbol,
      enclosingDeclaration,
      SymbolFlags.Value,
      /*shouldComputeAliasesToMakeVisible*/
      false,
      /*allowModules*/
      true
    );
    return access.accessibility === SymbolAccessibility.Accessible;
  }
  function isSymbolAccessibleByFlags(typeSymbol, enclosingDeclaration, flags) {
    const access = isSymbolAccessibleWorker(
      typeSymbol,
      enclosingDeclaration,
      flags,
      /*shouldComputeAliasesToMakeVisible*/
      false,
      /*allowModules*/
      false
    );
    return access.accessibility === SymbolAccessibility.Accessible;
  }
  function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
    if (!length(symbols)) return;
    let hadAccessibleChain;
    let earlyModuleBail = false;
    for (const symbol of symbols) {
      const accessibleSymbolChain = getAccessibleSymbolChain(
        symbol,
        enclosingDeclaration,
        meaning,
        /*useOnlyExternalAliasing*/
        false
      );
      if (accessibleSymbolChain) {
        hadAccessibleChain = symbol;
        const hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
        if (hasAccessibleDeclarations) {
          return hasAccessibleDeclarations;
        }
      }
      if (allowModules) {
        if (some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
          if (shouldComputeAliasesToMakeVisible) {
            earlyModuleBail = true;
            continue;
          }
          return {
            accessibility: SymbolAccessibility.Accessible
          };
        }
      }
      const containers = getContainersOfSymbol(symbol, enclosingDeclaration, meaning);
      const parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible, allowModules);
      if (parentResult) {
        return parentResult;
      }
    }
    if (earlyModuleBail) {
      return {
        accessibility: SymbolAccessibility.Accessible
      };
    }
    if (hadAccessibleChain) {
      return {
        accessibility: SymbolAccessibility.NotAccessible,
        errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
        errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, SymbolFlags.Namespace) : void 0
      };
    }
  }
  function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
    return isSymbolAccessibleWorker(
      symbol,
      enclosingDeclaration,
      meaning,
      shouldComputeAliasesToMakeVisible,
      /*allowModules*/
      true
    );
  }
  function isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
    if (symbol && enclosingDeclaration) {
      const result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible, allowModules);
      if (result) {
        return result;
      }
      const symbolExternalModule = forEach(symbol.declarations, getExternalModuleContainer);
      if (symbolExternalModule) {
        const enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
        if (symbolExternalModule !== enclosingExternalModule) {
          return {
            accessibility: SymbolAccessibility.CannotBeNamed,
            errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
            errorModuleName: symbolToString(symbolExternalModule),
            errorNode: isInJSFile(enclosingDeclaration) ? enclosingDeclaration : void 0
          };
        }
      }
      return {
        accessibility: SymbolAccessibility.NotAccessible,
        errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning)
      };
    }
    return { accessibility: SymbolAccessibility.Accessible };
  }
  function getExternalModuleContainer(declaration) {
    const node = findAncestor(declaration, hasExternalModuleSymbol);
    return node && getSymbolOfDeclaration(node);
  }
  function hasExternalModuleSymbol(declaration) {
    return isAmbientModule(declaration) || declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration);
  }
  function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
    return isModuleWithStringLiteralName(declaration) || declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration);
  }
  function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
    let aliasesToMakeVisible;
    if (!every(filter(symbol.declarations, (d) => d.kind !== SyntaxKind.Identifier), getIsDeclarationVisible)) {
      return void 0;
    }
    return { accessibility: SymbolAccessibility.Accessible, aliasesToMakeVisible };
    function getIsDeclarationVisible(declaration) {
      if (!isDeclarationVisible(declaration)) {
        const anyImportSyntax = getAnyImportSyntax(declaration);
        if (anyImportSyntax && !hasSyntacticModifier(anyImportSyntax, ModifierFlags.Export) && // import clause without export
        isDeclarationVisible(anyImportSyntax.parent)) {
          return addVisibleAlias(declaration, anyImportSyntax);
        } else if (isVariableDeclaration(declaration) && isVariableStatement(declaration.parent.parent) && !hasSyntacticModifier(declaration.parent.parent, ModifierFlags.Export) && // unexported variable statement
        isDeclarationVisible(declaration.parent.parent.parent)) {
          return addVisibleAlias(declaration, declaration.parent.parent);
        } else if (isLateVisibilityPaintedStatement(declaration) && !hasSyntacticModifier(declaration, ModifierFlags.Export) && isDeclarationVisible(declaration.parent)) {
          return addVisibleAlias(declaration, declaration);
        } else if (isBindingElement(declaration)) {
          if (symbol.flags & SymbolFlags.Alias && isInJSFile(declaration) && declaration.parent?.parent && isVariableDeclaration(declaration.parent.parent) && declaration.parent.parent.parent?.parent && isVariableStatement(declaration.parent.parent.parent.parent) && !hasSyntacticModifier(declaration.parent.parent.parent.parent, ModifierFlags.Export) && declaration.parent.parent.parent.parent.parent && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) {
            return addVisibleAlias(declaration, declaration.parent.parent.parent.parent);
          } else if (symbol.flags & SymbolFlags.BlockScopedVariable) {
            const variableStatement = findAncestor(declaration, isVariableStatement);
            if (hasSyntacticModifier(variableStatement, ModifierFlags.Export)) {
              return true;
            }
            if (!isDeclarationVisible(variableStatement.parent)) {
              return false;
            }
            return addVisibleAlias(declaration, variableStatement);
          }
        }
        return false;
      }
      return true;
    }
    function addVisibleAlias(declaration, aliasingStatement) {
      if (shouldComputeAliasToMakeVisible) {
        getNodeLinks(declaration).isVisible = true;
        aliasesToMakeVisible = appendIfUnique(aliasesToMakeVisible, aliasingStatement);
      }
      return true;
    }
  }
  function getMeaningOfEntityNameReference(entityName) {
    let meaning;
    if (entityName.parent.kind === SyntaxKind.TypeQuery || entityName.parent.kind === SyntaxKind.ExpressionWithTypeArguments && !isPartOfTypeNode(entityName.parent) || entityName.parent.kind === SyntaxKind.ComputedPropertyName || entityName.parent.kind === SyntaxKind.TypePredicate && entityName.parent.parameterName === entityName) {
      meaning = SymbolFlags.Value | SymbolFlags.ExportValue;
    } else if (entityName.kind === SyntaxKind.QualifiedName || entityName.kind === SyntaxKind.PropertyAccessExpression || entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration || entityName.parent.kind === SyntaxKind.QualifiedName && entityName.parent.left === entityName || entityName.parent.kind === SyntaxKind.PropertyAccessExpression && entityName.parent.expression === entityName || entityName.parent.kind === SyntaxKind.ElementAccessExpression && entityName.parent.expression === entityName) {
      meaning = SymbolFlags.Namespace;
    } else {
      meaning = SymbolFlags.Type;
    }
    return meaning;
  }
  function isEntityNameVisible(entityName, enclosingDeclaration, shouldComputeAliasToMakeVisible = true) {
    const meaning = getMeaningOfEntityNameReference(entityName);
    const firstIdentifier = getFirstIdentifier(entityName);
    const symbol = resolveName(
      enclosingDeclaration,
      firstIdentifier.escapedText,
      meaning,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false
    );
    if (symbol && symbol.flags & SymbolFlags.TypeParameter && meaning & SymbolFlags.Type) {
      return { accessibility: SymbolAccessibility.Accessible };
    }
    if (!symbol && isThisIdentifier(firstIdentifier) && isSymbolAccessible(
      getSymbolOfDeclaration(getThisContainer(
        firstIdentifier,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      )),
      firstIdentifier,
      meaning,
      /*shouldComputeAliasesToMakeVisible*/
      false
    ).accessibility === SymbolAccessibility.Accessible) {
      return { accessibility: SymbolAccessibility.Accessible };
    }
    if (!symbol) {
      return {
        accessibility: SymbolAccessibility.NotResolved,
        errorSymbolName: getTextOfNode(firstIdentifier),
        errorNode: firstIdentifier
      };
    }
    return hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) || {
      accessibility: SymbolAccessibility.NotAccessible,
      errorSymbolName: getTextOfNode(firstIdentifier),
      errorNode: firstIdentifier
    };
  }
  function symbolToString(symbol, enclosingDeclaration, meaning, flags = SymbolFormatFlags.AllowAnyNodeKind, writer) {
    let nodeFlags = NodeBuilderFlags.IgnoreErrors;
    let internalNodeFlags = InternalNodeBuilderFlags.None;
    if (flags & SymbolFormatFlags.UseOnlyExternalAliasing) {
      nodeFlags |= NodeBuilderFlags.UseOnlyExternalAliasing;
    }
    if (flags & SymbolFormatFlags.WriteTypeParametersOrArguments) {
      nodeFlags |= NodeBuilderFlags.WriteTypeParametersInQualifiedName;
    }
    if (flags & SymbolFormatFlags.UseAliasDefinedOutsideCurrentScope) {
      nodeFlags |= NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope;
    }
    if (flags & SymbolFormatFlags.DoNotIncludeSymbolChain) {
      internalNodeFlags |= InternalNodeBuilderFlags.DoNotIncludeSymbolChain;
    }
    if (flags & SymbolFormatFlags.WriteComputedProps) {
      internalNodeFlags |= InternalNodeBuilderFlags.WriteComputedProps;
    }
    const builder = flags & SymbolFormatFlags.AllowAnyNodeKind ? nodeBuilder.symbolToNode : nodeBuilder.symbolToEntityName;
    return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker);
    function symbolToStringWorker(writer2) {
      const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags, internalNodeFlags);
      const printer = enclosingDeclaration?.kind === SyntaxKind.SourceFile ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments();
      const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
      printer.writeNode(
        EmitHint.Unspecified,
        entity,
        /*sourceFile*/
        sourceFile,
        writer2
      );
      return writer2;
    }
  }
  function signatureToString(signature, enclosingDeclaration, flags = TypeFormatFlags.None, kind, writer) {
    return writer ? signatureToStringWorker(writer).getText() : usingSingleLineStringWriter(signatureToStringWorker);
    function signatureToStringWorker(writer2) {
      let sigOutput;
      if (flags & TypeFormatFlags.WriteArrowStyleSignature) {
        sigOutput = kind === SignatureKind.Construct ? SyntaxKind.ConstructorType : SyntaxKind.FunctionType;
      } else {
        sigOutput = kind === SignatureKind.Construct ? SyntaxKind.ConstructSignature : SyntaxKind.CallSignature;
      }
      const sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | NodeBuilderFlags.IgnoreErrors | NodeBuilderFlags.WriteTypeParametersInQualifiedName);
      const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon();
      const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
      printer.writeNode(
        EmitHint.Unspecified,
        sig,
        /*sourceFile*/
        sourceFile,
        getTrailingSemicolonDeferringWriter(writer2)
      );
      return writer2;
    }
  }
  function typeToString(type, enclosingDeclaration, flags = TypeFormatFlags.AllowUniqueESSymbolType | TypeFormatFlags.UseAliasDefinedOutsideCurrentScope, writer = createTextWriter("")) {
    const noTruncation = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation;
    const typeNode = nodeBuilder.typeToTypeNode(
      type,
      enclosingDeclaration,
      toNodeBuilderFlags(flags) | NodeBuilderFlags.IgnoreErrors | (noTruncation ? NodeBuilderFlags.NoTruncation : NodeBuilderFlags.None),
      /*internalFlags*/
      void 0
    );
    if (typeNode === void 0) return Debug.fail("should always get typenode");
    const printer = type !== unresolvedType ? createPrinterWithRemoveComments() : createPrinterWithDefaults();
    const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
    printer.writeNode(
      EmitHint.Unspecified,
      typeNode,
      /*sourceFile*/
      sourceFile,
      writer
    );
    const result = writer.getText();
    const maxLength = noTruncation ? noTruncationMaximumTruncationLength * 2 : defaultMaximumTruncationLength * 2;
    if (maxLength && result && result.length >= maxLength) {
      return result.substr(0, maxLength - "...".length) + "...";
    }
    return result;
  }
  function getTypeNamesForErrorDisplay(left, right) {
    let leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
    let rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
    if (leftStr === rightStr) {
      leftStr = getTypeNameForErrorDisplay(left);
      rightStr = getTypeNameForErrorDisplay(right);
    }
    return [leftStr, rightStr];
  }
  function getTypeNameForErrorDisplay(type) {
    return typeToString(
      type,
      /*enclosingDeclaration*/
      void 0,
      TypeFormatFlags.UseFullyQualifiedType
    );
  }
  function symbolValueDeclarationIsContextSensitive(symbol) {
    return symbol && !!symbol.valueDeclaration && isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
  }
  function toNodeBuilderFlags(flags = TypeFormatFlags.None) {
    return flags & TypeFormatFlags.NodeBuilderFlagsMask;
  }
  function isClassInstanceSide(type) {
    return !!type.symbol && !!(type.symbol.flags & SymbolFlags.Class) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(type.flags & TypeFlags.Object) && !!(getObjectFlags(type) & ObjectFlags.IsClassInstanceClone));
  }
  function getTypeFromTypeNodeWithoutContext(node) {
    return getTypeFromTypeNode(node);
  }
  function createNodeBuilder() {
    return {
      typeToTypeNode: (type, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeToTypeNodeHelper(type, context)),
      typePredicateToTypePredicateNode: (typePredicate, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typePredicateToTypePredicateNodeHelper(typePredicate, context)),
      expressionOrTypeToTypeNode: (expr, type, addUndefined, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => expressionOrTypeToTypeNode(context, expr, type, addUndefined)),
      serializeTypeForDeclaration: (declaration, type, symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => serializeTypeForDeclaration(context, declaration, type, symbol)),
      serializeReturnTypeForSignature: (signature, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => serializeReturnTypeForSignature(context, signature)),
      indexInfoToIndexSignatureDeclaration: (indexInfo, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => indexInfoToIndexSignatureDeclarationHelper(
        indexInfo,
        context,
        /*typeNode*/
        void 0
      )),
      signatureToSignatureDeclaration: (signature, kind, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => signatureToSignatureDeclarationHelper(signature, kind, context)),
      symbolToEntityName: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToName(
        symbol,
        context,
        meaning,
        /*expectsIdentifier*/
        false
      )),
      symbolToExpression: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToExpression(symbol, context, meaning)),
      symbolToTypeParameterDeclarations: (symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeParametersToTypeParameterDeclarations(symbol, context)),
      symbolToParameterDeclaration: (symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToParameterDeclaration(symbol, context)),
      typeParameterToDeclaration: (parameter, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeParameterToDeclaration(parameter, context)),
      symbolTableToDeclarationStatements: (symbolTable, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolTableToDeclarationStatements(symbolTable, context)),
      symbolToNode: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToNode(symbol, context, meaning))
    };
    function getTypeFromTypeNode2(context, node, noMappedTypes) {
      const type = getTypeFromTypeNodeWithoutContext(node);
      if (!context.mapper) return type;
      const mappedType = instantiateType(type, context.mapper);
      return noMappedTypes && mappedType !== type ? void 0 : mappedType;
    }
    function setTextRange(context, range, location) {
      if (!nodeIsSynthesized(range) || !(range.flags & NodeFlags.Synthesized) || !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(getOriginalNode(range))) {
        range = factory.cloneNode(range);
      }
      if (range === location) return range;
      if (!location) {
        return range;
      }
      let original = range.original;
      while (original && original !== location) {
        original = original.original;
      }
      if (!original) {
        setOriginalNode(range, location);
      }
      if (context.enclosingFile && context.enclosingFile === getSourceFileOfNode(getOriginalNode(location))) {
        return setTextRangeWorker(range, location);
      }
      return range;
    }
    function expressionOrTypeToTypeNode(context, expr, type, addUndefined) {
      const restoreFlags = saveRestoreFlags(context);
      if (expr && !(context.internalFlags & InternalNodeBuilderFlags.NoSyntacticPrinter)) {
        syntacticNodeBuilder.serializeTypeOfExpression(expr, context, addUndefined);
      }
      context.internalFlags |= InternalNodeBuilderFlags.NoSyntacticPrinter;
      const result = expressionOrTypeToTypeNodeHelper(context, expr, type, addUndefined);
      restoreFlags();
      return result;
    }
    function expressionOrTypeToTypeNodeHelper(context, expr, type, addUndefined) {
      if (expr) {
        const typeNode = isAssertionExpression(expr) ? expr.type : isJSDocTypeAssertion(expr) ? getJSDocTypeAssertionType(expr) : void 0;
        if (typeNode && !isConstTypeReference(typeNode)) {
          const result = tryReuseExistingTypeNode(context, typeNode, type, expr.parent, addUndefined);
          if (result) {
            return result;
          }
        }
      }
      if (addUndefined) {
        type = getOptionalType(type);
      }
      return typeToTypeNodeHelper(type, context);
    }
    function tryReuseExistingTypeNode(context, typeNode, type, host2, addUndefined) {
      const originalType = type;
      if (addUndefined) {
        type = getOptionalType(type, !isParameter(host2));
      }
      const clone = tryReuseExistingNonParameterTypeNode(context, typeNode, type, host2);
      if (clone) {
        if (addUndefined && containsNonMissingUndefinedType(type) && !someType(getTypeFromTypeNode2(context, typeNode), (t) => !!(t.flags & TypeFlags.Undefined))) {
          return factory.createUnionTypeNode([clone, factory.createKeywordTypeNode(SyntaxKind.UndefinedKeyword)]);
        }
        return clone;
      }
      if (addUndefined && originalType !== type) {
        const cloneMissingUndefined = tryReuseExistingNonParameterTypeNode(context, typeNode, originalType, host2);
        if (cloneMissingUndefined) {
          return factory.createUnionTypeNode([cloneMissingUndefined, factory.createKeywordTypeNode(SyntaxKind.UndefinedKeyword)]);
        }
      }
      return void 0;
    }
    function tryReuseExistingNonParameterTypeNode(context, existing, type, host2 = context.enclosingDeclaration, annotationType = getTypeFromTypeNode2(
      context,
      existing,
      /*noMappedTypes*/
      true
    )) {
      if (annotationType && typeNodeIsEquivalentToType(host2, type, annotationType) && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
        const result = tryReuseExistingTypeNodeHelper(context, existing);
        if (result) {
          return result;
        }
      }
      return void 0;
    }
    function symbolToNode(symbol, context, meaning) {
      if (context.internalFlags & InternalNodeBuilderFlags.WriteComputedProps) {
        if (symbol.valueDeclaration) {
          const name = getNameOfDeclaration(symbol.valueDeclaration);
          if (name && isComputedPropertyName(name)) return name;
        }
        const nameType = getSymbolLinks(symbol).nameType;
        if (nameType && nameType.flags & (TypeFlags.EnumLiteral | TypeFlags.UniqueESSymbol)) {
          context.enclosingDeclaration = nameType.symbol.valueDeclaration;
          return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, meaning));
        }
      }
      return symbolToExpression(symbol, context, meaning);
    }
    function withContext(enclosingDeclaration, flags, internalFlags, tracker, cb) {
      const moduleResolverHost = tracker?.trackSymbol ? tracker.moduleResolverHost : (internalFlags || InternalNodeBuilderFlags.None) & InternalNodeBuilderFlags.DoNotIncludeSymbolChain ? createBasicNodeBuilderModuleSpecifierResolutionHost(host) : void 0;
      const context = {
        enclosingDeclaration,
        enclosingFile: enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration),
        flags: flags || NodeBuilderFlags.None,
        internalFlags: internalFlags || InternalNodeBuilderFlags.None,
        tracker: void 0,
        encounteredError: false,
        reportedDiagnostic: false,
        visitedTypes: void 0,
        symbolDepth: void 0,
        inferTypeParameters: void 0,
        approximateLength: 0,
        trackedSymbols: void 0,
        bundled: !!compilerOptions.outFile && !!enclosingDeclaration && isExternalOrCommonJsModule(getSourceFileOfNode(enclosingDeclaration)),
        truncating: false,
        usedSymbolNames: void 0,
        remappedSymbolNames: void 0,
        remappedSymbolReferences: void 0,
        reverseMappedStack: void 0,
        mustCreateTypeParameterSymbolList: true,
        typeParameterSymbolList: void 0,
        mustCreateTypeParametersNamesLookups: true,
        typeParameterNames: void 0,
        typeParameterNamesByText: void 0,
        typeParameterNamesByTextNextNameCount: void 0,
        mapper: void 0
      };
      context.tracker = new SymbolTrackerImpl(context, tracker, moduleResolverHost);
      const resultingNode = cb(context);
      if (context.truncating && context.flags & NodeBuilderFlags.NoTruncation) {
        context.tracker.reportTruncationError();
      }
      return context.encounteredError ? void 0 : resultingNode;
    }
    function saveRestoreFlags(context) {
      const flags = context.flags;
      const internalFlags = context.internalFlags;
      return restore;
      function restore() {
        context.flags = flags;
        context.internalFlags = internalFlags;
      }
    }
    function checkTruncationLength(context) {
      if (context.truncating) return context.truncating;
      return context.truncating = context.approximateLength > (context.flags & NodeBuilderFlags.NoTruncation ? noTruncationMaximumTruncationLength : defaultMaximumTruncationLength);
    }
    function typeToTypeNodeHelper(type, context) {
      const restoreFlags = saveRestoreFlags(context);
      const typeNode = typeToTypeNodeWorker(type, context);
      restoreFlags();
      return typeNode;
    }
    function typeToTypeNodeWorker(type, context) {
      if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
        cancellationToken.throwIfCancellationRequested();
      }
      const inTypeAlias = context.flags & NodeBuilderFlags.InTypeAlias;
      context.flags &= ~NodeBuilderFlags.InTypeAlias;
      if (!type) {
        if (!(context.flags & NodeBuilderFlags.AllowEmptyUnionOrIntersection)) {
          context.encounteredError = true;
          return void 0;
        }
        context.approximateLength += 3;
        return factory.createKeywordTypeNode(SyntaxKind.AnyKeyword);
      }
      if (!(context.flags & NodeBuilderFlags.NoTypeReduction)) {
        type = getReducedType(type);
      }
      if (type.flags & TypeFlags.Any) {
        if (type.aliasSymbol) {
          return factory.createTypeReferenceNode(symbolToEntityNameNode(type.aliasSymbol), mapToTypeNodes(type.aliasTypeArguments, context));
        }
        if (type === unresolvedType) {
          return addSyntheticLeadingComment(factory.createKeywordTypeNode(SyntaxKind.AnyKeyword), SyntaxKind.MultiLineCommentTrivia, "unresolved");
        }
        context.approximateLength += 3;
        return factory.createKeywordTypeNode(type === intrinsicMarkerType ? SyntaxKind.IntrinsicKeyword : SyntaxKind.AnyKeyword);
      }
      if (type.flags & TypeFlags.Unknown) {
        return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
      }
      if (type.flags & TypeFlags.String) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(SyntaxKind.StringKeyword);
      }
      if (type.flags & TypeFlags.Number) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(SyntaxKind.NumberKeyword);
      }
      if (type.flags & TypeFlags.BigInt) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(SyntaxKind.BigIntKeyword);
      }
      if (type.flags & TypeFlags.Boolean && !type.aliasSymbol) {
        context.approximateLength += 7;
        return factory.createKeywordTypeNode(SyntaxKind.BooleanKeyword);
      }
      if (type.flags & TypeFlags.EnumLike) {
        if (type.symbol.flags & SymbolFlags.EnumMember) {
          const parentSymbol = getParentOfSymbol(type.symbol);
          const parentName = symbolToTypeNode(parentSymbol, context, SymbolFlags.Type);
          if (getDeclaredTypeOfSymbol(parentSymbol) === type) {
            return parentName;
          }
          const memberName = symbolName(type.symbol);
          if (isIdentifierText(memberName, ScriptTarget.ES5)) {
            return appendReferenceToType(
              parentName,
              factory.createTypeReferenceNode(
                memberName,
                /*typeArguments*/
                void 0
              )
            );
          }
          if (isImportTypeNode(parentName)) {
            parentName.isTypeOf = true;
            return factory.createIndexedAccessTypeNode(parentName, factory.createLiteralTypeNode(factory.createStringLiteral(memberName)));
          } else if (isTypeReferenceNode(parentName)) {
            return factory.createIndexedAccessTypeNode(factory.createTypeQueryNode(parentName.typeName), factory.createLiteralTypeNode(factory.createStringLiteral(memberName)));
          } else {
            return Debug.fail("Unhandled type node kind returned from `symbolToTypeNode`.");
          }
        }
        return symbolToTypeNode(type.symbol, context, SymbolFlags.Type);
      }
      if (type.flags & TypeFlags.StringLiteral) {
        context.approximateLength += type.value.length + 2;
        return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & NodeBuilderFlags.UseSingleQuotesForStringLiteralType)), EmitFlags.NoAsciiEscaping));
      }
      if (type.flags & TypeFlags.NumberLiteral) {
        const value = type.value;
        context.approximateLength += ("" + value).length;
        return factory.createLiteralTypeNode(value < 0 ? factory.createPrefixUnaryExpression(SyntaxKind.MinusToken, factory.createNumericLiteral(-value)) : factory.createNumericLiteral(value));
      }
      if (type.flags & TypeFlags.BigIntLiteral) {
        context.approximateLength += pseudoBigIntToString(type.value).length + 1;
        return factory.createLiteralTypeNode(factory.createBigIntLiteral(type.value));
      }
      if (type.flags & TypeFlags.BooleanLiteral) {
        context.approximateLength += type.intrinsicName.length;
        return factory.createLiteralTypeNode(type.intrinsicName === "true" ? factory.createTrue() : factory.createFalse());
      }
      if (type.flags & TypeFlags.UniqueESSymbol) {
        if (!(context.flags & NodeBuilderFlags.AllowUniqueESSymbolType)) {
          if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
            context.approximateLength += 6;
            return symbolToTypeNode(type.symbol, context, SymbolFlags.Value);
          }
          if (context.tracker.reportInaccessibleUniqueSymbolError) {
            context.tracker.reportInaccessibleUniqueSymbolError();
          }
        }
        context.approximateLength += 13;
        return factory.createTypeOperatorNode(SyntaxKind.UniqueKeyword, factory.createKeywordTypeNode(SyntaxKind.SymbolKeyword));
      }
      if (type.flags & TypeFlags.Void) {
        context.approximateLength += 4;
        return factory.createKeywordTypeNode(SyntaxKind.VoidKeyword);
      }
      if (type.flags & TypeFlags.Undefined) {
        context.approximateLength += 9;
        return factory.createKeywordTypeNode(SyntaxKind.UndefinedKeyword);
      }
      if (type.flags & TypeFlags.Null) {
        context.approximateLength += 4;
        return factory.createLiteralTypeNode(factory.createNull());
      }
      if (type.flags & TypeFlags.Never) {
        context.approximateLength += 5;
        return factory.createKeywordTypeNode(SyntaxKind.NeverKeyword);
      }
      if (type.flags & TypeFlags.ESSymbol) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(SyntaxKind.SymbolKeyword);
      }
      if (type.flags & TypeFlags.NonPrimitive) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(SyntaxKind.ObjectKeyword);
      }
      if (isThisTypeParameter(type)) {
        if (context.flags & NodeBuilderFlags.InObjectTypeLiteral) {
          if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowThisInObjectLiteral)) {
            context.encounteredError = true;
          }
          context.tracker.reportInaccessibleThisError?.();
        }
        context.approximateLength += 4;
        return factory.createThisTypeNode();
      }
      if (!inTypeAlias && type.aliasSymbol && (context.flags & NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
        const typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
        if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & SymbolFlags.Class)) return factory.createTypeReferenceNode(factory.createIdentifier(""), typeArgumentNodes);
        if (length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) {
          return factory.createArrayTypeNode(typeArgumentNodes[0]);
        }
        return symbolToTypeNode(type.aliasSymbol, context, SymbolFlags.Type, typeArgumentNodes);
      }
      const objectFlags = getObjectFlags(type);
      if (objectFlags & ObjectFlags.Reference) {
        Debug.assert(!!(type.flags & TypeFlags.Object));
        return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
      }
      if (type.flags & TypeFlags.TypeParameter || objectFlags & ObjectFlags.ClassOrInterface) {
        if (type.flags & TypeFlags.TypeParameter && contains(context.inferTypeParameters, type)) {
          context.approximateLength += symbolName(type.symbol).length + 6;
          let constraintNode;
          const constraint = getConstraintOfTypeParameter(type);
          if (constraint) {
            const inferredConstraint = getInferredTypeParameterConstraint(
              type,
              /*omitTypeReferences*/
              true
            );
            if (!(inferredConstraint && isTypeIdenticalTo(constraint, inferredConstraint))) {
              context.approximateLength += 9;
              constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
            }
          }
          return factory.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, constraintNode));
        }
        if (context.flags & NodeBuilderFlags.GenerateNamesForShadowedTypeParams && type.flags & TypeFlags.TypeParameter) {
          const name2 = typeParameterToName(type, context);
          context.approximateLength += idText(name2).length;
          return factory.createTypeReferenceNode(
            factory.createIdentifier(idText(name2)),
            /*typeArguments*/
            void 0
          );
        }
        if (type.symbol) {
          return symbolToTypeNode(type.symbol, context, SymbolFlags.Type);
        }
        const name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? (type === markerSubTypeForCheck ? "sub-" : "super-") + symbolName(varianceTypeParameter.symbol) : "?";
        return factory.createTypeReferenceNode(
          factory.createIdentifier(name),
          /*typeArguments*/
          void 0
        );
      }
      if (type.flags & TypeFlags.Union && type.origin) {
        type = type.origin;
      }
      if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) {
        const types = type.flags & TypeFlags.Union ? formatUnionTypes(type.types) : type.types;
        if (length(types) === 1) {
          return typeToTypeNodeHelper(types[0], context);
        }
        const typeNodes = mapToTypeNodes(
          types,
          context,
          /*isBareList*/
          true
        );
        if (typeNodes && typeNodes.length > 0) {
          return type.flags & TypeFlags.Union ? factory.createUnionTypeNode(typeNodes) : factory.createIntersectionTypeNode(typeNodes);
        } else {
          if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowEmptyUnionOrIntersection)) {
            context.encounteredError = true;
          }
          return void 0;
        }
      }
      if (objectFlags & (ObjectFlags.Anonymous | ObjectFlags.Mapped)) {
        Debug.assert(!!(type.flags & TypeFlags.Object));
        return createAnonymousTypeNode(type);
      }
      if (type.flags & TypeFlags.Index) {
        const indexedType = type.type;
        context.approximateLength += 6;
        const indexTypeNode = typeToTypeNodeHelper(indexedType, context);
        return factory.createTypeOperatorNode(SyntaxKind.KeyOfKeyword, indexTypeNode);
      }
      if (type.flags & TypeFlags.TemplateLiteral) {
        const texts = type.texts;
        const types = type.types;
        const templateHead = factory.createTemplateHead(texts[0]);
        const templateSpans = factory.createNodeArray(
          map(types, (t, i) => factory.createTemplateLiteralTypeSpan(
            typeToTypeNodeHelper(t, context),
            (i < types.length - 1 ? factory.createTemplateMiddle : factory.createTemplateTail)(texts[i + 1])
          ))
        );
        context.approximateLength += 2;
        return factory.createTemplateLiteralType(templateHead, templateSpans);
      }
      if (type.flags & TypeFlags.StringMapping) {
        const typeNode = typeToTypeNodeHelper(type.type, context);
        return symbolToTypeNode(type.symbol, context, SymbolFlags.Type, [typeNode]);
      }
      if (type.flags & TypeFlags.IndexedAccess) {
        const objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
        const indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
        context.approximateLength += 2;
        return factory.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
      }
      if (type.flags & TypeFlags.Conditional) {
        return visitAndTransformType(type, (type2) => conditionalTypeToTypeNode(type2));
      }
      if (type.flags & TypeFlags.Substitution) {
        const typeNode = typeToTypeNodeHelper(type.baseType, context);
        const noInferSymbol = isNoInferType(type) && getGlobalTypeSymbol(
          "NoInfer",
          /*reportErrors*/
          false
        );
        return noInferSymbol ? symbolToTypeNode(noInferSymbol, context, SymbolFlags.Type, [typeNode]) : typeNode;
      }
      return Debug.fail("Should be unreachable.");
      function conditionalTypeToTypeNode(type2) {
        const checkTypeNode = typeToTypeNodeHelper(type2.checkType, context);
        context.approximateLength += 15;
        if (context.flags & NodeBuilderFlags.GenerateNamesForShadowedTypeParams && type2.root.isDistributive && !(type2.checkType.flags & TypeFlags.TypeParameter)) {
          const newParam = createTypeParameter(createSymbol(SymbolFlags.TypeParameter, "T"));
          const name = typeParameterToName(newParam, context);
          const newTypeVariable = factory.createTypeReferenceNode(name);
          context.approximateLength += 37;
          const newMapper = prependTypeMapping(type2.root.checkType, newParam, type2.mapper);
          const saveInferTypeParameters2 = context.inferTypeParameters;
          context.inferTypeParameters = type2.root.inferTypeParameters;
          const extendsTypeNode2 = typeToTypeNodeHelper(instantiateType(type2.root.extendsType, newMapper), context);
          context.inferTypeParameters = saveInferTypeParameters2;
          const trueTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.trueType), newMapper));
          const falseTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.falseType), newMapper));
          return factory.createConditionalTypeNode(
            checkTypeNode,
            factory.createInferTypeNode(factory.createTypeParameterDeclaration(
              /*modifiers*/
              void 0,
              factory.cloneNode(newTypeVariable.typeName)
            )),
            factory.createConditionalTypeNode(
              factory.createTypeReferenceNode(factory.cloneNode(name)),
              typeToTypeNodeHelper(type2.checkType, context),
              factory.createConditionalTypeNode(newTypeVariable, extendsTypeNode2, trueTypeNode2, falseTypeNode2),
              factory.createKeywordTypeNode(SyntaxKind.NeverKeyword)
            ),
            factory.createKeywordTypeNode(SyntaxKind.NeverKeyword)
          );
        }
        const saveInferTypeParameters = context.inferTypeParameters;
        context.inferTypeParameters = type2.root.inferTypeParameters;
        const extendsTypeNode = typeToTypeNodeHelper(type2.extendsType, context);
        context.inferTypeParameters = saveInferTypeParameters;
        const trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type2));
        const falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type2));
        return factory.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
      }
      function typeToTypeNodeOrCircularityElision(type2) {
        if (type2.flags & TypeFlags.Union) {
          if (context.visitedTypes?.has(getTypeId(type2))) {
            if (!(context.flags & NodeBuilderFlags.AllowAnonymousIdentifier)) {
              context.encounteredError = true;
              context.tracker?.reportCyclicStructureError?.();
            }
            return createElidedInformationPlaceholder(context);
          }
          return visitAndTransformType(type2, (type3) => typeToTypeNodeHelper(type3, context));
        }
        return typeToTypeNodeHelper(type2, context);
      }
      function isMappedTypeHomomorphic(type2) {
        return !!getHomomorphicTypeVariable(type2);
      }
      function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) {
        return !!type2.target && isMappedTypeHomomorphic(type2.target) && !isMappedTypeHomomorphic(type2);
      }
      function createMappedTypeNodeFromType(type2) {
        Debug.assert(!!(type2.flags & TypeFlags.Object));
        const readonlyToken = type2.declaration.readonlyToken ? factory.createToken(type2.declaration.readonlyToken.kind) : void 0;
        const questionToken = type2.declaration.questionToken ? factory.createToken(type2.declaration.questionToken.kind) : void 0;
        let appropriateConstraintTypeNode;
        let newTypeVariable;
        const needsModifierPreservingWrapper = !isMappedTypeWithKeyofConstraintDeclaration(type2) && !(getModifiersTypeFromMappedType(type2).flags & TypeFlags.Unknown) && context.flags & NodeBuilderFlags.GenerateNamesForShadowedTypeParams && !(getConstraintTypeFromMappedType(type2).flags & TypeFlags.TypeParameter && getConstraintOfTypeParameter(getConstraintTypeFromMappedType(type2))?.flags & TypeFlags.Index);
        if (isMappedTypeWithKeyofConstraintDeclaration(type2)) {
          if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & NodeBuilderFlags.GenerateNamesForShadowedTypeParams) {
            const newParam = createTypeParameter(createSymbol(SymbolFlags.TypeParameter, "T"));
            const name = typeParameterToName(newParam, context);
            newTypeVariable = factory.createTypeReferenceNode(name);
          }
          appropriateConstraintTypeNode = factory.createTypeOperatorNode(SyntaxKind.KeyOfKeyword, newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context));
        } else if (needsModifierPreservingWrapper) {
          const newParam = createTypeParameter(createSymbol(SymbolFlags.TypeParameter, "T"));
          const name = typeParameterToName(newParam, context);
          newTypeVariable = factory.createTypeReferenceNode(name);
          appropriateConstraintTypeNode = newTypeVariable;
        } else {
          appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context);
        }
        const typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type2), context, appropriateConstraintTypeNode);
        const nameTypeNode = type2.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type2), context) : void 0;
        const templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type2), !!(getMappedTypeModifiers(type2) & 4 /* IncludeOptional */)), context);
        const mappedTypeNode = factory.createMappedTypeNode(
          readonlyToken,
          typeParameterNode,
          nameTypeNode,
          questionToken,
          templateTypeNode,
          /*members*/
          void 0
        );
        context.approximateLength += 10;
        const result = setEmitFlags(mappedTypeNode, EmitFlags.SingleLine);
        if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & NodeBuilderFlags.GenerateNamesForShadowedTypeParams) {
          const originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode2(context, type2.declaration.typeParameter.constraint.type)) || unknownType, type2.mapper);
          return factory.createConditionalTypeNode(
            typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context),
            factory.createInferTypeNode(factory.createTypeParameterDeclaration(
              /*modifiers*/
              void 0,
              factory.cloneNode(newTypeVariable.typeName),
              originalConstraint.flags & TypeFlags.Unknown ? void 0 : typeToTypeNodeHelper(originalConstraint, context)
            )),
            result,
            factory.createKeywordTypeNode(SyntaxKind.NeverKeyword)
          );
        } else if (needsModifierPreservingWrapper) {
          return factory.createConditionalTypeNode(
            typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context),
            factory.createInferTypeNode(factory.createTypeParameterDeclaration(
              /*modifiers*/
              void 0,
              factory.cloneNode(newTypeVariable.typeName),
              factory.createTypeOperatorNode(SyntaxKind.KeyOfKeyword, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context))
            )),
            result,
            factory.createKeywordTypeNode(SyntaxKind.NeverKeyword)
          );
        }
        return result;
      }
      function createAnonymousTypeNode(type2) {
        const typeId = type2.id;
        const symbol = type2.symbol;
        if (symbol) {
          const isInstantiationExpressionType = !!(getObjectFlags(type2) & ObjectFlags.InstantiationExpressionType);
          if (isInstantiationExpressionType) {
            const instantiationExpressionType = type2;
            const existing = instantiationExpressionType.node;
            if (isTypeQueryNode(existing)) {
              const typeNode = tryReuseExistingNonParameterTypeNode(context, existing, type2);
              if (typeNode) {
                return typeNode;
              }
            }
            if (context.visitedTypes?.has(typeId)) {
              return createElidedInformationPlaceholder(context);
            }
            return visitAndTransformType(type2, createTypeNodeFromObjectType);
          }
          const isInstanceType = isClassInstanceSide(type2) ? SymbolFlags.Type : SymbolFlags.Value;
          if (isJSConstructor(symbol.valueDeclaration)) {
            return symbolToTypeNode(symbol, context, isInstanceType);
          } else if (symbol.flags & SymbolFlags.Class && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration && isClassLike(symbol.valueDeclaration) && context.flags & NodeBuilderFlags.WriteClassExpressionAsTypeLiteral && (!isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(
            symbol,
            context.enclosingDeclaration,
            isInstanceType,
            /*shouldComputeAliasesToMakeVisible*/
            false
          ).accessibility !== SymbolAccessibility.Accessible)) || symbol.flags & (SymbolFlags.Enum | SymbolFlags.ValueModule) || shouldWriteTypeOfFunctionSymbol()) {
            return symbolToTypeNode(symbol, context, isInstanceType);
          } else if (context.visitedTypes?.has(typeId)) {
            const typeAlias = getTypeAliasForTypeLiteral(type2);
            if (typeAlias) {
              return symbolToTypeNode(typeAlias, context, SymbolFlags.Type);
            } else {
              return createElidedInformationPlaceholder(context);
            }
          } else {
            return visitAndTransformType(type2, createTypeNodeFromObjectType);
          }
        } else {
          return createTypeNodeFromObjectType(type2);
        }
        function shouldWriteTypeOfFunctionSymbol() {
          const isStaticMethodSymbol = !!(symbol.flags & SymbolFlags.Method) && // typeof static method
          some(symbol.declarations, (declaration) => isStatic(declaration));
          const isNonLocalFunctionSymbol = !!(symbol.flags & SymbolFlags.Function) && (symbol.parent || // is exported function symbol
          forEach(symbol.declarations, (declaration) => declaration.parent.kind === SyntaxKind.SourceFile || declaration.parent.kind === SyntaxKind.ModuleBlock));
          if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
            return (!!(context.flags & NodeBuilderFlags.UseTypeOfFunction) || context.visitedTypes?.has(typeId)) && // it is type of the symbol uses itself recursively
            (!(context.flags & NodeBuilderFlags.UseStructuralFallback) || isValueSymbolAccessible(symbol, context.enclosingDeclaration));
          }
        }
      }
      function visitAndTransformType(type2, transform) {
        const typeId = type2.id;
        const isConstructorObject = getObjectFlags(type2) & ObjectFlags.Anonymous && type2.symbol && type2.symbol.flags & SymbolFlags.Class;
        const id = getObjectFlags(type2) & ObjectFlags.Reference && type2.node ? "N" + getNodeId(type2.node) : type2.flags & TypeFlags.Conditional ? "N" + getNodeId(type2.root.node) : type2.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type2.symbol) : void 0;
        if (!context.visitedTypes) {
          context.visitedTypes = /* @__PURE__ */ new Set();
        }
        if (id && !context.symbolDepth) {
          context.symbolDepth = /* @__PURE__ */ new Map();
        }
        const links = context.enclosingDeclaration && getNodeLinks(context.enclosingDeclaration);
        const key = `${getTypeId(type2)}|${context.flags}|${context.internalFlags}`;
        if (links) {
          links.serializedTypes ||= /* @__PURE__ */ new Map();
        }
        const cachedResult = links?.serializedTypes?.get(key);
        if (cachedResult) {
          cachedResult.trackedSymbols?.forEach(
            ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol(
              symbol,
              enclosingDeclaration,
              meaning
            )
          );
          if (cachedResult.truncating) {
            context.truncating = true;
          }
          context.approximateLength += cachedResult.addedLength;
          return deepCloneOrReuseNode(cachedResult.node);
        }
        let depth;
        if (id) {
          depth = context.symbolDepth.get(id) || 0;
          if (depth > 10) {
            return createElidedInformationPlaceholder(context);
          }
          context.symbolDepth.set(id, depth + 1);
        }
        context.visitedTypes.add(typeId);
        const prevTrackedSymbols = context.trackedSymbols;
        context.trackedSymbols = void 0;
        const startLength = context.approximateLength;
        const result = transform(type2);
        const addedLength = context.approximateLength - startLength;
        if (!context.reportedDiagnostic && !context.encounteredError) {
          links?.serializedTypes?.set(key, {
            node: result,
            truncating: context.truncating,
            addedLength,
            trackedSymbols: context.trackedSymbols
          });
        }
        context.visitedTypes.delete(typeId);
        if (id) {
          context.symbolDepth.set(id, depth);
        }
        context.trackedSymbols = prevTrackedSymbols;
        return result;
        function deepCloneOrReuseNode(node) {
          if (!nodeIsSynthesized(node) && getParseTreeNode(node) === node) {
            return node;
          }
          return setTextRange(context, factory.cloneNode(visitEachChildWorker(
            node,
            deepCloneOrReuseNode,
            /*context*/
            void 0,
            deepCloneOrReuseNodes,
            deepCloneOrReuseNode
          )), node);
        }
        function deepCloneOrReuseNodes(nodes, visitor, test, start, count) {
          if (nodes && nodes.length === 0) {
            return setTextRangeWorker(factory.createNodeArray(
              /*elements*/
              void 0,
              nodes.hasTrailingComma
            ), nodes);
          }
          return visitNodes(nodes, visitor, test, start, count);
        }
      }
      function createTypeNodeFromObjectType(type2) {
        if (isGenericMappedType(type2) || type2.containsError) {
          return createMappedTypeNodeFromType(type2);
        }
        const resolved = resolveStructuredTypeMembers(type2);
        if (!resolved.properties.length && !resolved.indexInfos.length) {
          if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
            context.approximateLength += 2;
            return setEmitFlags(factory.createTypeLiteralNode(
              /*members*/
              void 0
            ), EmitFlags.SingleLine);
          }
          if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
            const signature = resolved.callSignatures[0];
            const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context);
            return signatureNode;
          }
          if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
            const signature = resolved.constructSignatures[0];
            const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructorType, context);
            return signatureNode;
          }
        }
        const abstractSignatures = filter(resolved.constructSignatures, (signature) => !!(signature.flags & SignatureFlags.Abstract));
        if (some(abstractSignatures)) {
          const types = map(abstractSignatures, (s) => getOrCreateTypeFromSignature(s));
          const typeElementCount = resolved.callSignatures.length + (resolved.constructSignatures.length - abstractSignatures.length) + resolved.indexInfos.length + // exclude `prototype` when writing a class expression as a type literal, as per
          // the logic in `createTypeNodesFromResolvedType`.
          (context.flags & NodeBuilderFlags.WriteClassExpressionAsTypeLiteral ? countWhere(resolved.properties, (p) => !(p.flags & SymbolFlags.Prototype)) : length(resolved.properties));
          if (typeElementCount) {
            types.push(getResolvedTypeWithoutAbstractConstructSignatures(resolved));
          }
          return typeToTypeNodeHelper(getIntersectionType(types), context);
        }
        const restoreFlags = saveRestoreFlags(context);
        context.flags |= NodeBuilderFlags.InObjectTypeLiteral;
        const members = createTypeNodesFromResolvedType(resolved);
        restoreFlags();
        const typeLiteralNode = factory.createTypeLiteralNode(members);
        context.approximateLength += 2;
        setEmitFlags(typeLiteralNode, context.flags & NodeBuilderFlags.MultilineObjectLiterals ? 0 : EmitFlags.SingleLine);
        return typeLiteralNode;
      }
      function typeReferenceToTypeNode(type2) {
        let typeArguments = getTypeArguments(type2);
        if (type2.target === globalArrayType || type2.target === globalReadonlyArrayType) {
          if (context.flags & NodeBuilderFlags.WriteArrayAsGenericType) {
            const typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
            return factory.createTypeReferenceNode(type2.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
          }
          const elementType = typeToTypeNodeHelper(typeArguments[0], context);
          const arrayType = factory.createArrayTypeNode(elementType);
          return type2.target === globalArrayType ? arrayType : factory.createTypeOperatorNode(SyntaxKind.ReadonlyKeyword, arrayType);
        } else if (type2.target.objectFlags & ObjectFlags.Tuple) {
          typeArguments = sameMap(typeArguments, (t, i) => removeMissingType(t, !!(type2.target.elementFlags[i] & ElementFlags.Optional)));
          if (typeArguments.length > 0) {
            const arity = getTypeReferenceArity(type2);
            const tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
            if (tupleConstituentNodes) {
              const { labeledElementDeclarations } = type2.target;
              for (let i = 0; i < tupleConstituentNodes.length; i++) {
                const flags = type2.target.elementFlags[i];
                const labeledElementDeclaration = labeledElementDeclarations?.[i];
                if (labeledElementDeclaration) {
                  tupleConstituentNodes[i] = factory.createNamedTupleMember(
                    flags & ElementFlags.Variable ? factory.createToken(SyntaxKind.DotDotDotToken) : void 0,
                    factory.createIdentifier(unescapeLeadingUnderscores(getTupleElementLabel(labeledElementDeclaration))),
                    flags & ElementFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : void 0,
                    flags & ElementFlags.Rest ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]
                  );
                } else {
                  tupleConstituentNodes[i] = flags & ElementFlags.Variable ? factory.createRestTypeNode(flags & ElementFlags.Rest ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) : flags & ElementFlags.Optional ? factory.createOptionalTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i];
                }
              }
              const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode(tupleConstituentNodes), EmitFlags.SingleLine);
              return type2.target.readonly ? factory.createTypeOperatorNode(SyntaxKind.ReadonlyKeyword, tupleTypeNode) : tupleTypeNode;
            }
          }
          if (context.encounteredError || context.flags & NodeBuilderFlags.AllowEmptyTuple) {
            const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode([]), EmitFlags.SingleLine);
            return type2.target.readonly ? factory.createTypeOperatorNode(SyntaxKind.ReadonlyKeyword, tupleTypeNode) : tupleTypeNode;
          }
          context.encounteredError = true;
          return void 0;
        } else if (context.flags & NodeBuilderFlags.WriteClassExpressionAsTypeLiteral && type2.symbol.valueDeclaration && isClassLike(type2.symbol.valueDeclaration) && !isValueSymbolAccessible(type2.symbol, context.enclosingDeclaration)) {
          return createAnonymousTypeNode(type2);
        } else {
          const outerTypeParameters = type2.target.outerTypeParameters;
          let i = 0;
          let resultType;
          if (outerTypeParameters) {
            const length2 = outerTypeParameters.length;
            while (i < length2) {
              const start = i;
              const parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
              do {
                i++;
              } while (i < length2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
              if (!rangeEquals(outerTypeParameters, typeArguments, start, i)) {
                const typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
                const restoreFlags2 = saveRestoreFlags(context);
                context.flags |= NodeBuilderFlags.ForbidIndexedAccessSymbolReferences;
                const ref = symbolToTypeNode(parent, context, SymbolFlags.Type, typeArgumentSlice);
                restoreFlags2();
                resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
              }
            }
          }
          let typeArgumentNodes;
          if (typeArguments.length > 0) {
            let typeParameterCount = 0;
            if (type2.target.typeParameters) {
              typeParameterCount = Math.min(type2.target.typeParameters.length, typeArguments.length);
              if (isReferenceToType(type2, getGlobalIterableType(
                /*reportErrors*/
                false
              )) || isReferenceToType(type2, getGlobalIterableIteratorType(
                /*reportErrors*/
                false
              )) || isReferenceToType(type2, getGlobalAsyncIterableType(
                /*reportErrors*/
                false
              )) || isReferenceToType(type2, getGlobalAsyncIterableIteratorType(
                /*reportErrors*/
                false
              ))) {
                if (!type2.node || !isTypeReferenceNode(type2.node) || !type2.node.typeArguments || type2.node.typeArguments.length < typeParameterCount) {
                  while (typeParameterCount > 0) {
                    const typeArgument = typeArguments[typeParameterCount - 1];
                    const typeParameter = type2.target.typeParameters[typeParameterCount - 1];
                    const defaultType = getDefaultFromTypeParameter(typeParameter);
                    if (!defaultType || !isTypeIdenticalTo(typeArgument, defaultType)) {
                      break;
                    }
                    typeParameterCount--;
                  }
                }
              }
            }
            typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
          }
          const restoreFlags = saveRestoreFlags(context);
          context.flags |= NodeBuilderFlags.ForbidIndexedAccessSymbolReferences;
          const finalRef = symbolToTypeNode(type2.symbol, context, SymbolFlags.Type, typeArgumentNodes);
          restoreFlags();
          return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
        }
      }
      function appendReferenceToType(root, ref) {
        if (isImportTypeNode(root)) {
          let typeArguments = root.typeArguments;
          let qualifier = root.qualifier;
          if (qualifier) {
            if (isIdentifier(qualifier)) {
              if (typeArguments !== getIdentifierTypeArguments(qualifier)) {
                qualifier = setIdentifierTypeArguments(factory.cloneNode(qualifier), typeArguments);
              }
            } else {
              if (typeArguments !== getIdentifierTypeArguments(qualifier.right)) {
                qualifier = factory.updateQualifiedName(qualifier, qualifier.left, setIdentifierTypeArguments(factory.cloneNode(qualifier.right), typeArguments));
              }
            }
          }
          typeArguments = ref.typeArguments;
          const ids = getAccessStack(ref);
          for (const id of ids) {
            qualifier = qualifier ? factory.createQualifiedName(qualifier, id) : id;
          }
          return factory.updateImportTypeNode(
            root,
            root.argument,
            root.attributes,
            qualifier,
            typeArguments,
            root.isTypeOf
          );
        } else {
          let typeArguments = root.typeArguments;
          let typeName = root.typeName;
          if (isIdentifier(typeName)) {
            if (typeArguments !== getIdentifierTypeArguments(typeName)) {
              typeName = setIdentifierTypeArguments(factory.cloneNode(typeName), typeArguments);
            }
          } else {
            if (typeArguments !== getIdentifierTypeArguments(typeName.right)) {
              typeName = factory.updateQualifiedName(typeName, typeName.left, setIdentifierTypeArguments(factory.cloneNode(typeName.right), typeArguments));
            }
          }
          typeArguments = ref.typeArguments;
          const ids = getAccessStack(ref);
          for (const id of ids) {
            typeName = factory.createQualifiedName(typeName, id);
          }
          return factory.updateTypeReferenceNode(
            root,
            typeName,
            typeArguments
          );
        }
      }
      function getAccessStack(ref) {
        let state = ref.typeName;
        const ids = [];
        while (!isIdentifier(state)) {
          ids.unshift(state.right);
          state = state.left;
        }
        ids.unshift(state);
        return ids;
      }
      function createTypeNodesFromResolvedType(resolvedType) {
        if (checkTruncationLength(context)) {
          return [factory.createPropertySignature(
            /*modifiers*/
            void 0,
            "...",
            /*questionToken*/
            void 0,
            /*type*/
            void 0
          )];
        }
        const typeElements = [];
        for (const signature of resolvedType.callSignatures) {
          typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.CallSignature, context));
        }
        for (const signature of resolvedType.constructSignatures) {
          if (signature.flags & SignatureFlags.Abstract) continue;
          typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructSignature, context));
        }
        for (const info of resolvedType.indexInfos) {
          typeElements.push(indexInfoToIndexSignatureDeclarationHelper(info, context, resolvedType.objectFlags & ObjectFlags.ReverseMapped ? createElidedInformationPlaceholder(context) : void 0));
        }
        const properties = resolvedType.properties;
        if (!properties) {
          return typeElements;
        }
        let i = 0;
        for (const propertySymbol of properties) {
          i++;
          if (context.flags & NodeBuilderFlags.WriteClassExpressionAsTypeLiteral) {
            if (propertySymbol.flags & SymbolFlags.Prototype) {
              continue;
            }
            if (getDeclarationModifierFlagsFromSymbol(propertySymbol) & (ModifierFlags.Private | ModifierFlags.Protected) && context.tracker.reportPrivateInBaseOfClassExpression) {
              context.tracker.reportPrivateInBaseOfClassExpression(unescapeLeadingUnderscores(propertySymbol.escapedName));
            }
          }
          if (checkTruncationLength(context) && i + 2 < properties.length - 1) {
            typeElements.push(factory.createPropertySignature(
              /*modifiers*/
              void 0,
              `... ${properties.length - i} more ...`,
              /*questionToken*/
              void 0,
              /*type*/
              void 0
            ));
            addPropertyToElementList(properties[properties.length - 1], context, typeElements);
            break;
          }
          addPropertyToElementList(propertySymbol, context, typeElements);
        }
        return typeElements.length ? typeElements : void 0;
      }
    }
    function createElidedInformationPlaceholder(context) {
      context.approximateLength += 3;
      if (!(context.flags & NodeBuilderFlags.NoTruncation)) {
        return factory.createTypeReferenceNode(
          factory.createIdentifier("..."),
          /*typeArguments*/
          void 0
        );
      }
      return factory.createKeywordTypeNode(SyntaxKind.AnyKeyword);
    }
    function shouldUsePlaceholderForProperty(propertySymbol, context) {
      const depth = 3;
      return !!(getCheckFlags(propertySymbol) & CheckFlags.ReverseMapped) && (contains(context.reverseMappedStack, propertySymbol) || context.reverseMappedStack?.[0] && !(getObjectFlags(last(context.reverseMappedStack).links.propertyType) & ObjectFlags.Anonymous) || isDeeplyNestedReverseMappedTypeProperty());
      function isDeeplyNestedReverseMappedTypeProperty() {
        if ((context.reverseMappedStack?.length ?? 0) < depth) {
          return false;
        }
        for (let i = 0; i < depth; i++) {
          const prop = context.reverseMappedStack[context.reverseMappedStack.length - 1 - i];
          if (prop.links.mappedType.symbol !== propertySymbol.links.mappedType.symbol) {
            return false;
          }
        }
        return true;
      }
    }
    function addPropertyToElementList(propertySymbol, context, typeElements) {
      const propertyIsReverseMapped = !!(getCheckFlags(propertySymbol) & CheckFlags.ReverseMapped);
      const propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getNonMissingTypeOfSymbol(propertySymbol);
      const saveEnclosingDeclaration = context.enclosingDeclaration;
      context.enclosingDeclaration = void 0;
      if (context.tracker.canTrackSymbol && isLateBoundName(propertySymbol.escapedName)) {
        if (propertySymbol.declarations) {
          const decl = first(propertySymbol.declarations);
          if (hasLateBindableName(decl)) {
            if (isBinaryExpression(decl)) {
              const name = getNameOfDeclaration(decl);
              if (name && isElementAccessExpression(name) && isPropertyAccessEntityNameExpression(name.argumentExpression)) {
                trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
              }
            } else {
              trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
            }
          }
        } else {
          context.tracker.reportNonSerializableProperty(symbolToString(propertySymbol));
        }
      }
      context.enclosingDeclaration = propertySymbol.valueDeclaration || propertySymbol.declarations?.[0] || saveEnclosingDeclaration;
      const propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
      context.enclosingDeclaration = saveEnclosingDeclaration;
      context.approximateLength += symbolName(propertySymbol).length + 1;
      if (propertySymbol.flags & SymbolFlags.Accessor) {
        const writeType = getWriteTypeOfSymbol(propertySymbol);
        if (propertyType !== writeType && !isErrorType(propertyType) && !isErrorType(writeType)) {
          const getterDeclaration = getDeclarationOfKind(propertySymbol, SyntaxKind.GetAccessor);
          const getterSignature = getSignatureFromDeclaration(getterDeclaration);
          typeElements.push(
            setCommentRange(
              context,
              signatureToSignatureDeclarationHelper(getterSignature, SyntaxKind.GetAccessor, context, { name: propertyName }),
              getterDeclaration
            )
          );
          const setterDeclaration = getDeclarationOfKind(propertySymbol, SyntaxKind.SetAccessor);
          const setterSignature = getSignatureFromDeclaration(setterDeclaration);
          typeElements.push(
            setCommentRange(
              context,
              signatureToSignatureDeclarationHelper(setterSignature, SyntaxKind.SetAccessor, context, { name: propertyName }),
              setterDeclaration
            )
          );
          return;
        }
      }
      const optionalToken = propertySymbol.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : void 0;
      if (propertySymbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
        const signatures = getSignaturesOfType(filterType(propertyType, (t) => !(t.flags & TypeFlags.Undefined)), SignatureKind.Call);
        for (const signature of signatures) {
          const methodDeclaration = signatureToSignatureDeclarationHelper(signature, SyntaxKind.MethodSignature, context, { name: propertyName, questionToken: optionalToken });
          typeElements.push(preserveCommentsOn(methodDeclaration));
        }
        if (signatures.length || !optionalToken) {
          return;
        }
      }
      let propertyTypeNode;
      if (shouldUsePlaceholderForProperty(propertySymbol, context)) {
        propertyTypeNode = createElidedInformationPlaceholder(context);
      } else {
        if (propertyIsReverseMapped) {
          context.reverseMappedStack ||= [];
          context.reverseMappedStack.push(propertySymbol);
        }
        propertyTypeNode = propertyType ? serializeTypeForDeclaration(
          context,
          /*declaration*/
          void 0,
          propertyType,
          propertySymbol
        ) : factory.createKeywordTypeNode(SyntaxKind.AnyKeyword);
        if (propertyIsReverseMapped) {
          context.reverseMappedStack.pop();
        }
      }
      const modifiers = isReadonlySymbol(propertySymbol) ? [factory.createToken(SyntaxKind.ReadonlyKeyword)] : void 0;
      if (modifiers) {
        context.approximateLength += 9;
      }
      const propertySignature = factory.createPropertySignature(
        modifiers,
        propertyName,
        optionalToken,
        propertyTypeNode
      );
      typeElements.push(preserveCommentsOn(propertySignature));
      function preserveCommentsOn(node) {
        const jsdocPropertyTag = propertySymbol.declarations?.find((d) => d.kind === SyntaxKind.JSDocPropertyTag);
        if (jsdocPropertyTag) {
          const commentText = getTextOfJSDocComment(jsdocPropertyTag.comment);
          if (commentText) {
            setSyntheticLeadingComments(node, [{ kind: SyntaxKind.MultiLineCommentTrivia, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
          }
        } else if (propertySymbol.valueDeclaration) {
          setCommentRange(context, node, propertySymbol.valueDeclaration);
        }
        return node;
      }
    }
    function setCommentRange(context, node, range) {
      if (context.enclosingFile && context.enclosingFile === getSourceFileOfNode(range)) {
        return setCommentRangeWorker(node, range);
      }
      return node;
    }
    function mapToTypeNodes(types, context, isBareList) {
      if (some(types)) {
        if (checkTruncationLength(context)) {
          if (!isBareList) {
            return [factory.createTypeReferenceNode(
              "...",
              /*typeArguments*/
              void 0
            )];
          } else if (types.length > 2) {
            return [
              typeToTypeNodeHelper(types[0], context),
              factory.createTypeReferenceNode(
                `... ${types.length - 2} more ...`,
                /*typeArguments*/
                void 0
              ),
              typeToTypeNodeHelper(types[types.length - 1], context)
            ];
          }
        }
        const mayHaveNameCollisions = !(context.flags & NodeBuilderFlags.UseFullyQualifiedType);
        const seenNames = mayHaveNameCollisions ? createMultiMap() : void 0;
        const result = [];
        let i = 0;
        for (const type of types) {
          i++;
          if (checkTruncationLength(context) && i + 2 < types.length - 1) {
            result.push(factory.createTypeReferenceNode(
              `... ${types.length - i} more ...`,
              /*typeArguments*/
              void 0
            ));
            const typeNode2 = typeToTypeNodeHelper(types[types.length - 1], context);
            if (typeNode2) {
              result.push(typeNode2);
            }
            break;
          }
          context.approximateLength += 2;
          const typeNode = typeToTypeNodeHelper(type, context);
          if (typeNode) {
            result.push(typeNode);
            if (seenNames && isIdentifierTypeReference(typeNode)) {
              seenNames.add(typeNode.typeName.escapedText, [type, result.length - 1]);
            }
          }
        }
        if (seenNames) {
          const restoreFlags = saveRestoreFlags(context);
          context.flags |= NodeBuilderFlags.UseFullyQualifiedType;
          seenNames.forEach((types2) => {
            if (!arrayIsHomogeneous(types2, ([a], [b]) => typesAreSameReference(a, b))) {
              for (const [type, resultIndex] of types2) {
                result[resultIndex] = typeToTypeNodeHelper(type, context);
              }
            }
          });
          restoreFlags();
        }
        return result;
      }
    }
    function typesAreSameReference(a, b) {
      return a === b || !!a.symbol && a.symbol === b.symbol || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
    }
    function indexInfoToIndexSignatureDeclarationHelper(indexInfo, context, typeNode) {
      const name = getNameFromIndexInfo(indexInfo) || "x";
      const indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context);
      const indexingParameter = factory.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        name,
        /*questionToken*/
        void 0,
        indexerTypeNode,
        /*initializer*/
        void 0
      );
      if (!typeNode) {
        typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
      }
      if (!indexInfo.type && !(context.flags & NodeBuilderFlags.AllowEmptyIndexInfoType)) {
        context.encounteredError = true;
      }
      context.approximateLength += name.length + 4;
      return factory.createIndexSignature(
        indexInfo.isReadonly ? [factory.createToken(SyntaxKind.ReadonlyKeyword)] : void 0,
        [indexingParameter],
        typeNode
      );
    }
    function signatureToSignatureDeclarationHelper(signature, kind, context, options) {
      let typeParameters;
      let typeArguments;
      const expandedParams = getExpandedParameters(
        signature,
        /*skipUnionExpanding*/
        true
      )[0];
      const cleanup = enterNewScope(context, signature.declaration, expandedParams, signature.typeParameters, signature.parameters, signature.mapper);
      context.approximateLength += 3;
      if (context.flags & NodeBuilderFlags.WriteTypeArgumentsOfSignature && signature.target && signature.mapper && signature.target.typeParameters) {
        typeArguments = signature.target.typeParameters.map((parameter) => typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context));
      } else {
        typeParameters = signature.typeParameters && signature.typeParameters.map((parameter) => typeParameterToDeclaration(parameter, context));
      }
      const restoreFlags = saveRestoreFlags(context);
      context.flags &= ~NodeBuilderFlags.SuppressAnyReturnType;
      const parameters = (some(expandedParams, (p) => p !== expandedParams[expandedParams.length - 1] && !!(getCheckFlags(p) & CheckFlags.RestParameter)) ? signature.parameters : expandedParams).map((parameter) => symbolToParameterDeclaration(parameter, context, kind === SyntaxKind.Constructor));
      const thisParameter = context.flags & NodeBuilderFlags.OmitThisParameter ? void 0 : tryGetThisParameterDeclaration(signature, context);
      if (thisParameter) {
        parameters.unshift(thisParameter);
      }
      restoreFlags();
      const returnTypeNode = serializeReturnTypeForSignature(context, signature);
      let modifiers = options?.modifiers;
      if (kind === SyntaxKind.ConstructorType && signature.flags & SignatureFlags.Abstract) {
        const flags = modifiersToFlags(modifiers);
        modifiers = factory.createModifiersFromModifierFlags(flags | ModifierFlags.Abstract);
      }
      const node = kind === SyntaxKind.CallSignature ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === SyntaxKind.ConstructSignature ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === SyntaxKind.MethodSignature ? factory.createMethodSignature(modifiers, options?.name ?? factory.createIdentifier(""), options?.questionToken, typeParameters, parameters, returnTypeNode) : kind === SyntaxKind.MethodDeclaration ? factory.createMethodDeclaration(
        modifiers,
        /*asteriskToken*/
        void 0,
        options?.name ?? factory.createIdentifier(""),
        /*questionToken*/
        void 0,
        typeParameters,
        parameters,
        returnTypeNode,
        /*body*/
        void 0
      ) : kind === SyntaxKind.Constructor ? factory.createConstructorDeclaration(
        modifiers,
        parameters,
        /*body*/
        void 0
      ) : kind === SyntaxKind.GetAccessor ? factory.createGetAccessorDeclaration(
        modifiers,
        options?.name ?? factory.createIdentifier(""),
        parameters,
        returnTypeNode,
        /*body*/
        void 0
      ) : kind === SyntaxKind.SetAccessor ? factory.createSetAccessorDeclaration(
        modifiers,
        options?.name ?? factory.createIdentifier(""),
        parameters,
        /*body*/
        void 0
      ) : kind === SyntaxKind.IndexSignature ? factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === SyntaxKind.JSDocFunctionType ? factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === SyntaxKind.FunctionType ? factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === SyntaxKind.ConstructorType ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === SyntaxKind.FunctionDeclaration ? factory.createFunctionDeclaration(
        modifiers,
        /*asteriskToken*/
        void 0,
        options?.name ? cast(options.name, isIdentifier) : factory.createIdentifier(""),
        typeParameters,
        parameters,
        returnTypeNode,
        /*body*/
        void 0
      ) : kind === SyntaxKind.FunctionExpression ? factory.createFunctionExpression(
        modifiers,
        /*asteriskToken*/
        void 0,
        options?.name ? cast(options.name, isIdentifier) : factory.createIdentifier(""),
        typeParameters,
        parameters,
        returnTypeNode,
        factory.createBlock([])
      ) : kind === SyntaxKind.ArrowFunction ? factory.createArrowFunction(
        modifiers,
        typeParameters,
        parameters,
        returnTypeNode,
        /*equalsGreaterThanToken*/
        void 0,
        factory.createBlock([])
      ) : Debug.assertNever(kind);
      if (typeArguments) {
        node.typeArguments = factory.createNodeArray(typeArguments);
      }
      if (signature.declaration?.kind === SyntaxKind.JSDocSignature && signature.declaration.parent.kind === SyntaxKind.JSDocOverloadTag) {
        const comment = getTextOfNode(
          signature.declaration.parent.parent,
          /*includeTrivia*/
          true
        ).slice(2, -2).split(/\r\n|\n|\r/).map((line) => line.replace(/^\s+/, " ")).join("\n");
        addSyntheticLeadingComment(
          node,
          SyntaxKind.MultiLineCommentTrivia,
          comment,
          /*hasTrailingNewLine*/
          true
        );
      }
      cleanup?.();
      return node;
    }
    function isNewScopeNode(node) {
      return isFunctionLike(node) || isJSDocSignature(node) || isMappedTypeNode(node);
    }
    function getTypeParametersInScope(node) {
      return isFunctionLike(node) || isJSDocSignature(node) ? getSignatureFromDeclaration(node).typeParameters : isConditionalTypeNode(node) ? getInferTypeParameters(node) : [getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))];
    }
    function getParametersInScope(node) {
      return isFunctionLike(node) || isJSDocSignature(node) ? getSignatureFromDeclaration(node).parameters : void 0;
    }
    function enterNewScope(context, declaration, expandedParams, typeParameters, originalParameters, mapper) {
      const cleanupContext = cloneNodeBuilderContext(context);
      let cleanupParams;
      let cleanupTypeParams;
      const oldEnclosingDecl = context.enclosingDeclaration;
      const oldMapper = context.mapper;
      if (mapper) {
        context.mapper = mapper;
      }
      if (context.enclosingDeclaration && declaration) {
        let pushFakeScope = function(kind, addAll) {
          Debug.assert(context.enclosingDeclaration);
          let existingFakeScope;
          if (getNodeLinks(context.enclosingDeclaration).fakeScopeForSignatureDeclaration === kind) {
            existingFakeScope = context.enclosingDeclaration;
          } else if (context.enclosingDeclaration.parent && getNodeLinks(context.enclosingDeclaration.parent).fakeScopeForSignatureDeclaration === kind) {
            existingFakeScope = context.enclosingDeclaration.parent;
          }
          Debug.assertOptionalNode(existingFakeScope, isBlock);
          const locals = existingFakeScope?.locals ?? createSymbolTable();
          let newLocals;
          let oldLocals;
          addAll((name, symbol) => {
            if (existingFakeScope) {
              const oldSymbol = locals.get(name);
              if (!oldSymbol) {
                newLocals = append(newLocals, name);
              } else {
                oldLocals = append(oldLocals, { name, oldSymbol });
              }
            }
            locals.set(name, symbol);
          });
          if (!existingFakeScope) {
            const fakeScope = factory.createBlock(emptyArray);
            getNodeLinks(fakeScope).fakeScopeForSignatureDeclaration = kind;
            fakeScope.locals = locals;
            setParent(fakeScope, context.enclosingDeclaration);
            context.enclosingDeclaration = fakeScope;
          } else {
            return function undo() {
              forEach(newLocals, (s) => locals.delete(s));
              forEach(oldLocals, (s) => locals.set(s.name, s.oldSymbol));
            };
          }
        };
        cleanupParams = !some(expandedParams) ? void 0 : pushFakeScope(
          "params",
          (add) => {
            if (!expandedParams) return;
            for (let pIndex = 0; pIndex < expandedParams.length; pIndex++) {
              const param = expandedParams[pIndex];
              const originalParam = originalParameters?.[pIndex];
              if (originalParameters && originalParam !== param) {
                add(param.escapedName, unknownSymbol);
                if (originalParam) {
                  add(originalParam.escapedName, unknownSymbol);
                }
              } else if (!forEach(param.declarations, (d) => {
                if (isParameter(d) && isBindingPattern(d.name)) {
                  bindPattern(d.name);
                  return true;
                }
                return void 0;
                function bindPattern(p) {
                  forEach(p.elements, (e) => {
                    switch (e.kind) {
                      case SyntaxKind.OmittedExpression:
                        return;
                      case SyntaxKind.BindingElement:
                        return bindElement(e);
                      default:
                        return Debug.assertNever(e);
                    }
                  });
                }
                function bindElement(e) {
                  if (isBindingPattern(e.name)) {
                    return bindPattern(e.name);
                  }
                  const symbol = getSymbolOfDeclaration(e);
                  add(symbol.escapedName, symbol);
                }
              })) {
                add(param.escapedName, param);
              }
            }
          }
        );
        if (context.flags & NodeBuilderFlags.GenerateNamesForShadowedTypeParams && some(typeParameters)) {
          cleanupTypeParams = pushFakeScope(
            "typeParams",
            (add) => {
              for (const typeParam of typeParameters ?? emptyArray) {
                const typeParamName = typeParameterToName(typeParam, context).escapedText;
                add(typeParamName, typeParam.symbol);
              }
            }
          );
        }
      }
      return () => {
        cleanupParams?.();
        cleanupTypeParams?.();
        cleanupContext();
        context.enclosingDeclaration = oldEnclosingDecl;
        context.mapper = oldMapper;
      };
    }
    function tryGetThisParameterDeclaration(signature, context) {
      if (signature.thisParameter) {
        return symbolToParameterDeclaration(signature.thisParameter, context);
      }
      if (signature.declaration && isInJSFile(signature.declaration)) {
        const thisTag = getJSDocThisTag(signature.declaration);
        if (thisTag && thisTag.typeExpression) {
          return factory.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            "this",
            /*questionToken*/
            void 0,
            typeToTypeNodeHelper(getTypeFromTypeNode2(context, thisTag.typeExpression), context)
          );
        }
      }
    }
    function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
      const restoreFlags = saveRestoreFlags(context);
      context.flags &= ~NodeBuilderFlags.WriteTypeParametersInQualifiedName;
      const modifiers = factory.createModifiersFromModifierFlags(getTypeParameterModifiers(type));
      const name = typeParameterToName(type, context);
      const defaultParameter = getDefaultFromTypeParameter(type);
      const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
      restoreFlags();
      return factory.createTypeParameterDeclaration(modifiers, name, constraintNode, defaultParameterNode);
    }
    function typeToTypeNodeHelperWithPossibleReusableTypeNode(type, typeNode, context) {
      return typeNode && tryReuseExistingNonParameterTypeNode(context, typeNode, type) || typeToTypeNodeHelper(type, context);
    }
    function typeParameterToDeclaration(type, context, constraint = getConstraintOfTypeParameter(type)) {
      const constraintNode = constraint && typeToTypeNodeHelperWithPossibleReusableTypeNode(constraint, getConstraintDeclaration(type), context);
      return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
    }
    function typePredicateToTypePredicateNodeHelper(typePredicate, context) {
      const assertsModifier = typePredicate.kind === TypePredicateKind.AssertsThis || typePredicate.kind === TypePredicateKind.AssertsIdentifier ? factory.createToken(SyntaxKind.AssertsKeyword) : void 0;
      const parameterName = typePredicate.kind === TypePredicateKind.Identifier || typePredicate.kind === TypePredicateKind.AssertsIdentifier ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), EmitFlags.NoAsciiEscaping) : factory.createThisTypeNode();
      const typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
      return factory.createTypePredicateNode(assertsModifier, parameterName, typeNode);
    }
    function getEffectiveParameterDeclaration(parameterSymbol) {
      const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter);
      if (parameterDeclaration) {
        return parameterDeclaration;
      }
      if (!isTransientSymbol(parameterSymbol)) {
        return getDeclarationOfKind(parameterSymbol, SyntaxKind.JSDocParameterTag);
      }
    }
    function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
      const parameterDeclaration = getEffectiveParameterDeclaration(parameterSymbol);
      const parameterType = getTypeOfSymbol(parameterSymbol);
      const parameterTypeNode = serializeTypeForDeclaration(context, parameterDeclaration, parameterType, parameterSymbol);
      const modifiers = !(context.flags & NodeBuilderFlags.OmitParameterModifiers) && preserveModifierFlags && parameterDeclaration && canHaveModifiers(parameterDeclaration) ? map(getModifiers(parameterDeclaration), factory.cloneNode) : void 0;
      const isRest = parameterDeclaration && isRestParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & CheckFlags.RestParameter;
      const dotDotDotToken = isRest ? factory.createToken(SyntaxKind.DotDotDotToken) : void 0;
      const name = parameterToParameterDeclarationName(parameterSymbol, parameterDeclaration, context);
      const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & CheckFlags.OptionalParameter;
      const questionToken = isOptional ? factory.createToken(SyntaxKind.QuestionToken) : void 0;
      const parameterNode = factory.createParameterDeclaration(
        modifiers,
        dotDotDotToken,
        name,
        questionToken,
        parameterTypeNode,
        /*initializer*/
        void 0
      );
      context.approximateLength += symbolName(parameterSymbol).length + 3;
      return parameterNode;
    }
    function parameterToParameterDeclarationName(parameterSymbol, parameterDeclaration, context) {
      return parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === SyntaxKind.Identifier ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), EmitFlags.NoAsciiEscaping) : parameterDeclaration.name.kind === SyntaxKind.QualifiedName ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), EmitFlags.NoAsciiEscaping) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol);
      function cloneBindingName(node) {
        return elideInitializerAndSetEmitFlags(node);
        function elideInitializerAndSetEmitFlags(node2) {
          if (context.tracker.canTrackSymbol && isComputedPropertyName(node2) && isLateBindableName(node2)) {
            trackComputedName(node2.expression, context.enclosingDeclaration, context);
          }
          let visited = visitEachChildWorker(
            node2,
            elideInitializerAndSetEmitFlags,
            /*context*/
            void 0,
            /*nodesVisitor*/
            void 0,
            elideInitializerAndSetEmitFlags
          );
          if (isBindingElement(visited)) {
            visited = factory.updateBindingElement(
              visited,
              visited.dotDotDotToken,
              visited.propertyName,
              visited.name,
              /*initializer*/
              void 0
            );
          }
          if (!nodeIsSynthesized(visited)) {
            visited = factory.cloneNode(visited);
          }
          return setEmitFlags(visited, EmitFlags.SingleLine | EmitFlags.NoAsciiEscaping);
        }
      }
    }
    function trackComputedName(accessExpression, enclosingDeclaration, context) {
      if (!context.tracker.canTrackSymbol) return;
      const firstIdentifier = getFirstIdentifier(accessExpression);
      const name = resolveName(
        firstIdentifier,
        firstIdentifier.escapedText,
        SymbolFlags.Value | SymbolFlags.ExportValue,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        true
      );
      if (name) {
        context.tracker.trackSymbol(name, enclosingDeclaration, SymbolFlags.Value);
      }
    }
    function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
      context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning);
      return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
    }
    function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
      let chain;
      const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter;
      if (!isTypeParameter && (context.enclosingDeclaration || context.flags & NodeBuilderFlags.UseFullyQualifiedType) && !(context.internalFlags & InternalNodeBuilderFlags.DoNotIncludeSymbolChain)) {
        chain = Debug.checkDefined(getSymbolChain(
          symbol,
          meaning,
          /*endOfChain*/
          true
        ));
        Debug.assert(chain && chain.length > 0);
      } else {
        chain = [symbol];
      }
      return chain;
      function getSymbolChain(symbol2, meaning2, endOfChain) {
        let accessibleSymbolChain = getAccessibleSymbolChain(symbol2, context.enclosingDeclaration, meaning2, !!(context.flags & NodeBuilderFlags.UseOnlyExternalAliasing));
        let parentSpecifiers;
        if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning2 : getQualifiedLeftMeaning(meaning2))) {
          const parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol2, context.enclosingDeclaration, meaning2);
          if (length(parents)) {
            parentSpecifiers = parents.map(
              (symbol3) => some(symbol3.declarations, hasNonGlobalAugmentationExternalModuleSymbol) ? getSpecifierForModuleSymbol(symbol3, context) : void 0
            );
            const indices = parents.map((_, i) => i);
            indices.sort(sortByBestName);
            const sortedParents = indices.map((i) => parents[i]);
            for (const parent of sortedParents) {
              const parentChain = getSymbolChain(
                parent,
                getQualifiedLeftMeaning(meaning2),
                /*endOfChain*/
                false
              );
              if (parentChain) {
                if (parent.exports && parent.exports.get(InternalSymbolName.ExportEquals) && getSymbolIfSameReference(parent.exports.get(InternalSymbolName.ExportEquals), symbol2)) {
                  accessibleSymbolChain = parentChain;
                  break;
                }
                accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol2) || symbol2]);
                break;
              }
            }
          }
        }
        if (accessibleSymbolChain) {
          return accessibleSymbolChain;
        }
        if (
          // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
          endOfChain || // If a parent symbol is an anonymous type, don't write it.
          !(symbol2.flags & (SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral))
        ) {
          if (!endOfChain && !yieldModuleSymbol && !!forEach(symbol2.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
            return;
          }
          return [symbol2];
        }
        function sortByBestName(a, b) {
          const specifierA = parentSpecifiers[a];
          const specifierB = parentSpecifiers[b];
          if (specifierA && specifierB) {
            const isBRelative = pathIsRelative(specifierB);
            if (pathIsRelative(specifierA) === isBRelative) {
              return moduleSpecifiers.countPathComponents(specifierA) - moduleSpecifiers.countPathComponents(specifierB);
            }
            if (isBRelative) {
              return -1;
            }
            return 1;
          }
          return 0;
        }
      }
    }
    function typeParametersToTypeParameterDeclarations(symbol, context) {
      let typeParameterNodes;
      const targetSymbol = getTargetSymbol(symbol);
      if (targetSymbol.flags & (SymbolFlags.Class | SymbolFlags.Interface | SymbolFlags.TypeAlias)) {
        typeParameterNodes = factory.createNodeArray(map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), (tp) => typeParameterToDeclaration(tp, context)));
      }
      return typeParameterNodes;
    }
    function lookupTypeParameterNodes(chain, index, context) {
      Debug.assert(chain && 0 <= index && index < chain.length);
      const symbol = chain[index];
      const symbolId = getSymbolId(symbol);
      if (context.typeParameterSymbolList?.has(symbolId)) {
        return void 0;
      }
      if (context.mustCreateTypeParameterSymbolList) {
        context.mustCreateTypeParameterSymbolList = false;
        context.typeParameterSymbolList = new Set(context.typeParameterSymbolList);
      }
      context.typeParameterSymbolList.add(symbolId);
      let typeParameterNodes;
      if (context.flags & NodeBuilderFlags.WriteTypeParametersInQualifiedName && index < chain.length - 1) {
        const parentSymbol = symbol;
        const nextSymbol = chain[index + 1];
        if (getCheckFlags(nextSymbol) & CheckFlags.Instantiated) {
          const params = getTypeParametersOfClassOrInterface(
            parentSymbol.flags & SymbolFlags.Alias ? resolveAlias(parentSymbol) : parentSymbol
          );
          typeParameterNodes = mapToTypeNodes(map(params, (t) => getMappedType(t, nextSymbol.links.mapper)), context);
        } else {
          typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
        }
      }
      return typeParameterNodes;
    }
    function getTopmostIndexedAccessType(top) {
      if (isIndexedAccessTypeNode(top.objectType)) {
        return getTopmostIndexedAccessType(top.objectType);
      }
      return top;
    }
    function getSpecifierForModuleSymbol(symbol, context, overrideImportMode) {
      let file = getDeclarationOfKind(symbol, SyntaxKind.SourceFile);
      if (!file) {
        const equivalentFileSymbol = firstDefined(symbol.declarations, (d) => getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol));
        if (equivalentFileSymbol) {
          file = getDeclarationOfKind(equivalentFileSymbol, SyntaxKind.SourceFile);
        }
      }
      if (file && file.moduleName !== void 0) {
        return file.moduleName;
      }
      if (!file) {
        if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
          return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
        }
      }
      if (!context.enclosingFile || !context.tracker.moduleResolverHost) {
        if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
          return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
        }
        return getSourceFileOfNode(getNonAugmentationDeclaration(symbol)).fileName;
      }
      const enclosingDeclaration = getOriginalNode(context.enclosingDeclaration);
      const originalModuleSpecifier = canHaveModuleSpecifier(enclosingDeclaration) ? tryGetModuleSpecifierFromDeclaration(enclosingDeclaration) : void 0;
      const contextFile = context.enclosingFile;
      const resolutionMode = overrideImportMode || originalModuleSpecifier && host.getModeForUsageLocation(contextFile, originalModuleSpecifier) || contextFile && host.getDefaultResolutionModeForFile(contextFile);
      const cacheKey = createModeAwareCacheKey(contextFile.path, resolutionMode);
      const links = getSymbolLinks(symbol);
      let specifier = links.specifierCache && links.specifierCache.get(cacheKey);
      if (!specifier) {
        const isBundle = !!compilerOptions.outFile;
        const { moduleResolverHost } = context.tracker;
        const specifierCompilerOptions = isBundle ? { ...compilerOptions, baseUrl: moduleResolverHost.getCommonSourceDirectory() } : compilerOptions;
        specifier = first(moduleSpecifiers.getModuleSpecifiers(
          symbol,
          checker,
          specifierCompilerOptions,
          contextFile,
          moduleResolverHost,
          {
            importModuleSpecifierPreference: isBundle ? "non-relative" : "project-relative",
            importModuleSpecifierEnding: isBundle ? "minimal" : resolutionMode === ModuleKind.ESNext ? "js" : void 0
          },
          { overrideImportMode }
        ));
        links.specifierCache ??= /* @__PURE__ */ new Map();
        links.specifierCache.set(cacheKey, specifier);
      }
      return specifier;
    }
    function symbolToEntityNameNode(symbol) {
      const identifier = factory.createIdentifier(unescapeLeadingUnderscores(symbol.escapedName));
      return symbol.parent ? factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier;
    }
    function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
      const chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope));
      const isTypeOf = meaning === SymbolFlags.Value;
      if (some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
        const nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : void 0;
        const typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
        const contextFile = getSourceFileOfNode(getOriginalNode(context.enclosingDeclaration));
        const targetFile = getSourceFileOfModule(chain[0]);
        let specifier;
        let attributes;
        if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Node16 || getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeNext) {
          if (targetFile?.impliedNodeFormat === ModuleKind.ESNext && targetFile.impliedNodeFormat !== contextFile?.impliedNodeFormat) {
            specifier = getSpecifierForModuleSymbol(chain[0], context, ModuleKind.ESNext);
            attributes = factory.createImportAttributes(
              factory.createNodeArray([
                factory.createImportAttribute(
                  factory.createStringLiteral("resolution-mode"),
                  factory.createStringLiteral("import")
                )
              ])
            );
          }
        }
        if (!specifier) {
          specifier = getSpecifierForModuleSymbol(chain[0], context);
        }
        if (!(context.flags & NodeBuilderFlags.AllowNodeModulesRelativePaths) && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Classic && specifier.includes("/node_modules/")) {
          const oldSpecifier = specifier;
          if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Node16 || getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeNext) {
            const swappedMode = contextFile?.impliedNodeFormat === ModuleKind.ESNext ? ModuleKind.CommonJS : ModuleKind.ESNext;
            specifier = getSpecifierForModuleSymbol(chain[0], context, swappedMode);
            if (specifier.includes("/node_modules/")) {
              specifier = oldSpecifier;
            } else {
              attributes = factory.createImportAttributes(
                factory.createNodeArray([
                  factory.createImportAttribute(
                    factory.createStringLiteral("resolution-mode"),
                    factory.createStringLiteral(swappedMode === ModuleKind.ESNext ? "import" : "require")
                  )
                ])
              );
            }
          }
          if (!attributes) {
            context.encounteredError = true;
            if (context.tracker.reportLikelyUnsafeImportRequiredError) {
              context.tracker.reportLikelyUnsafeImportRequiredError(oldSpecifier);
            }
          }
        }
        const lit = factory.createLiteralTypeNode(factory.createStringLiteral(specifier));
        context.approximateLength += specifier.length + 10;
        if (!nonRootParts || isEntityName(nonRootParts)) {
          if (nonRootParts) {
            const lastId = isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
            setIdentifierTypeArguments(
              lastId,
              /*typeArguments*/
              void 0
            );
          }
          return factory.createImportTypeNode(lit, attributes, nonRootParts, typeParameterNodes, isTypeOf);
        } else {
          const splitNode = getTopmostIndexedAccessType(nonRootParts);
          const qualifier = splitNode.objectType.typeName;
          return factory.createIndexedAccessTypeNode(factory.createImportTypeNode(lit, attributes, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
        }
      }
      const entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
      if (isIndexedAccessTypeNode(entityName)) {
        return entityName;
      }
      if (isTypeOf) {
        return factory.createTypeQueryNode(entityName);
      } else {
        const lastId = isIdentifier(entityName) ? entityName : entityName.right;
        const lastTypeArgs = getIdentifierTypeArguments(lastId);
        setIdentifierTypeArguments(
          lastId,
          /*typeArguments*/
          void 0
        );
        return factory.createTypeReferenceNode(entityName, lastTypeArgs);
      }
      function createAccessFromSymbolChain(chain2, index, stopper) {
        const typeParameterNodes = index === chain2.length - 1 ? overrideTypeArguments : lookupTypeParameterNodes(chain2, index, context);
        const symbol2 = chain2[index];
        const parent = chain2[index - 1];
        let symbolName2;
        if (index === 0) {
          context.flags |= NodeBuilderFlags.InInitialEntityName;
          symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
          context.approximateLength += (symbolName2 ? symbolName2.length : 0) + 1;
          context.flags ^= NodeBuilderFlags.InInitialEntityName;
        } else {
          if (parent && getExportsOfSymbol(parent)) {
            const exports = getExportsOfSymbol(parent);
            forEachEntry(exports, (ex, name) => {
              if (getSymbolIfSameReference(ex, symbol2) && !isLateBoundName(name) && name !== InternalSymbolName.ExportEquals) {
                symbolName2 = unescapeLeadingUnderscores(name);
                return true;
              }
            });
          }
        }
        if (symbolName2 === void 0) {
          const name = firstDefined(symbol2.declarations, getNameOfDeclaration);
          if (name && isComputedPropertyName(name) && isEntityName(name.expression)) {
            const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper);
            if (isEntityName(LHS)) {
              return factory.createIndexedAccessTypeNode(factory.createParenthesizedType(factory.createTypeQueryNode(LHS)), factory.createTypeQueryNode(name.expression));
            }
            return LHS;
          }
          symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
        }
        context.approximateLength += symbolName2.length + 1;
        if (!(context.flags & NodeBuilderFlags.ForbidIndexedAccessSymbolReferences) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol2.escapedName) && getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol2.escapedName), symbol2)) {
          const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper);
          if (isIndexedAccessTypeNode(LHS)) {
            return factory.createIndexedAccessTypeNode(LHS, factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2)));
          } else {
            return factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(LHS, typeParameterNodes), factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2)));
          }
        }
        const identifier = setEmitFlags(factory.createIdentifier(symbolName2), EmitFlags.NoAsciiEscaping);
        if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
        identifier.symbol = symbol2;
        if (index > stopper) {
          const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper);
          if (!isEntityName(LHS)) {
            return Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
          }
          return factory.createQualifiedName(LHS, identifier);
        }
        return identifier;
      }
    }
    function typeParameterShadowsOtherTypeParameterInScope(escapedName, context, type) {
      const result = resolveName(
        context.enclosingDeclaration,
        escapedName,
        SymbolFlags.Type,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      );
      if (result && result.flags & SymbolFlags.TypeParameter) {
        return result !== type.symbol;
      }
      return false;
    }
    function typeParameterToName(type, context) {
      if (context.flags & NodeBuilderFlags.GenerateNamesForShadowedTypeParams && context.typeParameterNames) {
        const cached = context.typeParameterNames.get(getTypeId(type));
        if (cached) {
          return cached;
        }
      }
      let result = symbolToName(
        type.symbol,
        context,
        SymbolFlags.Type,
        /*expectsIdentifier*/
        true
      );
      if (!(result.kind & SyntaxKind.Identifier)) {
        return factory.createIdentifier("(Missing type parameter)");
      }
      const decl = type.symbol?.declarations?.[0];
      if (decl && isTypeParameterDeclaration(decl)) {
        result = setTextRange(context, result, decl.name);
      }
      if (context.flags & NodeBuilderFlags.GenerateNamesForShadowedTypeParams) {
        const rawtext = result.escapedText;
        let i = context.typeParameterNamesByTextNextNameCount?.get(rawtext) || 0;
        let text = rawtext;
        while (context.typeParameterNamesByText?.has(text) || typeParameterShadowsOtherTypeParameterInScope(text, context, type)) {
          i++;
          text = `${rawtext}_${i}`;
        }
        if (text !== rawtext) {
          const typeArguments = getIdentifierTypeArguments(result);
          result = factory.createIdentifier(text);
          setIdentifierTypeArguments(result, typeArguments);
        }
        if (context.mustCreateTypeParametersNamesLookups) {
          context.mustCreateTypeParametersNamesLookups = false;
          context.typeParameterNames = new Map(context.typeParameterNames);
          context.typeParameterNamesByTextNextNameCount = new Map(context.typeParameterNamesByTextNextNameCount);
          context.typeParameterNamesByText = new Set(context.typeParameterNamesByText);
        }
        context.typeParameterNamesByTextNextNameCount.set(rawtext, i);
        context.typeParameterNames.set(getTypeId(type), result);
        context.typeParameterNamesByText.add(text);
      }
      return result;
    }
    function symbolToName(symbol, context, meaning, expectsIdentifier) {
      const chain = lookupSymbolChain(symbol, context, meaning);
      if (expectsIdentifier && chain.length !== 1 && !context.encounteredError && !(context.flags & NodeBuilderFlags.AllowQualifiedNameInPlaceOfIdentifier)) {
        context.encounteredError = true;
      }
      return createEntityNameFromSymbolChain(chain, chain.length - 1);
      function createEntityNameFromSymbolChain(chain2, index) {
        const typeParameterNodes = lookupTypeParameterNodes(chain2, index, context);
        const symbol2 = chain2[index];
        if (index === 0) {
          context.flags |= NodeBuilderFlags.InInitialEntityName;
        }
        const symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
        if (index === 0) {
          context.flags ^= NodeBuilderFlags.InInitialEntityName;
        }
        const identifier = setEmitFlags(factory.createIdentifier(symbolName2), EmitFlags.NoAsciiEscaping);
        if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
        identifier.symbol = symbol2;
        return index > 0 ? factory.createQualifiedName(createEntityNameFromSymbolChain(chain2, index - 1), identifier) : identifier;
      }
    }
    function symbolToExpression(symbol, context, meaning) {
      const chain = lookupSymbolChain(symbol, context, meaning);
      return createExpressionFromSymbolChain(chain, chain.length - 1);
      function createExpressionFromSymbolChain(chain2, index) {
        const typeParameterNodes = lookupTypeParameterNodes(chain2, index, context);
        const symbol2 = chain2[index];
        if (index === 0) {
          context.flags |= NodeBuilderFlags.InInitialEntityName;
        }
        let symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
        if (index === 0) {
          context.flags ^= NodeBuilderFlags.InInitialEntityName;
        }
        let firstChar = symbolName2.charCodeAt(0);
        if (isSingleOrDoubleQuote(firstChar) && some(symbol2.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
          return factory.createStringLiteral(getSpecifierForModuleSymbol(symbol2, context));
        }
        if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) {
          const identifier = setEmitFlags(factory.createIdentifier(symbolName2), EmitFlags.NoAsciiEscaping);
          if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
          identifier.symbol = symbol2;
          return index > 0 ? factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain2, index - 1), identifier) : identifier;
        } else {
          if (firstChar === CharacterCodes.openBracket) {
            symbolName2 = symbolName2.substring(1, symbolName2.length - 1);
            firstChar = symbolName2.charCodeAt(0);
          }
          let expression;
          if (isSingleOrDoubleQuote(firstChar) && !(symbol2.flags & SymbolFlags.EnumMember)) {
            expression = factory.createStringLiteral(stripQuotes(symbolName2).replace(/\\./g, (s) => s.substring(1)), firstChar === CharacterCodes.singleQuote);
          } else if ("" + +symbolName2 === symbolName2) {
            expression = factory.createNumericLiteral(+symbolName2);
          }
          if (!expression) {
            const identifier = setEmitFlags(factory.createIdentifier(symbolName2), EmitFlags.NoAsciiEscaping);
            if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
            identifier.symbol = symbol2;
            expression = identifier;
          }
          return factory.createElementAccessExpression(createExpressionFromSymbolChain(chain2, index - 1), expression);
        }
      }
    }
    function isStringNamed(d) {
      const name = getNameOfDeclaration(d);
      if (!name) {
        return false;
      }
      if (isComputedPropertyName(name)) {
        const type = checkExpression(name.expression);
        return !!(type.flags & TypeFlags.StringLike);
      }
      if (isElementAccessExpression(name)) {
        const type = checkExpression(name.argumentExpression);
        return !!(type.flags & TypeFlags.StringLike);
      }
      return isStringLiteral(name);
    }
    function isSingleQuotedStringNamed(d) {
      const name = getNameOfDeclaration(d);
      return !!(name && isStringLiteral(name) && (name.singleQuote || !nodeIsSynthesized(name) && startsWith(getTextOfNode(
        name,
        /*includeTrivia*/
        false
      ), "'")));
    }
    function getPropertyNameNodeForSymbol(symbol, context) {
      const stringNamed = !!length(symbol.declarations) && every(symbol.declarations, isStringNamed);
      const singleQuote = !!length(symbol.declarations) && every(symbol.declarations, isSingleQuotedStringNamed);
      const isMethod = !!(symbol.flags & SymbolFlags.Method);
      const fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed, isMethod);
      if (fromNameType) {
        return fromNameType;
      }
      const rawName = unescapeLeadingUnderscores(symbol.escapedName);
      return createPropertyNameNodeForIdentifierOrLiteral(rawName, getEmitScriptTarget(compilerOptions), singleQuote, stringNamed, isMethod);
    }
    function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed, isMethod) {
      const nameType = getSymbolLinks(symbol).nameType;
      if (nameType) {
        if (nameType.flags & TypeFlags.StringOrNumberLiteral) {
          const name = "" + nameType.value;
          if (!isIdentifierText(name, getEmitScriptTarget(compilerOptions)) && (stringNamed || !isNumericLiteralName(name))) {
            return factory.createStringLiteral(name, !!singleQuote);
          }
          if (isNumericLiteralName(name) && startsWith(name, "-")) {
            return factory.createComputedPropertyName(factory.createPrefixUnaryExpression(SyntaxKind.MinusToken, factory.createNumericLiteral(-name)));
          }
          return createPropertyNameNodeForIdentifierOrLiteral(name, getEmitScriptTarget(compilerOptions), singleQuote, stringNamed, isMethod);
        }
        if (nameType.flags & TypeFlags.UniqueESSymbol) {
          return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, SymbolFlags.Value));
        }
      }
    }
    function cloneNodeBuilderContext(context) {
      const oldMustCreateTypeParameterSymbolList = context.mustCreateTypeParameterSymbolList;
      const oldMustCreateTypeParametersNamesLookups = context.mustCreateTypeParametersNamesLookups;
      context.mustCreateTypeParameterSymbolList = true;
      context.mustCreateTypeParametersNamesLookups = true;
      const oldTypeParameterNames = context.typeParameterNames;
      const oldTypeParameterNamesByText = context.typeParameterNamesByText;
      const oldTypeParameterNamesByTextNextNameCount = context.typeParameterNamesByTextNextNameCount;
      const oldTypeParameterSymbolList = context.typeParameterSymbolList;
      return () => {
        context.typeParameterNames = oldTypeParameterNames;
        context.typeParameterNamesByText = oldTypeParameterNamesByText;
        context.typeParameterNamesByTextNextNameCount = oldTypeParameterNamesByTextNextNameCount;
        context.typeParameterSymbolList = oldTypeParameterSymbolList;
        context.mustCreateTypeParameterSymbolList = oldMustCreateTypeParameterSymbolList;
        context.mustCreateTypeParametersNamesLookups = oldMustCreateTypeParametersNamesLookups;
      };
    }
    function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
      return symbol.declarations && find(symbol.declarations, (s) => !!getNonlocalEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!findAncestor(s, (n) => n === enclosingDeclaration)));
    }
    function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
      if (!(getObjectFlags(type) & ObjectFlags.Reference)) return true;
      if (!isTypeReferenceNode(existing)) return true;
      void getTypeFromTypeReference(existing);
      const symbol = getNodeLinks(existing).resolvedSymbol;
      const existingTarget = symbol && getDeclaredTypeOfSymbol(symbol);
      if (!existingTarget || existingTarget !== type.target) return true;
      return length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
    }
    function getEnclosingDeclarationIgnoringFakeScope(enclosingDeclaration) {
      while (getNodeLinks(enclosingDeclaration).fakeScopeForSignatureDeclaration) {
        enclosingDeclaration = enclosingDeclaration.parent;
      }
      return enclosingDeclaration;
    }
    function serializeTypeForDeclaration(context, declaration, type, symbol) {
      const addUndefinedForParameter = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration, context.enclosingDeclaration);
      const enclosingDeclaration = context.enclosingDeclaration;
      const restoreFlags = saveRestoreFlags(context);
      if (declaration && hasInferredType(declaration) && !(context.internalFlags & InternalNodeBuilderFlags.NoSyntacticPrinter)) {
        syntacticNodeBuilder.serializeTypeOfDeclaration(declaration, context);
      }
      context.internalFlags |= InternalNodeBuilderFlags.NoSyntacticPrinter;
      if (enclosingDeclaration && (!isErrorType(type) || context.internalFlags & InternalNodeBuilderFlags.AllowUnresolvedNames)) {
        const declWithExistingAnnotation = declaration && getNonlocalEffectiveTypeAnnotationNode(declaration) ? declaration : getDeclarationWithTypeAnnotation(symbol);
        if (declWithExistingAnnotation && !isFunctionLikeDeclaration(declWithExistingAnnotation) && !isGetAccessorDeclaration(declWithExistingAnnotation)) {
          const existing = getNonlocalEffectiveTypeAnnotationNode(declWithExistingAnnotation);
          const addUndefined = addUndefinedForParameter || !!(symbol.flags & SymbolFlags.Property && symbol.flags & SymbolFlags.Optional && isOptionalDeclaration(declWithExistingAnnotation) && symbol.links?.mappedType && containsNonMissingUndefinedType(type));
          const result2 = !isTypePredicateNode(existing) && tryReuseExistingTypeNode(context, existing, type, declWithExistingAnnotation, addUndefined);
          if (result2) {
            restoreFlags();
            return result2;
          }
        }
      }
      if (type.flags & TypeFlags.UniqueESSymbol && type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)))) {
        context.flags |= NodeBuilderFlags.AllowUniqueESSymbolType;
      }
      const decl = declaration ?? symbol.valueDeclaration ?? symbol.declarations?.[0];
      const expr = decl && isDeclarationWithPossibleInnerTypeNodeReuse(decl) ? getPossibleTypeNodeReuseExpression(decl) : void 0;
      const result = expressionOrTypeToTypeNode(context, expr, type, addUndefinedForParameter);
      restoreFlags();
      return result;
    }
    function typeNodeIsEquivalentToType(annotatedDeclaration, type, typeFromTypeNode) {
      if (typeFromTypeNode === type) {
        return true;
      }
      if (annotatedDeclaration && (isParameter(annotatedDeclaration) || isPropertySignature(annotatedDeclaration) || isPropertyDeclaration(annotatedDeclaration)) && annotatedDeclaration.questionToken) {
        return getTypeWithFacts(type, 524288 /* NEUndefined */) === typeFromTypeNode;
      }
      return false;
    }
    function serializeReturnTypeForSignature(context, signature) {
      const suppressAny = context.flags & NodeBuilderFlags.SuppressAnyReturnType;
      const restoreFlags = saveRestoreFlags(context);
      if (suppressAny) context.flags &= ~NodeBuilderFlags.SuppressAnyReturnType;
      let returnTypeNode;
      const returnType = getReturnTypeOfSignature(signature);
      if (returnType && !(suppressAny && isTypeAny(returnType))) {
        if (signature.declaration && !(context.internalFlags & InternalNodeBuilderFlags.NoSyntacticPrinter)) {
          syntacticNodeBuilder.serializeReturnTypeForSignature(signature.declaration, context);
        }
        context.internalFlags |= InternalNodeBuilderFlags.NoSyntacticPrinter;
        returnTypeNode = serializeReturnTypeForSignatureWorker(context, signature);
      } else if (!suppressAny) {
        returnTypeNode = factory.createKeywordTypeNode(SyntaxKind.AnyKeyword);
      }
      restoreFlags();
      return returnTypeNode;
    }
    function serializeReturnTypeForSignatureWorker(context, signature) {
      const typePredicate = getTypePredicateOfSignature(signature);
      const type = getReturnTypeOfSignature(signature);
      if (context.enclosingDeclaration && (!isErrorType(type) || context.internalFlags & InternalNodeBuilderFlags.AllowUnresolvedNames) && signature.declaration && !nodeIsSynthesized(signature.declaration)) {
        const annotation = getNonlocalEffectiveReturnTypeAnnotationNode(signature.declaration);
        if (annotation) {
          const result = tryReuseExistingTypeNode(context, annotation, type, context.enclosingDeclaration);
          if (result) {
            return result;
          }
        }
      }
      if (typePredicate) {
        return typePredicateToTypePredicateNodeHelper(typePredicate, context);
      }
      const expr = signature.declaration && getPossibleTypeNodeReuseExpression(signature.declaration);
      return expressionOrTypeToTypeNode(context, expr, type);
    }
    function trackExistingEntityName(node, context) {
      let introducesError = false;
      const leftmost = getFirstIdentifier(node);
      if (isInJSFile(node) && (isExportsIdentifier(leftmost) || isModuleExportsAccessExpression(leftmost.parent) || isQualifiedName(leftmost.parent) && isModuleIdentifier(leftmost.parent.left) && isExportsIdentifier(leftmost.parent.right))) {
        introducesError = true;
        return { introducesError, node };
      }
      const meaning = getMeaningOfEntityNameReference(node);
      let sym;
      if (isThisIdentifier(leftmost)) {
        sym = getSymbolOfDeclaration(getThisContainer(
          leftmost,
          /*includeArrowFunctions*/
          false,
          /*includeClassComputedPropertyName*/
          false
        ));
        if (isSymbolAccessible(
          sym,
          leftmost,
          meaning,
          /*shouldComputeAliasesToMakeVisible*/
          false
        ).accessibility !== SymbolAccessibility.Accessible) {
          introducesError = true;
          context.tracker.reportInaccessibleThisError();
        }
        return { introducesError, node: attachSymbolToLeftmostIdentifier(node) };
      }
      sym = resolveEntityName(
        leftmost,
        meaning,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true
      );
      if (context.enclosingDeclaration && !(sym && sym.flags & SymbolFlags.TypeParameter)) {
        sym = getExportSymbolOfValueSymbolIfExported(sym);
        const symAtLocation = resolveEntityName(
          leftmost,
          meaning,
          /*ignoreErrors*/
          true,
          /*dontResolveAlias*/
          true,
          context.enclosingDeclaration
        );
        if (
          // Check for unusable parameters symbols
          symAtLocation === unknownSymbol || // If the symbol is not found, but was not found in the original scope either we probably have an error, don't reuse the node
          symAtLocation === void 0 && sym !== void 0 || // If the symbol is found both in declaration scope and in current scope then it shoudl point to the same reference
          symAtLocation && sym && !getSymbolIfSameReference(getExportSymbolOfValueSymbolIfExported(symAtLocation), sym)
        ) {
          if (symAtLocation !== unknownSymbol) {
            context.tracker.reportInferenceFallback(node);
          }
          introducesError = true;
          return { introducesError, node, sym };
        } else {
          sym = symAtLocation;
        }
      }
      if (sym) {
        if (sym.flags & SymbolFlags.FunctionScopedVariable && sym.valueDeclaration) {
          if (isPartOfParameterDeclaration(sym.valueDeclaration) || isJSDocParameterTag(sym.valueDeclaration)) {
            return { introducesError, node: attachSymbolToLeftmostIdentifier(node) };
          }
        }
        if (!(sym.flags & SymbolFlags.TypeParameter) && // Type parameters are visible in the current context if they are are resolvable
        !isDeclarationName(node) && isSymbolAccessible(
          sym,
          context.enclosingDeclaration,
          meaning,
          /*shouldComputeAliasesToMakeVisible*/
          false
        ).accessibility !== SymbolAccessibility.Accessible) {
          context.tracker.reportInferenceFallback(node);
          introducesError = true;
        } else {
          context.tracker.trackSymbol(sym, context.enclosingDeclaration, meaning);
        }
        return { introducesError, node: attachSymbolToLeftmostIdentifier(node) };
      }
      return { introducesError, node };
      function attachSymbolToLeftmostIdentifier(node2) {
        if (node2 === leftmost) {
          const type = getDeclaredTypeOfSymbol(sym);
          const name = sym.flags & SymbolFlags.TypeParameter ? typeParameterToName(type, context) : factory.cloneNode(node2);
          name.symbol = sym;
          return setTextRange(context, setEmitFlags(name, EmitFlags.NoAsciiEscaping), node2);
        }
        const updated = visitEachChildWorker(
          node2,
          (c) => attachSymbolToLeftmostIdentifier(c),
          /*context*/
          void 0
        );
        if (updated !== node2) {
          setTextRange(context, updated, node2);
        }
        return updated;
      }
    }
    function serializeTypeName(context, node, isTypeOf, typeArguments) {
      const meaning = isTypeOf ? SymbolFlags.Value : SymbolFlags.Type;
      const symbol = resolveEntityName(
        node,
        meaning,
        /*ignoreErrors*/
        true
      );
      if (!symbol) return void 0;
      const resolvedSymbol = symbol.flags & SymbolFlags.Alias ? resolveAlias(symbol) : symbol;
      if (isSymbolAccessible(
        symbol,
        context.enclosingDeclaration,
        meaning,
        /*shouldComputeAliasesToMakeVisible*/
        false
      ).accessibility !== SymbolAccessibility.Accessible) return void 0;
      return symbolToTypeNode(resolvedSymbol, context, meaning, typeArguments);
    }
    function canReuseTypeNode(context, existing) {
      if (isInJSFile(existing)) {
        if (isLiteralImportTypeNode(existing)) {
          void getTypeFromImportTypeNode(existing);
          const nodeSymbol = getNodeLinks(existing).resolvedSymbol;
          return !nodeSymbol || !// The import type resolved using jsdoc fallback logic
          (!existing.isTypeOf && !(nodeSymbol.flags & SymbolFlags.Type) || // The import type had type arguments autofilled by js fallback logic
          !(length(existing.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))));
        }
      }
      if (isThisTypeNode(existing)) {
        if (context.mapper === void 0) return true;
        const type = getTypeFromTypeNode2(
          context,
          existing,
          /*noMappedTypes*/
          true
        );
        return !!type;
      }
      if (isTypeReferenceNode(existing)) {
        if (isConstTypeReference(existing)) return false;
        const type = getTypeFromTypeReference(existing);
        const symbol = getNodeLinks(existing).resolvedSymbol;
        if (!symbol) return false;
        if (symbol.flags & SymbolFlags.TypeParameter) {
          const type2 = getDeclaredTypeOfSymbol(symbol);
          if (context.mapper && getMappedType(type2, context.mapper) !== type2) {
            return false;
          }
        }
        if (isInJSDoc(existing)) {
          return existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) && !getIntendedTypeFromJSDocTypeReference(existing) && symbol.flags & SymbolFlags.Type;
        }
      }
      if (isTypeOperatorNode(existing) && existing.operator === SyntaxKind.UniqueKeyword && existing.type.kind === SyntaxKind.SymbolKeyword) {
        const effectiveEnclosingContext = context.enclosingDeclaration && getEnclosingDeclarationIgnoringFakeScope(context.enclosingDeclaration);
        return !!findAncestor(existing, (n) => n === effectiveEnclosingContext);
      }
      return true;
    }
    function serializeExistingTypeNode(context, typeNode) {
      const type = getTypeFromTypeNode2(context, typeNode);
      return typeToTypeNodeHelper(type, context);
    }
    function tryReuseExistingTypeNodeHelper(context, existing) {
      if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
        cancellationToken.throwIfCancellationRequested();
      }
      let hadError = false;
      const { finalizeBoundary, startRecoveryScope } = createRecoveryBoundary();
      const transformed = visitNode(existing, visitExistingNodeTreeSymbols, isTypeNode);
      if (!finalizeBoundary()) {
        return void 0;
      }
      context.approximateLength += existing.end - existing.pos;
      return transformed;
      function visitExistingNodeTreeSymbols(node) {
        if (hadError) return node;
        const recover = startRecoveryScope();
        const onExitNewScope = isNewScopeNode(node) ? onEnterNewScope(node) : void 0;
        const result = visitExistingNodeTreeSymbolsWorker(node);
        onExitNewScope?.();
        if (hadError) {
          if (isTypeNode(node) && !isTypePredicateNode(node)) {
            recover();
            return serializeExistingTypeNode(context, node);
          }
          return node;
        }
        return result ? setTextRange(context, result, node) : void 0;
      }
      function createRecoveryBoundary() {
        let trackedSymbols;
        let unreportedErrors;
        const oldTracker = context.tracker;
        const oldTrackedSymbols = context.trackedSymbols;
        context.trackedSymbols = void 0;
        const oldEncounteredError = context.encounteredError;
        context.tracker = new SymbolTrackerImpl(context, {
          ...oldTracker.inner,
          reportCyclicStructureError() {
            markError(() => oldTracker.reportCyclicStructureError());
          },
          reportInaccessibleThisError() {
            markError(() => oldTracker.reportInaccessibleThisError());
          },
          reportInaccessibleUniqueSymbolError() {
            markError(() => oldTracker.reportInaccessibleUniqueSymbolError());
          },
          reportLikelyUnsafeImportRequiredError(specifier) {
            markError(() => oldTracker.reportLikelyUnsafeImportRequiredError(specifier));
          },
          reportNonSerializableProperty(name) {
            markError(() => oldTracker.reportNonSerializableProperty(name));
          },
          trackSymbol(sym, decl, meaning) {
            (trackedSymbols ??= []).push([sym, decl, meaning]);
            return false;
          },
          moduleResolverHost: context.tracker.moduleResolverHost
        }, context.tracker.moduleResolverHost);
        return {
          startRecoveryScope: startRecoveryScope2,
          finalizeBoundary: finalizeBoundary2
        };
        function markError(unreportedError) {
          hadError = true;
          (unreportedErrors ??= []).push(unreportedError);
        }
        function startRecoveryScope2() {
          const trackedSymbolsTop = trackedSymbols?.length ?? 0;
          const unreportedErrorsTop = unreportedErrors?.length ?? 0;
          return () => {
            hadError = false;
            if (trackedSymbols) {
              trackedSymbols.length = trackedSymbolsTop;
            }
            if (unreportedErrors) {
              unreportedErrors.length = unreportedErrorsTop;
            }
          };
        }
        function finalizeBoundary2() {
          context.tracker = oldTracker;
          context.trackedSymbols = oldTrackedSymbols;
          context.encounteredError = oldEncounteredError;
          unreportedErrors?.forEach((fn) => fn());
          if (hadError) {
            return false;
          }
          trackedSymbols?.forEach(
            ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol(
              symbol,
              enclosingDeclaration,
              meaning
            )
          );
          return true;
        }
      }
      function onEnterNewScope(node) {
        return enterNewScope(context, node, getParametersInScope(node), getTypeParametersInScope(node));
      }
      function tryVisitSimpleTypeNode(node) {
        const innerNode = skipTypeParentheses(node);
        switch (innerNode.kind) {
          case SyntaxKind.TypeReference:
            return tryVisitTypeReference(innerNode);
          case SyntaxKind.TypeQuery:
            return tryVisitTypeQuery(innerNode);
          case SyntaxKind.IndexedAccessType:
            return tryVisitIndexedAccess(innerNode);
          case SyntaxKind.TypeOperator:
            const typeOperatorNode = innerNode;
            if (typeOperatorNode.operator === SyntaxKind.KeyOfKeyword) {
              return tryVisitKeyOf(typeOperatorNode);
            }
        }
        return visitNode(node, visitExistingNodeTreeSymbols, isTypeNode);
      }
      function tryVisitIndexedAccess(node) {
        const resultObjectType = tryVisitSimpleTypeNode(node.objectType);
        if (resultObjectType === void 0) {
          return void 0;
        }
        return factory.updateIndexedAccessTypeNode(node, resultObjectType, visitNode(node.indexType, visitExistingNodeTreeSymbols, isTypeNode));
      }
      function tryVisitKeyOf(node) {
        Debug.assertEqual(node.operator, SyntaxKind.KeyOfKeyword);
        const type = tryVisitSimpleTypeNode(node.type);
        if (type === void 0) {
          return void 0;
        }
        return factory.updateTypeOperatorNode(node, type);
      }
      function tryVisitTypeQuery(node) {
        const { introducesError, node: exprName } = trackExistingEntityName(node.exprName, context);
        if (!introducesError) {
          return factory.updateTypeQueryNode(
            node,
            exprName,
            visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode)
          );
        }
        const serializedName = serializeTypeName(
          context,
          node.exprName,
          /*isTypeOf*/
          true
        );
        if (serializedName) {
          return setTextRange(context, serializedName, node.exprName);
        }
      }
      function tryVisitTypeReference(node) {
        if (canReuseTypeNode(context, node)) {
          const { introducesError, node: newName } = trackExistingEntityName(node.typeName, context);
          const typeArguments = visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode);
          if (!introducesError) {
            const updated = factory.updateTypeReferenceNode(
              node,
              newName,
              typeArguments
            );
            return setTextRange(context, updated, node);
          } else {
            const serializedName = serializeTypeName(
              context,
              node.typeName,
              /*isTypeOf*/
              false,
              typeArguments
            );
            if (serializedName) {
              return setTextRange(context, serializedName, node.typeName);
            }
          }
        }
      }
      function visitExistingNodeTreeSymbolsWorker(node) {
        if (isJSDocTypeExpression(node)) {
          return visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode);
        }
        if (isJSDocAllType(node) || node.kind === SyntaxKind.JSDocNamepathType) {
          return factory.createKeywordTypeNode(SyntaxKind.AnyKeyword);
        }
        if (isJSDocUnknownType(node)) {
          return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
        }
        if (isJSDocNullableType(node)) {
          return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createLiteralTypeNode(factory.createNull())]);
        }
        if (isJSDocOptionalType(node)) {
          return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createKeywordTypeNode(SyntaxKind.UndefinedKeyword)]);
        }
        if (isJSDocNonNullableType(node)) {
          return visitNode(node.type, visitExistingNodeTreeSymbols);
        }
        if (isJSDocVariadicType(node)) {
          return factory.createArrayTypeNode(visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode));
        }
        if (isJSDocTypeLiteral(node)) {
          return factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (t) => {
            const name = visitNode(isIdentifier(t.name) ? t.name : t.name.right, visitExistingNodeTreeSymbols, isIdentifier);
            const typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode2(context, node), name.escapedText);
            const overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode2(context, t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : void 0;
            return factory.createPropertySignature(
              /*modifiers*/
              void 0,
              name,
              t.isBracketed || t.typeExpression && isJSDocOptionalType(t.typeExpression.type) ? factory.createToken(SyntaxKind.QuestionToken) : void 0,
              overrideTypeNode || t.typeExpression && visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword)
            );
          }));
        }
        if (isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "") {
          return setOriginalNode(factory.createKeywordTypeNode(SyntaxKind.AnyKeyword), node);
        }
        if ((isExpressionWithTypeArguments(node) || isTypeReferenceNode(node)) && isJSDocIndexSignature(node)) {
          return factory.createTypeLiteralNode([factory.createIndexSignature(
            /*modifiers*/
            void 0,
            [factory.createParameterDeclaration(
              /*modifiers*/
              void 0,
              /*dotDotDotToken*/
              void 0,
              "x",
              /*questionToken*/
              void 0,
              visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols, isTypeNode)
            )],
            visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols, isTypeNode)
          )]);
        }
        if (isJSDocFunctionType(node)) {
          if (isJSDocConstructSignature(node)) {
            let newTypeNode;
            return factory.createConstructorTypeNode(
              /*modifiers*/
              void 0,
              visitNodes(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration),
              mapDefined(node.parameters, (p, i) => p.name && isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode = p.type, void 0) : factory.createParameterDeclaration(
                /*modifiers*/
                void 0,
                getEffectiveDotDotDotForParameter(p),
                setTextRange(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p),
                factory.cloneNode(p.questionToken),
                visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode),
                /*initializer*/
                void 0
              )),
              visitNode(newTypeNode || node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword)
            );
          } else {
            return factory.createFunctionTypeNode(
              visitNodes(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration),
              map(node.parameters, (p, i) => factory.createParameterDeclaration(
                /*modifiers*/
                void 0,
                getEffectiveDotDotDotForParameter(p),
                setTextRange(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p),
                factory.cloneNode(p.questionToken),
                visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode),
                /*initializer*/
                void 0
              )),
              visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword)
            );
          }
        }
        if (isThisTypeNode(node)) {
          if (canReuseTypeNode(context, node)) {
            return node;
          }
          hadError = true;
          return node;
        }
        if (isTypeParameterDeclaration(node)) {
          return factory.updateTypeParameterDeclaration(
            node,
            visitNodes(node.modifiers, visitExistingNodeTreeSymbols, isModifier),
            setTextRange(context, typeParameterToName(getDeclaredTypeOfSymbol(getSymbolOfDeclaration(node)), context), node),
            visitNode(node.constraint, visitExistingNodeTreeSymbols, isTypeNode),
            visitNode(node.default, visitExistingNodeTreeSymbols, isTypeNode)
          );
        }
        if (isIndexedAccessTypeNode(node)) {
          const result = tryVisitIndexedAccess(node);
          if (!result) {
            hadError = true;
            return node;
          }
          return result;
        }
        if (isTypeReferenceNode(node)) {
          const result = tryVisitTypeReference(node);
          if (result) {
            return result;
          }
          hadError = true;
          return node;
        }
        if (isLiteralImportTypeNode(node)) {
          const nodeSymbol = getNodeLinks(node).resolvedSymbol;
          if (isInJSDoc(node) && nodeSymbol && // The import type resolved using jsdoc fallback logic
          (!node.isTypeOf && !(nodeSymbol.flags & SymbolFlags.Type) || // The import type had type arguments autofilled by js fallback logic
          !(length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) {
            return setTextRange(context, typeToTypeNodeHelper(getTypeFromTypeNode2(context, node), context), node);
          }
          return factory.updateImportTypeNode(
            node,
            factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)),
            visitNode(node.attributes, visitExistingNodeTreeSymbols, isImportAttributes),
            visitNode(node.qualifier, visitExistingNodeTreeSymbols, isEntityName),
            visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode),
            node.isTypeOf
          );
        }
        if (isNamedDeclaration(node) && node.name.kind === SyntaxKind.ComputedPropertyName && !isLateBindableName(node.name)) {
          if (!hasDynamicName(node)) {
            return visitEachChild(node, visitExistingNodeTreeSymbols);
          }
          if (!(context.internalFlags & InternalNodeBuilderFlags.AllowUnresolvedNames && isEntityNameExpression(node.name.expression) && checkComputedPropertyName(node.name).flags & TypeFlags.Any)) {
            return void 0;
          }
        }
        if (isFunctionLike(node) && !node.type || isPropertyDeclaration(node) && !node.type && !node.initializer || isPropertySignature(node) && !node.type && !node.initializer || isParameter(node) && !node.type && !node.initializer) {
          let visited = visitEachChild(node, visitExistingNodeTreeSymbols);
          if (visited === node) {
            visited = setTextRange(context, factory.cloneNode(node), node);
          }
          visited.type = factory.createKeywordTypeNode(SyntaxKind.AnyKeyword);
          if (isParameter(node)) {
            visited.modifiers = void 0;
          }
          return visited;
        }
        if (isTypeQueryNode(node)) {
          const result = tryVisitTypeQuery(node);
          if (!result) {
            hadError = true;
            return node;
          }
          return result;
        }
        if (isComputedPropertyName(node) && isEntityNameExpression(node.expression)) {
          const { node: result, introducesError } = trackExistingEntityName(node.expression, context);
          if (!introducesError) {
            return factory.updateComputedPropertyName(node, result);
          } else {
            const type = getWidenedType(getRegularTypeOfExpression(node.expression));
            const computedPropertyNameType = typeToTypeNodeHelper(type, context);
            let literal;
            if (isLiteralTypeNode(computedPropertyNameType)) {
              literal = computedPropertyNameType.literal;
            } else {
              const evaluated = evaluateEntityNameExpression(node.expression);
              const literalNode = typeof evaluated.value === "string" ? factory.createStringLiteral(
                evaluated.value,
                /*isSingleQuote*/
                void 0
              ) : typeof evaluated.value === "number" ? factory.createNumericLiteral(
                evaluated.value,
                /*numericLiteralFlags*/
                0
              ) : void 0;
              if (!literalNode) {
                if (isImportTypeNode(computedPropertyNameType)) {
                  trackComputedName(node.expression, context.enclosingDeclaration, context);
                }
                return node;
              }
              literal = literalNode;
            }
            if (literal.kind === SyntaxKind.StringLiteral && isIdentifierText(literal.text, getEmitScriptTarget(compilerOptions))) {
              return factory.createIdentifier(literal.text);
            }
            if (literal.kind === SyntaxKind.NumericLiteral && !literal.text.startsWith("-")) {
              return literal;
            }
            return factory.updateComputedPropertyName(node, literal);
          }
        }
        if (isTypePredicateNode(node)) {
          let parameterName;
          if (isIdentifier(node.parameterName)) {
            const { node: result, introducesError } = trackExistingEntityName(node.parameterName, context);
            hadError = hadError || introducesError;
            parameterName = result;
          } else {
            parameterName = factory.cloneNode(node.parameterName);
          }
          return factory.updateTypePredicateNode(node, factory.cloneNode(node.assertsModifier), parameterName, visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode));
        }
        if (isTupleTypeNode(node) || isTypeLiteralNode(node) || isMappedTypeNode(node)) {
          const visited = visitEachChild(node, visitExistingNodeTreeSymbols);
          const clone = setTextRange(context, visited === node ? factory.cloneNode(node) : visited, node);
          const flags = getEmitFlags(clone);
          setEmitFlags(clone, flags | (context.flags & NodeBuilderFlags.MultilineObjectLiterals && isTypeLiteralNode(node) ? 0 : EmitFlags.SingleLine));
          return clone;
        }
        if (isStringLiteral(node) && !!(context.flags & NodeBuilderFlags.UseSingleQuotesForStringLiteralType) && !node.singleQuote) {
          const clone = factory.cloneNode(node);
          clone.singleQuote = true;
          return clone;
        }
        if (isConditionalTypeNode(node)) {
          const checkType = visitNode(node.checkType, visitExistingNodeTreeSymbols, isTypeNode);
          const disposeScope = onEnterNewScope(node);
          const extendType = visitNode(node.extendsType, visitExistingNodeTreeSymbols, isTypeNode);
          const trueType2 = visitNode(node.trueType, visitExistingNodeTreeSymbols, isTypeNode);
          disposeScope();
          const falseType2 = visitNode(node.falseType, visitExistingNodeTreeSymbols, isTypeNode);
          return factory.updateConditionalTypeNode(
            node,
            checkType,
            extendType,
            trueType2,
            falseType2
          );
        }
        if (isTypeOperatorNode(node)) {
          if (node.operator === SyntaxKind.UniqueKeyword && node.type.kind === SyntaxKind.SymbolKeyword) {
            if (!canReuseTypeNode(context, node)) {
              hadError = true;
              return node;
            }
          } else if (node.operator === SyntaxKind.KeyOfKeyword) {
            const result = tryVisitKeyOf(node);
            if (!result) {
              hadError = true;
              return node;
            }
            return result;
          }
        }
        return visitEachChild(node, visitExistingNodeTreeSymbols);
        function visitEachChild(node2, visitor) {
          const nonlocalNode = !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(node2);
          return visitEachChildWorker(
            node2,
            visitor,
            /*context*/
            void 0,
            nonlocalNode ? visitNodesWithoutCopyingPositions : void 0
          );
        }
        function visitNodesWithoutCopyingPositions(nodes, visitor, test, start, count) {
          let result = visitNodes(nodes, visitor, test, start, count);
          if (result) {
            if (result.pos !== -1 || result.end !== -1) {
              if (result === nodes) {
                result = factory.createNodeArray(nodes.slice(), nodes.hasTrailingComma);
              }
              setTextRangePosEnd(result, -1, -1);
            }
          }
          return result;
        }
        function getEffectiveDotDotDotForParameter(p) {
          return p.dotDotDotToken || (p.type && isJSDocVariadicType(p.type) ? factory.createToken(SyntaxKind.DotDotDotToken) : void 0);
        }
        function getNameForJSDocFunctionParameter(p, index) {
          return p.name && isIdentifier(p.name) && p.name.escapedText === "this" ? "this" : getEffectiveDotDotDotForParameter(p) ? `args` : `arg${index}`;
        }
        function rewriteModuleSpecifier(parent, lit) {
          if (context.bundled || context.enclosingFile !== getSourceFileOfNode(lit)) {
            let name = lit.text;
            const nodeSymbol = getNodeLinks(node).resolvedSymbol;
            const meaning = parent.isTypeOf ? SymbolFlags.Value : SymbolFlags.Type;
            const parentSymbol = nodeSymbol && isSymbolAccessible(
              nodeSymbol,
              context.enclosingDeclaration,
              meaning,
              /*shouldComputeAliasesToMakeVisible*/
              false
            ).accessibility === SymbolAccessibility.Accessible && lookupSymbolChain(
              nodeSymbol,
              context,
              meaning,
              /*yieldModuleSymbol*/
              true
            )[0];
            if (parentSymbol && isExternalModuleSymbol(parentSymbol)) {
              name = getSpecifierForModuleSymbol(parentSymbol, context);
            } else {
              const targetFile = getExternalModuleFileFromDeclaration(parent);
              if (targetFile) {
                name = getSpecifierForModuleSymbol(targetFile.symbol, context);
              }
            }
            if (name.includes("/node_modules/")) {
              context.encounteredError = true;
              if (context.tracker.reportLikelyUnsafeImportRequiredError) {
                context.tracker.reportLikelyUnsafeImportRequiredError(name);
              }
            }
            if (name !== lit.text) {
              return setOriginalNode(factory.createStringLiteral(name), lit);
            }
          }
          return visitNode(lit, visitExistingNodeTreeSymbols, isStringLiteral);
        }
      }
    }
    function symbolTableToDeclarationStatements(symbolTable, context) {
      const serializePropertySymbolForClass = makeSerializePropertySymbol(
        factory.createPropertyDeclaration,
        SyntaxKind.MethodDeclaration,
        /*useAccessors*/
        true
      );
      const serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(
        (mods, name, question, type) => factory.createPropertySignature(mods, name, question, type),
        SyntaxKind.MethodSignature,
        /*useAccessors*/
        false
      );
      const enclosingDeclaration = context.enclosingDeclaration;
      let results = [];
      const visitedSymbols = /* @__PURE__ */ new Set();
      const deferredPrivatesStack = [];
      const oldcontext = context;
      context = {
        ...oldcontext,
        usedSymbolNames: new Set(oldcontext.usedSymbolNames),
        remappedSymbolNames: /* @__PURE__ */ new Map(),
        remappedSymbolReferences: new Map(oldcontext.remappedSymbolReferences?.entries()),
        tracker: void 0
      };
      const tracker = {
        ...oldcontext.tracker.inner,
        trackSymbol: (sym, decl, meaning) => {
          if (context.remappedSymbolNames?.has(getSymbolId(sym))) return false;
          const accessibleResult = isSymbolAccessible(
            sym,
            decl,
            meaning,
            /*shouldComputeAliasesToMakeVisible*/
            false
          );
          if (accessibleResult.accessibility === SymbolAccessibility.Accessible) {
            const chain = lookupSymbolChainWorker(sym, context, meaning);
            if (!(sym.flags & SymbolFlags.Property)) {
              const root = chain[0];
              const contextFile = getSourceFileOfNode(oldcontext.enclosingDeclaration);
              if (some(root.declarations, (d) => getSourceFileOfNode(d) === contextFile)) {
                includePrivateSymbol(root);
              }
            }
          } else if (oldcontext.tracker.inner?.trackSymbol) {
            return oldcontext.tracker.inner.trackSymbol(sym, decl, meaning);
          }
          return false;
        }
      };
      context.tracker = new SymbolTrackerImpl(context, tracker, oldcontext.tracker.moduleResolverHost);
      forEachEntry(symbolTable, (symbol, name) => {
        const baseName = unescapeLeadingUnderscores(name);
        void getInternalSymbolName(symbol, baseName);
      });
      let addingDeclare = !context.bundled;
      const exportEquals = symbolTable.get(InternalSymbolName.ExportEquals);
      if (exportEquals && symbolTable.size > 1 && exportEquals.flags & (SymbolFlags.Alias | SymbolFlags.Module)) {
        symbolTable = createSymbolTable();
        symbolTable.set(InternalSymbolName.ExportEquals, exportEquals);
      }
      visitSymbolTable(symbolTable);
      return mergeRedundantStatements(results);
      function isIdentifierAndNotUndefined(node) {
        return !!node && node.kind === SyntaxKind.Identifier;
      }
      function getNamesOfDeclaration(statement) {
        if (isVariableStatement(statement)) {
          return filter(map(statement.declarationList.declarations, getNameOfDeclaration), isIdentifierAndNotUndefined);
        }
        return filter([getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
      }
      function flattenExportAssignedNamespace(statements) {
        const exportAssignment = find(statements, isExportAssignment);
        const nsIndex = findIndex(statements, isModuleDeclaration);
        let ns = nsIndex !== -1 ? statements[nsIndex] : void 0;
        if (ns && exportAssignment && exportAssignment.isExportEquals && isIdentifier(exportAssignment.expression) && isIdentifier(ns.name) && idText(ns.name) === idText(exportAssignment.expression) && ns.body && isModuleBlock(ns.body)) {
          const excessExports = filter(statements, (s) => !!(getEffectiveModifierFlags(s) & ModifierFlags.Export));
          const name = ns.name;
          let body = ns.body;
          if (length(excessExports)) {
            ns = factory.updateModuleDeclaration(
              ns,
              ns.modifiers,
              ns.name,
              body = factory.updateModuleBlock(
                body,
                factory.createNodeArray([
                  ...ns.body.statements,
                  factory.createExportDeclaration(
                    /*modifiers*/
                    void 0,
                    /*isTypeOnly*/
                    false,
                    factory.createNamedExports(map(flatMap(excessExports, (e) => getNamesOfDeclaration(e)), (id) => factory.createExportSpecifier(
                      /*isTypeOnly*/
                      false,
                      /*propertyName*/
                      void 0,
                      id
                    ))),
                    /*moduleSpecifier*/
                    void 0
                  )
                ])
              )
            );
            statements = [...statements.slice(0, nsIndex), ns, ...statements.slice(nsIndex + 1)];
          }
          if (!find(statements, (s) => s !== ns && nodeHasName(s, name))) {
            results = [];
            const mixinExportFlag = !some(body.statements, (s) => hasSyntacticModifier(s, ModifierFlags.Export) || isExportAssignment(s) || isExportDeclaration(s));
            forEach(body.statements, (s) => {
              addResult(s, mixinExportFlag ? ModifierFlags.Export : ModifierFlags.None);
            });
            statements = [...filter(statements, (s) => s !== ns && s !== exportAssignment), ...results];
          }
        }
        return statements;
      }
      function mergeExportDeclarations(statements) {
        const exports = filter(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause));
        if (length(exports) > 1) {
          const nonExports = filter(statements, (d) => !isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause);
          statements = [
            ...nonExports,
            factory.createExportDeclaration(
              /*modifiers*/
              void 0,
              /*isTypeOnly*/
              false,
              factory.createNamedExports(flatMap(exports, (e) => cast(e.exportClause, isNamedExports).elements)),
              /*moduleSpecifier*/
              void 0
            )
          ];
        }
        const reexports = filter(statements, (d) => isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause));
        if (length(reexports) > 1) {
          const groups = group(reexports, (decl) => isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">");
          if (groups.length !== reexports.length) {
            for (const group2 of groups) {
              if (group2.length > 1) {
                statements = [
                  ...filter(statements, (s) => !group2.includes(s)),
                  factory.createExportDeclaration(
                    /*modifiers*/
                    void 0,
                    /*isTypeOnly*/
                    false,
                    factory.createNamedExports(flatMap(group2, (e) => cast(e.exportClause, isNamedExports).elements)),
                    group2[0].moduleSpecifier
                  )
                ];
              }
            }
          }
        }
        return statements;
      }
      function inlineExportModifiers(statements) {
        const index = findIndex(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !d.attributes && !!d.exportClause && isNamedExports(d.exportClause));
        if (index >= 0) {
          const exportDecl = statements[index];
          const replacements = mapDefined(exportDecl.exportClause.elements, (e) => {
            if (!e.propertyName && e.name.kind !== SyntaxKind.StringLiteral) {
              const name = e.name;
              const indices = indicesOf(statements);
              const associatedIndices = filter(indices, (i) => nodeHasName(statements[i], name));
              if (length(associatedIndices) && every(associatedIndices, (i) => canHaveExportModifier(statements[i]))) {
                for (const index2 of associatedIndices) {
                  statements[index2] = addExportModifier(statements[index2]);
                }
                return void 0;
              }
            }
            return e;
          });
          if (!length(replacements)) {
            orderedRemoveItemAt(statements, index);
          } else {
            statements[index] = factory.updateExportDeclaration(
              exportDecl,
              exportDecl.modifiers,
              exportDecl.isTypeOnly,
              factory.updateNamedExports(
                exportDecl.exportClause,
                replacements
              ),
              exportDecl.moduleSpecifier,
              exportDecl.attributes
            );
          }
        }
        return statements;
      }
      function mergeRedundantStatements(statements) {
        statements = flattenExportAssignedNamespace(statements);
        statements = mergeExportDeclarations(statements);
        statements = inlineExportModifiers(statements);
        if (enclosingDeclaration && (isSourceFile(enclosingDeclaration) && isExternalOrCommonJsModule(enclosingDeclaration) || isModuleDeclaration(enclosingDeclaration)) && (!some(statements, isExternalModuleIndicator) || !hasScopeMarker(statements) && some(statements, needsScopeMarker))) {
          statements.push(createEmptyExports(factory));
        }
        return statements;
      }
      function addExportModifier(node) {
        const flags = (getEffectiveModifierFlags(node) | ModifierFlags.Export) & ~ModifierFlags.Ambient;
        return factory.replaceModifiers(node, flags);
      }
      function removeExportModifier(node) {
        const flags = getEffectiveModifierFlags(node) & ~ModifierFlags.Export;
        return factory.replaceModifiers(node, flags);
      }
      function visitSymbolTable(symbolTable2, suppressNewPrivateContext, propertyAsAlias) {
        if (!suppressNewPrivateContext) {
          deferredPrivatesStack.push(/* @__PURE__ */ new Map());
        }
        symbolTable2.forEach((symbol) => {
          serializeSymbol(
            symbol,
            /*isPrivate*/
            false,
            !!propertyAsAlias
          );
        });
        if (!suppressNewPrivateContext) {
          deferredPrivatesStack[deferredPrivatesStack.length - 1].forEach((symbol) => {
            serializeSymbol(
              symbol,
              /*isPrivate*/
              true,
              !!propertyAsAlias
            );
          });
          deferredPrivatesStack.pop();
        }
      }
      function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
        void getPropertiesOfType(getTypeOfSymbol(symbol));
        const visitedSym = getMergedSymbol(symbol);
        if (visitedSymbols.has(getSymbolId(visitedSym))) {
          return;
        }
        visitedSymbols.add(getSymbolId(visitedSym));
        const skipMembershipCheck = !isPrivate;
        if (skipMembershipCheck || !!length(symbol.declarations) && some(symbol.declarations, (d) => !!findAncestor(d, (n) => n === enclosingDeclaration))) {
          const scopeCleanup = cloneNodeBuilderContext(context);
          serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
          scopeCleanup();
        }
      }
      function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias, escapedSymbolName = symbol.escapedName) {
        const symbolName2 = unescapeLeadingUnderscores(escapedSymbolName);
        const isDefault = escapedSymbolName === InternalSymbolName.Default;
        if (isPrivate && !(context.flags & NodeBuilderFlags.AllowAnonymousIdentifier) && isStringANonContextualKeyword(symbolName2) && !isDefault) {
          context.encounteredError = true;
          return;
        }
        let needsPostExportDefault = isDefault && !!(symbol.flags & SymbolFlags.ExportDoesNotSupportDefaultModifier || symbol.flags & SymbolFlags.Function && length(getPropertiesOfType(getTypeOfSymbol(symbol)))) && !(symbol.flags & SymbolFlags.Alias);
        let needsExportDeclaration = !needsPostExportDefault && !isPrivate && isStringANonContextualKeyword(symbolName2) && !isDefault;
        if (needsPostExportDefault || needsExportDeclaration) {
          isPrivate = true;
        }
        const modifierFlags = (!isPrivate ? ModifierFlags.Export : 0) | (isDefault && !needsPostExportDefault ? ModifierFlags.Default : 0);
        const isConstMergedWithNS = symbol.flags & SymbolFlags.Module && symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.FunctionScopedVariable | SymbolFlags.Property) && escapedSymbolName !== InternalSymbolName.ExportEquals;
        const isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
        if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method) || isConstMergedWithNSPrintableAsSignatureMerge) {
          serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
        }
        if (symbol.flags & SymbolFlags.TypeAlias) {
          serializeTypeAlias(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.FunctionScopedVariable | SymbolFlags.Property | SymbolFlags.Accessor) && escapedSymbolName !== InternalSymbolName.ExportEquals && !(symbol.flags & SymbolFlags.Prototype) && !(symbol.flags & SymbolFlags.Class) && !(symbol.flags & SymbolFlags.Method) && !isConstMergedWithNSPrintableAsSignatureMerge) {
          if (propertyAsAlias) {
            const createdExport = serializeMaybeAliasAssignment(symbol);
            if (createdExport) {
              needsExportDeclaration = false;
              needsPostExportDefault = false;
            }
          } else {
            const type = getTypeOfSymbol(symbol);
            const localName = getInternalSymbolName(symbol, symbolName2);
            if (type.symbol && type.symbol !== symbol && type.symbol.flags & SymbolFlags.Function && some(type.symbol.declarations, isFunctionExpressionOrArrowFunction) && (type.symbol.members?.size || type.symbol.exports?.size)) {
              if (!context.remappedSymbolReferences) {
                context.remappedSymbolReferences = /* @__PURE__ */ new Map();
              }
              context.remappedSymbolReferences.set(getSymbolId(type.symbol), symbol);
              serializeSymbolWorker(type.symbol, isPrivate, propertyAsAlias, escapedSymbolName);
              context.remappedSymbolReferences.delete(getSymbolId(type.symbol));
            } else if (!(symbol.flags & SymbolFlags.Function) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
              serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
            } else {
              const flags = !(symbol.flags & SymbolFlags.BlockScopedVariable) ? symbol.parent?.valueDeclaration && isSourceFile(symbol.parent?.valueDeclaration) ? NodeFlags.Const : void 0 : isConstantVariable(symbol) ? NodeFlags.Const : NodeFlags.Let;
              const name = needsPostExportDefault || !(symbol.flags & SymbolFlags.Property) ? localName : getUnusedName(localName, symbol);
              let textRange = symbol.declarations && find(symbol.declarations, (d) => isVariableDeclaration(d));
              if (textRange && isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
                textRange = textRange.parent.parent;
              }
              const propertyAccessRequire = symbol.declarations?.find(isPropertyAccessExpression);
              if (propertyAccessRequire && isBinaryExpression(propertyAccessRequire.parent) && isIdentifier(propertyAccessRequire.parent.right) && type.symbol?.valueDeclaration && isSourceFile(type.symbol.valueDeclaration)) {
                const alias = localName === propertyAccessRequire.parent.right.escapedText ? void 0 : propertyAccessRequire.parent.right;
                addResult(
                  factory.createExportDeclaration(
                    /*modifiers*/
                    void 0,
                    /*isTypeOnly*/
                    false,
                    factory.createNamedExports([factory.createExportSpecifier(
                      /*isTypeOnly*/
                      false,
                      alias,
                      localName
                    )])
                  ),
                  ModifierFlags.None
                );
                context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, SymbolFlags.Value);
              } else {
                const statement = setTextRange(
                  context,
                  factory.createVariableStatement(
                    /*modifiers*/
                    void 0,
                    factory.createVariableDeclarationList([
                      factory.createVariableDeclaration(
                        name,
                        /*exclamationToken*/
                        void 0,
                        serializeTypeForDeclaration(
                          context,
                          /*declaration*/
                          void 0,
                          type,
                          symbol
                        )
                      )
                    ], flags)
                  ),
                  textRange
                );
                addResult(statement, name !== localName ? modifierFlags & ~ModifierFlags.Export : modifierFlags);
                if (name !== localName && !isPrivate) {
                  addResult(
                    factory.createExportDeclaration(
                      /*modifiers*/
                      void 0,
                      /*isTypeOnly*/
                      false,
                      factory.createNamedExports([factory.createExportSpecifier(
                        /*isTypeOnly*/
                        false,
                        name,
                        localName
                      )])
                    ),
                    ModifierFlags.None
                  );
                  needsExportDeclaration = false;
                  needsPostExportDefault = false;
                }
              }
            }
          }
        }
        if (symbol.flags & SymbolFlags.Enum) {
          serializeEnum(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & SymbolFlags.Class) {
          if (symbol.flags & SymbolFlags.Property && symbol.valueDeclaration && isBinaryExpression(symbol.valueDeclaration.parent) && isClassExpression(symbol.valueDeclaration.parent.right)) {
            serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
          } else {
            serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
          }
        }
        if (symbol.flags & (SymbolFlags.ValueModule | SymbolFlags.NamespaceModule) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol)) || isConstMergedWithNSPrintableAsSignatureMerge) {
          serializeModule(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & SymbolFlags.Interface && !(symbol.flags & SymbolFlags.Class)) {
          serializeInterface(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & SymbolFlags.Alias) {
          serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
        }
        if (symbol.flags & SymbolFlags.Property && symbol.escapedName === InternalSymbolName.ExportEquals) {
          serializeMaybeAliasAssignment(symbol);
        }
        if (symbol.flags & SymbolFlags.ExportStar) {
          if (symbol.declarations) {
            for (const node of symbol.declarations) {
              const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
              if (!resolvedModule) continue;
              addResult(factory.createExportDeclaration(
                /*modifiers*/
                void 0,
                /*isTypeOnly*/
                node.isTypeOnly,
                /*exportClause*/
                void 0,
                factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))
              ), ModifierFlags.None);
            }
          }
        }
        if (needsPostExportDefault) {
          addResult(factory.createExportAssignment(
            /*modifiers*/
            void 0,
            /*isExportEquals*/
            false,
            factory.createIdentifier(getInternalSymbolName(symbol, symbolName2))
          ), ModifierFlags.None);
        } else if (needsExportDeclaration) {
          addResult(
            factory.createExportDeclaration(
              /*modifiers*/
              void 0,
              /*isTypeOnly*/
              false,
              factory.createNamedExports([factory.createExportSpecifier(
                /*isTypeOnly*/
                false,
                getInternalSymbolName(symbol, symbolName2),
                symbolName2
              )])
            ),
            ModifierFlags.None
          );
        }
      }
      function includePrivateSymbol(symbol) {
        if (some(symbol.declarations, isPartOfParameterDeclaration)) return;
        Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]);
        getUnusedName(unescapeLeadingUnderscores(symbol.escapedName), symbol);
        const isExternalImportAlias = !!(symbol.flags & SymbolFlags.Alias) && !some(symbol.declarations, (d) => !!findAncestor(d, isExportDeclaration) || isNamespaceExport(d) || isImportEqualsDeclaration(d) && !isExternalModuleReference(d.moduleReference));
        deferredPrivatesStack[isExternalImportAlias ? 0 : deferredPrivatesStack.length - 1].set(getSymbolId(symbol), symbol);
      }
      function isExportingScope(enclosingDeclaration2) {
        return isSourceFile(enclosingDeclaration2) && (isExternalOrCommonJsModule(enclosingDeclaration2) || isJsonSourceFile(enclosingDeclaration2)) || isAmbientModule(enclosingDeclaration2) && !isGlobalScopeAugmentation(enclosingDeclaration2);
      }
      function addResult(node, additionalModifierFlags) {
        if (canHaveModifiers(node)) {
          let newModifierFlags = ModifierFlags.None;
          const enclosingDeclaration2 = context.enclosingDeclaration && (isJSDocTypeAlias(context.enclosingDeclaration) ? getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration);
          if (additionalModifierFlags & ModifierFlags.Export && enclosingDeclaration2 && (isExportingScope(enclosingDeclaration2) || isModuleDeclaration(enclosingDeclaration2)) && canHaveExportModifier(node)) {
            newModifierFlags |= ModifierFlags.Export;
          }
          if (addingDeclare && !(newModifierFlags & ModifierFlags.Export) && (!enclosingDeclaration2 || !(enclosingDeclaration2.flags & NodeFlags.Ambient)) && (isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isModuleDeclaration(node))) {
            newModifierFlags |= ModifierFlags.Ambient;
          }
          if (additionalModifierFlags & ModifierFlags.Default && (isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionDeclaration(node))) {
            newModifierFlags |= ModifierFlags.Default;
          }
          if (newModifierFlags) {
            node = factory.replaceModifiers(node, newModifierFlags | getEffectiveModifierFlags(node));
          }
        }
        results.push(node);
      }
      function serializeTypeAlias(symbol, symbolName2, modifierFlags) {
        const aliasType = getDeclaredTypeOfTypeAlias(symbol);
        const typeParams = getSymbolLinks(symbol).typeParameters;
        const typeParamDecls = map(typeParams, (p) => typeParameterToDeclaration(p, context));
        const jsdocAliasDecl = symbol.declarations?.find(isJSDocTypeAlias);
        const commentText = getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : void 0);
        const restoreFlags = saveRestoreFlags(context);
        context.flags |= NodeBuilderFlags.InTypeAlias;
        const oldEnclosingDecl = context.enclosingDeclaration;
        context.enclosingDeclaration = jsdocAliasDecl;
        const typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && tryReuseExistingNonParameterTypeNode(
          context,
          jsdocAliasDecl.typeExpression.type,
          aliasType,
          /*host*/
          void 0
        ) || typeToTypeNodeHelper(aliasType, context);
        addResult(
          setSyntheticLeadingComments(
            factory.createTypeAliasDeclaration(
              /*modifiers*/
              void 0,
              getInternalSymbolName(symbol, symbolName2),
              typeParamDecls,
              typeNode
            ),
            !commentText ? [] : [{ kind: SyntaxKind.MultiLineCommentTrivia, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]
          ),
          modifierFlags
        );
        restoreFlags();
        context.enclosingDeclaration = oldEnclosingDecl;
      }
      function serializeInterface(symbol, symbolName2, modifierFlags) {
        const interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
        const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
        const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context));
        const baseTypes = getBaseTypes(interfaceType);
        const baseType = length(baseTypes) ? getIntersectionType(baseTypes) : void 0;
        const members = flatMap(getPropertiesOfType(interfaceType), (p) => serializePropertySymbolForInterface(p, baseType));
        const callSignatures = serializeSignatures(SignatureKind.Call, interfaceType, baseType, SyntaxKind.CallSignature);
        const constructSignatures = serializeSignatures(SignatureKind.Construct, interfaceType, baseType, SyntaxKind.ConstructSignature);
        const indexSignatures = serializeIndexSignatures(interfaceType, baseType);
        const heritageClauses = !length(baseTypes) ? void 0 : [factory.createHeritageClause(SyntaxKind.ExtendsKeyword, mapDefined(baseTypes, (b) => trySerializeAsTypeReference(b, SymbolFlags.Value)))];
        addResult(
          factory.createInterfaceDeclaration(
            /*modifiers*/
            void 0,
            getInternalSymbolName(symbol, symbolName2),
            typeParamDecls,
            heritageClauses,
            [...indexSignatures, ...constructSignatures, ...callSignatures, ...members]
          ),
          modifierFlags
        );
      }
      function getNamespaceMembersForSerialization(symbol) {
        let exports = arrayFrom(getExportsOfSymbol(symbol).values());
        const merged = getMergedSymbol(symbol);
        if (merged !== symbol) {
          const membersSet = new Set(exports);
          for (const exported of getExportsOfSymbol(merged).values()) {
            if (!(getSymbolFlags(resolveSymbol(exported)) & SymbolFlags.Value)) {
              membersSet.add(exported);
            }
          }
          exports = arrayFrom(membersSet);
        }
        return filter(exports, (m) => isNamespaceMember(m) && isIdentifierText(m.escapedName, ScriptTarget.ESNext));
      }
      function isTypeOnlyNamespace(symbol) {
        return every(getNamespaceMembersForSerialization(symbol), (m) => !(getSymbolFlags(resolveSymbol(m)) & SymbolFlags.Value));
      }
      function serializeModule(symbol, symbolName2, modifierFlags) {
        const members = getNamespaceMembersForSerialization(symbol);
        const locationMap = arrayToMultiMap(members, (m) => m.parent && m.parent === symbol ? "real" : "merged");
        const realMembers = locationMap.get("real") || emptyArray;
        const mergedMembers = locationMap.get("merged") || emptyArray;
        if (length(realMembers)) {
          const localName = getInternalSymbolName(symbol, symbolName2);
          serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (SymbolFlags.Function | SymbolFlags.Assignment)));
        }
        if (length(mergedMembers)) {
          const containingFile = getSourceFileOfNode(context.enclosingDeclaration);
          const localName = getInternalSymbolName(symbol, symbolName2);
          const nsBody = factory.createModuleBlock([factory.createExportDeclaration(
            /*modifiers*/
            void 0,
            /*isTypeOnly*/
            false,
            factory.createNamedExports(mapDefined(filter(mergedMembers, (n) => n.escapedName !== InternalSymbolName.ExportEquals), (s) => {
              const name = unescapeLeadingUnderscores(s.escapedName);
              const localName2 = getInternalSymbolName(s, name);
              const aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
              if (containingFile && (aliasDecl ? containingFile !== getSourceFileOfNode(aliasDecl) : !some(s.declarations, (d) => getSourceFileOfNode(d) === containingFile))) {
                context.tracker?.reportNonlocalAugmentation?.(containingFile, symbol, s);
                return void 0;
              }
              const target = aliasDecl && getTargetOfAliasDeclaration(
                aliasDecl,
                /*dontRecursivelyResolve*/
                true
              );
              includePrivateSymbol(target || s);
              const targetName = target ? getInternalSymbolName(target, unescapeLeadingUnderscores(target.escapedName)) : localName2;
              return factory.createExportSpecifier(
                /*isTypeOnly*/
                false,
                name === targetName ? void 0 : targetName,
                name
              );
            }))
          )]);
          addResult(
            factory.createModuleDeclaration(
              /*modifiers*/
              void 0,
              factory.createIdentifier(localName),
              nsBody,
              NodeFlags.Namespace
            ),
            ModifierFlags.None
          );
        }
      }
      function serializeEnum(symbol, symbolName2, modifierFlags) {
        addResult(
          factory.createEnumDeclaration(
            factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? ModifierFlags.Const : 0),
            getInternalSymbolName(symbol, symbolName2),
            map(filter(getPropertiesOfType(getTypeOfSymbol(symbol)), (p) => !!(p.flags & SymbolFlags.EnumMember)), (p) => {
              const initializedValue = p.declarations && p.declarations[0] && isEnumMember(p.declarations[0]) ? getConstantValue(p.declarations[0]) : void 0;
              return factory.createEnumMember(
                unescapeLeadingUnderscores(p.escapedName),
                initializedValue === void 0 ? void 0 : typeof initializedValue === "string" ? factory.createStringLiteral(initializedValue) : factory.createNumericLiteral(initializedValue)
              );
            })
          ),
          modifierFlags
        );
      }
      function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
        const signatures = getSignaturesOfType(type, SignatureKind.Call);
        for (const sig of signatures) {
          const decl = signatureToSignatureDeclarationHelper(sig, SyntaxKind.FunctionDeclaration, context, { name: factory.createIdentifier(localName) });
          addResult(setTextRange(context, decl, getSignatureTextRangeLocation(sig)), modifierFlags);
        }
        if (!(symbol.flags & (SymbolFlags.ValueModule | SymbolFlags.NamespaceModule) && !!symbol.exports && !!symbol.exports.size)) {
          const props = filter(getPropertiesOfType(type), isNamespaceMember);
          serializeAsNamespaceDeclaration(
            props,
            localName,
            modifierFlags,
            /*suppressNewPrivateContext*/
            true
          );
        }
      }
      function getSignatureTextRangeLocation(signature) {
        if (signature.declaration && signature.declaration.parent) {
          if (isBinaryExpression(signature.declaration.parent) && getAssignmentDeclarationKind(signature.declaration.parent) === AssignmentDeclarationKind.Property) {
            return signature.declaration.parent;
          }
          if (isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) {
            return signature.declaration.parent.parent;
          }
        }
        return signature.declaration;
      }
      function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
        if (length(props)) {
          const localVsRemoteMap = arrayToMultiMap(props, (p) => !length(p.declarations) || some(p.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)) ? "local" : "remote");
          const localProps = localVsRemoteMap.get("local") || emptyArray;
          let fakespace = parseNodeFactory.createModuleDeclaration(
            /*modifiers*/
            void 0,
            factory.createIdentifier(localName),
            factory.createModuleBlock([]),
            NodeFlags.Namespace
          );
          setParent(fakespace, enclosingDeclaration);
          fakespace.locals = createSymbolTable(props);
          fakespace.symbol = props[0].parent;
          const oldResults = results;
          results = [];
          const oldAddingDeclare = addingDeclare;
          addingDeclare = false;
          const subcontext = { ...context, enclosingDeclaration: fakespace };
          const oldContext = context;
          context = subcontext;
          visitSymbolTable(
            createSymbolTable(localProps),
            suppressNewPrivateContext,
            /*propertyAsAlias*/
            true
          );
          context = oldContext;
          addingDeclare = oldAddingDeclare;
          const declarations = results;
          results = oldResults;
          const defaultReplaced = map(declarations, (d) => isExportAssignment(d) && !d.isExportEquals && isIdentifier(d.expression) ? factory.createExportDeclaration(
            /*modifiers*/
            void 0,
            /*isTypeOnly*/
            false,
            factory.createNamedExports([factory.createExportSpecifier(
              /*isTypeOnly*/
              false,
              d.expression,
              factory.createIdentifier(InternalSymbolName.Default)
            )])
          ) : d);
          const exportModifierStripped = every(defaultReplaced, (d) => hasSyntacticModifier(d, ModifierFlags.Export)) ? map(defaultReplaced, removeExportModifier) : defaultReplaced;
          fakespace = factory.updateModuleDeclaration(
            fakespace,
            fakespace.modifiers,
            fakespace.name,
            factory.createModuleBlock(exportModifierStripped)
          );
          addResult(fakespace, modifierFlags);
        }
      }
      function isNamespaceMember(p) {
        return !!(p.flags & (SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias)) || !(p.flags & SymbolFlags.Prototype || p.escapedName === "prototype" || p.valueDeclaration && isStatic(p.valueDeclaration) && isClassLike(p.valueDeclaration.parent));
      }
      function sanitizeJSDocImplements(clauses) {
        const result = mapDefined(clauses, (e) => {
          const oldEnclosing = context.enclosingDeclaration;
          context.enclosingDeclaration = e;
          let expr = e.expression;
          if (isEntityNameExpression(expr)) {
            if (isIdentifier(expr) && idText(expr) === "") {
              return cleanup(
                /*result*/
                void 0
              );
            }
            let introducesError;
            ({ introducesError, node: expr } = trackExistingEntityName(expr, context));
            if (introducesError) {
              return cleanup(
                /*result*/
                void 0
              );
            }
          }
          return cleanup(factory.createExpressionWithTypeArguments(
            expr,
            map(e.typeArguments, (a) => tryReuseExistingNonParameterTypeNode(context, a, getTypeFromTypeNode2(context, a)) || typeToTypeNodeHelper(getTypeFromTypeNode2(context, a), context))
          ));
          function cleanup(result2) {
            context.enclosingDeclaration = oldEnclosing;
            return result2;
          }
        });
        if (result.length === clauses.length) {
          return result;
        }
        return void 0;
      }
      function serializeAsClass(symbol, localName, modifierFlags) {
        const originalDecl = symbol.declarations?.find(isClassLike);
        const oldEnclosing = context.enclosingDeclaration;
        context.enclosingDeclaration = originalDecl || oldEnclosing;
        const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
        const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context));
        const classType = getTypeWithThisArgument(getDeclaredTypeOfClassOrInterface(symbol));
        const baseTypes = getBaseTypes(classType);
        const originalImplements = originalDecl && getEffectiveImplementsTypeNodes(originalDecl);
        const implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || mapDefined(getImplementsTypes(classType), serializeImplementedType);
        const staticType = getTypeOfSymbol(symbol);
        const isClass = !!staticType.symbol?.valueDeclaration && isClassLike(staticType.symbol.valueDeclaration);
        const staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType;
        const heritageClauses = [
          ...!length(baseTypes) ? [] : [factory.createHeritageClause(SyntaxKind.ExtendsKeyword, map(baseTypes, (b) => serializeBaseType(b, staticBaseType, localName)))],
          ...!length(implementsExpressions) ? [] : [factory.createHeritageClause(SyntaxKind.ImplementsKeyword, implementsExpressions)]
        ];
        const symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType));
        const publicSymbolProps = filter(symbolProps, (s) => {
          const valueDecl = s.valueDeclaration;
          return !!valueDecl && !(isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name));
        });
        const hasPrivateIdentifier = some(symbolProps, (s) => {
          const valueDecl = s.valueDeclaration;
          return !!valueDecl && isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name);
        });
        const privateProperties = hasPrivateIdentifier ? [factory.createPropertyDeclaration(
          /*modifiers*/
          void 0,
          factory.createPrivateIdentifier("#private"),
          /*questionOrExclamationToken*/
          void 0,
          /*type*/
          void 0,
          /*initializer*/
          void 0
        )] : emptyArray;
        const publicProperties = flatMap(publicSymbolProps, (p) => serializePropertySymbolForClass(
          p,
          /*isStatic*/
          false,
          baseTypes[0]
        ));
        const staticMembers = flatMap(
          filter(getPropertiesOfType(staticType), (p) => !(p.flags & SymbolFlags.Prototype) && p.escapedName !== "prototype" && !isNamespaceMember(p)),
          (p) => serializePropertySymbolForClass(
            p,
            /*isStatic*/
            true,
            staticBaseType
          )
        );
        const isNonConstructableClassLikeInJsFile = !isClass && !!symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && !some(getSignaturesOfType(staticType, SignatureKind.Construct));
        const constructors = isNonConstructableClassLikeInJsFile ? [factory.createConstructorDeclaration(
          factory.createModifiersFromModifierFlags(ModifierFlags.Private),
          [],
          /*body*/
          void 0
        )] : serializeSignatures(SignatureKind.Construct, staticType, staticBaseType, SyntaxKind.Constructor);
        const indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
        context.enclosingDeclaration = oldEnclosing;
        addResult(
          setTextRange(
            context,
            factory.createClassDeclaration(
              /*modifiers*/
              void 0,
              localName,
              typeParamDecls,
              heritageClauses,
              [...indexSignatures, ...staticMembers, ...constructors, ...publicProperties, ...privateProperties]
            ),
            symbol.declarations && filter(symbol.declarations, (d) => isClassDeclaration(d) || isClassExpression(d))[0]
          ),
          modifierFlags
        );
      }
      function getSomeTargetNameFromDeclarations(declarations) {
        return firstDefined(declarations, (d) => {
          if (isImportSpecifier(d) || isExportSpecifier(d)) {
            return moduleExportNameTextUnescaped(d.propertyName || d.name);
          }
          if (isBinaryExpression(d) || isExportAssignment(d)) {
            const expression = isExportAssignment(d) ? d.expression : d.right;
            if (isPropertyAccessExpression(expression)) {
              return idText(expression.name);
            }
          }
          if (isAliasSymbolDeclaration(d)) {
            const name = getNameOfDeclaration(d);
            if (name && isIdentifier(name)) {
              return idText(name);
            }
          }
          return void 0;
        });
      }
      function serializeAsAlias(symbol, localName, modifierFlags) {
        const node = getDeclarationOfAliasSymbol(symbol);
        if (!node) return Debug.fail();
        const target = getMergedSymbol(getTargetOfAliasDeclaration(
          node,
          /*dontRecursivelyResolve*/
          true
        ));
        if (!target) {
          return;
        }
        let verbatimTargetName = isShorthandAmbientModuleSymbol(target) && getSomeTargetNameFromDeclarations(symbol.declarations) || unescapeLeadingUnderscores(target.escapedName);
        if (verbatimTargetName === InternalSymbolName.ExportEquals && allowSyntheticDefaultImports) {
          verbatimTargetName = InternalSymbolName.Default;
        }
        const targetName = getInternalSymbolName(target, verbatimTargetName);
        includePrivateSymbol(target);
        switch (node.kind) {
          case SyntaxKind.BindingElement:
            if (node.parent?.parent?.kind === SyntaxKind.VariableDeclaration) {
              const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context);
              const { propertyName } = node;
              addResult(
                factory.createImportDeclaration(
                  /*modifiers*/
                  void 0,
                  factory.createImportClause(
                    /*isTypeOnly*/
                    false,
                    /*name*/
                    void 0,
                    factory.createNamedImports([factory.createImportSpecifier(
                      /*isTypeOnly*/
                      false,
                      propertyName && isIdentifier(propertyName) ? factory.createIdentifier(idText(propertyName)) : void 0,
                      factory.createIdentifier(localName)
                    )])
                  ),
                  factory.createStringLiteral(specifier2),
                  /*attributes*/
                  void 0
                ),
                ModifierFlags.None
              );
              break;
            }
            Debug.failBadSyntaxKind(node.parent?.parent || node, "Unhandled binding element grandparent kind in declaration serialization");
            break;
          case SyntaxKind.ShorthandPropertyAssignment:
            if (node.parent?.parent?.kind === SyntaxKind.BinaryExpression) {
              serializeExportSpecifier(
                unescapeLeadingUnderscores(symbol.escapedName),
                targetName
              );
            }
            break;
          case SyntaxKind.VariableDeclaration:
            if (isPropertyAccessExpression(node.initializer)) {
              const initializer = node.initializer;
              const uniqueName = factory.createUniqueName(localName);
              const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context);
              addResult(
                factory.createImportEqualsDeclaration(
                  /*modifiers*/
                  void 0,
                  /*isTypeOnly*/
                  false,
                  uniqueName,
                  factory.createExternalModuleReference(factory.createStringLiteral(specifier2))
                ),
                ModifierFlags.None
              );
              addResult(
                factory.createImportEqualsDeclaration(
                  /*modifiers*/
                  void 0,
                  /*isTypeOnly*/
                  false,
                  factory.createIdentifier(localName),
                  factory.createQualifiedName(uniqueName, initializer.name)
                ),
                modifierFlags
              );
              break;
            }
          // else fall through and treat commonjs require just like import=
          case SyntaxKind.ImportEqualsDeclaration:
            if (target.escapedName === InternalSymbolName.ExportEquals && some(target.declarations, (d) => isSourceFile(d) && isJsonSourceFile(d))) {
              serializeMaybeAliasAssignment(symbol);
              break;
            }
            const isLocalImport = !(target.flags & SymbolFlags.ValueModule) && !isVariableDeclaration(node);
            addResult(
              factory.createImportEqualsDeclaration(
                /*modifiers*/
                void 0,
                /*isTypeOnly*/
                false,
                factory.createIdentifier(localName),
                isLocalImport ? symbolToName(
                  target,
                  context,
                  SymbolFlags.All,
                  /*expectsIdentifier*/
                  false
                ) : factory.createExternalModuleReference(factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))
              ),
              isLocalImport ? modifierFlags : ModifierFlags.None
            );
            break;
          case SyntaxKind.NamespaceExportDeclaration:
            addResult(factory.createNamespaceExportDeclaration(idText(node.name)), ModifierFlags.None);
            break;
          case SyntaxKind.ImportClause: {
            const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context);
            const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.moduleSpecifier;
            const attributes = isImportDeclaration(node.parent) ? node.parent.attributes : void 0;
            const isTypeOnly = isJSDocImportTag(node.parent);
            addResult(
              factory.createImportDeclaration(
                /*modifiers*/
                void 0,
                factory.createImportClause(
                  isTypeOnly,
                  factory.createIdentifier(localName),
                  /*namedBindings*/
                  void 0
                ),
                specifier2,
                attributes
              ),
              ModifierFlags.None
            );
            break;
          }
          case SyntaxKind.NamespaceImport: {
            const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context);
            const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.moduleSpecifier;
            const isTypeOnly = isJSDocImportTag(node.parent.parent);
            addResult(
              factory.createImportDeclaration(
                /*modifiers*/
                void 0,
                factory.createImportClause(
                  isTypeOnly,
                  /*name*/
                  void 0,
                  factory.createNamespaceImport(factory.createIdentifier(localName))
                ),
                specifier2,
                node.parent.attributes
              ),
              ModifierFlags.None
            );
            break;
          }
          case SyntaxKind.NamespaceExport:
            addResult(
              factory.createExportDeclaration(
                /*modifiers*/
                void 0,
                /*isTypeOnly*/
                false,
                factory.createNamespaceExport(factory.createIdentifier(localName)),
                factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))
              ),
              ModifierFlags.None
            );
            break;
          case SyntaxKind.ImportSpecifier: {
            const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context);
            const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.parent.moduleSpecifier;
            const isTypeOnly = isJSDocImportTag(node.parent.parent.parent);
            addResult(
              factory.createImportDeclaration(
                /*modifiers*/
                void 0,
                factory.createImportClause(
                  isTypeOnly,
                  /*name*/
                  void 0,
                  factory.createNamedImports([
                    factory.createImportSpecifier(
                      /*isTypeOnly*/
                      false,
                      localName !== verbatimTargetName ? factory.createIdentifier(verbatimTargetName) : void 0,
                      factory.createIdentifier(localName)
                    )
                  ])
                ),
                specifier2,
                node.parent.parent.parent.attributes
              ),
              ModifierFlags.None
            );
            break;
          }
          case SyntaxKind.ExportSpecifier:
            const specifier = node.parent.parent.moduleSpecifier;
            if (specifier) {
              const propertyName = node.propertyName;
              if (propertyName && moduleExportNameIsDefault(propertyName)) {
                verbatimTargetName = InternalSymbolName.Default;
              }
            }
            serializeExportSpecifier(
              unescapeLeadingUnderscores(symbol.escapedName),
              specifier ? verbatimTargetName : targetName,
              specifier && isStringLiteralLike(specifier) ? factory.createStringLiteral(specifier.text) : void 0
            );
            break;
          case SyntaxKind.ExportAssignment:
            serializeMaybeAliasAssignment(symbol);
            break;
          case SyntaxKind.BinaryExpression:
          case SyntaxKind.PropertyAccessExpression:
          case SyntaxKind.ElementAccessExpression:
            if (symbol.escapedName === InternalSymbolName.Default || symbol.escapedName === InternalSymbolName.ExportEquals) {
              serializeMaybeAliasAssignment(symbol);
            } else {
              serializeExportSpecifier(localName, targetName);
            }
            break;
          default:
            return Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
        }
      }
      function serializeExportSpecifier(localName, targetName, specifier) {
        addResult(
          factory.createExportDeclaration(
            /*modifiers*/
            void 0,
            /*isTypeOnly*/
            false,
            factory.createNamedExports([factory.createExportSpecifier(
              /*isTypeOnly*/
              false,
              localName !== targetName ? targetName : void 0,
              localName
            )]),
            specifier
          ),
          ModifierFlags.None
        );
      }
      function serializeMaybeAliasAssignment(symbol) {
        if (symbol.flags & SymbolFlags.Prototype) {
          return false;
        }
        const name = unescapeLeadingUnderscores(symbol.escapedName);
        const isExportEquals = name === InternalSymbolName.ExportEquals;
        const isDefault = name === InternalSymbolName.Default;
        const isExportAssignmentCompatibleSymbolName = isExportEquals || isDefault;
        const aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
        const target = aliasDecl && getTargetOfAliasDeclaration(
          aliasDecl,
          /*dontRecursivelyResolve*/
          true
        );
        if (target && length(target.declarations) && some(target.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(enclosingDeclaration))) {
          const expr = aliasDecl && (isExportAssignment(aliasDecl) || isBinaryExpression(aliasDecl) ? getExportAssignmentExpression(aliasDecl) : getPropertyAssignmentAliasLikeExpression(aliasDecl));
          const first2 = expr && isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : void 0;
          const referenced = first2 && resolveEntityName(
            first2,
            SymbolFlags.All,
            /*ignoreErrors*/
            true,
            /*dontResolveAlias*/
            true,
            enclosingDeclaration
          );
          if (referenced || target) {
            includePrivateSymbol(referenced || target);
          }
          const prevDisableTrackSymbol = context.tracker.disableTrackSymbol;
          context.tracker.disableTrackSymbol = true;
          if (isExportAssignmentCompatibleSymbolName) {
            results.push(factory.createExportAssignment(
              /*modifiers*/
              void 0,
              isExportEquals,
              symbolToExpression(target, context, SymbolFlags.All)
            ));
          } else {
            if (first2 === expr && first2) {
              serializeExportSpecifier(name, idText(first2));
            } else if (expr && isClassExpression(expr)) {
              serializeExportSpecifier(name, getInternalSymbolName(target, symbolName(target)));
            } else {
              const varName = getUnusedName(name, symbol);
              addResult(
                factory.createImportEqualsDeclaration(
                  /*modifiers*/
                  void 0,
                  /*isTypeOnly*/
                  false,
                  factory.createIdentifier(varName),
                  symbolToName(
                    target,
                    context,
                    SymbolFlags.All,
                    /*expectsIdentifier*/
                    false
                  )
                ),
                ModifierFlags.None
              );
              serializeExportSpecifier(name, varName);
            }
          }
          context.tracker.disableTrackSymbol = prevDisableTrackSymbol;
          return true;
        } else {
          const varName = getUnusedName(name, symbol);
          const typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
          if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
            serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? ModifierFlags.None : ModifierFlags.Export);
          } else {
            const flags = context.enclosingDeclaration?.kind === SyntaxKind.ModuleDeclaration && (!(symbol.flags & SymbolFlags.Accessor) || symbol.flags & SymbolFlags.SetAccessor) ? NodeFlags.Let : NodeFlags.Const;
            const statement = factory.createVariableStatement(
              /*modifiers*/
              void 0,
              factory.createVariableDeclarationList([
                factory.createVariableDeclaration(
                  varName,
                  /*exclamationToken*/
                  void 0,
                  serializeTypeForDeclaration(
                    context,
                    /*declaration*/
                    void 0,
                    typeToSerialize,
                    symbol
                  )
                )
              ], flags)
            );
            addResult(
              statement,
              target && target.flags & SymbolFlags.Property && target.escapedName === InternalSymbolName.ExportEquals ? ModifierFlags.Ambient : name === varName ? ModifierFlags.Export : ModifierFlags.None
            );
          }
          if (isExportAssignmentCompatibleSymbolName) {
            results.push(factory.createExportAssignment(
              /*modifiers*/
              void 0,
              isExportEquals,
              factory.createIdentifier(varName)
            ));
            return true;
          } else if (name !== varName) {
            serializeExportSpecifier(name, varName);
            return true;
          }
          return false;
        }
      }
      function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
        const ctxSrc = getSourceFileOfNode(context.enclosingDeclaration);
        return getObjectFlags(typeToSerialize) & (ObjectFlags.Anonymous | ObjectFlags.Mapped) && !some(typeToSerialize.symbol?.declarations, isTypeNode) && // If the type comes straight from a type node, we shouldn't try to break it up
        !length(getIndexInfosOfType(typeToSerialize)) && !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class
        !!(length(filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || length(getSignaturesOfType(typeToSerialize, SignatureKind.Call))) && !length(getSignaturesOfType(typeToSerialize, SignatureKind.Construct)) && // TODO: could probably serialize as function + ns + class, now that that's OK
        !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && !some(getPropertiesOfType(typeToSerialize), (p) => isLateBoundName(p.escapedName)) && !some(getPropertiesOfType(typeToSerialize), (p) => some(p.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && every(getPropertiesOfType(typeToSerialize), (p) => {
          if (!isIdentifierText(symbolName(p), languageVersion)) {
            return false;
          }
          if (!(p.flags & SymbolFlags.Accessor)) {
            return true;
          }
          return getNonMissingTypeOfSymbol(p) === getWriteTypeOfSymbol(p);
        });
      }
      function makeSerializePropertySymbol(createProperty2, methodKind, useAccessors) {
        return function serializePropertySymbol(p, isStatic2, baseType) {
          const modifierFlags = getDeclarationModifierFlagsFromSymbol(p);
          const isPrivate = !!(modifierFlags & ModifierFlags.Private);
          if (isStatic2 && p.flags & (SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias)) {
            return [];
          }
          if (p.flags & SymbolFlags.Prototype || p.escapedName === "constructor" || baseType && getPropertyOfType(baseType, p.escapedName) && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) && (p.flags & SymbolFlags.Optional) === (getPropertyOfType(baseType, p.escapedName).flags & SymbolFlags.Optional) && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName))) {
            return [];
          }
          const flag = modifierFlags & ~ModifierFlags.Async | (isStatic2 ? ModifierFlags.Static : 0);
          const name = getPropertyNameNodeForSymbol(p, context);
          const firstPropertyLikeDecl = p.declarations?.find(or(isPropertyDeclaration, isAccessor, isVariableDeclaration, isPropertySignature, isBinaryExpression, isPropertyAccessExpression));
          if (p.flags & SymbolFlags.Accessor && useAccessors) {
            const result = [];
            if (p.flags & SymbolFlags.SetAccessor) {
              const setter = p.declarations && forEach(p.declarations, (d) => {
                if (d.kind === SyntaxKind.SetAccessor) {
                  return d;
                }
                if (isCallExpression(d) && isBindableObjectDefinePropertyCall(d)) {
                  return forEach(d.arguments[2].properties, (propDecl) => {
                    const id = getNameOfDeclaration(propDecl);
                    if (!!id && isIdentifier(id) && idText(id) === "set") {
                      return propDecl;
                    }
                  });
                }
              });
              Debug.assert(!!setter);
              const paramSymbol = isFunctionLikeDeclaration(setter) ? getSignatureFromDeclaration(setter).parameters[0] : void 0;
              result.push(setTextRange(
                context,
                factory.createSetAccessorDeclaration(
                  factory.createModifiersFromModifierFlags(flag),
                  name,
                  [factory.createParameterDeclaration(
                    /*modifiers*/
                    void 0,
                    /*dotDotDotToken*/
                    void 0,
                    paramSymbol ? parameterToParameterDeclarationName(paramSymbol, getEffectiveParameterDeclaration(paramSymbol), context) : "value",
                    /*questionToken*/
                    void 0,
                    isPrivate ? void 0 : serializeTypeForDeclaration(
                      context,
                      /*declaration*/
                      void 0,
                      getWriteTypeOfSymbol(p),
                      p
                    )
                  )],
                  /*body*/
                  void 0
                ),
                p.declarations?.find(isSetAccessor) || firstPropertyLikeDecl
              ));
            }
            if (p.flags & SymbolFlags.GetAccessor) {
              const isPrivate2 = modifierFlags & ModifierFlags.Private;
              result.push(setTextRange(
                context,
                factory.createGetAccessorDeclaration(
                  factory.createModifiersFromModifierFlags(flag),
                  name,
                  [],
                  isPrivate2 ? void 0 : serializeTypeForDeclaration(
                    context,
                    /*declaration*/
                    void 0,
                    getTypeOfSymbol(p),
                    p
                  ),
                  /*body*/
                  void 0
                ),
                p.declarations?.find(isGetAccessor) || firstPropertyLikeDecl
              ));
            }
            return result;
          } else if (p.flags & (SymbolFlags.Property | SymbolFlags.Variable | SymbolFlags.Accessor)) {
            return setTextRange(
              context,
              createProperty2(
                factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? ModifierFlags.Readonly : 0) | flag),
                name,
                p.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : void 0,
                isPrivate ? void 0 : serializeTypeForDeclaration(
                  context,
                  /*declaration*/
                  void 0,
                  getWriteTypeOfSymbol(p),
                  p
                ),
                // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
                // interface members can't have initializers, however class members _can_
                /*initializer*/
                void 0
              ),
              p.declarations?.find(or(isPropertyDeclaration, isVariableDeclaration)) || firstPropertyLikeDecl
            );
          }
          if (p.flags & (SymbolFlags.Method | SymbolFlags.Function)) {
            const type = getTypeOfSymbol(p);
            const signatures = getSignaturesOfType(type, SignatureKind.Call);
            if (flag & ModifierFlags.Private) {
              return setTextRange(
                context,
                createProperty2(
                  factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? ModifierFlags.Readonly : 0) | flag),
                  name,
                  p.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : void 0,
                  /*type*/
                  void 0,
                  /*initializer*/
                  void 0
                ),
                p.declarations?.find(isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]
              );
            }
            const results2 = [];
            for (const sig of signatures) {
              const decl = signatureToSignatureDeclarationHelper(
                sig,
                methodKind,
                context,
                {
                  name,
                  questionToken: p.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : void 0,
                  modifiers: flag ? factory.createModifiersFromModifierFlags(flag) : void 0
                }
              );
              const location = sig.declaration && isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration;
              results2.push(setTextRange(context, decl, location));
            }
            return results2;
          }
          return Debug.fail(`Unhandled class member kind! ${p.__debugFlags || p.flags}`);
        };
      }
      function serializePropertySymbolForInterface(p, baseType) {
        return serializePropertySymbolForInterfaceWorker(
          p,
          /*isStatic*/
          false,
          baseType
        );
      }
      function serializeSignatures(kind, input, baseType, outputKind) {
        const signatures = getSignaturesOfType(input, kind);
        if (kind === SignatureKind.Construct) {
          if (!baseType && every(signatures, (s) => length(s.parameters) === 0)) {
            return [];
          }
          if (baseType) {
            const baseSigs = getSignaturesOfType(baseType, SignatureKind.Construct);
            if (!length(baseSigs) && every(signatures, (s) => length(s.parameters) === 0)) {
              return [];
            }
            if (baseSigs.length === signatures.length) {
              let failed = false;
              for (let i = 0; i < baseSigs.length; i++) {
                if (!compareSignaturesIdentical(
                  signatures[i],
                  baseSigs[i],
                  /*partialMatch*/
                  false,
                  /*ignoreThisTypes*/
                  false,
                  /*ignoreReturnTypes*/
                  true,
                  compareTypesIdentical
                )) {
                  failed = true;
                  break;
                }
              }
              if (!failed) {
                return [];
              }
            }
          }
          let privateProtected = 0;
          for (const s of signatures) {
            if (s.declaration) {
              privateProtected |= getSelectedEffectiveModifierFlags(s.declaration, ModifierFlags.Private | ModifierFlags.Protected);
            }
          }
          if (privateProtected) {
            return [setTextRange(
              context,
              factory.createConstructorDeclaration(
                factory.createModifiersFromModifierFlags(privateProtected),
                /*parameters*/
                [],
                /*body*/
                void 0
              ),
              signatures[0].declaration
            )];
          }
        }
        const results2 = [];
        for (const sig of signatures) {
          const decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
          results2.push(setTextRange(context, decl, sig.declaration));
        }
        return results2;
      }
      function serializeIndexSignatures(input, baseType) {
        const results2 = [];
        for (const info of getIndexInfosOfType(input)) {
          if (baseType) {
            const baseInfo = getIndexInfoOfType(baseType, info.keyType);
            if (baseInfo) {
              if (isTypeIdenticalTo(info.type, baseInfo.type)) {
                continue;
              }
            }
          }
          results2.push(indexInfoToIndexSignatureDeclarationHelper(
            info,
            context,
            /*typeNode*/
            void 0
          ));
        }
        return results2;
      }
      function serializeBaseType(t, staticType, rootName) {
        const ref = trySerializeAsTypeReference(t, SymbolFlags.Value);
        if (ref) {
          return ref;
        }
        const tempName = getUnusedName(`${rootName}_base`);
        const statement = factory.createVariableStatement(
          /*modifiers*/
          void 0,
          factory.createVariableDeclarationList([
            factory.createVariableDeclaration(
              tempName,
              /*exclamationToken*/
              void 0,
              typeToTypeNodeHelper(staticType, context)
            )
          ], NodeFlags.Const)
        );
        addResult(statement, ModifierFlags.None);
        return factory.createExpressionWithTypeArguments(
          factory.createIdentifier(tempName),
          /*typeArguments*/
          void 0
        );
      }
      function trySerializeAsTypeReference(t, flags) {
        let typeArgs;
        let reference;
        if (t.target && isSymbolAccessibleByFlags(t.target.symbol, enclosingDeclaration, flags)) {
          typeArgs = map(getTypeArguments(t), (t2) => typeToTypeNodeHelper(t2, context));
          reference = symbolToExpression(t.target.symbol, context, SymbolFlags.Type);
        } else if (t.symbol && isSymbolAccessibleByFlags(t.symbol, enclosingDeclaration, flags)) {
          reference = symbolToExpression(t.symbol, context, SymbolFlags.Type);
        }
        if (reference) {
          return factory.createExpressionWithTypeArguments(reference, typeArgs);
        }
      }
      function serializeImplementedType(t) {
        const ref = trySerializeAsTypeReference(t, SymbolFlags.Type);
        if (ref) {
          return ref;
        }
        if (t.symbol) {
          return factory.createExpressionWithTypeArguments(
            symbolToExpression(t.symbol, context, SymbolFlags.Type),
            /*typeArguments*/
            void 0
          );
        }
      }
      function getUnusedName(input, symbol) {
        const id = symbol ? getSymbolId(symbol) : void 0;
        if (id) {
          if (context.remappedSymbolNames.has(id)) {
            return context.remappedSymbolNames.get(id);
          }
        }
        if (symbol) {
          input = getNameCandidateWorker(symbol, input);
        }
        let i = 0;
        const original = input;
        while (context.usedSymbolNames?.has(input)) {
          i++;
          input = `${original}_${i}`;
        }
        context.usedSymbolNames?.add(input);
        if (id) {
          context.remappedSymbolNames.set(id, input);
        }
        return input;
      }
      function getNameCandidateWorker(symbol, localName) {
        if (localName === InternalSymbolName.Default || localName === InternalSymbolName.Class || localName === InternalSymbolName.Function) {
          const restoreFlags = saveRestoreFlags(context);
          context.flags |= NodeBuilderFlags.InInitialEntityName;
          const nameCandidate = getNameOfSymbolAsWritten(symbol, context);
          restoreFlags();
          localName = nameCandidate.length > 0 && isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? stripQuotes(nameCandidate) : nameCandidate;
        }
        if (localName === InternalSymbolName.Default) {
          localName = "_default";
        } else if (localName === InternalSymbolName.ExportEquals) {
          localName = "_exports";
        }
        localName = isIdentifierText(localName, languageVersion) && !isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-z0-9]/gi, "_");
        return localName;
      }
      function getInternalSymbolName(symbol, localName) {
        const id = getSymbolId(symbol);
        if (context.remappedSymbolNames.has(id)) {
          return context.remappedSymbolNames.get(id);
        }
        localName = getNameCandidateWorker(symbol, localName);
        context.remappedSymbolNames.set(id, localName);
        return localName;
      }
    }
  }
  function typePredicateToString(typePredicate, enclosingDeclaration, flags = TypeFormatFlags.UseAliasDefinedOutsideCurrentScope, writer) {
    return writer ? typePredicateToStringWorker(writer).getText() : usingSingleLineStringWriter(typePredicateToStringWorker);
    function typePredicateToStringWorker(writer2) {
      const nodeBuilderFlags = toNodeBuilderFlags(flags) | NodeBuilderFlags.IgnoreErrors | NodeBuilderFlags.WriteTypeParametersInQualifiedName;
      const predicate = nodeBuilder.typePredicateToTypePredicateNode(typePredicate, enclosingDeclaration, nodeBuilderFlags);
      const printer = createPrinterWithRemoveComments();
      const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
      printer.writeNode(
        EmitHint.Unspecified,
        predicate,
        /*sourceFile*/
        sourceFile,
        writer2
      );
      return writer2;
    }
  }
  function formatUnionTypes(types) {
    const result = [];
    let flags = 0;
    for (let i = 0; i < types.length; i++) {
      const t = types[i];
      flags |= t.flags;
      if (!(t.flags & TypeFlags.Nullable)) {
        if (t.flags & (TypeFlags.BooleanLiteral | TypeFlags.EnumLike)) {
          const baseType = t.flags & TypeFlags.BooleanLiteral ? booleanType : getBaseTypeOfEnumLikeType(t);
          if (baseType.flags & TypeFlags.Union) {
            const count = baseType.types.length;
            if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
              result.push(baseType);
              i += count - 1;
              continue;
            }
          }
        }
        result.push(t);
      }
    }
    if (flags & TypeFlags.Null) result.push(nullType);
    if (flags & TypeFlags.Undefined) result.push(undefinedType);
    return result || types;
  }
  function visibilityToString(flags) {
    if (flags === ModifierFlags.Private) {
      return "private";
    }
    if (flags === ModifierFlags.Protected) {
      return "protected";
    }
    return "public";
  }
  function getTypeAliasForTypeLiteral(type) {
    if (type.symbol && type.symbol.flags & SymbolFlags.TypeLiteral && type.symbol.declarations) {
      const node = walkUpParenthesizedTypes(type.symbol.declarations[0].parent);
      if (isTypeAliasDeclaration(node)) {
        return getSymbolOfDeclaration(node);
      }
    }
    return void 0;
  }
  function isTopLevelInExternalModuleAugmentation(node) {
    return node && node.parent && node.parent.kind === SyntaxKind.ModuleBlock && isExternalModuleAugmentation(node.parent.parent);
  }
  function isDefaultBindingContext(location) {
    return location.kind === SyntaxKind.SourceFile || isAmbientModule(location);
  }
  function getNameOfSymbolFromNameType(symbol, context) {
    const nameType = getSymbolLinks(symbol).nameType;
    if (nameType) {
      if (nameType.flags & TypeFlags.StringOrNumberLiteral) {
        const name = "" + nameType.value;
        if (!isIdentifierText(name, getEmitScriptTarget(compilerOptions)) && !isNumericLiteralName(name)) {
          return `"${escapeString(name, CharacterCodes.doubleQuote)}"`;
        }
        if (isNumericLiteralName(name) && startsWith(name, "-")) {
          return `[${name}]`;
        }
        return name;
      }
      if (nameType.flags & TypeFlags.UniqueESSymbol) {
        return `[${getNameOfSymbolAsWritten(nameType.symbol, context)}]`;
      }
    }
  }
  function getNameOfSymbolAsWritten(symbol, context) {
    if (context?.remappedSymbolReferences?.has(getSymbolId(symbol))) {
      symbol = context.remappedSymbolReferences.get(getSymbolId(symbol));
    }
    if (context && symbol.escapedName === InternalSymbolName.Default && !(context.flags & NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope) && // If it's not the first part of an entity name, it must print as `default`
    (!(context.flags & NodeBuilderFlags.InInitialEntityName) || // if the symbol is synthesized, it will only be referenced externally it must print as `default`
    !symbol.declarations || // if not in the same binding context (source file, module declaration), it must print as `default`
    context.enclosingDeclaration && findAncestor(symbol.declarations[0], isDefaultBindingContext) !== findAncestor(context.enclosingDeclaration, isDefaultBindingContext))) {
      return "default";
    }
    if (symbol.declarations && symbol.declarations.length) {
      let declaration = firstDefined(symbol.declarations, (d) => getNameOfDeclaration(d) ? d : void 0);
      const name2 = declaration && getNameOfDeclaration(declaration);
      if (declaration && name2) {
        if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) {
          return symbolName(symbol);
        }
        if (isComputedPropertyName(name2) && !(getCheckFlags(symbol) & CheckFlags.Late)) {
          const nameType = getSymbolLinks(symbol).nameType;
          if (nameType && nameType.flags & TypeFlags.StringOrNumberLiteral) {
            const result = getNameOfSymbolFromNameType(symbol, context);
            if (result !== void 0) {
              return result;
            }
          }
        }
        return declarationNameToString(name2);
      }
      if (!declaration) {
        declaration = symbol.declarations[0];
      }
      if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) {
        return declarationNameToString(declaration.parent.name);
      }
      switch (declaration.kind) {
        case SyntaxKind.ClassExpression:
        case SyntaxKind.FunctionExpression:
        case SyntaxKind.ArrowFunction:
          if (context && !context.encounteredError && !(context.flags & NodeBuilderFlags.AllowAnonymousIdentifier)) {
            context.encounteredError = true;
          }
          return declaration.kind === SyntaxKind.ClassExpression ? "(Anonymous class)" : "(Anonymous function)";
      }
    }
    const name = getNameOfSymbolFromNameType(symbol, context);
    return name !== void 0 ? name : symbolName(symbol);
  }
  function isDeclarationVisible(node) {
    if (node) {
      const links = getNodeLinks(node);
      if (links.isVisible === void 0) {
        links.isVisible = !!determineIfDeclarationIsVisible();
      }
      return links.isVisible;
    }
    return false;
    function determineIfDeclarationIsVisible() {
      switch (node.kind) {
        case SyntaxKind.JSDocCallbackTag:
        case SyntaxKind.JSDocTypedefTag:
        case SyntaxKind.JSDocEnumTag:
          return !!(node.parent && node.parent.parent && node.parent.parent.parent && isSourceFile(node.parent.parent.parent));
        case SyntaxKind.BindingElement:
          return isDeclarationVisible(node.parent.parent);
        case SyntaxKind.VariableDeclaration:
          if (isBindingPattern(node.name) && !node.name.elements.length) {
            return false;
          }
        // falls through
        case SyntaxKind.ModuleDeclaration:
        case SyntaxKind.ClassDeclaration:
        case SyntaxKind.InterfaceDeclaration:
        case SyntaxKind.TypeAliasDeclaration:
        case SyntaxKind.FunctionDeclaration:
        case SyntaxKind.EnumDeclaration:
        case SyntaxKind.ImportEqualsDeclaration:
          if (isExternalModuleAugmentation(node)) {
            return true;
          }
          const parent = getDeclarationContainer(node);
          if (!(getCombinedModifierFlagsCached(node) & ModifierFlags.Export) && !(node.kind !== SyntaxKind.ImportEqualsDeclaration && parent.kind !== SyntaxKind.SourceFile && parent.flags & NodeFlags.Ambient)) {
            return isGlobalSourceFile(parent);
          }
          return isDeclarationVisible(parent);
        case SyntaxKind.PropertyDeclaration:
        case SyntaxKind.PropertySignature:
        case SyntaxKind.GetAccessor:
        case SyntaxKind.SetAccessor:
        case SyntaxKind.MethodDeclaration:
        case SyntaxKind.MethodSignature:
          if (hasEffectiveModifier(node, ModifierFlags.Private | ModifierFlags.Protected)) {
            return false;
          }
        // Public properties/methods are visible if its parents are visible, so:
        // falls through
        case SyntaxKind.Constructor:
        case SyntaxKind.ConstructSignature:
        case SyntaxKind.CallSignature:
        case SyntaxKind.IndexSignature:
        case SyntaxKind.Parameter:
        case SyntaxKind.ModuleBlock:
        case SyntaxKind.FunctionType:
        case SyntaxKind.ConstructorType:
        case SyntaxKind.TypeLiteral:
        case SyntaxKind.TypeReference:
        case SyntaxKind.ArrayType:
        case SyntaxKind.TupleType:
        case SyntaxKind.UnionType:
        case SyntaxKind.IntersectionType:
        case SyntaxKind.ParenthesizedType:
        case SyntaxKind.NamedTupleMember:
          return isDeclarationVisible(node.parent);
        // Default binding, import specifier and namespace import is visible
        // only on demand so by default it is not visible
        case SyntaxKind.ImportClause:
        case SyntaxKind.NamespaceImport:
        case SyntaxKind.ImportSpecifier:
          return false;
        // Type parameters are always visible
        case SyntaxKind.TypeParameter:
        // Source file and namespace export are always visible
        // falls through
        case SyntaxKind.SourceFile:
        case SyntaxKind.NamespaceExportDeclaration:
          return true;
        // Export assignments do not create name bindings outside the module
        case SyntaxKind.ExportAssignment:
          return false;
        default:
          return false;
      }
    }
  }
  function collectLinkedAliases(node, setVisibility) {
    let exportSymbol;
    if (node.kind !== SyntaxKind.StringLiteral && node.parent && node.parent.kind === SyntaxKind.ExportAssignment) {
      exportSymbol = resolveName(
        node,
        node,
        SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      );
    } else if (node.parent.kind === SyntaxKind.ExportSpecifier) {
      exportSymbol = getTargetOfExportSpecifier(node.parent, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias);
    }
    let result;
    let visited;
    if (exportSymbol) {
      visited = /* @__PURE__ */ new Set();
      visited.add(getSymbolId(exportSymbol));
      buildVisibleNodeList(exportSymbol.declarations);
    }
    return result;
    function buildVisibleNodeList(declarations) {
      forEach(declarations, (declaration) => {
        const resultNode = getAnyImportSyntax(declaration) || declaration;
        if (setVisibility) {
          getNodeLinks(declaration).isVisible = true;
        } else {
          result = result || [];
          pushIfUnique(result, resultNode);
        }
        if (isInternalModuleImportEqualsDeclaration(declaration)) {
          const internalModuleReference = declaration.moduleReference;
          const firstIdentifier = getFirstIdentifier(internalModuleReference);
          const importSymbol = resolveName(
            declaration,
            firstIdentifier.escapedText,
            SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace,
            /*nameNotFoundMessage*/
            void 0,
            /*isUse*/
            false
          );
          if (importSymbol && visited) {
            if (tryAddToSet(visited, getSymbolId(importSymbol))) {
              buildVisibleNodeList(importSymbol.declarations);
            }
          }
        }
      });
    }
  }
  function pushTypeResolution(target, propertyName) {
    const resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
    if (resolutionCycleStartIndex >= 0) {
      const { length: length2 } = resolutionTargets;
      for (let i = resolutionCycleStartIndex; i < length2; i++) {
        resolutionResults[i] = false;
      }
      return false;
    }
    resolutionTargets.push(target);
    resolutionResults.push(
      /*items*/
      true
    );
    resolutionPropertyNames.push(propertyName);
    return true;
  }
  function findResolutionCycleStartIndex(target, propertyName) {
    for (let i = resolutionTargets.length - 1; i >= resolutionStart; i--) {
      if (resolutionTargetHasProperty(resolutionTargets[i], resolutionPropertyNames[i])) {
        return -1;
      }
      if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
        return i;
      }
    }
    return -1;
  }
  function resolutionTargetHasProperty(target, propertyName) {
    switch (propertyName) {
      case 0 /* Type */:
        return !!getSymbolLinks(target).type;
      case 2 /* DeclaredType */:
        return !!getSymbolLinks(target).declaredType;
      case 1 /* ResolvedBaseConstructorType */:
        return !!target.resolvedBaseConstructorType;
      case 3 /* ResolvedReturnType */:
        return !!target.resolvedReturnType;
      case 4 /* ImmediateBaseConstraint */:
        return !!target.immediateBaseConstraint;
      case 5 /* ResolvedTypeArguments */:
        return !!target.resolvedTypeArguments;
      case 6 /* ResolvedBaseTypes */:
        return !!target.baseTypesResolved;
      case 7 /* WriteType */:
        return !!getSymbolLinks(target).writeType;
      case 8 /* ParameterInitializerContainsUndefined */:
        return getNodeLinks(target).parameterInitializerContainsUndefined !== void 0;
    }
    return Debug.assertNever(propertyName);
  }
  function popTypeResolution() {
    resolutionTargets.pop();
    resolutionPropertyNames.pop();
    return resolutionResults.pop();
  }
  function getDeclarationContainer(node) {
    return findAncestor(getRootDeclaration(node), (node2) => {
      switch (node2.kind) {
        case SyntaxKind.VariableDeclaration:
        case SyntaxKind.VariableDeclarationList:
        case SyntaxKind.ImportSpecifier:
        case SyntaxKind.NamedImports:
        case SyntaxKind.NamespaceImport:
        case SyntaxKind.ImportClause:
          return false;
        default:
          return true;
      }
    }).parent;
  }
  function getTypeOfPrototypeProperty(prototype) {
    const classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
    return classType.typeParameters ? createTypeReference(classType, map(classType.typeParameters, (_) => anyType)) : classType;
  }
  function getTypeOfPropertyOfType(type, name) {
    const prop = getPropertyOfType(type, name);
    return prop ? getTypeOfSymbol(prop) : void 0;
  }
  function getTypeOfPropertyOrIndexSignatureOfType(type, name) {
    let propType;
    return getTypeOfPropertyOfType(type, name) || (propType = getApplicableIndexInfoForName(type, name)?.type) && addOptionality(
      propType,
      /*isProperty*/
      true,
      /*isOptional*/
      true
    );
  }
  function isTypeAny(type) {
    return type && (type.flags & TypeFlags.Any) !== 0;
  }
  function isErrorType(type) {
    return type === errorType || !!(type.flags & TypeFlags.Any && type.aliasSymbol);
  }
  function getTypeForBindingElementParent(node, checkMode) {
    if (checkMode !== 0 /* Normal */) {
      return getTypeForVariableLikeDeclaration(
        node,
        /*includeOptionality*/
        false,
        checkMode
      );
    }
    const symbol = getSymbolOfDeclaration(node);
    return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(
      node,
      /*includeOptionality*/
      false,
      checkMode
    );
  }
  function getRestType(source, properties, symbol) {
    source = filterType(source, (t) => !(t.flags & TypeFlags.Nullable));
    if (source.flags & TypeFlags.Never) {
      return emptyObjectType;
    }
    if (source.flags & TypeFlags.Union) {
      return mapType(source, (t) => getRestType(t, properties, symbol));
    }
    let omitKeyType = getUnionType(map(properties, getLiteralTypeFromPropertyName));
    const spreadableProperties = [];
    const unspreadableToRestKeys = [];
    for (const prop of getPropertiesOfType(source)) {
      const literalTypeFromProperty = getLiteralTypeFromProperty(prop, TypeFlags.StringOrNumberLiteralOrUnique);
      if (!isTypeAssignableTo(literalTypeFromProperty, omitKeyType) && !(getDeclarationModifierFlagsFromSymbol(prop) & (ModifierFlags.Private | ModifierFlags.Protected)) && isSpreadableProperty(prop)) {
        spreadableProperties.push(prop);
      } else {
        unspreadableToRestKeys.push(literalTypeFromProperty);
      }
    }
    if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
      if (unspreadableToRestKeys.length) {
        omitKeyType = getUnionType([omitKeyType, ...unspreadableToRestKeys]);
      }
      if (omitKeyType.flags & TypeFlags.Never) {
        return source;
      }
      const omitTypeAlias = getGlobalOmitSymbol();
      if (!omitTypeAlias) {
        return errorType;
      }
      return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
    }
    const members = createSymbolTable();
    for (const prop of spreadableProperties) {
      members.set(prop.escapedName, getSpreadSymbol(
        prop,
        /*readonly*/
        false
      ));
    }
    const result = createAnonymousType(symbol, members, emptyArray, emptyArray, getIndexInfosOfType(source));
    result.objectFlags |= ObjectFlags.ObjectRestType;
    return result;
  }
  function isGenericTypeWithUndefinedConstraint(type) {
    return !!(type.flags & TypeFlags.Instantiable) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, TypeFlags.Undefined);
  }
  function getNonUndefinedType(type) {
    const typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, (t) => t.flags & TypeFlags.Instantiable ? getBaseConstraintOrType(t) : t) : type;
    return getTypeWithFacts(typeOrConstraint, 524288 /* NEUndefined */);
  }
  function getFlowTypeOfDestructuring(node, declaredType) {
    const reference = getSyntheticElementAccess(node);
    return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
  }
  function getSyntheticElementAccess(node) {
    const parentAccess = getParentElementAccess(node);
    if (parentAccess && canHaveFlowNode(parentAccess) && parentAccess.flowNode) {
      const propName = getDestructuringPropertyName(node);
      if (propName) {
        const literal = setTextRangeWorker(parseNodeFactory.createStringLiteral(propName), node);
        const lhsExpr = isLeftHandSideExpression(parentAccess) ? parentAccess : parseNodeFactory.createParenthesizedExpression(parentAccess);
        const result = setTextRangeWorker(parseNodeFactory.createElementAccessExpression(lhsExpr, literal), node);
        setParent(literal, result);
        setParent(result, node);
        if (lhsExpr !== parentAccess) {
          setParent(lhsExpr, result);
        }
        result.flowNode = parentAccess.flowNode;
        return result;
      }
    }
  }
  function getParentElementAccess(node) {
    const ancestor = node.parent.parent;
    switch (ancestor.kind) {
      case SyntaxKind.BindingElement:
      case SyntaxKind.PropertyAssignment:
        return getSyntheticElementAccess(ancestor);
      case SyntaxKind.ArrayLiteralExpression:
        return getSyntheticElementAccess(node.parent);
      case SyntaxKind.VariableDeclaration:
        return ancestor.initializer;
      case SyntaxKind.BinaryExpression:
        return ancestor.right;
    }
  }
  function getDestructuringPropertyName(node) {
    const parent = node.parent;
    if (node.kind === SyntaxKind.BindingElement && parent.kind === SyntaxKind.ObjectBindingPattern) {
      return getLiteralPropertyNameText(node.propertyName || node.name);
    }
    if (node.kind === SyntaxKind.PropertyAssignment || node.kind === SyntaxKind.ShorthandPropertyAssignment) {
      return getLiteralPropertyNameText(node.name);
    }
    return "" + parent.elements.indexOf(node);
  }
  function getLiteralPropertyNameText(name) {
    const type = getLiteralTypeFromPropertyName(name);
    return type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral) ? "" + type.value : void 0;
  }
  function getTypeForBindingElement(declaration) {
    const checkMode = declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */;
    const parentType = getTypeForBindingElementParent(declaration.parent.parent, checkMode);
    return parentType && getBindingElementTypeFromParentType(
      declaration,
      parentType,
      /*noTupleBoundsCheck*/
      false
    );
  }
  function getBindingElementTypeFromParentType(declaration, parentType, noTupleBoundsCheck) {
    if (isTypeAny(parentType)) {
      return parentType;
    }
    const pattern = declaration.parent;
    if (strictNullChecks && declaration.flags & NodeFlags.Ambient && isPartOfParameterDeclaration(declaration)) {
      parentType = getNonNullableType(parentType);
    } else if (strictNullChecks && pattern.parent.initializer && !hasTypeFacts(getTypeOfInitializer(pattern.parent.initializer), 65536 /* EQUndefined */)) {
      parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
    }
    const accessFlags = AccessFlags.ExpressionPosition | (noTupleBoundsCheck || hasDefaultValue(declaration) ? AccessFlags.AllowMissing : 0);
    let type;
    if (pattern.kind === SyntaxKind.ObjectBindingPattern) {
      if (declaration.dotDotDotToken) {
        parentType = getReducedType(parentType);
        if (parentType.flags & TypeFlags.Unknown || !isValidSpreadType(parentType)) {
          error(declaration, Diagnostics.Rest_types_may_only_be_created_from_object_types);
          return errorType;
        }
        const literalMembers = [];
        for (const element of pattern.elements) {
          if (!element.dotDotDotToken) {
            literalMembers.push(element.propertyName || element.name);
          }
        }
        type = getRestType(parentType, literalMembers, declaration.symbol);
      } else {
        const name = declaration.propertyName || declaration.name;
        const indexType = getLiteralTypeFromPropertyName(name);
        const declaredType = getIndexedAccessType(parentType, indexType, accessFlags, name);
        type = getFlowTypeOfDestructuring(declaration, declaredType);
      }
    } else {
      const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern);
      const index = pattern.elements.indexOf(declaration);
      if (declaration.dotDotDotToken) {
        const baseConstraint = mapType(parentType, (t) => t.flags & TypeFlags.InstantiableNonPrimitive ? getBaseConstraintOrType(t) : t);
        type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t) => sliceTupleType(t, index)) : createArrayType(elementType);
      } else if (isArrayLikeType(parentType)) {
        const indexType = getNumberLiteralType(index);
        const declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, accessFlags, declaration.name) || errorType;
        type = getFlowTypeOfDestructuring(declaration, declaredType);
      } else {
        type = elementType;
      }
    }
    if (!declaration.initializer) {
      return type;
    }
    if (getEffectiveTypeAnnotationNode(walkUpBindingElementsAndPatterns(declaration))) {
      return strictNullChecks && !hasTypeFacts(checkDeclarationInitializer(declaration, 0 /* Normal */), 16777216 /* IsUndefined */) ? getNonUndefinedType(type) : type;
    }
    return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* Normal */)], UnionReduction.Subtype));
  }
  function getTypeForDeclarationFromJSDocComment(declaration) {
    const jsdocType = getJSDocType(declaration);
    if (jsdocType) {
      return getTypeFromTypeNode(jsdocType);
    }
    return void 0;
  }
  function isNullOrUndefined(node) {
    const expr = skipParentheses(
      node,
      /*excludeJSDocTypeAssertions*/
      true
    );
    return expr.kind === SyntaxKind.NullKeyword || expr.kind === SyntaxKind.Identifier && getResolvedSymbol(expr) === undefinedSymbol;
  }
  function isEmptyArrayLiteral(node) {
    const expr = skipParentheses(
      node,
      /*excludeJSDocTypeAssertions*/
      true
    );
    return expr.kind === SyntaxKind.ArrayLiteralExpression && expr.elements.length === 0;
  }
  function addOptionality(type, isProperty = false, isOptional = true) {
    return strictNullChecks && isOptional ? getOptionalType(type, isProperty) : type;
  }
  function getTypeForVariableLikeDeclaration(declaration, includeOptionality, checkMode) {
    if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === SyntaxKind.ForInStatement) {
      const indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(
        declaration.parent.parent.expression,
        /*checkMode*/
        checkMode
      )));
      return indexType.flags & (TypeFlags.TypeParameter | TypeFlags.Index) ? getExtractStringType(indexType) : stringType;
    }
    if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === SyntaxKind.ForOfStatement) {
      const forOfStatement = declaration.parent.parent;
      return checkRightHandSideOfForOf(forOfStatement) || anyType;
    }
    if (isBindingPattern(declaration.parent)) {
      return getTypeForBindingElement(declaration);
    }
    const isProperty = isPropertyDeclaration(declaration) && !hasAccessorModifier(declaration) || isPropertySignature(declaration) || isJSDocPropertyTag(declaration);
    const isOptional = includeOptionality && isOptionalDeclaration(declaration);
    const declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
    if (isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
      if (declaredType) {
        return isTypeAny(declaredType) || declaredType === unknownType ? declaredType : errorType;
      }
      return useUnknownInCatchVariables ? unknownType : anyType;
    }
    if (declaredType) {
      return addOptionality(declaredType, isProperty, isOptional);
    }
    if ((noImplicitAny || isInJSFile(declaration)) && isVariableDeclaration(declaration) && !isBindingPattern(declaration.name) && !(getCombinedModifierFlagsCached(declaration) & ModifierFlags.Export) && !(declaration.flags & NodeFlags.Ambient)) {
      if (!(getCombinedNodeFlagsCached(declaration) & NodeFlags.Constant) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
        return autoType;
      }
      if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
        return autoArrayType;
      }
    }
    if (isParameter(declaration)) {
      if (!declaration.symbol) {
        return;
      }
      const func = declaration.parent;
      if (func.kind === SyntaxKind.SetAccessor && hasBindableName(func)) {
        const getter = getDeclarationOfKind(getSymbolOfDeclaration(declaration.parent), SyntaxKind.GetAccessor);
        if (getter) {
          const getterSignature = getSignatureFromDeclaration(getter);
          const thisParameter = getAccessorThisParameter(func);
          if (thisParameter && declaration === thisParameter) {
            Debug.assert(!thisParameter.type);
            return getTypeOfSymbol(getterSignature.thisParameter);
          }
          return getReturnTypeOfSignature(getterSignature);
        }
      }
      const parameterTypeOfTypeTag = getParameterTypeOfTypeTag(func, declaration);
      if (parameterTypeOfTypeTag) return parameterTypeOfTypeTag;
      const type = declaration.symbol.escapedName === InternalSymbolName.This ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
      if (type) {
        return addOptionality(
          type,
          /*isProperty*/
          false,
          isOptional
        );
      }
    }
    if (hasOnlyExpressionInitializer(declaration) && !!declaration.initializer) {
      if (isInJSFile(declaration) && !isParameter(declaration)) {
        const containerObjectType = getJSContainerObjectType(declaration, getSymbolOfDeclaration(declaration), getDeclaredExpandoInitializer(declaration));
        if (containerObjectType) {
          return containerObjectType;
        }
      }
      const type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration, checkMode));
      return addOptionality(type, isProperty, isOptional);
    }
    if (isPropertyDeclaration(declaration) && (noImplicitAny || isInJSFile(declaration))) {
      if (!hasStaticModifier(declaration)) {
        const constructor = findConstructorDeclaration(declaration.parent);
        const type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : getEffectiveModifierFlags(declaration) & ModifierFlags.Ambient ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0;
        return type && addOptionality(
          type,
          /*isProperty*/
          true,
          isOptional
        );
      } else {
        const staticBlocks = filter(declaration.parent.members, isClassStaticBlockDeclaration);
        const type = staticBlocks.length ? getFlowTypeInStaticBlocks(declaration.symbol, staticBlocks) : getEffectiveModifierFlags(declaration) & ModifierFlags.Ambient ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0;
        return type && addOptionality(
          type,
          /*isProperty*/
          true,
          isOptional
        );
      }
    }
    if (isJsxAttribute(declaration)) {
      return trueType;
    }
    if (isBindingPattern(declaration.name)) {
      return getTypeFromBindingPattern(
        declaration.name,
        /*includePatternInType*/
        false,
        /*reportErrors*/
        true
      );
    }
    return void 0;
  }
  function isConstructorDeclaredProperty(symbol) {
    if (symbol.valueDeclaration && isBinaryExpression(symbol.valueDeclaration)) {
      const links = getSymbolLinks(symbol);
      if (links.isConstructorDeclaredProperty === void 0) {
        links.isConstructorDeclaredProperty = false;
        links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && every(symbol.declarations, (declaration) => isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && (declaration.left.kind !== SyntaxKind.ElementAccessExpression || isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(
          /*declaredType*/
          void 0,
          declaration,
          symbol,
          declaration
        ));
      }
      return links.isConstructorDeclaredProperty;
    }
    return false;
  }
  function isAutoTypedProperty(symbol) {
    const declaration = symbol.valueDeclaration;
    return declaration && isPropertyDeclaration(declaration) && !getEffectiveTypeAnnotationNode(declaration) && !declaration.initializer && (noImplicitAny || isInJSFile(declaration));
  }
  function getDeclaringConstructor(symbol) {
    if (!symbol.declarations) {
      return;
    }
    for (const declaration of symbol.declarations) {
      const container = getThisContainer(
        declaration,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      );
      if (container && (container.kind === SyntaxKind.Constructor || isJSConstructor(container))) {
        return container;
      }
    }
  }
  function getFlowTypeFromCommonJSExport(symbol) {
    const file = getSourceFileOfNode(symbol.declarations[0]);
    const accessName = unescapeLeadingUnderscores(symbol.escapedName);
    const areAllModuleExports = symbol.declarations.every((d) => isInJSFile(d) && isAccessExpression(d) && isModuleExportsAccessExpression(d.expression));
    const reference = areAllModuleExports ? factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(factory.createIdentifier("module"), factory.createIdentifier("exports")), accessName) : factory.createPropertyAccessExpression(factory.createIdentifier("exports"), accessName);
    if (areAllModuleExports) {
      setParent(reference.expression.expression, reference.expression);
    }
    setParent(reference.expression, reference);
    setParent(reference, file);
    reference.flowNode = file.endFlowNode;
    return getFlowTypeOfReference(reference, autoType, undefinedType);
  }
  function getFlowTypeInStaticBlocks(symbol, staticBlocks) {
    const accessName = startsWith(symbol.escapedName, "__#") ? factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) : unescapeLeadingUnderscores(symbol.escapedName);
    for (const staticBlock of staticBlocks) {
      const reference = factory.createPropertyAccessExpression(factory.createThis(), accessName);
      setParent(reference.expression, reference);
      setParent(reference, staticBlock);
      reference.flowNode = staticBlock.returnFlowNode;
      const flowType = getFlowTypeOfProperty(reference, symbol);
      if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
        error(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
      }
      if (everyType(flowType, isNullableType)) {
        continue;
      }
      return convertAutoToAny(flowType);
    }
  }
  function getFlowTypeInConstructor(symbol, constructor) {
    const accessName = startsWith(symbol.escapedName, "__#") ? factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) : unescapeLeadingUnderscores(symbol.escapedName);
    const reference = factory.createPropertyAccessExpression(factory.createThis(), accessName);
    setParent(reference.expression, reference);
    setParent(reference, constructor);
    reference.flowNode = constructor.returnFlowNode;
    const flowType = getFlowTypeOfProperty(reference, symbol);
    if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
      error(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
    }
    return everyType(flowType, isNullableType) ? void 0 : convertAutoToAny(flowType);
  }
  function getFlowTypeOfProperty(reference, prop) {
    const initialType = prop?.valueDeclaration && (!isAutoTypedProperty(prop) || getEffectiveModifierFlags(prop.valueDeclaration) & ModifierFlags.Ambient) && getTypeOfPropertyInBaseClass(prop) || undefinedType;
    return getFlowTypeOfReference(reference, autoType, initialType);
  }
  function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
    const container = getAssignedExpandoInitializer(symbol.valueDeclaration);
    if (container) {
      const tag = isInJSFile(container) ? getJSDocTypeTag(container) : void 0;
      if (tag && tag.typeExpression) {
        return getTypeFromTypeNode(tag.typeExpression);
      }
      const containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
      return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
    }
    let type;
    let definedInConstructor = false;
    let definedInMethod = false;
    if (isConstructorDeclaredProperty(symbol)) {
      type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol));
    }
    if (!type) {
      let types;
      if (symbol.declarations) {
        let jsdocType;
        for (const declaration of symbol.declarations) {
          const expression = isBinaryExpression(declaration) || isCallExpression(declaration) ? declaration : isAccessExpression(declaration) ? isBinaryExpression(declaration.parent) ? declaration.parent : declaration : void 0;
          if (!expression) {
            continue;
          }
          const kind = isAccessExpression(expression) ? getAssignmentDeclarationPropertyAccessKind(expression) : getAssignmentDeclarationKind(expression);
          if (kind === AssignmentDeclarationKind.ThisProperty || isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) {
            if (isDeclarationInConstructor(expression)) {
              definedInConstructor = true;
            } else {
              definedInMethod = true;
            }
          }
          if (!isCallExpression(expression)) {
            jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
          }
          if (!jsdocType) {
            (types || (types = [])).push(isBinaryExpression(expression) || isCallExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
          }
        }
        type = jsdocType;
      }
      if (!type) {
        if (!length(types)) {
          return errorType;
        }
        let constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : void 0;
        if (definedInMethod) {
          const propType = getTypeOfPropertyInBaseClass(symbol);
          if (propType) {
            (constructorTypes || (constructorTypes = [])).push(propType);
            definedInConstructor = true;
          }
        }
        const sourceTypes = some(constructorTypes, (t) => !!(t.flags & ~TypeFlags.Nullable)) ? constructorTypes : types;
        type = getUnionType(sourceTypes);
      }
    }
    const widened = getWidenedType(addOptionality(
      type,
      /*isProperty*/
      false,
      definedInMethod && !definedInConstructor
    ));
    if (symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && filterType(widened, (t) => !!(t.flags & ~TypeFlags.Nullable)) === neverType) {
      reportImplicitAny(symbol.valueDeclaration, anyType);
      return anyType;
    }
    return widened;
  }
  function getJSContainerObjectType(decl, symbol, init) {
    if (!isInJSFile(decl) || !init || !isObjectLiteralExpression(init) || init.properties.length) {
      return void 0;
    }
    const exports = createSymbolTable();
    while (isBinaryExpression(decl) || isPropertyAccessExpression(decl)) {
      const s2 = getSymbolOfNode(decl);
      if (s2?.exports?.size) {
        mergeSymbolTable(exports, s2.exports);
      }
      decl = isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
    }
    const s = getSymbolOfNode(decl);
    if (s?.exports?.size) {
      mergeSymbolTable(exports, s.exports);
    }
    const type = createAnonymousType(symbol, exports, emptyArray, emptyArray, emptyArray);
    type.objectFlags |= ObjectFlags.JSLiteral;
    return type;
  }
  function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
    const typeNode = getEffectiveTypeAnnotationNode(expression.parent);
    if (typeNode) {
      const type = getWidenedType(getTypeFromTypeNode(typeNode));
      if (!declaredType) {
        return type;
      } else if (!isErrorType(declaredType) && !isErrorType(type) && !isTypeIdenticalTo(declaredType, type)) {
        errorNextVariableOrPropertyDeclarationMustHaveSameType(
          /*firstDeclaration*/
          void 0,
          declaredType,
          declaration,
          type
        );
      }
    }
    if (symbol.parent?.valueDeclaration) {
      const possiblyAnnotatedSymbol = getFunctionExpressionParentSymbolOrSymbol(symbol.parent);
      if (possiblyAnnotatedSymbol.valueDeclaration) {
        const typeNode2 = getEffectiveTypeAnnotationNode(possiblyAnnotatedSymbol.valueDeclaration);
        if (typeNode2) {
          const annotationSymbol = getPropertyOfType(getTypeFromTypeNode(typeNode2), symbol.escapedName);
          if (annotationSymbol) {
            return getNonMissingTypeOfSymbol(annotationSymbol);
          }
        }
      }
    }
    return declaredType;
  }
  function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
    if (isCallExpression(expression)) {
      if (resolvedSymbol) {
        return getTypeOfSymbol(resolvedSymbol);
      }
      const objectLitType = checkExpressionCached(expression.arguments[2]);
      const valueType = getTypeOfPropertyOfType(objectLitType, "value");
      if (valueType) {
        return valueType;
      }
      const getFunc = getTypeOfPropertyOfType(objectLitType, "get");
      if (getFunc) {
        const getSig = getSingleCallSignature(getFunc);
        if (getSig) {
          return getReturnTypeOfSignature(getSig);
        }
      }
      const setFunc = getTypeOfPropertyOfType(objectLitType, "set");
      if (setFunc) {
        const setSig = getSingleCallSignature(setFunc);
        if (setSig) {
          return getTypeOfFirstParameterOfSignature(setSig);
        }
      }
      return anyType;
    }
    if (containsSameNamedThisProperty(expression.left, expression.right)) {
      return anyType;
    }
    const isDirectExport = kind === AssignmentDeclarationKind.ExportsProperty && (isPropertyAccessExpression(expression.left) || isElementAccessExpression(expression.left)) && (isModuleExportsAccessExpression(expression.left.expression) || isIdentifier(expression.left.expression) && isExportsIdentifier(expression.left.expression));
    const type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : isDirectExport ? getRegularTypeOfLiteralType(checkExpressionCached(expression.right)) : getWidenedLiteralType(checkExpressionCached(expression.right));
    if (type.flags & TypeFlags.Object && kind === AssignmentDeclarationKind.ModuleExports && symbol.escapedName === InternalSymbolName.ExportEquals) {
      const exportedType = resolveStructuredTypeMembers(type);
      const members = createSymbolTable();
      copyEntries(exportedType.members, members);
      const initialSize = members.size;
      if (resolvedSymbol && !resolvedSymbol.exports) {
        resolvedSymbol.exports = createSymbolTable();
      }
      (resolvedSymbol || symbol).exports.forEach((s, name) => {
        const exportedMember = members.get(name);
        if (exportedMember && exportedMember !== s && !(s.flags & SymbolFlags.Alias)) {
          if (s.flags & SymbolFlags.Value && exportedMember.flags & SymbolFlags.Value) {
            if (s.valueDeclaration && exportedMember.valueDeclaration && getSourceFileOfNode(s.valueDeclaration) !== getSourceFileOfNode(exportedMember.valueDeclaration)) {
              const unescapedName = unescapeLeadingUnderscores(s.escapedName);
              const exportedMemberName = tryCast(exportedMember.valueDeclaration, isNamedDeclaration)?.name || exportedMember.valueDeclaration;
              addRelatedInfo(
                error(s.valueDeclaration, Diagnostics.Duplicate_identifier_0, unescapedName),
                createDiagnosticForNode(exportedMemberName, Diagnostics._0_was_also_declared_here, unescapedName)
              );
              addRelatedInfo(
                error(exportedMemberName, Diagnostics.Duplicate_identifier_0, unescapedName),
                createDiagnosticForNode(s.valueDeclaration, Diagnostics._0_was_also_declared_here, unescapedName)
              );
            }
            const union = createSymbol(s.flags | exportedMember.flags, name);
            union.links.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
            union.valueDeclaration = exportedMember.valueDeclaration;
            union.declarations = concatenate(exportedMember.declarations, s.declarations);
            members.set(name, union);
          } else {
            members.set(name, mergeSymbol(s, exportedMember));
          }
        } else {
          members.set(name, s);
        }
      });
      const result = createAnonymousType(
        initialSize !== members.size ? void 0 : exportedType.symbol,
        // Only set the type's symbol if it looks to be the same as the original type
        members,
        exportedType.callSignatures,
        exportedType.constructSignatures,
        exportedType.indexInfos
      );
      if (initialSize === members.size) {
        if (type.aliasSymbol) {
          result.aliasSymbol = type.aliasSymbol;
          result.aliasTypeArguments = type.aliasTypeArguments;
        }
        if (getObjectFlags(type) & ObjectFlags.Reference) {
          result.aliasSymbol = type.symbol;
          const args = getTypeArguments(type);
          result.aliasTypeArguments = length(args) ? args : void 0;
        }
      }
      result.objectFlags |= getPropagatingFlagsOfTypes([type]) | getObjectFlags(type) & (ObjectFlags.JSLiteral | ObjectFlags.ArrayLiteral | ObjectFlags.ObjectLiteral);
      if (result.symbol && result.symbol.flags & SymbolFlags.Class && type === getDeclaredTypeOfClassOrInterface(result.symbol)) {
        result.objectFlags |= ObjectFlags.IsClassInstanceClone;
      }
      return result;
    }
    if (isEmptyArrayLiteralType(type)) {
      reportImplicitAny(expression, anyArrayType);
      return anyArrayType;
    }
    return type;
  }
  function containsSameNamedThisProperty(thisProperty, expression) {
    return isPropertyAccessExpression(thisProperty) && thisProperty.expression.kind === SyntaxKind.ThisKeyword && forEachChildRecursively(expression, (n) => isMatchingReference(thisProperty, n));
  }
  function isDeclarationInConstructor(expression) {
    const thisContainer = getThisContainer(
      expression,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    return thisContainer.kind === SyntaxKind.Constructor || thisContainer.kind === SyntaxKind.FunctionDeclaration || thisContainer.kind === SyntaxKind.FunctionExpression && !isPrototypePropertyAssignment(thisContainer.parent);
  }
  function getConstructorDefinedThisAssignmentTypes(types, declarations) {
    Debug.assert(types.length === declarations.length);
    return types.filter((_, i) => {
      const declaration = declarations[i];
      const expression = isBinaryExpression(declaration) ? declaration : isBinaryExpression(declaration.parent) ? declaration.parent : void 0;
      return expression && isDeclarationInConstructor(expression);
    });
  }
  function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
    if (element.initializer) {
      const contextualType = isBindingPattern(element.name) ? getTypeFromBindingPattern(
        element.name,
        /*includePatternInType*/
        true,
        /*reportErrors*/
        false
      ) : unknownType;
      return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, 0 /* Normal */, contextualType)));
    }
    if (isBindingPattern(element.name)) {
      return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
    }
    if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
      reportImplicitAny(element, anyType);
    }
    return includePatternInType ? nonInferrableAnyType : anyType;
  }
  function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
    const members = createSymbolTable();
    let stringIndexInfo;
    let objectFlags = ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectOrArrayLiteral;
    forEach(pattern.elements, (e) => {
      const name = e.propertyName || e.name;
      if (e.dotDotDotToken) {
        stringIndexInfo = createIndexInfo(
          stringType,
          anyType,
          /*isReadonly*/
          false
        );
        return;
      }
      const exprType = getLiteralTypeFromPropertyName(name);
      if (!isTypeUsableAsPropertyName(exprType)) {
        objectFlags |= ObjectFlags.ObjectLiteralPatternWithComputedProperties;
        return;
      }
      const text = getPropertyNameFromType(exprType);
      const flags = SymbolFlags.Property | (e.initializer ? SymbolFlags.Optional : 0);
      const symbol = createSymbol(flags, text);
      symbol.links.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
      symbol.links.bindingElement = e;
      members.set(symbol.escapedName, symbol);
    });
    const result = createAnonymousType(
      /*symbol*/
      void 0,
      members,
      emptyArray,
      emptyArray,
      stringIndexInfo ? [stringIndexInfo] : emptyArray
    );
    result.objectFlags |= objectFlags;
    if (includePatternInType) {
      result.pattern = pattern;
      result.objectFlags |= ObjectFlags.ContainsObjectOrArrayLiteral;
    }
    return result;
  }
  function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
    const elements = pattern.elements;
    const lastElement = lastOrUndefined(elements);
    const restElement = lastElement && lastElement.kind === SyntaxKind.BindingElement && lastElement.dotDotDotToken ? lastElement : void 0;
    if (elements.length === 0 || elements.length === 1 && restElement) {
      return languageVersion >= ScriptTarget.ES2015 ? createIterableType(anyType) : anyArrayType;
    }
    const elementTypes = map(elements, (e) => isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors));
    const minLength = findLastIndex(elements, (e) => !(e === restElement || isOmittedExpression(e) || hasDefaultValue(e)), elements.length - 1) + 1;
    const elementFlags = map(elements, (e, i) => e === restElement ? ElementFlags.Rest : i >= minLength ? ElementFlags.Optional : ElementFlags.Required);
    let result = createTupleType(elementTypes, elementFlags);
    if (includePatternInType) {
      result = cloneTypeReference(result);
      result.pattern = pattern;
      result.objectFlags |= ObjectFlags.ContainsObjectOrArrayLiteral;
    }
    return result;
  }
  function getTypeFromBindingPattern(pattern, includePatternInType = false, reportErrors = false) {
    if (includePatternInType) contextualBindingPatterns.push(pattern);
    const result = pattern.kind === SyntaxKind.ObjectBindingPattern ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
    if (includePatternInType) contextualBindingPatterns.pop();
    return result;
  }
  function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
    return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(
      declaration,
      /*includeOptionality*/
      true,
      0 /* Normal */
    ), declaration, reportErrors);
  }
  function getTypeFromImportAttributes(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const symbol = createSymbol(SymbolFlags.ObjectLiteral, InternalSymbolName.ImportAttributes);
      const members = createSymbolTable();
      forEach(node.elements, (attr) => {
        const member = createSymbol(SymbolFlags.Property, getNameFromImportAttribute(attr));
        member.parent = symbol;
        member.links.type = checkImportAttribute(attr);
        member.links.target = member;
        members.set(member.escapedName, member);
      });
      const type = createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
      type.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.NonInferrableType;
      links.resolvedType = type;
    }
    return links.resolvedType;
  }
  function isGlobalSymbolConstructor(node) {
    const symbol = getSymbolOfNode(node);
    const globalSymbol = getGlobalESSymbolConstructorTypeSymbol(
      /*reportErrors*/
      false
    );
    return globalSymbol && symbol && symbol === globalSymbol;
  }
  function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
    if (type) {
      if (type.flags & TypeFlags.ESSymbol && isGlobalSymbolConstructor(declaration.parent)) {
        type = getESSymbolLikeTypeForNode(declaration);
      }
      if (reportErrors) {
        reportErrorsFromWidening(declaration, type);
      }
      if (type.flags & TypeFlags.UniqueESSymbol && (isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfDeclaration(declaration)) {
        type = esSymbolType;
      }
      return getWidenedType(type);
    }
    type = isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
    if (reportErrors) {
      if (!declarationBelongsToPrivateAmbientMember(declaration)) {
        reportImplicitAny(declaration, type);
      }
    }
    return type;
  }
  function declarationBelongsToPrivateAmbientMember(declaration) {
    const root = getRootDeclaration(declaration);
    const memberDeclaration = root.kind === SyntaxKind.Parameter ? root.parent : root;
    return isPrivateWithinAmbient(memberDeclaration);
  }
  function tryGetTypeFromEffectiveTypeNode(node) {
    const typeNode = getEffectiveTypeAnnotationNode(node);
    if (typeNode) {
      return getTypeFromTypeNode(typeNode);
    }
  }
  function isParameterOfContextSensitiveSignature(symbol) {
    let decl = symbol.valueDeclaration;
    if (!decl) {
      return false;
    }
    if (isBindingElement(decl)) {
      decl = walkUpBindingElementsAndPatterns(decl);
    }
    if (isParameter(decl)) {
      return isContextSensitiveFunctionOrObjectLiteralMethod(decl.parent);
    }
    return false;
  }
  function getTypeOfVariableOrParameterOrProperty(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      const type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
      if (!links.type && !isParameterOfContextSensitiveSignature(symbol)) {
        links.type = type;
      }
      return type;
    }
    return links.type;
  }
  function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
    if (symbol.flags & SymbolFlags.Prototype) {
      return getTypeOfPrototypeProperty(symbol);
    }
    if (symbol === requireSymbol) {
      return anyType;
    }
    if (symbol.flags & SymbolFlags.ModuleExports && symbol.valueDeclaration) {
      const fileSymbol = getSymbolOfDeclaration(getSourceFileOfNode(symbol.valueDeclaration));
      const result = createSymbol(fileSymbol.flags, "exports");
      result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : [];
      result.parent = symbol;
      result.links.target = fileSymbol;
      if (fileSymbol.valueDeclaration) result.valueDeclaration = fileSymbol.valueDeclaration;
      if (fileSymbol.members) result.members = new Map(fileSymbol.members);
      if (fileSymbol.exports) result.exports = new Map(fileSymbol.exports);
      const members = createSymbolTable();
      members.set("exports", result);
      return createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
    }
    Debug.assertIsDefined(symbol.valueDeclaration);
    const declaration = symbol.valueDeclaration;
    if (isSourceFile(declaration) && isJsonSourceFile(declaration)) {
      if (!declaration.statements.length) {
        return emptyObjectType;
      }
      return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
    }
    if (isAccessor(declaration)) {
      return getTypeOfAccessors(symbol);
    }
    if (!pushTypeResolution(symbol, 0 /* Type */)) {
      if (symbol.flags & SymbolFlags.ValueModule && !(symbol.flags & SymbolFlags.Assignment)) {
        return getTypeOfFuncClassEnumModule(symbol);
      }
      return reportCircularityError(symbol);
    }
    let type;
    if (declaration.kind === SyntaxKind.ExportAssignment) {
      type = widenTypeForVariableLikeDeclaration(tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionCached(declaration.expression), declaration);
    } else if (isBinaryExpression(declaration) || isInJSFile(declaration) && (isCallExpression(declaration) || (isPropertyAccessExpression(declaration) || isBindableStaticElementAccessExpression(declaration)) && isBinaryExpression(declaration.parent))) {
      type = getWidenedTypeForAssignmentDeclaration(symbol);
    } else if (isPropertyAccessExpression(declaration) || isElementAccessExpression(declaration) || isIdentifier(declaration) || isStringLiteralLike(declaration) || isNumericLiteral(declaration) || isClassDeclaration(declaration) || isFunctionDeclaration(declaration) || isMethodDeclaration(declaration) && !isObjectLiteralMethod(declaration) || isMethodSignature(declaration) || isSourceFile(declaration)) {
      if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule)) {
        return getTypeOfFuncClassEnumModule(symbol);
      }
      type = isBinaryExpression(declaration.parent) ? getWidenedTypeForAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
    } else if (isPropertyAssignment(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
    } else if (isJsxAttribute(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
    } else if (isShorthandPropertyAssignment(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
    } else if (isObjectLiteralMethod(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
    } else if (isParameter(declaration) || isPropertyDeclaration(declaration) || isPropertySignature(declaration) || isVariableDeclaration(declaration) || isBindingElement(declaration) || isJSDocPropertyLikeTag(declaration)) {
      type = getWidenedTypeForVariableLikeDeclaration(
        declaration,
        /*reportErrors*/
        true
      );
    } else if (isEnumDeclaration(declaration)) {
      type = getTypeOfFuncClassEnumModule(symbol);
    } else if (isEnumMember(declaration)) {
      type = getTypeOfEnumMember(symbol);
    } else {
      return Debug.fail("Unhandled declaration kind! " + Debug.formatSyntaxKind(declaration.kind) + " for " + Debug.formatSymbol(symbol));
    }
    if (!popTypeResolution()) {
      if (symbol.flags & SymbolFlags.ValueModule && !(symbol.flags & SymbolFlags.Assignment)) {
        return getTypeOfFuncClassEnumModule(symbol);
      }
      return reportCircularityError(symbol);
    }
    return type;
  }
  function getAnnotatedAccessorTypeNode(accessor) {
    if (accessor) {
      switch (accessor.kind) {
        case SyntaxKind.GetAccessor:
          const getterTypeAnnotation = getEffectiveReturnTypeNode(accessor);
          return getterTypeAnnotation;
        case SyntaxKind.SetAccessor:
          const setterTypeAnnotation = getEffectiveSetAccessorTypeAnnotationNode(accessor);
          return setterTypeAnnotation;
        case SyntaxKind.PropertyDeclaration:
          Debug.assert(hasAccessorModifier(accessor));
          const accessorTypeAnnotation = getEffectiveTypeAnnotationNode(accessor);
          return accessorTypeAnnotation;
      }
    }
    return void 0;
  }
  function getAnnotatedAccessorType(accessor) {
    const node = getAnnotatedAccessorTypeNode(accessor);
    return node && getTypeFromTypeNode(node);
  }
  function getAnnotatedAccessorThisParameter(accessor) {
    const parameter = getAccessorThisParameter(accessor);
    return parameter && parameter.symbol;
  }
  function getThisTypeOfDeclaration(declaration) {
    return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
  }
  function getTypeOfAccessors(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      if (!pushTypeResolution(symbol, 0 /* Type */)) {
        return errorType;
      }
      const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor);
      const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor);
      const accessor = tryCast(getDeclarationOfKind(symbol, SyntaxKind.PropertyDeclaration), isAutoAccessorPropertyDeclaration);
      let type = getter && isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || getAnnotatedAccessorType(getter) || getAnnotatedAccessorType(setter) || getAnnotatedAccessorType(accessor) || getter && getter.body && getReturnTypeFromBody(getter) || accessor && accessor.initializer && getWidenedTypeForVariableLikeDeclaration(
        accessor,
        /*reportErrors*/
        true
      );
      if (!type) {
        if (setter && !isPrivateWithinAmbient(setter)) {
          errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
        } else if (getter && !isPrivateWithinAmbient(getter)) {
          errorOrSuggestion(noImplicitAny, getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
        } else if (accessor && !isPrivateWithinAmbient(accessor)) {
          errorOrSuggestion(noImplicitAny, accessor, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), "any");
        }
        type = anyType;
      }
      if (!popTypeResolution()) {
        if (getAnnotatedAccessorTypeNode(getter)) {
          error(getter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        } else if (getAnnotatedAccessorTypeNode(setter)) {
          error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        } else if (getAnnotatedAccessorTypeNode(accessor)) {
          error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        } else if (getter && noImplicitAny) {
          error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol));
        }
        type = anyType;
      }
      links.type ??= type;
    }
    return links.type;
  }
  function getWriteTypeOfAccessors(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.writeType) {
      if (!pushTypeResolution(symbol, 7 /* WriteType */)) {
        return errorType;
      }
      const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor) ?? tryCast(getDeclarationOfKind(symbol, SyntaxKind.PropertyDeclaration), isAutoAccessorPropertyDeclaration);
      let writeType = getAnnotatedAccessorType(setter);
      if (!popTypeResolution()) {
        if (getAnnotatedAccessorTypeNode(setter)) {
          error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        }
        writeType = anyType;
      }
      links.writeType ??= writeType || getTypeOfAccessors(symbol);
    }
    return links.writeType;
  }
  function getBaseTypeVariableOfClass(symbol) {
    const baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
    return baseConstructorType.flags & TypeFlags.TypeVariable ? baseConstructorType : baseConstructorType.flags & TypeFlags.Intersection ? find(baseConstructorType.types, (t) => !!(t.flags & TypeFlags.TypeVariable)) : void 0;
  }
  function getTypeOfFuncClassEnumModule(symbol) {
    let links = getSymbolLinks(symbol);
    const originalLinks = links;
    if (!links.type) {
      const expando = symbol.valueDeclaration && getSymbolOfExpando(
        symbol.valueDeclaration,
        /*allowDeclaration*/
        false
      );
      if (expando) {
        const merged = mergeJSSymbols(symbol, expando);
        if (merged) {
          symbol = merged;
          links = merged.links;
        }
      }
      originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
    }
    return links.type;
  }
  function getTypeOfFuncClassEnumModuleWorker(symbol) {
    const declaration = symbol.valueDeclaration;
    if (symbol.flags & SymbolFlags.Module && isShorthandAmbientModuleSymbol(symbol)) {
      return anyType;
    } else if (declaration && (declaration.kind === SyntaxKind.BinaryExpression || isAccessExpression(declaration) && declaration.parent.kind === SyntaxKind.BinaryExpression)) {
      return getWidenedTypeForAssignmentDeclaration(symbol);
    } else if (symbol.flags & SymbolFlags.ValueModule && declaration && isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
      const resolvedModule = resolveExternalModuleSymbol(symbol);
      if (resolvedModule !== symbol) {
        if (!pushTypeResolution(symbol, 0 /* Type */)) {
          return errorType;
        }
        const exportEquals = getMergedSymbol(symbol.exports.get(InternalSymbolName.ExportEquals));
        const type2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? void 0 : resolvedModule);
        if (!popTypeResolution()) {
          return reportCircularityError(symbol);
        }
        return type2;
      }
    }
    const type = createObjectType(ObjectFlags.Anonymous, symbol);
    if (symbol.flags & SymbolFlags.Class) {
      const baseTypeVariable = getBaseTypeVariableOfClass(symbol);
      return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
    } else {
      return strictNullChecks && symbol.flags & SymbolFlags.Optional ? getOptionalType(
        type,
        /*isProperty*/
        true
      ) : type;
    }
  }
  function getTypeOfEnumMember(symbol) {
    const links = getSymbolLinks(symbol);
    return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
  }
  function getTypeOfAlias(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      if (!pushTypeResolution(symbol, 0 /* Type */)) {
        return errorType;
      }
      const targetSymbol = resolveAlias(symbol);
      const exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(
        getDeclarationOfAliasSymbol(symbol),
        /*dontRecursivelyResolve*/
        true
      );
      const declaredType = firstDefined(exportSymbol?.declarations, (d) => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0);
      links.type ??= exportSymbol?.declarations && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & SymbolFlags.Value ? getTypeOfSymbol(targetSymbol) : errorType;
      if (!popTypeResolution()) {
        reportCircularityError(exportSymbol ?? symbol);
        return links.type ??= errorType;
      }
    }
    return links.type;
  }
  function getTypeOfInstantiatedSymbol(symbol) {
    const links = getSymbolLinks(symbol);
    return links.type || (links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper));
  }
  function getWriteTypeOfInstantiatedSymbol(symbol) {
    const links = getSymbolLinks(symbol);
    return links.writeType || (links.writeType = instantiateType(getWriteTypeOfSymbol(links.target), links.mapper));
  }
  function reportCircularityError(symbol) {
    const declaration = symbol.valueDeclaration;
    if (declaration) {
      if (getEffectiveTypeAnnotationNode(declaration)) {
        error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        return errorType;
      }
      if (noImplicitAny && (declaration.kind !== SyntaxKind.Parameter || declaration.initializer)) {
        error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
      }
    } else if (symbol.flags & SymbolFlags.Alias) {
      const node = getDeclarationOfAliasSymbol(symbol);
      if (node) {
        error(node, Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
      }
    }
    return anyType;
  }
  function getTypeOfSymbolWithDeferredType(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      Debug.assertIsDefined(links.deferralParent);
      Debug.assertIsDefined(links.deferralConstituents);
      links.type = links.deferralParent.flags & TypeFlags.Union ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
    }
    return links.type;
  }
  function getWriteTypeOfSymbolWithDeferredType(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.writeType && links.deferralWriteConstituents) {
      Debug.assertIsDefined(links.deferralParent);
      Debug.assertIsDefined(links.deferralConstituents);
      links.writeType = links.deferralParent.flags & TypeFlags.Union ? getUnionType(links.deferralWriteConstituents) : getIntersectionType(links.deferralWriteConstituents);
    }
    return links.writeType;
  }
  function getWriteTypeOfSymbol(symbol) {
    const checkFlags = getCheckFlags(symbol);
    if (symbol.flags & SymbolFlags.Property) {
      return checkFlags & CheckFlags.SyntheticProperty ? checkFlags & CheckFlags.DeferredType ? getWriteTypeOfSymbolWithDeferredType(symbol) || getTypeOfSymbolWithDeferredType(symbol) : (
        // NOTE: cast to TransientSymbol should be safe because only TransientSymbols can have CheckFlags.SyntheticProperty
        symbol.links.writeType || symbol.links.type
      ) : removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & SymbolFlags.Optional));
    }
    if (symbol.flags & SymbolFlags.Accessor) {
      return checkFlags & CheckFlags.Instantiated ? getWriteTypeOfInstantiatedSymbol(symbol) : getWriteTypeOfAccessors(symbol);
    }
    return getTypeOfSymbol(symbol);
  }
  function getTypeOfSymbol(symbol) {
    const checkFlags = getCheckFlags(symbol);
    if (checkFlags & CheckFlags.DeferredType) {
      return getTypeOfSymbolWithDeferredType(symbol);
    }
    if (checkFlags & CheckFlags.Instantiated) {
      return getTypeOfInstantiatedSymbol(symbol);
    }
    if (checkFlags & CheckFlags.Mapped) {
      return getTypeOfMappedSymbol(symbol);
    }
    if (checkFlags & CheckFlags.ReverseMapped) {
      return getTypeOfReverseMappedSymbol(symbol);
    }
    if (symbol.flags & (SymbolFlags.Variable | SymbolFlags.Property)) {
      return getTypeOfVariableOrParameterOrProperty(symbol);
    }
    if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule)) {
      return getTypeOfFuncClassEnumModule(symbol);
    }
    if (symbol.flags & SymbolFlags.EnumMember) {
      return getTypeOfEnumMember(symbol);
    }
    if (symbol.flags & SymbolFlags.Accessor) {
      return getTypeOfAccessors(symbol);
    }
    if (symbol.flags & SymbolFlags.Alias) {
      return getTypeOfAlias(symbol);
    }
    return errorType;
  }
  function getNonMissingTypeOfSymbol(symbol) {
    return removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & SymbolFlags.Optional));
  }
  function isReferenceToSomeType(type, targets) {
    if (type === void 0 || (getObjectFlags(type) & ObjectFlags.Reference) === 0) {
      return false;
    }
    for (const target of targets) {
      if (type.target === target) {
        return true;
      }
    }
    return false;
  }
  function isReferenceToType(type, target) {
    return type !== void 0 && target !== void 0 && (getObjectFlags(type) & ObjectFlags.Reference) !== 0 && type.target === target;
  }
  function getTargetType(type) {
    return getObjectFlags(type) & ObjectFlags.Reference ? type.target : type;
  }
  function hasBaseType(type, checkBase) {
    return check(type);
    function check(type2) {
      if (getObjectFlags(type2) & (ObjectFlags.ClassOrInterface | ObjectFlags.Reference)) {
        const target = getTargetType(type2);
        return target === checkBase || some(getBaseTypes(target), check);
      } else if (type2.flags & TypeFlags.Intersection) {
        return some(type2.types, check);
      }
      return false;
    }
  }
  function appendTypeParameters(typeParameters, declarations) {
    for (const declaration of declarations) {
      typeParameters = appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(declaration)));
    }
    return typeParameters;
  }
  function getOuterTypeParameters(node, includeThisTypes) {
    while (true) {
      node = node.parent;
      if (node && isBinaryExpression(node)) {
        const assignmentKind = getAssignmentDeclarationKind(node);
        if (assignmentKind === AssignmentDeclarationKind.Prototype || assignmentKind === AssignmentDeclarationKind.PrototypeProperty) {
          const symbol = getSymbolOfDeclaration(node.left);
          if (symbol && symbol.parent && !findAncestor(symbol.parent.valueDeclaration, (d) => node === d)) {
            node = symbol.parent.valueDeclaration;
          }
        }
      }
      if (!node) {
        return void 0;
      }
      const kind = node.kind;
      switch (kind) {
        case SyntaxKind.ClassDeclaration:
        case SyntaxKind.ClassExpression:
        case SyntaxKind.InterfaceDeclaration:
        case SyntaxKind.CallSignature:
        case SyntaxKind.ConstructSignature:
        case SyntaxKind.MethodSignature:
        case SyntaxKind.FunctionType:
        case SyntaxKind.ConstructorType:
        case SyntaxKind.JSDocFunctionType:
        case SyntaxKind.FunctionDeclaration:
        case SyntaxKind.MethodDeclaration:
        case SyntaxKind.FunctionExpression:
        case SyntaxKind.ArrowFunction:
        case SyntaxKind.TypeAliasDeclaration:
        case SyntaxKind.JSDocTemplateTag:
        case SyntaxKind.JSDocTypedefTag:
        case SyntaxKind.JSDocEnumTag:
        case SyntaxKind.JSDocCallbackTag:
        case SyntaxKind.MappedType:
        case SyntaxKind.ConditionalType: {
          const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
          if ((kind === SyntaxKind.FunctionExpression || kind === SyntaxKind.ArrowFunction || isObjectLiteralMethod(node)) && isContextSensitive(node)) {
            const signature = firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfDeclaration(node)), SignatureKind.Call));
            if (signature && signature.typeParameters) {
              return [...outerTypeParameters || emptyArray, ...signature.typeParameters];
            }
          }
          if (kind === SyntaxKind.MappedType) {
            return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter)));
          } else if (kind === SyntaxKind.ConditionalType) {
            return concatenate(outerTypeParameters, getInferTypeParameters(node));
          }
          const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node));
          const thisType = includeThisTypes && (kind === SyntaxKind.ClassDeclaration || kind === SyntaxKind.ClassExpression || kind === SyntaxKind.InterfaceDeclaration || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node)).thisType;
          return thisType ? append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
        }
        case SyntaxKind.JSDocParameterTag:
          const paramSymbol = getParameterSymbolFromJSDoc(node);
          if (paramSymbol) {
            node = paramSymbol.valueDeclaration;
          }
          break;
        case SyntaxKind.JSDoc: {
          const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
          return node.tags ? appendTypeParameters(outerTypeParameters, flatMap(node.tags, (t) => isJSDocTemplateTag(t) ? t.typeParameters : void 0)) : outerTypeParameters;
        }
      }
    }
  }
  function getOuterTypeParametersOfClassOrInterface(symbol) {
    const declaration = symbol.flags & SymbolFlags.Class || symbol.flags & SymbolFlags.Function ? symbol.valueDeclaration : symbol.declarations?.find((decl) => {
      if (decl.kind === SyntaxKind.InterfaceDeclaration) {
        return true;
      }
      if (decl.kind !== SyntaxKind.VariableDeclaration) {
        return false;
      }
      const initializer = decl.initializer;
      return !!initializer && (initializer.kind === SyntaxKind.FunctionExpression || initializer.kind === SyntaxKind.ArrowFunction);
    });
    Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
    return getOuterTypeParameters(declaration);
  }
  function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
    if (!symbol.declarations) {
      return;
    }
    let result;
    for (const node of symbol.declarations) {
      if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression || isJSConstructor(node) || isTypeAlias(node)) {
        const declaration = node;
        result = appendTypeParameters(result, getEffectiveTypeParameterDeclarations(declaration));
      }
    }
    return result;
  }
  function getTypeParametersOfClassOrInterface(symbol) {
    return concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
  }
  function isMixinConstructorType(type) {
    const signatures = getSignaturesOfType(type, SignatureKind.Construct);
    if (signatures.length === 1) {
      const s = signatures[0];
      if (!s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s)) {
        const paramType = getTypeOfParameter(s.parameters[0]);
        return isTypeAny(paramType) || getElementTypeOfArrayType(paramType) === anyType;
      }
    }
    return false;
  }
  function isConstructorType(type) {
    if (getSignaturesOfType(type, SignatureKind.Construct).length > 0) {
      return true;
    }
    if (type.flags & TypeFlags.TypeVariable) {
      const constraint = getBaseConstraintOfType(type);
      return !!constraint && isMixinConstructorType(constraint);
    }
    return false;
  }
  function getBaseTypeNodeOfClass(type) {
    const decl = getClassLikeDeclarationOfSymbol(type.symbol);
    return decl && getEffectiveBaseTypeNode(decl);
  }
  function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
    const typeArgCount = length(typeArgumentNodes);
    const isJavascript = isInJSFile(location);
    return filter(getSignaturesOfType(type, SignatureKind.Construct), (sig) => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters));
  }
  function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
    const signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
    const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode);
    return sameMap(signatures, (sig) => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJSFile(location)) : sig);
  }
  function getBaseConstructorTypeOfClass(type) {
    if (!type.resolvedBaseConstructorType) {
      const decl = getClassLikeDeclarationOfSymbol(type.symbol);
      const extended = decl && getEffectiveBaseTypeNode(decl);
      const baseTypeNode = getBaseTypeNodeOfClass(type);
      if (!baseTypeNode) {
        return type.resolvedBaseConstructorType = undefinedType;
      }
      if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
        return errorType;
      }
      const baseConstructorType = checkExpression(baseTypeNode.expression);
      if (extended && baseTypeNode !== extended) {
        Debug.assert(!extended.typeArguments);
        checkExpression(extended.expression);
      }
      if (baseConstructorType.flags & (TypeFlags.Object | TypeFlags.Intersection)) {
        resolveStructuredTypeMembers(baseConstructorType);
      }
      if (!popTypeResolution()) {
        error(type.symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
        return type.resolvedBaseConstructorType ??= errorType;
      }
      if (!(baseConstructorType.flags & TypeFlags.Any) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
        const err = error(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
        if (baseConstructorType.flags & TypeFlags.TypeParameter) {
          const constraint = getConstraintFromTypeParameter(baseConstructorType);
          let ctorReturn = unknownType;
          if (constraint) {
            const ctorSig = getSignaturesOfType(constraint, SignatureKind.Construct);
            if (ctorSig[0]) {
              ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
            }
          }
          if (baseConstructorType.symbol.declarations) {
            addRelatedInfo(err, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
          }
        }
        return type.resolvedBaseConstructorType ??= errorType;
      }
      type.resolvedBaseConstructorType ??= baseConstructorType;
    }
    return type.resolvedBaseConstructorType;
  }
  function getImplementsTypes(type) {
    let resolvedImplementsTypes = emptyArray;
    if (type.symbol.declarations) {
      for (const declaration of type.symbol.declarations) {
        const implementsTypeNodes = getEffectiveImplementsTypeNodes(declaration);
        if (!implementsTypeNodes) continue;
        for (const node of implementsTypeNodes) {
          const implementsType = getTypeFromTypeNode(node);
          if (!isErrorType(implementsType)) {
            if (resolvedImplementsTypes === emptyArray) {
              resolvedImplementsTypes = [implementsType];
            } else {
              resolvedImplementsTypes.push(implementsType);
            }
          }
        }
      }
    }
    return resolvedImplementsTypes;
  }
  function reportCircularBaseType(node, type) {
    error(node, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(
      type,
      /*enclosingDeclaration*/
      void 0,
      TypeFormatFlags.WriteArrayAsGenericType
    ));
  }
  function getBaseTypes(type) {
    if (!type.baseTypesResolved) {
      if (pushTypeResolution(type, 6 /* ResolvedBaseTypes */)) {
        if (type.objectFlags & ObjectFlags.Tuple) {
          type.resolvedBaseTypes = [getTupleBaseType(type)];
        } else if (type.symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
          if (type.symbol.flags & SymbolFlags.Class) {
            resolveBaseTypesOfClass(type);
          }
          if (type.symbol.flags & SymbolFlags.Interface) {
            resolveBaseTypesOfInterface(type);
          }
        } else {
          Debug.fail("type must be class or interface");
        }
        if (!popTypeResolution() && type.symbol.declarations) {
          for (const declaration of type.symbol.declarations) {
            if (declaration.kind === SyntaxKind.ClassDeclaration || declaration.kind === SyntaxKind.InterfaceDeclaration) {
              reportCircularBaseType(declaration, type);
            }
          }
        }
      }
      type.baseTypesResolved = true;
    }
    return type.resolvedBaseTypes;
  }
  function getTupleBaseType(type) {
    const elementTypes = sameMap(type.typeParameters, (t, i) => type.elementFlags[i] & ElementFlags.Variadic ? getIndexedAccessType(t, numberType) : t);
    return createArrayType(getUnionType(elementTypes || emptyArray), type.readonly);
  }
  function resolveBaseTypesOfClass(type) {
    type.resolvedBaseTypes = resolvingEmptyArray;
    const baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
    if (!(baseConstructorType.flags & (TypeFlags.Object | TypeFlags.Intersection | TypeFlags.Any))) {
      return type.resolvedBaseTypes = emptyArray;
    }
    const baseTypeNode = getBaseTypeNodeOfClass(type);
    let baseType;
    const originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : void 0;
    if (baseConstructorType.symbol && baseConstructorType.symbol.flags & SymbolFlags.Class && areAllOuterTypeParametersApplied(originalBaseType)) {
      baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
    } else if (baseConstructorType.flags & TypeFlags.Any) {
      baseType = baseConstructorType;
    } else {
      const constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
      if (!constructors.length) {
        error(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
        return type.resolvedBaseTypes = emptyArray;
      }
      baseType = getReturnTypeOfSignature(constructors[0]);
    }
    if (isErrorType(baseType)) {
      return type.resolvedBaseTypes = emptyArray;
    }
    const reducedBaseType = getReducedType(baseType);
    if (!isValidBaseType(reducedBaseType)) {
      const elaboration = elaborateNeverIntersection(
        /*errorInfo*/
        void 0,
        baseType
      );
      const diagnostic = chainDiagnosticMessages(elaboration, Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType));
      diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(baseTypeNode.expression), baseTypeNode.expression, diagnostic));
      return type.resolvedBaseTypes = emptyArray;
    }
    if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
      error(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(
        type,
        /*enclosingDeclaration*/
        void 0,
        TypeFormatFlags.WriteArrayAsGenericType
      ));
      return type.resolvedBaseTypes = emptyArray;
    }
    if (type.resolvedBaseTypes === resolvingEmptyArray) {
      type.members = void 0;
    }
    return type.resolvedBaseTypes = [reducedBaseType];
  }
  function areAllOuterTypeParametersApplied(type) {
    const outerTypeParameters = type.outerTypeParameters;
    if (outerTypeParameters) {
      const last2 = outerTypeParameters.length - 1;
      const typeArguments = getTypeArguments(type);
      return outerTypeParameters[last2].symbol !== typeArguments[last2].symbol;
    }
    return true;
  }
  function isValidBaseType(type) {
    if (type.flags & TypeFlags.TypeParameter) {
      const constraint = getBaseConstraintOfType(type);
      if (constraint) {
        return isValidBaseType(constraint);
      }
    }
    return !!(type.flags & (TypeFlags.Object | TypeFlags.NonPrimitive | TypeFlags.Any) && !isGenericMappedType(type) || type.flags & TypeFlags.Intersection && every(type.types, isValidBaseType));
  }
  function resolveBaseTypesOfInterface(type) {
    type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
    if (type.symbol.declarations) {
      for (const declaration of type.symbol.declarations) {
        if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(declaration)) {
          for (const node of getInterfaceBaseTypeNodes(declaration)) {
            const baseType = getReducedType(getTypeFromTypeNode(node));
            if (!isErrorType(baseType)) {
              if (isValidBaseType(baseType)) {
                if (type !== baseType && !hasBaseType(baseType, type)) {
                  if (type.resolvedBaseTypes === emptyArray) {
                    type.resolvedBaseTypes = [baseType];
                  } else {
                    type.resolvedBaseTypes.push(baseType);
                  }
                } else {
                  reportCircularBaseType(declaration, type);
                }
              } else {
                error(node, Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
              }
            }
          }
        }
      }
    }
  }
  function isThislessInterface(symbol) {
    if (!symbol.declarations) {
      return true;
    }
    for (const declaration of symbol.declarations) {
      if (declaration.kind === SyntaxKind.InterfaceDeclaration) {
        if (declaration.flags & NodeFlags.ContainsThis) {
          return false;
        }
        const baseTypeNodes = getInterfaceBaseTypeNodes(declaration);
        if (baseTypeNodes) {
          for (const node of baseTypeNodes) {
            if (isEntityNameExpression(node.expression)) {
              const baseSymbol = resolveEntityName(
                node.expression,
                SymbolFlags.Type,
                /*ignoreErrors*/
                true
              );
              if (!baseSymbol || !(baseSymbol.flags & SymbolFlags.Interface) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
                return false;
              }
            }
          }
        }
      }
    }
    return true;
  }
  function getDeclaredTypeOfClassOrInterface(symbol) {
    let links = getSymbolLinks(symbol);
    const originalLinks = links;
    if (!links.declaredType) {
      const kind = symbol.flags & SymbolFlags.Class ? ObjectFlags.Class : ObjectFlags.Interface;
      const merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration));
      if (merged) {
        symbol = merged;
        links = merged.links;
      }
      const type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
      const outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
      const localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
      if (outerTypeParameters || localTypeParameters || kind === ObjectFlags.Class || !isThislessInterface(symbol)) {
        type.objectFlags |= ObjectFlags.Reference;
        type.typeParameters = concatenate(outerTypeParameters, localTypeParameters);
        type.outerTypeParameters = outerTypeParameters;
        type.localTypeParameters = localTypeParameters;
        type.instantiations = /* @__PURE__ */ new Map();
        type.instantiations.set(getTypeListId(type.typeParameters), type);
        type.target = type;
        type.resolvedTypeArguments = type.typeParameters;
        type.thisType = createTypeParameter(symbol);
        type.thisType.isThisType = true;
        type.thisType.constraint = type;
      }
    }
    return links.declaredType;
  }
  function getDeclaredTypeOfTypeAlias(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.declaredType) {
      if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
        return errorType;
      }
      const declaration = Debug.checkDefined(symbol.declarations?.find(isTypeAlias), "Type alias symbol with no valid declaration found");
      const typeNode = isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
      let type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
      if (popTypeResolution()) {
        const typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
        if (typeParameters) {
          links.typeParameters = typeParameters;
          links.instantiations = /* @__PURE__ */ new Map();
          links.instantiations.set(getTypeListId(typeParameters), type);
        }
        if (type === intrinsicMarkerType && symbol.escapedName === "BuiltinIteratorReturn") {
          type = getBuiltinIteratorReturnType();
        }
      } else {
        type = errorType;
        if (declaration.kind === SyntaxKind.JSDocEnumTag) {
          error(declaration.typeExpression.type, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
        } else {
          error(isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
        }
      }
      links.declaredType ??= type;
    }
    return links.declaredType;
  }
  function getBaseTypeOfEnumLikeType(type) {
    return type.flags & TypeFlags.EnumLike && type.symbol.flags & SymbolFlags.EnumMember ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
  }
  function getDeclaredTypeOfEnum(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.declaredType) {
      const memberTypeList = [];
      if (symbol.declarations) {
        for (const declaration of symbol.declarations) {
          if (declaration.kind === SyntaxKind.EnumDeclaration) {
            for (const member of declaration.members) {
              if (hasBindableName(member)) {
                const memberSymbol = getSymbolOfDeclaration(member);
                const value = getEnumMemberValue(member).value;
                const memberType = getFreshTypeOfLiteralType(
                  value !== void 0 ? getEnumLiteralType(value, getSymbolId(symbol), memberSymbol) : createComputedEnumType(memberSymbol)
                );
                getSymbolLinks(memberSymbol).declaredType = memberType;
                memberTypeList.push(getRegularTypeOfLiteralType(memberType));
              }
            }
          }
        }
      }
      const enumType = memberTypeList.length ? getUnionType(
        memberTypeList,
        UnionReduction.Literal,
        symbol,
        /*aliasTypeArguments*/
        void 0
      ) : createComputedEnumType(symbol);
      if (enumType.flags & TypeFlags.Union) {
        enumType.flags |= TypeFlags.EnumLiteral;
        enumType.symbol = symbol;
      }
      links.declaredType = enumType;
    }
    return links.declaredType;
  }
  function createComputedEnumType(symbol) {
    const regularType = createTypeWithSymbol(TypeFlags.Enum, symbol);
    const freshType = createTypeWithSymbol(TypeFlags.Enum, symbol);
    regularType.regularType = regularType;
    regularType.freshType = freshType;
    freshType.regularType = regularType;
    freshType.freshType = freshType;
    return regularType;
  }
  function getDeclaredTypeOfEnumMember(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.declaredType) {
      const enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
      if (!links.declaredType) {
        links.declaredType = enumType;
      }
    }
    return links.declaredType;
  }
  function getDeclaredTypeOfTypeParameter(symbol) {
    const links = getSymbolLinks(symbol);
    return links.declaredType || (links.declaredType = createTypeParameter(symbol));
  }
  function getDeclaredTypeOfAlias(symbol) {
    const links = getSymbolLinks(symbol);
    return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
  }
  function getDeclaredTypeOfSymbol(symbol) {
    return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
  }
  function tryGetDeclaredTypeOfSymbol(symbol) {
    if (symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
      return getDeclaredTypeOfClassOrInterface(symbol);
    }
    if (symbol.flags & SymbolFlags.TypeAlias) {
      return getDeclaredTypeOfTypeAlias(symbol);
    }
    if (symbol.flags & SymbolFlags.TypeParameter) {
      return getDeclaredTypeOfTypeParameter(symbol);
    }
    if (symbol.flags & SymbolFlags.Enum) {
      return getDeclaredTypeOfEnum(symbol);
    }
    if (symbol.flags & SymbolFlags.EnumMember) {
      return getDeclaredTypeOfEnumMember(symbol);
    }
    if (symbol.flags & SymbolFlags.Alias) {
      return getDeclaredTypeOfAlias(symbol);
    }
    return void 0;
  }
  function isThislessType(node) {
    switch (node.kind) {
      case SyntaxKind.AnyKeyword:
      case SyntaxKind.UnknownKeyword:
      case SyntaxKind.StringKeyword:
      case SyntaxKind.NumberKeyword:
      case SyntaxKind.BigIntKeyword:
      case SyntaxKind.BooleanKeyword:
      case SyntaxKind.SymbolKeyword:
      case SyntaxKind.ObjectKeyword:
      case SyntaxKind.VoidKeyword:
      case SyntaxKind.UndefinedKeyword:
      case SyntaxKind.NeverKeyword:
      case SyntaxKind.LiteralType:
        return true;
      case SyntaxKind.ArrayType:
        return isThislessType(node.elementType);
      case SyntaxKind.TypeReference:
        return !node.typeArguments || node.typeArguments.every(isThislessType);
    }
    return false;
  }
  function isThislessTypeParameter(node) {
    const constraint = getEffectiveConstraintOfTypeParameter(node);
    return !constraint || isThislessType(constraint);
  }
  function isThislessVariableLikeDeclaration(node) {
    const typeNode = getEffectiveTypeAnnotationNode(node);
    return typeNode ? isThislessType(typeNode) : !hasInitializer(node);
  }
  function isThislessFunctionLikeDeclaration(node) {
    const returnType = getEffectiveReturnTypeNode(node);
    const typeParameters = getEffectiveTypeParameterDeclarations(node);
    return (node.kind === SyntaxKind.Constructor || !!returnType && isThislessType(returnType)) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter);
  }
  function isThisless(symbol) {
    if (symbol.declarations && symbol.declarations.length === 1) {
      const declaration = symbol.declarations[0];
      if (declaration) {
        switch (declaration.kind) {
          case SyntaxKind.PropertyDeclaration:
          case SyntaxKind.PropertySignature:
            return isThislessVariableLikeDeclaration(declaration);
          case SyntaxKind.MethodDeclaration:
          case SyntaxKind.MethodSignature:
          case SyntaxKind.Constructor:
          case SyntaxKind.GetAccessor:
          case SyntaxKind.SetAccessor:
            return isThislessFunctionLikeDeclaration(declaration);
        }
      }
    }
    return false;
  }
  function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
    const result = createSymbolTable();
    for (const symbol of symbols) {
      result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
    }
    return result;
  }
  function addInheritedMembers(symbols, baseSymbols) {
    for (const base of baseSymbols) {
      if (isStaticPrivateIdentifierProperty(base)) {
        continue;
      }
      const derived = symbols.get(base.escapedName);
      if (!derived || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration) && !isConstructorDeclaredProperty(derived) && !getContainingClassStaticBlock(derived.valueDeclaration)) {
        symbols.set(base.escapedName, base);
        symbols.set(base.escapedName, base);
      }
    }
  }
  function isStaticPrivateIdentifierProperty(s) {
    return !!s.valueDeclaration && isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && isStatic(s.valueDeclaration);
  }
  function resolveDeclaredMembers(type) {
    if (!type.declaredProperties) {
      const symbol = type.symbol;
      const members = getMembersOfSymbol(symbol);
      type.declaredProperties = getNamedMembers(members);
      type.declaredCallSignatures = emptyArray;
      type.declaredConstructSignatures = emptyArray;
      type.declaredIndexInfos = emptyArray;
      type.declaredCallSignatures = getSignaturesOfSymbol(members.get(InternalSymbolName.Call));
      type.declaredConstructSignatures = getSignaturesOfSymbol(members.get(InternalSymbolName.New));
      type.declaredIndexInfos = getIndexInfosOfSymbol(symbol);
    }
    return type;
  }
  function isLateBindableName(node) {
    if (!isComputedPropertyName(node) && !isElementAccessExpression(node)) {
      return false;
    }
    const expr = isComputedPropertyName(node) ? node.expression : node.argumentExpression;
    return isEntityNameExpression(expr) && isTypeUsableAsPropertyName(isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
  }
  function isLateBoundName(name) {
    return name.charCodeAt(0) === CharacterCodes._ && name.charCodeAt(1) === CharacterCodes._ && name.charCodeAt(2) === CharacterCodes.at;
  }
  function hasLateBindableName(node) {
    const name = getNameOfDeclaration(node);
    return !!name && isLateBindableName(name);
  }
  function hasBindableName(node) {
    return !hasDynamicName(node) || hasLateBindableName(node);
  }
  function isNonBindableDynamicName(node) {
    return isDynamicName(node) && !isLateBindableName(node);
  }
  function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
    Debug.assert(!!(getCheckFlags(symbol) & CheckFlags.Late), "Expected a late-bound symbol.");
    symbol.flags |= symbolFlags;
    getSymbolLinks(member.symbol).lateSymbol = symbol;
    if (!symbol.declarations) {
      symbol.declarations = [member];
    } else if (!member.symbol.isReplaceableByMethod) {
      symbol.declarations.push(member);
    }
    if (symbolFlags & SymbolFlags.Value) {
      if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
        symbol.valueDeclaration = member;
      }
    }
  }
  function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
    Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
    const links = getNodeLinks(decl);
    if (!links.resolvedSymbol) {
      links.resolvedSymbol = decl.symbol;
      const declName = isBinaryExpression(decl) ? decl.left : decl.name;
      const type = isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
      if (isTypeUsableAsPropertyName(type)) {
        const memberName = getPropertyNameFromType(type);
        const symbolFlags = decl.symbol.flags;
        let lateSymbol = lateSymbols.get(memberName);
        if (!lateSymbol) lateSymbols.set(memberName, lateSymbol = createSymbol(SymbolFlags.None, memberName, CheckFlags.Late));
        const earlySymbol = earlySymbols && earlySymbols.get(memberName);
        if (!(parent.flags & SymbolFlags.Class) && lateSymbol.flags & getExcludedSymbolFlags(symbolFlags)) {
          const declarations = earlySymbol ? concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
          const name = !(type.flags & TypeFlags.UniqueESSymbol) && unescapeLeadingUnderscores(memberName) || declarationNameToString(declName);
          forEach(declarations, (declaration) => error(getNameOfDeclaration(declaration) || declaration, Diagnostics.Property_0_was_also_declared_here, name));
          error(declName || decl, Diagnostics.Duplicate_property_0, name);
          lateSymbol = createSymbol(SymbolFlags.None, memberName, CheckFlags.Late);
        }
        lateSymbol.links.nameType = type;
        addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
        if (lateSymbol.parent) {
          Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
        } else {
          lateSymbol.parent = parent;
        }
        return links.resolvedSymbol = lateSymbol;
      }
    }
    return links.resolvedSymbol;
  }
  function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
    const links = getSymbolLinks(symbol);
    if (!links[resolutionKind]) {
      const isStatic2 = resolutionKind === "resolvedExports" /* resolvedExports */;
      const earlySymbols = !isStatic2 ? symbol.members : symbol.flags & SymbolFlags.Module ? getExportsOfModuleWorker(symbol).exports : symbol.exports;
      links[resolutionKind] = earlySymbols || emptySymbols;
      const lateSymbols = createSymbolTable();
      for (const decl of symbol.declarations || emptyArray) {
        const members = getMembersOfDeclaration(decl);
        if (members) {
          for (const member of members) {
            if (isStatic2 === hasStaticModifier(member)) {
              if (hasLateBindableName(member)) {
                lateBindMember(symbol, earlySymbols, lateSymbols, member);
              }
            }
          }
        }
      }
      const assignments = getFunctionExpressionParentSymbolOrSymbol(symbol).assignmentDeclarationMembers;
      if (assignments) {
        const decls = arrayFrom(assignments.values());
        for (const member of decls) {
          const assignmentKind = getAssignmentDeclarationKind(member);
          const isInstanceMember = assignmentKind === AssignmentDeclarationKind.PrototypeProperty || isBinaryExpression(member) && isPossiblyAliasedThisProperty(member, assignmentKind) || assignmentKind === AssignmentDeclarationKind.ObjectDefinePrototypeProperty || assignmentKind === AssignmentDeclarationKind.Prototype;
          if (isStatic2 === !isInstanceMember) {
            if (hasLateBindableName(member)) {
              lateBindMember(symbol, earlySymbols, lateSymbols, member);
            }
          }
        }
      }
      let resolved = combineSymbolTables(earlySymbols, lateSymbols);
      if (symbol.flags & SymbolFlags.Transient && links.cjsExportMerged && symbol.declarations) {
        for (const decl of symbol.declarations) {
          const original = getSymbolLinks(decl.symbol)[resolutionKind];
          if (!resolved) {
            resolved = original;
            continue;
          }
          if (!original) continue;
          original.forEach((s, name) => {
            const existing = resolved.get(name);
            if (!existing) resolved.set(name, s);
            else if (existing === s) return;
            else resolved.set(name, mergeSymbol(existing, s));
          });
        }
      }
      links[resolutionKind] = resolved || emptySymbols;
    }
    return links[resolutionKind];
  }
  function getMembersOfSymbol(symbol) {
    return symbol.flags & SymbolFlags.LateBindingContainer ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) : symbol.members || emptySymbols;
  }
  function getLateBoundSymbol(symbol) {
    if (symbol.flags & SymbolFlags.ClassMember && symbol.escapedName === InternalSymbolName.Computed) {
      const links = getSymbolLinks(symbol);
      if (!links.lateSymbol && some(symbol.declarations, hasLateBindableName)) {
        const parent = getMergedSymbol(symbol.parent);
        if (some(symbol.declarations, hasStaticModifier)) {
          getExportsOfSymbol(parent);
        } else {
          getMembersOfSymbol(parent);
        }
      }
      return links.lateSymbol || (links.lateSymbol = symbol);
    }
    return symbol;
  }
  function getTypeWithThisArgument(type, thisArgument, needApparentType) {
    if (getObjectFlags(type) & ObjectFlags.Reference) {
      const target = type.target;
      const typeArguments = getTypeArguments(type);
      return length(target.typeParameters) === length(typeArguments) ? createTypeReference(target, concatenate(typeArguments, [thisArgument || target.thisType])) : type;
    } else if (type.flags & TypeFlags.Intersection) {
      const types = sameMap(type.types, (t) => getTypeWithThisArgument(t, thisArgument, needApparentType));
      return types !== type.types ? getIntersectionType(types) : type;
    }
    return needApparentType ? getApparentType(type) : type;
  }
  function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
    let mapper;
    let members;
    let callSignatures;
    let constructSignatures;
    let indexInfos;
    if (rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
      members = source.symbol ? getMembersOfSymbol(source.symbol) : createSymbolTable(source.declaredProperties);
      callSignatures = source.declaredCallSignatures;
      constructSignatures = source.declaredConstructSignatures;
      indexInfos = source.declaredIndexInfos;
    } else {
      mapper = createTypeMapper(typeParameters, typeArguments);
      members = createInstantiatedSymbolTable(
        source.declaredProperties,
        mapper,
        /*mappingThisOnly*/
        typeParameters.length === 1
      );
      callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
      constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
      indexInfos = instantiateIndexInfos(source.declaredIndexInfos, mapper);
    }
    const baseTypes = getBaseTypes(source);
    if (baseTypes.length) {
      if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
        const symbolTable = createSymbolTable(source.declaredProperties);
        const sourceIndex = getIndexSymbol(source.symbol);
        if (sourceIndex) {
          symbolTable.set(InternalSymbolName.Index, sourceIndex);
        }
        members = symbolTable;
      }
      setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos);
      const thisArgument = lastOrUndefined(typeArguments);
      for (const baseType of baseTypes) {
        const instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
        addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
        callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Call));
        constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Construct));
        const inheritedIndexInfos = instantiatedBaseType !== anyType ? getIndexInfosOfType(instantiatedBaseType) : [createIndexInfo(
          stringType,
          anyType,
          /*isReadonly*/
          false
        )];
        indexInfos = concatenate(indexInfos, filter(inheritedIndexInfos, (info) => !findIndexInfo(indexInfos, info.keyType)));
      }
    }
    setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos);
  }
  function resolveClassOrInterfaceMembers(type) {
    resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray);
  }
  function resolveTypeReferenceMembers(type) {
    const source = resolveDeclaredMembers(type.target);
    const typeParameters = concatenate(source.typeParameters, [source.thisType]);
    const typeArguments = getTypeArguments(type);
    const paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : concatenate(typeArguments, [type]);
    resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
  }
  function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
    const sig = new Signature2(checker, flags);
    sig.declaration = declaration;
    sig.typeParameters = typeParameters;
    sig.parameters = parameters;
    sig.thisParameter = thisParameter;
    sig.resolvedReturnType = resolvedReturnType;
    sig.resolvedTypePredicate = resolvedTypePredicate;
    sig.minArgumentCount = minArgumentCount;
    sig.resolvedMinArgumentCount = void 0;
    sig.target = void 0;
    sig.mapper = void 0;
    sig.compositeSignatures = void 0;
    sig.compositeKind = void 0;
    return sig;
  }
  function cloneSignature(sig) {
    const result = createSignature(
      sig.declaration,
      sig.typeParameters,
      sig.thisParameter,
      sig.parameters,
      /*resolvedReturnType*/
      void 0,
      /*resolvedTypePredicate*/
      void 0,
      sig.minArgumentCount,
      sig.flags & SignatureFlags.PropagatingFlags
    );
    result.target = sig.target;
    result.mapper = sig.mapper;
    result.compositeSignatures = sig.compositeSignatures;
    result.compositeKind = sig.compositeKind;
    return result;
  }
  function createUnionSignature(signature, unionSignatures) {
    const result = cloneSignature(signature);
    result.compositeSignatures = unionSignatures;
    result.compositeKind = TypeFlags.Union;
    result.target = void 0;
    result.mapper = void 0;
    return result;
  }
  function getOptionalCallSignature(signature, callChainFlags) {
    if ((signature.flags & SignatureFlags.CallChainFlags) === callChainFlags) {
      return signature;
    }
    if (!signature.optionalCallSignatureCache) {
      signature.optionalCallSignatureCache = {};
    }
    const key = callChainFlags === SignatureFlags.IsInnerCallChain ? "inner" : "outer";
    return signature.optionalCallSignatureCache[key] || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
  }
  function createOptionalCallSignature(signature, callChainFlags) {
    Debug.assert(callChainFlags === SignatureFlags.IsInnerCallChain || callChainFlags === SignatureFlags.IsOuterCallChain, "An optional call signature can either be for an inner call chain or an outer call chain, but not both.");
    const result = cloneSignature(signature);
    result.flags |= callChainFlags;
    return result;
  }
  function getExpandedParameters(sig, skipUnionExpanding) {
    if (signatureHasRestParameter(sig)) {
      const restIndex = sig.parameters.length - 1;
      const restSymbol = sig.parameters[restIndex];
      const restType = getTypeOfSymbol(restSymbol);
      if (isTupleType(restType)) {
        return [expandSignatureParametersWithTupleMembers(restType, restIndex, restSymbol)];
      } else if (!skipUnionExpanding && restType.flags & TypeFlags.Union && every(restType.types, isTupleType)) {
        return map(restType.types, (t) => expandSignatureParametersWithTupleMembers(t, restIndex, restSymbol));
      }
    }
    return [sig.parameters];
    function expandSignatureParametersWithTupleMembers(restType, restIndex, restSymbol) {
      const elementTypes = getTypeArguments(restType);
      const associatedNames = getUniqAssociatedNamesFromTupleType(restType, restSymbol);
      const restParams = map(elementTypes, (t, i) => {
        const name = associatedNames && associatedNames[i] ? associatedNames[i] : getParameterNameAtPosition(sig, restIndex + i, restType);
        const flags = restType.target.elementFlags[i];
        const checkFlags = flags & ElementFlags.Variable ? CheckFlags.RestParameter : flags & ElementFlags.Optional ? CheckFlags.OptionalParameter : 0;
        const symbol = createSymbol(SymbolFlags.FunctionScopedVariable, name, checkFlags);
        symbol.links.type = flags & ElementFlags.Rest ? createArrayType(t) : t;
        return symbol;
      });
      return concatenate(sig.parameters.slice(0, restIndex), restParams);
    }
    function getUniqAssociatedNamesFromTupleType(type, restSymbol) {
      const names = map(type.target.labeledElementDeclarations, (labeledElement, i) => getTupleElementLabel(labeledElement, i, type.target.elementFlags[i], restSymbol));
      if (names) {
        const duplicates = [];
        const uniqueNames = /* @__PURE__ */ new Set();
        for (let i = 0; i < names.length; i++) {
          const name = names[i];
          if (!tryAddToSet(uniqueNames, name)) {
            duplicates.push(i);
          }
        }
        const counters = /* @__PURE__ */ new Map();
        for (const i of duplicates) {
          let counter = counters.get(names[i]) ?? 1;
          let name;
          while (!tryAddToSet(uniqueNames, name = `${names[i]}_${counter}`)) {
            counter++;
          }
          names[i] = name;
          counters.set(names[i], counter + 1);
        }
      }
      return names;
    }
  }
  function getDefaultConstructSignatures(classType) {
    const baseConstructorType = getBaseConstructorTypeOfClass(classType);
    const baseSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct);
    const declaration = getClassLikeDeclarationOfSymbol(classType.symbol);
    const isAbstract = !!declaration && hasSyntacticModifier(declaration, ModifierFlags.Abstract);
    if (baseSignatures.length === 0) {
      return [createSignature(
        /*declaration*/
        void 0,
        classType.localTypeParameters,
        /*thisParameter*/
        void 0,
        emptyArray,
        classType,
        /*resolvedTypePredicate*/
        void 0,
        0,
        isAbstract ? SignatureFlags.Abstract : SignatureFlags.None
      )];
    }
    const baseTypeNode = getBaseTypeNodeOfClass(classType);
    const isJavaScript = isInJSFile(baseTypeNode);
    const typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
    const typeArgCount = length(typeArguments);
    const result = [];
    for (const baseSig of baseSignatures) {
      const minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
      const typeParamCount = length(baseSig.typeParameters);
      if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
        const sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
        sig.typeParameters = classType.localTypeParameters;
        sig.resolvedReturnType = classType;
        sig.flags = isAbstract ? sig.flags | SignatureFlags.Abstract : sig.flags & ~SignatureFlags.Abstract;
        result.push(sig);
      }
    }
    return result;
  }
  function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
    for (const s of signatureList) {
      if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
        return s;
      }
    }
  }
  function findMatchingSignatures(signatureLists, signature, listIndex) {
    if (signature.typeParameters) {
      if (listIndex > 0) {
        return void 0;
      }
      for (let i = 1; i < signatureLists.length; i++) {
        if (!findMatchingSignature(
          signatureLists[i],
          signature,
          /*partialMatch*/
          false,
          /*ignoreThisTypes*/
          false,
          /*ignoreReturnTypes*/
          false
        )) {
          return void 0;
        }
      }
      return [signature];
    }
    let result;
    for (let i = 0; i < signatureLists.length; i++) {
      const match = i === listIndex ? signature : findMatchingSignature(
        signatureLists[i],
        signature,
        /*partialMatch*/
        false,
        /*ignoreThisTypes*/
        false,
        /*ignoreReturnTypes*/
        true
      ) || findMatchingSignature(
        signatureLists[i],
        signature,
        /*partialMatch*/
        true,
        /*ignoreThisTypes*/
        false,
        /*ignoreReturnTypes*/
        true
      );
      if (!match) {
        return void 0;
      }
      result = appendIfUnique(result, match);
    }
    return result;
  }
  function getUnionSignatures(signatureLists) {
    let result;
    let indexWithLengthOverOne;
    for (let i = 0; i < signatureLists.length; i++) {
      if (signatureLists[i].length === 0) return emptyArray;
      if (signatureLists[i].length > 1) {
        indexWithLengthOverOne = indexWithLengthOverOne === void 0 ? i : -1;
      }
      for (const signature of signatureLists[i]) {
        if (!result || !findMatchingSignature(
          result,
          signature,
          /*partialMatch*/
          false,
          /*ignoreThisTypes*/
          false,
          /*ignoreReturnTypes*/
          true
        )) {
          const unionSignatures = findMatchingSignatures(signatureLists, signature, i);
          if (unionSignatures) {
            let s = signature;
            if (unionSignatures.length > 1) {
              let thisParameter = signature.thisParameter;
              const firstThisParameterOfUnionSignatures = forEach(unionSignatures, (sig) => sig.thisParameter);
              if (firstThisParameterOfUnionSignatures) {
                const thisType = getIntersectionType(mapDefined(unionSignatures, (sig) => sig.thisParameter && getTypeOfSymbol(sig.thisParameter)));
                thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
              }
              s = createUnionSignature(signature, unionSignatures);
              s.thisParameter = thisParameter;
            }
            (result || (result = [])).push(s);
          }
        }
      }
    }
    if (!length(result) && indexWithLengthOverOne !== -1) {
      const masterList = signatureLists[indexWithLengthOverOne !== void 0 ? indexWithLengthOverOne : 0];
      let results = masterList.slice();
      for (const signatures of signatureLists) {
        if (signatures !== masterList) {
          const signature = signatures[0];
          Debug.assert(!!signature, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
          results = !!signature.typeParameters && some(results, (s) => !!s.typeParameters && !compareTypeParametersIdentical(signature.typeParameters, s.typeParameters)) ? void 0 : map(results, (sig) => combineSignaturesOfUnionMembers(sig, signature));
          if (!results) {
            break;
          }
        }
      }
      result = results;
    }
    return result || emptyArray;
  }
  function compareTypeParametersIdentical(sourceParams, targetParams) {
    if (length(sourceParams) !== length(targetParams)) {
      return false;
    }
    if (!sourceParams || !targetParams) {
      return true;
    }
    const mapper = createTypeMapper(targetParams, sourceParams);
    for (let i = 0; i < sourceParams.length; i++) {
      const source = sourceParams[i];
      const target = targetParams[i];
      if (source === target) continue;
      if (!isTypeIdenticalTo(getConstraintFromTypeParameter(source) || unknownType, instantiateType(getConstraintFromTypeParameter(target) || unknownType, mapper))) return false;
    }
    return true;
  }
  function combineUnionThisParam(left, right, mapper) {
    if (!left || !right) {
      return left || right;
    }
    const thisType = getIntersectionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]);
    return createSymbolWithType(left, thisType);
  }
  function combineUnionParameters(left, right, mapper) {
    const leftCount = getParameterCount(left);
    const rightCount = getParameterCount(right);
    const longest = leftCount >= rightCount ? left : right;
    const shorter = longest === left ? right : left;
    const longestCount = longest === left ? leftCount : rightCount;
    const eitherHasEffectiveRest = hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right);
    const needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
    const params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
    for (let i = 0; i < longestCount; i++) {
      let longestParamType = tryGetTypeAtPosition(longest, i);
      if (longest === right) {
        longestParamType = instantiateType(longestParamType, mapper);
      }
      let shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
      if (shorter === right) {
        shorterParamType = instantiateType(shorterParamType, mapper);
      }
      const unionParamType = getIntersectionType([longestParamType, shorterParamType]);
      const isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === longestCount - 1;
      const isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
      const leftName = i >= leftCount ? void 0 : getParameterNameAtPosition(left, i);
      const rightName = i >= rightCount ? void 0 : getParameterNameAtPosition(right, i);
      const paramName = leftName === rightName ? leftName : !leftName ? rightName : !rightName ? leftName : void 0;
      const paramSymbol = createSymbol(
        SymbolFlags.FunctionScopedVariable | (isOptional && !isRestParam ? SymbolFlags.Optional : 0),
        paramName || `arg${i}`,
        isRestParam ? CheckFlags.RestParameter : isOptional ? CheckFlags.OptionalParameter : 0
      );
      paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
      params[i] = paramSymbol;
    }
    if (needsExtraRestElement) {
      const restParamSymbol = createSymbol(SymbolFlags.FunctionScopedVariable, "args", CheckFlags.RestParameter);
      restParamSymbol.links.type = createArrayType(getTypeAtPosition(shorter, longestCount));
      if (shorter === right) {
        restParamSymbol.links.type = instantiateType(restParamSymbol.links.type, mapper);
      }
      params[longestCount] = restParamSymbol;
    }
    return params;
  }
  function combineSignaturesOfUnionMembers(left, right) {
    const typeParams = left.typeParameters || right.typeParameters;
    let paramMapper;
    if (left.typeParameters && right.typeParameters) {
      paramMapper = createTypeMapper(right.typeParameters, left.typeParameters);
    }
    const declaration = left.declaration;
    const params = combineUnionParameters(left, right, paramMapper);
    const thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter, paramMapper);
    const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
    const result = createSignature(
      declaration,
      typeParams,
      thisParam,
      params,
      /*resolvedReturnType*/
      void 0,
      /*resolvedTypePredicate*/
      void 0,
      minArgCount,
      (left.flags | right.flags) & SignatureFlags.PropagatingFlags
    );
    result.compositeKind = TypeFlags.Union;
    result.compositeSignatures = concatenate(left.compositeKind !== TypeFlags.Intersection && left.compositeSignatures || [left], [right]);
    if (paramMapper) {
      result.mapper = left.compositeKind !== TypeFlags.Intersection && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper;
    } else if (left.compositeKind !== TypeFlags.Intersection && left.mapper && left.compositeSignatures) {
      result.mapper = left.mapper;
    }
    return result;
  }
  function getUnionIndexInfos(types) {
    const sourceInfos = getIndexInfosOfType(types[0]);
    if (sourceInfos) {
      const result = [];
      for (const info of sourceInfos) {
        const indexType = info.keyType;
        if (every(types, (t) => !!getIndexInfoOfType(t, indexType))) {
          result.push(createIndexInfo(indexType, getUnionType(map(types, (t) => getIndexTypeOfType(t, indexType))), some(types, (t) => getIndexInfoOfType(t, indexType).isReadonly)));
        }
      }
      return result;
    }
    return emptyArray;
  }
  function resolveUnionTypeMembers(type) {
    const callSignatures = getUnionSignatures(map(type.types, (t) => t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, SignatureKind.Call)));
    const constructSignatures = getUnionSignatures(map(type.types, (t) => getSignaturesOfType(t, SignatureKind.Construct)));
    const indexInfos = getUnionIndexInfos(type.types);
    setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, indexInfos);
  }
  function intersectTypes(type1, type2) {
    return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
  }
  function findMixins(types) {
    const constructorTypeCount = countWhere(types, (t) => getSignaturesOfType(t, SignatureKind.Construct).length > 0);
    const mixinFlags = map(types, isMixinConstructorType);
    if (constructorTypeCount > 0 && constructorTypeCount === countWhere(mixinFlags, (b) => b)) {
      const firstMixinIndex = mixinFlags.indexOf(
        /*searchElement*/
        true
      );
      mixinFlags[firstMixinIndex] = false;
    }
    return mixinFlags;
  }
  function includeMixinType(type, types, mixinFlags, index) {
    const mixedTypes = [];
    for (let i = 0; i < types.length; i++) {
      if (i === index) {
        mixedTypes.push(type);
      } else if (mixinFlags[i]) {
        mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], SignatureKind.Construct)[0]));
      }
    }
    return getIntersectionType(mixedTypes);
  }
  function resolveIntersectionTypeMembers(type) {
    let callSignatures;
    let constructSignatures;
    let indexInfos;
    const types = type.types;
    const mixinFlags = findMixins(types);
    const mixinCount = countWhere(mixinFlags, (b) => b);
    for (let i = 0; i < types.length; i++) {
      const t = type.types[i];
      if (!mixinFlags[i]) {
        let signatures = getSignaturesOfType(t, SignatureKind.Construct);
        if (signatures.length && mixinCount > 0) {
          signatures = map(signatures, (s) => {
            const clone = cloneSignature(s);
            clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
            return clone;
          });
        }
        constructSignatures = appendSignatures(constructSignatures, signatures);
      }
      callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, SignatureKind.Call));
      indexInfos = reduceLeft(getIndexInfosOfType(t), (infos, newInfo) => appendIndexInfo(
        infos,
        newInfo,
        /*union*/
        false
      ), indexInfos);
    }
    setStructuredTypeMembers(type, emptySymbols, callSignatures || emptyArray, constructSignatures || emptyArray, indexInfos || emptyArray);
  }
  function appendSignatures(signatures, newSignatures) {
    for (const sig of newSignatures) {
      if (!signatures || every(signatures, (s) => !compareSignaturesIdentical(
        s,
        sig,
        /*partialMatch*/
        false,
        /*ignoreThisTypes*/
        false,
        /*ignoreReturnTypes*/
        false,
        compareTypesIdentical
      ))) {
        signatures = append(signatures, sig);
      }
    }
    return signatures;
  }
  function appendIndexInfo(indexInfos, newInfo, union) {
    if (indexInfos) {
      for (let i = 0; i < indexInfos.length; i++) {
        const info = indexInfos[i];
        if (info.keyType === newInfo.keyType) {
          indexInfos[i] = createIndexInfo(info.keyType, union ? getUnionType([info.type, newInfo.type]) : getIntersectionType([info.type, newInfo.type]), union ? info.isReadonly || newInfo.isReadonly : info.isReadonly && newInfo.isReadonly);
          return indexInfos;
        }
      }
    }
    return append(indexInfos, newInfo);
  }
  function resolveAnonymousTypeMembers(type) {
    if (type.target) {
      setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray);
      const members2 = createInstantiatedSymbolTable(
        getPropertiesOfObjectType(type.target),
        type.mapper,
        /*mappingThisOnly*/
        false
      );
      const callSignatures = instantiateSignatures(getSignaturesOfType(type.target, SignatureKind.Call), type.mapper);
      const constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, SignatureKind.Construct), type.mapper);
      const indexInfos2 = instantiateIndexInfos(getIndexInfosOfType(type.target), type.mapper);
      setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2);
      return;
    }
    const symbol = getMergedSymbol(type.symbol);
    if (symbol.flags & SymbolFlags.TypeLiteral) {
      setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray);
      const members2 = getMembersOfSymbol(symbol);
      const callSignatures = getSignaturesOfSymbol(members2.get(InternalSymbolName.Call));
      const constructSignatures = getSignaturesOfSymbol(members2.get(InternalSymbolName.New));
      const indexInfos2 = getIndexInfosOfSymbol(symbol);
      setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2);
      return;
    }
    let members = getExportsOfSymbol(symbol);
    let indexInfos;
    if (symbol === globalThisSymbol) {
      const varsOnly = /* @__PURE__ */ new Map();
      members.forEach((p) => {
        if (!(p.flags & SymbolFlags.BlockScoped) && !(p.flags & SymbolFlags.ValueModule && p.declarations?.length && every(p.declarations, isAmbientModule))) {
          varsOnly.set(p.escapedName, p);
        }
      });
      members = varsOnly;
    }
    let baseConstructorIndexInfo;
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, emptyArray);
    if (symbol.flags & SymbolFlags.Class) {
      const classType = getDeclaredTypeOfClassOrInterface(symbol);
      const baseConstructorType = getBaseConstructorTypeOfClass(classType);
      if (baseConstructorType.flags & (TypeFlags.Object | TypeFlags.Intersection | TypeFlags.TypeVariable)) {
        members = createSymbolTable(getNamedOrIndexSignatureMembers(members));
        addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
      } else if (baseConstructorType === anyType) {
        baseConstructorIndexInfo = createIndexInfo(
          stringType,
          anyType,
          /*isReadonly*/
          false
        );
      }
    }
    const indexSymbol = getIndexSymbolFromSymbolTable(members);
    if (indexSymbol) {
      indexInfos = getIndexInfosOfIndexSymbol(indexSymbol);
    } else {
      if (baseConstructorIndexInfo) {
        indexInfos = append(indexInfos, baseConstructorIndexInfo);
      }
      if (symbol.flags & SymbolFlags.Enum && (getDeclaredTypeOfSymbol(symbol).flags & TypeFlags.Enum || some(type.properties, (prop) => !!(getTypeOfSymbol(prop).flags & TypeFlags.NumberLike)))) {
        indexInfos = append(indexInfos, enumNumberIndexInfo);
      }
    }
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos || emptyArray);
    if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method)) {
      type.callSignatures = getSignaturesOfSymbol(symbol);
    }
    if (symbol.flags & SymbolFlags.Class) {
      const classType = getDeclaredTypeOfClassOrInterface(symbol);
      let constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get(InternalSymbolName.Constructor)) : emptyArray;
      if (symbol.flags & SymbolFlags.Function) {
        constructSignatures = addRange(
          constructSignatures.slice(),
          mapDefined(
            type.callSignatures,
            (sig) => isJSConstructor(sig.declaration) ? createSignature(
              sig.declaration,
              sig.typeParameters,
              sig.thisParameter,
              sig.parameters,
              classType,
              /*resolvedTypePredicate*/
              void 0,
              sig.minArgumentCount,
              sig.flags & SignatureFlags.PropagatingFlags
            ) : void 0
          )
        );
      }
      if (!constructSignatures.length) {
        constructSignatures = getDefaultConstructSignatures(classType);
      }
      type.constructSignatures = constructSignatures;
    }
  }
  function replaceIndexedAccess(instantiable, type, replacement) {
    return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getNumberLiteralType(0), createTupleType([replacement])]));
  }
  function getLimitedConstraint(type) {
    const constraint = getConstraintTypeFromMappedType(type.mappedType);
    if (!(constraint.flags & TypeFlags.Union || constraint.flags & TypeFlags.Intersection)) {
      return;
    }
    const origin = constraint.flags & TypeFlags.Union ? constraint.origin : constraint;
    if (!origin || !(origin.flags & TypeFlags.Intersection)) {
      return;
    }
    const limitedConstraint = getIntersectionType(origin.types.filter((t) => t !== type.constraintType));
    return limitedConstraint !== neverType ? limitedConstraint : void 0;
  }
  function resolveReverseMappedTypeMembers(type) {
    const indexInfo = getIndexInfoOfType(type.source, stringType);
    const modifiers = getMappedTypeModifiers(type.mappedType);
    const readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
    const optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : SymbolFlags.Optional;
    const indexInfos = indexInfo ? [createIndexInfo(stringType, inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType) || unknownType, readonlyMask && indexInfo.isReadonly)] : emptyArray;
    const members = createSymbolTable();
    const limitedConstraint = getLimitedConstraint(type);
    for (const prop of getPropertiesOfType(type.source)) {
      if (limitedConstraint) {
        const propertyNameType = getLiteralTypeFromProperty(prop, TypeFlags.StringOrNumberLiteralOrUnique);
        if (!isTypeAssignableTo(propertyNameType, limitedConstraint)) {
          continue;
        }
      }
      const checkFlags = CheckFlags.ReverseMapped | (readonlyMask && isReadonlySymbol(prop) ? CheckFlags.Readonly : 0);
      const inferredProp = createSymbol(SymbolFlags.Property | prop.flags & optionalMask, prop.escapedName, checkFlags);
      inferredProp.declarations = prop.declarations;
      inferredProp.links.nameType = getSymbolLinks(prop).nameType;
      inferredProp.links.propertyType = getTypeOfSymbol(prop);
      if (type.constraintType.type.flags & TypeFlags.IndexedAccess && type.constraintType.type.objectType.flags & TypeFlags.TypeParameter && type.constraintType.type.indexType.flags & TypeFlags.TypeParameter) {
        const newTypeParam = type.constraintType.type.objectType;
        const newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam);
        inferredProp.links.mappedType = newMappedType;
        inferredProp.links.constraintType = getIndexType(newTypeParam);
      } else {
        inferredProp.links.mappedType = type.mappedType;
        inferredProp.links.constraintType = type.constraintType;
      }
      members.set(prop.escapedName, inferredProp);
    }
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos);
  }
  function getLowerBoundOfKeyType(type) {
    if (type.flags & TypeFlags.Index) {
      const t = getApparentType(type.type);
      return isGenericTupleType(t) ? getKnownKeysOfTupleType(t) : getIndexType(t);
    }
    if (type.flags & TypeFlags.Conditional) {
      if (type.root.isDistributive) {
        const checkType = type.checkType;
        const constraint = getLowerBoundOfKeyType(checkType);
        if (constraint !== checkType) {
          return getConditionalTypeInstantiation(
            type,
            prependTypeMapping(type.root.checkType, constraint, type.mapper),
            /*forConstraint*/
            false
          );
        }
      }
      return type;
    }
    if (type.flags & TypeFlags.Union) {
      return mapType(
        type,
        getLowerBoundOfKeyType,
        /*noReductions*/
        true
      );
    }
    if (type.flags & TypeFlags.Intersection) {
      const types = type.types;
      if (types.length === 2 && !!(types[0].flags & (TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt)) && types[1] === emptyTypeLiteralType) {
        return type;
      }
      return getIntersectionType(sameMap(type.types, getLowerBoundOfKeyType));
    }
    return type;
  }
  function getIsLateCheckFlag(s) {
    return getCheckFlags(s) & CheckFlags.Late;
  }
  function forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(type, include, stringsOnly, cb) {
    for (const prop of getPropertiesOfType(type)) {
      cb(getLiteralTypeFromProperty(prop, include));
    }
    if (type.flags & TypeFlags.Any) {
      cb(stringType);
    } else {
      for (const info of getIndexInfosOfType(type)) {
        if (!stringsOnly || info.keyType.flags & (TypeFlags.String | TypeFlags.TemplateLiteral)) {
          cb(info.keyType);
        }
      }
    }
  }
  function resolveMappedTypeMembers(type) {
    const members = createSymbolTable();
    let indexInfos;
    setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray);
    const typeParameter = getTypeParameterFromMappedType(type);
    const constraintType = getConstraintTypeFromMappedType(type);
    const mappedType = type.target || type;
    const nameType = getNameTypeFromMappedType(mappedType);
    const shouldLinkPropDeclarations = getMappedTypeNameTypeKind(mappedType) !== 2 /* Remapping */;
    const templateType = getTemplateTypeFromMappedType(mappedType);
    const modifiersType = getApparentType(getModifiersTypeFromMappedType(type));
    const templateModifiers = getMappedTypeModifiers(type);
    const include = TypeFlags.StringOrNumberLiteralOrUnique;
    if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
      forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(
        modifiersType,
        include,
        /*stringsOnly*/
        false,
        addMemberForKeyType
      );
    } else {
      forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
    }
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos || emptyArray);
    function addMemberForKeyType(keyType) {
      const propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType;
      forEachType(propNameType, (t) => addMemberForKeyTypeWorker(keyType, t));
    }
    function addMemberForKeyTypeWorker(keyType, propNameType) {
      if (isTypeUsableAsPropertyName(propNameType)) {
        const propName = getPropertyNameFromType(propNameType);
        const existingProp = members.get(propName);
        if (existingProp) {
          existingProp.links.nameType = getUnionType([existingProp.links.nameType, propNameType]);
          existingProp.links.keyType = getUnionType([existingProp.links.keyType, keyType]);
        } else {
          const modifiersProp = isTypeUsableAsPropertyName(keyType) ? getPropertyOfType(modifiersType, getPropertyNameFromType(keyType)) : void 0;
          const isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & SymbolFlags.Optional);
          const isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
          const stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & SymbolFlags.Optional;
          const lateFlag = modifiersProp ? getIsLateCheckFlag(modifiersProp) : 0;
          const prop = createSymbol(SymbolFlags.Property | (isOptional ? SymbolFlags.Optional : 0), propName, lateFlag | CheckFlags.Mapped | (isReadonly ? CheckFlags.Readonly : 0) | (stripOptional ? CheckFlags.StripOptional : 0));
          prop.links.mappedType = type;
          prop.links.nameType = propNameType;
          prop.links.keyType = keyType;
          if (modifiersProp) {
            prop.links.syntheticOrigin = modifiersProp;
            prop.declarations = shouldLinkPropDeclarations ? modifiersProp.declarations : void 0;
          }
          members.set(propName, prop);
        }
      } else if (isValidIndexKeyType(propNameType) || propNameType.flags & (TypeFlags.Any | TypeFlags.Enum)) {
        const indexKeyType = propNameType.flags & (TypeFlags.Any | TypeFlags.String) ? stringType : propNameType.flags & (TypeFlags.Number | TypeFlags.Enum) ? numberType : propNameType;
        const propType = instantiateType(templateType, appendTypeMapping(type.mapper, typeParameter, keyType));
        const modifiersIndexInfo = getApplicableIndexInfo(modifiersType, propNameType);
        const isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersIndexInfo?.isReadonly);
        const indexInfo = createIndexInfo(indexKeyType, propType, isReadonly);
        indexInfos = appendIndexInfo(
          indexInfos,
          indexInfo,
          /*union*/
          true
        );
      }
    }
  }
  function getTypeOfMappedSymbol(symbol) {
    if (!symbol.links.type) {
      const mappedType = symbol.links.mappedType;
      if (!pushTypeResolution(symbol, 0 /* Type */)) {
        mappedType.containsError = true;
        return errorType;
      }
      const templateType = getTemplateTypeFromMappedType(mappedType.target || mappedType);
      const mapper = appendTypeMapping(mappedType.mapper, getTypeParameterFromMappedType(mappedType), symbol.links.keyType);
      const propType = instantiateType(templateType, mapper);
      let type = strictNullChecks && symbol.flags & SymbolFlags.Optional && !maybeTypeOfKind(propType, TypeFlags.Undefined | TypeFlags.Void) ? getOptionalType(
        propType,
        /*isProperty*/
        true
      ) : symbol.links.checkFlags & CheckFlags.StripOptional ? removeMissingOrUndefinedType(propType) : propType;
      if (!popTypeResolution()) {
        error(currentNode, Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType));
        type = errorType;
      }
      symbol.links.type ??= type;
    }
    return symbol.links.type;
  }
  function getTypeParameterFromMappedType(type) {
    return type.typeParameter || (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(type.declaration.typeParameter)));
  }
  function getConstraintTypeFromMappedType(type) {
    return type.constraintType || (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
  }
  function getNameTypeFromMappedType(type) {
    return type.declaration.nameType ? type.nameType || (type.nameType = instantiateType(getTypeFromTypeNode(type.declaration.nameType), type.mapper)) : void 0;
  }
  function getTemplateTypeFromMappedType(type) {
    return type.templateType || (type.templateType = type.declaration.type ? instantiateType(addOptionality(
      getTypeFromTypeNode(type.declaration.type),
      /*isProperty*/
      true,
      !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)
    ), type.mapper) : errorType);
  }
  function getConstraintDeclarationForMappedType(type) {
    return getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
  }
  function isMappedTypeWithKeyofConstraintDeclaration(type) {
    const constraintDeclaration = getConstraintDeclarationForMappedType(type);
    return constraintDeclaration.kind === SyntaxKind.TypeOperator && constraintDeclaration.operator === SyntaxKind.KeyOfKeyword;
  }
  function getModifiersTypeFromMappedType(type) {
    if (!type.modifiersType) {
      if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
        type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
      } else {
        const declaredType = getTypeFromMappedTypeNode(type.declaration);
        const constraint = getConstraintTypeFromMappedType(declaredType);
        const extendedConstraint = constraint && constraint.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(constraint) : constraint;
        type.modifiersType = extendedConstraint && extendedConstraint.flags & TypeFlags.Index ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
      }
    }
    return type.modifiersType;
  }
  function getMappedTypeModifiers(type) {
    const declaration = type.declaration;
    return (declaration.readonlyToken ? declaration.readonlyToken.kind === SyntaxKind.MinusToken ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | (declaration.questionToken ? declaration.questionToken.kind === SyntaxKind.MinusToken ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
  }
  function getMappedTypeOptionality(type) {
    const modifiers = getMappedTypeModifiers(type);
    return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
  }
  function getCombinedMappedTypeOptionality(type) {
    if (getObjectFlags(type) & ObjectFlags.Mapped) {
      return getMappedTypeOptionality(type) || getCombinedMappedTypeOptionality(getModifiersTypeFromMappedType(type));
    }
    if (type.flags & TypeFlags.Intersection) {
      const optionality = getCombinedMappedTypeOptionality(type.types[0]);
      return every(type.types, (t, i) => i === 0 || getCombinedMappedTypeOptionality(t) === optionality) ? optionality : 0;
    }
    return 0;
  }
  function isPartialMappedType(type) {
    return !!(getObjectFlags(type) & ObjectFlags.Mapped && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
  }
  function isGenericMappedType(type) {
    if (getObjectFlags(type) & ObjectFlags.Mapped) {
      const constraint = getConstraintTypeFromMappedType(type);
      if (isGenericIndexType(constraint)) {
        return true;
      }
      const nameType = getNameTypeFromMappedType(type);
      if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type), constraint)))) {
        return true;
      }
    }
    return false;
  }
  function getMappedTypeNameTypeKind(type) {
    const nameType = getNameTypeFromMappedType(type);
    if (!nameType) {
      return 0 /* None */;
    }
    return isTypeAssignableTo(nameType, getTypeParameterFromMappedType(type)) ? 1 /* Filtering */ : 2 /* Remapping */;
  }
  function resolveStructuredTypeMembers(type) {
    if (!type.members) {
      if (type.flags & TypeFlags.Object) {
        if (type.objectFlags & ObjectFlags.Reference) {
          resolveTypeReferenceMembers(type);
        } else if (type.objectFlags & ObjectFlags.ClassOrInterface) {
          resolveClassOrInterfaceMembers(type);
        } else if (type.objectFlags & ObjectFlags.ReverseMapped) {
          resolveReverseMappedTypeMembers(type);
        } else if (type.objectFlags & ObjectFlags.Anonymous) {
          resolveAnonymousTypeMembers(type);
        } else if (type.objectFlags & ObjectFlags.Mapped) {
          resolveMappedTypeMembers(type);
        } else {
          Debug.fail("Unhandled object type " + Debug.formatObjectFlags(type.objectFlags));
        }
      } else if (type.flags & TypeFlags.Union) {
        resolveUnionTypeMembers(type);
      } else if (type.flags & TypeFlags.Intersection) {
        resolveIntersectionTypeMembers(type);
      } else {
        Debug.fail("Unhandled type " + Debug.formatTypeFlags(type.flags));
      }
    }
    return type;
  }
  function getPropertiesOfObjectType(type) {
    if (type.flags & TypeFlags.Object) {
      return resolveStructuredTypeMembers(type).properties;
    }
    return emptyArray;
  }
  function getPropertyOfObjectType(type, name) {
    if (type.flags & TypeFlags.Object) {
      const resolved = resolveStructuredTypeMembers(type);
      const symbol = resolved.members.get(name);
      if (symbol && symbolIsValue(symbol)) {
        return symbol;
      }
    }
  }
  function getPropertiesOfUnionOrIntersectionType(type) {
    if (!type.resolvedProperties) {
      const members = createSymbolTable();
      for (const current of type.types) {
        for (const prop of getPropertiesOfType(current)) {
          if (!members.has(prop.escapedName)) {
            const combinedProp = getPropertyOfUnionOrIntersectionType(
              type,
              prop.escapedName,
              /*skipObjectFunctionPropertyAugment*/
              !!(type.flags & TypeFlags.Intersection)
            );
            if (combinedProp) {
              members.set(prop.escapedName, combinedProp);
            }
          }
        }
        if (type.flags & TypeFlags.Union && getIndexInfosOfType(current).length === 0) {
          break;
        }
      }
      type.resolvedProperties = getNamedMembers(members);
    }
    return type.resolvedProperties;
  }
  function getPropertiesOfType(type) {
    type = getReducedApparentType(type);
    return type.flags & TypeFlags.UnionOrIntersection ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type);
  }
  function forEachPropertyOfType(type, action) {
    type = getReducedApparentType(type);
    if (type.flags & TypeFlags.StructuredType) {
      resolveStructuredTypeMembers(type).members.forEach((symbol, escapedName) => {
        if (isNamedMember(symbol, escapedName)) {
          action(symbol, escapedName);
        }
      });
    }
  }
  function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
    const list = obj.properties;
    return list.some((property) => {
      const nameType = property.name && (isJsxNamespacedName(property.name) ? getStringLiteralType(getTextOfJsxAttributeName(property.name)) : getLiteralTypeFromPropertyName(property.name));
      const name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : void 0;
      const expected = name === void 0 ? void 0 : getTypeOfPropertyOfType(contextualType, name);
      return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
    });
  }
  function getAllPossiblePropertiesOfTypes(types) {
    const unionType = getUnionType(types);
    if (!(unionType.flags & TypeFlags.Union)) {
      return getAugmentedPropertiesOfType(unionType);
    }
    const props = createSymbolTable();
    for (const memberType of types) {
      for (const { escapedName } of getAugmentedPropertiesOfType(memberType)) {
        if (!props.has(escapedName)) {
          const prop = createUnionOrIntersectionProperty(unionType, escapedName);
          if (prop) props.set(escapedName, prop);
        }
      }
    }
    return arrayFrom(props.values());
  }
  function getConstraintOfType(type) {
    return type.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(type) : type.flags & TypeFlags.IndexedAccess ? getConstraintOfIndexedAccess(type) : type.flags & TypeFlags.Conditional ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type);
  }
  function getConstraintOfTypeParameter(typeParameter) {
    return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : void 0;
  }
  function isConstMappedType(type, depth) {
    const typeVariable = getHomomorphicTypeVariable(type);
    return !!typeVariable && isConstTypeVariable(typeVariable, depth);
  }
  function isConstTypeVariable(type, depth = 0) {
    return depth < 5 && !!(type && (type.flags & TypeFlags.TypeParameter && some(type.symbol?.declarations, (d) => hasSyntacticModifier(d, ModifierFlags.Const)) || type.flags & TypeFlags.UnionOrIntersection && some(type.types, (t) => isConstTypeVariable(t, depth)) || type.flags & TypeFlags.IndexedAccess && isConstTypeVariable(type.objectType, depth + 1) || type.flags & TypeFlags.Conditional && isConstTypeVariable(getConstraintOfConditionalType(type), depth + 1) || type.flags & TypeFlags.Substitution && isConstTypeVariable(type.baseType, depth) || getObjectFlags(type) & ObjectFlags.Mapped && isConstMappedType(type, depth) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & ElementFlags.Variadic) && isConstTypeVariable(t, depth)) >= 0));
  }
  function getConstraintOfIndexedAccess(type) {
    return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : void 0;
  }
  function getSimplifiedTypeOrConstraint(type) {
    const simplified = getSimplifiedType(
      type,
      /*writing*/
      false
    );
    return simplified !== type ? simplified : getConstraintOfType(type);
  }
  function getConstraintFromIndexedAccess(type) {
    if (isMappedTypeGenericIndexedAccess(type)) {
      return substituteIndexedMappedType(type.objectType, type.indexType);
    }
    const indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
    if (indexConstraint && indexConstraint !== type.indexType) {
      const indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.accessFlags);
      if (indexedAccess) {
        return indexedAccess;
      }
    }
    const objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
    if (objectConstraint && objectConstraint !== type.objectType) {
      return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType, type.accessFlags);
    }
    return void 0;
  }
  function getDefaultConstraintOfConditionalType(type) {
    if (!type.resolvedDefaultConstraint) {
      const trueConstraint = getInferredTrueTypeFromConditionalType(type);
      const falseConstraint = getFalseTypeFromConditionalType(type);
      type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
    }
    return type.resolvedDefaultConstraint;
  }
  function getConstraintOfDistributiveConditionalType(type) {
    if (type.resolvedConstraintOfDistributive !== void 0) {
      return type.resolvedConstraintOfDistributive || void 0;
    }
    if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
      const simplified = getSimplifiedType(
        type.checkType,
        /*writing*/
        false
      );
      const constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
      if (constraint && constraint !== type.checkType) {
        const instantiated = getConditionalTypeInstantiation(
          type,
          prependTypeMapping(type.root.checkType, constraint, type.mapper),
          /*forConstraint*/
          true
        );
        if (!(instantiated.flags & TypeFlags.Never)) {
          type.resolvedConstraintOfDistributive = instantiated;
          return instantiated;
        }
      }
    }
    type.resolvedConstraintOfDistributive = false;
    return void 0;
  }
  function getConstraintFromConditionalType(type) {
    return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
  }
  function getConstraintOfConditionalType(type) {
    return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : void 0;
  }
  function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
    let constraints;
    let hasDisjointDomainType = false;
    for (const t of types) {
      if (t.flags & TypeFlags.Instantiable) {
        let constraint = getConstraintOfType(t);
        while (constraint && constraint.flags & (TypeFlags.TypeParameter | TypeFlags.Index | TypeFlags.Conditional)) {
          constraint = getConstraintOfType(constraint);
        }
        if (constraint) {
          constraints = append(constraints, constraint);
          if (targetIsUnion) {
            constraints = append(constraints, t);
          }
        }
      } else if (t.flags & TypeFlags.DisjointDomains || isEmptyAnonymousObjectType(t)) {
        hasDisjointDomainType = true;
      }
    }
    if (constraints && (targetIsUnion || hasDisjointDomainType)) {
      if (hasDisjointDomainType) {
        for (const t of types) {
          if (t.flags & TypeFlags.DisjointDomains || isEmptyAnonymousObjectType(t)) {
            constraints = append(constraints, t);
          }
        }
      }
      return getNormalizedType(
        getIntersectionType(constraints, IntersectionFlags.NoConstraintReduction),
        /*writing*/
        false
      );
    }
    return void 0;
  }
  function getBaseConstraintOfType(type) {
    if (type.flags & (TypeFlags.InstantiableNonPrimitive | TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) || isGenericTupleType(type)) {
      const constraint = getResolvedBaseConstraint(type);
      return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : void 0;
    }
    return type.flags & TypeFlags.Index ? stringNumberSymbolType : void 0;
  }
  function getBaseConstraintOrType(type) {
    return getBaseConstraintOfType(type) || type;
  }
  function hasNonCircularBaseConstraint(type) {
    return getResolvedBaseConstraint(type) !== circularConstraintType;
  }
  function getResolvedBaseConstraint(type) {
    if (type.resolvedBaseConstraint) {
      return type.resolvedBaseConstraint;
    }
    const stack = [];
    return type.resolvedBaseConstraint = getImmediateBaseConstraint(type);
    function getImmediateBaseConstraint(t) {
      if (!t.immediateBaseConstraint) {
        if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
          return circularConstraintType;
        }
        let result;
        const identity = getRecursionIdentity(t);
        if (stack.length < 10 || stack.length < 50 && !contains(stack, identity)) {
          stack.push(identity);
          result = computeBaseConstraint(getSimplifiedType(
            t,
            /*writing*/
            false
          ));
          stack.pop();
        }
        if (!popTypeResolution()) {
          if (t.flags & TypeFlags.TypeParameter) {
            const errorNode = getConstraintDeclaration(t);
            if (errorNode) {
              const diagnostic = error(errorNode, Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
              if (currentNode && !isNodeDescendantOf(errorNode, currentNode) && !isNodeDescendantOf(currentNode, errorNode)) {
                addRelatedInfo(diagnostic, createDiagnosticForNode(currentNode, Diagnostics.Circularity_originates_in_type_at_this_location));
              }
            }
          }
          result = circularConstraintType;
        }
        t.immediateBaseConstraint ??= result || noConstraintType;
      }
      return t.immediateBaseConstraint;
    }
    function getBaseConstraint(t) {
      const c = getImmediateBaseConstraint(t);
      return c !== noConstraintType && c !== circularConstraintType ? c : void 0;
    }
    function computeBaseConstraint(t) {
      if (t.flags & TypeFlags.TypeParameter) {
        const constraint = getConstraintFromTypeParameter(t);
        return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint);
      }
      if (t.flags & TypeFlags.UnionOrIntersection) {
        const types = t.types;
        const baseTypes = [];
        let different = false;
        for (const type2 of types) {
          const baseType = getBaseConstraint(type2);
          if (baseType) {
            if (baseType !== type2) {
              different = true;
            }
            baseTypes.push(baseType);
          } else {
            different = true;
          }
        }
        if (!different) {
          return t;
        }
        return t.flags & TypeFlags.Union && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & TypeFlags.Intersection && baseTypes.length ? getIntersectionType(baseTypes) : void 0;
      }
      if (t.flags & TypeFlags.Index) {
        return stringNumberSymbolType;
      }
      if (t.flags & TypeFlags.TemplateLiteral) {
        const types = t.types;
        const constraints = mapDefined(types, getBaseConstraint);
        return constraints.length === types.length ? getTemplateLiteralType(t.texts, constraints) : stringType;
      }
      if (t.flags & TypeFlags.StringMapping) {
        const constraint = getBaseConstraint(t.type);
        return constraint && constraint !== t.type ? getStringMappingType(t.symbol, constraint) : stringType;
      }
      if (t.flags & TypeFlags.IndexedAccess) {
        if (isMappedTypeGenericIndexedAccess(t)) {
          return getBaseConstraint(substituteIndexedMappedType(t.objectType, t.indexType));
        }
        const baseObjectType = getBaseConstraint(t.objectType);
        const baseIndexType = getBaseConstraint(t.indexType);
        const baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, t.accessFlags);
        return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
      }
      if (t.flags & TypeFlags.Conditional) {
        const constraint = getConstraintFromConditionalType(t);
        return constraint && getBaseConstraint(constraint);
      }
      if (t.flags & TypeFlags.Substitution) {
        return getBaseConstraint(getSubstitutionIntersection(t));
      }
      if (isGenericTupleType(t)) {
        const newElements = map(getElementTypes(t), (v, i) => {
          const constraint = v.flags & TypeFlags.TypeParameter && t.target.elementFlags[i] & ElementFlags.Variadic && getBaseConstraint(v) || v;
          return constraint !== v && everyType(constraint, (c) => isArrayOrTupleType(c) && !isGenericTupleType(c)) ? constraint : v;
        });
        return createTupleType(newElements, t.target.elementFlags, t.target.readonly, t.target.labeledElementDeclarations);
      }
      return t;
    }
  }
  function getApparentTypeOfIntersectionType(type, thisArgument) {
    if (type === thisArgument) {
      return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(
        type,
        thisArgument,
        /*needApparentType*/
        true
      ));
    }
    const key = `I${getTypeId(type)},${getTypeId(thisArgument)}`;
    return getCachedType(key) ?? setCachedType(key, getTypeWithThisArgument(
      type,
      thisArgument,
      /*needApparentType*/
      true
    ));
  }
  function getResolvedTypeParameterDefault(typeParameter) {
    if (!typeParameter.default) {
      if (typeParameter.target) {
        const targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
        typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
      } else {
        typeParameter.default = resolvingDefaultType;
        const defaultDeclaration = typeParameter.symbol && forEach(typeParameter.symbol.declarations, (decl) => isTypeParameterDeclaration(decl) && decl.default);
        const defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
        if (typeParameter.default === resolvingDefaultType) {
          typeParameter.default = defaultType;
        }
      }
    } else if (typeParameter.default === resolvingDefaultType) {
      typeParameter.default = circularConstraintType;
    }
    return typeParameter.default;
  }
  function getDefaultFromTypeParameter(typeParameter) {
    const defaultType = getResolvedTypeParameterDefault(typeParameter);
    return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : void 0;
  }
  function hasNonCircularTypeParameterDefault(typeParameter) {
    return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
  }
  function hasTypeParameterDefault(typeParameter) {
    return !!(typeParameter.symbol && forEach(typeParameter.symbol.declarations, (decl) => isTypeParameterDeclaration(decl) && decl.default));
  }
  function getApparentTypeOfMappedType(type) {
    return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
  }
  function getResolvedApparentTypeOfMappedType(type) {
    const target = type.target ?? type;
    const typeVariable = getHomomorphicTypeVariable(target);
    if (typeVariable && !target.declaration.nameType) {
      const modifiersType = getModifiersTypeFromMappedType(type);
      const baseConstraint = isGenericMappedType(modifiersType) ? getApparentTypeOfMappedType(modifiersType) : getBaseConstraintOfType(modifiersType);
      if (baseConstraint && everyType(baseConstraint, (t) => isArrayOrTupleType(t) || isArrayOrTupleOrIntersection(t))) {
        return instantiateType(target, prependTypeMapping(typeVariable, baseConstraint, type.mapper));
      }
    }
    return type;
  }
  function isArrayOrTupleOrIntersection(type) {
    return !!(type.flags & TypeFlags.Intersection) && every(type.types, isArrayOrTupleType);
  }
  function isMappedTypeGenericIndexedAccess(type) {
    let objectType;
    return !!(type.flags & TypeFlags.IndexedAccess && getObjectFlags(objectType = type.objectType) & ObjectFlags.Mapped && !isGenericMappedType(objectType) && isGenericIndexType(type.indexType) && !(getMappedTypeModifiers(objectType) & 8 /* ExcludeOptional */) && !objectType.declaration.nameType);
  }
  function getApparentType(type) {
    const t = type.flags & TypeFlags.Instantiable ? getBaseConstraintOfType(type) || unknownType : type;
    const objectFlags = getObjectFlags(t);
    return objectFlags & ObjectFlags.Mapped ? getApparentTypeOfMappedType(t) : objectFlags & ObjectFlags.Reference && t !== type ? getTypeWithThisArgument(t, type) : t.flags & TypeFlags.Intersection ? getApparentTypeOfIntersectionType(t, type) : t.flags & TypeFlags.StringLike ? globalStringType : t.flags & TypeFlags.NumberLike ? globalNumberType : t.flags & TypeFlags.BigIntLike ? getGlobalBigIntType() : t.flags & TypeFlags.BooleanLike ? globalBooleanType : t.flags & TypeFlags.ESSymbolLike ? getGlobalESSymbolType() : t.flags & TypeFlags.NonPrimitive ? emptyObjectType : t.flags & TypeFlags.Index ? stringNumberSymbolType : t.flags & TypeFlags.Unknown && !strictNullChecks ? emptyObjectType : t;
  }
  function getReducedApparentType(type) {
    return getReducedType(getApparentType(getReducedType(type)));
  }
  function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) {
    let singleProp;
    let propSet;
    let indexTypes;
    const isUnion = containingType.flags & TypeFlags.Union;
    let optionalFlag;
    let syntheticFlag = CheckFlags.SyntheticMethod;
    let checkFlags = isUnion ? 0 : CheckFlags.Readonly;
    let mergedInstantiations = false;
    for (const current of containingType.types) {
      const type = getApparentType(current);
      if (!(isErrorType(type) || type.flags & TypeFlags.Never)) {
        const prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment);
        const modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0;
        if (prop) {
          if (prop.flags & SymbolFlags.ClassMember) {
            optionalFlag ??= isUnion ? SymbolFlags.None : SymbolFlags.Optional;
            if (isUnion) {
              optionalFlag |= prop.flags & SymbolFlags.Optional;
            } else {
              optionalFlag &= prop.flags;
            }
          }
          if (!singleProp) {
            singleProp = prop;
          } else if (prop !== singleProp) {
            const isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp);
            if (isInstantiation && compareProperties(singleProp, prop, (a, b) => a === b ? Ternary.True : Ternary.False) === Ternary.True) {
              mergedInstantiations = !!singleProp.parent && !!length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent));
            } else {
              if (!propSet) {
                propSet = /* @__PURE__ */ new Map();
                propSet.set(getSymbolId(singleProp), singleProp);
              }
              const id = getSymbolId(prop);
              if (!propSet.has(id)) {
                propSet.set(id, prop);
              }
            }
          }
          if (isUnion && isReadonlySymbol(prop)) {
            checkFlags |= CheckFlags.Readonly;
          } else if (!isUnion && !isReadonlySymbol(prop)) {
            checkFlags &= ~CheckFlags.Readonly;
          }
          checkFlags |= (!(modifiers & ModifierFlags.NonPublicAccessibilityModifier) ? CheckFlags.ContainsPublic : 0) | (modifiers & ModifierFlags.Protected ? CheckFlags.ContainsProtected : 0) | (modifiers & ModifierFlags.Private ? CheckFlags.ContainsPrivate : 0) | (modifiers & ModifierFlags.Static ? CheckFlags.ContainsStatic : 0);
          if (!isPrototypeProperty(prop)) {
            syntheticFlag = CheckFlags.SyntheticProperty;
          }
        } else if (isUnion) {
          const indexInfo = !isLateBoundName(name) && getApplicableIndexInfoForName(type, name);
          if (indexInfo) {
            checkFlags |= CheckFlags.WritePartial | (indexInfo.isReadonly ? CheckFlags.Readonly : 0);
            indexTypes = append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
          } else if (isObjectLiteralType(type) && !(getObjectFlags(type) & ObjectFlags.ContainsSpread)) {
            checkFlags |= CheckFlags.WritePartial;
            indexTypes = append(indexTypes, undefinedType);
          } else {
            checkFlags |= CheckFlags.ReadPartial;
          }
        }
      }
    }
    if (!singleProp || isUnion && (propSet || checkFlags & CheckFlags.Partial) && checkFlags & (CheckFlags.ContainsPrivate | CheckFlags.ContainsProtected) && !(propSet && getCommonDeclarationsOfSymbols(propSet.values()))) {
      return void 0;
    }
    if (!propSet && !(checkFlags & CheckFlags.ReadPartial) && !indexTypes) {
      if (mergedInstantiations) {
        const links = tryCast(singleProp, isTransientSymbol)?.links;
        const clone = createSymbolWithType(singleProp, links?.type);
        clone.parent = singleProp.valueDeclaration?.symbol?.parent;
        clone.links.containingType = containingType;
        clone.links.mapper = links?.mapper;
        clone.links.writeType = getWriteTypeOfSymbol(singleProp);
        return clone;
      } else {
        return singleProp;
      }
    }
    const props = propSet ? arrayFrom(propSet.values()) : [singleProp];
    let declarations;
    let firstType;
    let nameType;
    const propTypes = [];
    let writeTypes;
    let firstValueDeclaration;
    let hasNonUniformValueDeclaration = false;
    for (const prop of props) {
      if (!firstValueDeclaration) {
        firstValueDeclaration = prop.valueDeclaration;
      } else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
        hasNonUniformValueDeclaration = true;
      }
      declarations = addRange(declarations, prop.declarations);
      const type = getTypeOfSymbol(prop);
      if (!firstType) {
        firstType = type;
        nameType = getSymbolLinks(prop).nameType;
      }
      const writeType = getWriteTypeOfSymbol(prop);
      if (writeTypes || writeType !== type) {
        writeTypes = append(!writeTypes ? propTypes.slice() : writeTypes, writeType);
      }
      if (type !== firstType) {
        checkFlags |= CheckFlags.HasNonUniformType;
      }
      if (isLiteralType(type) || isPatternLiteralType(type)) {
        checkFlags |= CheckFlags.HasLiteralType;
      }
      if (type.flags & TypeFlags.Never && type !== uniqueLiteralType) {
        checkFlags |= CheckFlags.HasNeverType;
      }
      propTypes.push(type);
    }
    addRange(propTypes, indexTypes);
    const result = createSymbol(SymbolFlags.Property | (optionalFlag ?? 0), name, syntheticFlag | checkFlags);
    result.links.containingType = containingType;
    if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
      result.valueDeclaration = firstValueDeclaration;
      if (firstValueDeclaration.symbol.parent) {
        result.parent = firstValueDeclaration.symbol.parent;
      }
    }
    result.declarations = declarations;
    result.links.nameType = nameType;
    if (propTypes.length > 2) {
      result.links.checkFlags |= CheckFlags.DeferredType;
      result.links.deferralParent = containingType;
      result.links.deferralConstituents = propTypes;
      result.links.deferralWriteConstituents = writeTypes;
    } else {
      result.links.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
      if (writeTypes) {
        result.links.writeType = isUnion ? getUnionType(writeTypes) : getIntersectionType(writeTypes);
      }
    }
    return result;
  }
  function getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment) {
    let property = skipObjectFunctionPropertyAugment ? type.propertyCacheWithoutObjectFunctionPropertyAugment?.get(name) : type.propertyCache?.get(name);
    if (!property) {
      property = createUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
      if (property) {
        const properties = skipObjectFunctionPropertyAugment ? type.propertyCacheWithoutObjectFunctionPropertyAugment ||= createSymbolTable() : type.propertyCache ||= createSymbolTable();
        properties.set(name, property);
        if (skipObjectFunctionPropertyAugment && !(getCheckFlags(property) & CheckFlags.Partial) && !type.propertyCache?.get(name)) {
          const properties2 = type.propertyCache ||= createSymbolTable();
          properties2.set(name, property);
        }
      }
    }
    return property;
  }
  function getCommonDeclarationsOfSymbols(symbols) {
    let commonDeclarations;
    for (const symbol of symbols) {
      if (!symbol.declarations) {
        return void 0;
      }
      if (!commonDeclarations) {
        commonDeclarations = new Set(symbol.declarations);
        continue;
      }
      commonDeclarations.forEach((declaration) => {
        if (!contains(symbol.declarations, declaration)) {
          commonDeclarations.delete(declaration);
        }
      });
      if (commonDeclarations.size === 0) {
        return void 0;
      }
    }
    return commonDeclarations;
  }
  function getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment) {
    const property = getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
    return property && !(getCheckFlags(property) & CheckFlags.ReadPartial) ? property : void 0;
  }
  function getReducedType(type) {
    if (type.flags & TypeFlags.Union && type.objectFlags & ObjectFlags.ContainsIntersections) {
      return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
    } else if (type.flags & TypeFlags.Intersection) {
      if (!(type.objectFlags & ObjectFlags.IsNeverIntersectionComputed)) {
        type.objectFlags |= ObjectFlags.IsNeverIntersectionComputed | (some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? ObjectFlags.IsNeverIntersection : 0);
      }
      return type.objectFlags & ObjectFlags.IsNeverIntersection ? neverType : type;
    }
    return type;
  }
  function getReducedUnionType(unionType) {
    const reducedTypes = sameMap(unionType.types, getReducedType);
    if (reducedTypes === unionType.types) {
      return unionType;
    }
    const reduced = getUnionType(reducedTypes);
    if (reduced.flags & TypeFlags.Union) {
      reduced.resolvedReducedType = reduced;
    }
    return reduced;
  }
  function isNeverReducedProperty(prop) {
    return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
  }
  function isDiscriminantWithNeverType(prop) {
    return !(prop.flags & SymbolFlags.Optional) && (getCheckFlags(prop) & (CheckFlags.Discriminant | CheckFlags.HasNeverType)) === CheckFlags.Discriminant && !!(getTypeOfSymbol(prop).flags & TypeFlags.Never);
  }
  function isConflictingPrivateProperty(prop) {
    return !prop.valueDeclaration && !!(getCheckFlags(prop) & CheckFlags.ContainsPrivate);
  }
  function isGenericReducibleType(type) {
    return !!(type.flags & TypeFlags.Union && type.objectFlags & ObjectFlags.ContainsIntersections && some(type.types, isGenericReducibleType) || type.flags & TypeFlags.Intersection && isReducibleIntersection(type));
  }
  function isReducibleIntersection(type) {
    const uniqueFilled = type.uniqueLiteralFilledInstantiation || (type.uniqueLiteralFilledInstantiation = instantiateType(type, uniqueLiteralMapper));
    return getReducedType(uniqueFilled) !== uniqueFilled;
  }
  function elaborateNeverIntersection(errorInfo, type) {
    if (type.flags & TypeFlags.Intersection && getObjectFlags(type) & ObjectFlags.IsNeverIntersection) {
      const neverProp = find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
      if (neverProp) {
        return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(
          type,
          /*enclosingDeclaration*/
          void 0,
          TypeFormatFlags.NoTypeReduction
        ), symbolToString(neverProp));
      }
      const privateProp = find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
      if (privateProp) {
        return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(
          type,
          /*enclosingDeclaration*/
          void 0,
          TypeFormatFlags.NoTypeReduction
        ), symbolToString(privateProp));
      }
    }
    return errorInfo;
  }
  function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment, includeTypeOnlyMembers) {
    type = getReducedApparentType(type);
    if (type.flags & TypeFlags.Object) {
      const resolved = resolveStructuredTypeMembers(type);
      const symbol = resolved.members.get(name);
      if (symbol && !includeTypeOnlyMembers && type.symbol?.flags & SymbolFlags.ValueModule && getSymbolLinks(type.symbol).typeOnlyExportStarMap?.has(name)) {
        return void 0;
      }
      if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) {
        return symbol;
      }
      if (skipObjectFunctionPropertyAugment) return void 0;
      const functionType = resolved === anyFunctionType ? globalFunctionType : resolved.callSignatures.length ? globalCallableFunctionType : resolved.constructSignatures.length ? globalNewableFunctionType : void 0;
      if (functionType) {
        const symbol2 = getPropertyOfObjectType(functionType, name);
        if (symbol2) {
          return symbol2;
        }
      }
      return getPropertyOfObjectType(globalObjectType, name);
    }
    if (type.flags & TypeFlags.Intersection) {
      const prop = getPropertyOfUnionOrIntersectionType(
        type,
        name,
        /*skipObjectFunctionPropertyAugment*/
        true
      );
      if (prop) {
        return prop;
      }
      if (!skipObjectFunctionPropertyAugment) {
        return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment);
      }
      return void 0;
    }
    if (type.flags & TypeFlags.Union) {
      return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment);
    }
    return void 0;
  }
  function getSignaturesOfStructuredType(type, kind) {
    if (type.flags & TypeFlags.StructuredType) {
      const resolved = resolveStructuredTypeMembers(type);
      return kind === SignatureKind.Call ? resolved.callSignatures : resolved.constructSignatures;
    }
    return emptyArray;
  }
  function getSignaturesOfType(type, kind) {
    const result = getSignaturesOfStructuredType(getReducedApparentType(type), kind);
    if (kind === SignatureKind.Call && !length(result) && type.flags & TypeFlags.Union) {
      if (type.arrayFallbackSignatures) {
        return type.arrayFallbackSignatures;
      }
      let memberName;
      if (everyType(type, (t) => !!t.symbol?.parent && isArrayOrTupleSymbol(t.symbol.parent) && (!memberName ? (memberName = t.symbol.escapedName, true) : memberName === t.symbol.escapedName))) {
        const arrayArg = mapType(type, (t) => getMappedType((isReadonlyArraySymbol(t.symbol.parent) ? globalReadonlyArrayType : globalArrayType).typeParameters[0], t.mapper));
        const arrayType = createArrayType(arrayArg, someType(type, (t) => isReadonlyArraySymbol(t.symbol.parent)));
        return type.arrayFallbackSignatures = getSignaturesOfType(getTypeOfPropertyOfType(arrayType, memberName), kind);
      }
      type.arrayFallbackSignatures = result;
    }
    return result;
  }
  function isArrayOrTupleSymbol(symbol) {
    if (!symbol || !globalArrayType.symbol || !globalReadonlyArrayType.symbol) {
      return false;
    }
    return !!getSymbolIfSameReference(symbol, globalArrayType.symbol) || !!getSymbolIfSameReference(symbol, globalReadonlyArrayType.symbol);
  }
  function isReadonlyArraySymbol(symbol) {
    if (!symbol || !globalReadonlyArrayType.symbol) {
      return false;
    }
    return !!getSymbolIfSameReference(symbol, globalReadonlyArrayType.symbol);
  }
  function findIndexInfo(indexInfos, keyType) {
    return find(indexInfos, (info) => info.keyType === keyType);
  }
  function findApplicableIndexInfo(indexInfos, keyType) {
    let stringIndexInfo;
    let applicableInfo;
    let applicableInfos;
    for (const info of indexInfos) {
      if (info.keyType === stringType) {
        stringIndexInfo = info;
      } else if (isApplicableIndexType(keyType, info.keyType)) {
        if (!applicableInfo) {
          applicableInfo = info;
        } else {
          (applicableInfos || (applicableInfos = [applicableInfo])).push(info);
        }
      }
    }
    return applicableInfos ? createIndexInfo(unknownType, getIntersectionType(map(applicableInfos, (info) => info.type)), reduceLeft(
      applicableInfos,
      (isReadonly, info) => isReadonly && info.isReadonly,
      /*initial*/
      true
    )) : applicableInfo ? applicableInfo : stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo : void 0;
  }
  function isApplicableIndexType(source, target) {
    return isTypeAssignableTo(source, target) || target === stringType && isTypeAssignableTo(source, numberType) || target === numberType && (source === numericStringType || !!(source.flags & TypeFlags.StringLiteral) && isNumericLiteralName(source.value));
  }
  function getIndexInfosOfStructuredType(type) {
    if (type.flags & TypeFlags.StructuredType) {
      const resolved = resolveStructuredTypeMembers(type);
      return resolved.indexInfos;
    }
    return emptyArray;
  }
  function getIndexInfosOfType(type) {
    return getIndexInfosOfStructuredType(getReducedApparentType(type));
  }
  function getIndexInfoOfType(type, keyType) {
    return findIndexInfo(getIndexInfosOfType(type), keyType);
  }
  function getIndexTypeOfType(type, keyType) {
    return getIndexInfoOfType(type, keyType)?.type;
  }
  function getApplicableIndexInfos(type, keyType) {
    return getIndexInfosOfType(type).filter((info) => isApplicableIndexType(keyType, info.keyType));
  }
  function getApplicableIndexInfo(type, keyType) {
    return findApplicableIndexInfo(getIndexInfosOfType(type), keyType);
  }
  function getApplicableIndexInfoForName(type, name) {
    return getApplicableIndexInfo(type, isLateBoundName(name) ? esSymbolType : getStringLiteralType(unescapeLeadingUnderscores(name)));
  }
  function getTypeParametersFromDeclaration(declaration) {
    let result;
    for (const node of getEffectiveTypeParameterDeclarations(declaration)) {
      result = appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
    }
    return result?.length ? result : isFunctionDeclaration(declaration) ? getSignatureOfTypeTag(declaration)?.typeParameters : void 0;
  }
  function symbolsToArray(symbols) {
    const result = [];
    symbols.forEach((symbol, id) => {
      if (!isReservedMemberName(id)) {
        result.push(symbol);
      }
    });
    return result;
  }
  function tryFindAmbientModule(moduleName, withAugmentations) {
    if (isExternalModuleNameRelative(moduleName)) {
      return void 0;
    }
    const symbol = getSymbol(globals, '"' + moduleName + '"', SymbolFlags.ValueModule);
    return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
  }
  function hasEffectiveQuestionToken(node) {
    return hasQuestionToken(node) || isOptionalJSDocPropertyLikeTag(node) || isParameter(node) && isJSDocOptionalParameter(node);
  }
  function isOptionalParameter(node) {
    if (hasEffectiveQuestionToken(node)) {
      return true;
    }
    if (!isParameter(node)) {
      return false;
    }
    if (node.initializer) {
      const signature = getSignatureFromDeclaration(node.parent);
      const parameterIndex = node.parent.parameters.indexOf(node);
      Debug.assert(parameterIndex >= 0);
      return parameterIndex >= getMinArgumentCount(signature, 1 /* StrongArityForUntypedJS */ | 2 /* VoidIsNonOptional */);
    }
    const iife = getImmediatelyInvokedFunctionExpression(node.parent);
    if (iife) {
      return !node.type && !node.dotDotDotToken && node.parent.parameters.indexOf(node) >= getEffectiveCallArguments(iife).length;
    }
    return false;
  }
  function isOptionalPropertyDeclaration(node) {
    return isPropertyDeclaration(node) && !hasAccessorModifier(node) && node.questionToken;
  }
  function createTypePredicate(kind, parameterName, parameterIndex, type) {
    return { kind, parameterName, parameterIndex, type };
  }
  function getMinTypeArgumentCount(typeParameters) {
    let minTypeArgumentCount = 0;
    if (typeParameters) {
      for (let i = 0; i < typeParameters.length; i++) {
        if (!hasTypeParameterDefault(typeParameters[i])) {
          minTypeArgumentCount = i + 1;
        }
      }
    }
    return minTypeArgumentCount;
  }
  function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
    const numTypeParameters = length(typeParameters);
    if (!numTypeParameters) {
      return [];
    }
    const numTypeArguments = length(typeArguments);
    if (isJavaScriptImplicitAny || numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters) {
      const result = typeArguments ? typeArguments.slice() : [];
      for (let i = numTypeArguments; i < numTypeParameters; i++) {
        result[i] = errorType;
      }
      const baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
      for (let i = numTypeArguments; i < numTypeParameters; i++) {
        let defaultType = getDefaultFromTypeParameter(typeParameters[i]);
        if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
          defaultType = anyType;
        }
        result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
      }
      result.length = typeParameters.length;
      return result;
    }
    return typeArguments && typeArguments.slice();
  }
  function getSignatureFromDeclaration(declaration) {
    const links = getNodeLinks(declaration);
    if (!links.resolvedSignature) {
      const parameters = [];
      let flags = SignatureFlags.None;
      let minArgumentCount = 0;
      let thisParameter;
      let thisTag = isInJSFile(declaration) ? getJSDocThisTag(declaration) : void 0;
      let hasThisParameter = false;
      const iife = getImmediatelyInvokedFunctionExpression(declaration);
      const isJSConstructSignature = isJSDocConstructSignature(declaration);
      const isUntypedSignatureInJSFile = !iife && isInJSFile(declaration) && isValueSignatureDeclaration(declaration) && !hasJSDocParameterTags(declaration) && !getJSDocType(declaration);
      if (isUntypedSignatureInJSFile) {
        flags |= SignatureFlags.IsUntypedSignatureInJSFile;
      }
      for (let i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
        const param = declaration.parameters[i];
        if (isInJSFile(param) && isJSDocThisTag(param)) {
          thisTag = param;
          continue;
        }
        let paramSymbol = param.symbol;
        const type = isJSDocParameterTag(param) ? param.typeExpression && param.typeExpression.type : param.type;
        if (paramSymbol && !!(paramSymbol.flags & SymbolFlags.Property) && !isBindingPattern(param.name)) {
          const resolvedSymbol = resolveName(
            param,
            paramSymbol.escapedName,
            SymbolFlags.Value,
            /*nameNotFoundMessage*/
            void 0,
            /*isUse*/
            false
          );
          paramSymbol = resolvedSymbol;
        }
        if (i === 0 && paramSymbol.escapedName === InternalSymbolName.This) {
          hasThisParameter = true;
          thisParameter = param.symbol;
        } else {
          parameters.push(paramSymbol);
        }
        if (type && type.kind === SyntaxKind.LiteralType) {
          flags |= SignatureFlags.HasLiteralTypes;
        }
        const isOptionalParameter2 = hasEffectiveQuestionToken(param) || isParameter(param) && param.initializer || isRestParameter(param) || iife && parameters.length > iife.arguments.length && !type;
        if (!isOptionalParameter2) {
          minArgumentCount = parameters.length;
        }
      }
      if ((declaration.kind === SyntaxKind.GetAccessor || declaration.kind === SyntaxKind.SetAccessor) && hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) {
        const otherKind = declaration.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor;
        const other = getDeclarationOfKind(getSymbolOfDeclaration(declaration), otherKind);
        if (other) {
          thisParameter = getAnnotatedAccessorThisParameter(other);
        }
      }
      if (thisTag && thisTag.typeExpression) {
        thisParameter = createSymbolWithType(createSymbol(SymbolFlags.FunctionScopedVariable, InternalSymbolName.This), getTypeFromTypeNode(thisTag.typeExpression));
      }
      const hostDeclaration = isJSDocSignature(declaration) ? getEffectiveJSDocHost(declaration) : declaration;
      const classType = hostDeclaration && isConstructorDeclaration(hostDeclaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(hostDeclaration.parent.symbol)) : void 0;
      const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
      if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
        flags |= SignatureFlags.HasRestParameter;
      }
      if (isConstructorTypeNode(declaration) && hasSyntacticModifier(declaration, ModifierFlags.Abstract) || isConstructorDeclaration(declaration) && hasSyntacticModifier(declaration.parent, ModifierFlags.Abstract)) {
        flags |= SignatureFlags.Abstract;
      }
      links.resolvedSignature = createSignature(
        declaration,
        typeParameters,
        thisParameter,
        parameters,
        /*resolvedReturnType*/
        void 0,
        /*resolvedTypePredicate*/
        void 0,
        minArgumentCount,
        flags
      );
    }
    return links.resolvedSignature;
  }
  function maybeAddJsSyntheticRestParameter(declaration, parameters) {
    if (isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
      return false;
    }
    const lastParam = lastOrUndefined(declaration.parameters);
    const lastParamTags = lastParam ? getJSDocParameterTags(lastParam) : getJSDocTags(declaration).filter(isJSDocParameterTag);
    const lastParamVariadicType = firstDefined(lastParamTags, (p) => p.typeExpression && isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : void 0);
    const syntheticArgsSymbol = createSymbol(SymbolFlags.Variable, "args", CheckFlags.RestParameter);
    if (lastParamVariadicType) {
      syntheticArgsSymbol.links.type = createArrayType(getTypeFromTypeNode(lastParamVariadicType.type));
    } else {
      syntheticArgsSymbol.links.checkFlags |= CheckFlags.DeferredType;
      syntheticArgsSymbol.links.deferralParent = neverType;
      syntheticArgsSymbol.links.deferralConstituents = [anyArrayType];
      syntheticArgsSymbol.links.deferralWriteConstituents = [anyArrayType];
    }
    if (lastParamVariadicType) {
      parameters.pop();
    }
    parameters.push(syntheticArgsSymbol);
    return true;
  }
  function getSignatureOfTypeTag(node) {
    if (!(isInJSFile(node) && isFunctionLikeDeclaration(node))) return void 0;
    const typeTag = getJSDocTypeTag(node);
    return typeTag?.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
  }
  function getParameterTypeOfTypeTag(func, parameter) {
    const signature = getSignatureOfTypeTag(func);
    if (!signature) return void 0;
    const pos = func.parameters.indexOf(parameter);
    return parameter.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos);
  }
  function getReturnTypeOfTypeTag(node) {
    const signature = getSignatureOfTypeTag(node);
    return signature && getReturnTypeOfSignature(signature);
  }
  function containsArgumentsReference(declaration) {
    const links = getNodeLinks(declaration);
    if (links.containsArgumentsReference === void 0) {
      if (links.flags & NodeCheckFlags.CaptureArguments) {
        links.containsArgumentsReference = true;
      } else {
        links.containsArgumentsReference = traverse(declaration.body);
      }
    }
    return links.containsArgumentsReference;
    function traverse(node) {
      if (!node) return false;
      switch (node.kind) {
        case SyntaxKind.Identifier:
          return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol;
        case SyntaxKind.PropertyDeclaration:
        case SyntaxKind.MethodDeclaration:
        case SyntaxKind.GetAccessor:
        case SyntaxKind.SetAccessor:
          return node.name.kind === SyntaxKind.ComputedPropertyName && traverse(node.name);
        case SyntaxKind.PropertyAccessExpression:
        case SyntaxKind.ElementAccessExpression:
          return traverse(node.expression);
        case SyntaxKind.PropertyAssignment:
          return traverse(node.initializer);
        default:
          return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && !!forEachChild(node, traverse);
      }
    }
  }
  function getSignaturesOfSymbol(symbol) {
    if (!symbol || !symbol.declarations) return emptyArray;
    const result = [];
    for (let i = 0; i < symbol.declarations.length; i++) {
      const decl = symbol.declarations[i];
      if (!isFunctionLike(decl)) continue;
      if (i > 0 && decl.body) {
        const previous = symbol.declarations[i - 1];
        if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
          continue;
        }
      }
      if (isInJSFile(decl) && decl.jsDoc) {
        const tags = getJSDocOverloadTags(decl);
        if (length(tags)) {
          for (const tag of tags) {
            const jsDocSignature = tag.typeExpression;
            if (jsDocSignature.type === void 0 && !isConstructorDeclaration(decl)) {
              reportImplicitAny(jsDocSignature, anyType);
            }
            result.push(getSignatureFromDeclaration(jsDocSignature));
          }
          continue;
        }
      }
      result.push(
        !isFunctionExpressionOrArrowFunction(decl) && !isObjectLiteralMethod(decl) && getSignatureOfTypeTag(decl) || getSignatureFromDeclaration(decl)
      );
    }
    return result;
  }
  function resolveExternalModuleTypeByLiteral(name) {
    const moduleSym = resolveExternalModuleName(name, name);
    if (moduleSym) {
      const resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
      if (resolvedModuleSymbol) {
        return getTypeOfSymbol(resolvedModuleSymbol);
      }
    }
    return anyType;
  }
  function getThisTypeOfSignature(signature) {
    if (signature.thisParameter) {
      return getTypeOfSymbol(signature.thisParameter);
    }
  }
  function getTypePredicateOfSignature(signature) {
    if (!signature.resolvedTypePredicate) {
      if (signature.target) {
        const targetTypePredicate = getTypePredicateOfSignature(signature.target);
        signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
      } else if (signature.compositeSignatures) {
        signature.resolvedTypePredicate = getUnionOrIntersectionTypePredicate(signature.compositeSignatures, signature.compositeKind) || noTypePredicate;
      } else {
        const type = signature.declaration && getEffectiveReturnTypeNode(signature.declaration);
        let jsdocPredicate;
        if (!type) {
          const jsdocSignature = getSignatureOfTypeTag(signature.declaration);
          if (jsdocSignature && signature !== jsdocSignature) {
            jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
          }
        }
        if (type || jsdocPredicate) {
          signature.resolvedTypePredicate = type && isTypePredicateNode(type) ? createTypePredicateFromTypePredicateNode(type, signature) : jsdocPredicate || noTypePredicate;
        } else if (signature.declaration && isFunctionLikeDeclaration(signature.declaration) && (!signature.resolvedReturnType || signature.resolvedReturnType.flags & TypeFlags.Boolean) && getParameterCount(signature) > 0) {
          const { declaration } = signature;
          signature.resolvedTypePredicate = noTypePredicate;
          signature.resolvedTypePredicate = getTypePredicateFromBody(declaration) || noTypePredicate;
        } else {
          signature.resolvedTypePredicate = noTypePredicate;
        }
      }
      Debug.assert(!!signature.resolvedTypePredicate);
    }
    return signature.resolvedTypePredicate === noTypePredicate ? void 0 : signature.resolvedTypePredicate;
  }
  function createTypePredicateFromTypePredicateNode(node, signature) {
    const parameterName = node.parameterName;
    const type = node.type && getTypeFromTypeNode(node.type);
    return parameterName.kind === SyntaxKind.ThisType ? createTypePredicate(
      node.assertsModifier ? TypePredicateKind.AssertsThis : TypePredicateKind.This,
      /*parameterName*/
      void 0,
      /*parameterIndex*/
      void 0,
      type
    ) : createTypePredicate(node.assertsModifier ? TypePredicateKind.AssertsIdentifier : TypePredicateKind.Identifier, parameterName.escapedText, findIndex(signature.parameters, (p) => p.escapedName === parameterName.escapedText), type);
  }
  function getUnionOrIntersectionType(types, kind, unionReduction) {
    return kind !== TypeFlags.Intersection ? getUnionType(types, unionReduction) : getIntersectionType(types);
  }
  function getReturnTypeOfSignature(signature) {
    if (!signature.resolvedReturnType) {
      if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
        return errorType;
      }
      let type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, UnionReduction.Subtype), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration) || (nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
      if (signature.flags & SignatureFlags.IsInnerCallChain) {
        type = addOptionalTypeMarker(type);
      } else if (signature.flags & SignatureFlags.IsOuterCallChain) {
        type = getOptionalType(type);
      }
      if (!popTypeResolution()) {
        if (signature.declaration) {
          const typeNode = getEffectiveReturnTypeNode(signature.declaration);
          if (typeNode) {
            error(typeNode, Diagnostics.Return_type_annotation_circularly_references_itself);
          } else if (noImplicitAny) {
            const declaration = signature.declaration;
            const name = getNameOfDeclaration(declaration);
            if (name) {
              error(name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(name));
            } else {
              error(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions);
            }
          }
        }
        type = anyType;
      }
      signature.resolvedReturnType ??= type;
    }
    return signature.resolvedReturnType;
  }
  function getReturnTypeFromAnnotation(declaration) {
    if (declaration.kind === SyntaxKind.Constructor) {
      return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
    }
    const typeNode = getEffectiveReturnTypeNode(declaration);
    if (isJSDocSignature(declaration)) {
      const root = getJSDocRoot(declaration);
      if (root && isConstructorDeclaration(root.parent) && !typeNode) {
        return getDeclaredTypeOfClassOrInterface(getMergedSymbol(root.parent.parent.symbol));
      }
    }
    if (isJSDocConstructSignature(declaration)) {
      return getTypeFromTypeNode(declaration.parameters[0].type);
    }
    if (typeNode) {
      return getTypeFromTypeNode(typeNode);
    }
    if (declaration.kind === SyntaxKind.GetAccessor && hasBindableName(declaration)) {
      const jsDocType = isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
      if (jsDocType) {
        return jsDocType;
      }
      const setter = getDeclarationOfKind(getSymbolOfDeclaration(declaration), SyntaxKind.SetAccessor);
      const setterType = getAnnotatedAccessorType(setter);
      if (setterType) {
        return setterType;
      }
    }
    return getReturnTypeOfTypeTag(declaration);
  }
  function isResolvingReturnTypeOfSignature(signature) {
    return signature.compositeSignatures && some(signature.compositeSignatures, isResolvingReturnTypeOfSignature) || !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
  }
  function getRestTypeOfSignature(signature) {
    return tryGetRestTypeOfSignature(signature) || anyType;
  }
  function tryGetRestTypeOfSignature(signature) {
    if (signatureHasRestParameter(signature)) {
      const sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
      const restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
      return restType && getIndexTypeOfType(restType, numberType);
    }
    return void 0;
  }
  function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
    const instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
    if (inferredTypeParameters) {
      const returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
      if (returnSignature) {
        const newReturnSignature = cloneSignature(returnSignature);
        newReturnSignature.typeParameters = inferredTypeParameters;
        const newInstantiatedSignature = cloneSignature(instantiatedSignature);
        newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
        return newInstantiatedSignature;
      }
    }
    return instantiatedSignature;
  }
  function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
    const instantiations = signature.instantiations || (signature.instantiations = /* @__PURE__ */ new Map());
    const id = getTypeListId(typeArguments);
    let instantiation = instantiations.get(id);
    if (!instantiation) {
      instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
    }
    return instantiation;
  }
  function createSignatureInstantiation(signature, typeArguments) {
    return instantiateSignature(
      signature,
      createSignatureTypeMapper(signature, typeArguments),
      /*eraseTypeParameters*/
      true
    );
  }
  function getTypeParametersForMapper(signature) {
    return sameMap(signature.typeParameters, (tp) => tp.mapper ? instantiateType(tp, tp.mapper) : tp);
  }
  function createSignatureTypeMapper(signature, typeArguments) {
    return createTypeMapper(getTypeParametersForMapper(signature), typeArguments);
  }
  function getErasedSignature(signature) {
    return signature.typeParameters ? signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : signature;
  }
  function createErasedSignature(signature) {
    return instantiateSignature(
      signature,
      createTypeEraser(signature.typeParameters),
      /*eraseTypeParameters*/
      true
    );
  }
  function getCanonicalSignature(signature) {
    return signature.typeParameters ? signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : signature;
  }
  function createCanonicalSignature(signature) {
    return getSignatureInstantiation(
      signature,
      map(signature.typeParameters, (tp) => tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp),
      isInJSFile(signature.declaration)
    );
  }
  function getImplementationSignature(signature) {
    return signature.typeParameters ? signature.implementationSignatureCache ||= createImplementationSignature(signature) : signature;
  }
  function createImplementationSignature(signature) {
    return signature.typeParameters ? instantiateSignature(signature, createTypeMapper([], [])) : signature;
  }
  function getBaseSignature(signature) {
    const typeParameters = signature.typeParameters;
    if (typeParameters) {
      if (signature.baseSignatureCache) {
        return signature.baseSignatureCache;
      }
      const typeEraser = createTypeEraser(typeParameters);
      const baseConstraintMapper = createTypeMapper(typeParameters, map(typeParameters, (tp) => getConstraintOfTypeParameter(tp) || unknownType));
      let baseConstraints = map(typeParameters, (tp) => instantiateType(tp, baseConstraintMapper) || unknownType);
      for (let i = 0; i < typeParameters.length - 1; i++) {
        baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper);
      }
      baseConstraints = instantiateTypes(baseConstraints, typeEraser);
      return signature.baseSignatureCache = instantiateSignature(
        signature,
        createTypeMapper(typeParameters, baseConstraints),
        /*eraseTypeParameters*/
        true
      );
    }
    return signature;
  }
  function getOrCreateTypeFromSignature(signature, outerTypeParameters) {
    if (!signature.isolatedSignatureType) {
      const kind = signature.declaration?.kind;
      const isConstructor = kind === void 0 || kind === SyntaxKind.Constructor || kind === SyntaxKind.ConstructSignature || kind === SyntaxKind.ConstructorType;
      const type = createObjectType(ObjectFlags.Anonymous | ObjectFlags.SingleSignatureType, createSymbol(SymbolFlags.Function, InternalSymbolName.Function));
      if (signature.declaration && !nodeIsSynthesized(signature.declaration)) {
        type.symbol.declarations = [signature.declaration];
        type.symbol.valueDeclaration = signature.declaration;
      }
      outerTypeParameters ||= signature.declaration && getOuterTypeParameters(
        signature.declaration,
        /*includeThisTypes*/
        true
      );
      type.outerTypeParameters = outerTypeParameters;
      type.members = emptySymbols;
      type.properties = emptyArray;
      type.callSignatures = !isConstructor ? [signature] : emptyArray;
      type.constructSignatures = isConstructor ? [signature] : emptyArray;
      type.indexInfos = emptyArray;
      signature.isolatedSignatureType = type;
    }
    return signature.isolatedSignatureType;
  }
  function getIndexSymbol(symbol) {
    return symbol.members ? getIndexSymbolFromSymbolTable(symbol.members) : void 0;
  }
  function getIndexSymbolFromSymbolTable(symbolTable) {
    return symbolTable.get(InternalSymbolName.Index);
  }
  function createIndexInfo(keyType, type, isReadonly, declaration) {
    return { keyType, type, isReadonly, declaration };
  }
  function getIndexInfosOfSymbol(symbol) {
    const indexSymbol = getIndexSymbol(symbol);
    return indexSymbol ? getIndexInfosOfIndexSymbol(indexSymbol) : emptyArray;
  }
  function getIndexInfosOfIndexSymbol(indexSymbol) {
    if (indexSymbol.declarations) {
      const indexInfos = [];
      for (const declaration of indexSymbol.declarations) {
        if (declaration.parameters.length === 1) {
          const parameter = declaration.parameters[0];
          if (parameter.type) {
            forEachType(getTypeFromTypeNode(parameter.type), (keyType) => {
              if (isValidIndexKeyType(keyType) && !findIndexInfo(indexInfos, keyType)) {
                indexInfos.push(createIndexInfo(keyType, declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, hasEffectiveModifier(declaration, ModifierFlags.Readonly), declaration));
              }
            });
          }
        }
      }
      return indexInfos;
    }
    return emptyArray;
  }
  function isValidIndexKeyType(type) {
    return !!(type.flags & (TypeFlags.String | TypeFlags.Number | TypeFlags.ESSymbol)) || isPatternLiteralType(type) || !!(type.flags & TypeFlags.Intersection) && !isGenericType(type) && some(type.types, isValidIndexKeyType);
  }
  function getConstraintDeclaration(type) {
    return mapDefined(filter(type.symbol && type.symbol.declarations, isTypeParameterDeclaration), getEffectiveConstraintOfTypeParameter)[0];
  }
  function getInferredTypeParameterConstraint(typeParameter, omitTypeReferences) {
    let inferences;
    if (typeParameter.symbol?.declarations) {
      for (const declaration of typeParameter.symbol.declarations) {
        if (declaration.parent.kind === SyntaxKind.InferType) {
          const [childTypeParameter = declaration.parent, grandParent] = walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent);
          if (grandParent.kind === SyntaxKind.TypeReference && !omitTypeReferences) {
            const typeReference = grandParent;
            const typeParameters = getTypeParametersForTypeReferenceOrImport(typeReference);
            if (typeParameters) {
              const index = typeReference.typeArguments.indexOf(childTypeParameter);
              if (index < typeParameters.length) {
                const declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
                if (declaredConstraint) {
                  const mapper = makeDeferredTypeMapper(
                    typeParameters,
                    typeParameters.map((_, index2) => () => {
                      return getEffectiveTypeArgumentAtIndex(typeReference, typeParameters, index2);
                    })
                  );
                  const constraint = instantiateType(declaredConstraint, mapper);
                  if (constraint !== typeParameter) {
                    inferences = append(inferences, constraint);
                  }
                }
              }
            }
          } else if (grandParent.kind === SyntaxKind.Parameter && grandParent.dotDotDotToken || grandParent.kind === SyntaxKind.RestType || grandParent.kind === SyntaxKind.NamedTupleMember && grandParent.dotDotDotToken) {
            inferences = append(inferences, createArrayType(unknownType));
          } else if (grandParent.kind === SyntaxKind.TemplateLiteralTypeSpan) {
            inferences = append(inferences, stringType);
          } else if (grandParent.kind === SyntaxKind.TypeParameter && grandParent.parent.kind === SyntaxKind.MappedType) {
            inferences = append(inferences, stringNumberSymbolType);
          } else if (grandParent.kind === SyntaxKind.MappedType && grandParent.type && skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === SyntaxKind.ConditionalType && grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === SyntaxKind.MappedType && grandParent.parent.checkType.type) {
            const checkMappedType2 = grandParent.parent.checkType;
            const nodeType = getTypeFromTypeNode(checkMappedType2.type);
            inferences = append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(checkMappedType2.typeParameter)), checkMappedType2.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType2.typeParameter.constraint) : stringNumberSymbolType)));
          }
        }
      }
    }
    return inferences && getIntersectionType(inferences);
  }
  function getConstraintFromTypeParameter(typeParameter) {
    if (!typeParameter.constraint) {
      if (typeParameter.target) {
        const targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
        typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
      } else {
        const constraintDeclaration = getConstraintDeclaration(typeParameter);
        if (!constraintDeclaration) {
          typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
        } else {
          let type = getTypeFromTypeNode(constraintDeclaration);
          if (type.flags & TypeFlags.Any && !isErrorType(type)) {
            type = constraintDeclaration.parent.parent.kind === SyntaxKind.MappedType ? stringNumberSymbolType : unknownType;
          }
          typeParameter.constraint = type;
        }
      }
    }
    return typeParameter.constraint === noConstraintType ? void 0 : typeParameter.constraint;
  }
  function getParentSymbolOfTypeParameter(typeParameter) {
    const tp = getDeclarationOfKind(typeParameter.symbol, SyntaxKind.TypeParameter);
    const host2 = isJSDocTemplateTag(tp.parent) ? getEffectiveContainerForJSDocTemplateTag(tp.parent) : tp.parent;
    return host2 && getSymbolOfNode(host2);
  }
  function getTypeListId(types) {
    let result = "";
    if (types) {
      const length2 = types.length;
      let i = 0;
      while (i < length2) {
        const startId = types[i].id;
        let count = 1;
        while (i + count < length2 && types[i + count].id === startId + count) {
          count++;
        }
        if (result.length) {
          result += ",";
        }
        result += startId;
        if (count > 1) {
          result += ":" + count;
        }
        i += count;
      }
    }
    return result;
  }
  function getAliasId(aliasSymbol, aliasTypeArguments) {
    return aliasSymbol ? `@${getSymbolId(aliasSymbol)}` + (aliasTypeArguments ? `:${getTypeListId(aliasTypeArguments)}` : "") : "";
  }
  function getPropagatingFlagsOfTypes(types, excludeKinds) {
    let result = 0;
    for (const type of types) {
      if (excludeKinds === void 0 || !(type.flags & excludeKinds)) {
        result |= getObjectFlags(type);
      }
    }
    return result & ObjectFlags.PropagatingFlags;
  }
  function tryCreateTypeReference(target, typeArguments) {
    if (some(typeArguments) && target === emptyGenericType) {
      return unknownType;
    }
    return createTypeReference(target, typeArguments);
  }
  function createTypeReference(target, typeArguments) {
    const id = getTypeListId(typeArguments);
    let type = target.instantiations.get(id);
    if (!type) {
      type = createObjectType(ObjectFlags.Reference, target.symbol);
      target.instantiations.set(id, type);
      type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0;
      type.target = target;
      type.resolvedTypeArguments = typeArguments;
    }
    return type;
  }
  function cloneTypeReference(source) {
    const type = createTypeWithSymbol(source.flags, source.symbol);
    type.objectFlags = source.objectFlags;
    type.target = source.target;
    type.resolvedTypeArguments = source.resolvedTypeArguments;
    return type;
  }
  function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) {
    if (!aliasSymbol) {
      aliasSymbol = getAliasSymbolForTypeNode(node);
      const localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
      aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments;
    }
    const type = createObjectType(ObjectFlags.Reference, target.symbol);
    type.target = target;
    type.node = node;
    type.mapper = mapper;
    type.aliasSymbol = aliasSymbol;
    type.aliasTypeArguments = aliasTypeArguments;
    return type;
  }
  function getTypeArguments(type) {
    if (!type.resolvedTypeArguments) {
      if (!pushTypeResolution(type, 5 /* ResolvedTypeArguments */)) {
        return concatenate(type.target.outerTypeParameters, type.target.localTypeParameters?.map(() => errorType)) || emptyArray;
      }
      const node = type.node;
      const typeArguments = !node ? emptyArray : node.kind === SyntaxKind.TypeReference ? concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : node.kind === SyntaxKind.ArrayType ? [getTypeFromTypeNode(node.elementType)] : map(node.elements, getTypeFromTypeNode);
      if (popTypeResolution()) {
        type.resolvedTypeArguments ??= type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
      } else {
        type.resolvedTypeArguments ??= concatenate(type.target.outerTypeParameters, type.target.localTypeParameters?.map(() => errorType) || emptyArray);
        error(
          type.node || currentNode,
          type.target.symbol ? Diagnostics.Type_arguments_for_0_circularly_reference_themselves : Diagnostics.Tuple_type_arguments_circularly_reference_themselves,
          type.target.symbol && symbolToString(type.target.symbol)
        );
      }
    }
    return type.resolvedTypeArguments;
  }
  function getTypeReferenceArity(type) {
    return length(type.target.typeParameters);
  }
  function getTypeFromClassOrInterfaceReference(node, symbol) {
    const type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
    const typeParameters = type.localTypeParameters;
    if (typeParameters) {
      const numTypeArguments = length(node.typeArguments);
      const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
      const isJs = isInJSFile(node);
      const isJsImplicitAny = !noImplicitAny && isJs;
      if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
        const missingAugmentsTag = isJs && isExpressionWithTypeArguments(node) && !isJSDocAugmentsTag(node.parent);
        const diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag : Diagnostics.Generic_type_0_requires_1_type_argument_s : missingAugmentsTag ? Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
        const typeStr = typeToString(
          type,
          /*enclosingDeclaration*/
          void 0,
          TypeFormatFlags.WriteArrayAsGenericType
        );
        error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
        if (!isJs) {
          return errorType;
        }
      }
      if (node.kind === SyntaxKind.TypeReference && isDeferredTypeReferenceNode(node, length(node.typeArguments) !== typeParameters.length)) {
        return createDeferredTypeReference(
          type,
          node,
          /*mapper*/
          void 0
        );
      }
      const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
      return createTypeReference(type, typeArguments);
    }
    return checkNoTypeArguments(node, symbol) ? type : errorType;
  }
  function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) {
    const type = getDeclaredTypeOfSymbol(symbol);
    if (type === intrinsicMarkerType) {
      const typeKind = intrinsicTypeKinds.get(symbol.escapedName);
      if (typeKind !== void 0 && typeArguments && typeArguments.length === 1) {
        return typeKind === 4 /* NoInfer */ ? getNoInferType(typeArguments[0]) : getStringMappingType(symbol, typeArguments[0]);
      }
    }
    const links = getSymbolLinks(symbol);
    const typeParameters = links.typeParameters;
    const id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments);
    let instantiation = links.instantiations.get(id);
    if (!instantiation) {
      links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments));
    }
    return instantiation;
  }
  function getTypeFromTypeAliasReference(node, symbol) {
    if (getCheckFlags(symbol) & CheckFlags.Unresolved) {
      const typeArguments = typeArgumentsFromTypeReferenceNode(node);
      const id = getAliasId(symbol, typeArguments);
      let errorType2 = errorTypes.get(id);
      if (!errorType2) {
        errorType2 = createIntrinsicType(
          TypeFlags.Any,
          "error",
          /*objectFlags*/
          void 0,
          `alias ${id}`
        );
        errorType2.aliasSymbol = symbol;
        errorType2.aliasTypeArguments = typeArguments;
        errorTypes.set(id, errorType2);
      }
      return errorType2;
    }
    const type = getDeclaredTypeOfSymbol(symbol);
    const typeParameters = getSymbolLinks(symbol).typeParameters;
    if (typeParameters) {
      const numTypeArguments = length(node.typeArguments);
      const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
      if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
        error(
          node,
          minTypeArgumentCount === typeParameters.length ? Diagnostics.Generic_type_0_requires_1_type_argument_s : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments,
          symbolToString(symbol),
          minTypeArgumentCount,
          typeParameters.length
        );
        return errorType;
      }
      const aliasSymbol = getAliasSymbolForTypeNode(node);
      let newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : void 0;
      let aliasTypeArguments;
      if (newAliasSymbol) {
        aliasTypeArguments = getTypeArgumentsForAliasSymbol(newAliasSymbol);
      } else if (isTypeReferenceType(node)) {
        const aliasSymbol2 = resolveTypeReferenceName(
          node,
          SymbolFlags.Alias,
          /*ignoreErrors*/
          true
        );
        if (aliasSymbol2 && aliasSymbol2 !== unknownSymbol) {
          const resolved = resolveAlias(aliasSymbol2);
          if (resolved && resolved.flags & SymbolFlags.TypeAlias) {
            newAliasSymbol = resolved;
            aliasTypeArguments = typeArgumentsFromTypeReferenceNode(node) || (typeParameters ? [] : void 0);
          }
        }
      }
      return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, aliasTypeArguments);
    }
    return checkNoTypeArguments(node, symbol) ? type : errorType;
  }
  function isLocalTypeAlias(symbol) {
    const declaration = symbol.declarations?.find(isTypeAlias);
    return !!(declaration && getContainingFunction(declaration));
  }
  function getTypeReferenceName(node) {
    switch (node.kind) {
      case SyntaxKind.TypeReference:
        return node.typeName;
      case SyntaxKind.ExpressionWithTypeArguments:
        const expr = node.expression;
        if (isEntityNameExpression(expr)) {
          return expr;
        }
    }
    return void 0;
  }
  function getSymbolPath(symbol) {
    return symbol.parent ? `${getSymbolPath(symbol.parent)}.${symbol.escapedName}` : symbol.escapedName;
  }
  function getUnresolvedSymbolForEntityName(name) {
    const identifier = name.kind === SyntaxKind.QualifiedName ? name.right : name.kind === SyntaxKind.PropertyAccessExpression ? name.name : name;
    const text = identifier.escapedText;
    if (text) {
      const parentSymbol = name.kind === SyntaxKind.QualifiedName ? getUnresolvedSymbolForEntityName(name.left) : name.kind === SyntaxKind.PropertyAccessExpression ? getUnresolvedSymbolForEntityName(name.expression) : void 0;
      const path = parentSymbol ? `${getSymbolPath(parentSymbol)}.${text}` : text;
      let result = unresolvedSymbols.get(path);
      if (!result) {
        unresolvedSymbols.set(path, result = createSymbol(SymbolFlags.TypeAlias, text, CheckFlags.Unresolved));
        result.parent = parentSymbol;
        result.links.declaredType = unresolvedType;
      }
      return result;
    }
    return unknownSymbol;
  }
  function resolveTypeReferenceName(typeReference, meaning, ignoreErrors) {
    const name = getTypeReferenceName(typeReference);
    if (!name) {
      return unknownSymbol;
    }
    const symbol = resolveEntityName(name, meaning, ignoreErrors);
    return symbol && symbol !== unknownSymbol ? symbol : ignoreErrors ? unknownSymbol : getUnresolvedSymbolForEntityName(name);
  }
  function getTypeReferenceType(node, symbol) {
    if (symbol === unknownSymbol) {
      return errorType;
    }
    symbol = getExpandoSymbol(symbol) || symbol;
    if (symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
      return getTypeFromClassOrInterfaceReference(node, symbol);
    }
    if (symbol.flags & SymbolFlags.TypeAlias) {
      return getTypeFromTypeAliasReference(node, symbol);
    }
    const res = tryGetDeclaredTypeOfSymbol(symbol);
    if (res) {
      return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
    }
    if (symbol.flags & SymbolFlags.Value && isJSDocTypeReference(node)) {
      const jsdocType = getTypeFromJSDocValueReference(node, symbol);
      if (jsdocType) {
        return jsdocType;
      } else {
        resolveTypeReferenceName(node, SymbolFlags.Type);
        return getTypeOfSymbol(symbol);
      }
    }
    return errorType;
  }
  function getTypeFromJSDocValueReference(node, symbol) {
    const links = getNodeLinks(node);
    if (!links.resolvedJSDocType) {
      const valueType = getTypeOfSymbol(symbol);
      let typeType = valueType;
      if (symbol.valueDeclaration) {
        const isImportTypeWithQualifier = node.kind === SyntaxKind.ImportType && node.qualifier;
        if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) {
          typeType = getTypeReferenceType(node, valueType.symbol);
        }
      }
      links.resolvedJSDocType = typeType;
    }
    return links.resolvedJSDocType;
  }
  function getNoInferType(type) {
    return isNoInferTargetType(type) ? getOrCreateSubstitutionType(type, unknownType) : type;
  }
  function isNoInferTargetType(type) {
    return !!(type.flags & TypeFlags.UnionOrIntersection && some(type.types, isNoInferTargetType) || type.flags & TypeFlags.Substitution && !isNoInferType(type) && isNoInferTargetType(type.baseType) || type.flags & TypeFlags.Object && !isEmptyAnonymousObjectType(type) || type.flags & (TypeFlags.Instantiable & ~TypeFlags.Substitution) && !isPatternLiteralType(type));
  }
  function isNoInferType(type) {
    return !!(type.flags & TypeFlags.Substitution && type.constraint.flags & TypeFlags.Unknown);
  }
  function getSubstitutionType(baseType, constraint) {
    return constraint.flags & TypeFlags.AnyOrUnknown || constraint === baseType || baseType.flags & TypeFlags.Any ? baseType : getOrCreateSubstitutionType(baseType, constraint);
  }
  function getOrCreateSubstitutionType(baseType, constraint) {
    const id = `${getTypeId(baseType)}>${getTypeId(constraint)}`;
    const cached = substitutionTypes.get(id);
    if (cached) {
      return cached;
    }
    const result = createType(TypeFlags.Substitution);
    result.baseType = baseType;
    result.constraint = constraint;
    substitutionTypes.set(id, result);
    return result;
  }
  function getSubstitutionIntersection(substitutionType) {
    return isNoInferType(substitutionType) ? substitutionType.baseType : getIntersectionType([substitutionType.constraint, substitutionType.baseType]);
  }
  function isUnaryTupleTypeNode(node) {
    return node.kind === SyntaxKind.TupleType && node.elements.length === 1;
  }
  function getImpliedConstraint(type, checkNode, extendsNode) {
    return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : getActualTypeVariable(getTypeFromTypeNode(checkNode)) === getActualTypeVariable(type) ? getTypeFromTypeNode(extendsNode) : void 0;
  }
  function getConditionalFlowTypeOfType(type, node) {
    let constraints;
    let covariant = true;
    while (node && !isStatement(node) && node.kind !== SyntaxKind.JSDoc) {
      const parent = node.parent;
      if (parent.kind === SyntaxKind.Parameter) {
        covariant = !covariant;
      }
      if ((covariant || type.flags & TypeFlags.TypeVariable) && parent.kind === SyntaxKind.ConditionalType && node === parent.trueType) {
        const constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
        if (constraint) {
          constraints = append(constraints, constraint);
        }
      } else if (type.flags & TypeFlags.TypeParameter && parent.kind === SyntaxKind.MappedType && !parent.nameType && node === parent.type) {
        const mappedType = getTypeFromTypeNode(parent);
        if (getTypeParameterFromMappedType(mappedType) === getActualTypeVariable(type)) {
          const typeParameter = getHomomorphicTypeVariable(mappedType);
          if (typeParameter) {
            const constraint = getConstraintOfTypeParameter(typeParameter);
            if (constraint && everyType(constraint, isArrayOrTupleType)) {
              constraints = append(constraints, getUnionType([numberType, numericStringType]));
            }
          }
        }
      }
      node = parent;
    }
    return constraints ? getSubstitutionType(type, getIntersectionType(constraints)) : type;
  }
  function isJSDocTypeReference(node) {
    return !!(node.flags & NodeFlags.JSDoc) && (node.kind === SyntaxKind.TypeReference || node.kind === SyntaxKind.ImportType);
  }
  function checkNoTypeArguments(node, symbol) {
    if (node.typeArguments) {
      error(node, Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? declarationNameToString(node.typeName) : anon);
      return false;
    }
    return true;
  }
  function getIntendedTypeFromJSDocTypeReference(node) {
    if (isIdentifier(node.typeName)) {
      const typeArgs = node.typeArguments;
      switch (node.typeName.escapedText) {
        case "String":
          checkNoTypeArguments(node);
          return stringType;
        case "Number":
          checkNoTypeArguments(node);
          return numberType;
        case "Boolean":
          checkNoTypeArguments(node);
          return booleanType;
        case "Void":
          checkNoTypeArguments(node);
          return voidType;
        case "Undefined":
          checkNoTypeArguments(node);
          return undefinedType;
        case "Null":
          checkNoTypeArguments(node);
          return nullType;
        case "Function":
        case "function":
          checkNoTypeArguments(node);
          return globalFunctionType;
        case "array":
          return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : void 0;
        case "promise":
          return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : void 0;
        case "Object":
          if (typeArgs && typeArgs.length === 2) {
            if (isJSDocIndexSignature(node)) {
              const indexed = getTypeFromTypeNode(typeArgs[0]);
              const target = getTypeFromTypeNode(typeArgs[1]);
              const indexInfo = indexed === stringType || indexed === numberType ? [createIndexInfo(
                indexed,
                target,
                /*isReadonly*/
                false
              )] : emptyArray;
              return createAnonymousType(
                /*symbol*/
                void 0,
                emptySymbols,
                emptyArray,
                emptyArray,
                indexInfo
              );
            }
            return anyType;
          }
          checkNoTypeArguments(node);
          return !noImplicitAny ? anyType : void 0;
      }
    }
  }
  function getTypeFromJSDocNullableTypeNode(node) {
    const type = getTypeFromTypeNode(node.type);
    return strictNullChecks ? getNullableType(type, TypeFlags.Null) : type;
  }
  function getTypeFromTypeReference(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      if (isConstTypeReference(node) && isAssertionExpression(node.parent)) {
        links.resolvedSymbol = unknownSymbol;
        return links.resolvedType = checkExpressionCached(node.parent.expression);
      }
      let symbol;
      let type;
      const meaning = SymbolFlags.Type;
      if (isJSDocTypeReference(node)) {
        type = getIntendedTypeFromJSDocTypeReference(node);
        if (!type) {
          symbol = resolveTypeReferenceName(
            node,
            meaning,
            /*ignoreErrors*/
            true
          );
          if (symbol === unknownSymbol) {
            symbol = resolveTypeReferenceName(node, meaning | SymbolFlags.Value);
          } else {
            resolveTypeReferenceName(node, meaning);
          }
          type = getTypeReferenceType(node, symbol);
        }
      }
      if (!type) {
        symbol = resolveTypeReferenceName(node, meaning);
        type = getTypeReferenceType(node, symbol);
      }
      links.resolvedSymbol = symbol;
      links.resolvedType = type;
    }
    return links.resolvedType;
  }
  function typeArgumentsFromTypeReferenceNode(node) {
    return map(node.typeArguments, getTypeFromTypeNode);
  }
  function getTypeFromTypeQueryNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const type = checkExpressionWithTypeArguments(node);
      links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(type));
    }
    return links.resolvedType;
  }
  function getTypeOfGlobalSymbol(symbol, arity) {
    function getTypeDeclaration(symbol2) {
      const declarations = symbol2.declarations;
      if (declarations) {
        for (const declaration of declarations) {
          switch (declaration.kind) {
            case SyntaxKind.ClassDeclaration:
            case SyntaxKind.InterfaceDeclaration:
            case SyntaxKind.EnumDeclaration:
              return declaration;
          }
        }
      }
    }
    if (!symbol) {
      return arity ? emptyGenericType : emptyObjectType;
    }
    const type = getDeclaredTypeOfSymbol(symbol);
    if (!(type.flags & TypeFlags.Object)) {
      error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbolName(symbol));
      return arity ? emptyGenericType : emptyObjectType;
    }
    if (length(type.typeParameters) !== arity) {
      error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity);
      return arity ? emptyGenericType : emptyObjectType;
    }
    return type;
  }
  function getGlobalValueSymbol(name, reportErrors) {
    return getGlobalSymbol(name, SymbolFlags.Value, reportErrors ? Diagnostics.Cannot_find_global_value_0 : void 0);
  }
  function getGlobalTypeSymbol(name, reportErrors) {
    return getGlobalSymbol(name, SymbolFlags.Type, reportErrors ? Diagnostics.Cannot_find_global_type_0 : void 0);
  }
  function getGlobalTypeAliasSymbol(name, arity, reportErrors) {
    const symbol = getGlobalSymbol(name, SymbolFlags.Type, reportErrors ? Diagnostics.Cannot_find_global_type_0 : void 0);
    if (symbol) {
      getDeclaredTypeOfSymbol(symbol);
      if (length(getSymbolLinks(symbol).typeParameters) !== arity) {
        const decl = symbol.declarations && find(symbol.declarations, isTypeAliasDeclaration);
        error(decl, Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity);
        return void 0;
      }
    }
    return symbol;
  }
  function getGlobalSymbol(name, meaning, diagnostic) {
    return resolveName(
      /*location*/
      void 0,
      name,
      meaning,
      diagnostic,
      /*isUse*/
      false,
      /*excludeGlobals*/
      false
    );
  }
  function getGlobalType(name, arity, reportErrors) {
    const symbol = getGlobalTypeSymbol(name, reportErrors);
    return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : void 0;
  }
  function getGlobalBuiltinTypes(typeNames, arity) {
    let types;
    for (const typeName of typeNames) {
      types = append(types, getGlobalType(
        typeName,
        arity,
        /*reportErrors*/
        false
      ));
    }
    return types ?? emptyArray;
  }
  function getGlobalTypedPropertyDescriptorType() {
    return deferredGlobalTypedPropertyDescriptorType ||= getGlobalType(
      "TypedPropertyDescriptor",
      /*arity*/
      1,
      /*reportErrors*/
      true
    ) || emptyGenericType;
  }
  function getGlobalTemplateStringsArrayType() {
    return deferredGlobalTemplateStringsArrayType ||= getGlobalType(
      "TemplateStringsArray",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || emptyObjectType;
  }
  function getGlobalImportMetaType() {
    return deferredGlobalImportMetaType ||= getGlobalType(
      "ImportMeta",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || emptyObjectType;
  }
  function getGlobalImportMetaExpressionType() {
    if (!deferredGlobalImportMetaExpressionType) {
      const symbol = createSymbol(SymbolFlags.None, "ImportMetaExpression");
      const importMetaType = getGlobalImportMetaType();
      const metaPropertySymbol = createSymbol(SymbolFlags.Property, "meta", CheckFlags.Readonly);
      metaPropertySymbol.parent = symbol;
      metaPropertySymbol.links.type = importMetaType;
      const members = createSymbolTable([metaPropertySymbol]);
      symbol.members = members;
      deferredGlobalImportMetaExpressionType = createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
    }
    return deferredGlobalImportMetaExpressionType;
  }
  function getGlobalImportCallOptionsType(reportErrors) {
    return (deferredGlobalImportCallOptionsType ||= getGlobalType(
      "ImportCallOptions",
      /*arity*/
      0,
      reportErrors
    )) || emptyObjectType;
  }
  function getGlobalImportAttributesType(reportErrors) {
    return (deferredGlobalImportAttributesType ||= getGlobalType(
      "ImportAttributes",
      /*arity*/
      0,
      reportErrors
    )) || emptyObjectType;
  }
  function getGlobalESSymbolConstructorSymbol(reportErrors) {
    return deferredGlobalESSymbolConstructorSymbol ||= getGlobalValueSymbol("Symbol", reportErrors);
  }
  function getGlobalESSymbolConstructorTypeSymbol(reportErrors) {
    return deferredGlobalESSymbolConstructorTypeSymbol ||= getGlobalTypeSymbol("SymbolConstructor", reportErrors);
  }
  function getGlobalESSymbolType() {
    return (deferredGlobalESSymbolType ||= getGlobalType(
      "Symbol",
      /*arity*/
      0,
      /*reportErrors*/
      false
    )) || emptyObjectType;
  }
  function getGlobalPromiseType(reportErrors) {
    return (deferredGlobalPromiseType ||= getGlobalType(
      "Promise",
      /*arity*/
      1,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalPromiseLikeType(reportErrors) {
    return (deferredGlobalPromiseLikeType ||= getGlobalType(
      "PromiseLike",
      /*arity*/
      1,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalPromiseConstructorSymbol(reportErrors) {
    return deferredGlobalPromiseConstructorSymbol ||= getGlobalValueSymbol("Promise", reportErrors);
  }
  function getGlobalPromiseConstructorLikeType(reportErrors) {
    return (deferredGlobalPromiseConstructorLikeType ||= getGlobalType(
      "PromiseConstructorLike",
      /*arity*/
      0,
      reportErrors
    )) || emptyObjectType;
  }
  function getGlobalAsyncIterableType(reportErrors) {
    return (deferredGlobalAsyncIterableType ||= getGlobalType(
      "AsyncIterable",
      /*arity*/
      3,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalAsyncIteratorType(reportErrors) {
    return (deferredGlobalAsyncIteratorType ||= getGlobalType(
      "AsyncIterator",
      /*arity*/
      3,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalAsyncIterableIteratorType(reportErrors) {
    return (deferredGlobalAsyncIterableIteratorType ||= getGlobalType(
      "AsyncIterableIterator",
      /*arity*/
      3,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalBuiltinAsyncIteratorTypes() {
    return deferredGlobalBuiltinAsyncIteratorTypes ??= getGlobalBuiltinTypes(["ReadableStreamAsyncIterator"], 1);
  }
  function getGlobalAsyncIteratorObjectType(reportErrors) {
    return (deferredGlobalAsyncIteratorObjectType ||= getGlobalType(
      "AsyncIteratorObject",
      /*arity*/
      3,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalAsyncGeneratorType(reportErrors) {
    return (deferredGlobalAsyncGeneratorType ||= getGlobalType(
      "AsyncGenerator",
      /*arity*/
      3,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalIterableType(reportErrors) {
    return (deferredGlobalIterableType ||= getGlobalType(
      "Iterable",
      /*arity*/
      3,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalIteratorType(reportErrors) {
    return (deferredGlobalIteratorType ||= getGlobalType(
      "Iterator",
      /*arity*/
      3,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalIterableIteratorType(reportErrors) {
    return (deferredGlobalIterableIteratorType ||= getGlobalType(
      "IterableIterator",
      /*arity*/
      3,
      reportErrors
    )) || emptyGenericType;
  }
  function getBuiltinIteratorReturnType() {
    return strictBuiltinIteratorReturn ? undefinedType : anyType;
  }
  function getGlobalBuiltinIteratorTypes() {
    return deferredGlobalBuiltinIteratorTypes ??= getGlobalBuiltinTypes(["ArrayIterator", "MapIterator", "SetIterator", "StringIterator"], 1);
  }
  function getGlobalIteratorObjectType(reportErrors) {
    return (deferredGlobalIteratorObjectType ||= getGlobalType(
      "IteratorObject",
      /*arity*/
      3,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalGeneratorType(reportErrors) {
    return (deferredGlobalGeneratorType ||= getGlobalType(
      "Generator",
      /*arity*/
      3,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalIteratorYieldResultType(reportErrors) {
    return (deferredGlobalIteratorYieldResultType ||= getGlobalType(
      "IteratorYieldResult",
      /*arity*/
      1,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalIteratorReturnResultType(reportErrors) {
    return (deferredGlobalIteratorReturnResultType ||= getGlobalType(
      "IteratorReturnResult",
      /*arity*/
      1,
      reportErrors
    )) || emptyGenericType;
  }
  function getGlobalDisposableType(reportErrors) {
    return (deferredGlobalDisposableType ||= getGlobalType(
      "Disposable",
      /*arity*/
      0,
      reportErrors
    )) || emptyObjectType;
  }
  function getGlobalAsyncDisposableType(reportErrors) {
    return (deferredGlobalAsyncDisposableType ||= getGlobalType(
      "AsyncDisposable",
      /*arity*/
      0,
      reportErrors
    )) || emptyObjectType;
  }
  function getGlobalTypeOrUndefined(name, arity = 0) {
    const symbol = getGlobalSymbol(
      name,
      SymbolFlags.Type,
      /*diagnostic*/
      void 0
    );
    return symbol && getTypeOfGlobalSymbol(symbol, arity);
  }
  function getGlobalExtractSymbol() {
    deferredGlobalExtractSymbol ||= getGlobalTypeAliasSymbol(
      "Extract",
      /*arity*/
      2,
      /*reportErrors*/
      true
    ) || unknownSymbol;
    return deferredGlobalExtractSymbol === unknownSymbol ? void 0 : deferredGlobalExtractSymbol;
  }
  function getGlobalOmitSymbol() {
    deferredGlobalOmitSymbol ||= getGlobalTypeAliasSymbol(
      "Omit",
      /*arity*/
      2,
      /*reportErrors*/
      true
    ) || unknownSymbol;
    return deferredGlobalOmitSymbol === unknownSymbol ? void 0 : deferredGlobalOmitSymbol;
  }
  function getGlobalAwaitedSymbol(reportErrors) {
    deferredGlobalAwaitedSymbol ||= getGlobalTypeAliasSymbol(
      "Awaited",
      /*arity*/
      1,
      reportErrors
    ) || (reportErrors ? unknownSymbol : void 0);
    return deferredGlobalAwaitedSymbol === unknownSymbol ? void 0 : deferredGlobalAwaitedSymbol;
  }
  function getGlobalBigIntType() {
    return (deferredGlobalBigIntType ||= getGlobalType(
      "BigInt",
      /*arity*/
      0,
      /*reportErrors*/
      false
    )) || emptyObjectType;
  }
  function getGlobalClassDecoratorContextType(reportErrors) {
    return (deferredGlobalClassDecoratorContextType ??= getGlobalType(
      "ClassDecoratorContext",
      /*arity*/
      1,
      reportErrors
    )) ?? emptyGenericType;
  }
  function getGlobalClassMethodDecoratorContextType(reportErrors) {
    return (deferredGlobalClassMethodDecoratorContextType ??= getGlobalType(
      "ClassMethodDecoratorContext",
      /*arity*/
      2,
      reportErrors
    )) ?? emptyGenericType;
  }
  function getGlobalClassGetterDecoratorContextType(reportErrors) {
    return (deferredGlobalClassGetterDecoratorContextType ??= getGlobalType(
      "ClassGetterDecoratorContext",
      /*arity*/
      2,
      reportErrors
    )) ?? emptyGenericType;
  }
  function getGlobalClassSetterDecoratorContextType(reportErrors) {
    return (deferredGlobalClassSetterDecoratorContextType ??= getGlobalType(
      "ClassSetterDecoratorContext",
      /*arity*/
      2,
      reportErrors
    )) ?? emptyGenericType;
  }
  function getGlobalClassAccessorDecoratorContextType(reportErrors) {
    return (deferredGlobalClassAccessorDecoratorContextType ??= getGlobalType(
      "ClassAccessorDecoratorContext",
      /*arity*/
      2,
      reportErrors
    )) ?? emptyGenericType;
  }
  function getGlobalClassAccessorDecoratorTargetType(reportErrors) {
    return (deferredGlobalClassAccessorDecoratorTargetType ??= getGlobalType(
      "ClassAccessorDecoratorTarget",
      /*arity*/
      2,
      reportErrors
    )) ?? emptyGenericType;
  }
  function getGlobalClassAccessorDecoratorResultType(reportErrors) {
    return (deferredGlobalClassAccessorDecoratorResultType ??= getGlobalType(
      "ClassAccessorDecoratorResult",
      /*arity*/
      2,
      reportErrors
    )) ?? emptyGenericType;
  }
  function getGlobalClassFieldDecoratorContextType(reportErrors) {
    return (deferredGlobalClassFieldDecoratorContextType ??= getGlobalType(
      "ClassFieldDecoratorContext",
      /*arity*/
      2,
      reportErrors
    )) ?? emptyGenericType;
  }
  function getGlobalNaNSymbol() {
    return deferredGlobalNaNSymbol ||= getGlobalValueSymbol(
      "NaN",
      /*reportErrors*/
      false
    );
  }
  function getGlobalRecordSymbol() {
    deferredGlobalRecordSymbol ||= getGlobalTypeAliasSymbol(
      "Record",
      /*arity*/
      2,
      /*reportErrors*/
      true
    ) || unknownSymbol;
    return deferredGlobalRecordSymbol === unknownSymbol ? void 0 : deferredGlobalRecordSymbol;
  }
  function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
    return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
  }
  function createTypedPropertyDescriptorType(propertyType) {
    return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
  }
  function createIterableType(iteratedType) {
    return createTypeFromGenericGlobalType(getGlobalIterableType(
      /*reportErrors*/
      true
    ), [iteratedType, voidType, undefinedType]);
  }
  function createArrayType(elementType, readonly) {
    return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
  }
  function getTupleElementFlags(node) {
    switch (node.kind) {
      case SyntaxKind.OptionalType:
        return ElementFlags.Optional;
      case SyntaxKind.RestType:
        return getRestTypeElementFlags(node);
      case SyntaxKind.NamedTupleMember:
        return node.questionToken ? ElementFlags.Optional : node.dotDotDotToken ? getRestTypeElementFlags(node) : ElementFlags.Required;
      default:
        return ElementFlags.Required;
    }
  }
  function getRestTypeElementFlags(node) {
    return getArrayElementTypeNode(node.type) ? ElementFlags.Rest : ElementFlags.Variadic;
  }
  function getArrayOrTupleTargetType(node) {
    const readonly = isReadonlyTypeOperator(node.parent);
    const elementType = getArrayElementTypeNode(node);
    if (elementType) {
      return readonly ? globalReadonlyArrayType : globalArrayType;
    }
    const elementFlags = map(node.elements, getTupleElementFlags);
    return getTupleTargetType(elementFlags, readonly, map(node.elements, memberIfLabeledElementDeclaration));
  }
  function memberIfLabeledElementDeclaration(member) {
    return isNamedTupleMember(member) || isParameter(member) ? member : void 0;
  }
  function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
    return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === SyntaxKind.ArrayType ? mayResolveTypeAlias(node.elementType) : node.kind === SyntaxKind.TupleType ? some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || some(node.typeArguments, mayResolveTypeAlias));
  }
  function isResolvedByTypeAlias(node) {
    const parent = node.parent;
    switch (parent.kind) {
      case SyntaxKind.ParenthesizedType:
      case SyntaxKind.NamedTupleMember:
      case SyntaxKind.TypeReference:
      case SyntaxKind.UnionType:
      case SyntaxKind.IntersectionType:
      case SyntaxKind.IndexedAccessType:
      case SyntaxKind.ConditionalType:
      case SyntaxKind.TypeOperator:
      case SyntaxKind.ArrayType:
      case SyntaxKind.TupleType:
        return isResolvedByTypeAlias(parent);
      case SyntaxKind.TypeAliasDeclaration:
        return true;
    }
    return false;
  }
  function mayResolveTypeAlias(node) {
    switch (node.kind) {
      case SyntaxKind.TypeReference:
        return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node, SymbolFlags.Type).flags & SymbolFlags.TypeAlias);
      case SyntaxKind.TypeQuery:
        return true;
      case SyntaxKind.TypeOperator:
        return node.operator !== SyntaxKind.UniqueKeyword && mayResolveTypeAlias(node.type);
      case SyntaxKind.ParenthesizedType:
      case SyntaxKind.OptionalType:
      case SyntaxKind.NamedTupleMember:
      case SyntaxKind.JSDocOptionalType:
      case SyntaxKind.JSDocNullableType:
      case SyntaxKind.JSDocNonNullableType:
      case SyntaxKind.JSDocTypeExpression:
        return mayResolveTypeAlias(node.type);
      case SyntaxKind.RestType:
        return node.type.kind !== SyntaxKind.ArrayType || mayResolveTypeAlias(node.type.elementType);
      case SyntaxKind.UnionType:
      case SyntaxKind.IntersectionType:
        return some(node.types, mayResolveTypeAlias);
      case SyntaxKind.IndexedAccessType:
        return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
      case SyntaxKind.ConditionalType:
        return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
    }
    return false;
  }
  function getTypeFromArrayOrTupleTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const target = getArrayOrTupleTargetType(node);
      if (target === emptyGenericType) {
        links.resolvedType = emptyObjectType;
      } else if (!(node.kind === SyntaxKind.TupleType && some(node.elements, (e) => !!(getTupleElementFlags(e) & ElementFlags.Variadic))) && isDeferredTypeReferenceNode(node)) {
        links.resolvedType = node.kind === SyntaxKind.TupleType && node.elements.length === 0 ? target : createDeferredTypeReference(
          target,
          node,
          /*mapper*/
          void 0
        );
      } else {
        const elementTypes = node.kind === SyntaxKind.ArrayType ? [getTypeFromTypeNode(node.elementType)] : map(node.elements, getTypeFromTypeNode);
        links.resolvedType = createNormalizedTypeReference(target, elementTypes);
      }
    }
    return links.resolvedType;
  }
  function isReadonlyTypeOperator(node) {
    return isTypeOperatorNode(node) && node.operator === SyntaxKind.ReadonlyKeyword;
  }
  function createTupleType(elementTypes, elementFlags, readonly = false, namedMemberDeclarations = []) {
    const tupleTarget = getTupleTargetType(elementFlags || map(elementTypes, (_) => ElementFlags.Required), readonly, namedMemberDeclarations);
    return tupleTarget === emptyGenericType ? emptyObjectType : elementTypes.length ? createNormalizedTypeReference(tupleTarget, elementTypes) : tupleTarget;
  }
  function getTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
    if (elementFlags.length === 1 && elementFlags[0] & ElementFlags.Rest) {
      return readonly ? globalReadonlyArrayType : globalArrayType;
    }
    const key = map(elementFlags, (f) => f & ElementFlags.Required ? "#" : f & ElementFlags.Optional ? "?" : f & ElementFlags.Rest ? "." : "*").join() + (readonly ? "R" : "") + (some(namedMemberDeclarations, (node) => !!node) ? "," + map(namedMemberDeclarations, (node) => node ? getNodeId(node) : "_").join(",") : "");
    let type = tupleTypes.get(key);
    if (!type) {
      tupleTypes.set(key, type = createTupleTargetType(elementFlags, readonly, namedMemberDeclarations));
    }
    return type;
  }
  function createTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
    const arity = elementFlags.length;
    const minLength = countWhere(elementFlags, (f) => !!(f & (ElementFlags.Required | ElementFlags.Variadic)));
    let typeParameters;
    const properties = [];
    let combinedFlags = 0;
    if (arity) {
      typeParameters = new Array(arity);
      for (let i = 0; i < arity; i++) {
        const typeParameter = typeParameters[i] = createTypeParameter();
        const flags = elementFlags[i];
        combinedFlags |= flags;
        if (!(combinedFlags & ElementFlags.Variable)) {
          const property = createSymbol(SymbolFlags.Property | (flags & ElementFlags.Optional ? SymbolFlags.Optional : 0), "" + i, readonly ? CheckFlags.Readonly : 0);
          property.links.tupleLabelDeclaration = namedMemberDeclarations?.[i];
          property.links.type = typeParameter;
          properties.push(property);
        }
      }
    }
    const fixedLength = properties.length;
    const lengthSymbol = createSymbol(SymbolFlags.Property, "length", readonly ? CheckFlags.Readonly : 0);
    if (combinedFlags & ElementFlags.Variable) {
      lengthSymbol.links.type = numberType;
    } else {
      const literalTypes = [];
      for (let i = minLength; i <= arity; i++) literalTypes.push(getNumberLiteralType(i));
      lengthSymbol.links.type = getUnionType(literalTypes);
    }
    properties.push(lengthSymbol);
    const type = createObjectType(ObjectFlags.Tuple | ObjectFlags.Reference);
    type.typeParameters = typeParameters;
    type.outerTypeParameters = void 0;
    type.localTypeParameters = typeParameters;
    type.instantiations = /* @__PURE__ */ new Map();
    type.instantiations.set(getTypeListId(type.typeParameters), type);
    type.target = type;
    type.resolvedTypeArguments = type.typeParameters;
    type.thisType = createTypeParameter();
    type.thisType.isThisType = true;
    type.thisType.constraint = type;
    type.declaredProperties = properties;
    type.declaredCallSignatures = emptyArray;
    type.declaredConstructSignatures = emptyArray;
    type.declaredIndexInfos = emptyArray;
    type.elementFlags = elementFlags;
    type.minLength = minLength;
    type.fixedLength = fixedLength;
    type.hasRestElement = !!(combinedFlags & ElementFlags.Variable);
    type.combinedFlags = combinedFlags;
    type.readonly = readonly;
    type.labeledElementDeclarations = namedMemberDeclarations;
    return type;
  }
  function createNormalizedTypeReference(target, typeArguments) {
    return target.objectFlags & ObjectFlags.Tuple ? createNormalizedTupleType(target, typeArguments) : createTypeReference(target, typeArguments);
  }
  function createNormalizedTupleType(target, elementTypes) {
    if (!(target.combinedFlags & ElementFlags.NonRequired)) {
      return createTypeReference(target, elementTypes);
    }
    if (target.combinedFlags & ElementFlags.Variadic) {
      const unionIndex = findIndex(elementTypes, (t, i) => !!(target.elementFlags[i] & ElementFlags.Variadic && t.flags & (TypeFlags.Never | TypeFlags.Union)));
      if (unionIndex >= 0) {
        return checkCrossProductUnion(map(elementTypes, (t, i) => target.elementFlags[i] & ElementFlags.Variadic ? t : unknownType)) ? mapType(elementTypes[unionIndex], (t) => createNormalizedTupleType(target, replaceElement(elementTypes, unionIndex, t))) : errorType;
      }
    }
    const expandedTypes = [];
    const expandedFlags = [];
    const expandedDeclarations = [];
    let lastRequiredIndex = -1;
    let firstRestIndex = -1;
    let lastOptionalOrRestIndex = -1;
    for (let i = 0; i < elementTypes.length; i++) {
      const type = elementTypes[i];
      const flags = target.elementFlags[i];
      if (flags & ElementFlags.Variadic) {
        if (type.flags & TypeFlags.Any) {
          addElement(type, ElementFlags.Rest, target.labeledElementDeclarations?.[i]);
        } else if (type.flags & TypeFlags.InstantiableNonPrimitive || isGenericMappedType(type)) {
          addElement(type, ElementFlags.Variadic, target.labeledElementDeclarations?.[i]);
        } else if (isTupleType(type)) {
          const elements = getElementTypes(type);
          if (elements.length + expandedTypes.length >= 1e4) {
            error(
              currentNode,
              isPartOfTypeNode(currentNode) ? Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent : Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent
            );
            return errorType;
          }
          forEach(elements, (t, n) => addElement(t, type.target.elementFlags[n], type.target.labeledElementDeclarations?.[n]));
        } else {
          addElement(isArrayLikeType(type) && getIndexTypeOfType(type, numberType) || errorType, ElementFlags.Rest, target.labeledElementDeclarations?.[i]);
        }
      } else {
        addElement(type, flags, target.labeledElementDeclarations?.[i]);
      }
    }
    for (let i = 0; i < lastRequiredIndex; i++) {
      if (expandedFlags[i] & ElementFlags.Optional) expandedFlags[i] = ElementFlags.Required;
    }
    if (firstRestIndex >= 0 && firstRestIndex < lastOptionalOrRestIndex) {
      expandedTypes[firstRestIndex] = getUnionType(sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), (t, i) => expandedFlags[firstRestIndex + i] & ElementFlags.Variadic ? getIndexedAccessType(t, numberType) : t));
      expandedTypes.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
      expandedFlags.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
      expandedDeclarations.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
    }
    const tupleTarget = getTupleTargetType(expandedFlags, target.readonly, expandedDeclarations);
    return tupleTarget === emptyGenericType ? emptyObjectType : expandedFlags.length ? createTypeReference(tupleTarget, expandedTypes) : tupleTarget;
    function addElement(type, flags, declaration) {
      if (flags & ElementFlags.Required) {
        lastRequiredIndex = expandedFlags.length;
      }
      if (flags & ElementFlags.Rest && firstRestIndex < 0) {
        firstRestIndex = expandedFlags.length;
      }
      if (flags & (ElementFlags.Optional | ElementFlags.Rest)) {
        lastOptionalOrRestIndex = expandedFlags.length;
      }
      expandedTypes.push(flags & ElementFlags.Optional ? addOptionality(
        type,
        /*isProperty*/
        true
      ) : type);
      expandedFlags.push(flags);
      expandedDeclarations.push(declaration);
    }
  }
  function sliceTupleType(type, index, endSkipCount = 0) {
    const target = type.target;
    const endIndex = getTypeReferenceArity(type) - endSkipCount;
    return index > target.fixedLength ? getRestArrayTypeOfTupleType(type) || createTupleType(emptyArray) : createTupleType(
      getTypeArguments(type).slice(index, endIndex),
      target.elementFlags.slice(index, endIndex),
      /*readonly*/
      false,
      target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex)
    );
  }
  function getKnownKeysOfTupleType(type) {
    return getUnionType(append(arrayOf(type.target.fixedLength, (i) => getStringLiteralType("" + i)), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType)));
  }
  function getStartElementCount(type, flags) {
    const index = findIndex(type.elementFlags, (f) => !(f & flags));
    return index >= 0 ? index : type.elementFlags.length;
  }
  function getEndElementCount(type, flags) {
    return type.elementFlags.length - findLastIndex(type.elementFlags, (f) => !(f & flags)) - 1;
  }
  function getTotalFixedElementCount(type) {
    return type.fixedLength + getEndElementCount(type, ElementFlags.Fixed);
  }
  function getElementTypes(type) {
    const typeArguments = getTypeArguments(type);
    const arity = getTypeReferenceArity(type);
    return typeArguments.length === arity ? typeArguments : typeArguments.slice(0, arity);
  }
  function getTypeFromOptionalTypeNode(node) {
    return addOptionality(
      getTypeFromTypeNode(node.type),
      /*isProperty*/
      true
    );
  }
  function getTypeId(type) {
    return type.id;
  }
  function containsType(types, type) {
    return binarySearch(types, type, getTypeId, compareValues) >= 0;
  }
  function insertType(types, type) {
    const index = binarySearch(types, type, getTypeId, compareValues);
    if (index < 0) {
      types.splice(~index, 0, type);
      return true;
    }
    return false;
  }
  function addTypeToUnion(typeSet, includes, type) {
    const flags = type.flags;
    if (!(flags & TypeFlags.Never)) {
      includes |= flags & TypeFlags.IncludesMask;
      if (flags & TypeFlags.Instantiable) includes |= TypeFlags.IncludesInstantiable;
      if (flags & TypeFlags.Intersection && getObjectFlags(type) & ObjectFlags.IsConstrainedTypeVariable) includes |= TypeFlags.IncludesConstrainedTypeVariable;
      if (type === wildcardType) includes |= TypeFlags.IncludesWildcard;
      if (isErrorType(type)) includes |= TypeFlags.IncludesError;
      if (!strictNullChecks && flags & TypeFlags.Nullable) {
        if (!(getObjectFlags(type) & ObjectFlags.ContainsWideningType)) includes |= TypeFlags.IncludesNonWideningType;
      } else {
        const len = typeSet.length;
        const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearch(typeSet, type, getTypeId, compareValues);
        if (index < 0) {
          typeSet.splice(~index, 0, type);
        }
      }
    }
    return includes;
  }
  function addTypesToUnion(typeSet, includes, types) {
    let lastType;
    for (const type of types) {
      if (type !== lastType) {
        includes = type.flags & TypeFlags.Union ? addTypesToUnion(typeSet, includes | (isNamedUnionType(type) ? TypeFlags.Union : 0), type.types) : addTypeToUnion(typeSet, includes, type);
        lastType = type;
      }
    }
    return includes;
  }
  function removeSubtypes(types, hasObjectTypes) {
    if (types.length < 2) {
      return types;
    }
    const id = getTypeListId(types);
    const match = subtypeReductionCache.get(id);
    if (match) {
      return match;
    }
    const hasEmptyObject = hasObjectTypes && some(types, (t) => !!(t.flags & TypeFlags.Object) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)));
    const len = types.length;
    let i = len;
    let count = 0;
    while (i > 0) {
      i--;
      const source = types[i];
      if (hasEmptyObject || source.flags & TypeFlags.StructuredOrInstantiable) {
        if (source.flags & TypeFlags.TypeParameter && getBaseConstraintOrType(source).flags & TypeFlags.Union) {
          if (isTypeRelatedTo(source, getUnionType(map(types, (t) => t === source ? neverType : t)), strictSubtypeRelation)) {
            orderedRemoveItemAt(types, i);
          }
          continue;
        }
        const keyProperty = source.flags & (TypeFlags.Object | TypeFlags.Intersection | TypeFlags.InstantiableNonPrimitive) ? find(getPropertiesOfType(source), (p) => isUnitType(getTypeOfSymbol(p))) : void 0;
        const keyPropertyType = keyProperty && getRegularTypeOfLiteralType(getTypeOfSymbol(keyProperty));
        for (const target of types) {
          if (source !== target) {
            if (count === 1e5) {
              const estimatedCount = count / (len - i) * len;
              if (estimatedCount > 1e6) {
                tracing?.instant(tracing.Phase.CheckTypes, "removeSubtypes_DepthLimit", { typeIds: types.map((t) => t.id) });
                error(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
                return void 0;
              }
            }
            count++;
            if (keyProperty && target.flags & (TypeFlags.Object | TypeFlags.Intersection | TypeFlags.InstantiableNonPrimitive)) {
              const t = getTypeOfPropertyOfType(target, keyProperty.escapedName);
              if (t && isUnitType(t) && getRegularTypeOfLiteralType(t) !== keyPropertyType) {
                continue;
              }
            }
            if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(getObjectFlags(getTargetType(source)) & ObjectFlags.Class) || !(getObjectFlags(getTargetType(target)) & ObjectFlags.Class) || isTypeDerivedFrom(source, target))) {
              orderedRemoveItemAt(types, i);
              break;
            }
          }
        }
      }
    }
    subtypeReductionCache.set(id, types);
    return types;
  }
  function removeRedundantLiteralTypes(types, includes, reduceVoidUndefined) {
    let i = types.length;
    while (i > 0) {
      i--;
      const t = types[i];
      const flags = t.flags;
      const remove = flags & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) && includes & TypeFlags.String || flags & TypeFlags.NumberLiteral && includes & TypeFlags.Number || flags & TypeFlags.BigIntLiteral && includes & TypeFlags.BigInt || flags & TypeFlags.UniqueESSymbol && includes & TypeFlags.ESSymbol || reduceVoidUndefined && flags & TypeFlags.Undefined && includes & TypeFlags.Void || isFreshLiteralType(t) && containsType(types, t.regularType);
      if (remove) {
        orderedRemoveItemAt(types, i);
      }
    }
  }
  function removeStringLiteralsMatchedByTemplateLiterals(types) {
    const templates = filter(types, isPatternLiteralType);
    if (templates.length) {
      let i = types.length;
      while (i > 0) {
        i--;
        const t = types[i];
        if (t.flags & TypeFlags.StringLiteral && some(templates, (template) => isTypeMatchedByTemplateLiteralOrStringMapping(t, template))) {
          orderedRemoveItemAt(types, i);
        }
      }
    }
  }
  function isTypeMatchedByTemplateLiteralOrStringMapping(type, template) {
    return template.flags & TypeFlags.TemplateLiteral ? isTypeMatchedByTemplateLiteralType(type, template) : isMemberOfStringMapping(type, template);
  }
  function removeConstrainedTypeVariables(types) {
    const typeVariables = [];
    for (const type of types) {
      if (type.flags & TypeFlags.Intersection && getObjectFlags(type) & ObjectFlags.IsConstrainedTypeVariable) {
        const index = type.types[0].flags & TypeFlags.TypeVariable ? 0 : 1;
        pushIfUnique(typeVariables, type.types[index]);
      }
    }
    for (const typeVariable of typeVariables) {
      const primitives = [];
      for (const type of types) {
        if (type.flags & TypeFlags.Intersection && getObjectFlags(type) & ObjectFlags.IsConstrainedTypeVariable) {
          const index = type.types[0].flags & TypeFlags.TypeVariable ? 0 : 1;
          if (type.types[index] === typeVariable) {
            insertType(primitives, type.types[1 - index]);
          }
        }
      }
      const constraint = getBaseConstraintOfType(typeVariable);
      if (everyType(constraint, (t) => containsType(primitives, t))) {
        let i = types.length;
        while (i > 0) {
          i--;
          const type = types[i];
          if (type.flags & TypeFlags.Intersection && getObjectFlags(type) & ObjectFlags.IsConstrainedTypeVariable) {
            const index = type.types[0].flags & TypeFlags.TypeVariable ? 0 : 1;
            if (type.types[index] === typeVariable && containsType(primitives, type.types[1 - index])) {
              orderedRemoveItemAt(types, i);
            }
          }
        }
        insertType(types, typeVariable);
      }
    }
  }
  function isNamedUnionType(type) {
    return !!(type.flags & TypeFlags.Union && (type.aliasSymbol || type.origin));
  }
  function addNamedUnions(namedUnions, types) {
    for (const t of types) {
      if (t.flags & TypeFlags.Union) {
        const origin = t.origin;
        if (t.aliasSymbol || origin && !(origin.flags & TypeFlags.Union)) {
          pushIfUnique(namedUnions, t);
        } else if (origin && origin.flags & TypeFlags.Union) {
          addNamedUnions(namedUnions, origin.types);
        }
      }
    }
  }
  function createOriginUnionOrIntersectionType(flags, types) {
    const result = createOriginType(flags);
    result.types = types;
    return result;
  }
  function getUnionType(types, unionReduction = UnionReduction.Literal, aliasSymbol, aliasTypeArguments, origin) {
    if (types.length === 0) {
      return neverType;
    }
    if (types.length === 1) {
      return types[0];
    }
    if (types.length === 2 && !origin && (types[0].flags & TypeFlags.Union || types[1].flags & TypeFlags.Union)) {
      const infix = unionReduction === UnionReduction.None ? "N" : unionReduction === UnionReduction.Subtype ? "S" : "L";
      const index = types[0].id < types[1].id ? 0 : 1;
      const id = types[index].id + infix + types[1 - index].id + getAliasId(aliasSymbol, aliasTypeArguments);
      let type = unionOfUnionTypes.get(id);
      if (!type) {
        type = getUnionTypeWorker(
          types,
          unionReduction,
          aliasSymbol,
          aliasTypeArguments,
          /*origin*/
          void 0
        );
        unionOfUnionTypes.set(id, type);
      }
      return type;
    }
    return getUnionTypeWorker(types, unionReduction, aliasSymbol, aliasTypeArguments, origin);
  }
  function getUnionTypeWorker(types, unionReduction, aliasSymbol, aliasTypeArguments, origin) {
    let typeSet = [];
    const includes = addTypesToUnion(typeSet, 0, types);
    if (unionReduction !== UnionReduction.None) {
      if (includes & TypeFlags.AnyOrUnknown) {
        return includes & TypeFlags.Any ? includes & TypeFlags.IncludesWildcard ? wildcardType : includes & TypeFlags.IncludesError ? errorType : anyType : unknownType;
      }
      if (includes & TypeFlags.Undefined) {
        if (typeSet.length >= 2 && typeSet[0] === undefinedType && typeSet[1] === missingType) {
          orderedRemoveItemAt(typeSet, 1);
        }
      }
      if (includes & (TypeFlags.Enum | TypeFlags.Literal | TypeFlags.UniqueESSymbol | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) || includes & TypeFlags.Void && includes & TypeFlags.Undefined) {
        removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & UnionReduction.Subtype));
      }
      if (includes & TypeFlags.StringLiteral && includes & (TypeFlags.TemplateLiteral | TypeFlags.StringMapping)) {
        removeStringLiteralsMatchedByTemplateLiterals(typeSet);
      }
      if (includes & TypeFlags.IncludesConstrainedTypeVariable) {
        removeConstrainedTypeVariables(typeSet);
      }
      if (unionReduction === UnionReduction.Subtype) {
        typeSet = removeSubtypes(typeSet, !!(includes & TypeFlags.Object));
        if (!typeSet) {
          return errorType;
        }
      }
      if (typeSet.length === 0) {
        return includes & TypeFlags.Null ? includes & TypeFlags.IncludesNonWideningType ? nullType : nullWideningType : includes & TypeFlags.Undefined ? includes & TypeFlags.IncludesNonWideningType ? undefinedType : undefinedWideningType : neverType;
      }
    }
    if (!origin && includes & TypeFlags.Union) {
      const namedUnions = [];
      addNamedUnions(namedUnions, types);
      const reducedTypes = [];
      for (const t of typeSet) {
        if (!some(namedUnions, (union) => containsType(union.types, t))) {
          reducedTypes.push(t);
        }
      }
      if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) {
        return namedUnions[0];
      }
      const namedTypesCount = reduceLeft(namedUnions, (sum, union) => sum + union.types.length, 0);
      if (namedTypesCount + reducedTypes.length === typeSet.length) {
        for (const t of namedUnions) {
          insertType(reducedTypes, t);
        }
        origin = createOriginUnionOrIntersectionType(TypeFlags.Union, reducedTypes);
      }
    }
    const objectFlags = (includes & TypeFlags.NotPrimitiveUnion ? 0 : ObjectFlags.PrimitiveUnion) | (includes & TypeFlags.Intersection ? ObjectFlags.ContainsIntersections : 0);
    return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin);
  }
  function getUnionOrIntersectionTypePredicate(signatures, kind) {
    let last2;
    const types = [];
    for (const sig of signatures) {
      const pred = getTypePredicateOfSignature(sig);
      if (pred) {
        if (pred.kind !== TypePredicateKind.This && pred.kind !== TypePredicateKind.Identifier || last2 && !typePredicateKindsMatch(last2, pred)) {
          return void 0;
        }
        last2 = pred;
        types.push(pred.type);
      } else {
        const returnType = kind !== TypeFlags.Intersection ? getReturnTypeOfSignature(sig) : void 0;
        if (returnType !== falseType && returnType !== regularFalseType) {
          return void 0;
        }
      }
    }
    if (!last2) {
      return void 0;
    }
    const compositeType = getUnionOrIntersectionType(types, kind);
    return createTypePredicate(last2.kind, last2.parameterName, last2.parameterIndex, compositeType);
  }
  function typePredicateKindsMatch(a, b) {
    return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
  }
  function getUnionTypeFromSortedList(types, precomputedObjectFlags, aliasSymbol, aliasTypeArguments, origin) {
    if (types.length === 0) {
      return neverType;
    }
    if (types.length === 1) {
      return types[0];
    }
    const typeKey = !origin ? getTypeListId(types) : origin.flags & TypeFlags.Union ? `|${getTypeListId(origin.types)}` : origin.flags & TypeFlags.Intersection ? `&${getTypeListId(origin.types)}` : `#${origin.type.id}|${getTypeListId(types)}`;
    const id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments);
    let type = unionTypes.get(id);
    if (!type) {
      type = createType(TypeFlags.Union);
      type.objectFlags = precomputedObjectFlags | getPropagatingFlagsOfTypes(
        types,
        /*excludeKinds*/
        TypeFlags.Nullable
      );
      type.types = types;
      type.origin = origin;
      type.aliasSymbol = aliasSymbol;
      type.aliasTypeArguments = aliasTypeArguments;
      if (types.length === 2 && types[0].flags & TypeFlags.BooleanLiteral && types[1].flags & TypeFlags.BooleanLiteral) {
        type.flags |= TypeFlags.Boolean;
        type.intrinsicName = "boolean";
      }
      unionTypes.set(id, type);
    }
    return type;
  }
  function getTypeFromUnionTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const aliasSymbol = getAliasSymbolForTypeNode(node);
      links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), UnionReduction.Literal, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
    }
    return links.resolvedType;
  }
  function addTypeToIntersection(typeSet, includes, type) {
    const flags = type.flags;
    if (flags & TypeFlags.Intersection) {
      return addTypesToIntersection(typeSet, includes, type.types);
    }
    if (isEmptyAnonymousObjectType(type)) {
      if (!(includes & TypeFlags.IncludesEmptyObject)) {
        includes |= TypeFlags.IncludesEmptyObject;
        typeSet.set(type.id.toString(), type);
      }
    } else {
      if (flags & TypeFlags.AnyOrUnknown) {
        if (type === wildcardType) includes |= TypeFlags.IncludesWildcard;
        if (isErrorType(type)) includes |= TypeFlags.IncludesError;
      } else if (strictNullChecks || !(flags & TypeFlags.Nullable)) {
        if (type === missingType) {
          includes |= TypeFlags.IncludesMissingType;
          type = undefinedType;
        }
        if (!typeSet.has(type.id.toString())) {
          if (type.flags & TypeFlags.Unit && includes & TypeFlags.Unit) {
            includes |= TypeFlags.NonPrimitive;
          }
          typeSet.set(type.id.toString(), type);
        }
      }
      includes |= flags & TypeFlags.IncludesMask;
    }
    return includes;
  }
  function addTypesToIntersection(typeSet, includes, types) {
    for (const type of types) {
      includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
    }
    return includes;
  }
  function removeRedundantSupertypes(types, includes) {
    let i = types.length;
    while (i > 0) {
      i--;
      const t = types[i];
      const remove = t.flags & TypeFlags.String && includes & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) || t.flags & TypeFlags.Number && includes & TypeFlags.NumberLiteral || t.flags & TypeFlags.BigInt && includes & TypeFlags.BigIntLiteral || t.flags & TypeFlags.ESSymbol && includes & TypeFlags.UniqueESSymbol || t.flags & TypeFlags.Void && includes & TypeFlags.Undefined || isEmptyAnonymousObjectType(t) && includes & TypeFlags.DefinitelyNonNullable;
      if (remove) {
        orderedRemoveItemAt(types, i);
      }
    }
  }
  function eachUnionContains(unionTypes2, type) {
    for (const u of unionTypes2) {
      if (!containsType(u.types, type)) {
        if (type === missingType) {
          return containsType(u.types, undefinedType);
        }
        if (type === undefinedType) {
          return containsType(u.types, missingType);
        }
        const primitive = type.flags & TypeFlags.StringLiteral ? stringType : type.flags & (TypeFlags.Enum | TypeFlags.NumberLiteral) ? numberType : type.flags & TypeFlags.BigIntLiteral ? bigintType : type.flags & TypeFlags.UniqueESSymbol ? esSymbolType : void 0;
        if (!primitive || !containsType(u.types, primitive)) {
          return false;
        }
      }
    }
    return true;
  }
  function extractRedundantTemplateLiterals(types) {
    let i = types.length;
    const literals = filter(types, (t) => !!(t.flags & TypeFlags.StringLiteral));
    while (i > 0) {
      i--;
      const t = types[i];
      if (!(t.flags & (TypeFlags.TemplateLiteral | TypeFlags.StringMapping))) continue;
      for (const t2 of literals) {
        if (isTypeSubtypeOf(t2, t)) {
          orderedRemoveItemAt(types, i);
          break;
        } else if (isPatternLiteralType(t)) {
          return true;
        }
      }
    }
    return false;
  }
  function removeFromEach(types, flag) {
    for (let i = 0; i < types.length; i++) {
      types[i] = filterType(types[i], (t) => !(t.flags & flag));
    }
  }
  function intersectUnionsOfPrimitiveTypes(types) {
    let unionTypes2;
    const index = findIndex(types, (t) => !!(getObjectFlags(t) & ObjectFlags.PrimitiveUnion));
    if (index < 0) {
      return false;
    }
    let i = index + 1;
    while (i < types.length) {
      const t = types[i];
      if (getObjectFlags(t) & ObjectFlags.PrimitiveUnion) {
        (unionTypes2 || (unionTypes2 = [types[index]])).push(t);
        orderedRemoveItemAt(types, i);
      } else {
        i++;
      }
    }
    if (!unionTypes2) {
      return false;
    }
    const checked = [];
    const result = [];
    for (const u of unionTypes2) {
      for (const t of u.types) {
        if (insertType(checked, t)) {
          if (eachUnionContains(unionTypes2, t)) {
            if (t === undefinedType && result.length && result[0] === missingType) {
              continue;
            }
            if (t === missingType && result.length && result[0] === undefinedType) {
              result[0] = missingType;
              continue;
            }
            insertType(result, t);
          }
        }
      }
    }
    types[index] = getUnionTypeFromSortedList(result, ObjectFlags.PrimitiveUnion);
    return true;
  }
  function createIntersectionType(types, objectFlags, aliasSymbol, aliasTypeArguments) {
    const result = createType(TypeFlags.Intersection);
    result.objectFlags = objectFlags | getPropagatingFlagsOfTypes(
      types,
      /*excludeKinds*/
      TypeFlags.Nullable
    );
    result.types = types;
    result.aliasSymbol = aliasSymbol;
    result.aliasTypeArguments = aliasTypeArguments;
    return result;
  }
  function getIntersectionType(types, flags = IntersectionFlags.None, aliasSymbol, aliasTypeArguments) {
    const typeMembershipMap = /* @__PURE__ */ new Map();
    const includes = addTypesToIntersection(typeMembershipMap, 0, types);
    const typeSet = arrayFrom(typeMembershipMap.values());
    let objectFlags = ObjectFlags.None;
    if (includes & TypeFlags.Never) {
      return contains(typeSet, silentNeverType) ? silentNeverType : neverType;
    }
    if (strictNullChecks && includes & TypeFlags.Nullable && includes & (TypeFlags.Object | TypeFlags.NonPrimitive | TypeFlags.IncludesEmptyObject) || includes & TypeFlags.NonPrimitive && includes & (TypeFlags.DisjointDomains & ~TypeFlags.NonPrimitive) || includes & TypeFlags.StringLike && includes & (TypeFlags.DisjointDomains & ~TypeFlags.StringLike) || includes & TypeFlags.NumberLike && includes & (TypeFlags.DisjointDomains & ~TypeFlags.NumberLike) || includes & TypeFlags.BigIntLike && includes & (TypeFlags.DisjointDomains & ~TypeFlags.BigIntLike) || includes & TypeFlags.ESSymbolLike && includes & (TypeFlags.DisjointDomains & ~TypeFlags.ESSymbolLike) || includes & TypeFlags.VoidLike && includes & (TypeFlags.DisjointDomains & ~TypeFlags.VoidLike)) {
      return neverType;
    }
    if (includes & (TypeFlags.TemplateLiteral | TypeFlags.StringMapping) && includes & TypeFlags.StringLiteral && extractRedundantTemplateLiterals(typeSet)) {
      return neverType;
    }
    if (includes & TypeFlags.Any) {
      return includes & TypeFlags.IncludesWildcard ? wildcardType : includes & TypeFlags.IncludesError ? errorType : anyType;
    }
    if (!strictNullChecks && includes & TypeFlags.Nullable) {
      return includes & TypeFlags.IncludesEmptyObject ? neverType : includes & TypeFlags.Undefined ? undefinedType : nullType;
    }
    if (includes & TypeFlags.String && includes & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) || includes & TypeFlags.Number && includes & TypeFlags.NumberLiteral || includes & TypeFlags.BigInt && includes & TypeFlags.BigIntLiteral || includes & TypeFlags.ESSymbol && includes & TypeFlags.UniqueESSymbol || includes & TypeFlags.Void && includes & TypeFlags.Undefined || includes & TypeFlags.IncludesEmptyObject && includes & TypeFlags.DefinitelyNonNullable) {
      if (!(flags & IntersectionFlags.NoSupertypeReduction)) removeRedundantSupertypes(typeSet, includes);
    }
    if (includes & TypeFlags.IncludesMissingType) {
      typeSet[typeSet.indexOf(undefinedType)] = missingType;
    }
    if (typeSet.length === 0) {
      return unknownType;
    }
    if (typeSet.length === 1) {
      return typeSet[0];
    }
    if (typeSet.length === 2 && !(flags & IntersectionFlags.NoConstraintReduction)) {
      const typeVarIndex = typeSet[0].flags & TypeFlags.TypeVariable ? 0 : 1;
      const typeVariable = typeSet[typeVarIndex];
      const primitiveType = typeSet[1 - typeVarIndex];
      if (typeVariable.flags & TypeFlags.TypeVariable && (primitiveType.flags & (TypeFlags.Primitive | TypeFlags.NonPrimitive) && !isGenericStringLikeType(primitiveType) || includes & TypeFlags.IncludesEmptyObject)) {
        const constraint = getBaseConstraintOfType(typeVariable);
        if (constraint && everyType(constraint, (t) => !!(t.flags & (TypeFlags.Primitive | TypeFlags.NonPrimitive)) || isEmptyAnonymousObjectType(t))) {
          if (isTypeStrictSubtypeOf(constraint, primitiveType)) {
            return typeVariable;
          }
          if (!(constraint.flags & TypeFlags.Union && someType(constraint, (c) => isTypeStrictSubtypeOf(c, primitiveType)))) {
            if (!isTypeStrictSubtypeOf(primitiveType, constraint)) {
              return neverType;
            }
          }
          objectFlags = ObjectFlags.IsConstrainedTypeVariable;
        }
      }
    }
    const id = getTypeListId(typeSet) + (flags & IntersectionFlags.NoConstraintReduction ? "*" : getAliasId(aliasSymbol, aliasTypeArguments));
    let result = intersectionTypes.get(id);
    if (!result) {
      if (includes & TypeFlags.Union) {
        if (intersectUnionsOfPrimitiveTypes(typeSet)) {
          result = getIntersectionType(typeSet, flags, aliasSymbol, aliasTypeArguments);
        } else if (every(typeSet, (t) => !!(t.flags & TypeFlags.Union && t.types[0].flags & TypeFlags.Undefined))) {
          const containedUndefinedType = some(typeSet, containsMissingType) ? missingType : undefinedType;
          removeFromEach(typeSet, TypeFlags.Undefined);
          result = getUnionType([getIntersectionType(typeSet, flags), containedUndefinedType], UnionReduction.Literal, aliasSymbol, aliasTypeArguments);
        } else if (every(typeSet, (t) => !!(t.flags & TypeFlags.Union && (t.types[0].flags & TypeFlags.Null || t.types[1].flags & TypeFlags.Null)))) {
          removeFromEach(typeSet, TypeFlags.Null);
          result = getUnionType([getIntersectionType(typeSet, flags), nullType], UnionReduction.Literal, aliasSymbol, aliasTypeArguments);
        } else if (typeSet.length >= 3 && types.length > 2) {
          const middle = Math.floor(typeSet.length / 2);
          result = getIntersectionType([getIntersectionType(typeSet.slice(0, middle), flags), getIntersectionType(typeSet.slice(middle), flags)], flags, aliasSymbol, aliasTypeArguments);
        } else {
          if (!checkCrossProductUnion(typeSet)) {
            return errorType;
          }
          const constituents = getCrossProductIntersections(typeSet, flags);
          const origin = some(constituents, (t) => !!(t.flags & TypeFlags.Intersection)) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(TypeFlags.Intersection, typeSet) : void 0;
          result = getUnionType(constituents, UnionReduction.Literal, aliasSymbol, aliasTypeArguments, origin);
        }
      } else {
        result = createIntersectionType(typeSet, objectFlags, aliasSymbol, aliasTypeArguments);
      }
      intersectionTypes.set(id, result);
    }
    return result;
  }
  function getCrossProductUnionSize(types) {
    return reduceLeft(types, (n, t) => t.flags & TypeFlags.Union ? n * t.types.length : t.flags & TypeFlags.Never ? 0 : n, 1);
  }
  function checkCrossProductUnion(types) {
    const size = getCrossProductUnionSize(types);
    if (size >= 1e5) {
      tracing?.instant(tracing.Phase.CheckTypes, "checkCrossProductUnion_DepthLimit", { typeIds: types.map((t) => t.id), size });
      error(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
      return false;
    }
    return true;
  }
  function getCrossProductIntersections(types, flags) {
    const count = getCrossProductUnionSize(types);
    const intersections = [];
    for (let i = 0; i < count; i++) {
      const constituents = types.slice();
      let n = i;
      for (let j = types.length - 1; j >= 0; j--) {
        if (types[j].flags & TypeFlags.Union) {
          const sourceTypes = types[j].types;
          const length2 = sourceTypes.length;
          constituents[j] = sourceTypes[n % length2];
          n = Math.floor(n / length2);
        }
      }
      const t = getIntersectionType(constituents, flags);
      if (!(t.flags & TypeFlags.Never)) intersections.push(t);
    }
    return intersections;
  }
  function getConstituentCount(type) {
    return !(type.flags & TypeFlags.UnionOrIntersection) || type.aliasSymbol ? 1 : type.flags & TypeFlags.Union && type.origin ? getConstituentCount(type.origin) : getConstituentCountOfTypes(type.types);
  }
  function getConstituentCountOfTypes(types) {
    return reduceLeft(types, (n, t) => n + getConstituentCount(t), 0);
  }
  function getTypeFromIntersectionTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const aliasSymbol = getAliasSymbolForTypeNode(node);
      const types = map(node.types, getTypeFromTypeNode);
      const emptyIndex = types.length === 2 ? types.indexOf(emptyTypeLiteralType) : -1;
      const t = emptyIndex >= 0 ? types[1 - emptyIndex] : unknownType;
      const noSupertypeReduction = !!(t.flags & (TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt) || t.flags & TypeFlags.TemplateLiteral && isPatternLiteralType(t));
      links.resolvedType = getIntersectionType(types, noSupertypeReduction ? IntersectionFlags.NoSupertypeReduction : 0, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
    }
    return links.resolvedType;
  }
  function createIndexType(type, indexFlags) {
    const result = createType(TypeFlags.Index);
    result.type = type;
    result.indexFlags = indexFlags;
    return result;
  }
  function createOriginIndexType(type) {
    const result = createOriginType(TypeFlags.Index);
    result.type = type;
    return result;
  }
  function getIndexTypeForGenericType(type, indexFlags) {
    return indexFlags & IndexFlags.StringsOnly ? type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, IndexFlags.StringsOnly)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, IndexFlags.None));
  }
  function getIndexTypeForMappedType(type, indexFlags) {
    const typeParameter = getTypeParameterFromMappedType(type);
    const constraintType = getConstraintTypeFromMappedType(type);
    const nameType = getNameTypeFromMappedType(type.target || type);
    if (!nameType && !(indexFlags & IndexFlags.NoIndexSignatures)) {
      return constraintType;
    }
    const keyTypes = [];
    if (isGenericIndexType(constraintType)) {
      if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
        return getIndexTypeForGenericType(type, indexFlags);
      }
      forEachType(constraintType, addMemberForKeyType);
    } else if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
      const modifiersType = getApparentType(getModifiersTypeFromMappedType(type));
      forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(modifiersType, TypeFlags.StringOrNumberLiteralOrUnique, !!(indexFlags & IndexFlags.StringsOnly), addMemberForKeyType);
    } else {
      forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
    }
    const result = indexFlags & IndexFlags.NoIndexSignatures ? filterType(getUnionType(keyTypes), (t) => !(t.flags & (TypeFlags.Any | TypeFlags.String))) : getUnionType(keyTypes);
    if (result.flags & TypeFlags.Union && constraintType.flags & TypeFlags.Union && getTypeListId(result.types) === getTypeListId(constraintType.types)) {
      return constraintType;
    }
    return result;
    function addMemberForKeyType(keyType) {
      const propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType;
      keyTypes.push(propNameType === stringType ? stringOrNumberType : propNameType);
    }
  }
  function hasDistributiveNameType(mappedType) {
    const typeVariable = getTypeParameterFromMappedType(mappedType);
    return isDistributive(getNameTypeFromMappedType(mappedType) || typeVariable);
    function isDistributive(type) {
      return type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Primitive | TypeFlags.Never | TypeFlags.TypeParameter | TypeFlags.Object | TypeFlags.NonPrimitive) ? true : type.flags & TypeFlags.Conditional ? type.root.isDistributive && type.checkType === typeVariable : type.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral) ? every(type.types, isDistributive) : type.flags & TypeFlags.IndexedAccess ? isDistributive(type.objectType) && isDistributive(type.indexType) : type.flags & TypeFlags.Substitution ? isDistributive(type.baseType) && isDistributive(type.constraint) : type.flags & TypeFlags.StringMapping ? isDistributive(type.type) : false;
    }
  }
  function getLiteralTypeFromPropertyName(name) {
    if (isPrivateIdentifier(name)) {
      return neverType;
    }
    if (isNumericLiteral(name)) {
      return getRegularTypeOfLiteralType(checkExpression(name));
    }
    if (isComputedPropertyName(name)) {
      return getRegularTypeOfLiteralType(checkComputedPropertyName(name));
    }
    const propertyName = getPropertyNameForPropertyNameNode(name);
    if (propertyName !== void 0) {
      return getStringLiteralType(unescapeLeadingUnderscores(propertyName));
    }
    if (isExpression(name)) {
      return getRegularTypeOfLiteralType(checkExpression(name));
    }
    return neverType;
  }
  function getLiteralTypeFromProperty(prop, include, includeNonPublic) {
    if (includeNonPublic || !(getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier)) {
      let type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
      if (!type) {
        const name = getNameOfDeclaration(prop.valueDeclaration);
        type = prop.escapedName === InternalSymbolName.Default ? getStringLiteralType("default") : name && getLiteralTypeFromPropertyName(name) || (!isKnownSymbol(prop) ? getStringLiteralType(symbolName(prop)) : void 0);
      }
      if (type && type.flags & include) {
        return type;
      }
    }
    return neverType;
  }
  function isKeyTypeIncluded(keyType, include) {
    return !!(keyType.flags & include || keyType.flags & TypeFlags.Intersection && some(keyType.types, (t) => isKeyTypeIncluded(t, include)));
  }
  function getLiteralTypeFromProperties(type, include, includeOrigin) {
    const origin = includeOrigin && (getObjectFlags(type) & (ObjectFlags.ClassOrInterface | ObjectFlags.Reference) || type.aliasSymbol) ? createOriginIndexType(type) : void 0;
    const propertyTypes = map(getPropertiesOfType(type), (prop) => getLiteralTypeFromProperty(prop, include));
    const indexKeyTypes = map(getIndexInfosOfType(type), (info) => info !== enumNumberIndexInfo && isKeyTypeIncluded(info.keyType, include) ? info.keyType === stringType && include & TypeFlags.Number ? stringOrNumberType : info.keyType : neverType);
    return getUnionType(
      concatenate(propertyTypes, indexKeyTypes),
      UnionReduction.Literal,
      /*aliasSymbol*/
      void 0,
      /*aliasTypeArguments*/
      void 0,
      origin
    );
  }
  function shouldDeferIndexType(type, indexFlags = IndexFlags.None) {
    return !!(type.flags & TypeFlags.InstantiableNonPrimitive || isGenericTupleType(type) || isGenericMappedType(type) && (!hasDistributiveNameType(type) || getMappedTypeNameTypeKind(type) === 2 /* Remapping */) || type.flags & TypeFlags.Union && !(indexFlags & IndexFlags.NoReducibleCheck) && isGenericReducibleType(type) || type.flags & TypeFlags.Intersection && maybeTypeOfKind(type, TypeFlags.Instantiable) && some(type.types, isEmptyAnonymousObjectType));
  }
  function getIndexType(type, indexFlags = IndexFlags.None) {
    type = getReducedType(type);
    return isNoInferType(type) ? getNoInferType(getIndexType(type.baseType, indexFlags)) : shouldDeferIndexType(type, indexFlags) ? getIndexTypeForGenericType(type, indexFlags) : type.flags & TypeFlags.Union ? getIntersectionType(map(type.types, (t) => getIndexType(t, indexFlags))) : type.flags & TypeFlags.Intersection ? getUnionType(map(type.types, (t) => getIndexType(t, indexFlags))) : getObjectFlags(type) & ObjectFlags.Mapped ? getIndexTypeForMappedType(type, indexFlags) : type === wildcardType ? wildcardType : type.flags & TypeFlags.Unknown ? neverType : type.flags & (TypeFlags.Any | TypeFlags.Never) ? stringNumberSymbolType : getLiteralTypeFromProperties(type, (indexFlags & IndexFlags.NoIndexSignatures ? TypeFlags.StringLiteral : TypeFlags.StringLike) | (indexFlags & IndexFlags.StringsOnly ? 0 : TypeFlags.NumberLike | TypeFlags.ESSymbolLike), indexFlags === IndexFlags.None);
  }
  function getExtractStringType(type) {
    const extractTypeAlias = getGlobalExtractSymbol();
    return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
  }
  function getIndexTypeOrString(type) {
    const indexType = getExtractStringType(getIndexType(type));
    return indexType.flags & TypeFlags.Never ? stringType : indexType;
  }
  function getTypeFromTypeOperatorNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      switch (node.operator) {
        case SyntaxKind.KeyOfKeyword:
          links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
          break;
        case SyntaxKind.UniqueKeyword:
          links.resolvedType = node.type.kind === SyntaxKind.SymbolKeyword ? getESSymbolLikeTypeForNode(walkUpParenthesizedTypes(node.parent)) : errorType;
          break;
        case SyntaxKind.ReadonlyKeyword:
          links.resolvedType = getTypeFromTypeNode(node.type);
          break;
        default:
          Debug.assertNever(node.operator);
      }
    }
    return links.resolvedType;
  }
  function getTypeFromTemplateTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      links.resolvedType = getTemplateLiteralType(
        [node.head.text, ...map(node.templateSpans, (span) => span.literal.text)],
        map(node.templateSpans, (span) => getTypeFromTypeNode(span.type))
      );
    }
    return links.resolvedType;
  }
  function getTemplateLiteralType(texts, types) {
    const unionIndex = findIndex(types, (t) => !!(t.flags & (TypeFlags.Never | TypeFlags.Union)));
    if (unionIndex >= 0) {
      return checkCrossProductUnion(types) ? mapType(types[unionIndex], (t) => getTemplateLiteralType(texts, replaceElement(types, unionIndex, t))) : errorType;
    }
    if (contains(types, wildcardType)) {
      return wildcardType;
    }
    const newTypes = [];
    const newTexts = [];
    let text = texts[0];
    if (!addSpans(texts, types)) {
      return stringType;
    }
    if (newTypes.length === 0) {
      return getStringLiteralType(text);
    }
    newTexts.push(text);
    if (every(newTexts, (t) => t === "")) {
      if (every(newTypes, (t) => !!(t.flags & TypeFlags.String))) {
        return stringType;
      }
      if (newTypes.length === 1 && isPatternLiteralType(newTypes[0])) {
        return newTypes[0];
      }
    }
    const id = `${getTypeListId(newTypes)}|${map(newTexts, (t) => t.length).join(",")}|${newTexts.join("")}`;
    let type = templateLiteralTypes.get(id);
    if (!type) {
      templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes));
    }
    return type;
    function addSpans(texts2, types2) {
      for (let i = 0; i < types2.length; i++) {
        const t = types2[i];
        if (t.flags & (TypeFlags.Literal | TypeFlags.Null | TypeFlags.Undefined)) {
          text += getTemplateStringForType(t) || "";
          text += texts2[i + 1];
        } else if (t.flags & TypeFlags.TemplateLiteral) {
          text += t.texts[0];
          if (!addSpans(t.texts, t.types)) return false;
          text += texts2[i + 1];
        } else if (isGenericIndexType(t) || isPatternLiteralPlaceholderType(t)) {
          newTypes.push(t);
          newTexts.push(text);
          text = texts2[i + 1];
        } else {
          return false;
        }
      }
      return true;
    }
  }
  function getTemplateStringForType(type) {
    return type.flags & TypeFlags.StringLiteral ? type.value : type.flags & TypeFlags.NumberLiteral ? "" + type.value : type.flags & TypeFlags.BigIntLiteral ? pseudoBigIntToString(type.value) : type.flags & (TypeFlags.BooleanLiteral | TypeFlags.Nullable) ? type.intrinsicName : void 0;
  }
  function createTemplateLiteralType(texts, types) {
    const type = createType(TypeFlags.TemplateLiteral);
    type.texts = texts;
    type.types = types;
    return type;
  }
  function getStringMappingType(symbol, type) {
    return type.flags & (TypeFlags.Union | TypeFlags.Never) ? mapType(type, (t) => getStringMappingType(symbol, t)) : type.flags & TypeFlags.StringLiteral ? getStringLiteralType(applyStringMapping(symbol, type.value)) : type.flags & TypeFlags.TemplateLiteral ? getTemplateLiteralType(...applyTemplateStringMapping(symbol, type.texts, type.types)) : (
      // Mapping<Mapping<T>> === Mapping<T>
      type.flags & TypeFlags.StringMapping && symbol === type.symbol ? type : type.flags & (TypeFlags.Any | TypeFlags.String | TypeFlags.StringMapping) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : (
        // This handles Mapping<`${number}`> and Mapping<`${bigint}`>
        isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : type
      )
    );
  }
  function applyStringMapping(symbol, str) {
    switch (intrinsicTypeKinds.get(symbol.escapedName)) {
      case 0 /* Uppercase */:
        return str.toUpperCase();
      case 1 /* Lowercase */:
        return str.toLowerCase();
      case 2 /* Capitalize */:
        return str.charAt(0).toUpperCase() + str.slice(1);
      case 3 /* Uncapitalize */:
        return str.charAt(0).toLowerCase() + str.slice(1);
    }
    return str;
  }
  function applyTemplateStringMapping(symbol, texts, types) {
    switch (intrinsicTypeKinds.get(symbol.escapedName)) {
      case 0 /* Uppercase */:
        return [texts.map((t) => t.toUpperCase()), types.map((t) => getStringMappingType(symbol, t))];
      case 1 /* Lowercase */:
        return [texts.map((t) => t.toLowerCase()), types.map((t) => getStringMappingType(symbol, t))];
      case 2 /* Capitalize */:
        return [texts[0] === "" ? texts : [texts[0].charAt(0).toUpperCase() + texts[0].slice(1), ...texts.slice(1)], texts[0] === "" ? [getStringMappingType(symbol, types[0]), ...types.slice(1)] : types];
      case 3 /* Uncapitalize */:
        return [texts[0] === "" ? texts : [texts[0].charAt(0).toLowerCase() + texts[0].slice(1), ...texts.slice(1)], texts[0] === "" ? [getStringMappingType(symbol, types[0]), ...types.slice(1)] : types];
    }
    return [texts, types];
  }
  function getStringMappingTypeForGenericType(symbol, type) {
    const id = `${getSymbolId(symbol)},${getTypeId(type)}`;
    let result = stringMappingTypes.get(id);
    if (!result) {
      stringMappingTypes.set(id, result = createStringMappingType(symbol, type));
    }
    return result;
  }
  function createStringMappingType(symbol, type) {
    const result = createTypeWithSymbol(TypeFlags.StringMapping, symbol);
    result.type = type;
    return result;
  }
  function createIndexedAccessType(objectType, indexType, accessFlags, aliasSymbol, aliasTypeArguments) {
    const type = createType(TypeFlags.IndexedAccess);
    type.objectType = objectType;
    type.indexType = indexType;
    type.accessFlags = accessFlags;
    type.aliasSymbol = aliasSymbol;
    type.aliasTypeArguments = aliasTypeArguments;
    return type;
  }
  function isJSLiteralType(type) {
    if (noImplicitAny) {
      return false;
    }
    if (getObjectFlags(type) & ObjectFlags.JSLiteral) {
      return true;
    }
    if (type.flags & TypeFlags.Union) {
      return every(type.types, isJSLiteralType);
    }
    if (type.flags & TypeFlags.Intersection) {
      return some(type.types, isJSLiteralType);
    }
    if (type.flags & TypeFlags.Instantiable) {
      const constraint = getResolvedBaseConstraint(type);
      return constraint !== type && isJSLiteralType(constraint);
    }
    return false;
  }
  function getPropertyNameFromIndex(indexType, accessNode) {
    return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : accessNode && isPropertyName(accessNode) ? (
      // late bound names are handled in the first branch, so here we only need to handle normal names
      getPropertyNameForPropertyNameNode(accessNode)
    ) : void 0;
  }
  function isUncalledFunctionReference(node, symbol) {
    if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method)) {
      const parent = findAncestor(node.parent, (n) => !isAccessExpression(n)) || node.parent;
      if (isCallLikeExpression(parent)) {
        return isCallOrNewExpression(parent) && isIdentifier(node) && hasMatchingArgument(parent, node);
      }
      return every(symbol.declarations, (d) => !isFunctionLike(d) || isDeprecatedDeclaration(d));
    }
    return true;
  }
  function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, accessNode, accessFlags) {
    const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : void 0;
    const propName = accessNode && isPrivateIdentifier(accessNode) ? void 0 : getPropertyNameFromIndex(indexType, accessNode);
    if (propName !== void 0) {
      if (accessFlags & AccessFlags.Contextual) {
        return getTypeOfPropertyOfContextualType(objectType, propName) || anyType;
      }
      const prop = getPropertyOfType(objectType, propName);
      if (prop) {
        if (accessFlags & AccessFlags.ReportDeprecated && accessNode && prop.declarations && isDeprecatedSymbol(prop) && isUncalledFunctionReference(accessNode, prop)) {
          const deprecatedNode = accessExpression?.argumentExpression ?? (isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode);
          addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName);
        }
        if (accessExpression) {
          markPropertyAsReferenced(prop, accessExpression, isSelfTypeAccess(accessExpression.expression, objectType.symbol));
          if (isAssignmentToReadonlyEntity(accessExpression, prop, getAssignmentTargetKind(accessExpression))) {
            error(accessExpression.argumentExpression, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
            return void 0;
          }
          if (accessFlags & AccessFlags.CacheSymbol) {
            getNodeLinks(accessNode).resolvedSymbol = prop;
          }
          if (isThisPropertyAccessInConstructor(accessExpression, prop)) {
            return autoType;
          }
        }
        const propType = accessFlags & AccessFlags.Writing ? getWriteTypeOfSymbol(prop) : getTypeOfSymbol(prop);
        return accessExpression && getAssignmentTargetKind(accessExpression) !== AssignmentKind.Definite ? getFlowTypeOfReference(accessExpression, propType) : accessNode && isIndexedAccessTypeNode(accessNode) && containsMissingType(propType) ? getUnionType([propType, undefinedType]) : propType;
      }
      if (everyType(objectType, isTupleType) && isNumericLiteralName(propName)) {
        const index = +propName;
        if (accessNode && everyType(objectType, (t) => !(t.target.combinedFlags & ElementFlags.Variable)) && !(accessFlags & AccessFlags.AllowMissing)) {
          const indexNode = getIndexNodeForAccessExpression(accessNode);
          if (isTupleType(objectType)) {
            if (index < 0) {
              error(indexNode, Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value);
              return undefinedType;
            }
            error(indexNode, Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), unescapeLeadingUnderscores(propName));
          } else {
            error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType));
          }
        }
        if (index >= 0) {
          errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType));
          return getTupleElementTypeOutOfStartCount(objectType, index, accessFlags & AccessFlags.IncludeUndefined ? missingType : void 0);
        }
      }
    }
    if (!(indexType.flags & TypeFlags.Nullable) && isTypeAssignableToKind(indexType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike)) {
      if (objectType.flags & (TypeFlags.Any | TypeFlags.Never)) {
        return objectType;
      }
      const indexInfo = getApplicableIndexInfo(objectType, indexType) || getIndexInfoOfType(objectType, stringType);
      if (indexInfo) {
        if (accessFlags & AccessFlags.NoIndexSignatures && indexInfo.keyType !== numberType) {
          if (accessExpression) {
            if (accessFlags & AccessFlags.Writing) {
              error(accessExpression, Diagnostics.Type_0_is_generic_and_can_only_be_indexed_for_reading, typeToString(originalObjectType));
            } else {
              error(accessExpression, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
            }
          }
          return void 0;
        }
        if (accessNode && indexInfo.keyType === stringType && !isTypeAssignableToKind(indexType, TypeFlags.String | TypeFlags.Number)) {
          const indexNode = getIndexNodeForAccessExpression(accessNode);
          error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
          return accessFlags & AccessFlags.IncludeUndefined ? getUnionType([indexInfo.type, missingType]) : indexInfo.type;
        }
        errorIfWritingToReadonlyIndex(indexInfo);
        if (accessFlags & AccessFlags.IncludeUndefined && !(objectType.symbol && objectType.symbol.flags & (SymbolFlags.RegularEnum | SymbolFlags.ConstEnum) && (indexType.symbol && indexType.flags & TypeFlags.EnumLiteral && getParentOfSymbol(indexType.symbol) === objectType.symbol))) {
          return getUnionType([indexInfo.type, missingType]);
        }
        return indexInfo.type;
      }
      if (indexType.flags & TypeFlags.Never) {
        return neverType;
      }
      if (isJSLiteralType(objectType)) {
        return anyType;
      }
      if (accessExpression && !isConstEnumObjectType(objectType)) {
        if (isObjectLiteralType(objectType)) {
          if (noImplicitAny && indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) {
            diagnostics.add(createDiagnosticForNode(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType)));
            return undefinedType;
          } else if (indexType.flags & (TypeFlags.Number | TypeFlags.String)) {
            const types = map(objectType.properties, (property) => {
              return getTypeOfSymbol(property);
            });
            return getUnionType(append(types, undefinedType));
          }
        }
        if (objectType.symbol === globalThisSymbol && propName !== void 0 && globalThisSymbol.exports.has(propName) && globalThisSymbol.exports.get(propName).flags & SymbolFlags.BlockScoped) {
          error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType));
        } else if (noImplicitAny && !(accessFlags & AccessFlags.SuppressNoImplicitAnyError)) {
          if (propName !== void 0 && typeHasStaticProperty(propName, objectType)) {
            const typeName = typeToString(objectType);
            error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "[" + getTextOfNode(accessExpression.argumentExpression) + "]");
          } else if (getIndexTypeOfType(objectType, numberType)) {
            error(accessExpression.argumentExpression, Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
          } else {
            let suggestion;
            if (propName !== void 0 && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
              if (suggestion !== void 0) {
                error(accessExpression.argumentExpression, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
              }
            } else {
              const suggestion2 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
              if (suggestion2 !== void 0) {
                error(accessExpression, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1, typeToString(objectType), suggestion2);
              } else {
                let errorInfo;
                if (indexType.flags & TypeFlags.EnumLiteral) {
                  errorInfo = chainDiagnosticMessages(
                    /*details*/
                    void 0,
                    Diagnostics.Property_0_does_not_exist_on_type_1,
                    "[" + typeToString(indexType) + "]",
                    typeToString(objectType)
                  );
                } else if (indexType.flags & TypeFlags.UniqueESSymbol) {
                  const symbolName2 = getFullyQualifiedName(indexType.symbol, accessExpression);
                  errorInfo = chainDiagnosticMessages(
                    /*details*/
                    void 0,
                    Diagnostics.Property_0_does_not_exist_on_type_1,
                    "[" + symbolName2 + "]",
                    typeToString(objectType)
                  );
                } else if (indexType.flags & TypeFlags.StringLiteral) {
                  errorInfo = chainDiagnosticMessages(
                    /*details*/
                    void 0,
                    Diagnostics.Property_0_does_not_exist_on_type_1,
                    indexType.value,
                    typeToString(objectType)
                  );
                } else if (indexType.flags & TypeFlags.NumberLiteral) {
                  errorInfo = chainDiagnosticMessages(
                    /*details*/
                    void 0,
                    Diagnostics.Property_0_does_not_exist_on_type_1,
                    indexType.value,
                    typeToString(objectType)
                  );
                } else if (indexType.flags & (TypeFlags.Number | TypeFlags.String)) {
                  errorInfo = chainDiagnosticMessages(
                    /*details*/
                    void 0,
                    Diagnostics.No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1,
                    typeToString(indexType),
                    typeToString(objectType)
                  );
                }
                errorInfo = chainDiagnosticMessages(
                  errorInfo,
                  Diagnostics.Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1,
                  typeToString(fullIndexType),
                  typeToString(objectType)
                );
                diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(accessExpression), accessExpression, errorInfo));
              }
            }
          }
        }
        return void 0;
      }
    }
    if (accessFlags & AccessFlags.AllowMissing && isObjectLiteralType(objectType)) {
      return undefinedType;
    }
    if (isJSLiteralType(objectType)) {
      return anyType;
    }
    if (accessNode) {
      const indexNode = getIndexNodeForAccessExpression(accessNode);
      if (indexNode.kind !== SyntaxKind.BigIntLiteral && indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) {
        error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
      } else if (indexType.flags & (TypeFlags.String | TypeFlags.Number)) {
        error(indexNode, Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
      } else {
        const typeString = indexNode.kind === SyntaxKind.BigIntLiteral ? "bigint" : typeToString(indexType);
        error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeString);
      }
    }
    if (isTypeAny(indexType)) {
      return indexType;
    }
    return void 0;
    function errorIfWritingToReadonlyIndex(indexInfo) {
      if (indexInfo && indexInfo.isReadonly && accessExpression && (isAssignmentTarget(accessExpression) || isDeleteTarget(accessExpression))) {
        error(accessExpression, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
      }
    }
  }
  function getIndexNodeForAccessExpression(accessNode) {
    return accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : accessNode.kind === SyntaxKind.IndexedAccessType ? accessNode.indexType : accessNode.kind === SyntaxKind.ComputedPropertyName ? accessNode.expression : accessNode;
  }
  function isPatternLiteralPlaceholderType(type) {
    if (type.flags & TypeFlags.Intersection) {
      let seenPlaceholder = false;
      for (const t of type.types) {
        if (t.flags & (TypeFlags.Literal | TypeFlags.Nullable) || isPatternLiteralPlaceholderType(t)) {
          seenPlaceholder = true;
        } else if (!(t.flags & TypeFlags.Object)) {
          return false;
        }
      }
      return seenPlaceholder;
    }
    return !!(type.flags & (TypeFlags.Any | TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt)) || isPatternLiteralType(type);
  }
  function isPatternLiteralType(type) {
    return !!(type.flags & TypeFlags.TemplateLiteral) && every(type.types, isPatternLiteralPlaceholderType) || !!(type.flags & TypeFlags.StringMapping) && isPatternLiteralPlaceholderType(type.type);
  }
  function isGenericStringLikeType(type) {
    return !!(type.flags & (TypeFlags.TemplateLiteral | TypeFlags.StringMapping)) && !isPatternLiteralType(type);
  }
  function isGenericType(type) {
    return !!getGenericObjectFlags(type);
  }
  function isGenericObjectType(type) {
    return !!(getGenericObjectFlags(type) & ObjectFlags.IsGenericObjectType);
  }
  function isGenericIndexType(type) {
    return !!(getGenericObjectFlags(type) & ObjectFlags.IsGenericIndexType);
  }
  function getGenericObjectFlags(type) {
    if (type.flags & TypeFlags.UnionOrIntersection) {
      if (!(type.objectFlags & ObjectFlags.IsGenericTypeComputed)) {
        type.objectFlags |= ObjectFlags.IsGenericTypeComputed | reduceLeft(type.types, (flags, t) => flags | getGenericObjectFlags(t), 0);
      }
      return type.objectFlags & ObjectFlags.IsGenericType;
    }
    if (type.flags & TypeFlags.Substitution) {
      if (!(type.objectFlags & ObjectFlags.IsGenericTypeComputed)) {
        type.objectFlags |= ObjectFlags.IsGenericTypeComputed | getGenericObjectFlags(type.baseType) | getGenericObjectFlags(type.constraint);
      }
      return type.objectFlags & ObjectFlags.IsGenericType;
    }
    return (type.flags & TypeFlags.InstantiableNonPrimitive || isGenericMappedType(type) || isGenericTupleType(type) ? ObjectFlags.IsGenericObjectType : 0) | (type.flags & (TypeFlags.InstantiableNonPrimitive | TypeFlags.Index) || isGenericStringLikeType(type) ? ObjectFlags.IsGenericIndexType : 0);
  }
  function getSimplifiedType(type, writing) {
    return type.flags & TypeFlags.IndexedAccess ? getSimplifiedIndexedAccessType(type, writing) : type.flags & TypeFlags.Conditional ? getSimplifiedConditionalType(type, writing) : type;
  }
  function distributeIndexOverObjectType(objectType, indexType, writing) {
    if (objectType.flags & TypeFlags.Union || objectType.flags & TypeFlags.Intersection && !shouldDeferIndexType(objectType)) {
      const types = map(objectType.types, (t) => getSimplifiedType(getIndexedAccessType(t, indexType), writing));
      return objectType.flags & TypeFlags.Intersection || writing ? getIntersectionType(types) : getUnionType(types);
    }
  }
  function distributeObjectOverIndexType(objectType, indexType, writing) {
    if (indexType.flags & TypeFlags.Union) {
      const types = map(indexType.types, (t) => getSimplifiedType(getIndexedAccessType(objectType, t), writing));
      return writing ? getIntersectionType(types) : getUnionType(types);
    }
  }
  function getSimplifiedIndexedAccessType(type, writing) {
    const cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
    if (type[cache]) {
      return type[cache] === circularConstraintType ? type : type[cache];
    }
    type[cache] = circularConstraintType;
    const objectType = getSimplifiedType(type.objectType, writing);
    const indexType = getSimplifiedType(type.indexType, writing);
    const distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
    if (distributedOverIndex) {
      return type[cache] = distributedOverIndex;
    }
    if (!(indexType.flags & TypeFlags.Instantiable)) {
      const distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
      if (distributedOverObject) {
        return type[cache] = distributedOverObject;
      }
    }
    if (isGenericTupleType(objectType) && indexType.flags & TypeFlags.NumberLike) {
      const elementType = getElementTypeOfSliceOfTupleType(
        objectType,
        indexType.flags & TypeFlags.Number ? 0 : objectType.target.fixedLength,
        /*endSkipCount*/
        0,
        writing
      );
      if (elementType) {
        return type[cache] = elementType;
      }
    }
    if (isGenericMappedType(objectType)) {
      if (getMappedTypeNameTypeKind(objectType) !== 2 /* Remapping */) {
        return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), (t) => getSimplifiedType(t, writing));
      }
    }
    return type[cache] = type;
  }
  function getSimplifiedConditionalType(type, writing) {
    const checkType = type.checkType;
    const extendsType = type.extendsType;
    const trueType2 = getTrueTypeFromConditionalType(type);
    const falseType2 = getFalseTypeFromConditionalType(type);
    if (falseType2.flags & TypeFlags.Never && getActualTypeVariable(trueType2) === getActualTypeVariable(checkType)) {
      if (checkType.flags & TypeFlags.Any || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) {
        return getSimplifiedType(trueType2, writing);
      } else if (isIntersectionEmpty(checkType, extendsType)) {
        return neverType;
      }
    } else if (trueType2.flags & TypeFlags.Never && getActualTypeVariable(falseType2) === getActualTypeVariable(checkType)) {
      if (!(checkType.flags & TypeFlags.Any) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) {
        return neverType;
      } else if (checkType.flags & TypeFlags.Any || isIntersectionEmpty(checkType, extendsType)) {
        return getSimplifiedType(falseType2, writing);
      }
    }
    return type;
  }
  function isIntersectionEmpty(type1, type2) {
    return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & TypeFlags.Never);
  }
  function substituteIndexedMappedType(objectType, index) {
    const mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
    const templateMapper = combineTypeMappers(objectType.mapper, mapper);
    const instantiatedTemplateType = instantiateType(getTemplateTypeFromMappedType(objectType.target || objectType), templateMapper);
    const isOptional = getMappedTypeOptionality(objectType) > 0 || (isGenericType(objectType) ? getCombinedMappedTypeOptionality(getModifiersTypeFromMappedType(objectType)) > 0 : couldAccessOptionalProperty(objectType, index));
    return addOptionality(
      instantiatedTemplateType,
      /*isProperty*/
      true,
      isOptional
    );
  }
  function couldAccessOptionalProperty(objectType, indexType) {
    const indexConstraint = getBaseConstraintOfType(indexType);
    return !!indexConstraint && some(getPropertiesOfType(objectType), (p) => !!(p.flags & SymbolFlags.Optional) && isTypeAssignableTo(getLiteralTypeFromProperty(p, TypeFlags.StringOrNumberLiteralOrUnique), indexConstraint));
  }
  function getIndexedAccessType(objectType, indexType, accessFlags = AccessFlags.None, accessNode, aliasSymbol, aliasTypeArguments) {
    return getIndexedAccessTypeOrUndefined(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType);
  }
  function indexTypeLessThan(indexType, limit) {
    return everyType(indexType, (t) => {
      if (t.flags & TypeFlags.StringOrNumberLiteral) {
        const propName = getPropertyNameFromType(t);
        if (isNumericLiteralName(propName)) {
          const index = +propName;
          return index >= 0 && index < limit;
        }
      }
      return false;
    });
  }
  function getIndexedAccessTypeOrUndefined(objectType, indexType, accessFlags = AccessFlags.None, accessNode, aliasSymbol, aliasTypeArguments) {
    if (objectType === wildcardType || indexType === wildcardType) {
      return wildcardType;
    }
    objectType = getReducedType(objectType);
    if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & TypeFlags.Nullable) && isTypeAssignableToKind(indexType, TypeFlags.String | TypeFlags.Number)) {
      indexType = stringType;
    }
    if (compilerOptions.noUncheckedIndexedAccess && accessFlags & AccessFlags.ExpressionPosition) accessFlags |= AccessFlags.IncludeUndefined;
    if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== SyntaxKind.IndexedAccessType ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType))) {
      if (objectType.flags & TypeFlags.AnyOrUnknown) {
        return objectType;
      }
      const persistentAccessFlags = accessFlags & AccessFlags.Persistent;
      const id = objectType.id + "," + indexType.id + "," + persistentAccessFlags + getAliasId(aliasSymbol, aliasTypeArguments);
      let type = indexedAccessTypes.get(id);
      if (!type) {
        indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, persistentAccessFlags, aliasSymbol, aliasTypeArguments));
      }
      return type;
    }
    const apparentObjectType = getReducedApparentType(objectType);
    if (indexType.flags & TypeFlags.Union && !(indexType.flags & TypeFlags.Boolean)) {
      const propTypes = [];
      let wasMissingProp = false;
      for (const t of indexType.types) {
        const propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, accessNode, accessFlags | (wasMissingProp ? AccessFlags.SuppressNoImplicitAnyError : 0));
        if (propType) {
          propTypes.push(propType);
        } else if (!accessNode) {
          return void 0;
        } else {
          wasMissingProp = true;
        }
      }
      if (wasMissingProp) {
        return void 0;
      }
      return accessFlags & AccessFlags.Writing ? getIntersectionType(propTypes, IntersectionFlags.None, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, UnionReduction.Literal, aliasSymbol, aliasTypeArguments);
    }
    return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, accessNode, accessFlags | AccessFlags.CacheSymbol | AccessFlags.ReportDeprecated);
  }
  function getTypeFromIndexedAccessTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const objectType = getTypeFromTypeNode(node.objectType);
      const indexType = getTypeFromTypeNode(node.indexType);
      const potentialAlias = getAliasSymbolForTypeNode(node);
      links.resolvedType = getIndexedAccessType(objectType, indexType, AccessFlags.None, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
    }
    return links.resolvedType;
  }
  function getTypeFromMappedTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const type = createObjectType(ObjectFlags.Mapped, node.symbol);
      type.declaration = node;
      type.aliasSymbol = getAliasSymbolForTypeNode(node);
      type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
      links.resolvedType = type;
      getConstraintTypeFromMappedType(type);
    }
    return links.resolvedType;
  }
  function getActualTypeVariable(type) {
    if (type.flags & TypeFlags.Substitution) {
      return getActualTypeVariable(type.baseType);
    }
    if (type.flags & TypeFlags.IndexedAccess && (type.objectType.flags & TypeFlags.Substitution || type.indexType.flags & TypeFlags.Substitution)) {
      return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
    }
    return type;
  }
  function isSimpleTupleType(node) {
    return isTupleTypeNode(node) && length(node.elements) > 0 && !some(node.elements, (e) => isOptionalTypeNode(e) || isRestTypeNode(e) || isNamedTupleMember(e) && !!(e.questionToken || e.dotDotDotToken));
  }
  function isDeferredType(type, checkTuples) {
    return isGenericType(type) || checkTuples && isTupleType(type) && some(getElementTypes(type), isGenericType);
  }
  function getConditionalType(root, mapper, forConstraint, aliasSymbol, aliasTypeArguments) {
    let result;
    let extraTypes;
    let tailCount = 0;
    while (true) {
      if (tailCount === 1e3) {
        error(currentNode, Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
        return errorType;
      }
      const checkType = instantiateType(getActualTypeVariable(root.checkType), mapper);
      const extendsType = instantiateType(root.extendsType, mapper);
      if (checkType === errorType || extendsType === errorType) {
        return errorType;
      }
      if (checkType === wildcardType || extendsType === wildcardType) {
        return wildcardType;
      }
      const checkTypeNode = skipTypeParentheses(root.node.checkType);
      const extendsTypeNode = skipTypeParentheses(root.node.extendsType);
      const checkTuples = isSimpleTupleType(checkTypeNode) && isSimpleTupleType(extendsTypeNode) && length(checkTypeNode.elements) === length(extendsTypeNode.elements);
      const checkTypeDeferred = isDeferredType(checkType, checkTuples);
      let combinedMapper;
      if (root.inferTypeParameters) {
        const context = createInferenceContext(
          root.inferTypeParameters,
          /*signature*/
          void 0,
          InferenceFlags.None
        );
        if (mapper) {
          context.nonFixingMapper = combineTypeMappers(context.nonFixingMapper, mapper);
        }
        if (!checkTypeDeferred) {
          inferTypes(context.inferences, checkType, extendsType, InferencePriority.NoConstraints | InferencePriority.AlwaysStrict);
        }
        combinedMapper = mapper ? combineTypeMappers(context.mapper, mapper) : context.mapper;
      }
      const inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
      if (!checkTypeDeferred && !isDeferredType(inferredExtendsType, checkTuples)) {
        if (!(inferredExtendsType.flags & TypeFlags.AnyOrUnknown) && (checkType.flags & TypeFlags.Any || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
          if (checkType.flags & TypeFlags.Any || forConstraint && !(inferredExtendsType.flags & TypeFlags.Never) && someType(getPermissiveInstantiation(inferredExtendsType), (t) => isTypeAssignableTo(t, getPermissiveInstantiation(checkType)))) {
            (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper));
          }
          const falseType2 = getTypeFromTypeNode(root.node.falseType);
          if (falseType2.flags & TypeFlags.Conditional) {
            const newRoot = falseType2.root;
            if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
              root = newRoot;
              continue;
            }
            if (canTailRecurse(falseType2, mapper)) {
              continue;
            }
          }
          result = instantiateType(falseType2, mapper);
          break;
        }
        if (inferredExtendsType.flags & TypeFlags.AnyOrUnknown || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
          const trueType2 = getTypeFromTypeNode(root.node.trueType);
          const trueMapper = combinedMapper || mapper;
          if (canTailRecurse(trueType2, trueMapper)) {
            continue;
          }
          result = instantiateType(trueType2, trueMapper);
          break;
        }
      }
      result = createType(TypeFlags.Conditional);
      result.root = root;
      result.checkType = instantiateType(root.checkType, mapper);
      result.extendsType = instantiateType(root.extendsType, mapper);
      result.mapper = mapper;
      result.combinedMapper = combinedMapper;
      result.aliasSymbol = aliasSymbol || root.aliasSymbol;
      result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper);
      break;
    }
    return extraTypes ? getUnionType(append(extraTypes, result)) : result;
    function canTailRecurse(newType, newMapper) {
      if (newType.flags & TypeFlags.Conditional && newMapper) {
        const newRoot = newType.root;
        if (newRoot.outerTypeParameters) {
          const typeParamMapper = combineTypeMappers(newType.mapper, newMapper);
          const typeArguments = map(newRoot.outerTypeParameters, (t) => getMappedType(t, typeParamMapper));
          const newRootMapper = createTypeMapper(newRoot.outerTypeParameters, typeArguments);
          const newCheckType = newRoot.isDistributive ? getMappedType(newRoot.checkType, newRootMapper) : void 0;
          if (!newCheckType || newCheckType === newRoot.checkType || !(newCheckType.flags & (TypeFlags.Union | TypeFlags.Never))) {
            root = newRoot;
            mapper = newRootMapper;
            aliasSymbol = void 0;
            aliasTypeArguments = void 0;
            if (newRoot.aliasSymbol) {
              tailCount++;
            }
            return true;
          }
        }
      }
      return false;
    }
  }
  function getTrueTypeFromConditionalType(type) {
    return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.mapper));
  }
  function getFalseTypeFromConditionalType(type) {
    return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(getTypeFromTypeNode(type.root.node.falseType), type.mapper));
  }
  function getInferredTrueTypeFromConditionalType(type) {
    return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.combinedMapper) : getTrueTypeFromConditionalType(type));
  }
  function getInferTypeParameters(node) {
    let result;
    if (node.locals) {
      node.locals.forEach((symbol) => {
        if (symbol.flags & SymbolFlags.TypeParameter) {
          result = append(result, getDeclaredTypeOfSymbol(symbol));
        }
      });
    }
    return result;
  }
  function isDistributionDependent(root) {
    return root.isDistributive && (isTypeParameterPossiblyReferenced(root.checkType, root.node.trueType) || isTypeParameterPossiblyReferenced(root.checkType, root.node.falseType));
  }
  function getTypeFromConditionalTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const checkType = getTypeFromTypeNode(node.checkType);
      const aliasSymbol = getAliasSymbolForTypeNode(node);
      const aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
      const allOuterTypeParameters = getOuterTypeParameters(
        node,
        /*includeThisTypes*/
        true
      );
      const outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : filter(allOuterTypeParameters, (tp) => isTypeParameterPossiblyReferenced(tp, node));
      const root = {
        node,
        checkType,
        extendsType: getTypeFromTypeNode(node.extendsType),
        isDistributive: !!(checkType.flags & TypeFlags.TypeParameter),
        inferTypeParameters: getInferTypeParameters(node),
        outerTypeParameters,
        instantiations: void 0,
        aliasSymbol,
        aliasTypeArguments
      };
      links.resolvedType = getConditionalType(
        root,
        /*mapper*/
        void 0,
        /*forConstraint*/
        false
      );
      if (outerTypeParameters) {
        root.instantiations = /* @__PURE__ */ new Map();
        root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
      }
    }
    return links.resolvedType;
  }
  function getTypeFromInferTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter));
    }
    return links.resolvedType;
  }
  function getIdentifierChain(node) {
    if (isIdentifier(node)) {
      return [node];
    } else {
      return append(getIdentifierChain(node.left), node.right);
    }
  }
  function getTypeFromImportTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      if (!isLiteralImportTypeNode(node)) {
        error(node.argument, Diagnostics.String_literal_expected);
        links.resolvedSymbol = unknownSymbol;
        return links.resolvedType = errorType;
      }
      const targetMeaning = node.isTypeOf ? SymbolFlags.Value : node.flags & NodeFlags.JSDoc ? SymbolFlags.Value | SymbolFlags.Type : SymbolFlags.Type;
      const innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
      if (!innerModuleSymbol) {
        links.resolvedSymbol = unknownSymbol;
        return links.resolvedType = errorType;
      }
      const isExportEquals = !!innerModuleSymbol.exports?.get(InternalSymbolName.ExportEquals);
      const moduleSymbol = resolveExternalModuleSymbol(
        innerModuleSymbol,
        /*dontResolveAlias*/
        false
      );
      if (!nodeIsMissing(node.qualifier)) {
        const nameStack = getIdentifierChain(node.qualifier);
        let currentNamespace = moduleSymbol;
        let current;
        while (current = nameStack.shift()) {
          const meaning = nameStack.length ? SymbolFlags.Namespace : targetMeaning;
          const mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace));
          const symbolFromVariable = node.isTypeOf || isInJSFile(node) && isExportEquals ? getPropertyOfType(
            getTypeOfSymbol(mergedResolvedSymbol),
            current.escapedText,
            /*skipObjectFunctionPropertyAugment*/
            false,
            /*includeTypeOnlyMembers*/
            true
          ) : void 0;
          const symbolFromModule = node.isTypeOf ? void 0 : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning);
          const next = symbolFromModule ?? symbolFromVariable;
          if (!next) {
            error(current, Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), declarationNameToString(current));
            return links.resolvedType = errorType;
          }
          getNodeLinks(current).resolvedSymbol = next;
          getNodeLinks(current.parent).resolvedSymbol = next;
          currentNamespace = next;
        }
        links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
      } else {
        if (moduleSymbol.flags & targetMeaning) {
          links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
        } else {
          const errorMessage = targetMeaning === SymbolFlags.Value ? Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
          error(node, errorMessage, node.argument.literal.text);
          links.resolvedSymbol = unknownSymbol;
          links.resolvedType = errorType;
        }
      }
    }
    return links.resolvedType;
  }
  function resolveImportSymbolType(node, links, symbol, meaning) {
    const resolvedSymbol = resolveSymbol(symbol);
    links.resolvedSymbol = resolvedSymbol;
    if (meaning === SymbolFlags.Value) {
      return getInstantiationExpressionType(getTypeOfSymbol(symbol), node);
    } else {
      return getTypeReferenceType(node, resolvedSymbol);
    }
  }
  function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const aliasSymbol = getAliasSymbolForTypeNode(node);
      if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
        links.resolvedType = emptyTypeLiteralType;
      } else {
        let type = createObjectType(ObjectFlags.Anonymous, node.symbol);
        type.aliasSymbol = aliasSymbol;
        type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
        if (isJSDocTypeLiteral(node) && node.isArrayType) {
          type = createArrayType(type);
        }
        links.resolvedType = type;
      }
    }
    return links.resolvedType;
  }
  function getAliasSymbolForTypeNode(node) {
    let host2 = node.parent;
    while (isParenthesizedTypeNode(host2) || isJSDocTypeExpression(host2) || isTypeOperatorNode(host2) && host2.operator === SyntaxKind.ReadonlyKeyword) {
      host2 = host2.parent;
    }
    return isTypeAlias(host2) ? getSymbolOfDeclaration(host2) : void 0;
  }
  function getTypeArgumentsForAliasSymbol(symbol) {
    return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : void 0;
  }
  function isNonGenericObjectType(type) {
    return !!(type.flags & TypeFlags.Object) && !isGenericMappedType(type);
  }
  function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
    return isEmptyObjectType(type) || !!(type.flags & (TypeFlags.Null | TypeFlags.Undefined | TypeFlags.BooleanLike | TypeFlags.NumberLike | TypeFlags.BigIntLike | TypeFlags.StringLike | TypeFlags.EnumLike | TypeFlags.NonPrimitive | TypeFlags.Index));
  }
  function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
    if (!(type.flags & TypeFlags.Union)) {
      return type;
    }
    if (every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
      return find(type.types, isEmptyObjectType) || emptyObjectType;
    }
    const firstType = find(type.types, (t) => !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t));
    if (!firstType) {
      return type;
    }
    const secondType = find(type.types, (t) => t !== firstType && !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t));
    if (secondType) {
      return type;
    }
    return getAnonymousPartialType(firstType);
    function getAnonymousPartialType(type2) {
      const members = createSymbolTable();
      for (const prop of getPropertiesOfType(type2)) {
        if (getDeclarationModifierFlagsFromSymbol(prop) & (ModifierFlags.Private | ModifierFlags.Protected)) {
        } else if (isSpreadableProperty(prop)) {
          const isSetonlyAccessor = prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor);
          const flags = SymbolFlags.Property | SymbolFlags.Optional;
          const result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? CheckFlags.Readonly : 0));
          result.links.type = isSetonlyAccessor ? undefinedType : addOptionality(
            getTypeOfSymbol(prop),
            /*isProperty*/
            true
          );
          result.declarations = prop.declarations;
          result.links.nameType = getSymbolLinks(prop).nameType;
          result.links.syntheticOrigin = prop;
          members.set(prop.escapedName, result);
        }
      }
      const spread = createAnonymousType(type2.symbol, members, emptyArray, emptyArray, getIndexInfosOfType(type2));
      spread.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectOrArrayLiteral;
      return spread;
    }
  }
  function getSpreadType(left, right, symbol, objectFlags, readonly) {
    if (left.flags & TypeFlags.Any || right.flags & TypeFlags.Any) {
      return anyType;
    }
    if (left.flags & TypeFlags.Unknown || right.flags & TypeFlags.Unknown) {
      return unknownType;
    }
    if (left.flags & TypeFlags.Never) {
      return right;
    }
    if (right.flags & TypeFlags.Never) {
      return left;
    }
    left = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
    if (left.flags & TypeFlags.Union) {
      return checkCrossProductUnion([left, right]) ? mapType(left, (t) => getSpreadType(t, right, symbol, objectFlags, readonly)) : errorType;
    }
    right = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
    if (right.flags & TypeFlags.Union) {
      return checkCrossProductUnion([left, right]) ? mapType(right, (t) => getSpreadType(left, t, symbol, objectFlags, readonly)) : errorType;
    }
    if (right.flags & (TypeFlags.BooleanLike | TypeFlags.NumberLike | TypeFlags.BigIntLike | TypeFlags.StringLike | TypeFlags.EnumLike | TypeFlags.NonPrimitive | TypeFlags.Index)) {
      return left;
    }
    if (isGenericObjectType(left) || isGenericObjectType(right)) {
      if (isEmptyObjectType(left)) {
        return right;
      }
      if (left.flags & TypeFlags.Intersection) {
        const types = left.types;
        const lastLeft = types[types.length - 1];
        if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
          return getIntersectionType(concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
        }
      }
      return getIntersectionType([left, right]);
    }
    const members = createSymbolTable();
    const skippedPrivateMembers = /* @__PURE__ */ new Set();
    const indexInfos = left === emptyObjectType ? getIndexInfosOfType(right) : getUnionIndexInfos([left, right]);
    for (const rightProp of getPropertiesOfType(right)) {
      if (getDeclarationModifierFlagsFromSymbol(rightProp) & (ModifierFlags.Private | ModifierFlags.Protected)) {
        skippedPrivateMembers.add(rightProp.escapedName);
      } else if (isSpreadableProperty(rightProp)) {
        members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
      }
    }
    for (const leftProp of getPropertiesOfType(left)) {
      if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
        continue;
      }
      if (members.has(leftProp.escapedName)) {
        const rightProp = members.get(leftProp.escapedName);
        const rightType = getTypeOfSymbol(rightProp);
        if (rightProp.flags & SymbolFlags.Optional) {
          const declarations = concatenate(leftProp.declarations, rightProp.declarations);
          const flags = SymbolFlags.Property | leftProp.flags & SymbolFlags.Optional;
          const result = createSymbol(flags, leftProp.escapedName);
          const leftType = getTypeOfSymbol(leftProp);
          const leftTypeWithoutUndefined = removeMissingOrUndefinedType(leftType);
          const rightTypeWithoutUndefined = removeMissingOrUndefinedType(rightType);
          result.links.type = leftTypeWithoutUndefined === rightTypeWithoutUndefined ? leftType : getUnionType([leftType, rightTypeWithoutUndefined], UnionReduction.Subtype);
          result.links.leftSpread = leftProp;
          result.links.rightSpread = rightProp;
          result.declarations = declarations;
          result.links.nameType = getSymbolLinks(leftProp).nameType;
          members.set(leftProp.escapedName, result);
        }
      } else {
        members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
      }
    }
    const spread = createAnonymousType(symbol, members, emptyArray, emptyArray, sameMap(indexInfos, (info) => getIndexInfoWithReadonly(info, readonly)));
    spread.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectOrArrayLiteral | ObjectFlags.ContainsSpread | objectFlags;
    return spread;
  }
  function isSpreadableProperty(prop) {
    return !some(prop.declarations, isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (SymbolFlags.Method | SymbolFlags.GetAccessor | SymbolFlags.SetAccessor)) || !prop.declarations?.some((decl) => isClassLike(decl.parent)));
  }
  function getSpreadSymbol(prop, readonly) {
    const isSetonlyAccessor = prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor);
    if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
      return prop;
    }
    const flags = SymbolFlags.Property | prop.flags & SymbolFlags.Optional;
    const result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? CheckFlags.Readonly : 0));
    result.links.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
    result.declarations = prop.declarations;
    result.links.nameType = getSymbolLinks(prop).nameType;
    result.links.syntheticOrigin = prop;
    return result;
  }
  function getIndexInfoWithReadonly(info, readonly) {
    return info.isReadonly !== readonly ? createIndexInfo(info.keyType, info.type, readonly, info.declaration) : info;
  }
  function createLiteralType(flags, value, symbol, regularType) {
    const type = createTypeWithSymbol(flags, symbol);
    type.value = value;
    type.regularType = regularType || type;
    return type;
  }
  function getFreshTypeOfLiteralType(type) {
    if (type.flags & TypeFlags.Freshable) {
      if (!type.freshType) {
        const freshType = createLiteralType(type.flags, type.value, type.symbol, type);
        freshType.freshType = freshType;
        type.freshType = freshType;
      }
      return type.freshType;
    }
    return type;
  }
  function getRegularTypeOfLiteralType(type) {
    return type.flags & TypeFlags.Freshable ? type.regularType : type.flags & TypeFlags.Union ? type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType)) : type;
  }
  function isFreshLiteralType(type) {
    return !!(type.flags & TypeFlags.Freshable) && type.freshType === type;
  }
  function getStringLiteralType(value) {
    let type;
    return stringLiteralTypes.get(value) || (stringLiteralTypes.set(value, type = createLiteralType(TypeFlags.StringLiteral, value)), type);
  }
  function getNumberLiteralType(value) {
    let type;
    return numberLiteralTypes.get(value) || (numberLiteralTypes.set(value, type = createLiteralType(TypeFlags.NumberLiteral, value)), type);
  }
  function getBigIntLiteralType(value) {
    let type;
    const key = pseudoBigIntToString(value);
    return bigIntLiteralTypes.get(key) || (bigIntLiteralTypes.set(key, type = createLiteralType(TypeFlags.BigIntLiteral, value)), type);
  }
  function getEnumLiteralType(value, enumId, symbol) {
    let type;
    const key = `${enumId}${typeof value === "string" ? "@" : "#"}${value}`;
    const flags = TypeFlags.EnumLiteral | (typeof value === "string" ? TypeFlags.StringLiteral : TypeFlags.NumberLiteral);
    return enumLiteralTypes.get(key) || (enumLiteralTypes.set(key, type = createLiteralType(flags, value, symbol)), type);
  }
  function getTypeFromLiteralTypeNode(node) {
    if (node.literal.kind === SyntaxKind.NullKeyword) {
      return nullType;
    }
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
    }
    return links.resolvedType;
  }
  function createUniqueESSymbolType(symbol) {
    const type = createTypeWithSymbol(TypeFlags.UniqueESSymbol, symbol);
    type.escapedName = `__@${type.symbol.escapedName}@${getSymbolId(type.symbol)}`;
    return type;
  }
  function getESSymbolLikeTypeForNode(node) {
    if (isInJSFile(node) && isJSDocTypeExpression(node)) {
      const host2 = getJSDocHost(node);
      if (host2) {
        node = getSingleVariableOfVariableStatement(host2) || host2;
      }
    }
    if (isValidESSymbolDeclaration(node)) {
      const symbol = isCommonJsExportPropertyAssignment(node) ? getSymbolOfNode(node.left) : getSymbolOfNode(node);
      if (symbol) {
        const links = getSymbolLinks(symbol);
        return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
      }
    }
    return esSymbolType;
  }
  function getThisType(node) {
    const container = getThisContainer(
      node,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    const parent = container && container.parent;
    if (parent && (isClassLike(parent) || parent.kind === SyntaxKind.InterfaceDeclaration)) {
      if (!isStatic(container) && (!isConstructorDeclaration(container) || isNodeDescendantOf(node, container.body))) {
        return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(parent)).thisType;
      }
    }
    if (parent && isObjectLiteralExpression(parent) && isBinaryExpression(parent.parent) && getAssignmentDeclarationKind(parent.parent) === AssignmentDeclarationKind.Prototype) {
      return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
    }
    const host2 = node.flags & NodeFlags.JSDoc ? getHostSignatureFromJSDoc(node) : void 0;
    if (host2 && isFunctionExpression(host2) && isBinaryExpression(host2.parent) && getAssignmentDeclarationKind(host2.parent) === AssignmentDeclarationKind.PrototypeProperty) {
      return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host2.parent.left).parent).thisType;
    }
    if (isJSConstructor(container) && isNodeDescendantOf(node, container.body)) {
      return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(container)).thisType;
    }
    error(node, Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
    return errorType;
  }
  function getTypeFromThisTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      links.resolvedType = getThisType(node);
    }
    return links.resolvedType;
  }
  function getTypeFromRestTypeNode(node) {
    return getTypeFromTypeNode(getArrayElementTypeNode(node.type) || node.type);
  }
  function getArrayElementTypeNode(node) {
    switch (node.kind) {
      case SyntaxKind.ParenthesizedType:
        return getArrayElementTypeNode(node.type);
      case SyntaxKind.TupleType:
        if (node.elements.length === 1) {
          node = node.elements[0];
          if (node.kind === SyntaxKind.RestType || node.kind === SyntaxKind.NamedTupleMember && node.dotDotDotToken) {
            return getArrayElementTypeNode(node.type);
          }
        }
        break;
      case SyntaxKind.ArrayType:
        return node.elementType;
    }
    return void 0;
  }
  function getTypeFromNamedTupleTypeNode(node) {
    const links = getNodeLinks(node);
    return links.resolvedType || (links.resolvedType = node.dotDotDotToken ? getTypeFromRestTypeNode(node) : addOptionality(
      getTypeFromTypeNode(node.type),
      /*isProperty*/
      true,
      !!node.questionToken
    ));
  }
  function getTypeFromTypeNode(node) {
    return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
  }
  function getTypeFromTypeNodeWorker(node) {
    switch (node.kind) {
      case SyntaxKind.AnyKeyword:
      case SyntaxKind.JSDocAllType:
      case SyntaxKind.JSDocUnknownType:
        return anyType;
      case SyntaxKind.UnknownKeyword:
        return unknownType;
      case SyntaxKind.StringKeyword:
        return stringType;
      case SyntaxKind.NumberKeyword:
        return numberType;
      case SyntaxKind.BigIntKeyword:
        return bigintType;
      case SyntaxKind.BooleanKeyword:
        return booleanType;
      case SyntaxKind.SymbolKeyword:
        return esSymbolType;
      case SyntaxKind.VoidKeyword:
        return voidType;
      case SyntaxKind.UndefinedKeyword:
        return undefinedType;
      case SyntaxKind.NullKeyword:
        return nullType;
      case SyntaxKind.NeverKeyword:
        return neverType;
      case SyntaxKind.ObjectKeyword:
        return node.flags & NodeFlags.JavaScriptFile && !noImplicitAny ? anyType : nonPrimitiveType;
      case SyntaxKind.IntrinsicKeyword:
        return intrinsicMarkerType;
      case SyntaxKind.ThisType:
      case SyntaxKind.ThisKeyword:
        return getTypeFromThisTypeNode(node);
      case SyntaxKind.LiteralType:
        return getTypeFromLiteralTypeNode(node);
      case SyntaxKind.TypeReference:
        return getTypeFromTypeReference(node);
      case SyntaxKind.TypePredicate:
        return node.assertsModifier ? voidType : booleanType;
      case SyntaxKind.ExpressionWithTypeArguments:
        return getTypeFromTypeReference(node);
      case SyntaxKind.TypeQuery:
        return getTypeFromTypeQueryNode(node);
      case SyntaxKind.ArrayType:
      case SyntaxKind.TupleType:
        return getTypeFromArrayOrTupleTypeNode(node);
      case SyntaxKind.OptionalType:
        return getTypeFromOptionalTypeNode(node);
      case SyntaxKind.UnionType:
        return getTypeFromUnionTypeNode(node);
      case SyntaxKind.IntersectionType:
        return getTypeFromIntersectionTypeNode(node);
      case SyntaxKind.JSDocNullableType:
        return getTypeFromJSDocNullableTypeNode(node);
      case SyntaxKind.JSDocOptionalType:
        return addOptionality(getTypeFromTypeNode(node.type));
      case SyntaxKind.NamedTupleMember:
        return getTypeFromNamedTupleTypeNode(node);
      case SyntaxKind.ParenthesizedType:
      case SyntaxKind.JSDocNonNullableType:
      case SyntaxKind.JSDocTypeExpression:
        return getTypeFromTypeNode(node.type);
      case SyntaxKind.RestType:
        return getTypeFromRestTypeNode(node);
      case SyntaxKind.JSDocVariadicType:
        return getTypeFromJSDocVariadicType(node);
      case SyntaxKind.FunctionType:
      case SyntaxKind.ConstructorType:
      case SyntaxKind.TypeLiteral:
      case SyntaxKind.JSDocTypeLiteral:
      case SyntaxKind.JSDocFunctionType:
      case SyntaxKind.JSDocSignature:
        return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
      case SyntaxKind.TypeOperator:
        return getTypeFromTypeOperatorNode(node);
      case SyntaxKind.IndexedAccessType:
        return getTypeFromIndexedAccessTypeNode(node);
      case SyntaxKind.MappedType:
        return getTypeFromMappedTypeNode(node);
      case SyntaxKind.ConditionalType:
        return getTypeFromConditionalTypeNode(node);
      case SyntaxKind.InferType:
        return getTypeFromInferTypeNode(node);
      case SyntaxKind.TemplateLiteralType:
        return getTypeFromTemplateTypeNode(node);
      case SyntaxKind.ImportType:
        return getTypeFromImportTypeNode(node);
      // This function assumes that an identifier, qualified name, or property access expression is a type expression
      // Callers should first ensure this by calling `isPartOfTypeNode`
      // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s.
      case SyntaxKind.Identifier:
      case SyntaxKind.QualifiedName:
      case SyntaxKind.PropertyAccessExpression:
        const symbol = getSymbolAtLocation(node);
        return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
      default:
        return errorType;
    }
  }
  function instantiateList(items, mapper, instantiator) {
    if (items && items.length) {
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        const mapped = instantiator(item, mapper);
        if (item !== mapped) {
          const result = i === 0 ? [] : items.slice(0, i);
          result.push(mapped);
          for (i++; i < items.length; i++) {
            result.push(instantiator(items[i], mapper));
          }
          return result;
        }
      }
    }
    return items;
  }
  function instantiateTypes(types, mapper) {
    return instantiateList(types, mapper, instantiateType);
  }
  function instantiateSignatures(signatures, mapper) {
    return instantiateList(signatures, mapper, instantiateSignature);
  }
  function instantiateIndexInfos(indexInfos, mapper) {
    return instantiateList(indexInfos, mapper, instantiateIndexInfo);
  }
  function createTypeMapper(sources, targets) {
    return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
  }
  function getMappedType(type, mapper) {
    switch (mapper.kind) {
      case TypeMapKind.Simple:
        return type === mapper.source ? mapper.target : type;
      case TypeMapKind.Array: {
        const sources = mapper.sources;
        const targets = mapper.targets;
        for (let i = 0; i < sources.length; i++) {
          if (type === sources[i]) {
            return targets ? targets[i] : anyType;
          }
        }
        return type;
      }
      case TypeMapKind.Deferred: {
        const sources = mapper.sources;
        const targets = mapper.targets;
        for (let i = 0; i < sources.length; i++) {
          if (type === sources[i]) {
            return targets[i]();
          }
        }
        return type;
      }
      case TypeMapKind.Function:
        return mapper.func(type);
      case TypeMapKind.Composite:
      case TypeMapKind.Merged:
        const t1 = getMappedType(type, mapper.mapper1);
        return t1 !== type && mapper.kind === TypeMapKind.Composite ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
    }
  }
  function makeUnaryTypeMapper(source, target) {
    return Debug.attachDebugPrototypeIfDebug({ kind: TypeMapKind.Simple, source, target });
  }
  function makeArrayTypeMapper(sources, targets) {
    return Debug.attachDebugPrototypeIfDebug({ kind: TypeMapKind.Array, sources, targets });
  }
  function makeFunctionTypeMapper(func, debugInfo) {
    return Debug.attachDebugPrototypeIfDebug({ kind: TypeMapKind.Function, func, debugInfo: Debug.isDebugging ? debugInfo : void 0 });
  }
  function makeDeferredTypeMapper(sources, targets) {
    return Debug.attachDebugPrototypeIfDebug({ kind: TypeMapKind.Deferred, sources, targets });
  }
  function makeCompositeTypeMapper(kind, mapper1, mapper2) {
    return Debug.attachDebugPrototypeIfDebug({ kind, mapper1, mapper2 });
  }
  function createTypeEraser(sources) {
    return createTypeMapper(
      sources,
      /*targets*/
      void 0
    );
  }
  function createBackreferenceMapper(context, index) {
    const forwardInferences = context.inferences.slice(index);
    return createTypeMapper(map(forwardInferences, (i) => i.typeParameter), map(forwardInferences, () => unknownType));
  }
  function combineTypeMappers(mapper1, mapper2) {
    return mapper1 ? makeCompositeTypeMapper(TypeMapKind.Composite, mapper1, mapper2) : mapper2;
  }
  function mergeTypeMappers(mapper1, mapper2) {
    return mapper1 ? makeCompositeTypeMapper(TypeMapKind.Merged, mapper1, mapper2) : mapper2;
  }
  function prependTypeMapping(source, target, mapper) {
    return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(TypeMapKind.Merged, makeUnaryTypeMapper(source, target), mapper);
  }
  function appendTypeMapping(mapper, source, target) {
    return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(TypeMapKind.Merged, mapper, makeUnaryTypeMapper(source, target));
  }
  function getRestrictiveTypeParameter(tp) {
    return !tp.constraint && !getConstraintDeclaration(tp) || tp.constraint === noConstraintType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), tp.restrictiveInstantiation.constraint = noConstraintType, tp.restrictiveInstantiation);
  }
  function cloneTypeParameter(typeParameter) {
    const result = createTypeParameter(typeParameter.symbol);
    result.target = typeParameter;
    return result;
  }
  function instantiateTypePredicate(predicate, mapper) {
    return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
  }
  function instantiateSignature(signature, mapper, eraseTypeParameters) {
    let freshTypeParameters;
    if (signature.typeParameters && !eraseTypeParameters) {
      freshTypeParameters = map(signature.typeParameters, cloneTypeParameter);
      mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
      for (const tp of freshTypeParameters) {
        tp.mapper = mapper;
      }
    }
    const result = createSignature(
      signature.declaration,
      freshTypeParameters,
      signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper),
      instantiateList(signature.parameters, mapper, instantiateSymbol),
      /*resolvedReturnType*/
      void 0,
      /*resolvedTypePredicate*/
      void 0,
      signature.minArgumentCount,
      signature.flags & SignatureFlags.PropagatingFlags
    );
    result.target = signature;
    result.mapper = mapper;
    return result;
  }
  function instantiateSymbol(symbol, mapper) {
    const links = getSymbolLinks(symbol);
    if (links.type && !couldContainTypeVariables(links.type)) {
      if (!(symbol.flags & SymbolFlags.SetAccessor)) {
        return symbol;
      }
      if (links.writeType && !couldContainTypeVariables(links.writeType)) {
        return symbol;
      }
    }
    if (getCheckFlags(symbol) & CheckFlags.Instantiated) {
      symbol = links.target;
      mapper = combineTypeMappers(links.mapper, mapper);
    }
    const result = createSymbol(symbol.flags, symbol.escapedName, CheckFlags.Instantiated | getCheckFlags(symbol) & (CheckFlags.Readonly | CheckFlags.Late | CheckFlags.OptionalParameter | CheckFlags.RestParameter));
    result.declarations = symbol.declarations;
    result.parent = symbol.parent;
    result.links.target = symbol;
    result.links.mapper = mapper;
    if (symbol.valueDeclaration) {
      result.valueDeclaration = symbol.valueDeclaration;
    }
    if (links.nameType) {
      result.links.nameType = links.nameType;
    }
    return result;
  }
  function getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) {
    const declaration = type.objectFlags & ObjectFlags.Reference ? type.node : type.objectFlags & ObjectFlags.InstantiationExpressionType ? type.node : type.symbol.declarations[0];
    const links = getNodeLinks(declaration);
    const target = type.objectFlags & ObjectFlags.Reference ? links.resolvedType : type.objectFlags & ObjectFlags.Instantiated ? type.target : type;
    let typeParameters = type.objectFlags & ObjectFlags.SingleSignatureType ? type.outerTypeParameters : links.outerTypeParameters;
    if (!typeParameters) {
      let outerTypeParameters = getOuterTypeParameters(
        declaration,
        /*includeThisTypes*/
        true
      );
      if (isJSConstructor(declaration)) {
        const templateTagParameters = getTypeParametersFromDeclaration(declaration);
        outerTypeParameters = addRange(outerTypeParameters, templateTagParameters);
      }
      typeParameters = outerTypeParameters || emptyArray;
      const allDeclarations = type.objectFlags & (ObjectFlags.Reference | ObjectFlags.InstantiationExpressionType) ? [declaration] : type.symbol.declarations;
      typeParameters = (target.objectFlags & (ObjectFlags.Reference | ObjectFlags.InstantiationExpressionType) || target.symbol.flags & SymbolFlags.Method || target.symbol.flags & SymbolFlags.TypeLiteral) && !target.aliasTypeArguments ? filter(typeParameters, (tp) => some(allDeclarations, (d) => isTypeParameterPossiblyReferenced(tp, d))) : typeParameters;
      links.outerTypeParameters = typeParameters;
    }
    if (typeParameters.length) {
      const combinedMapper = combineTypeMappers(type.mapper, mapper);
      const typeArguments = map(typeParameters, (t) => getMappedType(t, combinedMapper));
      const newAliasSymbol = aliasSymbol || type.aliasSymbol;
      const newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
      const id = (type.objectFlags & ObjectFlags.SingleSignatureType ? "S" : "") + getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments);
      if (!target.instantiations) {
        target.instantiations = /* @__PURE__ */ new Map();
        target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target);
      }
      let result = target.instantiations.get(id);
      if (!result) {
        if (type.objectFlags & ObjectFlags.SingleSignatureType) {
          result = instantiateAnonymousType(type, mapper);
          target.instantiations.set(id, result);
          return result;
        }
        const newMapper = createTypeMapper(typeParameters, typeArguments);
        result = target.objectFlags & ObjectFlags.Reference ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & ObjectFlags.Mapped ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments);
        target.instantiations.set(id, result);
        const resultObjectFlags = getObjectFlags(result);
        if (result.flags & TypeFlags.ObjectFlagsType && !(resultObjectFlags & ObjectFlags.CouldContainTypeVariablesComputed)) {
          const resultCouldContainTypeVariables = some(typeArguments, couldContainTypeVariables);
          if (!(getObjectFlags(result) & ObjectFlags.CouldContainTypeVariablesComputed)) {
            if (resultObjectFlags & (ObjectFlags.Mapped | ObjectFlags.Anonymous | ObjectFlags.Reference)) {
              result.objectFlags |= ObjectFlags.CouldContainTypeVariablesComputed | (resultCouldContainTypeVariables ? ObjectFlags.CouldContainTypeVariables : 0);
            } else {
              result.objectFlags |= !resultCouldContainTypeVariables ? ObjectFlags.CouldContainTypeVariablesComputed : 0;
            }
          }
        }
      }
      return result;
    }
    return type;
  }
  function maybeTypeParameterReference(node) {
    return !(node.parent.kind === SyntaxKind.TypeReference && node.parent.typeArguments && node === node.parent.typeName || node.parent.kind === SyntaxKind.ImportType && node.parent.typeArguments && node === node.parent.qualifier);
  }
  function isTypeParameterPossiblyReferenced(tp, node) {
    if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
      const container = tp.symbol.declarations[0].parent;
      for (let n = node; n !== container; n = n.parent) {
        if (!n || n.kind === SyntaxKind.Block || n.kind === SyntaxKind.ConditionalType && forEachChild(n.extendsType, containsReference)) {
          return true;
        }
      }
      return containsReference(node);
    }
    return true;
    function containsReference(node2) {
      switch (node2.kind) {
        case SyntaxKind.ThisType:
          return !!tp.isThisType;
        case SyntaxKind.Identifier:
          return !tp.isThisType && isPartOfTypeNode(node2) && maybeTypeParameterReference(node2) && getTypeFromTypeNodeWorker(node2) === tp;
        // use worker because we're looking for === equality
        case SyntaxKind.TypeQuery:
          const entityName = node2.exprName;
          const firstIdentifier = getFirstIdentifier(entityName);
          if (!isThisIdentifier(firstIdentifier)) {
            const firstIdentifierSymbol = getResolvedSymbol(firstIdentifier);
            const tpDeclaration = tp.symbol.declarations[0];
            const tpScope = tpDeclaration.kind === SyntaxKind.TypeParameter ? tpDeclaration.parent : (
              // Type parameter is a regular type parameter, e.g. foo<T>
              tp.isThisType ? tpDeclaration : (
                // Type parameter is the this type, and its declaration is the class declaration.
                void 0
              )
            );
            if (firstIdentifierSymbol.declarations && tpScope) {
              return some(firstIdentifierSymbol.declarations, (idDecl) => isNodeDescendantOf(idDecl, tpScope)) || some(node2.typeArguments, containsReference);
            }
          }
          return true;
        case SyntaxKind.MethodDeclaration:
        case SyntaxKind.MethodSignature:
          return !node2.type && !!node2.body || some(node2.typeParameters, containsReference) || some(node2.parameters, containsReference) || !!node2.type && containsReference(node2.type);
      }
      return !!forEachChild(node2, containsReference);
    }
  }
  function getHomomorphicTypeVariable(type) {
    const constraintType = getConstraintTypeFromMappedType(type);
    if (constraintType.flags & TypeFlags.Index) {
      const typeVariable = getActualTypeVariable(constraintType.type);
      if (typeVariable.flags & TypeFlags.TypeParameter) {
        return typeVariable;
      }
    }
    return void 0;
  }
  function instantiateMappedType(type, mapper, aliasSymbol, aliasTypeArguments) {
    const typeVariable = getHomomorphicTypeVariable(type);
    if (typeVariable) {
      const mappedTypeVariable = instantiateType(typeVariable, mapper);
      if (typeVariable !== mappedTypeVariable) {
        return mapTypeWithAlias(getReducedType(mappedTypeVariable), instantiateConstituent, aliasSymbol, aliasTypeArguments);
      }
    }
    return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments);
    function instantiateConstituent(t) {
      if (t.flags & (TypeFlags.AnyOrUnknown | TypeFlags.InstantiableNonPrimitive | TypeFlags.Object | TypeFlags.Intersection) && t !== wildcardType && !isErrorType(t)) {
        if (!type.declaration.nameType) {
          let constraint;
          if (isArrayType(t) || t.flags & TypeFlags.Any && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 && (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, isArrayOrTupleType)) {
            return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper));
          }
          if (isTupleType(t)) {
            return instantiateMappedTupleType(t, type, typeVariable, mapper);
          }
          if (isArrayOrTupleOrIntersection(t)) {
            return getIntersectionType(map(t.types, instantiateConstituent));
          }
        }
        return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper));
      }
      return t;
    }
  }
  function getModifiedReadonlyState(state, modifiers) {
    return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
  }
  function instantiateMappedTupleType(tupleType, mappedType, typeVariable, mapper) {
    const elementFlags = tupleType.target.elementFlags;
    const fixedLength = tupleType.target.fixedLength;
    const fixedMapper = fixedLength ? prependTypeMapping(typeVariable, tupleType, mapper) : mapper;
    const newElementTypes = map(getElementTypes(tupleType), (type, i) => {
      const flags = elementFlags[i];
      return i < fixedLength ? instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(flags & ElementFlags.Optional), fixedMapper) : flags & ElementFlags.Variadic ? instantiateType(mappedType, prependTypeMapping(typeVariable, type, mapper)) : getElementTypeOfArrayType(instantiateType(mappedType, prependTypeMapping(typeVariable, createArrayType(type), mapper))) ?? unknownType;
    });
    const modifiers = getMappedTypeModifiers(mappedType);
    const newElementFlags = modifiers & 4 /* IncludeOptional */ ? map(elementFlags, (f) => f & ElementFlags.Required ? ElementFlags.Optional : f) : modifiers & 8 /* ExcludeOptional */ ? map(elementFlags, (f) => f & ElementFlags.Optional ? ElementFlags.Required : f) : elementFlags;
    const newReadonly = getModifiedReadonlyState(tupleType.target.readonly, getMappedTypeModifiers(mappedType));
    return contains(newElementTypes, errorType) ? errorType : createTupleType(newElementTypes, newElementFlags, newReadonly, tupleType.target.labeledElementDeclarations);
  }
  function instantiateMappedArrayType(arrayType, mappedType, mapper) {
    const elementType = instantiateMappedTypeTemplate(
      mappedType,
      numberType,
      /*isOptional*/
      true,
      mapper
    );
    return isErrorType(elementType) ? errorType : createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
  }
  function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
    const templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
    const propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
    const modifiers = getMappedTypeModifiers(type);
    return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, TypeFlags.Undefined | TypeFlags.Void) ? getOptionalType(
      propType,
      /*isProperty*/
      true
    ) : strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType;
  }
  function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) {
    Debug.assert(type.symbol, "anonymous type must have symbol to be instantiated");
    const result = createObjectType(type.objectFlags & ~(ObjectFlags.CouldContainTypeVariablesComputed | ObjectFlags.CouldContainTypeVariables) | ObjectFlags.Instantiated, type.symbol);
    if (type.objectFlags & ObjectFlags.Mapped) {
      result.declaration = type.declaration;
      const origTypeParameter = getTypeParameterFromMappedType(type);
      const freshTypeParameter = cloneTypeParameter(origTypeParameter);
      result.typeParameter = freshTypeParameter;
      mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
      freshTypeParameter.mapper = mapper;
    }
    if (type.objectFlags & ObjectFlags.InstantiationExpressionType) {
      result.node = type.node;
    }
    if (type.objectFlags & ObjectFlags.SingleSignatureType) {
      result.outerTypeParameters = type.outerTypeParameters;
    }
    result.target = type;
    result.mapper = mapper;
    result.aliasSymbol = aliasSymbol || type.aliasSymbol;
    result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
    result.objectFlags |= result.aliasTypeArguments ? getPropagatingFlagsOfTypes(result.aliasTypeArguments) : 0;
    return result;
  }
  function getConditionalTypeInstantiation(type, mapper, forConstraint, aliasSymbol, aliasTypeArguments) {
    const root = type.root;
    if (root.outerTypeParameters) {
      const typeArguments = map(root.outerTypeParameters, (t) => getMappedType(t, mapper));
      const id = (forConstraint ? "C" : "") + getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments);
      let result = root.instantiations.get(id);
      if (!result) {
        const newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
        const checkType = root.checkType;
        const distributionType = root.isDistributive ? getReducedType(getMappedType(checkType, newMapper)) : void 0;
        result = distributionType && checkType !== distributionType && distributionType.flags & (TypeFlags.Union | TypeFlags.Never) ? mapTypeWithAlias(distributionType, (t) => getConditionalType(root, prependTypeMapping(checkType, t, newMapper), forConstraint), aliasSymbol, aliasTypeArguments) : getConditionalType(root, newMapper, forConstraint, aliasSymbol, aliasTypeArguments);
        root.instantiations.set(id, result);
      }
      return result;
    }
    return type;
  }
  function instantiateType(type, mapper) {
    return type && mapper ? instantiateTypeWithAlias(
      type,
      mapper,
      /*aliasSymbol*/
      void 0,
      /*aliasTypeArguments*/
      void 0
    ) : type;
  }
  function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) {
    if (!couldContainTypeVariables(type)) {
      return type;
    }
    if (instantiationDepth === 100 || instantiationCount >= 5e6) {
      tracing?.instant(tracing.Phase.CheckTypes, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth, instantiationCount });
      error(currentNode, Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
      return errorType;
    }
    totalInstantiationCount++;
    instantiationCount++;
    instantiationDepth++;
    const result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments);
    instantiationDepth--;
    return result;
  }
  function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) {
    const flags = type.flags;
    if (flags & TypeFlags.TypeParameter) {
      return getMappedType(type, mapper);
    }
    if (flags & TypeFlags.Object) {
      const objectFlags = type.objectFlags;
      if (objectFlags & (ObjectFlags.Reference | ObjectFlags.Anonymous | ObjectFlags.Mapped)) {
        if (objectFlags & ObjectFlags.Reference && !type.node) {
          const resolvedTypeArguments = type.resolvedTypeArguments;
          const newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
          return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type;
        }
        if (objectFlags & ObjectFlags.ReverseMapped) {
          return instantiateReverseMappedType(type, mapper);
        }
        return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments);
      }
      return type;
    }
    if (flags & TypeFlags.UnionOrIntersection) {
      const origin = type.flags & TypeFlags.Union ? type.origin : void 0;
      const types = origin && origin.flags & TypeFlags.UnionOrIntersection ? origin.types : type.types;
      const newTypes = instantiateTypes(types, mapper);
      if (newTypes === types && aliasSymbol === type.aliasSymbol) {
        return type;
      }
      const newAliasSymbol = aliasSymbol || type.aliasSymbol;
      const newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
      return flags & TypeFlags.Intersection || origin && origin.flags & TypeFlags.Intersection ? getIntersectionType(newTypes, IntersectionFlags.None, newAliasSymbol, newAliasTypeArguments) : getUnionType(newTypes, UnionReduction.Literal, newAliasSymbol, newAliasTypeArguments);
    }
    if (flags & TypeFlags.Index) {
      return getIndexType(instantiateType(type.type, mapper));
    }
    if (flags & TypeFlags.TemplateLiteral) {
      return getTemplateLiteralType(type.texts, instantiateTypes(type.types, mapper));
    }
    if (flags & TypeFlags.StringMapping) {
      return getStringMappingType(type.symbol, instantiateType(type.type, mapper));
    }
    if (flags & TypeFlags.IndexedAccess) {
      const newAliasSymbol = aliasSymbol || type.aliasSymbol;
      const newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
      return getIndexedAccessType(
        instantiateType(type.objectType, mapper),
        instantiateType(type.indexType, mapper),
        type.accessFlags,
        /*accessNode*/
        void 0,
        newAliasSymbol,
        newAliasTypeArguments
      );
    }
    if (flags & TypeFlags.Conditional) {
      return getConditionalTypeInstantiation(
        type,
        combineTypeMappers(type.mapper, mapper),
        /*forConstraint*/
        false,
        aliasSymbol,
        aliasTypeArguments
      );
    }
    if (flags & TypeFlags.Substitution) {
      const newBaseType = instantiateType(type.baseType, mapper);
      if (isNoInferType(type)) {
        return getNoInferType(newBaseType);
      }
      const newConstraint = instantiateType(type.constraint, mapper);
      if (newBaseType.flags & TypeFlags.TypeVariable && isGenericType(newConstraint)) {
        return getSubstitutionType(newBaseType, newConstraint);
      }
      if (newConstraint.flags & TypeFlags.AnyOrUnknown || isTypeAssignableTo(getRestrictiveInstantiation(newBaseType), getRestrictiveInstantiation(newConstraint))) {
        return newBaseType;
      }
      return newBaseType.flags & TypeFlags.TypeVariable ? getSubstitutionType(newBaseType, newConstraint) : getIntersectionType([newConstraint, newBaseType]);
    }
    return type;
  }
  function instantiateReverseMappedType(type, mapper) {
    const innerMappedType = instantiateType(type.mappedType, mapper);
    if (!(getObjectFlags(innerMappedType) & ObjectFlags.Mapped)) {
      return type;
    }
    const innerIndexType = instantiateType(type.constraintType, mapper);
    if (!(innerIndexType.flags & TypeFlags.Index)) {
      return type;
    }
    const instantiated = inferTypeForHomomorphicMappedType(
      instantiateType(type.source, mapper),
      innerMappedType,
      innerIndexType
    );
    if (instantiated) {
      return instantiated;
    }
    return type;
  }
  function getPermissiveInstantiation(type) {
    return type.flags & (TypeFlags.Primitive | TypeFlags.AnyOrUnknown | TypeFlags.Never) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
  }
  function getRestrictiveInstantiation(type) {
    if (type.flags & (TypeFlags.Primitive | TypeFlags.AnyOrUnknown | TypeFlags.Never)) {
      return type;
    }
    if (type.restrictiveInstantiation) {
      return type.restrictiveInstantiation;
    }
    type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
    type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
    return type.restrictiveInstantiation;
  }
  function instantiateIndexInfo(info, mapper) {
    return createIndexInfo(info.keyType, instantiateType(info.type, mapper), info.isReadonly, info.declaration);
  }
  function isContextSensitive(node) {
    Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node));
    switch (node.kind) {
      case SyntaxKind.FunctionExpression:
      case SyntaxKind.ArrowFunction:
      case SyntaxKind.MethodDeclaration:
      case SyntaxKind.FunctionDeclaration:
        return isContextSensitiveFunctionLikeDeclaration(node);
      case SyntaxKind.ObjectLiteralExpression:
        return some(node.properties, isContextSensitive);
      case SyntaxKind.ArrayLiteralExpression:
        return some(node.elements, isContextSensitive);
      case SyntaxKind.ConditionalExpression:
        return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse);
      case SyntaxKind.BinaryExpression:
        return (node.operatorToken.kind === SyntaxKind.BarBarToken || node.operatorToken.kind === SyntaxKind.QuestionQuestionToken) && (isContextSensitive(node.left) || isContextSensitive(node.right));
      case SyntaxKind.PropertyAssignment:
        return isContextSensitive(node.initializer);
      case SyntaxKind.ParenthesizedExpression:
        return isContextSensitive(node.expression);
      case SyntaxKind.JsxAttributes:
        return some(node.properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive);
      case SyntaxKind.JsxAttribute: {
        const { initializer } = node;
        return !!initializer && isContextSensitive(initializer);
      }
      case SyntaxKind.JsxExpression: {
        const { expression } = node;
        return !!expression && isContextSensitive(expression);
      }
    }
    return false;
  }
  function isContextSensitiveFunctionLikeDeclaration(node) {
    return hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node);
  }
  function hasContextSensitiveReturnExpression(node) {
    if (node.typeParameters || getEffectiveReturnTypeNode(node) || !node.body) {
      return false;
    }
    if (node.body.kind !== SyntaxKind.Block) {
      return isContextSensitive(node.body);
    }
    return !!forEachReturnStatement(node.body, (statement) => !!statement.expression && isContextSensitive(statement.expression));
  }
  function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
    return (isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func);
  }
  function getTypeWithoutSignatures(type) {
    if (type.flags & TypeFlags.Object) {
      const resolved = resolveStructuredTypeMembers(type);
      if (resolved.constructSignatures.length || resolved.callSignatures.length) {
        const result = createObjectType(ObjectFlags.Anonymous, type.symbol);
        result.members = resolved.members;
        result.properties = resolved.properties;
        result.callSignatures = emptyArray;
        result.constructSignatures = emptyArray;
        result.indexInfos = emptyArray;
        return result;
      }
    } else if (type.flags & TypeFlags.Intersection) {
      return getIntersectionType(map(type.types, getTypeWithoutSignatures));
    }
    return type;
  }
  function isTypeIdenticalTo(source, target) {
    return isTypeRelatedTo(source, target, identityRelation);
  }
  function compareTypesIdentical(source, target) {
    return isTypeRelatedTo(source, target, identityRelation) ? Ternary.True : Ternary.False;
  }
  function compareTypesAssignable(source, target) {
    return isTypeRelatedTo(source, target, assignableRelation) ? Ternary.True : Ternary.False;
  }
  function compareTypesSubtypeOf(source, target) {
    return isTypeRelatedTo(source, target, subtypeRelation) ? Ternary.True : Ternary.False;
  }
  function isTypeSubtypeOf(source, target) {
    return isTypeRelatedTo(source, target, subtypeRelation);
  }
  function isTypeStrictSubtypeOf(source, target) {
    return isTypeRelatedTo(source, target, strictSubtypeRelation);
  }
  function isTypeAssignableTo(source, target) {
    return isTypeRelatedTo(source, target, assignableRelation);
  }
  function isTypeDerivedFrom(source, target) {
    return source.flags & TypeFlags.Union ? every(source.types, (t) => isTypeDerivedFrom(t, target)) : target.flags & TypeFlags.Union ? some(target.types, (t) => isTypeDerivedFrom(source, t)) : source.flags & TypeFlags.Intersection ? some(source.types, (t) => isTypeDerivedFrom(t, target)) : source.flags & TypeFlags.InstantiableNonPrimitive ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) : isEmptyAnonymousObjectType(target) ? !!(source.flags & (TypeFlags.Object | TypeFlags.NonPrimitive)) : target === globalObjectType ? !!(source.flags & (TypeFlags.Object | TypeFlags.NonPrimitive)) && !isEmptyAnonymousObjectType(source) : target === globalFunctionType ? !!(source.flags & TypeFlags.Object) && isFunctionObjectType(source) : hasBaseType(source, getTargetType(target)) || isArrayType(target) && !isReadonlyArrayType(target) && isTypeDerivedFrom(source, globalReadonlyArrayType);
  }
  function isTypeComparableTo(source, target) {
    return isTypeRelatedTo(source, target, comparableRelation);
  }
  function areTypesComparable(type1, type2) {
    return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
  }
  function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
    return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
  }
  function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
    return checkTypeRelatedToAndOptionallyElaborate(
      source,
      target,
      assignableRelation,
      errorNode,
      expr,
      headMessage,
      containingMessageChain,
      /*errorOutputContainer*/
      void 0
    );
  }
  function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
    if (isTypeRelatedTo(source, target, relation)) return true;
    if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
      return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
    }
    return false;
  }
  function isOrHasGenericConditional(type) {
    return !!(type.flags & TypeFlags.Conditional || type.flags & TypeFlags.Intersection && some(type.types, isOrHasGenericConditional));
  }
  function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
    if (!node || isOrHasGenericConditional(target)) return false;
    if (!checkTypeRelatedTo(
      source,
      target,
      relation,
      /*errorNode*/
      void 0
    ) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
      return true;
    }
    switch (node.kind) {
      case SyntaxKind.AsExpression:
        if (!isConstAssertion(node)) {
          break;
        }
      // fallthrough
      case SyntaxKind.JsxExpression:
      case SyntaxKind.ParenthesizedExpression:
        return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
      case SyntaxKind.BinaryExpression:
        switch (node.operatorToken.kind) {
          case SyntaxKind.EqualsToken:
          case SyntaxKind.CommaToken:
            return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
        }
        break;
      case SyntaxKind.ObjectLiteralExpression:
        return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
      case SyntaxKind.ArrayLiteralExpression:
        return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
      case SyntaxKind.JsxAttributes:
        return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
      case SyntaxKind.ArrowFunction:
        return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
    }
    return false;
  }
  function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
    const callSignatures = getSignaturesOfType(source, SignatureKind.Call);
    const constructSignatures = getSignaturesOfType(source, SignatureKind.Construct);
    for (const signatures of [constructSignatures, callSignatures]) {
      if (some(signatures, (s) => {
        const returnType = getReturnTypeOfSignature(s);
        return !(returnType.flags & (TypeFlags.Any | TypeFlags.Never)) && checkTypeRelatedTo(
          returnType,
          target,
          relation,
          /*errorNode*/
          void 0
        );
      })) {
        const resultObj = errorOutputContainer || {};
        checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
        const diagnostic = resultObj.errors[resultObj.errors.length - 1];
        addRelatedInfo(
          diagnostic,
          createDiagnosticForNode(
            node,
            signatures === constructSignatures ? Diagnostics.Did_you_mean_to_use_new_with_this_expression : Diagnostics.Did_you_mean_to_call_this_expression
          )
        );
        return true;
      }
    }
    return false;
  }
  function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
    if (isBlock(node.body)) {
      return false;
    }
    if (some(node.parameters, hasType)) {
      return false;
    }
    const sourceSig = getSingleCallSignature(source);
    if (!sourceSig) {
      return false;
    }
    const targetSignatures = getSignaturesOfType(target, SignatureKind.Call);
    if (!length(targetSignatures)) {
      return false;
    }
    const returnExpression = node.body;
    const sourceReturn = getReturnTypeOfSignature(sourceSig);
    const targetReturn = getUnionType(map(targetSignatures, getReturnTypeOfSignature));
    if (!checkTypeRelatedTo(
      sourceReturn,
      targetReturn,
      relation,
      /*errorNode*/
      void 0
    )) {
      const elaborated = returnExpression && elaborateError(
        returnExpression,
        sourceReturn,
        targetReturn,
        relation,
        /*headMessage*/
        void 0,
        containingMessageChain,
        errorOutputContainer
      );
      if (elaborated) {
        return elaborated;
      }
      const resultObj = errorOutputContainer || {};
      checkTypeRelatedTo(
        sourceReturn,
        targetReturn,
        relation,
        returnExpression,
        /*headMessage*/
        void 0,
        containingMessageChain,
        resultObj
      );
      if (resultObj.errors) {
        if (target.symbol && length(target.symbol.declarations)) {
          addRelatedInfo(
            resultObj.errors[resultObj.errors.length - 1],
            createDiagnosticForNode(
              target.symbol.declarations[0],
              Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature
            )
          );
        }
        if ((getFunctionFlags(node) & FunctionFlags.Async) === 0 && !getTypeOfPropertyOfType(sourceReturn, "then") && checkTypeRelatedTo(
          createPromiseType(sourceReturn),
          targetReturn,
          relation,
          /*errorNode*/
          void 0
        )) {
          addRelatedInfo(
            resultObj.errors[resultObj.errors.length - 1],
            createDiagnosticForNode(
              node,
              Diagnostics.Did_you_mean_to_mark_this_function_as_async
            )
          );
        }
        return true;
      }
    }
    return false;
  }
  function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
    const idx = getIndexedAccessTypeOrUndefined(target, nameType);
    if (idx) {
      return idx;
    }
    if (target.flags & TypeFlags.Union) {
      const best = getBestMatchingType(source, target);
      if (best) {
        return getIndexedAccessTypeOrUndefined(best, nameType);
      }
    }
  }
  function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
    pushContextualType(
      next,
      sourcePropType,
      /*isCache*/
      false
    );
    const result = checkExpressionForMutableLocation(next, 1 /* Contextual */);
    popContextualType();
    return result;
  }
  function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
    let reportedError = false;
    for (const value of iterator) {
      const { errorNode: prop, innerExpression: next, nameType, errorMessage } = value;
      let targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
      if (!targetPropType || targetPropType.flags & TypeFlags.IndexedAccess) continue;
      let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
      if (!sourcePropType) continue;
      const propName = getPropertyNameFromIndex(
        nameType,
        /*accessNode*/
        void 0
      );
      if (!checkTypeRelatedTo(
        sourcePropType,
        targetPropType,
        relation,
        /*errorNode*/
        void 0
      )) {
        const elaborated = next && elaborateError(
          next,
          sourcePropType,
          targetPropType,
          relation,
          /*headMessage*/
          void 0,
          containingMessageChain,
          errorOutputContainer
        );
        reportedError = true;
        if (!elaborated) {
          const resultObj = errorOutputContainer || {};
          const specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
          if (exactOptionalPropertyTypes && isExactOptionalPropertyMismatch(specificSource, targetPropType)) {
            const diag = createDiagnosticForNode(prop, Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target, typeToString(specificSource), typeToString(targetPropType));
            diagnostics.add(diag);
            resultObj.errors = [diag];
          } else {
            const targetIsOptional = !!(propName && (getPropertyOfType(target, propName) || unknownSymbol).flags & SymbolFlags.Optional);
            const sourceIsOptional = !!(propName && (getPropertyOfType(source, propName) || unknownSymbol).flags & SymbolFlags.Optional);
            targetPropType = removeMissingType(targetPropType, targetIsOptional);
            sourcePropType = removeMissingType(sourcePropType, targetIsOptional && sourceIsOptional);
            const result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
            if (result && specificSource !== sourcePropType) {
              checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
            }
          }
          if (resultObj.errors) {
            const reportedDiag = resultObj.errors[resultObj.errors.length - 1];
            const propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : void 0;
            const targetProp = propertyName !== void 0 ? getPropertyOfType(target, propertyName) : void 0;
            let issuedElaboration = false;
            if (!targetProp) {
              const indexInfo = getApplicableIndexInfo(target, nameType);
              if (indexInfo && indexInfo.declaration && !getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
                issuedElaboration = true;
                addRelatedInfo(reportedDiag, createDiagnosticForNode(indexInfo.declaration, Diagnostics.The_expected_type_comes_from_this_index_signature));
              }
            }
            if (!issuedElaboration && (targetProp && length(targetProp.declarations) || target.symbol && length(target.symbol.declarations))) {
              const targetNode = targetProp && length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
              if (!getSourceFileOfNode(targetNode).hasNoDefaultLib) {
                addRelatedInfo(
                  reportedDiag,
                  createDiagnosticForNode(
                    targetNode,
                    Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1,
                    propertyName && !(nameType.flags & TypeFlags.UniqueESSymbol) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType),
                    typeToString(target)
                  )
                );
              }
            }
          }
        }
      }
    }
    return reportedError;
  }
  function elaborateIterableOrArrayLikeTargetElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
    const tupleOrArrayLikeTargetParts = filterType(target, isArrayOrTupleLikeType);
    const nonTupleOrArrayLikeTargetParts = filterType(target, (t) => !isArrayOrTupleLikeType(t));
    const iterationType = nonTupleOrArrayLikeTargetParts !== neverType ? getIterationTypeOfIterable(
      13 /* ForOf */,
      0 /* Yield */,
      nonTupleOrArrayLikeTargetParts,
      /*errorNode*/
      void 0
    ) : void 0;
    let reportedError = false;
    for (let status = iterator.next(); !status.done; status = iterator.next()) {
      const { errorNode: prop, innerExpression: next, nameType, errorMessage } = status.value;
      let targetPropType = iterationType;
      const targetIndexedPropType = tupleOrArrayLikeTargetParts !== neverType ? getBestMatchIndexedAccessTypeOrUndefined(source, tupleOrArrayLikeTargetParts, nameType) : void 0;
      if (targetIndexedPropType && !(targetIndexedPropType.flags & TypeFlags.IndexedAccess)) {
        targetPropType = iterationType ? getUnionType([iterationType, targetIndexedPropType]) : targetIndexedPropType;
      }
      if (!targetPropType) continue;
      let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
      if (!sourcePropType) continue;
      const propName = getPropertyNameFromIndex(
        nameType,
        /*accessNode*/
        void 0
      );
      if (!checkTypeRelatedTo(
        sourcePropType,
        targetPropType,
        relation,
        /*errorNode*/
        void 0
      )) {
        const elaborated = next && elaborateError(
          next,
          sourcePropType,
          targetPropType,
          relation,
          /*headMessage*/
          void 0,
          containingMessageChain,
          errorOutputContainer
        );
        reportedError = true;
        if (!elaborated) {
          const resultObj = errorOutputContainer || {};
          const specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
          if (exactOptionalPropertyTypes && isExactOptionalPropertyMismatch(specificSource, targetPropType)) {
            const diag = createDiagnosticForNode(prop, Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target, typeToString(specificSource), typeToString(targetPropType));
            diagnostics.add(diag);
            resultObj.errors = [diag];
          } else {
            const targetIsOptional = !!(propName && (getPropertyOfType(tupleOrArrayLikeTargetParts, propName) || unknownSymbol).flags & SymbolFlags.Optional);
            const sourceIsOptional = !!(propName && (getPropertyOfType(source, propName) || unknownSymbol).flags & SymbolFlags.Optional);
            targetPropType = removeMissingType(targetPropType, targetIsOptional);
            sourcePropType = removeMissingType(sourcePropType, targetIsOptional && sourceIsOptional);
            const result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
            if (result && specificSource !== sourcePropType) {
              checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
            }
          }
        }
      }
    }
    return reportedError;
  }
  function* generateJsxAttributes(node) {
    if (!length(node.properties)) return;
    for (const prop of node.properties) {
      if (isJsxSpreadAttribute(prop) || isHyphenatedJsxName(getTextOfJsxAttributeName(prop.name))) continue;
      yield { errorNode: prop.name, innerExpression: prop.initializer, nameType: getStringLiteralType(getTextOfJsxAttributeName(prop.name)) };
    }
  }
  function* generateJsxChildren(node, getInvalidTextDiagnostic) {
    if (!length(node.children)) return;
    let memberOffset = 0;
    for (let i = 0; i < node.children.length; i++) {
      const child = node.children[i];
      const nameType = getNumberLiteralType(i - memberOffset);
      const elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
      if (elem) {
        yield elem;
      } else {
        memberOffset++;
      }
    }
  }
  function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
    switch (child.kind) {
      case SyntaxKind.JsxExpression:
        return { errorNode: child, innerExpression: child.expression, nameType };
      case SyntaxKind.JsxText:
        if (child.containsOnlyTriviaWhiteSpaces) {
          break;
        }
        return { errorNode: child, innerExpression: void 0, nameType, errorMessage: getInvalidTextDiagnostic() };
      case SyntaxKind.JsxElement:
      case SyntaxKind.JsxSelfClosingElement:
      case SyntaxKind.JsxFragment:
        return { errorNode: child, innerExpression: child, nameType };
      default:
        return Debug.assertNever(child, "Found invalid jsx child");
    }
  }
  function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
    let result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
    let invalidTextDiagnostic;
    if (isJsxOpeningElement(node.parent) && isJsxElement(node.parent.parent)) {
      const containingElement = node.parent.parent;
      const childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
      const childrenPropName = childPropName === void 0 ? "children" : unescapeLeadingUnderscores(childPropName);
      const childrenNameType = getStringLiteralType(childrenPropName);
      const childrenTargetType = getIndexedAccessType(target, childrenNameType);
      const validChildren = getSemanticJsxChildren(containingElement.children);
      if (!length(validChildren)) {
        return result;
      }
      const moreThanOneRealChildren = length(validChildren) > 1;
      let arrayLikeTargetParts;
      let nonArrayLikeTargetParts;
      const iterableType = getGlobalIterableType(
        /*reportErrors*/
        false
      );
      if (iterableType !== emptyGenericType) {
        const anyIterable = createIterableType(anyType);
        arrayLikeTargetParts = filterType(childrenTargetType, (t) => isTypeAssignableTo(t, anyIterable));
        nonArrayLikeTargetParts = filterType(childrenTargetType, (t) => !isTypeAssignableTo(t, anyIterable));
      } else {
        arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
        nonArrayLikeTargetParts = filterType(childrenTargetType, (t) => !isArrayOrTupleLikeType(t));
      }
      if (moreThanOneRealChildren) {
        if (arrayLikeTargetParts !== neverType) {
          const realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
          const children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
          result = elaborateIterableOrArrayLikeTargetElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
        } else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
          result = true;
          const diag = error(
            containingElement.openingElement.tagName,
            Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided,
            childrenPropName,
            typeToString(childrenTargetType)
          );
          if (errorOutputContainer && errorOutputContainer.skipLogging) {
            (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
          }
        }
      } else {
        if (nonArrayLikeTargetParts !== neverType) {
          const child = validChildren[0];
          const elem = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
          if (elem) {
            result = elaborateElementwise(
              function* () {
                yield elem;
              }(),
              source,
              target,
              relation,
              containingMessageChain,
              errorOutputContainer
            ) || result;
          }
        } else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
          result = true;
          const diag = error(
            containingElement.openingElement.tagName,
            Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided,
            childrenPropName,
            typeToString(childrenTargetType)
          );
          if (errorOutputContainer && errorOutputContainer.skipLogging) {
            (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
          }
        }
      }
    }
    return result;
    function getInvalidTextualChildDiagnostic() {
      if (!invalidTextDiagnostic) {
        const tagNameText = getTextOfNode(node.parent.tagName);
        const childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
        const childrenPropName = childPropName === void 0 ? "children" : unescapeLeadingUnderscores(childPropName);
        const childrenTargetType = getIndexedAccessType(target, getStringLiteralType(childrenPropName));
        const diagnostic = Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2;
        invalidTextDiagnostic = { ...diagnostic, key: "!!ALREADY FORMATTED!!", message: formatMessage(diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) };
      }
      return invalidTextDiagnostic;
    }
  }
  function* generateLimitedTupleElements(node, target) {
    const len = length(node.elements);
    if (!len) return;
    for (let i = 0; i < len; i++) {
      if (isTupleLikeType(target) && !getPropertyOfType(target, "" + i)) continue;
      const elem = node.elements[i];
      if (isOmittedExpression(elem)) continue;
      const nameType = getNumberLiteralType(i);
      const checkNode = getEffectiveCheckNode(elem);
      yield { errorNode: checkNode, innerExpression: checkNode, nameType };
    }
  }
  function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
    if (target.flags & (TypeFlags.Primitive | TypeFlags.Never)) return false;
    if (isTupleLikeType(source)) {
      return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
    }
    pushContextualType(
      node,
      target,
      /*isCache*/
      false
    );
    const tupleizedType = checkArrayLiteral(
      node,
      1 /* Contextual */,
      /*forceTuple*/
      true
    );
    popContextualType();
    if (isTupleLikeType(tupleizedType)) {
      return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
    }
    return false;
  }
  function* generateObjectLiteralElements(node) {
    if (!length(node.properties)) return;
    for (const prop of node.properties) {
      if (isSpreadAssignment(prop)) continue;
      const type = getLiteralTypeFromProperty(getSymbolOfDeclaration(prop), TypeFlags.StringOrNumberLiteralOrUnique);
      if (!type || type.flags & TypeFlags.Never) {
        continue;
      }
      switch (prop.kind) {
        case SyntaxKind.SetAccessor:
        case SyntaxKind.GetAccessor:
        case SyntaxKind.MethodDeclaration:
        case SyntaxKind.ShorthandPropertyAssignment:
          yield { errorNode: prop.name, innerExpression: void 0, nameType: type };
          break;
        case SyntaxKind.PropertyAssignment:
          yield { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : void 0 };
          break;
        default:
          Debug.assertNever(prop);
      }
    }
  }
  function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
    if (target.flags & (TypeFlags.Primitive | TypeFlags.Never)) return false;
    return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
  }
  function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
    return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
  }
  function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
    return compareSignaturesRelated(
      source,
      target,
      ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0 /* None */,
      /*reportErrors*/
      false,
      /*errorReporter*/
      void 0,
      /*incompatibleErrorReporter*/
      void 0,
      compareTypesAssignable,
      /*reportUnreliableMarkers*/
      void 0
    ) !== Ternary.False;
  }
  function isTopSignature(s) {
    if (!s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && signatureHasRestParameter(s)) {
      const paramType = getTypeOfParameter(s.parameters[0]);
      const restType = isArrayType(paramType) ? getTypeArguments(paramType)[0] : paramType;
      return !!(restType.flags & (TypeFlags.Any | TypeFlags.Never) && getReturnTypeOfSignature(s).flags & TypeFlags.AnyOrUnknown);
    }
    return false;
  }
  function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
    if (source === target) {
      return Ternary.True;
    }
    if (!(checkMode & 16 /* StrictTopSignature */ && isTopSignature(source)) && isTopSignature(target)) {
      return Ternary.True;
    }
    if (checkMode & 16 /* StrictTopSignature */ && isTopSignature(source) && !isTopSignature(target)) {
      return Ternary.False;
    }
    const targetCount = getParameterCount(target);
    const sourceHasMoreParameters = !hasEffectiveRestParameter(target) && (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
    if (sourceHasMoreParameters) {
      if (reportErrors && !(checkMode & 8 /* StrictArity */)) {
        errorReporter(Diagnostics.Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1, getMinArgumentCount(source), targetCount);
      }
      return Ternary.False;
    }
    if (source.typeParameters && source.typeParameters !== target.typeParameters) {
      target = getCanonicalSignature(target);
      source = instantiateSignatureInContextOf(
        source,
        target,
        /*inferenceContext*/
        void 0,
        compareTypes
      );
    }
    const sourceCount = getParameterCount(source);
    const sourceRestType = getNonArrayRestType(source);
    const targetRestType = getNonArrayRestType(target);
    if (sourceRestType || targetRestType) {
      void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
    }
    const kind = target.declaration ? target.declaration.kind : SyntaxKind.Unknown;
    const strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== SyntaxKind.MethodDeclaration && kind !== SyntaxKind.MethodSignature && kind !== SyntaxKind.Constructor;
    let result = Ternary.True;
    const sourceThisType = getThisTypeOfSignature(source);
    if (sourceThisType && sourceThisType !== voidType) {
      const targetThisType = getThisTypeOfSignature(target);
      if (targetThisType) {
        const related = !strictVariance && compareTypes(
          sourceThisType,
          targetThisType,
          /*reportErrors*/
          false
        ) || compareTypes(targetThisType, sourceThisType, reportErrors);
        if (!related) {
          if (reportErrors) {
            errorReporter(Diagnostics.The_this_types_of_each_signature_are_incompatible);
          }
          return Ternary.False;
        }
        result &= related;
      }
    }
    const paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
    const restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
    for (let i = 0; i < paramCount; i++) {
      const sourceType = i === restIndex ? getRestOrAnyTypeAtPosition(source, i) : tryGetTypeAtPosition(source, i);
      const targetType = i === restIndex ? getRestOrAnyTypeAtPosition(target, i) : tryGetTypeAtPosition(target, i);
      if (sourceType && targetType && (sourceType !== targetType || checkMode & 8 /* StrictArity */)) {
        const sourceSig = checkMode & 3 /* Callback */ || isInstantiatedGenericParameter(source, i) ? void 0 : getSingleCallSignature(getNonNullableType(sourceType));
        const targetSig = checkMode & 3 /* Callback */ || isInstantiatedGenericParameter(target, i) ? void 0 : getSingleCallSignature(getNonNullableType(targetType));
        const callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && getTypeFacts(sourceType, 50331648 /* IsUndefinedOrNull */) === getTypeFacts(targetType, 50331648 /* IsUndefinedOrNull */);
        let related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, checkMode & 8 /* StrictArity */ | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(
          sourceType,
          targetType,
          /*reportErrors*/
          false
        ) || compareTypes(targetType, sourceType, reportErrors);
        if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(
          sourceType,
          targetType,
          /*reportErrors*/
          false
        )) {
          related = Ternary.False;
        }
        if (!related) {
          if (reportErrors) {
            errorReporter(Diagnostics.Types_of_parameters_0_and_1_are_incompatible, unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
          }
          return Ternary.False;
        }
        result &= related;
      }
    }
    if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
      const targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol)) : getReturnTypeOfSignature(target);
      if (targetReturnType === voidType || targetReturnType === anyType) {
        return result;
      }
      const sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol)) : getReturnTypeOfSignature(source);
      const targetTypePredicate = getTypePredicateOfSignature(target);
      if (targetTypePredicate) {
        const sourceTypePredicate = getTypePredicateOfSignature(source);
        if (sourceTypePredicate) {
          result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
        } else if (isIdentifierTypePredicate(targetTypePredicate) || isThisTypePredicate(targetTypePredicate)) {
          if (reportErrors) {
            errorReporter(Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
          }
          return Ternary.False;
        }
      } else {
        result &= checkMode & 1 /* BivariantCallback */ && compareTypes(
          targetReturnType,
          sourceReturnType,
          /*reportErrors*/
          false
        ) || compareTypes(sourceReturnType, targetReturnType, reportErrors);
        if (!result && reportErrors && incompatibleErrorReporter) {
          incompatibleErrorReporter(sourceReturnType, targetReturnType);
        }
      }
    }
    return result;
  }
  function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
    if (source.kind !== target.kind) {
      if (reportErrors) {
        errorReporter(Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
        errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
      }
      return Ternary.False;
    }
    if (source.kind === TypePredicateKind.Identifier || source.kind === TypePredicateKind.AssertsIdentifier) {
      if (source.parameterIndex !== target.parameterIndex) {
        if (reportErrors) {
          errorReporter(Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
          errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
        }
        return Ternary.False;
      }
    }
    const related = source.type === target.type ? Ternary.True : source.type && target.type ? compareTypes(source.type, target.type, reportErrors) : Ternary.False;
    if (related === Ternary.False && reportErrors) {
      errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
    }
    return related;
  }
  function isImplementationCompatibleWithOverload(implementation, overload) {
    const erasedSource = getErasedSignature(implementation);
    const erasedTarget = getErasedSignature(overload);
    const sourceReturnType = getReturnTypeOfSignature(erasedSource);
    const targetReturnType = getReturnTypeOfSignature(erasedTarget);
    if (targetReturnType === voidType || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
      return isSignatureAssignableTo(
        erasedSource,
        erasedTarget,
        /*ignoreReturnTypes*/
        true
      );
    }
    return false;
  }
  function isEmptyResolvedType(t) {
    return t !== anyFunctionType && t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && t.indexInfos.length === 0;
  }
  function isEmptyObjectType(type) {
    return type.flags & TypeFlags.Object ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & TypeFlags.NonPrimitive ? true : type.flags & TypeFlags.Union ? some(type.types, isEmptyObjectType) : type.flags & TypeFlags.Intersection ? every(type.types, isEmptyObjectType) : false;
  }
  function isEmptyAnonymousObjectType(type) {
    return !!(getObjectFlags(type) & ObjectFlags.Anonymous && (type.members && isEmptyResolvedType(type) || type.symbol && type.symbol.flags & SymbolFlags.TypeLiteral && getMembersOfSymbol(type.symbol).size === 0));
  }
  function isUnknownLikeUnionType(type) {
    if (strictNullChecks && type.flags & TypeFlags.Union) {
      if (!(type.objectFlags & ObjectFlags.IsUnknownLikeUnionComputed)) {
        const types = type.types;
        type.objectFlags |= ObjectFlags.IsUnknownLikeUnionComputed | (types.length >= 3 && types[0].flags & TypeFlags.Undefined && types[1].flags & TypeFlags.Null && some(types, isEmptyAnonymousObjectType) ? ObjectFlags.IsUnknownLikeUnion : 0);
      }
      return !!(type.objectFlags & ObjectFlags.IsUnknownLikeUnion);
    }
    return false;
  }
  function containsUndefinedType(type) {
    return !!((type.flags & TypeFlags.Union ? type.types[0] : type).flags & TypeFlags.Undefined);
  }
  function containsNonMissingUndefinedType(type) {
    const candidate = type.flags & TypeFlags.Union ? type.types[0] : type;
    return !!(candidate.flags & TypeFlags.Undefined) && candidate !== missingType;
  }
  function isStringIndexSignatureOnlyType(type) {
    return type.flags & TypeFlags.Object && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) || type.flags & TypeFlags.UnionOrIntersection && every(type.types, isStringIndexSignatureOnlyType) || false;
  }
  function isEnumTypeRelatedTo(source, target, errorReporter) {
    const sourceSymbol = source.flags & SymbolFlags.EnumMember ? getParentOfSymbol(source) : source;
    const targetSymbol = target.flags & SymbolFlags.EnumMember ? getParentOfSymbol(target) : target;
    if (sourceSymbol === targetSymbol) {
      return true;
    }
    if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & SymbolFlags.RegularEnum) || !(targetSymbol.flags & SymbolFlags.RegularEnum)) {
      return false;
    }
    const id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
    const entry = enumRelation.get(id);
    if (entry !== void 0 && !(entry & RelationComparisonResult.Failed && errorReporter)) {
      return !!(entry & RelationComparisonResult.Succeeded);
    }
    const targetEnumType = getTypeOfSymbol(targetSymbol);
    for (const sourceProperty of getPropertiesOfType(getTypeOfSymbol(sourceSymbol))) {
      if (sourceProperty.flags & SymbolFlags.EnumMember) {
        const targetProperty = getPropertyOfType(targetEnumType, sourceProperty.escapedName);
        if (!targetProperty || !(targetProperty.flags & SymbolFlags.EnumMember)) {
          if (errorReporter) {
            errorReporter(Diagnostics.Property_0_is_missing_in_type_1, symbolName(sourceProperty), typeToString(
              getDeclaredTypeOfSymbol(targetSymbol),
              /*enclosingDeclaration*/
              void 0,
              TypeFormatFlags.UseFullyQualifiedType
            ));
          }
          enumRelation.set(id, RelationComparisonResult.Failed);
          return false;
        }
        const sourceValue = getEnumMemberValue(getDeclarationOfKind(sourceProperty, SyntaxKind.EnumMember)).value;
        const targetValue = getEnumMemberValue(getDeclarationOfKind(targetProperty, SyntaxKind.EnumMember)).value;
        if (sourceValue !== targetValue) {
          const sourceIsString = typeof sourceValue === "string";
          const targetIsString = typeof targetValue === "string";
          if (sourceValue !== void 0 && targetValue !== void 0) {
            if (errorReporter) {
              const escapedSource = sourceIsString ? `"${escapeString(sourceValue)}"` : sourceValue;
              const escapedTarget = targetIsString ? `"${escapeString(targetValue)}"` : targetValue;
              errorReporter(Diagnostics.Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given, symbolName(targetSymbol), symbolName(targetProperty), escapedTarget, escapedSource);
            }
            enumRelation.set(id, RelationComparisonResult.Failed);
            return false;
          }
          if (sourceIsString || targetIsString) {
            if (errorReporter) {
              const knownStringValue = sourceValue ?? targetValue;
              Debug.assert(typeof knownStringValue === "string");
              const escapedValue = `"${escapeString(knownStringValue)}"`;
              errorReporter(Diagnostics.One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value, symbolName(targetSymbol), symbolName(targetProperty), escapedValue);
            }
            enumRelation.set(id, RelationComparisonResult.Failed);
            return false;
          }
        }
      }
    }
    enumRelation.set(id, RelationComparisonResult.Succeeded);
    return true;
  }
  function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
    const s = source.flags;
    const t = target.flags;
    if (t & TypeFlags.Any || s & TypeFlags.Never || source === wildcardType) return true;
    if (t & TypeFlags.Unknown && !(relation === strictSubtypeRelation && s & TypeFlags.Any)) return true;
    if (t & TypeFlags.Never) return false;
    if (s & TypeFlags.StringLike && t & TypeFlags.String) return true;
    if (s & TypeFlags.StringLiteral && s & TypeFlags.EnumLiteral && t & TypeFlags.StringLiteral && !(t & TypeFlags.EnumLiteral) && source.value === target.value) return true;
    if (s & TypeFlags.NumberLike && t & TypeFlags.Number) return true;
    if (s & TypeFlags.NumberLiteral && s & TypeFlags.EnumLiteral && t & TypeFlags.NumberLiteral && !(t & TypeFlags.EnumLiteral) && source.value === target.value) return true;
    if (s & TypeFlags.BigIntLike && t & TypeFlags.BigInt) return true;
    if (s & TypeFlags.BooleanLike && t & TypeFlags.Boolean) return true;
    if (s & TypeFlags.ESSymbolLike && t & TypeFlags.ESSymbol) return true;
    if (s & TypeFlags.Enum && t & TypeFlags.Enum && source.symbol.escapedName === target.symbol.escapedName && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true;
    if (s & TypeFlags.EnumLiteral && t & TypeFlags.EnumLiteral) {
      if (s & TypeFlags.Union && t & TypeFlags.Union && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true;
      if (s & TypeFlags.Literal && t & TypeFlags.Literal && source.value === target.value && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true;
    }
    if (s & TypeFlags.Undefined && (!strictNullChecks && !(t & TypeFlags.UnionOrIntersection) || t & (TypeFlags.Undefined | TypeFlags.Void))) return true;
    if (s & TypeFlags.Null && (!strictNullChecks && !(t & TypeFlags.UnionOrIntersection) || t & TypeFlags.Null)) return true;
    if (s & TypeFlags.Object && t & TypeFlags.NonPrimitive && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(getObjectFlags(source) & ObjectFlags.FreshLiteral))) return true;
    if (relation === assignableRelation || relation === comparableRelation) {
      if (s & TypeFlags.Any) return true;
      if (s & TypeFlags.Number && (t & TypeFlags.Enum || t & TypeFlags.NumberLiteral && t & TypeFlags.EnumLiteral)) return true;
      if (s & TypeFlags.NumberLiteral && !(s & TypeFlags.EnumLiteral) && (t & TypeFlags.Enum || t & TypeFlags.NumberLiteral && t & TypeFlags.EnumLiteral && source.value === target.value)) return true;
      if (isUnknownLikeUnionType(target)) return true;
    }
    return false;
  }
  function isTypeRelatedTo(source, target, relation) {
    if (isFreshLiteralType(source)) {
      source = source.regularType;
    }
    if (isFreshLiteralType(target)) {
      target = target.regularType;
    }
    if (source === target) {
      return true;
    }
    if (relation !== identityRelation) {
      if (relation === comparableRelation && !(target.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
        return true;
      }
    } else if (!((source.flags | target.flags) & (TypeFlags.UnionOrIntersection | TypeFlags.IndexedAccess | TypeFlags.Conditional | TypeFlags.Substitution))) {
      if (source.flags !== target.flags) return false;
      if (source.flags & TypeFlags.Singleton) return true;
    }
    if (source.flags & TypeFlags.Object && target.flags & TypeFlags.Object) {
      const related = relation.get(getRelationKey(
        source,
        target,
        0 /* None */,
        relation,
        /*ignoreConstraints*/
        false
      ));
      if (related !== void 0) {
        return !!(related & RelationComparisonResult.Succeeded);
      }
    }
    if (source.flags & TypeFlags.StructuredOrInstantiable || target.flags & TypeFlags.StructuredOrInstantiable) {
      return checkTypeRelatedTo(
        source,
        target,
        relation,
        /*errorNode*/
        void 0
      );
    }
    return false;
  }
  function isIgnoredJsxProperty(source, sourceProp) {
    return getObjectFlags(source) & ObjectFlags.JsxAttributes && isHyphenatedJsxName(sourceProp.escapedName);
  }
  function getNormalizedType(type, writing) {
    while (true) {
      const t = isFreshLiteralType(type) ? type.regularType : isGenericTupleType(type) ? getNormalizedTupleType(type, writing) : getObjectFlags(type) & ObjectFlags.Reference ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : type.flags & TypeFlags.UnionOrIntersection ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & TypeFlags.Substitution ? writing ? type.baseType : getSubstitutionIntersection(type) : type.flags & TypeFlags.Simplifiable ? getSimplifiedType(type, writing) : type;
      if (t === type) return t;
      type = t;
    }
  }
  function getNormalizedUnionOrIntersectionType(type, writing) {
    const reduced = getReducedType(type);
    if (reduced !== type) {
      return reduced;
    }
    if (type.flags & TypeFlags.Intersection && shouldNormalizeIntersection(type)) {
      const normalizedTypes = sameMap(type.types, (t) => getNormalizedType(t, writing));
      if (normalizedTypes !== type.types) {
        return getIntersectionType(normalizedTypes);
      }
    }
    return type;
  }
  function shouldNormalizeIntersection(type) {
    let hasInstantiable = false;
    let hasNullableOrEmpty = false;
    for (const t of type.types) {
      hasInstantiable ||= !!(t.flags & TypeFlags.Instantiable);
      hasNullableOrEmpty ||= !!(t.flags & TypeFlags.Nullable) || isEmptyAnonymousObjectType(t);
      if (hasInstantiable && hasNullableOrEmpty) return true;
    }
    return false;
  }
  function getNormalizedTupleType(type, writing) {
    const elements = getElementTypes(type);
    const normalizedElements = sameMap(elements, (t) => t.flags & TypeFlags.Simplifiable ? getSimplifiedType(t, writing) : t);
    return elements !== normalizedElements ? createNormalizedTupleType(type.target, normalizedElements) : type;
  }
  function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
    let errorInfo;
    let relatedInfo;
    let maybeKeys;
    let maybeKeysSet;
    let sourceStack;
    let targetStack;
    let maybeCount = 0;
    let sourceDepth = 0;
    let targetDepth = 0;
    let expandingFlags = 0 /* None */;
    let overflow = false;
    let overrideNextErrorInfo = 0;
    let skipParentCounter = 0;
    let lastSkippedInfo;
    let incompatibleStack;
    let relationCount = 16e6 - relation.size >> 3;
    Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
    const result = isRelatedTo(
      source,
      target,
      3 /* Both */,
      /*reportErrors*/
      !!errorNode,
      headMessage
    );
    if (incompatibleStack) {
      reportIncompatibleStack();
    }
    if (overflow) {
      const id = getRelationKey(
        source,
        target,
        /*intersectionState*/
        0 /* None */,
        relation,
        /*ignoreConstraints*/
        false
      );
      relation.set(id, RelationComparisonResult.Failed | (relationCount <= 0 ? RelationComparisonResult.ComplexityOverflow : RelationComparisonResult.StackDepthOverflow));
      tracing?.instant(tracing.Phase.CheckTypes, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: sourceDepth, targetDepth });
      const message = relationCount <= 0 ? Diagnostics.Excessive_complexity_comparing_types_0_and_1 : Diagnostics.Excessive_stack_depth_comparing_types_0_and_1;
      const diag = error(errorNode || currentNode, message, typeToString(source), typeToString(target));
      if (errorOutputContainer) {
        (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
      }
    } else if (errorInfo) {
      if (containingMessageChain) {
        const chain = containingMessageChain();
        if (chain) {
          concatenateDiagnosticMessageChains(chain, errorInfo);
          errorInfo = chain;
        }
      }
      let relatedInformation;
      if (headMessage && errorNode && !result && source.symbol) {
        const links = getSymbolLinks(source.symbol);
        if (links.originatingImport && !isImportCall(links.originatingImport)) {
          const helpfulRetry = checkTypeRelatedTo(
            getTypeOfSymbol(links.target),
            target,
            relation,
            /*errorNode*/
            void 0
          );
          if (helpfulRetry) {
            const diag2 = createDiagnosticForNode(links.originatingImport, Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead);
            relatedInformation = append(relatedInformation, diag2);
          }
        }
      }
      const diag = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorNode), errorNode, errorInfo, relatedInformation);
      if (relatedInfo) {
        addRelatedInfo(diag, ...relatedInfo);
      }
      if (errorOutputContainer) {
        (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
      }
      if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
        diagnostics.add(diag);
      }
    }
    if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === Ternary.False) {
      Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
    }
    return result !== Ternary.False;
    function resetErrorInfo(saved) {
      errorInfo = saved.errorInfo;
      lastSkippedInfo = saved.lastSkippedInfo;
      incompatibleStack = saved.incompatibleStack;
      overrideNextErrorInfo = saved.overrideNextErrorInfo;
      skipParentCounter = saved.skipParentCounter;
      relatedInfo = saved.relatedInfo;
    }
    function captureErrorCalculationState() {
      return {
        errorInfo,
        lastSkippedInfo,
        incompatibleStack: incompatibleStack?.slice(),
        overrideNextErrorInfo,
        skipParentCounter,
        relatedInfo: relatedInfo?.slice()
      };
    }
    function reportIncompatibleError(message, ...args) {
      overrideNextErrorInfo++;
      lastSkippedInfo = void 0;
      (incompatibleStack ||= []).push([message, ...args]);
    }
    function reportIncompatibleStack() {
      const stack = incompatibleStack || [];
      incompatibleStack = void 0;
      const info = lastSkippedInfo;
      lastSkippedInfo = void 0;
      if (stack.length === 1) {
        reportError(...stack[0]);
        if (info) {
          reportRelationError(
            /*message*/
            void 0,
            ...info
          );
        }
        return;
      }
      let path = "";
      const secondaryRootErrors = [];
      while (stack.length) {
        const [msg, ...args] = stack.pop();
        switch (msg.code) {
          case Diagnostics.Types_of_property_0_are_incompatible.code: {
            if (path.indexOf("new ") === 0) {
              path = `(${path})`;
            }
            const str = "" + args[0];
            if (path.length === 0) {
              path = `${str}`;
            } else if (isIdentifierText(str, getEmitScriptTarget(compilerOptions))) {
              path = `${path}.${str}`;
            } else if (str[0] === "[" && str[str.length - 1] === "]") {
              path = `${path}${str}`;
            } else {
              path = `${path}[${str}]`;
            }
            break;
          }
          case Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
          case Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
          case Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
          case Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
            if (path.length === 0) {
              let mappedMsg = msg;
              if (msg.code === Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
                mappedMsg = Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
              } else if (msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
                mappedMsg = Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
              }
              secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
            } else {
              const prefix = msg.code === Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code || msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ? "new " : "";
              const params = msg.code === Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code || msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ? "" : "...";
              path = `${prefix}${path}(${params})`;
            }
            break;
          }
          case Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: {
            secondaryRootErrors.unshift([Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]);
            break;
          }
          case Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: {
            secondaryRootErrors.unshift([Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]);
            break;
          }
          default:
            return Debug.fail(`Unhandled Diagnostic: ${msg.code}`);
        }
      }
      if (path) {
        reportError(
          path[path.length - 1] === ")" ? Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types : Diagnostics.The_types_of_0_are_incompatible_between_these_types,
          path
        );
      } else {
        secondaryRootErrors.shift();
      }
      for (const [msg, ...args] of secondaryRootErrors) {
        const originalValue = msg.elidedInCompatabilityPyramid;
        msg.elidedInCompatabilityPyramid = false;
        reportError(msg, ...args);
        msg.elidedInCompatabilityPyramid = originalValue;
      }
      if (info) {
        reportRelationError(
          /*message*/
          void 0,
          ...info
        );
      }
    }
    function reportError(message, ...args) {
      Debug.assert(!!errorNode);
      if (incompatibleStack) reportIncompatibleStack();
      if (message.elidedInCompatabilityPyramid) return;
      if (skipParentCounter === 0) {
        errorInfo = chainDiagnosticMessages(errorInfo, message, ...args);
      } else {
        skipParentCounter--;
      }
    }
    function reportParentSkippedError(message, ...args) {
      reportError(message, ...args);
      skipParentCounter++;
    }
    function associateRelatedInfo(info) {
      Debug.assert(!!errorInfo);
      if (!relatedInfo) {
        relatedInfo = [info];
      } else {
        relatedInfo.push(info);
      }
    }
    function reportRelationError(message, source2, target2) {
      if (incompatibleStack) reportIncompatibleStack();
      const [sourceType, targetType] = getTypeNamesForErrorDisplay(source2, target2);
      let generalizedSource = source2;
      let generalizedSourceType = sourceType;
      if (isLiteralType(source2) && !typeCouldHaveTopLevelSingletonTypes(target2)) {
        generalizedSource = getBaseTypeOfLiteralType(source2);
        Debug.assert(!isTypeAssignableTo(generalizedSource, target2), "generalized source shouldn't be assignable");
        generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource);
      }
      const targetFlags = target2.flags & TypeFlags.IndexedAccess && !(source2.flags & TypeFlags.IndexedAccess) ? target2.objectType.flags : target2.flags;
      if (targetFlags & TypeFlags.TypeParameter && target2 !== markerSuperTypeForCheck && target2 !== markerSubTypeForCheck) {
        const constraint = getBaseConstraintOfType(target2);
        let needsOriginalSource;
        if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source2, constraint)))) {
          reportError(
            Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2,
            needsOriginalSource ? sourceType : generalizedSourceType,
            targetType,
            typeToString(constraint)
          );
        } else {
          errorInfo = void 0;
          reportError(
            Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1,
            targetType,
            generalizedSourceType
          );
        }
      }
      if (!message) {
        if (relation === comparableRelation) {
          message = Diagnostics.Type_0_is_not_comparable_to_type_1;
        } else if (sourceType === targetType) {
          message = Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
        } else if (exactOptionalPropertyTypes && getExactOptionalUnassignableProperties(source2, target2).length) {
          message = Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties;
        } else {
          if (source2.flags & TypeFlags.StringLiteral && target2.flags & TypeFlags.Union) {
            const suggestedType = getSuggestedTypeForNonexistentStringLiteralType(source2, target2);
            if (suggestedType) {
              reportError(Diagnostics.Type_0_is_not_assignable_to_type_1_Did_you_mean_2, generalizedSourceType, targetType, typeToString(suggestedType));
              return;
            }
          }
          message = Diagnostics.Type_0_is_not_assignable_to_type_1;
        }
      } else if (message === Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1 && exactOptionalPropertyTypes && getExactOptionalUnassignableProperties(source2, target2).length) {
        message = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties;
      }
      reportError(message, generalizedSourceType, targetType);
    }
    function tryElaborateErrorsForPrimitivesAndObjects(source2, target2) {
      const sourceType = symbolValueDeclarationIsContextSensitive(source2.symbol) ? typeToString(source2, source2.symbol.valueDeclaration) : typeToString(source2);
      const targetType = symbolValueDeclarationIsContextSensitive(target2.symbol) ? typeToString(target2, target2.symbol.valueDeclaration) : typeToString(target2);
      if (globalStringType === source2 && stringType === target2 || globalNumberType === source2 && numberType === target2 || globalBooleanType === source2 && booleanType === target2 || getGlobalESSymbolType() === source2 && esSymbolType === target2) {
        reportError(Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
      }
    }
    function tryElaborateArrayLikeErrors(source2, target2, reportErrors) {
      if (isTupleType(source2)) {
        if (source2.target.readonly && isMutableArrayOrTuple(target2)) {
          if (reportErrors) {
            reportError(Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source2), typeToString(target2));
          }
          return false;
        }
        return isArrayOrTupleType(target2);
      }
      if (isReadonlyArrayType(source2) && isMutableArrayOrTuple(target2)) {
        if (reportErrors) {
          reportError(Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source2), typeToString(target2));
        }
        return false;
      }
      if (isTupleType(target2)) {
        return isArrayType(source2);
      }
      return true;
    }
    function isRelatedToWorker(source2, target2, reportErrors) {
      return isRelatedTo(source2, target2, 3 /* Both */, reportErrors);
    }
    function isRelatedTo(originalSource, originalTarget, recursionFlags = 3 /* Both */, reportErrors = false, headMessage2, intersectionState = 0 /* None */) {
      if (originalSource === originalTarget) return Ternary.True;
      if (originalSource.flags & TypeFlags.Object && originalTarget.flags & TypeFlags.Primitive) {
        if (relation === comparableRelation && !(originalTarget.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : void 0)) {
          return Ternary.True;
        }
        if (reportErrors) {
          reportErrorResults(originalSource, originalTarget, originalSource, originalTarget, headMessage2);
        }
        return Ternary.False;
      }
      const source2 = getNormalizedType(
        originalSource,
        /*writing*/
        false
      );
      let target2 = getNormalizedType(
        originalTarget,
        /*writing*/
        true
      );
      if (source2 === target2) return Ternary.True;
      if (relation === identityRelation) {
        if (source2.flags !== target2.flags) return Ternary.False;
        if (source2.flags & TypeFlags.Singleton) return Ternary.True;
        traceUnionsOrIntersectionsTooLarge(source2, target2);
        return recursiveTypeRelatedTo(
          source2,
          target2,
          /*reportErrors*/
          false,
          0 /* None */,
          recursionFlags
        );
      }
      if (source2.flags & TypeFlags.TypeParameter && getConstraintOfType(source2) === target2) {
        return Ternary.True;
      }
      if (source2.flags & TypeFlags.DefinitelyNonNullable && target2.flags & TypeFlags.Union) {
        const types = target2.types;
        const candidate = types.length === 2 && types[0].flags & TypeFlags.Nullable ? types[1] : types.length === 3 && types[0].flags & TypeFlags.Nullable && types[1].flags & TypeFlags.Nullable ? types[2] : void 0;
        if (candidate && !(candidate.flags & TypeFlags.Nullable)) {
          target2 = getNormalizedType(
            candidate,
            /*writing*/
            true
          );
          if (source2 === target2) return Ternary.True;
        }
      }
      if (relation === comparableRelation && !(target2.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(target2, source2, relation) || isSimpleTypeRelatedTo(source2, target2, relation, reportErrors ? reportError : void 0)) return Ternary.True;
      if (source2.flags & TypeFlags.StructuredOrInstantiable || target2.flags & TypeFlags.StructuredOrInstantiable) {
        const isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source2) && getObjectFlags(source2) & ObjectFlags.FreshLiteral);
        if (isPerformingExcessPropertyChecks) {
          if (hasExcessProperties(source2, target2, reportErrors)) {
            if (reportErrors) {
              reportRelationError(headMessage2, source2, originalTarget.aliasSymbol ? originalTarget : target2);
            }
            return Ternary.False;
          }
        }
        const isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source2)) && !(intersectionState & 2 /* Target */) && source2.flags & (TypeFlags.Primitive | TypeFlags.Object | TypeFlags.Intersection) && source2 !== globalObjectType && target2.flags & (TypeFlags.Object | TypeFlags.Intersection) && isWeakType(target2) && (getPropertiesOfType(source2).length > 0 || typeHasCallOrConstructSignatures(source2));
        const isComparingJsxAttributes = !!(getObjectFlags(source2) & ObjectFlags.JsxAttributes);
        if (isPerformingCommonPropertyChecks && !hasCommonProperties(source2, target2, isComparingJsxAttributes)) {
          if (reportErrors) {
            const sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source2);
            const targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target2);
            const calls = getSignaturesOfType(source2, SignatureKind.Call);
            const constructs = getSignaturesOfType(source2, SignatureKind.Construct);
            if (calls.length > 0 && isRelatedTo(
              getReturnTypeOfSignature(calls[0]),
              target2,
              1 /* Source */,
              /*reportErrors*/
              false
            ) || constructs.length > 0 && isRelatedTo(
              getReturnTypeOfSignature(constructs[0]),
              target2,
              1 /* Source */,
              /*reportErrors*/
              false
            )) {
              reportError(Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString);
            } else {
              reportError(Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString);
            }
          }
          return Ternary.False;
        }
        traceUnionsOrIntersectionsTooLarge(source2, target2);
        const skipCaching = source2.flags & TypeFlags.Union && source2.types.length < 4 && !(target2.flags & TypeFlags.Union) || target2.flags & TypeFlags.Union && target2.types.length < 4 && !(source2.flags & TypeFlags.StructuredOrInstantiable);
        const result2 = skipCaching ? unionOrIntersectionRelatedTo(source2, target2, reportErrors, intersectionState) : recursiveTypeRelatedTo(source2, target2, reportErrors, intersectionState, recursionFlags);
        if (result2) {
          return result2;
        }
      }
      if (reportErrors) {
        reportErrorResults(originalSource, originalTarget, source2, target2, headMessage2);
      }
      return Ternary.False;
    }
    function reportErrorResults(originalSource, originalTarget, source2, target2, headMessage2) {
      const sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource);
      const targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget);
      source2 = originalSource.aliasSymbol || sourceHasBase ? originalSource : source2;
      target2 = originalTarget.aliasSymbol || targetHasBase ? originalTarget : target2;
      let maybeSuppress = overrideNextErrorInfo > 0;
      if (maybeSuppress) {
        overrideNextErrorInfo--;
      }
      if (source2.flags & TypeFlags.Object && target2.flags & TypeFlags.Object) {
        const currentError = errorInfo;
        tryElaborateArrayLikeErrors(
          source2,
          target2,
          /*reportErrors*/
          true
        );
        if (errorInfo !== currentError) {
          maybeSuppress = !!errorInfo;
        }
      }
      if (source2.flags & TypeFlags.Object && target2.flags & TypeFlags.Primitive) {
        tryElaborateErrorsForPrimitivesAndObjects(source2, target2);
      } else if (source2.symbol && source2.flags & TypeFlags.Object && globalObjectType === source2) {
        reportError(Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
      } else if (getObjectFlags(source2) & ObjectFlags.JsxAttributes && target2.flags & TypeFlags.Intersection) {
        const targetTypes = target2.types;
        const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
        const intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
        if (!isErrorType(intrinsicAttributes) && !isErrorType(intrinsicClassAttributes) && (contains(targetTypes, intrinsicAttributes) || contains(targetTypes, intrinsicClassAttributes))) {
          return;
        }
      } else {
        errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
      }
      if (!headMessage2 && maybeSuppress) {
        const savedErrorState = captureErrorCalculationState();
        reportRelationError(headMessage2, source2, target2);
        let canonical;
        if (errorInfo && errorInfo !== savedErrorState.errorInfo) {
          canonical = { code: errorInfo.code, messageText: errorInfo.messageText };
        }
        resetErrorInfo(savedErrorState);
        if (canonical && errorInfo) {
          errorInfo.canonicalHead = canonical;
        }
        lastSkippedInfo = [source2, target2];
        return;
      }
      reportRelationError(headMessage2, source2, target2);
      if (source2.flags & TypeFlags.TypeParameter && source2.symbol?.declarations?.[0] && !getConstraintOfType(source2)) {
        const syntheticParam = cloneTypeParameter(source2);
        syntheticParam.constraint = instantiateType(target2, makeUnaryTypeMapper(source2, syntheticParam));
        if (hasNonCircularBaseConstraint(syntheticParam)) {
          const targetConstraintString = typeToString(target2, source2.symbol.declarations[0]);
          associateRelatedInfo(createDiagnosticForNode(source2.symbol.declarations[0], Diagnostics.This_type_parameter_might_need_an_extends_0_constraint, targetConstraintString));
        }
      }
    }
    function traceUnionsOrIntersectionsTooLarge(source2, target2) {
      if (!tracing) {
        return;
      }
      if (source2.flags & TypeFlags.UnionOrIntersection && target2.flags & TypeFlags.UnionOrIntersection) {
        const sourceUnionOrIntersection = source2;
        const targetUnionOrIntersection = target2;
        if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & ObjectFlags.PrimitiveUnion) {
          return;
        }
        const sourceSize = sourceUnionOrIntersection.types.length;
        const targetSize = targetUnionOrIntersection.types.length;
        if (sourceSize * targetSize > 1e6) {
          tracing.instant(tracing.Phase.CheckTypes, "traceUnionsOrIntersectionsTooLarge_DepthLimit", {
            sourceId: source2.id,
            sourceSize,
            targetId: target2.id,
            targetSize,
            pos: errorNode?.pos,
            end: errorNode?.end
          });
        }
      }
    }
    function getTypeOfPropertyInTypes(types, name) {
      const appendPropType = (propTypes, type) => {
        type = getApparentType(type);
        const prop = type.flags & TypeFlags.UnionOrIntersection ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
        const propType = prop && getTypeOfSymbol(prop) || getApplicableIndexInfoForName(type, name)?.type || undefinedType;
        return append(propTypes, propType);
      };
      return getUnionType(reduceLeft(
        types,
        appendPropType,
        /*initial*/
        void 0
      ) || emptyArray);
    }
    function hasExcessProperties(source2, target2, reportErrors) {
      if (!isExcessPropertyCheckTarget(target2) || !noImplicitAny && getObjectFlags(target2) & ObjectFlags.JSLiteral) {
        return false;
      }
      const isComparingJsxAttributes = !!(getObjectFlags(source2) & ObjectFlags.JsxAttributes);
      if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target2) || !isComparingJsxAttributes && isEmptyObjectType(target2))) {
        return false;
      }
      let reducedTarget = target2;
      let checkTypes;
      if (target2.flags & TypeFlags.Union) {
        reducedTarget = findMatchingDiscriminantType(source2, target2, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target2);
        checkTypes = reducedTarget.flags & TypeFlags.Union ? reducedTarget.types : [reducedTarget];
      }
      for (const prop of getPropertiesOfType(source2)) {
        if (shouldCheckAsExcessProperty(prop, source2.symbol) && !isIgnoredJsxProperty(source2, prop)) {
          if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
            if (reportErrors) {
              const errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
              if (!errorNode) return Debug.fail();
              if (isJsxAttributes(errorNode) || isJsxOpeningLikeElement(errorNode) || isJsxOpeningLikeElement(errorNode.parent)) {
                if (prop.valueDeclaration && isJsxAttribute(prop.valueDeclaration) && getSourceFileOfNode(errorNode) === getSourceFileOfNode(prop.valueDeclaration.name)) {
                  errorNode = prop.valueDeclaration.name;
                }
                const propName = symbolToString(prop);
                const suggestionSymbol = getSuggestedSymbolForNonexistentJSXAttribute(propName, errorTarget);
                const suggestion = suggestionSymbol ? symbolToString(suggestionSymbol) : void 0;
                if (suggestion) {
                  reportError(Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(errorTarget), suggestion);
                } else {
                  reportError(Diagnostics.Property_0_does_not_exist_on_type_1, propName, typeToString(errorTarget));
                }
              } else {
                const objectLiteralDeclaration = source2.symbol?.declarations && firstOrUndefined(source2.symbol.declarations);
                let suggestion;
                if (prop.valueDeclaration && findAncestor(prop.valueDeclaration, (d) => d === objectLiteralDeclaration) && getSourceFileOfNode(objectLiteralDeclaration) === getSourceFileOfNode(errorNode)) {
                  const propDeclaration = prop.valueDeclaration;
                  Debug.assertNode(propDeclaration, isObjectLiteralElementLike);
                  const name = propDeclaration.name;
                  errorNode = name;
                  if (isIdentifier(name)) {
                    suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
                  }
                }
                if (suggestion !== void 0) {
                  reportParentSkippedError(Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion);
                } else {
                  reportParentSkippedError(Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
                }
              }
            }
            return true;
          }
          if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), 3 /* Both */, reportErrors)) {
            if (reportErrors) {
              reportIncompatibleError(Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
            }
            return true;
          }
        }
      }
      return false;
    }
    function shouldCheckAsExcessProperty(prop, container) {
      return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
    }
    function unionOrIntersectionRelatedTo(source2, target2, reportErrors, intersectionState) {
      if (source2.flags & TypeFlags.Union) {
        if (target2.flags & TypeFlags.Union) {
          const sourceOrigin = source2.origin;
          if (sourceOrigin && sourceOrigin.flags & TypeFlags.Intersection && target2.aliasSymbol && contains(sourceOrigin.types, target2)) {
            return Ternary.True;
          }
          const targetOrigin = target2.origin;
          if (targetOrigin && targetOrigin.flags & TypeFlags.Union && source2.aliasSymbol && contains(targetOrigin.types, source2)) {
            return Ternary.True;
          }
        }
        return relation === comparableRelation ? someTypeRelatedToType(source2, target2, reportErrors && !(source2.flags & TypeFlags.Primitive), intersectionState) : eachTypeRelatedToType(source2, target2, reportErrors && !(source2.flags & TypeFlags.Primitive), intersectionState);
      }
      if (target2.flags & TypeFlags.Union) {
        return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source2), target2, reportErrors && !(source2.flags & TypeFlags.Primitive) && !(target2.flags & TypeFlags.Primitive), intersectionState);
      }
      if (target2.flags & TypeFlags.Intersection) {
        return typeRelatedToEachType(source2, target2, reportErrors, 2 /* Target */);
      }
      if (relation === comparableRelation && target2.flags & TypeFlags.Primitive) {
        const constraints = sameMap(source2.types, (t) => t.flags & TypeFlags.Instantiable ? getBaseConstraintOfType(t) || unknownType : t);
        if (constraints !== source2.types) {
          source2 = getIntersectionType(constraints);
          if (source2.flags & TypeFlags.Never) {
            return Ternary.False;
          }
          if (!(source2.flags & TypeFlags.Intersection)) {
            return isRelatedTo(
              source2,
              target2,
              1 /* Source */,
              /*reportErrors*/
              false
            ) || isRelatedTo(
              target2,
              source2,
              1 /* Source */,
              /*reportErrors*/
              false
            );
          }
        }
      }
      return someTypeRelatedToType(
        source2,
        target2,
        /*reportErrors*/
        false,
        1 /* Source */
      );
    }
    function eachTypeRelatedToSomeType(source2, target2) {
      let result2 = Ternary.True;
      const sourceTypes = source2.types;
      for (const sourceType of sourceTypes) {
        const related = typeRelatedToSomeType(
          sourceType,
          target2,
          /*reportErrors*/
          false,
          0 /* None */
        );
        if (!related) {
          return Ternary.False;
        }
        result2 &= related;
      }
      return result2;
    }
    function typeRelatedToSomeType(source2, target2, reportErrors, intersectionState) {
      const targetTypes = target2.types;
      if (target2.flags & TypeFlags.Union) {
        if (containsType(targetTypes, source2)) {
          return Ternary.True;
        }
        if (relation !== comparableRelation && getObjectFlags(target2) & ObjectFlags.PrimitiveUnion && !(source2.flags & TypeFlags.EnumLiteral) && (source2.flags & (TypeFlags.StringLiteral | TypeFlags.BooleanLiteral | TypeFlags.BigIntLiteral) || (relation === subtypeRelation || relation === strictSubtypeRelation) && source2.flags & TypeFlags.NumberLiteral)) {
          const alternateForm = source2 === source2.regularType ? source2.freshType : source2.regularType;
          const primitive = source2.flags & TypeFlags.StringLiteral ? stringType : source2.flags & TypeFlags.NumberLiteral ? numberType : source2.flags & TypeFlags.BigIntLiteral ? bigintType : void 0;
          return primitive && containsType(targetTypes, primitive) || alternateForm && containsType(targetTypes, alternateForm) ? Ternary.True : Ternary.False;
        }
        const match = getMatchingUnionConstituentForType(target2, source2);
        if (match) {
          const related = isRelatedTo(
            source2,
            match,
            2 /* Target */,
            /*reportErrors*/
            false,
            /*headMessage*/
            void 0,
            intersectionState
          );
          if (related) {
            return related;
          }
        }
      }
      for (const type of targetTypes) {
        const related = isRelatedTo(
          source2,
          type,
          2 /* Target */,
          /*reportErrors*/
          false,
          /*headMessage*/
          void 0,
          intersectionState
        );
        if (related) {
          return related;
        }
      }
      if (reportErrors) {
        const bestMatchingType = getBestMatchingType(source2, target2, isRelatedTo);
        if (bestMatchingType) {
          isRelatedTo(
            source2,
            bestMatchingType,
            2 /* Target */,
            /*reportErrors*/
            true,
            /*headMessage*/
            void 0,
            intersectionState
          );
        }
      }
      return Ternary.False;
    }
    function typeRelatedToEachType(source2, target2, reportErrors, intersectionState) {
      let result2 = Ternary.True;
      const targetTypes = target2.types;
      for (const targetType of targetTypes) {
        const related = isRelatedTo(
          source2,
          targetType,
          2 /* Target */,
          reportErrors,
          /*headMessage*/
          void 0,
          intersectionState
        );
        if (!related) {
          return Ternary.False;
        }
        result2 &= related;
      }
      return result2;
    }
    function someTypeRelatedToType(source2, target2, reportErrors, intersectionState) {
      const sourceTypes = source2.types;
      if (source2.flags & TypeFlags.Union && containsType(sourceTypes, target2)) {
        return Ternary.True;
      }
      const len = sourceTypes.length;
      for (let i = 0; i < len; i++) {
        const related = isRelatedTo(
          sourceTypes[i],
          target2,
          1 /* Source */,
          reportErrors && i === len - 1,
          /*headMessage*/
          void 0,
          intersectionState
        );
        if (related) {
          return related;
        }
      }
      return Ternary.False;
    }
    function getUndefinedStrippedTargetIfNeeded(source2, target2) {
      if (source2.flags & TypeFlags.Union && target2.flags & TypeFlags.Union && !(source2.types[0].flags & TypeFlags.Undefined) && target2.types[0].flags & TypeFlags.Undefined) {
        return extractTypesOfKind(target2, ~TypeFlags.Undefined);
      }
      return target2;
    }
    function eachTypeRelatedToType(source2, target2, reportErrors, intersectionState) {
      let result2 = Ternary.True;
      const sourceTypes = source2.types;
      const undefinedStrippedTarget = getUndefinedStrippedTargetIfNeeded(source2, target2);
      for (let i = 0; i < sourceTypes.length; i++) {
        const sourceType = sourceTypes[i];
        if (undefinedStrippedTarget.flags & TypeFlags.Union && sourceTypes.length >= undefinedStrippedTarget.types.length && sourceTypes.length % undefinedStrippedTarget.types.length === 0) {
          const related2 = isRelatedTo(
            sourceType,
            undefinedStrippedTarget.types[i % undefinedStrippedTarget.types.length],
            3 /* Both */,
            /*reportErrors*/
            false,
            /*headMessage*/
            void 0,
            intersectionState
          );
          if (related2) {
            result2 &= related2;
            continue;
          }
        }
        const related = isRelatedTo(
          sourceType,
          target2,
          1 /* Source */,
          reportErrors,
          /*headMessage*/
          void 0,
          intersectionState
        );
        if (!related) {
          return Ternary.False;
        }
        result2 &= related;
      }
      return result2;
    }
    function typeArgumentsRelatedTo(sources = emptyArray, targets = emptyArray, variances = emptyArray, reportErrors, intersectionState) {
      if (sources.length !== targets.length && relation === identityRelation) {
        return Ternary.False;
      }
      const length2 = sources.length <= targets.length ? sources.length : targets.length;
      let result2 = Ternary.True;
      for (let i = 0; i < length2; i++) {
        const varianceFlags = i < variances.length ? variances[i] : VarianceFlags.Covariant;
        const variance = varianceFlags & VarianceFlags.VarianceMask;
        if (variance !== VarianceFlags.Independent) {
          const s = sources[i];
          const t = targets[i];
          let related = Ternary.True;
          if (varianceFlags & VarianceFlags.Unmeasurable) {
            related = relation === identityRelation ? isRelatedTo(
              s,
              t,
              3 /* Both */,
              /*reportErrors*/
              false
            ) : compareTypesIdentical(s, t);
          } else if (variance === VarianceFlags.Covariant) {
            related = isRelatedTo(
              s,
              t,
              3 /* Both */,
              reportErrors,
              /*headMessage*/
              void 0,
              intersectionState
            );
          } else if (variance === VarianceFlags.Contravariant) {
            related = isRelatedTo(
              t,
              s,
              3 /* Both */,
              reportErrors,
              /*headMessage*/
              void 0,
              intersectionState
            );
          } else if (variance === VarianceFlags.Bivariant) {
            related = isRelatedTo(
              t,
              s,
              3 /* Both */,
              /*reportErrors*/
              false
            );
            if (!related) {
              related = isRelatedTo(
                s,
                t,
                3 /* Both */,
                reportErrors,
                /*headMessage*/
                void 0,
                intersectionState
              );
            }
          } else {
            related = isRelatedTo(
              s,
              t,
              3 /* Both */,
              reportErrors,
              /*headMessage*/
              void 0,
              intersectionState
            );
            if (related) {
              related &= isRelatedTo(
                t,
                s,
                3 /* Both */,
                reportErrors,
                /*headMessage*/
                void 0,
                intersectionState
              );
            }
          }
          if (!related) {
            return Ternary.False;
          }
          result2 &= related;
        }
      }
      return result2;
    }
    function recursiveTypeRelatedTo(source2, target2, reportErrors, intersectionState, recursionFlags) {
      if (overflow) {
        return Ternary.False;
      }
      const id = getRelationKey(
        source2,
        target2,
        intersectionState,
        relation,
        /*ignoreConstraints*/
        false
      );
      const entry = relation.get(id);
      if (entry !== void 0) {
        if (reportErrors && entry & RelationComparisonResult.Failed && !(entry & RelationComparisonResult.Overflow)) {
        } else {
          if (outofbandVarianceMarkerHandler) {
            const saved = entry & RelationComparisonResult.ReportsMask;
            if (saved & RelationComparisonResult.ReportsUnmeasurable) {
              instantiateType(source2, reportUnmeasurableMapper);
            }
            if (saved & RelationComparisonResult.ReportsUnreliable) {
              instantiateType(source2, reportUnreliableMapper);
            }
          }
          if (reportErrors && entry & RelationComparisonResult.Overflow) {
            const message = entry & RelationComparisonResult.ComplexityOverflow ? Diagnostics.Excessive_complexity_comparing_types_0_and_1 : Diagnostics.Excessive_stack_depth_comparing_types_0_and_1;
            reportError(message, typeToString(source2), typeToString(target2));
            overrideNextErrorInfo++;
          }
          return entry & RelationComparisonResult.Succeeded ? Ternary.True : Ternary.False;
        }
      }
      if (relationCount <= 0) {
        overflow = true;
        return Ternary.False;
      }
      if (!maybeKeys) {
        maybeKeys = [];
        maybeKeysSet = /* @__PURE__ */ new Set();
        sourceStack = [];
        targetStack = [];
      } else {
        if (maybeKeysSet.has(id)) {
          return Ternary.Maybe;
        }
        const broadestEquivalentId = id.startsWith("*") ? getRelationKey(
          source2,
          target2,
          intersectionState,
          relation,
          /*ignoreConstraints*/
          true
        ) : void 0;
        if (broadestEquivalentId && maybeKeysSet.has(broadestEquivalentId)) {
          return Ternary.Maybe;
        }
        if (sourceDepth === 100 || targetDepth === 100) {
          overflow = true;
          return Ternary.False;
        }
      }
      const maybeStart = maybeCount;
      maybeKeys[maybeCount] = id;
      maybeKeysSet.add(id);
      maybeCount++;
      const saveExpandingFlags = expandingFlags;
      if (recursionFlags & 1 /* Source */) {
        sourceStack[sourceDepth] = source2;
        sourceDepth++;
        if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source2, sourceStack, sourceDepth)) expandingFlags |= 1 /* Source */;
      }
      if (recursionFlags & 2 /* Target */) {
        targetStack[targetDepth] = target2;
        targetDepth++;
        if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target2, targetStack, targetDepth)) expandingFlags |= 2 /* Target */;
      }
      let originalHandler;
      let propagatingVarianceFlags = 0;
      if (outofbandVarianceMarkerHandler) {
        originalHandler = outofbandVarianceMarkerHandler;
        outofbandVarianceMarkerHandler = (onlyUnreliable) => {
          propagatingVarianceFlags |= onlyUnreliable ? RelationComparisonResult.ReportsUnreliable : RelationComparisonResult.ReportsUnmeasurable;
          return originalHandler(onlyUnreliable);
        };
      }
      let result2;
      if (expandingFlags === 3 /* Both */) {
        tracing?.instant(tracing.Phase.CheckTypes, "recursiveTypeRelatedTo_DepthLimit", {
          sourceId: source2.id,
          sourceIdStack: sourceStack.map((t) => t.id),
          targetId: target2.id,
          targetIdStack: targetStack.map((t) => t.id),
          depth: sourceDepth,
          targetDepth
        });
        result2 = Ternary.Maybe;
      } else {
        tracing?.push(tracing.Phase.CheckTypes, "structuredTypeRelatedTo", { sourceId: source2.id, targetId: target2.id });
        result2 = structuredTypeRelatedTo(source2, target2, reportErrors, intersectionState);
        tracing?.pop();
      }
      if (outofbandVarianceMarkerHandler) {
        outofbandVarianceMarkerHandler = originalHandler;
      }
      if (recursionFlags & 1 /* Source */) {
        sourceDepth--;
      }
      if (recursionFlags & 2 /* Target */) {
        targetDepth--;
      }
      expandingFlags = saveExpandingFlags;
      if (result2) {
        if (result2 === Ternary.True || sourceDepth === 0 && targetDepth === 0) {
          if (result2 === Ternary.True || result2 === Ternary.Maybe) {
            resetMaybeStack(
              /*markAllAsSucceeded*/
              true
            );
          } else {
            resetMaybeStack(
              /*markAllAsSucceeded*/
              false
            );
          }
        }
      } else {
        relation.set(id, RelationComparisonResult.Failed | propagatingVarianceFlags);
        relationCount--;
        resetMaybeStack(
          /*markAllAsSucceeded*/
          false
        );
      }
      return result2;
      function resetMaybeStack(markAllAsSucceeded) {
        for (let i = maybeStart; i < maybeCount; i++) {
          maybeKeysSet.delete(maybeKeys[i]);
          if (markAllAsSucceeded) {
            relation.set(maybeKeys[i], RelationComparisonResult.Succeeded | propagatingVarianceFlags);
            relationCount--;
          }
        }
        maybeCount = maybeStart;
      }
    }
    function structuredTypeRelatedTo(source2, target2, reportErrors, intersectionState) {
      const saveErrorInfo = captureErrorCalculationState();
      let result2 = structuredTypeRelatedToWorker(source2, target2, reportErrors, intersectionState, saveErrorInfo);
      if (relation !== identityRelation) {
        if (!result2 && (source2.flags & TypeFlags.Intersection || source2.flags & TypeFlags.TypeParameter && target2.flags & TypeFlags.Union)) {
          const constraint = getEffectiveConstraintOfIntersection(source2.flags & TypeFlags.Intersection ? source2.types : [source2], !!(target2.flags & TypeFlags.Union));
          if (constraint && everyType(constraint, (c) => c !== source2)) {
            result2 = isRelatedTo(
              constraint,
              target2,
              1 /* Source */,
              /*reportErrors*/
              false,
              /*headMessage*/
              void 0,
              intersectionState
            );
          }
        }
        if (result2 && !(intersectionState & 2 /* Target */) && target2.flags & TypeFlags.Intersection && !isGenericObjectType(target2) && source2.flags & (TypeFlags.Object | TypeFlags.Intersection)) {
          result2 &= propertiesRelatedTo(
            source2,
            target2,
            reportErrors,
            /*excludedProperties*/
            void 0,
            /*optionalsOnly*/
            false,
            0 /* None */
          );
          if (result2 && isObjectLiteralType(source2) && getObjectFlags(source2) & ObjectFlags.FreshLiteral) {
            result2 &= indexSignaturesRelatedTo(
              source2,
              target2,
              /*sourceIsPrimitive*/
              false,
              reportErrors,
              0 /* None */
            );
          }
        } else if (result2 && isNonGenericObjectType(target2) && !isArrayOrTupleType(target2) && source2.flags & TypeFlags.Intersection && getApparentType(source2).flags & TypeFlags.StructuredType && !some(source2.types, (t) => t === target2 || !!(getObjectFlags(t) & ObjectFlags.NonInferrableType))) {
          result2 &= propertiesRelatedTo(
            source2,
            target2,
            reportErrors,
            /*excludedProperties*/
            void 0,
            /*optionalsOnly*/
            true,
            intersectionState
          );
        }
      }
      if (result2) {
        resetErrorInfo(saveErrorInfo);
      }
      return result2;
    }
    function getApparentMappedTypeKeys(nameType, targetType) {
      const modifiersType = getApparentType(getModifiersTypeFromMappedType(targetType));
      const mappedKeys = [];
      forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(
        modifiersType,
        TypeFlags.StringOrNumberLiteralOrUnique,
        /*stringsOnly*/
        false,
        (t) => void mappedKeys.push(instantiateType(nameType, appendTypeMapping(targetType.mapper, getTypeParameterFromMappedType(targetType), t)))
      );
      return getUnionType(mappedKeys);
    }
    function structuredTypeRelatedToWorker(source2, target2, reportErrors, intersectionState, saveErrorInfo) {
      let result2;
      let originalErrorInfo;
      let varianceCheckFailed = false;
      let sourceFlags = source2.flags;
      const targetFlags = target2.flags;
      if (relation === identityRelation) {
        if (sourceFlags & TypeFlags.UnionOrIntersection) {
          let result3 = eachTypeRelatedToSomeType(source2, target2);
          if (result3) {
            result3 &= eachTypeRelatedToSomeType(target2, source2);
          }
          return result3;
        }
        if (sourceFlags & TypeFlags.Index) {
          return isRelatedTo(
            source2.type,
            target2.type,
            3 /* Both */,
            /*reportErrors*/
            false
          );
        }
        if (sourceFlags & TypeFlags.IndexedAccess) {
          if (result2 = isRelatedTo(
            source2.objectType,
            target2.objectType,
            3 /* Both */,
            /*reportErrors*/
            false
          )) {
            if (result2 &= isRelatedTo(
              source2.indexType,
              target2.indexType,
              3 /* Both */,
              /*reportErrors*/
              false
            )) {
              return result2;
            }
          }
        }
        if (sourceFlags & TypeFlags.Conditional) {
          if (source2.root.isDistributive === target2.root.isDistributive) {
            if (result2 = isRelatedTo(
              source2.checkType,
              target2.checkType,
              3 /* Both */,
              /*reportErrors*/
              false
            )) {
              if (result2 &= isRelatedTo(
                source2.extendsType,
                target2.extendsType,
                3 /* Both */,
                /*reportErrors*/
                false
              )) {
                if (result2 &= isRelatedTo(
                  getTrueTypeFromConditionalType(source2),
                  getTrueTypeFromConditionalType(target2),
                  3 /* Both */,
                  /*reportErrors*/
                  false
                )) {
                  if (result2 &= isRelatedTo(
                    getFalseTypeFromConditionalType(source2),
                    getFalseTypeFromConditionalType(target2),
                    3 /* Both */,
                    /*reportErrors*/
                    false
                  )) {
                    return result2;
                  }
                }
              }
            }
          }
        }
        if (sourceFlags & TypeFlags.Substitution) {
          if (result2 = isRelatedTo(
            source2.baseType,
            target2.baseType,
            3 /* Both */,
            /*reportErrors*/
            false
          )) {
            if (result2 &= isRelatedTo(
              source2.constraint,
              target2.constraint,
              3 /* Both */,
              /*reportErrors*/
              false
            )) {
              return result2;
            }
          }
        }
        if (!(sourceFlags & TypeFlags.Object)) {
          return Ternary.False;
        }
      } else if (sourceFlags & TypeFlags.UnionOrIntersection || targetFlags & TypeFlags.UnionOrIntersection) {
        if (result2 = unionOrIntersectionRelatedTo(source2, target2, reportErrors, intersectionState)) {
          return result2;
        }
        if (!(sourceFlags & TypeFlags.Instantiable || sourceFlags & TypeFlags.Object && targetFlags & TypeFlags.Union || sourceFlags & TypeFlags.Intersection && targetFlags & (TypeFlags.Object | TypeFlags.Union | TypeFlags.Instantiable))) {
          return Ternary.False;
        }
      }
      if (sourceFlags & (TypeFlags.Object | TypeFlags.Conditional) && source2.aliasSymbol && source2.aliasTypeArguments && source2.aliasSymbol === target2.aliasSymbol && !(isMarkerType(source2) || isMarkerType(target2))) {
        const variances = getAliasVariances(source2.aliasSymbol);
        if (variances === emptyArray) {
          return Ternary.Unknown;
        }
        const params = getSymbolLinks(source2.aliasSymbol).typeParameters;
        const minParams = getMinTypeArgumentCount(params);
        const sourceTypes = fillMissingTypeArguments(source2.aliasTypeArguments, params, minParams, isInJSFile(source2.aliasSymbol.valueDeclaration));
        const targetTypes = fillMissingTypeArguments(target2.aliasTypeArguments, params, minParams, isInJSFile(source2.aliasSymbol.valueDeclaration));
        const varianceResult = relateVariances(sourceTypes, targetTypes, variances, intersectionState);
        if (varianceResult !== void 0) {
          return varianceResult;
        }
      }
      if (isSingleElementGenericTupleType(source2) && !source2.target.readonly && (result2 = isRelatedTo(getTypeArguments(source2)[0], target2, 1 /* Source */)) || isSingleElementGenericTupleType(target2) && (target2.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source2) || source2)) && (result2 = isRelatedTo(source2, getTypeArguments(target2)[0], 2 /* Target */))) {
        return result2;
      }
      if (targetFlags & TypeFlags.TypeParameter) {
        if (getObjectFlags(source2) & ObjectFlags.Mapped && !source2.declaration.nameType && isRelatedTo(getIndexType(target2), getConstraintTypeFromMappedType(source2), 3 /* Both */)) {
          if (!(getMappedTypeModifiers(source2) & 4 /* IncludeOptional */)) {
            const templateType = getTemplateTypeFromMappedType(source2);
            const indexedAccessType = getIndexedAccessType(target2, getTypeParameterFromMappedType(source2));
            if (result2 = isRelatedTo(templateType, indexedAccessType, 3 /* Both */, reportErrors)) {
              return result2;
            }
          }
        }
        if (relation === comparableRelation && sourceFlags & TypeFlags.TypeParameter) {
          let constraint = getConstraintOfTypeParameter(source2);
          if (constraint) {
            while (constraint && someType(constraint, (c) => !!(c.flags & TypeFlags.TypeParameter))) {
              if (result2 = isRelatedTo(
                constraint,
                target2,
                1 /* Source */,
                /*reportErrors*/
                false
              )) {
                return result2;
              }
              constraint = getConstraintOfTypeParameter(constraint);
            }
          }
          return Ternary.False;
        }
      } else if (targetFlags & TypeFlags.Index) {
        const targetType = target2.type;
        if (sourceFlags & TypeFlags.Index) {
          if (result2 = isRelatedTo(
            targetType,
            source2.type,
            3 /* Both */,
            /*reportErrors*/
            false
          )) {
            return result2;
          }
        }
        if (isTupleType(targetType)) {
          if (result2 = isRelatedTo(source2, getKnownKeysOfTupleType(targetType), 2 /* Target */, reportErrors)) {
            return result2;
          }
        } else {
          const constraint = getSimplifiedTypeOrConstraint(targetType);
          if (constraint) {
            if (isRelatedTo(source2, getIndexType(constraint, target2.indexFlags | IndexFlags.NoReducibleCheck), 2 /* Target */, reportErrors) === Ternary.True) {
              return Ternary.True;
            }
          } else if (isGenericMappedType(targetType)) {
            const nameType = getNameTypeFromMappedType(targetType);
            const constraintType = getConstraintTypeFromMappedType(targetType);
            let targetKeys;
            if (nameType && isMappedTypeWithKeyofConstraintDeclaration(targetType)) {
              const mappedKeys = getApparentMappedTypeKeys(nameType, targetType);
              targetKeys = getUnionType([mappedKeys, nameType]);
            } else {
              targetKeys = nameType || constraintType;
            }
            if (isRelatedTo(source2, targetKeys, 2 /* Target */, reportErrors) === Ternary.True) {
              return Ternary.True;
            }
          }
        }
      } else if (targetFlags & TypeFlags.IndexedAccess) {
        if (sourceFlags & TypeFlags.IndexedAccess) {
          if (result2 = isRelatedTo(source2.objectType, target2.objectType, 3 /* Both */, reportErrors)) {
            result2 &= isRelatedTo(source2.indexType, target2.indexType, 3 /* Both */, reportErrors);
          }
          if (result2) {
            return result2;
          }
          if (reportErrors) {
            originalErrorInfo = errorInfo;
          }
        }
        if (relation === assignableRelation || relation === comparableRelation) {
          const objectType = target2.objectType;
          const indexType = target2.indexType;
          const baseObjectType = getBaseConstraintOfType(objectType) || objectType;
          const baseIndexType = getBaseConstraintOfType(indexType) || indexType;
          if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
            const accessFlags = AccessFlags.Writing | (baseObjectType !== objectType ? AccessFlags.NoIndexSignatures : 0);
            const constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, accessFlags);
            if (constraint) {
              if (reportErrors && originalErrorInfo) {
                resetErrorInfo(saveErrorInfo);
              }
              if (result2 = isRelatedTo(
                source2,
                constraint,
                2 /* Target */,
                reportErrors,
                /*headMessage*/
                void 0,
                intersectionState
              )) {
                return result2;
              }
              if (reportErrors && originalErrorInfo && errorInfo) {
                errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo;
              }
            }
          }
        }
        if (reportErrors) {
          originalErrorInfo = void 0;
        }
      } else if (isGenericMappedType(target2) && relation !== identityRelation) {
        const keysRemapped = !!target2.declaration.nameType;
        const templateType = getTemplateTypeFromMappedType(target2);
        const modifiers = getMappedTypeModifiers(target2);
        if (!(modifiers & 8 /* ExcludeOptional */)) {
          if (!keysRemapped && templateType.flags & TypeFlags.IndexedAccess && templateType.objectType === source2 && templateType.indexType === getTypeParameterFromMappedType(target2)) {
            return Ternary.True;
          }
          if (!isGenericMappedType(source2)) {
            const targetKeys = keysRemapped ? getNameTypeFromMappedType(target2) : getConstraintTypeFromMappedType(target2);
            const sourceKeys = getIndexType(source2, IndexFlags.NoIndexSignatures);
            const includeOptional = modifiers & 4 /* IncludeOptional */;
            const filteredByApplicability = includeOptional ? intersectTypes(targetKeys, sourceKeys) : void 0;
            if (includeOptional ? !(filteredByApplicability.flags & TypeFlags.Never) : isRelatedTo(targetKeys, sourceKeys, 3 /* Both */)) {
              const templateType2 = getTemplateTypeFromMappedType(target2);
              const typeParameter = getTypeParameterFromMappedType(target2);
              const nonNullComponent = extractTypesOfKind(templateType2, ~TypeFlags.Nullable);
              if (!keysRemapped && nonNullComponent.flags & TypeFlags.IndexedAccess && nonNullComponent.indexType === typeParameter) {
                if (result2 = isRelatedTo(source2, nonNullComponent.objectType, 2 /* Target */, reportErrors)) {
                  return result2;
                }
              } else {
                const indexingType = keysRemapped ? filteredByApplicability || targetKeys : filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
                const indexedAccessType = getIndexedAccessType(source2, indexingType);
                if (result2 = isRelatedTo(indexedAccessType, templateType2, 3 /* Both */, reportErrors)) {
                  return result2;
                }
              }
            }
            originalErrorInfo = errorInfo;
            resetErrorInfo(saveErrorInfo);
          }
        }
      } else if (targetFlags & TypeFlags.Conditional) {
        if (isDeeplyNestedType(target2, targetStack, targetDepth, 10)) {
          return Ternary.Maybe;
        }
        const c = target2;
        if (!c.root.inferTypeParameters && !isDistributionDependent(c.root) && !(source2.flags & TypeFlags.Conditional && source2.root === c.root)) {
          const skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType));
          const skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType));
          if (result2 = skipTrue ? Ternary.True : isRelatedTo(
            source2,
            getTrueTypeFromConditionalType(c),
            2 /* Target */,
            /*reportErrors*/
            false,
            /*headMessage*/
            void 0,
            intersectionState
          )) {
            result2 &= skipFalse ? Ternary.True : isRelatedTo(
              source2,
              getFalseTypeFromConditionalType(c),
              2 /* Target */,
              /*reportErrors*/
              false,
              /*headMessage*/
              void 0,
              intersectionState
            );
            if (result2) {
              return result2;
            }
          }
        }
      } else if (targetFlags & TypeFlags.TemplateLiteral) {
        if (sourceFlags & TypeFlags.TemplateLiteral) {
          if (relation === comparableRelation) {
            return templateLiteralTypesDefinitelyUnrelated(source2, target2) ? Ternary.False : Ternary.True;
          }
          instantiateType(source2, reportUnreliableMapper);
        }
        if (isTypeMatchedByTemplateLiteralType(source2, target2)) {
          return Ternary.True;
        }
      } else if (target2.flags & TypeFlags.StringMapping) {
        if (!(source2.flags & TypeFlags.StringMapping)) {
          if (isMemberOfStringMapping(source2, target2)) {
            return Ternary.True;
          }
        }
      }
      if (sourceFlags & TypeFlags.TypeVariable) {
        if (!(sourceFlags & TypeFlags.IndexedAccess && targetFlags & TypeFlags.IndexedAccess)) {
          const constraint = getConstraintOfType(source2) || unknownType;
          if (result2 = isRelatedTo(
            constraint,
            target2,
            1 /* Source */,
            /*reportErrors*/
            false,
            /*headMessage*/
            void 0,
            intersectionState
          )) {
            return result2;
          } else if (result2 = isRelatedTo(
            getTypeWithThisArgument(constraint, source2),
            target2,
            1 /* Source */,
            reportErrors && constraint !== unknownType && !(targetFlags & sourceFlags & TypeFlags.TypeParameter),
            /*headMessage*/
            void 0,
            intersectionState
          )) {
            return result2;
          }
          if (isMappedTypeGenericIndexedAccess(source2)) {
            const indexConstraint = getConstraintOfType(source2.indexType);
            if (indexConstraint) {
              if (result2 = isRelatedTo(getIndexedAccessType(source2.objectType, indexConstraint), target2, 1 /* Source */, reportErrors)) {
                return result2;
              }
            }
          }
        }
      } else if (sourceFlags & TypeFlags.Index) {
        const isDeferredMappedIndex = shouldDeferIndexType(source2.type, source2.indexFlags) && getObjectFlags(source2.type) & ObjectFlags.Mapped;
        if (result2 = isRelatedTo(stringNumberSymbolType, target2, 1 /* Source */, reportErrors && !isDeferredMappedIndex)) {
          return result2;
        }
        if (isDeferredMappedIndex) {
          const mappedType = source2.type;
          const nameType = getNameTypeFromMappedType(mappedType);
          const sourceMappedKeys = nameType && isMappedTypeWithKeyofConstraintDeclaration(mappedType) ? getApparentMappedTypeKeys(nameType, mappedType) : nameType || getConstraintTypeFromMappedType(mappedType);
          if (result2 = isRelatedTo(sourceMappedKeys, target2, 1 /* Source */, reportErrors)) {
            return result2;
          }
        }
      } else if (sourceFlags & TypeFlags.TemplateLiteral && !(targetFlags & TypeFlags.Object)) {
        if (!(targetFlags & TypeFlags.TemplateLiteral)) {
          const constraint = getBaseConstraintOfType(source2);
          if (constraint && constraint !== source2 && (result2 = isRelatedTo(constraint, target2, 1 /* Source */, reportErrors))) {
            return result2;
          }
        }
      } else if (sourceFlags & TypeFlags.StringMapping) {
        if (targetFlags & TypeFlags.StringMapping) {
          if (source2.symbol !== target2.symbol) {
            return Ternary.False;
          }
          if (result2 = isRelatedTo(source2.type, target2.type, 3 /* Both */, reportErrors)) {
            return result2;
          }
        } else {
          const constraint = getBaseConstraintOfType(source2);
          if (constraint && (result2 = isRelatedTo(constraint, target2, 1 /* Source */, reportErrors))) {
            return result2;
          }
        }
      } else if (sourceFlags & TypeFlags.Conditional) {
        if (isDeeplyNestedType(source2, sourceStack, sourceDepth, 10)) {
          return Ternary.Maybe;
        }
        if (targetFlags & TypeFlags.Conditional) {
          const sourceParams = source2.root.inferTypeParameters;
          let sourceExtends = source2.extendsType;
          let mapper;
          if (sourceParams) {
            const ctx = createInferenceContext(
              sourceParams,
              /*signature*/
              void 0,
              InferenceFlags.None,
              isRelatedToWorker
            );
            inferTypes(ctx.inferences, target2.extendsType, sourceExtends, InferencePriority.NoConstraints | InferencePriority.AlwaysStrict);
            sourceExtends = instantiateType(sourceExtends, ctx.mapper);
            mapper = ctx.mapper;
          }
          if (isTypeIdenticalTo(sourceExtends, target2.extendsType) && (isRelatedTo(source2.checkType, target2.checkType, 3 /* Both */) || isRelatedTo(target2.checkType, source2.checkType, 3 /* Both */))) {
            if (result2 = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source2), mapper), getTrueTypeFromConditionalType(target2), 3 /* Both */, reportErrors)) {
              result2 &= isRelatedTo(getFalseTypeFromConditionalType(source2), getFalseTypeFromConditionalType(target2), 3 /* Both */, reportErrors);
            }
            if (result2) {
              return result2;
            }
          }
        }
        const defaultConstraint = getDefaultConstraintOfConditionalType(source2);
        if (defaultConstraint) {
          if (result2 = isRelatedTo(defaultConstraint, target2, 1 /* Source */, reportErrors)) {
            return result2;
          }
        }
        const distributiveConstraint = !(targetFlags & TypeFlags.Conditional) && hasNonCircularBaseConstraint(source2) ? getConstraintOfDistributiveConditionalType(source2) : void 0;
        if (distributiveConstraint) {
          resetErrorInfo(saveErrorInfo);
          if (result2 = isRelatedTo(distributiveConstraint, target2, 1 /* Source */, reportErrors)) {
            return result2;
          }
        }
      } else {
        if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target2) && isEmptyObjectType(source2)) {
          return Ternary.True;
        }
        if (isGenericMappedType(target2)) {
          if (isGenericMappedType(source2)) {
            if (result2 = mappedTypeRelatedTo(source2, target2, reportErrors)) {
              return result2;
            }
          }
          return Ternary.False;
        }
        const sourceIsPrimitive = !!(sourceFlags & TypeFlags.Primitive);
        if (relation !== identityRelation) {
          source2 = getApparentType(source2);
          sourceFlags = source2.flags;
        } else if (isGenericMappedType(source2)) {
          return Ternary.False;
        }
        if (getObjectFlags(source2) & ObjectFlags.Reference && getObjectFlags(target2) & ObjectFlags.Reference && source2.target === target2.target && !isTupleType(source2) && !(isMarkerType(source2) || isMarkerType(target2))) {
          if (isEmptyArrayLiteralType(source2)) {
            return Ternary.True;
          }
          const variances = getVariances(source2.target);
          if (variances === emptyArray) {
            return Ternary.Unknown;
          }
          const varianceResult = relateVariances(getTypeArguments(source2), getTypeArguments(target2), variances, intersectionState);
          if (varianceResult !== void 0) {
            return varianceResult;
          }
        } else if (isReadonlyArrayType(target2) ? everyType(source2, isArrayOrTupleType) : isArrayType(target2) && everyType(source2, (t) => isTupleType(t) && !t.target.readonly)) {
          if (relation !== identityRelation) {
            return isRelatedTo(getIndexTypeOfType(source2, numberType) || anyType, getIndexTypeOfType(target2, numberType) || anyType, 3 /* Both */, reportErrors);
          } else {
            return Ternary.False;
          }
        } else if (isGenericTupleType(source2) && isTupleType(target2) && !isGenericTupleType(target2)) {
          const constraint = getBaseConstraintOrType(source2);
          if (constraint !== source2) {
            return isRelatedTo(constraint, target2, 1 /* Source */, reportErrors);
          }
        } else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target2) && getObjectFlags(target2) & ObjectFlags.FreshLiteral && !isEmptyObjectType(source2)) {
          return Ternary.False;
        }
        if (sourceFlags & (TypeFlags.Object | TypeFlags.Intersection) && targetFlags & TypeFlags.Object) {
          const reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
          result2 = propertiesRelatedTo(
            source2,
            target2,
            reportStructuralErrors,
            /*excludedProperties*/
            void 0,
            /*optionalsOnly*/
            false,
            intersectionState
          );
          if (result2) {
            result2 &= signaturesRelatedTo(source2, target2, SignatureKind.Call, reportStructuralErrors, intersectionState);
            if (result2) {
              result2 &= signaturesRelatedTo(source2, target2, SignatureKind.Construct, reportStructuralErrors, intersectionState);
              if (result2) {
                result2 &= indexSignaturesRelatedTo(source2, target2, sourceIsPrimitive, reportStructuralErrors, intersectionState);
              }
            }
          }
          if (varianceCheckFailed && result2) {
            errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo;
          } else if (result2) {
            return result2;
          }
        }
        if (sourceFlags & (TypeFlags.Object | TypeFlags.Intersection) && targetFlags & TypeFlags.Union) {
          const objectOnlyTarget = extractTypesOfKind(target2, TypeFlags.Object | TypeFlags.Intersection | TypeFlags.Substitution);
          if (objectOnlyTarget.flags & TypeFlags.Union) {
            const result3 = typeRelatedToDiscriminatedType(source2, objectOnlyTarget);
            if (result3) {
              return result3;
            }
          }
        }
      }
      return Ternary.False;
      function countMessageChainBreadth(info) {
        if (!info) return 0;
        return reduceLeft(info, (value, chain) => value + 1 + countMessageChainBreadth(chain.next), 0);
      }
      function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState2) {
        if (result2 = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState2)) {
          return result2;
        }
        if (some(variances, (v) => !!(v & VarianceFlags.AllowsStructuralFallback))) {
          originalErrorInfo = void 0;
          resetErrorInfo(saveErrorInfo);
          return void 0;
        }
        const allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
        varianceCheckFailed = !allowStructuralFallback;
        if (variances !== emptyArray && !allowStructuralFallback) {
          if (varianceCheckFailed && !(reportErrors && some(variances, (v) => (v & VarianceFlags.VarianceMask) === VarianceFlags.Invariant))) {
            return Ternary.False;
          }
          originalErrorInfo = errorInfo;
          resetErrorInfo(saveErrorInfo);
        }
      }
    }
    function mappedTypeRelatedTo(source2, target2, reportErrors) {
      const modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source2) === getMappedTypeModifiers(target2) : getCombinedMappedTypeOptionality(source2) <= getCombinedMappedTypeOptionality(target2));
      if (modifiersRelated) {
        let result2;
        const targetConstraint = getConstraintTypeFromMappedType(target2);
        const sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source2), getCombinedMappedTypeOptionality(source2) < 0 ? reportUnmeasurableMapper : reportUnreliableMapper);
        if (result2 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) {
          const mapper = createTypeMapper([getTypeParameterFromMappedType(source2)], [getTypeParameterFromMappedType(target2)]);
          if (instantiateType(getNameTypeFromMappedType(source2), mapper) === instantiateType(getNameTypeFromMappedType(target2), mapper)) {
            return result2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source2), mapper), getTemplateTypeFromMappedType(target2), 3 /* Both */, reportErrors);
          }
        }
      }
      return Ternary.False;
    }
    function typeRelatedToDiscriminatedType(source2, target2) {
      const sourceProperties = getPropertiesOfType(source2);
      const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target2);
      if (!sourcePropertiesFiltered) return Ternary.False;
      let numCombinations = 1;
      for (const sourceProperty of sourcePropertiesFiltered) {
        numCombinations *= countTypes(getNonMissingTypeOfSymbol(sourceProperty));
        if (numCombinations > 25) {
          tracing?.instant(tracing.Phase.CheckTypes, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source2.id, targetId: target2.id, numCombinations });
          return Ternary.False;
        }
      }
      const sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
      const excludedProperties = /* @__PURE__ */ new Set();
      for (let i = 0; i < sourcePropertiesFiltered.length; i++) {
        const sourceProperty = sourcePropertiesFiltered[i];
        const sourcePropertyType = getNonMissingTypeOfSymbol(sourceProperty);
        sourceDiscriminantTypes[i] = sourcePropertyType.flags & TypeFlags.Union ? sourcePropertyType.types : [sourcePropertyType];
        excludedProperties.add(sourceProperty.escapedName);
      }
      const discriminantCombinations = cartesianProduct(sourceDiscriminantTypes);
      const matchingTypes = [];
      for (const combination of discriminantCombinations) {
        let hasMatch = false;
        outer:
          for (const type of target2.types) {
            for (let i = 0; i < sourcePropertiesFiltered.length; i++) {
              const sourceProperty = sourcePropertiesFiltered[i];
              const targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
              if (!targetProperty) continue outer;
              if (sourceProperty === targetProperty) continue;
              const related = propertyRelatedTo(
                source2,
                target2,
                sourceProperty,
                targetProperty,
                (_) => combination[i],
                /*reportErrors*/
                false,
                0 /* None */,
                /*skipOptional*/
                strictNullChecks || relation === comparableRelation
              );
              if (!related) {
                continue outer;
              }
            }
            pushIfUnique(matchingTypes, type, equateValues);
            hasMatch = true;
          }
        if (!hasMatch) {
          return Ternary.False;
        }
      }
      let result2 = Ternary.True;
      for (const type of matchingTypes) {
        result2 &= propertiesRelatedTo(
          source2,
          type,
          /*reportErrors*/
          false,
          excludedProperties,
          /*optionalsOnly*/
          false,
          0 /* None */
        );
        if (result2) {
          result2 &= signaturesRelatedTo(
            source2,
            type,
            SignatureKind.Call,
            /*reportErrors*/
            false,
            0 /* None */
          );
          if (result2) {
            result2 &= signaturesRelatedTo(
              source2,
              type,
              SignatureKind.Construct,
              /*reportErrors*/
              false,
              0 /* None */
            );
            if (result2 && !(isTupleType(source2) && isTupleType(type))) {
              result2 &= indexSignaturesRelatedTo(
                source2,
                type,
                /*sourceIsPrimitive*/
                false,
                /*reportErrors*/
                false,
                0 /* None */
              );
            }
          }
        }
        if (!result2) {
          return result2;
        }
      }
      return result2;
    }
    function excludeProperties(properties, excludedProperties) {
      if (!excludedProperties || properties.length === 0) return properties;
      let result2;
      for (let i = 0; i < properties.length; i++) {
        if (!excludedProperties.has(properties[i].escapedName)) {
          if (result2) {
            result2.push(properties[i]);
          }
        } else if (!result2) {
          result2 = properties.slice(0, i);
        }
      }
      return result2 || properties;
    }
    function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
      const targetIsOptional = strictNullChecks && !!(getCheckFlags(targetProp) & CheckFlags.Partial);
      const effectiveTarget = addOptionality(
        getNonMissingTypeOfSymbol(targetProp),
        /*isProperty*/
        false,
        targetIsOptional
      );
      const effectiveSource = getTypeOfSourceProperty(sourceProp);
      return isRelatedTo(
        effectiveSource,
        effectiveTarget,
        3 /* Both */,
        reportErrors,
        /*headMessage*/
        void 0,
        intersectionState
      );
    }
    function propertyRelatedTo(source2, target2, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
      const sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp);
      const targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp);
      if (sourcePropFlags & ModifierFlags.Private || targetPropFlags & ModifierFlags.Private) {
        if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
          if (reportErrors) {
            if (sourcePropFlags & ModifierFlags.Private && targetPropFlags & ModifierFlags.Private) {
              reportError(Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
            } else {
              reportError(Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & ModifierFlags.Private ? source2 : target2), typeToString(sourcePropFlags & ModifierFlags.Private ? target2 : source2));
            }
          }
          return Ternary.False;
        }
      } else if (targetPropFlags & ModifierFlags.Protected) {
        if (!isValidOverrideOf(sourceProp, targetProp)) {
          if (reportErrors) {
            reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source2), typeToString(getDeclaringClass(targetProp) || target2));
          }
          return Ternary.False;
        }
      } else if (sourcePropFlags & ModifierFlags.Protected) {
        if (reportErrors) {
          reportError(Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source2), typeToString(target2));
        }
        return Ternary.False;
      }
      if (relation === strictSubtypeRelation && isReadonlySymbol(sourceProp) && !isReadonlySymbol(targetProp)) {
        return Ternary.False;
      }
      const related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
      if (!related) {
        if (reportErrors) {
          reportIncompatibleError(Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
        }
        return Ternary.False;
      }
      if (!skipOptional && sourceProp.flags & SymbolFlags.Optional && targetProp.flags & SymbolFlags.ClassMember && !(targetProp.flags & SymbolFlags.Optional)) {
        if (reportErrors) {
          reportError(Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source2), typeToString(target2));
        }
        return Ternary.False;
      }
      return related;
    }
    function reportUnmatchedProperty(source2, target2, unmatchedProperty, requireOptionalProperties) {
      let shouldSkipElaboration = false;
      if (unmatchedProperty.valueDeclaration && isNamedDeclaration(unmatchedProperty.valueDeclaration) && isPrivateIdentifier(unmatchedProperty.valueDeclaration.name) && source2.symbol && source2.symbol.flags & SymbolFlags.Class) {
        const privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
        const symbolTableKey = getSymbolNameForPrivateIdentifier(source2.symbol, privateIdentifierDescription);
        if (symbolTableKey && getPropertyOfType(source2, symbolTableKey)) {
          const sourceName = factory.getDeclarationName(source2.symbol.valueDeclaration);
          const targetName = factory.getDeclarationName(target2.symbol.valueDeclaration);
          reportError(
            Diagnostics.Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2,
            diagnosticName(privateIdentifierDescription),
            diagnosticName(sourceName.escapedText === "" ? anon : sourceName),
            diagnosticName(targetName.escapedText === "" ? anon : targetName)
          );
          return;
        }
      }
      const props = arrayFrom(getUnmatchedProperties(
        source2,
        target2,
        requireOptionalProperties,
        /*matchDiscriminantProperties*/
        false
      ));
      if (!headMessage || headMessage.code !== Diagnostics.Class_0_incorrectly_implements_interface_1.code && headMessage.code !== Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code) {
        shouldSkipElaboration = true;
      }
      if (props.length === 1) {
        const propName = symbolToString(
          unmatchedProperty,
          /*enclosingDeclaration*/
          void 0,
          SymbolFlags.None,
          SymbolFormatFlags.AllowAnyNodeKind | SymbolFormatFlags.WriteComputedProps
        );
        reportError(Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, ...getTypeNamesForErrorDisplay(source2, target2));
        if (length(unmatchedProperty.declarations)) {
          associateRelatedInfo(createDiagnosticForNode(unmatchedProperty.declarations[0], Diagnostics._0_is_declared_here, propName));
        }
        if (shouldSkipElaboration && errorInfo) {
          overrideNextErrorInfo++;
        }
      } else if (tryElaborateArrayLikeErrors(
        source2,
        target2,
        /*reportErrors*/
        false
      )) {
        if (props.length > 5) {
          reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source2), typeToString(target2), map(props.slice(0, 4), (p) => symbolToString(p)).join(", "), props.length - 4);
        } else {
          reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source2), typeToString(target2), map(props, (p) => symbolToString(p)).join(", "));
        }
        if (shouldSkipElaboration && errorInfo) {
          overrideNextErrorInfo++;
        }
      }
    }
    function propertiesRelatedTo(source2, target2, reportErrors, excludedProperties, optionalsOnly, intersectionState) {
      if (relation === identityRelation) {
        return propertiesIdenticalTo(source2, target2, excludedProperties);
      }
      let result2 = Ternary.True;
      if (isTupleType(target2)) {
        if (isArrayOrTupleType(source2)) {
          if (!target2.target.readonly && (isReadonlyArrayType(source2) || isTupleType(source2) && source2.target.readonly)) {
            return Ternary.False;
          }
          const sourceArity = getTypeReferenceArity(source2);
          const targetArity = getTypeReferenceArity(target2);
          const sourceRestFlag = isTupleType(source2) ? source2.target.combinedFlags & ElementFlags.Rest : ElementFlags.Rest;
          const targetHasRestElement = !!(target2.target.combinedFlags & ElementFlags.Variable);
          const sourceMinLength = isTupleType(source2) ? source2.target.minLength : 0;
          const targetMinLength = target2.target.minLength;
          if (!sourceRestFlag && sourceArity < targetMinLength) {
            if (reportErrors) {
              reportError(Diagnostics.Source_has_0_element_s_but_target_requires_1, sourceArity, targetMinLength);
            }
            return Ternary.False;
          }
          if (!targetHasRestElement && targetArity < sourceMinLength) {
            if (reportErrors) {
              reportError(Diagnostics.Source_has_0_element_s_but_target_allows_only_1, sourceMinLength, targetArity);
            }
            return Ternary.False;
          }
          if (!targetHasRestElement && (sourceRestFlag || targetArity < sourceArity)) {
            if (reportErrors) {
              if (sourceMinLength < targetMinLength) {
                reportError(Diagnostics.Target_requires_0_element_s_but_source_may_have_fewer, targetMinLength);
              } else {
                reportError(Diagnostics.Target_allows_only_0_element_s_but_source_may_have_more, targetArity);
              }
            }
            return Ternary.False;
          }
          const sourceTypeArguments = getTypeArguments(source2);
          const targetTypeArguments = getTypeArguments(target2);
          const targetStartCount = getStartElementCount(target2.target, ElementFlags.NonRest);
          const targetEndCount = getEndElementCount(target2.target, ElementFlags.NonRest);
          let canExcludeDiscriminants = !!excludedProperties;
          for (let sourcePosition = 0; sourcePosition < sourceArity; sourcePosition++) {
            const sourceFlags = isTupleType(source2) ? source2.target.elementFlags[sourcePosition] : ElementFlags.Rest;
            const sourcePositionFromEnd = sourceArity - 1 - sourcePosition;
            const targetPosition = targetHasRestElement && sourcePosition >= targetStartCount ? targetArity - 1 - Math.min(sourcePositionFromEnd, targetEndCount) : sourcePosition;
            const targetFlags = target2.target.elementFlags[targetPosition];
            if (targetFlags & ElementFlags.Variadic && !(sourceFlags & ElementFlags.Variadic)) {
              if (reportErrors) {
                reportError(Diagnostics.Source_provides_no_match_for_variadic_element_at_position_0_in_target, targetPosition);
              }
              return Ternary.False;
            }
            if (sourceFlags & ElementFlags.Variadic && !(targetFlags & ElementFlags.Variable)) {
              if (reportErrors) {
                reportError(Diagnostics.Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target, sourcePosition, targetPosition);
              }
              return Ternary.False;
            }
            if (targetFlags & ElementFlags.Required && !(sourceFlags & ElementFlags.Required)) {
              if (reportErrors) {
                reportError(Diagnostics.Source_provides_no_match_for_required_element_at_position_0_in_target, targetPosition);
              }
              return Ternary.False;
            }
            if (canExcludeDiscriminants) {
              if (sourceFlags & ElementFlags.Variable || targetFlags & ElementFlags.Variable) {
                canExcludeDiscriminants = false;
              }
              if (canExcludeDiscriminants && excludedProperties?.has("" + sourcePosition)) {
                continue;
              }
            }
            const sourceType = removeMissingType(sourceTypeArguments[sourcePosition], !!(sourceFlags & targetFlags & ElementFlags.Optional));
            const targetType = targetTypeArguments[targetPosition];
            const targetCheckType = sourceFlags & ElementFlags.Variadic && targetFlags & ElementFlags.Rest ? createArrayType(targetType) : removeMissingType(targetType, !!(targetFlags & ElementFlags.Optional));
            const related = isRelatedTo(
              sourceType,
              targetCheckType,
              3 /* Both */,
              reportErrors,
              /*headMessage*/
              void 0,
              intersectionState
            );
            if (!related) {
              if (reportErrors && (targetArity > 1 || sourceArity > 1)) {
                if (targetHasRestElement && sourcePosition >= targetStartCount && sourcePositionFromEnd >= targetEndCount && targetStartCount !== sourceArity - targetEndCount - 1) {
                  reportIncompatibleError(Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, targetStartCount, sourceArity - targetEndCount - 1, targetPosition);
                } else {
                  reportIncompatibleError(Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, sourcePosition, targetPosition);
                }
              }
              return Ternary.False;
            }
            result2 &= related;
          }
          return result2;
        }
        if (target2.target.combinedFlags & ElementFlags.Variable) {
          return Ternary.False;
        }
      }
      const requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source2) && !isEmptyArrayLiteralType(source2) && !isTupleType(source2);
      const unmatchedProperty = getUnmatchedProperty(
        source2,
        target2,
        requireOptionalProperties,
        /*matchDiscriminantProperties*/
        false
      );
      if (unmatchedProperty) {
        if (reportErrors && shouldReportUnmatchedPropertyError(source2, target2)) {
          reportUnmatchedProperty(source2, target2, unmatchedProperty, requireOptionalProperties);
        }
        return Ternary.False;
      }
      if (isObjectLiteralType(target2)) {
        for (const sourceProp of excludeProperties(getPropertiesOfType(source2), excludedProperties)) {
          if (!getPropertyOfObjectType(target2, sourceProp.escapedName)) {
            const sourceType = getTypeOfSymbol(sourceProp);
            if (!(sourceType.flags & TypeFlags.Undefined)) {
              if (reportErrors) {
                reportError(Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target2));
              }
              return Ternary.False;
            }
          }
        }
      }
      const properties = getPropertiesOfType(target2);
      const numericNamesOnly = isTupleType(source2) && isTupleType(target2);
      for (const targetProp of excludeProperties(properties, excludedProperties)) {
        const name = targetProp.escapedName;
        if (!(targetProp.flags & SymbolFlags.Prototype) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length") && (!optionalsOnly || targetProp.flags & SymbolFlags.Optional)) {
          const sourceProp = getPropertyOfType(source2, name);
          if (sourceProp && sourceProp !== targetProp) {
            const related = propertyRelatedTo(source2, target2, sourceProp, targetProp, getNonMissingTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
            if (!related) {
              return Ternary.False;
            }
            result2 &= related;
          }
        }
      }
      return result2;
    }
    function propertiesIdenticalTo(source2, target2, excludedProperties) {
      if (!(source2.flags & TypeFlags.Object && target2.flags & TypeFlags.Object)) {
        return Ternary.False;
      }
      const sourceProperties = excludeProperties(getPropertiesOfObjectType(source2), excludedProperties);
      const targetProperties = excludeProperties(getPropertiesOfObjectType(target2), excludedProperties);
      if (sourceProperties.length !== targetProperties.length) {
        return Ternary.False;
      }
      let result2 = Ternary.True;
      for (const sourceProp of sourceProperties) {
        const targetProp = getPropertyOfObjectType(target2, sourceProp.escapedName);
        if (!targetProp) {
          return Ternary.False;
        }
        const related = compareProperties(sourceProp, targetProp, isRelatedTo);
        if (!related) {
          return Ternary.False;
        }
        result2 &= related;
      }
      return result2;
    }
    function signaturesRelatedTo(source2, target2, kind, reportErrors, intersectionState) {
      if (relation === identityRelation) {
        return signaturesIdenticalTo(source2, target2, kind);
      }
      if (target2 === anyFunctionType || source2 === anyFunctionType) {
        return Ternary.True;
      }
      const sourceIsJSConstructor = source2.symbol && isJSConstructor(source2.symbol.valueDeclaration);
      const targetIsJSConstructor = target2.symbol && isJSConstructor(target2.symbol.valueDeclaration);
      const sourceSignatures = getSignaturesOfType(
        source2,
        sourceIsJSConstructor && kind === SignatureKind.Construct ? SignatureKind.Call : kind
      );
      const targetSignatures = getSignaturesOfType(
        target2,
        targetIsJSConstructor && kind === SignatureKind.Construct ? SignatureKind.Call : kind
      );
      if (kind === SignatureKind.Construct && sourceSignatures.length && targetSignatures.length) {
        const sourceIsAbstract = !!(sourceSignatures[0].flags & SignatureFlags.Abstract);
        const targetIsAbstract = !!(targetSignatures[0].flags & SignatureFlags.Abstract);
        if (sourceIsAbstract && !targetIsAbstract) {
          if (reportErrors) {
            reportError(Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
          }
          return Ternary.False;
        }
        if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
          return Ternary.False;
        }
      }
      let result2 = Ternary.True;
      const incompatibleReporter = kind === SignatureKind.Construct ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
      const sourceObjectFlags = getObjectFlags(source2);
      const targetObjectFlags = getObjectFlags(target2);
      if (sourceObjectFlags & ObjectFlags.Instantiated && targetObjectFlags & ObjectFlags.Instantiated && source2.symbol === target2.symbol || sourceObjectFlags & ObjectFlags.Reference && targetObjectFlags & ObjectFlags.Reference && source2.target === target2.target) {
        Debug.assertEqual(sourceSignatures.length, targetSignatures.length);
        for (let i = 0; i < targetSignatures.length; i++) {
          const related = signatureRelatedTo(
            sourceSignatures[i],
            targetSignatures[i],
            /*erase*/
            true,
            reportErrors,
            intersectionState,
            incompatibleReporter(sourceSignatures[i], targetSignatures[i])
          );
          if (!related) {
            return Ternary.False;
          }
          result2 &= related;
        }
      } else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
        const eraseGenerics = relation === comparableRelation;
        const sourceSignature = first(sourceSignatures);
        const targetSignature = first(targetSignatures);
        result2 = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, intersectionState, incompatibleReporter(sourceSignature, targetSignature));
        if (!result2 && reportErrors && kind === SignatureKind.Construct && sourceObjectFlags & targetObjectFlags && (targetSignature.declaration?.kind === SyntaxKind.Constructor || sourceSignature.declaration?.kind === SyntaxKind.Constructor)) {
          const constructSignatureToString = (signature) => signatureToString(
            signature,
            /*enclosingDeclaration*/
            void 0,
            TypeFormatFlags.WriteArrowStyleSignature,
            kind
          );
          reportError(Diagnostics.Type_0_is_not_assignable_to_type_1, constructSignatureToString(sourceSignature), constructSignatureToString(targetSignature));
          reportError(Diagnostics.Types_of_construct_signatures_are_incompatible);
          return result2;
        }
      } else {
        outer:
          for (const t of targetSignatures) {
            const saveErrorInfo = captureErrorCalculationState();
            let shouldElaborateErrors = reportErrors;
            for (const s of sourceSignatures) {
              const related = signatureRelatedTo(
                s,
                t,
                /*erase*/
                true,
                shouldElaborateErrors,
                intersectionState,
                incompatibleReporter(s, t)
              );
              if (related) {
                result2 &= related;
                resetErrorInfo(saveErrorInfo);
                continue outer;
              }
              shouldElaborateErrors = false;
            }
            if (shouldElaborateErrors) {
              reportError(Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source2), signatureToString(
                t,
                /*enclosingDeclaration*/
                void 0,
                /*flags*/
                void 0,
                kind
              ));
            }
            return Ternary.False;
          }
      }
      return result2;
    }
    function shouldReportUnmatchedPropertyError(source2, target2) {
      const typeCallSignatures = getSignaturesOfStructuredType(source2, SignatureKind.Call);
      const typeConstructSignatures = getSignaturesOfStructuredType(source2, SignatureKind.Construct);
      const typeProperties = getPropertiesOfObjectType(source2);
      if ((typeCallSignatures.length || typeConstructSignatures.length) && !typeProperties.length) {
        if (getSignaturesOfType(target2, SignatureKind.Call).length && typeCallSignatures.length || getSignaturesOfType(target2, SignatureKind.Construct).length && typeConstructSignatures.length) {
          return true;
        }
        return false;
      }
      return true;
    }
    function reportIncompatibleCallSignatureReturn(siga, sigb) {
      if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
        return (source2, target2) => reportIncompatibleError(Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source2), typeToString(target2));
      }
      return (source2, target2) => reportIncompatibleError(Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source2), typeToString(target2));
    }
    function reportIncompatibleConstructSignatureReturn(siga, sigb) {
      if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
        return (source2, target2) => reportIncompatibleError(Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source2), typeToString(target2));
      }
      return (source2, target2) => reportIncompatibleError(Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source2), typeToString(target2));
    }
    function signatureRelatedTo(source2, target2, erase, reportErrors, intersectionState, incompatibleReporter) {
      const checkMode = relation === subtypeRelation ? 16 /* StrictTopSignature */ : relation === strictSubtypeRelation ? 16 /* StrictTopSignature */ | 8 /* StrictArity */ : 0 /* None */;
      return compareSignaturesRelated(erase ? getErasedSignature(source2) : source2, erase ? getErasedSignature(target2) : target2, checkMode, reportErrors, reportError, incompatibleReporter, isRelatedToWorker2, reportUnreliableMapper);
      function isRelatedToWorker2(source3, target3, reportErrors2) {
        return isRelatedTo(
          source3,
          target3,
          3 /* Both */,
          reportErrors2,
          /*headMessage*/
          void 0,
          intersectionState
        );
      }
    }
    function signaturesIdenticalTo(source2, target2, kind) {
      const sourceSignatures = getSignaturesOfType(source2, kind);
      const targetSignatures = getSignaturesOfType(target2, kind);
      if (sourceSignatures.length !== targetSignatures.length) {
        return Ternary.False;
      }
      let result2 = Ternary.True;
      for (let i = 0; i < sourceSignatures.length; i++) {
        const related = compareSignaturesIdentical(
          sourceSignatures[i],
          targetSignatures[i],
          /*partialMatch*/
          false,
          /*ignoreThisTypes*/
          false,
          /*ignoreReturnTypes*/
          false,
          isRelatedTo
        );
        if (!related) {
          return Ternary.False;
        }
        result2 &= related;
      }
      return result2;
    }
    function membersRelatedToIndexInfo(source2, targetInfo, reportErrors, intersectionState) {
      let result2 = Ternary.True;
      const keyType = targetInfo.keyType;
      const props = source2.flags & TypeFlags.Intersection ? getPropertiesOfUnionOrIntersectionType(source2) : getPropertiesOfObjectType(source2);
      for (const prop of props) {
        if (isIgnoredJsxProperty(source2, prop)) {
          continue;
        }
        if (isApplicableIndexType(getLiteralTypeFromProperty(prop, TypeFlags.StringOrNumberLiteralOrUnique), keyType)) {
          const propType = getNonMissingTypeOfSymbol(prop);
          const type = exactOptionalPropertyTypes || propType.flags & TypeFlags.Undefined || keyType === numberType || !(prop.flags & SymbolFlags.Optional) ? propType : getTypeWithFacts(propType, 524288 /* NEUndefined */);
          const related = isRelatedTo(
            type,
            targetInfo.type,
            3 /* Both */,
            reportErrors,
            /*headMessage*/
            void 0,
            intersectionState
          );
          if (!related) {
            if (reportErrors) {
              reportError(Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
            }
            return Ternary.False;
          }
          result2 &= related;
        }
      }
      for (const info of getIndexInfosOfType(source2)) {
        if (isApplicableIndexType(info.keyType, keyType)) {
          const related = indexInfoRelatedTo(info, targetInfo, reportErrors, intersectionState);
          if (!related) {
            return Ternary.False;
          }
          result2 &= related;
        }
      }
      return result2;
    }
    function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors, intersectionState) {
      const related = isRelatedTo(
        sourceInfo.type,
        targetInfo.type,
        3 /* Both */,
        reportErrors,
        /*headMessage*/
        void 0,
        intersectionState
      );
      if (!related && reportErrors) {
        if (sourceInfo.keyType === targetInfo.keyType) {
          reportError(Diagnostics._0_index_signatures_are_incompatible, typeToString(sourceInfo.keyType));
        } else {
          reportError(Diagnostics._0_and_1_index_signatures_are_incompatible, typeToString(sourceInfo.keyType), typeToString(targetInfo.keyType));
        }
      }
      return related;
    }
    function indexSignaturesRelatedTo(source2, target2, sourceIsPrimitive, reportErrors, intersectionState) {
      if (relation === identityRelation) {
        return indexSignaturesIdenticalTo(source2, target2);
      }
      const indexInfos = getIndexInfosOfType(target2);
      const targetHasStringIndex = some(indexInfos, (info) => info.keyType === stringType);
      let result2 = Ternary.True;
      for (const targetInfo of indexInfos) {
        const related = relation !== strictSubtypeRelation && !sourceIsPrimitive && targetHasStringIndex && targetInfo.type.flags & TypeFlags.Any ? Ternary.True : isGenericMappedType(source2) && targetHasStringIndex ? isRelatedTo(getTemplateTypeFromMappedType(source2), targetInfo.type, 3 /* Both */, reportErrors) : typeRelatedToIndexInfo(source2, targetInfo, reportErrors, intersectionState);
        if (!related) {
          return Ternary.False;
        }
        result2 &= related;
      }
      return result2;
    }
    function typeRelatedToIndexInfo(source2, targetInfo, reportErrors, intersectionState) {
      const sourceInfo = getApplicableIndexInfo(source2, targetInfo.keyType);
      if (sourceInfo) {
        return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors, intersectionState);
      }
      if (!(intersectionState & 1 /* Source */) && (relation !== strictSubtypeRelation || getObjectFlags(source2) & ObjectFlags.FreshLiteral) && isObjectTypeWithInferableIndex(source2)) {
        return membersRelatedToIndexInfo(source2, targetInfo, reportErrors, intersectionState);
      }
      if (reportErrors) {
        reportError(Diagnostics.Index_signature_for_type_0_is_missing_in_type_1, typeToString(targetInfo.keyType), typeToString(source2));
      }
      return Ternary.False;
    }
    function indexSignaturesIdenticalTo(source2, target2) {
      const sourceInfos = getIndexInfosOfType(source2);
      const targetInfos = getIndexInfosOfType(target2);
      if (sourceInfos.length !== targetInfos.length) {
        return Ternary.False;
      }
      for (const targetInfo of targetInfos) {
        const sourceInfo = getIndexInfoOfType(source2, targetInfo.keyType);
        if (!(sourceInfo && isRelatedTo(sourceInfo.type, targetInfo.type, 3 /* Both */) && sourceInfo.isReadonly === targetInfo.isReadonly)) {
          return Ternary.False;
        }
      }
      return Ternary.True;
    }
    function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
      if (!sourceSignature.declaration || !targetSignature.declaration) {
        return true;
      }
      const sourceAccessibility = getSelectedEffectiveModifierFlags(sourceSignature.declaration, ModifierFlags.NonPublicAccessibilityModifier);
      const targetAccessibility = getSelectedEffectiveModifierFlags(targetSignature.declaration, ModifierFlags.NonPublicAccessibilityModifier);
      if (targetAccessibility === ModifierFlags.Private) {
        return true;
      }
      if (targetAccessibility === ModifierFlags.Protected && sourceAccessibility !== ModifierFlags.Private) {
        return true;
      }
      if (targetAccessibility !== ModifierFlags.Protected && !sourceAccessibility) {
        return true;
      }
      if (reportErrors) {
        reportError(Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
      }
      return false;
    }
  }
  function typeCouldHaveTopLevelSingletonTypes(type) {
    if (type.flags & TypeFlags.Boolean) {
      return false;
    }
    if (type.flags & TypeFlags.UnionOrIntersection) {
      return !!forEach(type.types, typeCouldHaveTopLevelSingletonTypes);
    }
    if (type.flags & TypeFlags.Instantiable) {
      const constraint = getConstraintOfType(type);
      if (constraint && constraint !== type) {
        return typeCouldHaveTopLevelSingletonTypes(constraint);
      }
    }
    return isUnitType(type) || !!(type.flags & TypeFlags.TemplateLiteral) || !!(type.flags & TypeFlags.StringMapping);
  }
  function getExactOptionalUnassignableProperties(source, target) {
    if (isTupleType(source) && isTupleType(target)) return emptyArray;
    return getPropertiesOfType(target).filter((targetProp) => isExactOptionalPropertyMismatch(getTypeOfPropertyOfType(source, targetProp.escapedName), getTypeOfSymbol(targetProp)));
  }
  function isExactOptionalPropertyMismatch(source, target) {
    return !!source && !!target && maybeTypeOfKind(source, TypeFlags.Undefined) && !!containsMissingType(target);
  }
  function getExactOptionalProperties(type) {
    return getPropertiesOfType(type).filter((targetProp) => containsMissingType(getTypeOfSymbol(targetProp)));
  }
  function getBestMatchingType(source, target, isRelatedTo = compareTypesAssignable) {
    return findMatchingDiscriminantType(source, target, isRelatedTo) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target);
  }
  function discriminateTypeByDiscriminableItems(target, discriminators, related) {
    const types = target.types;
    const include = types.map((t) => t.flags & TypeFlags.Primitive ? Ternary.False : Ternary.True);
    for (const [getDiscriminatingType, propertyName] of discriminators) {
      let matched = false;
      for (let i = 0; i < types.length; i++) {
        if (include[i]) {
          const targetType = getTypeOfPropertyOrIndexSignatureOfType(types[i], propertyName);
          if (targetType && someType(getDiscriminatingType(), (t) => !!related(t, targetType))) {
            matched = true;
          } else {
            include[i] = Ternary.Maybe;
          }
        }
      }
      for (let i = 0; i < types.length; i++) {
        if (include[i] === Ternary.Maybe) {
          include[i] = matched ? Ternary.False : Ternary.True;
        }
      }
    }
    const filtered = contains(include, Ternary.False) ? getUnionType(types.filter((_, i) => include[i]), UnionReduction.None) : target;
    return filtered.flags & TypeFlags.Never ? target : filtered;
  }
  function isWeakType(type) {
    if (type.flags & TypeFlags.Object) {
      const resolved = resolveStructuredTypeMembers(type);
      return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && resolved.indexInfos.length === 0 && resolved.properties.length > 0 && every(resolved.properties, (p) => !!(p.flags & SymbolFlags.Optional));
    }
    if (type.flags & TypeFlags.Substitution) {
      return isWeakType(type.baseType);
    }
    if (type.flags & TypeFlags.Intersection) {
      return every(type.types, isWeakType);
    }
    return false;
  }
  function hasCommonProperties(source, target, isComparingJsxAttributes) {
    for (const prop of getPropertiesOfType(source)) {
      if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
        return true;
      }
    }
    return false;
  }
  function getVariances(type) {
    return type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & ObjectFlags.Tuple ? arrayVariances : getVariancesWorker(type.symbol, type.typeParameters);
  }
  function getAliasVariances(symbol) {
    return getVariancesWorker(symbol, getSymbolLinks(symbol).typeParameters);
  }
  function getVariancesWorker(symbol, typeParameters = emptyArray) {
    const links = getSymbolLinks(symbol);
    if (!links.variances) {
      tracing?.push(tracing.Phase.CheckTypes, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) });
      const oldVarianceComputation = inVarianceComputation;
      const saveResolutionStart = resolutionStart;
      if (!inVarianceComputation) {
        inVarianceComputation = true;
        resolutionStart = resolutionTargets.length;
      }
      links.variances = emptyArray;
      const variances = [];
      for (const tp of typeParameters) {
        const modifiers = getTypeParameterModifiers(tp);
        let variance = modifiers & ModifierFlags.Out ? modifiers & ModifierFlags.In ? VarianceFlags.Invariant : VarianceFlags.Covariant : modifiers & ModifierFlags.In ? VarianceFlags.Contravariant : void 0;
        if (variance === void 0) {
          let unmeasurable = false;
          let unreliable = false;
          const oldHandler = outofbandVarianceMarkerHandler;
          outofbandVarianceMarkerHandler = (onlyUnreliable) => onlyUnreliable ? unreliable = true : unmeasurable = true;
          const typeWithSuper = createMarkerType(symbol, tp, markerSuperType);
          const typeWithSub = createMarkerType(symbol, tp, markerSubType);
          variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? VarianceFlags.Covariant : 0) | (isTypeAssignableTo(typeWithSuper, typeWithSub) ? VarianceFlags.Contravariant : 0);
          if (variance === VarianceFlags.Bivariant && isTypeAssignableTo(createMarkerType(symbol, tp, markerOtherType), typeWithSuper)) {
            variance = VarianceFlags.Independent;
          }
          outofbandVarianceMarkerHandler = oldHandler;
          if (unmeasurable || unreliable) {
            if (unmeasurable) {
              variance |= VarianceFlags.Unmeasurable;
            }
            if (unreliable) {
              variance |= VarianceFlags.Unreliable;
            }
          }
        }
        variances.push(variance);
      }
      if (!oldVarianceComputation) {
        inVarianceComputation = false;
        resolutionStart = saveResolutionStart;
      }
      links.variances = variances;
      tracing?.pop({ variances: variances.map(Debug.formatVariance) });
    }
    return links.variances;
  }
  function createMarkerType(symbol, source, target) {
    const mapper = makeUnaryTypeMapper(source, target);
    const type = getDeclaredTypeOfSymbol(symbol);
    if (isErrorType(type)) {
      return type;
    }
    const result = symbol.flags & SymbolFlags.TypeAlias ? getTypeAliasInstantiation(symbol, instantiateTypes(getSymbolLinks(symbol).typeParameters, mapper)) : createTypeReference(type, instantiateTypes(type.typeParameters, mapper));
    markerTypes.add(getTypeId(result));
    return result;
  }
  function isMarkerType(type) {
    return markerTypes.has(getTypeId(type));
  }
  function getTypeParameterModifiers(tp) {
    return reduceLeft(tp.symbol?.declarations, (modifiers, d) => modifiers | getEffectiveModifierFlags(d), ModifierFlags.None) & (ModifierFlags.In | ModifierFlags.Out | ModifierFlags.Const);
  }
  function hasCovariantVoidArgument(typeArguments, variances) {
    for (let i = 0; i < variances.length; i++) {
      if ((variances[i] & VarianceFlags.VarianceMask) === VarianceFlags.Covariant && typeArguments[i].flags & TypeFlags.Void) {
        return true;
      }
    }
    return false;
  }
  function isUnconstrainedTypeParameter(type) {
    return type.flags & TypeFlags.TypeParameter && !getConstraintOfTypeParameter(type);
  }
  function isNonDeferredTypeReference(type) {
    return !!(getObjectFlags(type) & ObjectFlags.Reference) && !type.node;
  }
  function isTypeReferenceWithGenericArguments(type) {
    return isNonDeferredTypeReference(type) && some(getTypeArguments(type), (t) => !!(t.flags & TypeFlags.TypeParameter) || isTypeReferenceWithGenericArguments(t));
  }
  function getGenericTypeReferenceRelationKey(source, target, postFix, ignoreConstraints) {
    const typeParameters = [];
    let constraintMarker = "";
    const sourceId = getTypeReferenceId(source, 0);
    const targetId = getTypeReferenceId(target, 0);
    return `${constraintMarker}${sourceId},${targetId}${postFix}`;
    function getTypeReferenceId(type, depth = 0) {
      let result = "" + type.target.id;
      for (const t of getTypeArguments(type)) {
        if (t.flags & TypeFlags.TypeParameter) {
          if (ignoreConstraints || isUnconstrainedTypeParameter(t)) {
            let index = typeParameters.indexOf(t);
            if (index < 0) {
              index = typeParameters.length;
              typeParameters.push(t);
            }
            result += "=" + index;
            continue;
          }
          constraintMarker = "*";
        } else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
          result += "<" + getTypeReferenceId(t, depth + 1) + ">";
          continue;
        }
        result += "-" + t.id;
      }
      return result;
    }
  }
  function getRelationKey(source, target, intersectionState, relation, ignoreConstraints) {
    if (relation === identityRelation && source.id > target.id) {
      const temp = source;
      source = target;
      target = temp;
    }
    const postFix = intersectionState ? ":" + intersectionState : "";
    return isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target) ? getGenericTypeReferenceRelationKey(source, target, postFix, ignoreConstraints) : `${source.id},${target.id}${postFix}`;
  }
  function forEachProperty(prop, callback) {
    if (getCheckFlags(prop) & CheckFlags.Synthetic) {
      for (const t of prop.links.containingType.types) {
        const p = getPropertyOfType(t, prop.escapedName);
        const result = p && forEachProperty(p, callback);
        if (result) {
          return result;
        }
      }
      return void 0;
    }
    return callback(prop);
  }
  function getDeclaringClass(prop) {
    return prop.parent && prop.parent.flags & SymbolFlags.Class ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : void 0;
  }
  function getTypeOfPropertyInBaseClass(property) {
    const classType = getDeclaringClass(property);
    const baseClassType = classType && getBaseTypes(classType)[0];
    return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName);
  }
  function isPropertyInClassDerivedFrom(prop, baseClass) {
    return forEachProperty(prop, (sp) => {
      const sourceClass = getDeclaringClass(sp);
      return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
    });
  }
  function isValidOverrideOf(sourceProp, targetProp) {
    return !forEachProperty(targetProp, (tp) => getDeclarationModifierFlagsFromSymbol(tp) & ModifierFlags.Protected ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false);
  }
  function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) {
    return forEachProperty(prop, (p) => getDeclarationModifierFlagsFromSymbol(p, writing) & ModifierFlags.Protected ? !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? void 0 : checkClass;
  }
  function isDeeplyNestedType(type, stack, depth, maxDepth = 3) {
    if (depth >= maxDepth) {
      if ((getObjectFlags(type) & ObjectFlags.InstantiatedMapped) === ObjectFlags.InstantiatedMapped) {
        type = getMappedTargetWithSymbol(type);
      }
      if (type.flags & TypeFlags.Intersection) {
        return some(type.types, (t) => isDeeplyNestedType(t, stack, depth, maxDepth));
      }
      const identity = getRecursionIdentity(type);
      let count = 0;
      let lastTypeId = 0;
      for (let i = 0; i < depth; i++) {
        const t = stack[i];
        if (hasMatchingRecursionIdentity(t, identity)) {
          if (t.id >= lastTypeId) {
            count++;
            if (count >= maxDepth) {
              return true;
            }
          }
          lastTypeId = t.id;
        }
      }
    }
    return false;
  }
  function getMappedTargetWithSymbol(type) {
    let target;
    while ((getObjectFlags(type) & ObjectFlags.InstantiatedMapped) === ObjectFlags.InstantiatedMapped && (target = getModifiersTypeFromMappedType(type)) && (target.symbol || target.flags & TypeFlags.Intersection && some(target.types, (t) => !!t.symbol))) {
      type = target;
    }
    return type;
  }
  function hasMatchingRecursionIdentity(type, identity) {
    if ((getObjectFlags(type) & ObjectFlags.InstantiatedMapped) === ObjectFlags.InstantiatedMapped) {
      type = getMappedTargetWithSymbol(type);
    }
    if (type.flags & TypeFlags.Intersection) {
      return some(type.types, (t) => hasMatchingRecursionIdentity(t, identity));
    }
    return getRecursionIdentity(type) === identity;
  }
  function getRecursionIdentity(type) {
    if (type.flags & TypeFlags.Object && !isObjectOrArrayLiteralType(type)) {
      if (getObjectFlags(type) & ObjectFlags.Reference && type.node) {
        return type.node;
      }
      if (type.symbol && !(getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol.flags & SymbolFlags.Class)) {
        return type.symbol;
      }
      if (isTupleType(type)) {
        return type.target;
      }
    }
    if (type.flags & TypeFlags.TypeParameter) {
      return type.symbol;
    }
    if (type.flags & TypeFlags.IndexedAccess) {
      do {
        type = type.objectType;
      } while (type.flags & TypeFlags.IndexedAccess);
      return type;
    }
    if (type.flags & TypeFlags.Conditional) {
      return type.root;
    }
    return type;
  }
  function isPropertyIdenticalTo(sourceProp, targetProp) {
    return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== Ternary.False;
  }
  function compareProperties(sourceProp, targetProp, compareTypes) {
    if (sourceProp === targetProp) {
      return Ternary.True;
    }
    const sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & ModifierFlags.NonPublicAccessibilityModifier;
    const targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & ModifierFlags.NonPublicAccessibilityModifier;
    if (sourcePropAccessibility !== targetPropAccessibility) {
      return Ternary.False;
    }
    if (sourcePropAccessibility) {
      if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
        return Ternary.False;
      }
    } else {
      if ((sourceProp.flags & SymbolFlags.Optional) !== (targetProp.flags & SymbolFlags.Optional)) {
        return Ternary.False;
      }
    }
    if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
      return Ternary.False;
    }
    return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
  }
  function isMatchingSignature(source, target, partialMatch) {
    const sourceParameterCount = getParameterCount(source);
    const targetParameterCount = getParameterCount(target);
    const sourceMinArgumentCount = getMinArgumentCount(source);
    const targetMinArgumentCount = getMinArgumentCount(target);
    const sourceHasRestParameter = hasEffectiveRestParameter(source);
    const targetHasRestParameter = hasEffectiveRestParameter(target);
    if (sourceParameterCount === targetParameterCount && sourceMinArgumentCount === targetMinArgumentCount && sourceHasRestParameter === targetHasRestParameter) {
      return true;
    }
    if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
      return true;
    }
    return false;
  }
  function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
    if (source === target) {
      return Ternary.True;
    }
    if (!isMatchingSignature(source, target, partialMatch)) {
      return Ternary.False;
    }
    if (length(source.typeParameters) !== length(target.typeParameters)) {
      return Ternary.False;
    }
    if (target.typeParameters) {
      const mapper = createTypeMapper(source.typeParameters, target.typeParameters);
      for (let i = 0; i < target.typeParameters.length; i++) {
        const s = source.typeParameters[i];
        const t = target.typeParameters[i];
        if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) && compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
          return Ternary.False;
        }
      }
      source = instantiateSignature(
        source,
        mapper,
        /*eraseTypeParameters*/
        true
      );
    }
    let result = Ternary.True;
    if (!ignoreThisTypes) {
      const sourceThisType = getThisTypeOfSignature(source);
      if (sourceThisType) {
        const targetThisType = getThisTypeOfSignature(target);
        if (targetThisType) {
          const related = compareTypes(sourceThisType, targetThisType);
          if (!related) {
            return Ternary.False;
          }
          result &= related;
        }
      }
    }
    const targetLen = getParameterCount(target);
    for (let i = 0; i < targetLen; i++) {
      const s = getTypeAtPosition(source, i);
      const t = getTypeAtPosition(target, i);
      const related = compareTypes(t, s);
      if (!related) {
        return Ternary.False;
      }
      result &= related;
    }
    if (!ignoreReturnTypes) {
      const sourceTypePredicate = getTypePredicateOfSignature(source);
      const targetTypePredicate = getTypePredicateOfSignature(target);
      result &= sourceTypePredicate || targetTypePredicate ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
    }
    return result;
  }
  function compareTypePredicatesIdentical(source, target, compareTypes) {
    return !(source && target && typePredicateKindsMatch(source, target)) ? Ternary.False : source.type === target.type ? Ternary.True : source.type && target.type ? compareTypes(source.type, target.type) : Ternary.False;
  }
  function literalTypesWithSameBaseType(types) {
    let commonBaseType;
    for (const t of types) {
      if (!(t.flags & TypeFlags.Never)) {
        const baseType = getBaseTypeOfLiteralType(t);
        commonBaseType ??= baseType;
        if (baseType === t || baseType !== commonBaseType) {
          return false;
        }
      }
    }
    return true;
  }
  function getCombinedTypeFlags(types) {
    return reduceLeft(types, (flags, t) => flags | (t.flags & TypeFlags.Union ? getCombinedTypeFlags(t.types) : t.flags), 0);
  }
  function getCommonSupertype(types) {
    if (types.length === 1) {
      return types[0];
    }
    const primaryTypes = strictNullChecks ? sameMap(types, (t) => filterType(t, (u) => !(u.flags & TypeFlags.Nullable))) : types;
    const superTypeOrUnion = literalTypesWithSameBaseType(primaryTypes) ? getUnionType(primaryTypes) : reduceLeft(primaryTypes, (s, t) => isTypeSubtypeOf(s, t) ? t : s);
    return primaryTypes === types ? superTypeOrUnion : getNullableType(superTypeOrUnion, getCombinedTypeFlags(types) & TypeFlags.Nullable);
  }
  function getCommonSubtype(types) {
    return reduceLeft(types, (s, t) => isTypeSubtypeOf(t, s) ? t : s);
  }
  function isArrayType(type) {
    return !!(getObjectFlags(type) & ObjectFlags.Reference) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
  }
  function isReadonlyArrayType(type) {
    return !!(getObjectFlags(type) & ObjectFlags.Reference) && type.target === globalReadonlyArrayType;
  }
  function isArrayOrTupleType(type) {
    return isArrayType(type) || isTupleType(type);
  }
  function isMutableArrayOrTuple(type) {
    return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
  }
  function getElementTypeOfArrayType(type) {
    return isArrayType(type) ? getTypeArguments(type)[0] : void 0;
  }
  function isArrayLikeType(type) {
    return isArrayType(type) || !(type.flags & TypeFlags.Nullable) && isTypeAssignableTo(type, anyReadonlyArrayType);
  }
  function isMutableArrayLikeType(type) {
    return isMutableArrayOrTuple(type) || !(type.flags & (TypeFlags.Any | TypeFlags.Nullable)) && isTypeAssignableTo(type, anyArrayType);
  }
  function getSingleBaseForNonAugmentingSubtype(type) {
    if (!(getObjectFlags(type) & ObjectFlags.Reference) || !(getObjectFlags(type.target) & ObjectFlags.ClassOrInterface)) {
      return void 0;
    }
    if (getObjectFlags(type) & ObjectFlags.IdenticalBaseTypeCalculated) {
      return getObjectFlags(type) & ObjectFlags.IdenticalBaseTypeExists ? type.cachedEquivalentBaseType : void 0;
    }
    type.objectFlags |= ObjectFlags.IdenticalBaseTypeCalculated;
    const target = type.target;
    if (getObjectFlags(target) & ObjectFlags.Class) {
      const baseTypeNode = getBaseTypeNodeOfClass(target);
      if (baseTypeNode && baseTypeNode.expression.kind !== SyntaxKind.Identifier && baseTypeNode.expression.kind !== SyntaxKind.PropertyAccessExpression) {
        return void 0;
      }
    }
    const bases = getBaseTypes(target);
    if (bases.length !== 1) {
      return void 0;
    }
    if (getMembersOfSymbol(type.symbol).size) {
      return void 0;
    }
    let instantiatedBase = !length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length)));
    if (length(getTypeArguments(type)) > length(target.typeParameters)) {
      instantiatedBase = getTypeWithThisArgument(instantiatedBase, last(getTypeArguments(type)));
    }
    type.objectFlags |= ObjectFlags.IdenticalBaseTypeExists;
    return type.cachedEquivalentBaseType = instantiatedBase;
  }
  function isEmptyLiteralType(type) {
    return strictNullChecks ? type === implicitNeverType : type === undefinedWideningType;
  }
  function isEmptyArrayLiteralType(type) {
    const elementType = getElementTypeOfArrayType(type);
    return !!elementType && isEmptyLiteralType(elementType);
  }
  function isTupleLikeType(type) {
    let lengthType;
    return isTupleType(type) || !!getPropertyOfType(type, "0") || isArrayLikeType(type) && !!(lengthType = getTypeOfPropertyOfType(type, "length")) && everyType(lengthType, (t) => !!(t.flags & TypeFlags.NumberLiteral));
  }
  function isArrayOrTupleLikeType(type) {
    return isArrayLikeType(type) || isTupleLikeType(type);
  }
  function getTupleElementType(type, index) {
    const propType = getTypeOfPropertyOfType(type, "" + index);
    if (propType) {
      return propType;
    }
    if (everyType(type, isTupleType)) {
      return getTupleElementTypeOutOfStartCount(type, index, compilerOptions.noUncheckedIndexedAccess ? undefinedType : void 0);
    }
    return void 0;
  }
  function isNeitherUnitTypeNorNever(type) {
    return !(type.flags & (TypeFlags.Unit | TypeFlags.Never));
  }
  function isUnitType(type) {
    return !!(type.flags & TypeFlags.Unit);
  }
  function isUnitLikeType(type) {
    const t = getBaseConstraintOrType(type);
    return t.flags & TypeFlags.Intersection ? some(t.types, isUnitType) : isUnitType(t);
  }
  function extractUnitType(type) {
    return type.flags & TypeFlags.Intersection ? find(type.types, isUnitType) || type : type;
  }
  function isLiteralType(type) {
    return type.flags & TypeFlags.Boolean ? true : type.flags & TypeFlags.Union ? type.flags & TypeFlags.EnumLiteral ? true : every(type.types, isUnitType) : isUnitType(type);
  }
  function getBaseTypeOfLiteralType(type) {
    return type.flags & TypeFlags.EnumLike ? getBaseTypeOfEnumLikeType(type) : type.flags & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) ? stringType : type.flags & TypeFlags.NumberLiteral ? numberType : type.flags & TypeFlags.BigIntLiteral ? bigintType : type.flags & TypeFlags.BooleanLiteral ? booleanType : type.flags & TypeFlags.Union ? getBaseTypeOfLiteralTypeUnion(type) : type;
  }
  function getBaseTypeOfLiteralTypeUnion(type) {
    const key = `B${getTypeId(type)}`;
    return getCachedType(key) ?? setCachedType(key, mapType(type, getBaseTypeOfLiteralType));
  }
  function getBaseTypeOfLiteralTypeForComparison(type) {
    return type.flags & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) ? stringType : type.flags & (TypeFlags.NumberLiteral | TypeFlags.Enum) ? numberType : type.flags & TypeFlags.BigIntLiteral ? bigintType : type.flags & TypeFlags.BooleanLiteral ? booleanType : type.flags & TypeFlags.Union ? mapType(type, getBaseTypeOfLiteralTypeForComparison) : type;
  }
  function getWidenedLiteralType(type) {
    return type.flags & TypeFlags.EnumLike && isFreshLiteralType(type) ? getBaseTypeOfEnumLikeType(type) : type.flags & TypeFlags.StringLiteral && isFreshLiteralType(type) ? stringType : type.flags & TypeFlags.NumberLiteral && isFreshLiteralType(type) ? numberType : type.flags & TypeFlags.BigIntLiteral && isFreshLiteralType(type) ? bigintType : type.flags & TypeFlags.BooleanLiteral && isFreshLiteralType(type) ? booleanType : type.flags & TypeFlags.Union ? mapType(type, getWidenedLiteralType) : type;
  }
  function getWidenedUniqueESSymbolType(type) {
    return type.flags & TypeFlags.UniqueESSymbol ? esSymbolType : type.flags & TypeFlags.Union ? mapType(type, getWidenedUniqueESSymbolType) : type;
  }
  function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
    if (!isLiteralOfContextualType(type, contextualType)) {
      type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
    }
    return getRegularTypeOfLiteralType(type);
  }
  function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
    if (type && isUnitType(type)) {
      const contextualType = !contextualSignatureReturnType ? void 0 : isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) : contextualSignatureReturnType;
      type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
    }
    return type;
  }
  function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
    if (type && isUnitType(type)) {
      const contextualType = !contextualSignatureReturnType ? void 0 : getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
      type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
    }
    return type;
  }
  function isTupleType(type) {
    return !!(getObjectFlags(type) & ObjectFlags.Reference && type.target.objectFlags & ObjectFlags.Tuple);
  }
  function isGenericTupleType(type) {
    return isTupleType(type) && !!(type.target.combinedFlags & ElementFlags.Variadic);
  }
  function isSingleElementGenericTupleType(type) {
    return isGenericTupleType(type) && type.target.elementFlags.length === 1;
  }
  function getRestTypeOfTupleType(type) {
    return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength);
  }
  function getTupleElementTypeOutOfStartCount(type, index, undefinedOrMissingType2) {
    return mapType(type, (t) => {
      const tupleType = t;
      const restType = getRestTypeOfTupleType(tupleType);
      if (!restType) {
        return undefinedType;
      }
      if (undefinedOrMissingType2 && index >= getTotalFixedElementCount(tupleType.target)) {
        return getUnionType([restType, undefinedOrMissingType2]);
      }
      return restType;
    });
  }
  function getRestArrayTypeOfTupleType(type) {
    const restType = getRestTypeOfTupleType(type);
    return restType && createArrayType(restType);
  }
  function getElementTypeOfSliceOfTupleType(type, index, endSkipCount = 0, writing = false, noReductions = false) {
    const length2 = getTypeReferenceArity(type) - endSkipCount;
    if (index < length2) {
      const typeArguments = getTypeArguments(type);
      const elementTypes = [];
      for (let i = index; i < length2; i++) {
        const t = typeArguments[i];
        elementTypes.push(type.target.elementFlags[i] & ElementFlags.Variadic ? getIndexedAccessType(t, numberType) : t);
      }
      return writing ? getIntersectionType(elementTypes) : getUnionType(elementTypes, noReductions ? UnionReduction.None : UnionReduction.Literal);
    }
    return void 0;
  }
  function isTupleTypeStructureMatching(t1, t2) {
    return getTypeReferenceArity(t1) === getTypeReferenceArity(t2) && every(t1.target.elementFlags, (f, i) => (f & ElementFlags.Variable) === (t2.target.elementFlags[i] & ElementFlags.Variable));
  }
  function isZeroBigInt({ value }) {
    return value.base10Value === "0";
  }
  function removeDefinitelyFalsyTypes(type) {
    return filterType(type, (t) => hasTypeFacts(t, 4194304 /* Truthy */));
  }
  function extractDefinitelyFalsyTypes(type) {
    return mapType(type, getDefinitelyFalsyPartOfType);
  }
  function getDefinitelyFalsyPartOfType(type) {
    return type.flags & TypeFlags.String ? emptyStringType : type.flags & TypeFlags.Number ? zeroType : type.flags & TypeFlags.BigInt ? zeroBigIntType : type === regularFalseType || type === falseType || type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null | TypeFlags.AnyOrUnknown) || type.flags & TypeFlags.StringLiteral && type.value === "" || type.flags & TypeFlags.NumberLiteral && type.value === 0 || type.flags & TypeFlags.BigIntLiteral && isZeroBigInt(type) ? type : neverType;
  }
  function getNullableType(type, flags) {
    const missing = flags & ~type.flags & (TypeFlags.Undefined | TypeFlags.Null);
    return missing === 0 ? type : missing === TypeFlags.Undefined ? getUnionType([type, undefinedType]) : missing === TypeFlags.Null ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]);
  }
  function getOptionalType(type, isProperty = false) {
    Debug.assert(strictNullChecks);
    const missingOrUndefined = isProperty ? undefinedOrMissingType : undefinedType;
    return type === missingOrUndefined || type.flags & TypeFlags.Union && type.types[0] === missingOrUndefined ? type : getUnionType([type, missingOrUndefined]);
  }
  function getGlobalNonNullableTypeInstantiation(type) {
    if (!deferredGlobalNonNullableTypeAlias) {
      deferredGlobalNonNullableTypeAlias = getGlobalSymbol(
        "NonNullable",
        SymbolFlags.TypeAlias,
        /*diagnostic*/
        void 0
      ) || unknownSymbol;
    }
    return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]) : getIntersectionType([type, emptyObjectType]);
  }
  function getNonNullableType(type) {
    return strictNullChecks ? getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
  }
  function addOptionalTypeMarker(type) {
    return strictNullChecks ? getUnionType([type, optionalType]) : type;
  }
  function removeOptionalTypeMarker(type) {
    return strictNullChecks ? removeType(type, optionalType) : type;
  }
  function propagateOptionalTypeMarker(type, node, wasOptional) {
    return wasOptional ? isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
  }
  function getOptionalExpressionType(exprType, expression) {
    return isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : exprType;
  }
  function removeMissingType(type, isOptional) {
    return exactOptionalPropertyTypes && isOptional ? removeType(type, missingType) : type;
  }
  function containsMissingType(type) {
    return type === missingType || !!(type.flags & TypeFlags.Union) && type.types[0] === missingType;
  }
  function removeMissingOrUndefinedType(type) {
    return exactOptionalPropertyTypes ? removeType(type, missingType) : getTypeWithFacts(type, 524288 /* NEUndefined */);
  }
  function isCoercibleUnderDoubleEquals(source, target) {
    return (source.flags & (TypeFlags.Number | TypeFlags.String | TypeFlags.BooleanLiteral)) !== 0 && (target.flags & (TypeFlags.Number | TypeFlags.String | TypeFlags.Boolean)) !== 0;
  }
  function isObjectTypeWithInferableIndex(type) {
    const objectFlags = getObjectFlags(type);
    return type.flags & TypeFlags.Intersection ? every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (SymbolFlags.ObjectLiteral | SymbolFlags.TypeLiteral | SymbolFlags.Enum | SymbolFlags.ValueModule)) !== 0 && !(type.symbol.flags & SymbolFlags.Class) && !typeHasCallOrConstructSignatures(type)) || !!(objectFlags & ObjectFlags.ObjectRestType) || !!(objectFlags & ObjectFlags.ReverseMapped && isObjectTypeWithInferableIndex(type.source));
  }
  function createSymbolWithType(source, type) {
    const symbol = createSymbol(source.flags, source.escapedName, getCheckFlags(source) & CheckFlags.Readonly);
    symbol.declarations = source.declarations;
    symbol.parent = source.parent;
    symbol.links.type = type;
    symbol.links.target = source;
    if (source.valueDeclaration) {
      symbol.valueDeclaration = source.valueDeclaration;
    }
    const nameType = getSymbolLinks(source).nameType;
    if (nameType) {
      symbol.links.nameType = nameType;
    }
    return symbol;
  }
  function transformTypeOfMembers(type, f) {
    const members = createSymbolTable();
    for (const property of getPropertiesOfObjectType(type)) {
      const original = getTypeOfSymbol(property);
      const updated = f(original);
      members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
    }
    return members;
  }
  function getRegularTypeOfObjectLiteral(type) {
    if (!(isObjectLiteralType(type) && getObjectFlags(type) & ObjectFlags.FreshLiteral)) {
      return type;
    }
    const regularType = type.regularType;
    if (regularType) {
      return regularType;
    }
    const resolved = type;
    const members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
    const regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.indexInfos);
    regularNew.flags = resolved.flags;
    regularNew.objectFlags |= resolved.objectFlags & ~ObjectFlags.FreshLiteral;
    type.regularType = regularNew;
    return regularNew;
  }
  function createWideningContext(parent, propertyName, siblings) {
    return { parent, propertyName, siblings, resolvedProperties: void 0 };
  }
  function getSiblingsOfContext(context) {
    if (!context.siblings) {
      const siblings = [];
      for (const type of getSiblingsOfContext(context.parent)) {
        if (isObjectLiteralType(type)) {
          const prop = getPropertyOfObjectType(type, context.propertyName);
          if (prop) {
            forEachType(getTypeOfSymbol(prop), (t) => {
              siblings.push(t);
            });
          }
        }
      }
      context.siblings = siblings;
    }
    return context.siblings;
  }
  function getPropertiesOfContext(context) {
    if (!context.resolvedProperties) {
      const names = /* @__PURE__ */ new Map();
      for (const t of getSiblingsOfContext(context)) {
        if (isObjectLiteralType(t) && !(getObjectFlags(t) & ObjectFlags.ContainsSpread)) {
          for (const prop of getPropertiesOfType(t)) {
            names.set(prop.escapedName, prop);
          }
        }
      }
      context.resolvedProperties = arrayFrom(names.values());
    }
    return context.resolvedProperties;
  }
  function getWidenedProperty(prop, context) {
    if (!(prop.flags & SymbolFlags.Property)) {
      return prop;
    }
    const original = getTypeOfSymbol(prop);
    const propContext = context && createWideningContext(
      context,
      prop.escapedName,
      /*siblings*/
      void 0
    );
    const widened = getWidenedTypeWithContext(original, propContext);
    return widened === original ? prop : createSymbolWithType(prop, widened);
  }
  function getUndefinedProperty(prop) {
    const cached = undefinedProperties.get(prop.escapedName);
    if (cached) {
      return cached;
    }
    const result = createSymbolWithType(prop, undefinedOrMissingType);
    result.flags |= SymbolFlags.Optional;
    undefinedProperties.set(prop.escapedName, result);
    return result;
  }
  function getWidenedTypeOfObjectLiteral(type, context) {
    const members = createSymbolTable();
    for (const prop of getPropertiesOfObjectType(type)) {
      members.set(prop.escapedName, getWidenedProperty(prop, context));
    }
    if (context) {
      for (const prop of getPropertiesOfContext(context)) {
        if (!members.has(prop.escapedName)) {
          members.set(prop.escapedName, getUndefinedProperty(prop));
        }
      }
    }
    const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, sameMap(getIndexInfosOfType(type), (info) => createIndexInfo(info.keyType, getWidenedType(info.type), info.isReadonly)));
    result.objectFlags |= getObjectFlags(type) & (ObjectFlags.JSLiteral | ObjectFlags.NonInferrableType);
    return result;
  }
  function getWidenedType(type) {
    return getWidenedTypeWithContext(
      type,
      /*context*/
      void 0
    );
  }
  function getWidenedTypeWithContext(type, context) {
    if (getObjectFlags(type) & ObjectFlags.RequiresWidening) {
      if (context === void 0 && type.widened) {
        return type.widened;
      }
      let result;
      if (type.flags & (TypeFlags.Any | TypeFlags.Nullable)) {
        result = anyType;
      } else if (isObjectLiteralType(type)) {
        result = getWidenedTypeOfObjectLiteral(type, context);
      } else if (type.flags & TypeFlags.Union) {
        const unionContext = context || createWideningContext(
          /*parent*/
          void 0,
          /*propertyName*/
          void 0,
          type.types
        );
        const widenedTypes = sameMap(type.types, (t) => t.flags & TypeFlags.Nullable ? t : getWidenedTypeWithContext(t, unionContext));
        result = getUnionType(widenedTypes, some(widenedTypes, isEmptyObjectType) ? UnionReduction.Subtype : UnionReduction.Literal);
      } else if (type.flags & TypeFlags.Intersection) {
        result = getIntersectionType(sameMap(type.types, getWidenedType));
      } else if (isArrayOrTupleType(type)) {
        result = createTypeReference(type.target, sameMap(getTypeArguments(type), getWidenedType));
      }
      if (result && context === void 0) {
        type.widened = result;
      }
      return result || type;
    }
    return type;
  }
  function reportWideningErrorsInType(type) {
    let errorReported = false;
    if (getObjectFlags(type) & ObjectFlags.ContainsWideningType) {
      if (type.flags & TypeFlags.Union) {
        if (some(type.types, isEmptyObjectType)) {
          errorReported = true;
        } else {
          for (const t of type.types) {
            errorReported ||= reportWideningErrorsInType(t);
          }
        }
      } else if (isArrayOrTupleType(type)) {
        for (const t of getTypeArguments(type)) {
          errorReported ||= reportWideningErrorsInType(t);
        }
      } else if (isObjectLiteralType(type)) {
        for (const p of getPropertiesOfObjectType(type)) {
          const t = getTypeOfSymbol(p);
          if (getObjectFlags(t) & ObjectFlags.ContainsWideningType) {
            errorReported = reportWideningErrorsInType(t);
            if (!errorReported) {
              const valueDeclaration = p.declarations?.find((d) => d.symbol.valueDeclaration?.parent === type.symbol.valueDeclaration);
              if (valueDeclaration) {
                error(valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
                errorReported = true;
              }
            }
          }
        }
      }
    }
    return errorReported;
  }
  function reportImplicitAny(declaration, type, wideningKind) {
    const typeAsString = typeToString(getWidenedType(type));
    if (isInJSFile(declaration) && !isCheckJsEnabledForFile(getSourceFileOfNode(declaration), compilerOptions)) {
      return;
    }
    let diagnostic;
    switch (declaration.kind) {
      case SyntaxKind.BinaryExpression:
      case SyntaxKind.PropertyDeclaration:
      case SyntaxKind.PropertySignature:
        diagnostic = noImplicitAny ? Diagnostics.Member_0_implicitly_has_an_1_type : Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
        break;
      case SyntaxKind.Parameter:
        const param = declaration;
        if (isIdentifier(param.name)) {
          const originalKeywordKind = identifierToKeywordKind(param.name);
          if ((isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && param.parent.parameters.includes(param) && (resolveName(
            param,
            param.name.escapedText,
            SymbolFlags.Type,
            /*nameNotFoundMessage*/
            void 0,
            /*isUse*/
            true
          ) || originalKeywordKind && isTypeNodeKind(originalKeywordKind))) {
            const newName = "arg" + param.parent.parameters.indexOf(param);
            const typeName = declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : "");
            errorOrSuggestion(noImplicitAny, declaration, Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName);
            return;
          }
        }
        diagnostic = declaration.dotDotDotToken ? noImplicitAny ? Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? Diagnostics.Parameter_0_implicitly_has_an_1_type : Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
        break;
      case SyntaxKind.BindingElement:
        diagnostic = Diagnostics.Binding_element_0_implicitly_has_an_1_type;
        if (!noImplicitAny) {
          return;
        }
        break;
      case SyntaxKind.JSDocFunctionType:
        error(declaration, Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
        return;
      case SyntaxKind.JSDocSignature:
        if (noImplicitAny && isJSDocOverloadTag(declaration.parent)) {
          error(declaration.parent.tagName, Diagnostics.This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation, typeAsString);
        }
        return;
      case SyntaxKind.FunctionDeclaration:
      case SyntaxKind.MethodDeclaration:
      case SyntaxKind.MethodSignature:
      case SyntaxKind.GetAccessor:
      case SyntaxKind.SetAccessor:
      case SyntaxKind.FunctionExpression:
      case SyntaxKind.ArrowFunction:
        if (noImplicitAny && !declaration.name) {
          if (wideningKind === 3 /* GeneratorYield */) {
            error(declaration, Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
          } else {
            error(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
          }
          return;
        }
        diagnostic = !noImplicitAny ? Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : wideningKind === 3 /* GeneratorYield */ ? Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
        break;
      case SyntaxKind.MappedType:
        if (noImplicitAny) {
          error(declaration, Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
        }
        return;
      default:
        diagnostic = noImplicitAny ? Diagnostics.Variable_0_implicitly_has_an_1_type : Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
    }
    errorOrSuggestion(noImplicitAny, declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString);
  }
  function reportErrorsFromWidening(declaration, type, wideningKind) {
    addLazyDiagnostic(() => {
      if (noImplicitAny && getObjectFlags(type) & ObjectFlags.ContainsWideningType && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
        if (!reportWideningErrorsInType(type)) {
          reportImplicitAny(declaration, type, wideningKind);
        }
      }
    });
  }
  function applyToParameterTypes(source, target, callback) {
    const sourceCount = getParameterCount(source);
    const targetCount = getParameterCount(target);
    const sourceRestType = getEffectiveRestType(source);
    const targetRestType = getEffectiveRestType(target);
    const targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
    const paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
    const sourceThisType = getThisTypeOfSignature(source);
    if (sourceThisType) {
      const targetThisType = getThisTypeOfSignature(target);
      if (targetThisType) {
        callback(sourceThisType, targetThisType);
      }
    }
    for (let i = 0; i < paramCount; i++) {
      callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
    }
    if (targetRestType) {
      callback(getRestTypeAtPosition(
        source,
        paramCount,
        /*readonly*/
        isConstTypeVariable(targetRestType) && !someType(targetRestType, isMutableArrayLikeType)
      ), targetRestType);
    }
  }
  function applyToReturnTypes(source, target, callback) {
    const targetTypePredicate = getTypePredicateOfSignature(target);
    if (targetTypePredicate) {
      const sourceTypePredicate = getTypePredicateOfSignature(source);
      if (sourceTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
        callback(sourceTypePredicate.type, targetTypePredicate.type);
        return;
      }
    }
    const targetReturnType = getReturnTypeOfSignature(target);
    if (couldContainTypeVariables(targetReturnType)) {
      callback(getReturnTypeOfSignature(source), targetReturnType);
    }
  }
  function createInferenceContext(typeParameters, signature, flags, compareTypes) {
    return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
  }
  function cloneInferenceContext(context, extraFlags = 0) {
    return context && createInferenceContextWorker(map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
  }
  function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
    const context = {
      inferences,
      signature,
      flags,
      compareTypes,
      mapper: reportUnmeasurableMapper,
      // initialize to a noop mapper so the context object is available, but the underlying object shape is right upon construction
      nonFixingMapper: reportUnmeasurableMapper
    };
    context.mapper = makeFixingMapperForContext(context);
    context.nonFixingMapper = makeNonFixingMapperForContext(context);
    return context;
  }
  function makeFixingMapperForContext(context) {
    return makeDeferredTypeMapper(
      map(context.inferences, (i) => i.typeParameter),
      map(context.inferences, (inference, i) => () => {
        if (!inference.isFixed) {
          inferFromIntraExpressionSites(context);
          clearCachedInferences(context.inferences);
          inference.isFixed = true;
        }
        return getInferredType(context, i);
      })
    );
  }
  function makeNonFixingMapperForContext(context) {
    return makeDeferredTypeMapper(
      map(context.inferences, (i) => i.typeParameter),
      map(context.inferences, (_, i) => () => {
        return getInferredType(context, i);
      })
    );
  }
  function clearCachedInferences(inferences) {
    for (const inference of inferences) {
      if (!inference.isFixed) {
        inference.inferredType = void 0;
      }
    }
  }
  function addIntraExpressionInferenceSite(context, node, type) {
    (context.intraExpressionInferenceSites ??= []).push({ node, type });
  }
  function inferFromIntraExpressionSites(context) {
    if (context.intraExpressionInferenceSites) {
      for (const { node, type } of context.intraExpressionInferenceSites) {
        const contextualType = node.kind === SyntaxKind.MethodDeclaration ? getContextualTypeForObjectLiteralMethod(node, ContextFlags.NoConstraints) : getContextualType(node, ContextFlags.NoConstraints);
        if (contextualType) {
          inferTypes(context.inferences, type, contextualType);
        }
      }
      context.intraExpressionInferenceSites = void 0;
    }
  }
  function createInferenceInfo(typeParameter) {
    return {
      typeParameter,
      candidates: void 0,
      contraCandidates: void 0,
      inferredType: void 0,
      priority: void 0,
      topLevel: true,
      isFixed: false,
      impliedArity: void 0
    };
  }
  function cloneInferenceInfo(inference) {
    return {
      typeParameter: inference.typeParameter,
      candidates: inference.candidates && inference.candidates.slice(),
      contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
      inferredType: inference.inferredType,
      priority: inference.priority,
      topLevel: inference.topLevel,
      isFixed: inference.isFixed,
      impliedArity: inference.impliedArity
    };
  }
  function cloneInferredPartOfContext(context) {
    const inferences = filter(context.inferences, hasInferenceCandidates);
    return inferences.length ? createInferenceContextWorker(map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) : void 0;
  }
  function getMapperFromContext(context) {
    return context && context.mapper;
  }
  function couldContainTypeVariables(type) {
    const objectFlags = getObjectFlags(type);
    if (objectFlags & ObjectFlags.CouldContainTypeVariablesComputed) {
      return !!(objectFlags & ObjectFlags.CouldContainTypeVariables);
    }
    const result = !!(type.flags & TypeFlags.Instantiable || type.flags & TypeFlags.Object && !isNonGenericTopLevelType(type) && (objectFlags & ObjectFlags.Reference && (type.node || some(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & ObjectFlags.SingleSignatureType && !!length(type.outerTypeParameters) || objectFlags & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && type.symbol.declarations || objectFlags & (ObjectFlags.Mapped | ObjectFlags.ReverseMapped | ObjectFlags.ObjectRestType | ObjectFlags.InstantiationExpressionType)) || type.flags & TypeFlags.UnionOrIntersection && !(type.flags & TypeFlags.EnumLiteral) && !isNonGenericTopLevelType(type) && some(type.types, couldContainTypeVariables));
    if (type.flags & TypeFlags.ObjectFlagsType) {
      type.objectFlags |= ObjectFlags.CouldContainTypeVariablesComputed | (result ? ObjectFlags.CouldContainTypeVariables : 0);
    }
    return result;
  }
  function isNonGenericTopLevelType(type) {
    if (type.aliasSymbol && !type.aliasTypeArguments) {
      const declaration = getDeclarationOfKind(type.aliasSymbol, SyntaxKind.TypeAliasDeclaration);
      return !!(declaration && findAncestor(declaration.parent, (n) => n.kind === SyntaxKind.SourceFile ? true : n.kind === SyntaxKind.ModuleDeclaration ? false : "quit"));
    }
    return false;
  }
  function isTypeParameterAtTopLevel(type, tp, depth = 0) {
    return !!(type === tp || type.flags & TypeFlags.UnionOrIntersection && some(type.types, (t) => isTypeParameterAtTopLevel(t, tp, depth)) || depth < 3 && type.flags & TypeFlags.Conditional && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), tp, depth + 1) || isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), tp, depth + 1)));
  }
  function isTypeParameterAtTopLevelInReturnType(signature, typeParameter) {
    const typePredicate = getTypePredicateOfSignature(signature);
    return typePredicate ? !!typePredicate.type && isTypeParameterAtTopLevel(typePredicate.type, typeParameter) : isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), typeParameter);
  }
  function createEmptyObjectTypeFromStringLiteral(type) {
    const members = createSymbolTable();
    forEachType(type, (t) => {
      if (!(t.flags & TypeFlags.StringLiteral)) {
        return;
      }
      const name = escapeLeadingUnderscores(t.value);
      const literalProp = createSymbol(SymbolFlags.Property, name);
      literalProp.links.type = anyType;
      if (t.symbol) {
        literalProp.declarations = t.symbol.declarations;
        literalProp.valueDeclaration = t.symbol.valueDeclaration;
      }
      members.set(name, literalProp);
    });
    const indexInfos = type.flags & TypeFlags.String ? [createIndexInfo(
      stringType,
      emptyObjectType,
      /*isReadonly*/
      false
    )] : emptyArray;
    return createAnonymousType(
      /*symbol*/
      void 0,
      members,
      emptyArray,
      emptyArray,
      indexInfos
    );
  }
  function inferTypeForHomomorphicMappedType(source, target, constraint) {
    const cacheKey = source.id + "," + target.id + "," + constraint.id;
    if (reverseHomomorphicMappedCache.has(cacheKey)) {
      return reverseHomomorphicMappedCache.get(cacheKey);
    }
    const type = createReverseMappedType(source, target, constraint);
    reverseHomomorphicMappedCache.set(cacheKey, type);
    return type;
  }
  function isPartiallyInferableType(type) {
    return !(getObjectFlags(type) & ObjectFlags.NonInferrableType) || isObjectLiteralType(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getElementTypes(type), isPartiallyInferableType);
  }
  function createReverseMappedType(source, target, constraint) {
    if (!(getIndexInfoOfType(source, stringType) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
      return void 0;
    }
    if (isArrayType(source)) {
      const elementType = inferReverseMappedType(getTypeArguments(source)[0], target, constraint);
      if (!elementType) {
        return void 0;
      }
      return createArrayType(elementType, isReadonlyArrayType(source));
    }
    if (isTupleType(source)) {
      const elementTypes = map(getElementTypes(source), (t) => inferReverseMappedType(t, target, constraint));
      if (!every(elementTypes, (t) => !!t)) {
        return void 0;
      }
      const elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? sameMap(source.target.elementFlags, (f) => f & ElementFlags.Optional ? ElementFlags.Required : f) : source.target.elementFlags;
      return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations);
    }
    const reversed = createObjectType(
      ObjectFlags.ReverseMapped | ObjectFlags.Anonymous,
      /*symbol*/
      void 0
    );
    reversed.source = source;
    reversed.mappedType = target;
    reversed.constraintType = constraint;
    return reversed;
  }
  function getTypeOfReverseMappedSymbol(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      links.type = inferReverseMappedType(symbol.links.propertyType, symbol.links.mappedType, symbol.links.constraintType) || unknownType;
    }
    return links.type;
  }
  function inferReverseMappedTypeWorker(sourceType, target, constraint) {
    const typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
    const templateType = getTemplateTypeFromMappedType(target);
    const inference = createInferenceInfo(typeParameter);
    inferTypes([inference], sourceType, templateType);
    return getTypeFromInference(inference) || unknownType;
  }
  function inferReverseMappedType(source, target, constraint) {
    const cacheKey = source.id + "," + target.id + "," + constraint.id;
    if (reverseMappedCache.has(cacheKey)) {
      return reverseMappedCache.get(cacheKey) || unknownType;
    }
    reverseMappedSourceStack.push(source);
    reverseMappedTargetStack.push(target);
    const saveExpandingFlags = reverseExpandingFlags;
    if (isDeeplyNestedType(source, reverseMappedSourceStack, reverseMappedSourceStack.length, 2)) reverseExpandingFlags |= 1 /* Source */;
    if (isDeeplyNestedType(target, reverseMappedTargetStack, reverseMappedTargetStack.length, 2)) reverseExpandingFlags |= 2 /* Target */;
    let type;
    if (reverseExpandingFlags !== 3 /* Both */) {
      type = inferReverseMappedTypeWorker(source, target, constraint);
    }
    reverseMappedSourceStack.pop();
    reverseMappedTargetStack.pop();
    reverseExpandingFlags = saveExpandingFlags;
    reverseMappedCache.set(cacheKey, type);
    return type;
  }
  function* getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
    const properties = getPropertiesOfType(target);
    for (const targetProp of properties) {
      if (isStaticPrivateIdentifierProperty(targetProp)) {
        continue;
      }
      if (requireOptionalProperties || !(targetProp.flags & SymbolFlags.Optional || getCheckFlags(targetProp) & CheckFlags.Partial)) {
        const sourceProp = getPropertyOfType(source, targetProp.escapedName);
        if (!sourceProp) {
          yield targetProp;
        } else if (matchDiscriminantProperties) {
          const targetType = getTypeOfSymbol(targetProp);
          if (targetType.flags & TypeFlags.Unit) {
            const sourceType = getTypeOfSymbol(sourceProp);
            if (!(sourceType.flags & TypeFlags.Any || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) {
              yield targetProp;
            }
          }
        }
      }
    }
  }
  function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
    return firstOrUndefinedIterator(getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties));
  }
  function tupleTypesDefinitelyUnrelated(source, target) {
    return !(target.target.combinedFlags & ElementFlags.Variadic) && target.target.minLength > source.target.minLength || !(target.target.combinedFlags & ElementFlags.Variable) && (!!(source.target.combinedFlags & ElementFlags.Variable) || target.target.fixedLength < source.target.fixedLength);
  }
  function typesDefinitelyUnrelated(source, target) {
    return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) : !!getUnmatchedProperty(
      source,
      target,
      /*requireOptionalProperties*/
      false,
      /*matchDiscriminantProperties*/
      true
    ) && !!getUnmatchedProperty(
      target,
      source,
      /*requireOptionalProperties*/
      false,
      /*matchDiscriminantProperties*/
      false
    );
  }
  function getTypeFromInference(inference) {
    return inference.candidates ? getUnionType(inference.candidates, UnionReduction.Subtype) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : void 0;
  }
  function hasSkipDirectInferenceFlag(node) {
    return !!getNodeLinks(node).skipDirectInference;
  }
  function isFromInferenceBlockedSource(type) {
    return !!(type.symbol && some(type.symbol.declarations, hasSkipDirectInferenceFlag));
  }
  function templateLiteralTypesDefinitelyUnrelated(source, target) {
    const sourceStart = source.texts[0];
    const targetStart = target.texts[0];
    const sourceEnd = source.texts[source.texts.length - 1];
    const targetEnd = target.texts[target.texts.length - 1];
    const startLen = Math.min(sourceStart.length, targetStart.length);
    const endLen = Math.min(sourceEnd.length, targetEnd.length);
    return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen);
  }
  function isValidNumberString(s, roundTripOnly) {
    if (s === "") return false;
    const n = +s;
    return isFinite(n) && (!roundTripOnly || "" + n === s);
  }
  function parseBigIntLiteralType(text) {
    return getBigIntLiteralType(parseValidBigInt(text));
  }
  function isMemberOfStringMapping(source, target) {
    if (target.flags & TypeFlags.Any) {
      return true;
    }
    if (target.flags & (TypeFlags.String | TypeFlags.TemplateLiteral)) {
      return isTypeAssignableTo(source, target);
    }
    if (target.flags & TypeFlags.StringMapping) {
      const mappingStack = [];
      while (target.flags & TypeFlags.StringMapping) {
        mappingStack.unshift(target.symbol);
        target = target.type;
      }
      const mappedSource = reduceLeft(mappingStack, (memo, value) => getStringMappingType(value, memo), source);
      return mappedSource === source && isMemberOfStringMapping(source, target);
    }
    return false;
  }
  function isValidTypeForTemplateLiteralPlaceholder(source, target) {
    if (target.flags & TypeFlags.Intersection) {
      return every(target.types, (t) => t === emptyTypeLiteralType || isValidTypeForTemplateLiteralPlaceholder(source, t));
    }
    if (target.flags & TypeFlags.String || isTypeAssignableTo(source, target)) {
      return true;
    }
    if (source.flags & TypeFlags.StringLiteral) {
      const value = source.value;
      return !!(target.flags & TypeFlags.Number && isValidNumberString(
        value,
        /*roundTripOnly*/
        false
      ) || target.flags & TypeFlags.BigInt && isValidBigIntString(
        value,
        /*roundTripOnly*/
        false
      ) || target.flags & (TypeFlags.BooleanLiteral | TypeFlags.Nullable) && value === target.intrinsicName || target.flags & TypeFlags.StringMapping && isMemberOfStringMapping(getStringLiteralType(value), target) || target.flags & TypeFlags.TemplateLiteral && isTypeMatchedByTemplateLiteralType(source, target));
    }
    if (source.flags & TypeFlags.TemplateLiteral) {
      const texts = source.texts;
      return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo(source.types[0], target);
    }
    return false;
  }
  function inferTypesFromTemplateLiteralType(source, target) {
    return source.flags & TypeFlags.StringLiteral ? inferFromLiteralPartsToTemplateLiteral([source.value], emptyArray, target) : source.flags & TypeFlags.TemplateLiteral ? arrayIsEqualTo(source.texts, target.texts) ? map(source.types, (s, i) => {
      return isTypeAssignableTo(getBaseConstraintOrType(s), getBaseConstraintOrType(target.types[i])) ? s : getStringLikeTypeForType(s);
    }) : inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : void 0;
  }
  function isTypeMatchedByTemplateLiteralType(source, target) {
    const inferences = inferTypesFromTemplateLiteralType(source, target);
    return !!inferences && every(inferences, (r, i) => isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]));
  }
  function getStringLikeTypeForType(type) {
    return type.flags & (TypeFlags.Any | TypeFlags.StringLike) ? type : getTemplateLiteralType(["", ""], [type]);
  }
  function inferFromLiteralPartsToTemplateLiteral(sourceTexts, sourceTypes, target) {
    const lastSourceIndex = sourceTexts.length - 1;
    const sourceStartText = sourceTexts[0];
    const sourceEndText = sourceTexts[lastSourceIndex];
    const targetTexts = target.texts;
    const lastTargetIndex = targetTexts.length - 1;
    const targetStartText = targetTexts[0];
    const targetEndText = targetTexts[lastTargetIndex];
    if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return void 0;
    const remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length);
    const matches = [];
    let seg = 0;
    let pos = targetStartText.length;
    for (let i = 1; i < lastTargetIndex; i++) {
      const delim = targetTexts[i];
      if (delim.length > 0) {
        let s = seg;
        let p = pos;
        while (true) {
          p = getSourceText(s).indexOf(delim, p);
          if (p >= 0) break;
          s++;
          if (s === sourceTexts.length) return void 0;
          p = 0;
        }
        addMatch(s, p);
        pos += delim.length;
      } else if (pos < getSourceText(seg).length) {
        addMatch(seg, pos + 1);
      } else if (seg < lastSourceIndex) {
        addMatch(seg + 1, 0);
      } else {
        return void 0;
      }
    }
    addMatch(lastSourceIndex, getSourceText(lastSourceIndex).length);
    return matches;
    function getSourceText(index) {
      return index < lastSourceIndex ? sourceTexts[index] : remainingEndText;
    }
    function addMatch(s, p) {
      const matchType = s === seg ? getStringLiteralType(getSourceText(s).slice(pos, p)) : getTemplateLiteralType(
        [sourceTexts[seg].slice(pos), ...sourceTexts.slice(seg + 1, s), getSourceText(s).slice(0, p)],
        sourceTypes.slice(seg, s)
      );
      matches.push(matchType);
      seg = s;
      pos = p;
    }
  }
  function isTupleOfSelf(typeParameter, type) {
    return isTupleType(type) && getTupleElementType(type, 0) === getIndexedAccessType(typeParameter, getNumberLiteralType(0)) && !getTypeOfPropertyOfType(type, "1");
  }
  function inferTypes(inferences, originalSource, originalTarget, priority = InferencePriority.None, contravariant = false) {
    let bivariant = false;
    let propagationType;
    let inferencePriority = InferencePriority.MaxValue;
    let visited;
    let sourceStack;
    let targetStack;
    let expandingFlags = 0 /* None */;
    inferFromTypes(originalSource, originalTarget);
    function inferFromTypes(source, target) {
      if (!couldContainTypeVariables(target) || isNoInferType(target)) {
        return;
      }
      if (source === wildcardType || source === blockedStringType) {
        const savePropagationType = propagationType;
        propagationType = source;
        inferFromTypes(target, target);
        propagationType = savePropagationType;
        return;
      }
      if (source.aliasSymbol && source.aliasSymbol === target.aliasSymbol) {
        if (source.aliasTypeArguments) {
          const params = getSymbolLinks(source.aliasSymbol).typeParameters;
          const minParams = getMinTypeArgumentCount(params);
          const sourceTypes = fillMissingTypeArguments(source.aliasTypeArguments, params, minParams, isInJSFile(source.aliasSymbol.valueDeclaration));
          const targetTypes = fillMissingTypeArguments(target.aliasTypeArguments, params, minParams, isInJSFile(source.aliasSymbol.valueDeclaration));
          inferFromTypeArguments(sourceTypes, targetTypes, getAliasVariances(source.aliasSymbol));
        }
        return;
      }
      if (source === target && source.flags & TypeFlags.UnionOrIntersection) {
        for (const t of source.types) {
          inferFromTypes(t, t);
        }
        return;
      }
      if (target.flags & TypeFlags.Union) {
        const [tempSources, tempTargets] = inferFromMatchingTypes(source.flags & TypeFlags.Union ? source.types : [source], target.types, isTypeOrBaseIdenticalTo);
        const [sources, targets] = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy);
        if (targets.length === 0) {
          return;
        }
        target = getUnionType(targets);
        if (sources.length === 0) {
          inferWithPriority(source, target, InferencePriority.NakedTypeVariable);
          return;
        }
        source = getUnionType(sources);
      } else if (target.flags & TypeFlags.Intersection && !every(target.types, isNonGenericObjectType)) {
        if (!(source.flags & TypeFlags.Union)) {
          const [sources, targets] = inferFromMatchingTypes(source.flags & TypeFlags.Intersection ? source.types : [source], target.types, isTypeIdenticalTo);
          if (sources.length === 0 || targets.length === 0) {
            return;
          }
          source = getIntersectionType(sources);
          target = getIntersectionType(targets);
        }
      }
      if (target.flags & (TypeFlags.IndexedAccess | TypeFlags.Substitution)) {
        if (isNoInferType(target)) {
          return;
        }
        target = getActualTypeVariable(target);
      }
      if (target.flags & TypeFlags.TypeVariable) {
        if (isFromInferenceBlockedSource(source)) {
          return;
        }
        const inference = getInferenceInfoForType(target);
        if (inference) {
          if (getObjectFlags(source) & ObjectFlags.NonInferrableType || source === nonInferrableAnyType) {
            return;
          }
          if (!inference.isFixed) {
            const candidate = propagationType || source;
            if (candidate === blockedStringType) {
              return;
            }
            if (inference.priority === void 0 || priority < inference.priority) {
              inference.candidates = void 0;
              inference.contraCandidates = void 0;
              inference.topLevel = true;
              inference.priority = priority;
            }
            if (priority === inference.priority) {
              if (isTupleOfSelf(inference.typeParameter, candidate)) {
                return;
              }
              if (contravariant && !bivariant) {
                if (!contains(inference.contraCandidates, candidate)) {
                  inference.contraCandidates = append(inference.contraCandidates, candidate);
                  clearCachedInferences(inferences);
                }
              } else if (!contains(inference.candidates, candidate)) {
                inference.candidates = append(inference.candidates, candidate);
                clearCachedInferences(inferences);
              }
            }
            if (!(priority & InferencePriority.ReturnType) && target.flags & TypeFlags.TypeParameter && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
              inference.topLevel = false;
              clearCachedInferences(inferences);
            }
          }
          inferencePriority = Math.min(inferencePriority, priority);
          return;
        }
        const simplified = getSimplifiedType(
          target,
          /*writing*/
          false
        );
        if (simplified !== target) {
          inferFromTypes(source, simplified);
        } else if (target.flags & TypeFlags.IndexedAccess) {
          const indexType = getSimplifiedType(
            target.indexType,
            /*writing*/
            false
          );
          if (indexType.flags & TypeFlags.Instantiable) {
            const simplified2 = distributeIndexOverObjectType(
              getSimplifiedType(
                target.objectType,
                /*writing*/
                false
              ),
              indexType,
              /*writing*/
              false
            );
            if (simplified2 && simplified2 !== target) {
              inferFromTypes(source, simplified2);
            }
          }
        }
      }
      if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source.target === target.target || isArrayType(source) && isArrayType(target)) && !(source.node && target.node)) {
        inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
      } else if (source.flags & TypeFlags.Index && target.flags & TypeFlags.Index) {
        inferFromContravariantTypes(source.type, target.type);
      } else if ((isLiteralType(source) || source.flags & TypeFlags.String) && target.flags & TypeFlags.Index) {
        const empty = createEmptyObjectTypeFromStringLiteral(source);
        inferFromContravariantTypesWithPriority(empty, target.type, InferencePriority.LiteralKeyof);
      } else if (source.flags & TypeFlags.IndexedAccess && target.flags & TypeFlags.IndexedAccess) {
        inferFromTypes(source.objectType, target.objectType);
        inferFromTypes(source.indexType, target.indexType);
      } else if (source.flags & TypeFlags.StringMapping && target.flags & TypeFlags.StringMapping) {
        if (source.symbol === target.symbol) {
          inferFromTypes(source.type, target.type);
        }
      } else if (source.flags & TypeFlags.Substitution) {
        inferFromTypes(source.baseType, target);
        inferWithPriority(getSubstitutionIntersection(source), target, InferencePriority.SubstituteSource);
      } else if (target.flags & TypeFlags.Conditional) {
        invokeOnce(source, target, inferToConditionalType);
      } else if (target.flags & TypeFlags.UnionOrIntersection) {
        inferToMultipleTypes(source, target.types, target.flags);
      } else if (source.flags & TypeFlags.Union) {
        const sourceTypes = source.types;
        for (const sourceType of sourceTypes) {
          inferFromTypes(sourceType, target);
        }
      } else if (target.flags & TypeFlags.TemplateLiteral) {
        inferToTemplateLiteralType(source, target);
      } else {
        source = getReducedType(source);
        if (isGenericMappedType(source) && isGenericMappedType(target)) {
          invokeOnce(source, target, inferFromGenericMappedTypes);
        }
        if (!(priority & InferencePriority.NoConstraints && source.flags & (TypeFlags.Intersection | TypeFlags.Instantiable))) {
          const apparentSource = getApparentType(source);
          if (apparentSource !== source && !(apparentSource.flags & (TypeFlags.Object | TypeFlags.Intersection))) {
            return inferFromTypes(apparentSource, target);
          }
          source = apparentSource;
        }
        if (source.flags & (TypeFlags.Object | TypeFlags.Intersection)) {
          invokeOnce(source, target, inferFromObjectTypes);
        }
      }
    }
    function inferWithPriority(source, target, newPriority) {
      const savePriority = priority;
      priority |= newPriority;
      inferFromTypes(source, target);
      priority = savePriority;
    }
    function inferFromContravariantTypesWithPriority(source, target, newPriority) {
      const savePriority = priority;
      priority |= newPriority;
      inferFromContravariantTypes(source, target);
      priority = savePriority;
    }
    function inferToMultipleTypesWithPriority(source, targets, targetFlags, newPriority) {
      const savePriority = priority;
      priority |= newPriority;
      inferToMultipleTypes(source, targets, targetFlags);
      priority = savePriority;
    }
    function invokeOnce(source, target, action) {
      const key = source.id + "," + target.id;
      const status = visited && visited.get(key);
      if (status !== void 0) {
        inferencePriority = Math.min(inferencePriority, status);
        return;
      }
      (visited || (visited = /* @__PURE__ */ new Map())).set(key, InferencePriority.Circularity);
      const saveInferencePriority = inferencePriority;
      inferencePriority = InferencePriority.MaxValue;
      const saveExpandingFlags = expandingFlags;
      (sourceStack ??= []).push(source);
      (targetStack ??= []).push(target);
      if (isDeeplyNestedType(source, sourceStack, sourceStack.length, 2)) expandingFlags |= 1 /* Source */;
      if (isDeeplyNestedType(target, targetStack, targetStack.length, 2)) expandingFlags |= 2 /* Target */;
      if (expandingFlags !== 3 /* Both */) {
        action(source, target);
      } else {
        inferencePriority = InferencePriority.Circularity;
      }
      targetStack.pop();
      sourceStack.pop();
      expandingFlags = saveExpandingFlags;
      visited.set(key, inferencePriority);
      inferencePriority = Math.min(inferencePriority, saveInferencePriority);
    }
    function inferFromMatchingTypes(sources, targets, matches) {
      let matchedSources;
      let matchedTargets;
      for (const t of targets) {
        for (const s of sources) {
          if (matches(s, t)) {
            inferFromTypes(s, t);
            matchedSources = appendIfUnique(matchedSources, s);
            matchedTargets = appendIfUnique(matchedTargets, t);
          }
        }
      }
      return [
        matchedSources ? filter(sources, (t) => !contains(matchedSources, t)) : sources,
        matchedTargets ? filter(targets, (t) => !contains(matchedTargets, t)) : targets
      ];
    }
    function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
      const count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
      for (let i = 0; i < count; i++) {
        if (i < variances.length && (variances[i] & VarianceFlags.VarianceMask) === VarianceFlags.Contravariant) {
          inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
        } else {
          inferFromTypes(sourceTypes[i], targetTypes[i]);
        }
      }
    }
    function inferFromContravariantTypes(source, target) {
      contravariant = !contravariant;
      inferFromTypes(source, target);
      contravariant = !contravariant;
    }
    function inferFromContravariantTypesIfStrictFunctionTypes(source, target) {
      if (strictFunctionTypes || priority & InferencePriority.AlwaysStrict) {
        inferFromContravariantTypes(source, target);
      } else {
        inferFromTypes(source, target);
      }
    }
    function getInferenceInfoForType(type) {
      if (type.flags & TypeFlags.TypeVariable) {
        for (const inference of inferences) {
          if (type === inference.typeParameter) {
            return inference;
          }
        }
      }
      return void 0;
    }
    function getSingleTypeVariableFromIntersectionTypes(types) {
      let typeVariable;
      for (const type of types) {
        const t = type.flags & TypeFlags.Intersection && find(type.types, (t2) => !!getInferenceInfoForType(t2));
        if (!t || typeVariable && t !== typeVariable) {
          return void 0;
        }
        typeVariable = t;
      }
      return typeVariable;
    }
    function inferToMultipleTypes(source, targets, targetFlags) {
      let typeVariableCount = 0;
      if (targetFlags & TypeFlags.Union) {
        let nakedTypeVariable;
        const sources = source.flags & TypeFlags.Union ? source.types : [source];
        const matched = new Array(sources.length);
        let inferenceCircularity = false;
        for (const t of targets) {
          if (getInferenceInfoForType(t)) {
            nakedTypeVariable = t;
            typeVariableCount++;
          } else {
            for (let i = 0; i < sources.length; i++) {
              const saveInferencePriority = inferencePriority;
              inferencePriority = InferencePriority.MaxValue;
              inferFromTypes(sources[i], t);
              if (inferencePriority === priority) matched[i] = true;
              inferenceCircularity = inferenceCircularity || inferencePriority === InferencePriority.Circularity;
              inferencePriority = Math.min(inferencePriority, saveInferencePriority);
            }
          }
        }
        if (typeVariableCount === 0) {
          const intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
          if (intersectionTypeVariable) {
            inferWithPriority(source, intersectionTypeVariable, InferencePriority.NakedTypeVariable);
          }
          return;
        }
        if (typeVariableCount === 1 && !inferenceCircularity) {
          const unmatched = flatMap(sources, (s, i) => matched[i] ? void 0 : s);
          if (unmatched.length) {
            inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
            return;
          }
        }
      } else {
        for (const t of targets) {
          if (getInferenceInfoForType(t)) {
            typeVariableCount++;
          } else {
            inferFromTypes(source, t);
          }
        }
      }
      if (targetFlags & TypeFlags.Intersection ? typeVariableCount === 1 : typeVariableCount > 0) {
        for (const t of targets) {
          if (getInferenceInfoForType(t)) {
            inferWithPriority(source, t, InferencePriority.NakedTypeVariable);
          }
        }
      }
    }
    function inferToMappedType(source, target, constraintType) {
      if (constraintType.flags & TypeFlags.Union || constraintType.flags & TypeFlags.Intersection) {
        let result = false;
        for (const type of constraintType.types) {
          result = inferToMappedType(source, target, type) || result;
        }
        return result;
      }
      if (constraintType.flags & TypeFlags.Index) {
        const inference = getInferenceInfoForType(constraintType.type);
        if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
          const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
          if (inferredType) {
            inferWithPriority(
              inferredType,
              inference.typeParameter,
              getObjectFlags(source) & ObjectFlags.NonInferrableType ? InferencePriority.PartialHomomorphicMappedType : InferencePriority.HomomorphicMappedType
            );
          }
        }
        return true;
      }
      if (constraintType.flags & TypeFlags.TypeParameter) {
        inferWithPriority(getIndexType(
          source,
          /*indexFlags*/
          !!source.pattern ? IndexFlags.NoIndexSignatures : IndexFlags.None
        ), constraintType, InferencePriority.MappedTypeConstraint);
        const extendedConstraint = getConstraintOfType(constraintType);
        if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
          return true;
        }
        const propTypes = map(getPropertiesOfType(source), getTypeOfSymbol);
        const indexTypes = map(getIndexInfosOfType(source), (info) => info !== enumNumberIndexInfo ? info.type : neverType);
        inferFromTypes(getUnionType(concatenate(propTypes, indexTypes)), getTemplateTypeFromMappedType(target));
        return true;
      }
      return false;
    }
    function inferToConditionalType(source, target) {
      if (source.flags & TypeFlags.Conditional) {
        inferFromTypes(source.checkType, target.checkType);
        inferFromTypes(source.extendsType, target.extendsType);
        inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
        inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
      } else {
        const targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
        inferToMultipleTypesWithPriority(source, targetTypes, target.flags, contravariant ? InferencePriority.ContravariantConditional : 0);
      }
    }
    function inferToTemplateLiteralType(source, target) {
      const matches = inferTypesFromTemplateLiteralType(source, target);
      const types = target.types;
      if (matches || every(target.texts, (s) => s.length === 0)) {
        for (let i = 0; i < types.length; i++) {
          const source2 = matches ? matches[i] : neverType;
          const target2 = types[i];
          if (source2.flags & TypeFlags.StringLiteral && target2.flags & TypeFlags.TypeVariable) {
            const inferenceContext = getInferenceInfoForType(target2);
            const constraint = inferenceContext ? getBaseConstraintOfType(inferenceContext.typeParameter) : void 0;
            if (constraint && !isTypeAny(constraint)) {
              const constraintTypes = constraint.flags & TypeFlags.Union ? constraint.types : [constraint];
              let allTypeFlags = reduceLeft(constraintTypes, (flags, t) => flags | t.flags, 0);
              if (!(allTypeFlags & TypeFlags.String)) {
                const str = source2.value;
                if (allTypeFlags & TypeFlags.NumberLike && !isValidNumberString(
                  str,
                  /*roundTripOnly*/
                  true
                )) {
                  allTypeFlags &= ~TypeFlags.NumberLike;
                }
                if (allTypeFlags & TypeFlags.BigIntLike && !isValidBigIntString(
                  str,
                  /*roundTripOnly*/
                  true
                )) {
                  allTypeFlags &= ~TypeFlags.BigIntLike;
                }
                const matchingType = reduceLeft(constraintTypes, (left, right) => !(right.flags & allTypeFlags) ? left : left.flags & TypeFlags.String ? left : right.flags & TypeFlags.String ? source2 : left.flags & TypeFlags.TemplateLiteral ? left : right.flags & TypeFlags.TemplateLiteral && isTypeMatchedByTemplateLiteralType(source2, right) ? source2 : left.flags & TypeFlags.StringMapping ? left : right.flags & TypeFlags.StringMapping && str === applyStringMapping(right.symbol, str) ? source2 : left.flags & TypeFlags.StringLiteral ? left : right.flags & TypeFlags.StringLiteral && right.value === str ? right : left.flags & TypeFlags.Number ? left : right.flags & TypeFlags.Number ? getNumberLiteralType(+str) : left.flags & TypeFlags.Enum ? left : right.flags & TypeFlags.Enum ? getNumberLiteralType(+str) : left.flags & TypeFlags.NumberLiteral ? left : right.flags & TypeFlags.NumberLiteral && right.value === +str ? right : left.flags & TypeFlags.BigInt ? left : right.flags & TypeFlags.BigInt ? parseBigIntLiteralType(str) : left.flags & TypeFlags.BigIntLiteral ? left : right.flags & TypeFlags.BigIntLiteral && pseudoBigIntToString(right.value) === str ? right : left.flags & TypeFlags.Boolean ? left : right.flags & TypeFlags.Boolean ? str === "true" ? trueType : str === "false" ? falseType : booleanType : left.flags & TypeFlags.BooleanLiteral ? left : right.flags & TypeFlags.BooleanLiteral && right.intrinsicName === str ? right : left.flags & TypeFlags.Undefined ? left : right.flags & TypeFlags.Undefined && right.intrinsicName === str ? right : left.flags & TypeFlags.Null ? left : right.flags & TypeFlags.Null && right.intrinsicName === str ? right : left, neverType);
                if (!(matchingType.flags & TypeFlags.Never)) {
                  inferFromTypes(matchingType, target2);
                  continue;
                }
              }
            }
          }
          inferFromTypes(source2, target2);
        }
      }
    }
    function inferFromGenericMappedTypes(source, target) {
      inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
      inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
      const sourceNameType = getNameTypeFromMappedType(source);
      const targetNameType = getNameTypeFromMappedType(target);
      if (sourceNameType && targetNameType) inferFromTypes(sourceNameType, targetNameType);
    }
    function inferFromObjectTypes(source, target) {
      if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
        inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
        return;
      }
      if (isGenericMappedType(source) && isGenericMappedType(target)) {
        inferFromGenericMappedTypes(source, target);
      }
      if (getObjectFlags(target) & ObjectFlags.Mapped && !target.declaration.nameType) {
        const constraintType = getConstraintTypeFromMappedType(target);
        if (inferToMappedType(source, target, constraintType)) {
          return;
        }
      }
      if (!typesDefinitelyUnrelated(source, target)) {
        if (isArrayOrTupleType(source)) {
          if (isTupleType(target)) {
            const sourceArity = getTypeReferenceArity(source);
            const targetArity = getTypeReferenceArity(target);
            const elementTypes = getTypeArguments(target);
            const elementFlags = target.target.elementFlags;
            if (isTupleType(source) && isTupleTypeStructureMatching(source, target)) {
              for (let i = 0; i < targetArity; i++) {
                inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
              }
              return;
            }
            const startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0;
            const endLength = Math.min(isTupleType(source) ? getEndElementCount(source.target, ElementFlags.Fixed) : 0, target.target.combinedFlags & ElementFlags.Variable ? getEndElementCount(target.target, ElementFlags.Fixed) : 0);
            for (let i = 0; i < startLength; i++) {
              inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
            }
            if (!isTupleType(source) || sourceArity - startLength - endLength === 1 && source.target.elementFlags[startLength] & ElementFlags.Rest) {
              const restType = getTypeArguments(source)[startLength];
              for (let i = startLength; i < targetArity - endLength; i++) {
                inferFromTypes(elementFlags[i] & ElementFlags.Variadic ? createArrayType(restType) : restType, elementTypes[i]);
              }
            } else {
              const middleLength = targetArity - startLength - endLength;
              if (middleLength === 2) {
                if (elementFlags[startLength] & elementFlags[startLength + 1] & ElementFlags.Variadic) {
                  const targetInfo = getInferenceInfoForType(elementTypes[startLength]);
                  if (targetInfo && targetInfo.impliedArity !== void 0) {
                    inferFromTypes(sliceTupleType(source, startLength, endLength + sourceArity - targetInfo.impliedArity), elementTypes[startLength]);
                    inferFromTypes(sliceTupleType(source, startLength + targetInfo.impliedArity, endLength), elementTypes[startLength + 1]);
                  }
                } else if (elementFlags[startLength] & ElementFlags.Variadic && elementFlags[startLength + 1] & ElementFlags.Rest) {
                  const param = getInferenceInfoForType(elementTypes[startLength])?.typeParameter;
                  const constraint = param && getBaseConstraintOfType(param);
                  if (constraint && isTupleType(constraint) && !(constraint.target.combinedFlags & ElementFlags.Variable)) {
                    const impliedArity = constraint.target.fixedLength;
                    inferFromTypes(sliceTupleType(source, startLength, sourceArity - (startLength + impliedArity)), elementTypes[startLength]);
                    inferFromTypes(getElementTypeOfSliceOfTupleType(source, startLength + impliedArity, endLength), elementTypes[startLength + 1]);
                  }
                } else if (elementFlags[startLength] & ElementFlags.Rest && elementFlags[startLength + 1] & ElementFlags.Variadic) {
                  const param = getInferenceInfoForType(elementTypes[startLength + 1])?.typeParameter;
                  const constraint = param && getBaseConstraintOfType(param);
                  if (constraint && isTupleType(constraint) && !(constraint.target.combinedFlags & ElementFlags.Variable)) {
                    const impliedArity = constraint.target.fixedLength;
                    const endIndex = sourceArity - getEndElementCount(target.target, ElementFlags.Fixed);
                    const startIndex = endIndex - impliedArity;
                    const trailingSlice = createTupleType(
                      getTypeArguments(source).slice(startIndex, endIndex),
                      source.target.elementFlags.slice(startIndex, endIndex),
                      /*readonly*/
                      false,
                      source.target.labeledElementDeclarations && source.target.labeledElementDeclarations.slice(startIndex, endIndex)
                    );
                    inferFromTypes(getElementTypeOfSliceOfTupleType(source, startLength, endLength + impliedArity), elementTypes[startLength]);
                    inferFromTypes(trailingSlice, elementTypes[startLength + 1]);
                  }
                }
              } else if (middleLength === 1 && elementFlags[startLength] & ElementFlags.Variadic) {
                const endsInOptional = target.target.elementFlags[targetArity - 1] & ElementFlags.Optional;
                const sourceSlice = sliceTupleType(source, startLength, endLength);
                inferWithPriority(sourceSlice, elementTypes[startLength], endsInOptional ? InferencePriority.SpeculativeTuple : 0);
              } else if (middleLength === 1 && elementFlags[startLength] & ElementFlags.Rest) {
                const restType = getElementTypeOfSliceOfTupleType(source, startLength, endLength);
                if (restType) {
                  inferFromTypes(restType, elementTypes[startLength]);
                }
              }
            }
            for (let i = 0; i < endLength; i++) {
              inferFromTypes(getTypeArguments(source)[sourceArity - i - 1], elementTypes[targetArity - i - 1]);
            }
            return;
          }
          if (isArrayType(target)) {
            inferFromIndexTypes(source, target);
            return;
          }
        }
        inferFromProperties(source, target);
        inferFromSignatures(source, target, SignatureKind.Call);
        inferFromSignatures(source, target, SignatureKind.Construct);
        inferFromIndexTypes(source, target);
      }
    }
    function inferFromProperties(source, target) {
      const properties = getPropertiesOfObjectType(target);
      for (const targetProp of properties) {
        const sourceProp = getPropertyOfType(source, targetProp.escapedName);
        if (sourceProp && !some(sourceProp.declarations, hasSkipDirectInferenceFlag)) {
          inferFromTypes(
            removeMissingType(getTypeOfSymbol(sourceProp), !!(sourceProp.flags & SymbolFlags.Optional)),
            removeMissingType(getTypeOfSymbol(targetProp), !!(targetProp.flags & SymbolFlags.Optional))
          );
        }
      }
    }
    function inferFromSignatures(source, target, kind) {
      const sourceSignatures = getSignaturesOfType(source, kind);
      const sourceLen = sourceSignatures.length;
      if (sourceLen > 0) {
        const targetSignatures = getSignaturesOfType(target, kind);
        const targetLen = targetSignatures.length;
        for (let i = 0; i < targetLen; i++) {
          const sourceIndex = Math.max(sourceLen - targetLen + i, 0);
          inferFromSignature(getBaseSignature(sourceSignatures[sourceIndex]), getErasedSignature(targetSignatures[i]));
        }
      }
    }
    function inferFromSignature(source, target) {
      if (!(source.flags & SignatureFlags.IsNonInferrable)) {
        const saveBivariant = bivariant;
        const kind = target.declaration ? target.declaration.kind : SyntaxKind.Unknown;
        bivariant = bivariant || kind === SyntaxKind.MethodDeclaration || kind === SyntaxKind.MethodSignature || kind === SyntaxKind.Constructor;
        applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes);
        bivariant = saveBivariant;
      }
      applyToReturnTypes(source, target, inferFromTypes);
    }
    function inferFromIndexTypes(source, target) {
      const priority2 = getObjectFlags(source) & getObjectFlags(target) & ObjectFlags.Mapped ? InferencePriority.HomomorphicMappedType : 0;
      const indexInfos = getIndexInfosOfType(target);
      if (isObjectTypeWithInferableIndex(source)) {
        for (const targetInfo of indexInfos) {
          const propTypes = [];
          for (const prop of getPropertiesOfType(source)) {
            if (isApplicableIndexType(getLiteralTypeFromProperty(prop, TypeFlags.StringOrNumberLiteralOrUnique), targetInfo.keyType)) {
              const propType = getTypeOfSymbol(prop);
              propTypes.push(prop.flags & SymbolFlags.Optional ? removeMissingOrUndefinedType(propType) : propType);
            }
          }
          for (const info of getIndexInfosOfType(source)) {
            if (isApplicableIndexType(info.keyType, targetInfo.keyType)) {
              propTypes.push(info.type);
            }
          }
          if (propTypes.length) {
            inferWithPriority(getUnionType(propTypes), targetInfo.type, priority2);
          }
        }
      }
      for (const targetInfo of indexInfos) {
        const sourceInfo = getApplicableIndexInfo(source, targetInfo.keyType);
        if (sourceInfo) {
          inferWithPriority(sourceInfo.type, targetInfo.type, priority2);
        }
      }
    }
  }
  function isTypeOrBaseIdenticalTo(s, t) {
    return t === missingType ? s === t : isTypeIdenticalTo(s, t) || !!(t.flags & TypeFlags.String && s.flags & TypeFlags.StringLiteral || t.flags & TypeFlags.Number && s.flags & TypeFlags.NumberLiteral);
  }
  function isTypeCloselyMatchedBy(s, t) {
    return !!(s.flags & TypeFlags.Object && t.flags & TypeFlags.Object && s.symbol && s.symbol === t.symbol || s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
  }
  function hasPrimitiveConstraint(type) {
    const constraint = getConstraintOfTypeParameter(type);
    return !!constraint && maybeTypeOfKind(constraint.flags & TypeFlags.Conditional ? getDefaultConstraintOfConditionalType(constraint) : constraint, TypeFlags.Primitive | TypeFlags.Index | TypeFlags.TemplateLiteral | TypeFlags.StringMapping);
  }
  function isObjectLiteralType(type) {
    return !!(getObjectFlags(type) & ObjectFlags.ObjectLiteral);
  }
  function isObjectOrArrayLiteralType(type) {
    return !!(getObjectFlags(type) & (ObjectFlags.ObjectLiteral | ObjectFlags.ArrayLiteral));
  }
  function unionObjectAndArrayLiteralCandidates(candidates) {
    if (candidates.length > 1) {
      const objectLiterals = filter(candidates, isObjectOrArrayLiteralType);
      if (objectLiterals.length) {
        const literalsType = getUnionType(objectLiterals, UnionReduction.Subtype);
        return concatenate(filter(candidates, (t) => !isObjectOrArrayLiteralType(t)), [literalsType]);
      }
    }
    return candidates;
  }
  function getContravariantInference(inference) {
    return inference.priority & InferencePriority.PriorityImpliesCombination ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
  }
  function getCovariantInference(inference, signature) {
    const candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
    const primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter) || isConstTypeVariable(inference.typeParameter);
    const widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevelInReturnType(signature, inference.typeParameter));
    const baseCandidates = primitiveConstraint ? sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? sameMap(candidates, getWidenedLiteralType) : candidates;
    const unwidenedType = inference.priority & InferencePriority.PriorityImpliesCombination ? getUnionType(baseCandidates, UnionReduction.Subtype) : getCommonSupertype(baseCandidates);
    return getWidenedType(unwidenedType);
  }
  function getInferredType(context, index) {
    const inference = context.inferences[index];
    if (!inference.inferredType) {
      let inferredType;
      let fallbackType;
      if (context.signature) {
        const inferredCovariantType = inference.candidates ? getCovariantInference(inference, context.signature) : void 0;
        const inferredContravariantType = inference.contraCandidates ? getContravariantInference(inference) : void 0;
        if (inferredCovariantType || inferredContravariantType) {
          const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & (TypeFlags.Never | TypeFlags.Any)) && some(inference.contraCandidates, (t) => isTypeAssignableTo(inferredCovariantType, t)) && every(context.inferences, (other) => other !== inference && getConstraintOfTypeParameter(other.typeParameter) !== inference.typeParameter || every(other.candidates, (t) => isTypeAssignableTo(t, inferredCovariantType))));
          inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType;
          fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType;
        } else if (context.flags & InferenceFlags.NoDefault) {
          inferredType = silentNeverType;
        } else {
          const defaultType = getDefaultFromTypeParameter(inference.typeParameter);
          if (defaultType) {
            inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
          }
        }
      } else {
        inferredType = getTypeFromInference(inference);
      }
      inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & InferenceFlags.AnyDefault));
      const constraint = getConstraintOfTypeParameter(inference.typeParameter);
      if (constraint) {
        const instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
        if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
          inference.inferredType = fallbackType && context.compareTypes(fallbackType, getTypeWithThisArgument(instantiatedConstraint, fallbackType)) ? fallbackType : instantiatedConstraint;
        }
      }
    }
    return inference.inferredType;
  }
  function getDefaultTypeArgumentType(isInJavaScriptFile) {
    return isInJavaScriptFile ? anyType : unknownType;
  }
  function getInferredTypes(context) {
    const result = [];
    for (let i = 0; i < context.inferences.length; i++) {
      result.push(getInferredType(context, i));
    }
    return result;
  }
  function getCannotFindNameDiagnosticForName(node) {
    switch (node.escapedText) {
      case "document":
      case "console":
        return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
      case "$":
        return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery;
      case "describe":
      case "suite":
      case "it":
      case "test":
        return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha;
      case "process":
      case "require":
      case "Buffer":
      case "module":
        return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode;
      case "Bun":
        return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_and_then_add_bun_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun;
      case "Map":
      case "Set":
      case "Promise":
      case "Symbol":
      case "WeakMap":
      case "WeakSet":
      case "Iterator":
      case "AsyncIterator":
      case "SharedArrayBuffer":
      case "Atomics":
      case "AsyncIterable":
      case "AsyncIterableIterator":
      case "AsyncGenerator":
      case "AsyncGeneratorFunction":
      case "BigInt":
      case "Reflect":
      case "BigInt64Array":
      case "BigUint64Array":
        return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later;
      case "await":
        if (isCallExpression(node.parent)) {
          return Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function;
        }
      // falls through
      default:
        if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) {
          return Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
        } else {
          return Diagnostics.Cannot_find_name_0;
        }
    }
  }
  function getResolvedSymbol(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedSymbol) {
      links.resolvedSymbol = !nodeIsMissing(node) && resolveName(
        node,
        node,
        SymbolFlags.Value | SymbolFlags.ExportValue,
        getCannotFindNameDiagnosticForName(node),
        !isWriteOnlyAccess(node),
        /*excludeGlobals*/
        false
      ) || unknownSymbol;
    }
    return links.resolvedSymbol;
  }
  function isInAmbientOrTypeNode(node) {
    return !!(node.flags & NodeFlags.Ambient || findAncestor(node, (n) => isInterfaceDeclaration(n) || isTypeAliasDeclaration(n) || isTypeLiteralNode(n)));
  }
  function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
    switch (node.kind) {
      case SyntaxKind.Identifier:
        if (!isThisInTypeQuery(node)) {
          const symbol = getResolvedSymbol(node);
          return symbol !== unknownSymbol ? `${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}|${getSymbolId(symbol)}` : void 0;
        }
      // falls through
      case SyntaxKind.ThisKeyword:
        return `0|${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}`;
      case SyntaxKind.NonNullExpression:
      case SyntaxKind.ParenthesizedExpression:
        return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
      case SyntaxKind.QualifiedName:
        const left = getFlowCacheKey(node.left, declaredType, initialType, flowContainer);
        return left && `${left}.${node.right.escapedText}`;
      case SyntaxKind.PropertyAccessExpression:
      case SyntaxKind.ElementAccessExpression:
        const propName = getAccessedPropertyName(node);
        if (propName !== void 0) {
          const key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
          return key && `${key}.${propName}`;
        }
        if (isElementAccessExpression(node) && isIdentifier(node.argumentExpression)) {
          const symbol = getResolvedSymbol(node.argumentExpression);
          if (isConstantVariable(symbol) || isParameterOrMutableLocalVariable(symbol) && !isSymbolAssigned(symbol)) {
            const key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
            return key && `${key}.@${getSymbolId(symbol)}`;
          }
        }
        break;
      case SyntaxKind.ObjectBindingPattern:
      case SyntaxKind.ArrayBindingPattern:
      case SyntaxKind.FunctionDeclaration:
      case SyntaxKind.FunctionExpression:
      case SyntaxKind.ArrowFunction:
      case SyntaxKind.MethodDeclaration:
        return `${getNodeId(node)}#${getTypeId(declaredType)}`;
    }
    return void 0;
  }
  function isMatchingReference(source, target) {
    switch (target.kind) {
      case SyntaxKind.ParenthesizedExpression:
      case SyntaxKind.NonNullExpression:
        return isMatchingReference(source, target.expression);
      case SyntaxKind.BinaryExpression:
        return isAssignmentExpression(target) && isMatchingReference(source, target.left) || isBinaryExpression(target) && target.operatorToken.kind === SyntaxKind.CommaToken && isMatchingReference(source, target.right);
    }
    switch (source.kind) {
      case SyntaxKind.MetaProperty:
        return target.kind === SyntaxKind.MetaProperty && source.keywordToken === target.keywordToken && source.name.escapedText === target.name.escapedText;
      case SyntaxKind.Identifier:
      case SyntaxKind.PrivateIdentifier:
        return isThisInTypeQuery(source) ? target.kind === SyntaxKind.ThisKeyword : target.kind === SyntaxKind.Identifier && getResolvedSymbol(source) === getResolvedSymbol(target) || (isVariableDeclaration(target) || isBindingElement(target)) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfDeclaration(target);
      case SyntaxKind.ThisKeyword:
        return target.kind === SyntaxKind.ThisKeyword;
      case SyntaxKind.SuperKeyword:
        return target.kind === SyntaxKind.SuperKeyword;
      case SyntaxKind.NonNullExpression:
      case SyntaxKind.ParenthesizedExpression:
        return isMatchingReference(source.expression, target);
      case SyntaxKind.PropertyAccessExpression:
      case SyntaxKind.ElementAccessExpression:
        const sourcePropertyName = getAccessedPropertyName(source);
        if (sourcePropertyName !== void 0) {
          const targetPropertyName = isAccessExpression(target) ? getAccessedPropertyName(target) : void 0;
          if (targetPropertyName !== void 0) {
            return targetPropertyName === sourcePropertyName && isMatchingReference(source.expression, target.expression);
          }
        }
        if (isElementAccessExpression(source) && isElementAccessExpression(target) && isIdentifier(source.argumentExpression) && isIdentifier(target.argumentExpression)) {
          const symbol = getResolvedSymbol(source.argumentExpression);
          if (symbol === getResolvedSymbol(target.argumentExpression) && (isConstantVariable(symbol) || isParameterOrMutableLocalVariable(symbol) && !isSymbolAssigned(symbol))) {
            return isMatchingReference(source.expression, target.expression);
          }
        }
        break;
      case SyntaxKind.QualifiedName:
        return isAccessExpression(target) && source.right.escapedText === getAccessedPropertyName(target) && isMatchingReference(source.left, target.expression);
      case SyntaxKind.BinaryExpression:
        return isBinaryExpression(source) && source.operatorToken.kind === SyntaxKind.CommaToken && isMatchingReference(source.right, target);
    }
    return false;
  }
  function getAccessedPropertyName(access) {
    if (isPropertyAccessExpression(access)) {
      return access.name.escapedText;
    }
    if (isElementAccessExpression(access)) {
      return tryGetElementAccessExpressionName(access);
    }
    if (isBindingElement(access)) {
      const name = getDestructuringPropertyName(access);
      return name ? escapeLeadingUnderscores(name) : void 0;
    }
    if (isParameter(access)) {
      return "" + access.parent.parameters.indexOf(access);
    }
    return void 0;
  }
  function tryGetNameFromType(type) {
    return type.flags & TypeFlags.UniqueESSymbol ? type.escapedName : type.flags & TypeFlags.StringOrNumberLiteral ? escapeLeadingUnderscores("" + type.value) : void 0;
  }
  function tryGetElementAccessExpressionName(node) {
    return isStringOrNumericLiteralLike(node.argumentExpression) ? escapeLeadingUnderscores(node.argumentExpression.text) : isEntityNameExpression(node.argumentExpression) ? tryGetNameFromEntityNameExpression(node.argumentExpression) : void 0;
  }
  function tryGetNameFromEntityNameExpression(node) {
    const symbol = resolveEntityName(
      node,
      SymbolFlags.Value,
      /*ignoreErrors*/
      true
    );
    if (!symbol || !(isConstantVariable(symbol) || symbol.flags & SymbolFlags.EnumMember)) return void 0;
    const declaration = symbol.valueDeclaration;
    if (declaration === void 0) return void 0;
    const type = tryGetTypeFromEffectiveTypeNode(declaration);
    if (type) {
      const name = tryGetNameFromType(type);
      if (name !== void 0) {
        return name;
      }
    }
    if (hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node)) {
      const initializer = getEffectiveInitializer(declaration);
      if (initializer) {
        const initializerType = isBindingPattern(declaration.parent) ? getTypeForBindingElement(declaration) : getTypeOfExpression(initializer);
        return initializerType && tryGetNameFromType(initializerType);
      }
      if (isEnumMember(declaration)) {
        return getTextOfPropertyName(declaration.name);
      }
    }
    return void 0;
  }
  function containsMatchingReference(source, target) {
    while (isAccessExpression(source)) {
      source = source.expression;
      if (isMatchingReference(source, target)) {
        return true;
      }
    }
    return false;
  }
  function optionalChainContainsReference(source, target) {
    while (isOptionalChain(source)) {
      source = source.expression;
      if (isMatchingReference(source, target)) {
        return true;
      }
    }
    return false;
  }
  function isDiscriminantProperty(type, name) {
    if (type && type.flags & TypeFlags.Union) {
      const prop = getUnionOrIntersectionProperty(type, name);
      if (prop && getCheckFlags(prop) & CheckFlags.SyntheticProperty) {
        if (prop.links.isDiscriminantProperty === void 0) {
          prop.links.isDiscriminantProperty = (prop.links.checkFlags & CheckFlags.Discriminant) === CheckFlags.Discriminant && !isGenericType(getTypeOfSymbol(prop));
        }
        return !!prop.links.isDiscriminantProperty;
      }
    }
    return false;
  }
  function findDiscriminantProperties(sourceProperties, target) {
    let result;
    for (const sourceProperty of sourceProperties) {
      if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
        if (result) {
          result.push(sourceProperty);
          continue;
        }
        result = [sourceProperty];
      }
    }
    return result;
  }
  function mapTypesByKeyProperty(types, name) {
    const map2 = /* @__PURE__ */ new Map();
    let count = 0;
    for (const type of types) {
      if (type.flags & (TypeFlags.Object | TypeFlags.Intersection | TypeFlags.InstantiableNonPrimitive)) {
        const discriminant = getTypeOfPropertyOfType(type, name);
        if (discriminant) {
          if (!isLiteralType(discriminant)) {
            return void 0;
          }
          let duplicate = false;
          forEachType(discriminant, (t) => {
            const id = getTypeId(getRegularTypeOfLiteralType(t));
            const existing = map2.get(id);
            if (!existing) {
              map2.set(id, type);
            } else if (existing !== unknownType) {
              map2.set(id, unknownType);
              duplicate = true;
            }
          });
          if (!duplicate) count++;
        }
      }
    }
    return count >= 10 && count * 2 >= types.length ? map2 : void 0;
  }
  function getKeyPropertyName(unionType) {
    const types = unionType.types;
    if (types.length < 10 || getObjectFlags(unionType) & ObjectFlags.PrimitiveUnion || countWhere(types, (t) => !!(t.flags & (TypeFlags.Object | TypeFlags.InstantiableNonPrimitive))) < 10) {
      return void 0;
    }
    if (unionType.keyPropertyName === void 0) {
      const keyPropertyName = forEach(types, (t) => t.flags & (TypeFlags.Object | TypeFlags.InstantiableNonPrimitive) ? forEach(getPropertiesOfType(t), (p) => isUnitType(getTypeOfSymbol(p)) ? p.escapedName : void 0) : void 0);
      const mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName);
      unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : "";
      unionType.constituentMap = mapByKeyProperty;
    }
    return unionType.keyPropertyName.length ? unionType.keyPropertyName : void 0;
  }
  function getConstituentTypeForKeyType(unionType, keyType) {
    const result = unionType.constituentMap?.get(getTypeId(getRegularTypeOfLiteralType(keyType)));
    return result !== unknownType ? result : void 0;
  }
  function getMatchingUnionConstituentForType(unionType, type) {
    const keyPropertyName = getKeyPropertyName(unionType);
    const propType = keyPropertyName && getTypeOfPropertyOfType(type, keyPropertyName);
    return propType && getConstituentTypeForKeyType(unionType, propType);
  }
  function getMatchingUnionConstituentForObjectLiteral(unionType, node) {
    const keyPropertyName = getKeyPropertyName(unionType);
    const propNode = keyPropertyName && find(node.properties, (p) => p.symbol && p.kind === SyntaxKind.PropertyAssignment && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer));
    const propType = propNode && getContextFreeTypeOfExpression(propNode.initializer);
    return propType && getConstituentTypeForKeyType(unionType, propType);
  }
  function isOrContainsMatchingReference(source, target) {
    return isMatchingReference(source, target) || containsMatchingReference(source, target);
  }
  function hasMatchingArgument(expression, reference) {
    if (expression.arguments) {
      for (const argument of expression.arguments) {
        if (isOrContainsMatchingReference(reference, argument) || optionalChainContainsReference(argument, reference)) {
          return true;
        }
      }
    }
    if (expression.expression.kind === SyntaxKind.PropertyAccessExpression && isOrContainsMatchingReference(reference, expression.expression.expression)) {
      return true;
    }
    return false;
  }
  function getFlowNodeId(flow) {
    if (flow.id <= 0) {
      flow.id = nextFlowId;
      nextFlowId++;
    }
    return flow.id;
  }
  function typeMaybeAssignableTo(source, target) {
    if (!(source.flags & TypeFlags.Union)) {
      return isTypeAssignableTo(source, target);
    }
    for (const t of source.types) {
      if (isTypeAssignableTo(t, target)) {
        return true;
      }
    }
    return false;
  }
  function getAssignmentReducedType(declaredType, assignedType) {
    if (declaredType === assignedType) {
      return declaredType;
    }
    if (assignedType.flags & TypeFlags.Never) {
      return assignedType;
    }
    const key = `A${getTypeId(declaredType)},${getTypeId(assignedType)}`;
    return getCachedType(key) ?? setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType));
  }
  function getAssignmentReducedTypeWorker(declaredType, assignedType) {
    const filteredType = filterType(declaredType, (t) => typeMaybeAssignableTo(assignedType, t));
    const reducedType = assignedType.flags & TypeFlags.BooleanLiteral && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType;
    return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType;
  }
  function isFunctionObjectType(type) {
    if (getObjectFlags(type) & ObjectFlags.EvolvingArray) {
      return false;
    }
    const resolved = resolveStructuredTypeMembers(type);
    return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
  }
  function getTypeFacts(type, mask) {
    return getTypeFactsWorker(type, mask) & mask;
  }
  function hasTypeFacts(type, mask) {
    return getTypeFacts(type, mask) !== 0;
  }
  function getTypeFactsWorker(type, callerOnlyNeeds) {
    if (type.flags & (TypeFlags.Intersection | TypeFlags.Instantiable)) {
      type = getBaseConstraintOfType(type) || unknownType;
    }
    const flags = type.flags;
    if (flags & (TypeFlags.String | TypeFlags.StringMapping)) {
      return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
    }
    if (flags & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral)) {
      const isEmpty = flags & TypeFlags.StringLiteral && type.value === "";
      return strictNullChecks ? isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
    }
    if (flags & (TypeFlags.Number | TypeFlags.Enum)) {
      return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
    }
    if (flags & TypeFlags.NumberLiteral) {
      const isZero = type.value === 0;
      return strictNullChecks ? isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
    }
    if (flags & TypeFlags.BigInt) {
      return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
    }
    if (flags & TypeFlags.BigIntLiteral) {
      const isZero = isZeroBigInt(type);
      return strictNullChecks ? isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
    }
    if (flags & TypeFlags.Boolean) {
      return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
    }
    if (flags & TypeFlags.BooleanLike) {
      return strictNullChecks ? type === falseType || type === regularFalseType ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : type === falseType || type === regularFalseType ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
    }
    if (flags & TypeFlags.Object) {
      const possibleFacts = strictNullChecks ? 83427327 /* EmptyObjectStrictFacts */ | 7880640 /* FunctionStrictFacts */ | 7888800 /* ObjectStrictFacts */ : 83886079 /* EmptyObjectFacts */ | 16728e3 /* FunctionFacts */ | 16736160 /* ObjectFacts */;
      if ((callerOnlyNeeds & possibleFacts) === 0) {
        return 0;
      }
      return getObjectFlags(type) & ObjectFlags.Anonymous && isEmptyObjectType(type) ? strictNullChecks ? 83427327 /* EmptyObjectStrictFacts */ : 83886079 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728e3 /* FunctionFacts */ : strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
    }
    if (flags & TypeFlags.Void) {
      return 9830144 /* VoidFacts */;
    }
    if (flags & TypeFlags.Undefined) {
      return 26607360 /* UndefinedFacts */;
    }
    if (flags & TypeFlags.Null) {
      return 42917664 /* NullFacts */;
    }
    if (flags & TypeFlags.ESSymbolLike) {
      return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
    }
    if (flags & TypeFlags.NonPrimitive) {
      return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
    }
    if (flags & TypeFlags.Never) {
      return 0 /* None */;
    }
    if (flags & TypeFlags.Union) {
      return reduceLeft(type.types, (facts, t) => facts | getTypeFactsWorker(t, callerOnlyNeeds), 0 /* None */);
    }
    if (flags & TypeFlags.Intersection) {
      return getIntersectionTypeFacts(type, callerOnlyNeeds);
    }
    return 83886079 /* UnknownFacts */;
  }
  function getIntersectionTypeFacts(type, callerOnlyNeeds) {
    const ignoreObjects = maybeTypeOfKind(type, TypeFlags.Primitive);
    let oredFacts = 0 /* None */;
    let andedFacts = 134217727 /* All */;
    for (const t of type.types) {
      if (!(ignoreObjects && t.flags & TypeFlags.Object)) {
        const f = getTypeFactsWorker(t, callerOnlyNeeds);
        oredFacts |= f;
        andedFacts &= f;
      }
    }
    return oredFacts & 8256 /* OrFactsMask */ | andedFacts & 134209471 /* AndFactsMask */;
  }
  function getTypeWithFacts(type, include) {
    return filterType(type, (t) => hasTypeFacts(t, include));
  }
  function getAdjustedTypeWithFacts(type, facts) {
    const reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & TypeFlags.Unknown ? unknownUnionType : type, facts));
    if (strictNullChecks) {
      switch (facts) {
        case 524288 /* NEUndefined */:
          return removeNullableByIntersection(reduced, 65536 /* EQUndefined */, 131072 /* EQNull */, 33554432 /* IsNull */, nullType);
        case 1048576 /* NENull */:
          return removeNullableByIntersection(reduced, 131072 /* EQNull */, 65536 /* EQUndefined */, 16777216 /* IsUndefined */, undefinedType);
        case 2097152 /* NEUndefinedOrNull */:
        case 4194304 /* Truthy */:
          return mapType(reduced, (t) => hasTypeFacts(t, 262144 /* EQUndefinedOrNull */) ? getGlobalNonNullableTypeInstantiation(t) : t);
      }
    }
    return reduced;
  }
  function removeNullableByIntersection(type, targetFacts, otherFacts, otherIncludesFacts, otherType) {
    const facts = getTypeFacts(type, 65536 /* EQUndefined */ | 131072 /* EQNull */ | 16777216 /* IsUndefined */ | 33554432 /* IsNull */);
    if (!(facts & targetFacts)) {
      return type;
    }
    const emptyAndOtherUnion = getUnionType([emptyObjectType, otherType]);
    return mapType(type, (t) => hasTypeFacts(t, targetFacts) ? getIntersectionType([t, !(facts & otherIncludesFacts) && hasTypeFacts(t, otherFacts) ? emptyAndOtherUnion : emptyObjectType]) : t);
  }
  function recombineUnknownType(type) {
    return type === unknownUnionType ? unknownType : type;
  }
  function getTypeWithDefault(type, defaultExpression) {
    return defaultExpression ? getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : type;
  }
  function getTypeOfDestructuredProperty(type, name) {
    const nameType = getLiteralTypeFromPropertyName(name);
    if (!isTypeUsableAsPropertyName(nameType)) return errorType;
    const text = getPropertyNameFromType(nameType);
    return getTypeOfPropertyOfType(type, text) || includeUndefinedInIndexSignature(getApplicableIndexInfoForName(type, text)?.type) || errorType;
  }
  function getTypeOfDestructuredArrayElement(type, index) {
    return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || includeUndefinedInIndexSignature(checkIteratedTypeOrElementType(
      65 /* Destructuring */,
      type,
      undefinedType,
      /*errorNode*/
      void 0
    )) || errorType;
  }
  function includeUndefinedInIndexSignature(type) {
    if (!type) return type;
    return compilerOptions.noUncheckedIndexedAccess ? getUnionType([type, missingType]) : type;
  }
  function getTypeOfDestructuredSpreadExpression(type) {
    return createArrayType(checkIteratedTypeOrElementType(
      65 /* Destructuring */,
      type,
      undefinedType,
      /*errorNode*/
      void 0
    ) || errorType);
  }
  function getAssignedTypeOfBinaryExpression(node) {
    const isDestructuringDefaultAssignment = node.parent.kind === SyntaxKind.ArrayLiteralExpression && isDestructuringAssignmentTarget(node.parent) || node.parent.kind === SyntaxKind.PropertyAssignment && isDestructuringAssignmentTarget(node.parent.parent);
    return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right);
  }
  function isDestructuringAssignmentTarget(parent) {
    return parent.parent.kind === SyntaxKind.BinaryExpression && parent.parent.left === parent || parent.parent.kind === SyntaxKind.ForOfStatement && parent.parent.initializer === parent;
  }
  function getAssignedTypeOfArrayLiteralElement(node, element) {
    return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
  }
  function getAssignedTypeOfSpreadExpression(node) {
    return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
  }
  function getAssignedTypeOfPropertyAssignment(node) {
    return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
  }
  function getAssignedTypeOfShorthandPropertyAssignment(node) {
    return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
  }
  function getAssignedType(node) {
    const { parent } = node;
    switch (parent.kind) {
      case SyntaxKind.ForInStatement:
        return stringType;
      case SyntaxKind.ForOfStatement:
        return checkRightHandSideOfForOf(parent) || errorType;
      case SyntaxKind.BinaryExpression:
        return getAssignedTypeOfBinaryExpression(parent);
      case SyntaxKind.DeleteExpression:
        return undefinedType;
      case SyntaxKind.ArrayLiteralExpression:
        return getAssignedTypeOfArrayLiteralElement(parent, node);
      case SyntaxKind.SpreadElement:
        return getAssignedTypeOfSpreadExpression(parent);
      case SyntaxKind.PropertyAssignment:
        return getAssignedTypeOfPropertyAssignment(parent);
      case SyntaxKind.ShorthandPropertyAssignment:
        return getAssignedTypeOfShorthandPropertyAssignment(parent);
    }
    return errorType;
  }
  function getInitialTypeOfBindingElement(node) {
    const pattern = node.parent;
    const parentType = getInitialType(pattern.parent);
    const type = pattern.kind === SyntaxKind.ObjectBindingPattern ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType);
    return getTypeWithDefault(type, node.initializer);
  }
  function getTypeOfInitializer(node) {
    const links = getNodeLinks(node);
    return links.resolvedType || getTypeOfExpression(node);
  }
  function getInitialTypeOfVariableDeclaration(node) {
    if (node.initializer) {
      return getTypeOfInitializer(node.initializer);
    }
    if (node.parent.parent.kind === SyntaxKind.ForInStatement) {
      return stringType;
    }
    if (node.parent.parent.kind === SyntaxKind.ForOfStatement) {
      return checkRightHandSideOfForOf(node.parent.parent) || errorType;
    }
    return errorType;
  }
  function getInitialType(node) {
    return node.kind === SyntaxKind.VariableDeclaration ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node);
  }
  function isEmptyArrayAssignment(node) {
    return node.kind === SyntaxKind.VariableDeclaration && node.initializer && isEmptyArrayLiteral(node.initializer) || node.kind !== SyntaxKind.BindingElement && node.parent.kind === SyntaxKind.BinaryExpression && isEmptyArrayLiteral(node.parent.right);
  }
  function getReferenceCandidate(node) {
    switch (node.kind) {
      case SyntaxKind.ParenthesizedExpression:
        return getReferenceCandidate(node.expression);
      case SyntaxKind.BinaryExpression:
        switch (node.operatorToken.kind) {
          case SyntaxKind.EqualsToken:
          case SyntaxKind.BarBarEqualsToken:
          case SyntaxKind.AmpersandAmpersandEqualsToken:
          case SyntaxKind.QuestionQuestionEqualsToken:
            return getReferenceCandidate(node.left);
          case SyntaxKind.CommaToken:
            return getReferenceCandidate(node.right);
        }
    }
    return node;
  }
  function getReferenceRoot(node) {
    const { parent } = node;
    return parent.kind === SyntaxKind.ParenthesizedExpression || parent.kind === SyntaxKind.BinaryExpression && parent.operatorToken.kind === SyntaxKind.EqualsToken && parent.left === node || parent.kind === SyntaxKind.BinaryExpression && parent.operatorToken.kind === SyntaxKind.CommaToken && parent.right === node ? getReferenceRoot(parent) : node;
  }
  function getTypeOfSwitchClause(clause) {
    if (clause.kind === SyntaxKind.CaseClause) {
      return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
    }
    return neverType;
  }
  function getSwitchClauseTypes(switchStatement) {
    const links = getNodeLinks(switchStatement);
    if (!links.switchTypes) {
      links.switchTypes = [];
      for (const clause of switchStatement.caseBlock.clauses) {
        links.switchTypes.push(getTypeOfSwitchClause(clause));
      }
    }
    return links.switchTypes;
  }
  function getSwitchClauseTypeOfWitnesses(switchStatement) {
    if (some(switchStatement.caseBlock.clauses, (clause) => clause.kind === SyntaxKind.CaseClause && !isStringLiteralLike(clause.expression))) {
      return void 0;
    }
    const witnesses = [];
    for (const clause of switchStatement.caseBlock.clauses) {
      const text = clause.kind === SyntaxKind.CaseClause ? clause.expression.text : void 0;
      witnesses.push(text && !contains(witnesses, text) ? text : void 0);
    }
    return witnesses;
  }
  function eachTypeContainedIn(source, types) {
    return source.flags & TypeFlags.Union ? !forEach(source.types, (t) => !contains(types, t)) : contains(types, source);
  }
  function isTypeSubsetOf(source, target) {
    return !!(source === target || source.flags & TypeFlags.Never || target.flags & TypeFlags.Union && isTypeSubsetOfUnion(source, target));
  }
  function isTypeSubsetOfUnion(source, target) {
    if (source.flags & TypeFlags.Union) {
      for (const t of source.types) {
        if (!containsType(target.types, t)) {
          return false;
        }
      }
      return true;
    }
    if (source.flags & TypeFlags.EnumLike && getBaseTypeOfEnumLikeType(source) === target) {
      return true;
    }
    return containsType(target.types, source);
  }
  function forEachType(type, f) {
    return type.flags & TypeFlags.Union ? forEach(type.types, f) : f(type);
  }
  function someType(type, f) {
    return type.flags & TypeFlags.Union ? some(type.types, f) : f(type);
  }
  function everyType(type, f) {
    return type.flags & TypeFlags.Union ? every(type.types, f) : f(type);
  }
  function everyContainedType(type, f) {
    return type.flags & TypeFlags.UnionOrIntersection ? every(type.types, f) : f(type);
  }
  function filterType(type, f) {
    if (type.flags & TypeFlags.Union) {
      const types = type.types;
      const filtered = filter(types, f);
      if (filtered === types) {
        return type;
      }
      const origin = type.origin;
      let newOrigin;
      if (origin && origin.flags & TypeFlags.Union) {
        const originTypes = origin.types;
        const originFiltered = filter(originTypes, (t) => !!(t.flags & TypeFlags.Union) || f(t));
        if (originTypes.length - originFiltered.length === types.length - filtered.length) {
          if (originFiltered.length === 1) {
            return originFiltered[0];
          }
          newOrigin = createOriginUnionOrIntersectionType(TypeFlags.Union, originFiltered);
        }
      }
      return getUnionTypeFromSortedList(
        filtered,
        type.objectFlags & (ObjectFlags.PrimitiveUnion | ObjectFlags.ContainsIntersections),
        /*aliasSymbol*/
        void 0,
        /*aliasTypeArguments*/
        void 0,
        newOrigin
      );
    }
    return type.flags & TypeFlags.Never || f(type) ? type : neverType;
  }
  function removeType(type, targetType) {
    return filterType(type, (t) => t !== targetType);
  }
  function countTypes(type) {
    return type.flags & TypeFlags.Union ? type.types.length : 1;
  }
  function mapType(type, mapper, noReductions) {
    if (type.flags & TypeFlags.Never) {
      return type;
    }
    if (!(type.flags & TypeFlags.Union)) {
      return mapper(type);
    }
    const origin = type.origin;
    const types = origin && origin.flags & TypeFlags.Union ? origin.types : type.types;
    let mappedTypes;
    let changed = false;
    for (const t of types) {
      const mapped = t.flags & TypeFlags.Union ? mapType(t, mapper, noReductions) : mapper(t);
      changed ||= t !== mapped;
      if (mapped) {
        if (!mappedTypes) {
          mappedTypes = [mapped];
        } else {
          mappedTypes.push(mapped);
        }
      }
    }
    return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? UnionReduction.None : UnionReduction.Literal) : type;
  }
  function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) {
    return type.flags & TypeFlags.Union && aliasSymbol ? getUnionType(map(type.types, mapper), UnionReduction.Literal, aliasSymbol, aliasTypeArguments) : mapType(type, mapper);
  }
  function extractTypesOfKind(type, kind) {
    return filterType(type, (t) => (t.flags & kind) !== 0);
  }
  function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
    if (maybeTypeOfKind(typeWithPrimitives, TypeFlags.String | TypeFlags.TemplateLiteral | TypeFlags.Number | TypeFlags.BigInt) && maybeTypeOfKind(typeWithLiterals, TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping | TypeFlags.NumberLiteral | TypeFlags.BigIntLiteral)) {
      return mapType(typeWithPrimitives, (t) => t.flags & TypeFlags.String ? extractTypesOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) : isPatternLiteralType(t) && !maybeTypeOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) ? extractTypesOfKind(typeWithLiterals, TypeFlags.StringLiteral) : t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) : t.flags & TypeFlags.BigInt ? extractTypesOfKind(typeWithLiterals, TypeFlags.BigInt | TypeFlags.BigIntLiteral) : t);
    }
    return typeWithPrimitives;
  }
  function isIncomplete(flowType) {
    return flowType.flags === 0;
  }
  function getTypeFromFlowType(flowType) {
    return flowType.flags === 0 ? flowType.type : flowType;
  }
  function createFlowType(type, incomplete) {
    return incomplete ? { flags: 0, type: type.flags & TypeFlags.Never ? silentNeverType : type } : type;
  }
  function createEvolvingArrayType(elementType) {
    const result = createObjectType(ObjectFlags.EvolvingArray);
    result.elementType = elementType;
    return result;
  }
  function getEvolvingArrayType(elementType) {
    return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
  }
  function addEvolvingArrayElementType(evolvingArrayType, node) {
    const elementType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)));
    return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
  }
  function createFinalArrayType(elementType) {
    return elementType.flags & TypeFlags.Never ? autoArrayType : createArrayType(
      elementType.flags & TypeFlags.Union ? getUnionType(elementType.types, UnionReduction.Subtype) : elementType
    );
  }
  function getFinalArrayType(evolvingArrayType) {
    return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
  }
  function finalizeEvolvingArrayType(type) {
    return getObjectFlags(type) & ObjectFlags.EvolvingArray ? getFinalArrayType(type) : type;
  }
  function getElementTypeOfEvolvingArrayType(type) {
    return getObjectFlags(type) & ObjectFlags.EvolvingArray ? type.elementType : neverType;
  }
  function isEvolvingArrayTypeList(types) {
    let hasEvolvingArrayType = false;
    for (const t of types) {
      if (!(t.flags & TypeFlags.Never)) {
        if (!(getObjectFlags(t) & ObjectFlags.EvolvingArray)) {
          return false;
        }
        hasEvolvingArrayType = true;
      }
    }
    return hasEvolvingArrayType;
  }
  function isEvolvingArrayOperationTarget(node) {
    const root = getReferenceRoot(node);
    const parent = root.parent;
    const isLengthPushOrUnshift = isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" || parent.parent.kind === SyntaxKind.CallExpression && isIdentifier(parent.name) && isPushOrUnshiftIdentifier(parent.name));
    const isElementAssignment = parent.kind === SyntaxKind.ElementAccessExpression && parent.expression === root && parent.parent.kind === SyntaxKind.BinaryExpression && parent.parent.operatorToken.kind === SyntaxKind.EqualsToken && parent.parent.left === parent && !isAssignmentTarget(parent.parent) && isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), TypeFlags.NumberLike);
    return isLengthPushOrUnshift || isElementAssignment;
  }
  function isDeclarationWithExplicitTypeAnnotation(node) {
    return (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isParameter(node)) && !!(getEffectiveTypeAnnotationNode(node) || isInJSFile(node) && hasInitializer(node) && node.initializer && isFunctionExpressionOrArrowFunction(node.initializer) && getEffectiveReturnTypeNode(node.initializer));
  }
  function getExplicitTypeOfSymbol(symbol, diagnostic) {
    symbol = resolveSymbol(symbol);
    if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.ValueModule)) {
      return getTypeOfSymbol(symbol);
    }
    if (symbol.flags & (SymbolFlags.Variable | SymbolFlags.Property)) {
      if (getCheckFlags(symbol) & CheckFlags.Mapped) {
        const origin = symbol.links.syntheticOrigin;
        if (origin && getExplicitTypeOfSymbol(origin)) {
          return getTypeOfSymbol(symbol);
        }
      }
      const declaration = symbol.valueDeclaration;
      if (declaration) {
        if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
          return getTypeOfSymbol(symbol);
        }
        if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === SyntaxKind.ForOfStatement) {
          const statement = declaration.parent.parent;
          const expressionType = getTypeOfDottedName(
            statement.expression,
            /*diagnostic*/
            void 0
          );
          if (expressionType) {
            const use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
            return checkIteratedTypeOrElementType(
              use,
              expressionType,
              undefinedType,
              /*errorNode*/
              void 0
            );
          }
        }
        if (diagnostic) {
          addRelatedInfo(diagnostic, createDiagnosticForNode(declaration, Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
        }
      }
    }
  }
  function getTypeOfDottedName(node, diagnostic) {
    if (!(node.flags & NodeFlags.InWithStatement)) {
      switch (node.kind) {
        case SyntaxKind.Identifier:
          const symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
          return getExplicitTypeOfSymbol(symbol, diagnostic);
        case SyntaxKind.ThisKeyword:
          return getExplicitThisType(node);
        case SyntaxKind.SuperKeyword:
          return checkSuperExpression(node);
        case SyntaxKind.PropertyAccessExpression: {
          const type = getTypeOfDottedName(node.expression, diagnostic);
          if (type) {
            const name = node.name;
            let prop;
            if (isPrivateIdentifier(name)) {
              if (!type.symbol) {
                return void 0;
              }
              prop = getPropertyOfType(type, getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText));
            } else {
              prop = getPropertyOfType(type, name.escapedText);
            }
            return prop && getExplicitTypeOfSymbol(prop, diagnostic);
          }
          return void 0;
        }
        case SyntaxKind.ParenthesizedExpression:
          return getTypeOfDottedName(node.expression, diagnostic);
      }
    }
  }
  function getEffectsSignature(node) {
    const links = getNodeLinks(node);
    let signature = links.effectsSignature;
    if (signature === void 0) {
      let funcType;
      if (isBinaryExpression(node)) {
        const rightType = checkNonNullExpression(node.right);
        funcType = getSymbolHasInstanceMethodOfObjectType(rightType);
      } else if (node.parent.kind === SyntaxKind.ExpressionStatement) {
        funcType = getTypeOfDottedName(
          node.expression,
          /*diagnostic*/
          void 0
        );
      } else if (node.expression.kind !== SyntaxKind.SuperKeyword) {
        if (isOptionalChain(node)) {
          funcType = checkNonNullType(
            getOptionalExpressionType(checkExpression(node.expression), node.expression),
            node.expression
          );
        } else {
          funcType = checkNonNullExpression(node.expression);
        }
      }
      const signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, SignatureKind.Call);
      const candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : void 0;
      signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
    }
    return signature === unknownSignature ? void 0 : signature;
  }
  function hasTypePredicateOrNeverReturnType(signature) {
    return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & TypeFlags.Never);
  }
  function getTypePredicateArgument(predicate, callExpression) {
    if (predicate.kind === TypePredicateKind.Identifier || predicate.kind === TypePredicateKind.AssertsIdentifier) {
      return callExpression.arguments[predicate.parameterIndex];
    }
    const invokedExpression = skipParentheses(callExpression.expression);
    return isAccessExpression(invokedExpression) ? skipParentheses(invokedExpression.expression) : void 0;
  }
  function reportFlowControlError(node) {
    const block = findAncestor(node, isFunctionOrModuleBlock);
    const sourceFile = getSourceFileOfNode(node);
    const span = getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
    diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
  }
  function isReachableFlowNode(flow) {
    const result = isReachableFlowNodeWorker(
      flow,
      /*noCacheCheck*/
      false
    );
    lastFlowNode = flow;
    lastFlowNodeReachable = result;
    return result;
  }
  function isFalseExpression(expr) {
    const node = skipParentheses(
      expr,
      /*excludeJSDocTypeAssertions*/
      true
    );
    return node.kind === SyntaxKind.FalseKeyword || node.kind === SyntaxKind.BinaryExpression && (node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === SyntaxKind.BarBarToken && isFalseExpression(node.left) && isFalseExpression(node.right));
  }
  function isReachableFlowNodeWorker(flow, noCacheCheck) {
    while (true) {
      if (flow === lastFlowNode) {
        return lastFlowNodeReachable;
      }
      const flags = flow.flags;
      if (flags & FlowFlags.Shared) {
        if (!noCacheCheck) {
          const id = getFlowNodeId(flow);
          const reachable = flowNodeReachable[id];
          return reachable !== void 0 ? reachable : flowNodeReachable[id] = isReachableFlowNodeWorker(
            flow,
            /*noCacheCheck*/
            true
          );
        }
        noCacheCheck = false;
      }
      if (flags & (FlowFlags.Assignment | FlowFlags.Condition | FlowFlags.ArrayMutation)) {
        flow = flow.antecedent;
      } else if (flags & FlowFlags.Call) {
        const signature = getEffectsSignature(flow.node);
        if (signature) {
          const predicate = getTypePredicateOfSignature(signature);
          if (predicate && predicate.kind === TypePredicateKind.AssertsIdentifier && !predicate.type) {
            const predicateArgument = flow.node.arguments[predicate.parameterIndex];
            if (predicateArgument && isFalseExpression(predicateArgument)) {
              return false;
            }
          }
          if (getReturnTypeOfSignature(signature).flags & TypeFlags.Never) {
            return false;
          }
        }
        flow = flow.antecedent;
      } else if (flags & FlowFlags.BranchLabel) {
        return some(flow.antecedent, (f) => isReachableFlowNodeWorker(
          f,
          /*noCacheCheck*/
          false
        ));
      } else if (flags & FlowFlags.LoopLabel) {
        const antecedents = flow.antecedent;
        if (antecedents === void 0 || antecedents.length === 0) {
          return false;
        }
        flow = antecedents[0];
      } else if (flags & FlowFlags.SwitchClause) {
        const data = flow.node;
        if (data.clauseStart === data.clauseEnd && isExhaustiveSwitchStatement(data.switchStatement)) {
          return false;
        }
        flow = flow.antecedent;
      } else if (flags & FlowFlags.ReduceLabel) {
        lastFlowNode = void 0;
        const target = flow.node.target;
        const saveAntecedents = target.antecedent;
        target.antecedent = flow.node.antecedents;
        const result = isReachableFlowNodeWorker(
          flow.antecedent,
          /*noCacheCheck*/
          false
        );
        target.antecedent = saveAntecedents;
        return result;
      } else {
        return !(flags & FlowFlags.Unreachable);
      }
    }
  }
  function isPostSuperFlowNode(flow, noCacheCheck) {
    while (true) {
      const flags = flow.flags;
      if (flags & FlowFlags.Shared) {
        if (!noCacheCheck) {
          const id = getFlowNodeId(flow);
          const postSuper = flowNodePostSuper[id];
          return postSuper !== void 0 ? postSuper : flowNodePostSuper[id] = isPostSuperFlowNode(
            flow,
            /*noCacheCheck*/
            true
          );
        }
        noCacheCheck = false;
      }
      if (flags & (FlowFlags.Assignment | FlowFlags.Condition | FlowFlags.ArrayMutation | FlowFlags.SwitchClause)) {
        flow = flow.antecedent;
      } else if (flags & FlowFlags.Call) {
        if (flow.node.expression.kind === SyntaxKind.SuperKeyword) {
          return true;
        }
        flow = flow.antecedent;
      } else if (flags & FlowFlags.BranchLabel) {
        return every(flow.antecedent, (f) => isPostSuperFlowNode(
          f,
          /*noCacheCheck*/
          false
        ));
      } else if (flags & FlowFlags.LoopLabel) {
        flow = flow.antecedent[0];
      } else if (flags & FlowFlags.ReduceLabel) {
        const target = flow.node.target;
        const saveAntecedents = target.antecedent;
        target.antecedent = flow.node.antecedents;
        const result = isPostSuperFlowNode(
          flow.antecedent,
          /*noCacheCheck*/
          false
        );
        target.antecedent = saveAntecedents;
        return result;
      } else {
        return !!(flags & FlowFlags.Unreachable);
      }
    }
  }
  function isConstantReference(node) {
    switch (node.kind) {
      case SyntaxKind.ThisKeyword:
        return true;
      case SyntaxKind.Identifier:
        if (!isThisInTypeQuery(node)) {
          const symbol = getResolvedSymbol(node);
          return isConstantVariable(symbol) || isParameterOrMutableLocalVariable(symbol) && !isSymbolAssigned(symbol) || !!symbol.valueDeclaration && isFunctionExpression(symbol.valueDeclaration);
        }
        break;
      case SyntaxKind.PropertyAccessExpression:
      case SyntaxKind.ElementAccessExpression:
        return isConstantReference(node.expression) && isReadonlySymbol(getNodeLinks(node).resolvedSymbol || unknownSymbol);
      case SyntaxKind.ObjectBindingPattern:
      case SyntaxKind.ArrayBindingPattern:
        const rootDeclaration = getRootDeclaration(node.parent);
        return isParameter(rootDeclaration) || isCatchClauseVariableDeclaration(rootDeclaration) ? !isSomeSymbolAssigned(rootDeclaration) : isVariableDeclaration(rootDeclaration) && isVarConstLike(rootDeclaration);
    }
    return false;
  }
  function getFlowTypeOfReference(reference, declaredType, initialType = declaredType, flowContainer, flowNode = tryCast(reference, canHaveFlowNode)?.flowNode) {
    let key;
    let isKeySet = false;
    let flowDepth = 0;
    if (flowAnalysisDisabled) {
      return errorType;
    }
    if (!flowNode) {
      return declaredType;
    }
    flowInvocationCount++;
    const sharedFlowStart = sharedFlowCount;
    const evolvedType = getTypeFromFlowType(getTypeAtFlowNode(flowNode));
    sharedFlowCount = sharedFlowStart;
    const resultType = getObjectFlags(evolvedType) & ObjectFlags.EvolvingArray && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
    if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === SyntaxKind.NonNullExpression && !(resultType.flags & TypeFlags.Never) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & TypeFlags.Never) {
      return declaredType;
    }
    return resultType;
    function getOrSetCacheKey() {
      if (isKeySet) {
        return key;
      }
      isKeySet = true;
      return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
    }
    function getTypeAtFlowNode(flow) {
      if (flowDepth === 2e3) {
        tracing?.instant(tracing.Phase.CheckTypes, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id });
        flowAnalysisDisabled = true;
        reportFlowControlError(reference);
        return errorType;
      }
      flowDepth++;
      let sharedFlow;
      while (true) {
        const flags = flow.flags;
        if (flags & FlowFlags.Shared) {
          for (let i = sharedFlowStart; i < sharedFlowCount; i++) {
            if (sharedFlowNodes[i] === flow) {
              flowDepth--;
              return sharedFlowTypes[i];
            }
          }
          sharedFlow = flow;
        }
        let type;
        if (flags & FlowFlags.Assignment) {
          type = getTypeAtFlowAssignment(flow);
          if (!type) {
            flow = flow.antecedent;
            continue;
          }
        } else if (flags & FlowFlags.Call) {
          type = getTypeAtFlowCall(flow);
          if (!type) {
            flow = flow.antecedent;
            continue;
          }
        } else if (flags & FlowFlags.Condition) {
          type = getTypeAtFlowCondition(flow);
        } else if (flags & FlowFlags.SwitchClause) {
          type = getTypeAtSwitchClause(flow);
        } else if (flags & FlowFlags.Label) {
          if (flow.antecedent.length === 1) {
            flow = flow.antecedent[0];
            continue;
          }
          type = flags & FlowFlags.BranchLabel ? getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow);
        } else if (flags & FlowFlags.ArrayMutation) {
          type = getTypeAtFlowArrayMutation(flow);
          if (!type) {
            flow = flow.antecedent;
            continue;
          }
        } else if (flags & FlowFlags.ReduceLabel) {
          const target = flow.node.target;
          const saveAntecedents = target.antecedent;
          target.antecedent = flow.node.antecedents;
          type = getTypeAtFlowNode(flow.antecedent);
          target.antecedent = saveAntecedents;
        } else if (flags & FlowFlags.Start) {
          const container = flow.node;
          if (container && container !== flowContainer && reference.kind !== SyntaxKind.PropertyAccessExpression && reference.kind !== SyntaxKind.ElementAccessExpression && !(reference.kind === SyntaxKind.ThisKeyword && container.kind !== SyntaxKind.ArrowFunction)) {
            flow = container.flowNode;
            continue;
          }
          type = initialType;
        } else {
          type = convertAutoToAny(declaredType);
        }
        if (sharedFlow) {
          sharedFlowNodes[sharedFlowCount] = sharedFlow;
          sharedFlowTypes[sharedFlowCount] = type;
          sharedFlowCount++;
        }
        flowDepth--;
        return type;
      }
    }
    function getInitialOrAssignedType(flow) {
      const node = flow.node;
      return getNarrowableTypeForReference(
        node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement ? getInitialType(node) : getAssignedType(node),
        reference
      );
    }
    function getTypeAtFlowAssignment(flow) {
      const node = flow.node;
      if (isMatchingReference(reference, node)) {
        if (!isReachableFlowNode(flow)) {
          return unreachableNeverType;
        }
        if (getAssignmentTargetKind(node) === AssignmentKind.Compound) {
          const flowType = getTypeAtFlowNode(flow.antecedent);
          return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
        }
        if (declaredType === autoType || declaredType === autoArrayType) {
          if (isEmptyArrayAssignment(node)) {
            return getEvolvingArrayType(neverType);
          }
          const assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow));
          return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
        }
        const t = isInCompoundLikeAssignment(node) ? getBaseTypeOfLiteralType(declaredType) : declaredType;
        if (t.flags & TypeFlags.Union) {
          return getAssignmentReducedType(t, getInitialOrAssignedType(flow));
        }
        return t;
      }
      if (containsMatchingReference(reference, node)) {
        if (!isReachableFlowNode(flow)) {
          return unreachableNeverType;
        }
        if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConstLike(node))) {
          const init = getDeclaredExpandoInitializer(node);
          if (init && (init.kind === SyntaxKind.FunctionExpression || init.kind === SyntaxKind.ArrowFunction)) {
            return getTypeAtFlowNode(flow.antecedent);
          }
        }
        return declaredType;
      }
      if (isVariableDeclaration(node) && node.parent.parent.kind === SyntaxKind.ForInStatement && (isMatchingReference(reference, node.parent.parent.expression) || optionalChainContainsReference(node.parent.parent.expression, reference))) {
        return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))));
      }
      return void 0;
    }
    function narrowTypeByAssertion(type, expr) {
      const node = skipParentheses(
        expr,
        /*excludeJSDocTypeAssertions*/
        true
      );
      if (node.kind === SyntaxKind.FalseKeyword) {
        return unreachableNeverType;
      }
      if (node.kind === SyntaxKind.BinaryExpression) {
        if (node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) {
          return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
        }
        if (node.operatorToken.kind === SyntaxKind.BarBarToken) {
          return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
        }
      }
      return narrowType(
        type,
        node,
        /*assumeTrue*/
        true
      );
    }
    function getTypeAtFlowCall(flow) {
      const signature = getEffectsSignature(flow.node);
      if (signature) {
        const predicate = getTypePredicateOfSignature(signature);
        if (predicate && (predicate.kind === TypePredicateKind.AssertsThis || predicate.kind === TypePredicateKind.AssertsIdentifier)) {
          const flowType = getTypeAtFlowNode(flow.antecedent);
          const type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
          const narrowedType = predicate.type ? narrowTypeByTypePredicate(
            type,
            predicate,
            flow.node,
            /*assumeTrue*/
            true
          ) : predicate.kind === TypePredicateKind.AssertsIdentifier && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type;
          return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
        }
        if (getReturnTypeOfSignature(signature).flags & TypeFlags.Never) {
          return unreachableNeverType;
        }
      }
      return void 0;
    }
    function getTypeAtFlowArrayMutation(flow) {
      if (declaredType === autoType || declaredType === autoArrayType) {
        const node = flow.node;
        const expr = node.kind === SyntaxKind.CallExpression ? node.expression.expression : node.left.expression;
        if (isMatchingReference(reference, getReferenceCandidate(expr))) {
          const flowType = getTypeAtFlowNode(flow.antecedent);
          const type = getTypeFromFlowType(flowType);
          if (getObjectFlags(type) & ObjectFlags.EvolvingArray) {
            let evolvedType2 = type;
            if (node.kind === SyntaxKind.CallExpression) {
              for (const arg of node.arguments) {
                evolvedType2 = addEvolvingArrayElementType(evolvedType2, arg);
              }
            } else {
              const indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
              if (isTypeAssignableToKind(indexType, TypeFlags.NumberLike)) {
                evolvedType2 = addEvolvingArrayElementType(evolvedType2, node.right);
              }
            }
            return evolvedType2 === type ? flowType : createFlowType(evolvedType2, isIncomplete(flowType));
          }
          return flowType;
        }
      }
      return void 0;
    }
    function getTypeAtFlowCondition(flow) {
      const flowType = getTypeAtFlowNode(flow.antecedent);
      const type = getTypeFromFlowType(flowType);
      if (type.flags & TypeFlags.Never) {
        return flowType;
      }
      const assumeTrue = (flow.flags & FlowFlags.TrueCondition) !== 0;
      const nonEvolvingType = finalizeEvolvingArrayType(type);
      const narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
      if (narrowedType === nonEvolvingType) {
        return flowType;
      }
      return createFlowType(narrowedType, isIncomplete(flowType));
    }
    function getTypeAtSwitchClause(flow) {
      const expr = skipParentheses(flow.node.switchStatement.expression);
      const flowType = getTypeAtFlowNode(flow.antecedent);
      let type = getTypeFromFlowType(flowType);
      if (isMatchingReference(reference, expr)) {
        type = narrowTypeBySwitchOnDiscriminant(type, flow.node);
      } else if (expr.kind === SyntaxKind.TypeOfExpression && isMatchingReference(reference, expr.expression)) {
        type = narrowTypeBySwitchOnTypeOf(type, flow.node);
      } else if (expr.kind === SyntaxKind.TrueKeyword) {
        type = narrowTypeBySwitchOnTrue(type, flow.node);
      } else {
        if (strictNullChecks) {
          if (optionalChainContainsReference(expr, reference)) {
            type = narrowTypeBySwitchOptionalChainContainment(type, flow.node, (t) => !(t.flags & (TypeFlags.Undefined | TypeFlags.Never)));
          } else if (expr.kind === SyntaxKind.TypeOfExpression && optionalChainContainsReference(expr.expression, reference)) {
            type = narrowTypeBySwitchOptionalChainContainment(type, flow.node, (t) => !(t.flags & TypeFlags.Never || t.flags & TypeFlags.StringLiteral && t.value === "undefined"));
          }
        }
        const access = getDiscriminantPropertyAccess(expr, type);
        if (access) {
          type = narrowTypeBySwitchOnDiscriminantProperty(type, access, flow.node);
        }
      }
      return createFlowType(type, isIncomplete(flowType));
    }
    function getTypeAtFlowBranchLabel(flow) {
      const antecedentTypes = [];
      let subtypeReduction = false;
      let seenIncomplete = false;
      let bypassFlow;
      for (const antecedent of flow.antecedent) {
        if (!bypassFlow && antecedent.flags & FlowFlags.SwitchClause && antecedent.node.clauseStart === antecedent.node.clauseEnd) {
          bypassFlow = antecedent;
          continue;
        }
        const flowType = getTypeAtFlowNode(antecedent);
        const type = getTypeFromFlowType(flowType);
        if (type === declaredType && declaredType === initialType) {
          return type;
        }
        pushIfUnique(antecedentTypes, type);
        if (!isTypeSubsetOf(type, initialType)) {
          subtypeReduction = true;
        }
        if (isIncomplete(flowType)) {
          seenIncomplete = true;
        }
      }
      if (bypassFlow) {
        const flowType = getTypeAtFlowNode(bypassFlow);
        const type = getTypeFromFlowType(flowType);
        if (!(type.flags & TypeFlags.Never) && !contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.node.switchStatement)) {
          if (type === declaredType && declaredType === initialType) {
            return type;
          }
          antecedentTypes.push(type);
          if (!isTypeSubsetOf(type, initialType)) {
            subtypeReduction = true;
          }
          if (isIncomplete(flowType)) {
            seenIncomplete = true;
          }
        }
      }
      return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? UnionReduction.Subtype : UnionReduction.Literal), seenIncomplete);
    }
    function getTypeAtFlowLoopLabel(flow) {
      const id = getFlowNodeId(flow);
      const cache = flowLoopCaches[id] || (flowLoopCaches[id] = /* @__PURE__ */ new Map());
      const key2 = getOrSetCacheKey();
      if (!key2) {
        return declaredType;
      }
      const cached = cache.get(key2);
      if (cached) {
        return cached;
      }
      for (let i = flowLoopStart; i < flowLoopCount; i++) {
        if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key2 && flowLoopTypes[i].length) {
          return createFlowType(
            getUnionOrEvolvingArrayType(flowLoopTypes[i], UnionReduction.Literal),
            /*incomplete*/
            true
          );
        }
      }
      const antecedentTypes = [];
      let subtypeReduction = false;
      let firstAntecedentType;
      for (const antecedent of flow.antecedent) {
        let flowType;
        if (!firstAntecedentType) {
          flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
        } else {
          flowLoopNodes[flowLoopCount] = flow;
          flowLoopKeys[flowLoopCount] = key2;
          flowLoopTypes[flowLoopCount] = antecedentTypes;
          flowLoopCount++;
          const saveFlowTypeCache = flowTypeCache;
          flowTypeCache = void 0;
          flowType = getTypeAtFlowNode(antecedent);
          flowTypeCache = saveFlowTypeCache;
          flowLoopCount--;
          const cached2 = cache.get(key2);
          if (cached2) {
            return cached2;
          }
        }
        const type = getTypeFromFlowType(flowType);
        pushIfUnique(antecedentTypes, type);
        if (!isTypeSubsetOf(type, initialType)) {
          subtypeReduction = true;
        }
        if (type === declaredType) {
          break;
        }
      }
      const result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? UnionReduction.Subtype : UnionReduction.Literal);
      if (isIncomplete(firstAntecedentType)) {
        return createFlowType(
          result,
          /*incomplete*/
          true
        );
      }
      cache.set(key2, result);
      return result;
    }
    function getUnionOrEvolvingArrayType(types, subtypeReduction) {
      if (isEvolvingArrayTypeList(types)) {
        return getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType)));
      }
      const result = recombineUnknownType(getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction));
      if (result !== declaredType && result.flags & declaredType.flags & TypeFlags.Union && arrayIsEqualTo(result.types, declaredType.types)) {
        return declaredType;
      }
      return result;
    }
    function getCandidateDiscriminantPropertyAccess(expr) {
      if (isBindingPattern(reference) || isFunctionExpressionOrArrowFunction(reference) || isObjectLiteralMethod(reference)) {
        if (isIdentifier(expr)) {
          const symbol = getResolvedSymbol(expr);
          const declaration = symbol.valueDeclaration;
          if (declaration && (isBindingElement(declaration) || isParameter(declaration)) && reference === declaration.parent && !declaration.initializer && !declaration.dotDotDotToken) {
            return declaration;
          }
        }
      } else if (isAccessExpression(expr)) {
        if (isMatchingReference(reference, expr.expression)) {
          return expr;
        }
      } else if (isIdentifier(expr)) {
        const symbol = getResolvedSymbol(expr);
        if (isConstantVariable(symbol)) {
          const declaration = symbol.valueDeclaration;
          if (isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isAccessExpression(declaration.initializer) && isMatchingReference(reference, declaration.initializer.expression)) {
            return declaration.initializer;
          }
          if (isBindingElement(declaration) && !declaration.initializer) {
            const parent = declaration.parent.parent;
            if (isVariableDeclaration(parent) && !parent.type && parent.initializer && (isIdentifier(parent.initializer) || isAccessExpression(parent.initializer)) && isMatchingReference(reference, parent.initializer)) {
              return declaration;
            }
          }
        }
      }
      return void 0;
    }
    function getDiscriminantPropertyAccess(expr, computedType) {
      if (declaredType.flags & TypeFlags.Union || computedType.flags & TypeFlags.Union) {
        const access = getCandidateDiscriminantPropertyAccess(expr);
        if (access) {
          const name = getAccessedPropertyName(access);
          if (name) {
            const type = declaredType.flags & TypeFlags.Union && isTypeSubsetOf(computedType, declaredType) ? declaredType : computedType;
            if (isDiscriminantProperty(type, name)) {
              return access;
            }
          }
        }
      }
      return void 0;
    }
    function narrowTypeByDiscriminant(type, access, narrowType2) {
      const propName = getAccessedPropertyName(access);
      if (propName === void 0) {
        return type;
      }
      const optionalChain = isOptionalChain(access);
      const removeNullable = strictNullChecks && (optionalChain || isNonNullAccess(access)) && maybeTypeOfKind(type, TypeFlags.Nullable);
      let propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName);
      if (!propType) {
        return type;
      }
      propType = removeNullable && optionalChain ? getOptionalType(propType) : propType;
      const narrowedPropType = narrowType2(propType);
      return filterType(type, (t) => {
        const discriminantType = getTypeOfPropertyOrIndexSignatureOfType(t, propName) || unknownType;
        return !(discriminantType.flags & TypeFlags.Never) && !(narrowedPropType.flags & TypeFlags.Never) && areTypesComparable(narrowedPropType, discriminantType);
      });
    }
    function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) {
      if ((operator === SyntaxKind.EqualsEqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) && type.flags & TypeFlags.Union) {
        const keyPropertyName = getKeyPropertyName(type);
        if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) {
          const candidate = getConstituentTypeForKeyType(type, getTypeOfExpression(value));
          if (candidate) {
            return operator === (assumeTrue ? SyntaxKind.EqualsEqualsEqualsToken : SyntaxKind.ExclamationEqualsEqualsToken) ? candidate : isUnitType(getTypeOfPropertyOfType(candidate, keyPropertyName) || unknownType) ? removeType(type, candidate) : type;
          }
        }
      }
      return narrowTypeByDiscriminant(type, access, (t) => narrowTypeByEquality(t, operator, value, assumeTrue));
    }
    function narrowTypeBySwitchOnDiscriminantProperty(type, access, data) {
      if (data.clauseStart < data.clauseEnd && type.flags & TypeFlags.Union && getKeyPropertyName(type) === getAccessedPropertyName(access)) {
        const clauseTypes = getSwitchClauseTypes(data.switchStatement).slice(data.clauseStart, data.clauseEnd);
        const candidate = getUnionType(map(clauseTypes, (t) => getConstituentTypeForKeyType(type, t) || unknownType));
        if (candidate !== unknownType) {
          return candidate;
        }
      }
      return narrowTypeByDiscriminant(type, access, (t) => narrowTypeBySwitchOnDiscriminant(t, data));
    }
    function narrowTypeByTruthiness(type, expr, assumeTrue) {
      if (isMatchingReference(reference, expr)) {
        return getAdjustedTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
      }
      if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
        type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
      }
      const access = getDiscriminantPropertyAccess(expr, type);
      if (access) {
        return narrowTypeByDiscriminant(type, access, (t) => getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */));
      }
      return type;
    }
    function isTypePresencePossible(type, propName, assumeTrue) {
      const prop = getPropertyOfType(type, propName);
      return prop ? !!(prop.flags & SymbolFlags.Optional || getCheckFlags(prop) & CheckFlags.Partial) || assumeTrue : !!getApplicableIndexInfoForName(type, propName) || !assumeTrue;
    }
    function narrowTypeByInKeyword(type, nameType, assumeTrue) {
      const name = getPropertyNameFromType(nameType);
      const isKnownProperty2 = someType(type, (t) => isTypePresencePossible(
        t,
        name,
        /*assumeTrue*/
        true
      ));
      if (isKnownProperty2) {
        return filterType(type, (t) => isTypePresencePossible(t, name, assumeTrue));
      }
      if (assumeTrue) {
        const recordSymbol = getGlobalRecordSymbol();
        if (recordSymbol) {
          return getIntersectionType([type, getTypeAliasInstantiation(recordSymbol, [nameType, unknownType])]);
        }
      }
      return type;
    }
    function narrowTypeByBooleanComparison(type, expr, bool, operator, assumeTrue) {
      assumeTrue = assumeTrue !== (bool.kind === SyntaxKind.TrueKeyword) !== (operator !== SyntaxKind.ExclamationEqualsEqualsToken && operator !== SyntaxKind.ExclamationEqualsToken);
      return narrowType(type, expr, assumeTrue);
    }
    function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
      switch (expr.operatorToken.kind) {
        case SyntaxKind.EqualsToken:
        case SyntaxKind.BarBarEqualsToken:
        case SyntaxKind.AmpersandAmpersandEqualsToken:
        case SyntaxKind.QuestionQuestionEqualsToken:
          return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
        case SyntaxKind.EqualsEqualsToken:
        case SyntaxKind.ExclamationEqualsToken:
        case SyntaxKind.EqualsEqualsEqualsToken:
        case SyntaxKind.ExclamationEqualsEqualsToken:
          const operator = expr.operatorToken.kind;
          const left = getReferenceCandidate(expr.left);
          const right = getReferenceCandidate(expr.right);
          if (left.kind === SyntaxKind.TypeOfExpression && isStringLiteralLike(right)) {
            return narrowTypeByTypeof(type, left, operator, right, assumeTrue);
          }
          if (right.kind === SyntaxKind.TypeOfExpression && isStringLiteralLike(left)) {
            return narrowTypeByTypeof(type, right, operator, left, assumeTrue);
          }
          if (isMatchingReference(reference, left)) {
            return narrowTypeByEquality(type, operator, right, assumeTrue);
          }
          if (isMatchingReference(reference, right)) {
            return narrowTypeByEquality(type, operator, left, assumeTrue);
          }
          if (strictNullChecks) {
            if (optionalChainContainsReference(left, reference)) {
              type = narrowTypeByOptionalChainContainment(type, operator, right, assumeTrue);
            } else if (optionalChainContainsReference(right, reference)) {
              type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue);
            }
          }
          const leftAccess = getDiscriminantPropertyAccess(left, type);
          if (leftAccess) {
            return narrowTypeByDiscriminantProperty(type, leftAccess, operator, right, assumeTrue);
          }
          const rightAccess = getDiscriminantPropertyAccess(right, type);
          if (rightAccess) {
            return narrowTypeByDiscriminantProperty(type, rightAccess, operator, left, assumeTrue);
          }
          if (isMatchingConstructorReference(left)) {
            return narrowTypeByConstructor(type, operator, right, assumeTrue);
          }
          if (isMatchingConstructorReference(right)) {
            return narrowTypeByConstructor(type, operator, left, assumeTrue);
          }
          if (isBooleanLiteral(right) && !isAccessExpression(left)) {
            return narrowTypeByBooleanComparison(type, left, right, operator, assumeTrue);
          }
          if (isBooleanLiteral(left) && !isAccessExpression(right)) {
            return narrowTypeByBooleanComparison(type, right, left, operator, assumeTrue);
          }
          break;
        case SyntaxKind.InstanceOfKeyword:
          return narrowTypeByInstanceof(type, expr, assumeTrue);
        case SyntaxKind.InKeyword:
          if (isPrivateIdentifier(expr.left)) {
            return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue);
          }
          const target = getReferenceCandidate(expr.right);
          if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target)) {
            const leftType = getTypeOfExpression(expr.left);
            if (isTypeUsableAsPropertyName(leftType) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) {
              return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */);
            }
          }
          if (isMatchingReference(reference, target)) {
            const leftType = getTypeOfExpression(expr.left);
            if (isTypeUsableAsPropertyName(leftType)) {
              return narrowTypeByInKeyword(type, leftType, assumeTrue);
            }
          }
          break;
        case SyntaxKind.CommaToken:
          return narrowType(type, expr.right, assumeTrue);
        // Ordinarily we won't see && and || expressions in control flow analysis because the Binder breaks those
        // expressions down to individual conditional control flows. However, we may encounter them when analyzing
        // aliased conditional expressions.
        case SyntaxKind.AmpersandAmpersandToken:
          return assumeTrue ? narrowType(
            narrowType(
              type,
              expr.left,
              /*assumeTrue*/
              true
            ),
            expr.right,
            /*assumeTrue*/
            true
          ) : getUnionType([narrowType(
            type,
            expr.left,
            /*assumeTrue*/
            false
          ), narrowType(
            type,
            expr.right,
            /*assumeTrue*/
            false
          )]);
        case SyntaxKind.BarBarToken:
          return assumeTrue ? getUnionType([narrowType(
            type,
            expr.left,
            /*assumeTrue*/
            true
          ), narrowType(
            type,
            expr.right,
            /*assumeTrue*/
            true
          )]) : narrowType(
            narrowType(
              type,
              expr.left,
              /*assumeTrue*/
              false
            ),
            expr.right,
            /*assumeTrue*/
            false
          );
      }
      return type;
    }
    function narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue) {
      const target = getReferenceCandidate(expr.right);
      if (!isMatchingReference(reference, target)) {
        return type;
      }
      Debug.assertNode(expr.left, isPrivateIdentifier);
      const symbol = getSymbolForPrivateIdentifierExpression(expr.left);
      if (symbol === void 0) {
        return type;
      }
      const classSymbol = symbol.parent;
      const targetType = hasStaticModifier(Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration")) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol);
      return getNarrowedType(
        type,
        targetType,
        assumeTrue,
        /*checkDerived*/
        true
      );
    }
    function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
      const equalsOperator = operator === SyntaxKind.EqualsEqualsToken || operator === SyntaxKind.EqualsEqualsEqualsToken;
      const nullableFlags = operator === SyntaxKind.EqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsToken ? TypeFlags.Nullable : TypeFlags.Undefined;
      const valueType = getTypeOfExpression(value);
      const removeNullable = equalsOperator !== assumeTrue && everyType(valueType, (t) => !!(t.flags & nullableFlags)) || equalsOperator === assumeTrue && everyType(valueType, (t) => !(t.flags & (TypeFlags.AnyOrUnknown | nullableFlags)));
      return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
    }
    function narrowTypeByEquality(type, operator, value, assumeTrue) {
      if (type.flags & TypeFlags.Any) {
        return type;
      }
      if (operator === SyntaxKind.ExclamationEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) {
        assumeTrue = !assumeTrue;
      }
      const valueType = getTypeOfExpression(value);
      const doubleEquals = operator === SyntaxKind.EqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsToken;
      if (valueType.flags & TypeFlags.Nullable) {
        if (!strictNullChecks) {
          return type;
        }
        const facts = doubleEquals ? assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : valueType.flags & TypeFlags.Null ? assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
        return getAdjustedTypeWithFacts(type, facts);
      }
      if (assumeTrue) {
        if (!doubleEquals && (type.flags & TypeFlags.Unknown || someType(type, isEmptyAnonymousObjectType))) {
          if (valueType.flags & (TypeFlags.Primitive | TypeFlags.NonPrimitive) || isEmptyAnonymousObjectType(valueType)) {
            return valueType;
          }
          if (valueType.flags & TypeFlags.Object) {
            return nonPrimitiveType;
          }
        }
        const filteredType = filterType(type, (t) => areTypesComparable(t, valueType) || doubleEquals && isCoercibleUnderDoubleEquals(t, valueType));
        return replacePrimitivesWithLiterals(filteredType, valueType);
      }
      if (isUnitType(valueType)) {
        return filterType(type, (t) => !(isUnitLikeType(t) && areTypesComparable(t, valueType)));
      }
      return type;
    }
    function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
      if (operator === SyntaxKind.ExclamationEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) {
        assumeTrue = !assumeTrue;
      }
      const target = getReferenceCandidate(typeOfExpr.expression);
      if (!isMatchingReference(reference, target)) {
        if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
          type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
        }
        const propertyAccess = getDiscriminantPropertyAccess(target, type);
        if (propertyAccess) {
          return narrowTypeByDiscriminant(type, propertyAccess, (t) => narrowTypeByLiteralExpression(t, literal, assumeTrue));
        }
        return type;
      }
      return narrowTypeByLiteralExpression(type, literal, assumeTrue);
    }
    function narrowTypeByLiteralExpression(type, literal, assumeTrue) {
      return assumeTrue ? narrowTypeByTypeName(type, literal.text) : getAdjustedTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */);
    }
    function narrowTypeBySwitchOptionalChainContainment(type, { switchStatement, clauseStart, clauseEnd }, clauseCheck) {
      const everyClauseChecks = clauseStart !== clauseEnd && every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
      return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
    }
    function narrowTypeBySwitchOnDiscriminant(type, { switchStatement, clauseStart, clauseEnd }) {
      const switchTypes = getSwitchClauseTypes(switchStatement);
      if (!switchTypes.length) {
        return type;
      }
      const clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
      const hasDefaultClause = clauseStart === clauseEnd || contains(clauseTypes, neverType);
      if (type.flags & TypeFlags.Unknown && !hasDefaultClause) {
        let groundClauseTypes;
        for (let i = 0; i < clauseTypes.length; i += 1) {
          const t = clauseTypes[i];
          if (t.flags & (TypeFlags.Primitive | TypeFlags.NonPrimitive)) {
            if (groundClauseTypes !== void 0) {
              groundClauseTypes.push(t);
            }
          } else if (t.flags & TypeFlags.Object) {
            if (groundClauseTypes === void 0) {
              groundClauseTypes = clauseTypes.slice(0, i);
            }
            groundClauseTypes.push(nonPrimitiveType);
          } else {
            return type;
          }
        }
        return getUnionType(groundClauseTypes === void 0 ? clauseTypes : groundClauseTypes);
      }
      const discriminantType = getUnionType(clauseTypes);
      const caseType = discriminantType.flags & TypeFlags.Never ? neverType : replacePrimitivesWithLiterals(filterType(type, (t) => areTypesComparable(discriminantType, t)), discriminantType);
      if (!hasDefaultClause) {
        return caseType;
      }
      const defaultType = filterType(type, (t) => !(isUnitLikeType(t) && contains(switchTypes, t.flags & TypeFlags.Undefined ? undefinedType : getRegularTypeOfLiteralType(extractUnitType(t)))));
      return caseType.flags & TypeFlags.Never ? defaultType : getUnionType([caseType, defaultType]);
    }
    function narrowTypeByTypeName(type, typeName) {
      switch (typeName) {
        case "string":
          return narrowTypeByTypeFacts(type, stringType, 1 /* TypeofEQString */);
        case "number":
          return narrowTypeByTypeFacts(type, numberType, 2 /* TypeofEQNumber */);
        case "bigint":
          return narrowTypeByTypeFacts(type, bigintType, 4 /* TypeofEQBigInt */);
        case "boolean":
          return narrowTypeByTypeFacts(type, booleanType, 8 /* TypeofEQBoolean */);
        case "symbol":
          return narrowTypeByTypeFacts(type, esSymbolType, 16 /* TypeofEQSymbol */);
        case "object":
          return type.flags & TypeFlags.Any ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, 32 /* TypeofEQObject */), narrowTypeByTypeFacts(type, nullType, 131072 /* EQNull */)]);
        case "function":
          return type.flags & TypeFlags.Any ? type : narrowTypeByTypeFacts(type, globalFunctionType, 64 /* TypeofEQFunction */);
        case "undefined":
          return narrowTypeByTypeFacts(type, undefinedType, 65536 /* EQUndefined */);
      }
      return narrowTypeByTypeFacts(type, nonPrimitiveType, 128 /* TypeofEQHostObject */);
    }
    function narrowTypeByTypeFacts(type, impliedType, facts) {
      return mapType(type, (t) => (
        // We first check if a constituent is a subtype of the implied type. If so, we either keep or eliminate
        // the constituent based on its type facts. We use the strict subtype relation because it treats `object`
        // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`,
        // but are classified as "function" according to `typeof`.
        isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? hasTypeFacts(t, facts) ? t : neverType : (
          // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied
          // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`.
          isTypeSubtypeOf(impliedType, t) ? impliedType : (
            // Neither the constituent nor the implied type is a subtype of the other, however their domains may still
            // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate
            // possible overlap, we form an intersection. Otherwise, we eliminate the constituent.
            hasTypeFacts(t, facts) ? getIntersectionType([t, impliedType]) : neverType
          )
        )
      ));
    }
    function narrowTypeBySwitchOnTypeOf(type, { switchStatement, clauseStart, clauseEnd }) {
      const witnesses = getSwitchClauseTypeOfWitnesses(switchStatement);
      if (!witnesses) {
        return type;
      }
      const defaultIndex = findIndex(switchStatement.caseBlock.clauses, (clause) => clause.kind === SyntaxKind.DefaultClause);
      const hasDefaultClause = clauseStart === clauseEnd || defaultIndex >= clauseStart && defaultIndex < clauseEnd;
      if (hasDefaultClause) {
        const notEqualFacts = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses);
        return filterType(type, (t) => getTypeFacts(t, notEqualFacts) === notEqualFacts);
      }
      const clauseWitnesses = witnesses.slice(clauseStart, clauseEnd);
      return getUnionType(map(clauseWitnesses, (text) => text ? narrowTypeByTypeName(type, text) : neverType));
    }
    function narrowTypeBySwitchOnTrue(type, { switchStatement, clauseStart, clauseEnd }) {
      const defaultIndex = findIndex(switchStatement.caseBlock.clauses, (clause) => clause.kind === SyntaxKind.DefaultClause);
      const hasDefaultClause = clauseStart === clauseEnd || defaultIndex >= clauseStart && defaultIndex < clauseEnd;
      for (let i = 0; i < clauseStart; i++) {
        const clause = switchStatement.caseBlock.clauses[i];
        if (clause.kind === SyntaxKind.CaseClause) {
          type = narrowType(
            type,
            clause.expression,
            /*assumeTrue*/
            false
          );
        }
      }
      if (hasDefaultClause) {
        for (let i = clauseEnd; i < switchStatement.caseBlock.clauses.length; i++) {
          const clause = switchStatement.caseBlock.clauses[i];
          if (clause.kind === SyntaxKind.CaseClause) {
            type = narrowType(
              type,
              clause.expression,
              /*assumeTrue*/
              false
            );
          }
        }
        return type;
      }
      const clauses = switchStatement.caseBlock.clauses.slice(clauseStart, clauseEnd);
      return getUnionType(map(clauses, (clause) => clause.kind === SyntaxKind.CaseClause ? narrowType(
        type,
        clause.expression,
        /*assumeTrue*/
        true
      ) : neverType));
    }
    function isMatchingConstructorReference(expr) {
      return (isPropertyAccessExpression(expr) && idText(expr.name) === "constructor" || isElementAccessExpression(expr) && isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && isMatchingReference(reference, expr.expression);
    }
    function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
      if (assumeTrue ? operator !== SyntaxKind.EqualsEqualsToken && operator !== SyntaxKind.EqualsEqualsEqualsToken : operator !== SyntaxKind.ExclamationEqualsToken && operator !== SyntaxKind.ExclamationEqualsEqualsToken) {
        return type;
      }
      const identifierType = getTypeOfExpression(identifier);
      if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
        return type;
      }
      const prototypeProperty = getPropertyOfType(identifierType, "prototype");
      if (!prototypeProperty) {
        return type;
      }
      const prototypeType = getTypeOfSymbol(prototypeProperty);
      const candidate = !isTypeAny(prototypeType) ? prototypeType : void 0;
      if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
        return type;
      }
      if (isTypeAny(type)) {
        return candidate;
      }
      return filterType(type, (t) => isConstructedBy(t, candidate));
      function isConstructedBy(source, target) {
        if (source.flags & TypeFlags.Object && getObjectFlags(source) & ObjectFlags.Class || target.flags & TypeFlags.Object && getObjectFlags(target) & ObjectFlags.Class) {
          return source.symbol === target.symbol;
        }
        return isTypeSubtypeOf(source, target);
      }
    }
    function narrowTypeByInstanceof(type, expr, assumeTrue) {
      const left = getReferenceCandidate(expr.left);
      if (!isMatchingReference(reference, left)) {
        if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
          return getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
        }
        return type;
      }
      const right = expr.right;
      const rightType = getTypeOfExpression(right);
      if (!isTypeDerivedFrom(rightType, globalObjectType)) {
        return type;
      }
      const signature = getEffectsSignature(expr);
      const predicate = signature && getTypePredicateOfSignature(signature);
      if (predicate && predicate.kind === TypePredicateKind.Identifier && predicate.parameterIndex === 0) {
        return getNarrowedType(
          type,
          predicate.type,
          assumeTrue,
          /*checkDerived*/
          true
        );
      }
      if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
        return type;
      }
      const instanceType = mapType(rightType, getInstanceType);
      if (isTypeAny(type) && (instanceType === globalObjectType || instanceType === globalFunctionType) || !assumeTrue && !(instanceType.flags & TypeFlags.Object && !isEmptyAnonymousObjectType(instanceType))) {
        return type;
      }
      return getNarrowedType(
        type,
        instanceType,
        assumeTrue,
        /*checkDerived*/
        true
      );
    }
    function getInstanceType(constructorType) {
      const prototypePropertyType = getTypeOfPropertyOfType(constructorType, "prototype");
      if (prototypePropertyType && !isTypeAny(prototypePropertyType)) {
        return prototypePropertyType;
      }
      const constructSignatures = getSignaturesOfType(constructorType, SignatureKind.Construct);
      if (constructSignatures.length) {
        return getUnionType(map(constructSignatures, (signature) => getReturnTypeOfSignature(getErasedSignature(signature))));
      }
      return emptyObjectType;
    }
    function getNarrowedType(type, candidate, assumeTrue, checkDerived) {
      const key2 = type.flags & TypeFlags.Union ? `N${getTypeId(type)},${getTypeId(candidate)},${(assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)}` : void 0;
      return getCachedType(key2) ?? setCachedType(key2, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived));
    }
    function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) {
      if (!assumeTrue) {
        if (type === candidate) {
          return neverType;
        }
        if (checkDerived) {
          return filterType(type, (t) => !isTypeDerivedFrom(t, candidate));
        }
        const trueType2 = getNarrowedType(
          type,
          candidate,
          /*assumeTrue*/
          true,
          /*checkDerived*/
          false
        );
        return filterType(type, (t) => !isTypeSubsetOf(t, trueType2));
      }
      if (type.flags & TypeFlags.AnyOrUnknown) {
        return candidate;
      }
      if (type === candidate) {
        return candidate;
      }
      const isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf;
      const keyPropertyName = type.flags & TypeFlags.Union ? getKeyPropertyName(type) : void 0;
      const narrowedType = mapType(candidate, (c) => {
        const discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName);
        const matching = discriminant && getConstituentTypeForKeyType(type, discriminant);
        const directlyRelated = mapType(
          matching || type,
          checkDerived ? (t) => isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType : (t) => isTypeStrictSubtypeOf(t, c) ? t : isTypeStrictSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : isTypeSubtypeOf(c, t) ? c : neverType
        );
        return directlyRelated.flags & TypeFlags.Never ? mapType(type, (t) => maybeTypeOfKind(t, TypeFlags.Instantiable) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType) : directlyRelated;
      });
      return !(narrowedType.flags & TypeFlags.Never) ? narrowedType : isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : isTypeAssignableTo(candidate, type) ? candidate : getIntersectionType([type, candidate]);
    }
    function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
      if (hasMatchingArgument(callExpression, reference)) {
        const signature = assumeTrue || !isCallChain(callExpression) ? getEffectsSignature(callExpression) : void 0;
        const predicate = signature && getTypePredicateOfSignature(signature);
        if (predicate && (predicate.kind === TypePredicateKind.This || predicate.kind === TypePredicateKind.Identifier)) {
          return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
        }
      }
      if (containsMissingType(type) && isAccessExpression(reference) && isPropertyAccessExpression(callExpression.expression)) {
        const callAccess = callExpression.expression;
        if (isMatchingReference(reference.expression, getReferenceCandidate(callAccess.expression)) && isIdentifier(callAccess.name) && callAccess.name.escapedText === "hasOwnProperty" && callExpression.arguments.length === 1) {
          const argument = callExpression.arguments[0];
          if (isStringLiteralLike(argument) && getAccessedPropertyName(reference) === escapeLeadingUnderscores(argument.text)) {
            return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */);
          }
        }
      }
      return type;
    }
    function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
      if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
        const predicateArgument = getTypePredicateArgument(predicate, callExpression);
        if (predicateArgument) {
          if (isMatchingReference(reference, predicateArgument)) {
            return getNarrowedType(
              type,
              predicate.type,
              assumeTrue,
              /*checkDerived*/
              false
            );
          }
          if (strictNullChecks && optionalChainContainsReference(predicateArgument, reference) && (assumeTrue && !hasTypeFacts(predicate.type, 65536 /* EQUndefined */) || !assumeTrue && everyType(predicate.type, isNullableType))) {
            type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
          }
          const access = getDiscriminantPropertyAccess(predicateArgument, type);
          if (access) {
            return narrowTypeByDiscriminant(type, access, (t) => getNarrowedType(
              t,
              predicate.type,
              assumeTrue,
              /*checkDerived*/
              false
            ));
          }
        }
      }
      return type;
    }
    function narrowType(type, expr, assumeTrue) {
      if (isExpressionOfOptionalChainRoot(expr) || isBinaryExpression(expr.parent) && (expr.parent.operatorToken.kind === SyntaxKind.QuestionQuestionToken || expr.parent.operatorToken.kind === SyntaxKind.QuestionQuestionEqualsToken) && expr.parent.left === expr) {
        return narrowTypeByOptionality(type, expr, assumeTrue);
      }
      switch (expr.kind) {
        case SyntaxKind.Identifier:
          if (!isMatchingReference(reference, expr) && inlineLevel < 5) {
            const symbol = getResolvedSymbol(expr);
            if (isConstantVariable(symbol)) {
              const declaration = symbol.valueDeclaration;
              if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isConstantReference(reference)) {
                inlineLevel++;
                const result = narrowType(type, declaration.initializer, assumeTrue);
                inlineLevel--;
                return result;
              }
            }
          }
        // falls through
        case SyntaxKind.ThisKeyword:
        case SyntaxKind.SuperKeyword:
        case SyntaxKind.PropertyAccessExpression:
        case SyntaxKind.ElementAccessExpression:
          return narrowTypeByTruthiness(type, expr, assumeTrue);
        case SyntaxKind.CallExpression:
          return narrowTypeByCallExpression(type, expr, assumeTrue);
        case SyntaxKind.ParenthesizedExpression:
        case SyntaxKind.NonNullExpression:
          return narrowType(type, expr.expression, assumeTrue);
        case SyntaxKind.BinaryExpression:
          return narrowTypeByBinaryExpression(type, expr, assumeTrue);
        case SyntaxKind.PrefixUnaryExpression:
          if (expr.operator === SyntaxKind.ExclamationToken) {
            return narrowType(type, expr.operand, !assumeTrue);
          }
          break;
      }
      return type;
    }
    function narrowTypeByOptionality(type, expr, assumePresent) {
      if (isMatchingReference(reference, expr)) {
        return getAdjustedTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
      }
      const access = getDiscriminantPropertyAccess(expr, type);
      if (access) {
        return narrowTypeByDiscriminant(type, access, (t) => getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */));
      }
      return type;
    }
  }
  function getTypeOfSymbolAtLocation(symbol, location) {
    symbol = getExportSymbolOfValueSymbolIfExported(symbol);
    if (location.kind === SyntaxKind.Identifier || location.kind === SyntaxKind.PrivateIdentifier) {
      if (isRightSideOfQualifiedNameOrPropertyAccess(location)) {
        location = location.parent;
      }
      if (isExpressionNode(location) && (!isAssignmentTarget(location) || isWriteAccess(location))) {
        const type = removeOptionalTypeMarker(
          isWriteAccess(location) && location.kind === SyntaxKind.PropertyAccessExpression ? checkPropertyAccessExpression(
            location,
            /*checkMode*/
            void 0,
            /*writeOnly*/
            true
          ) : getTypeOfExpression(location)
        );
        if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
          return type;
        }
      }
    }
    if (isDeclarationName(location) && isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) {
      return getWriteTypeOfAccessors(location.parent.symbol);
    }
    return isRightSideOfAccessExpression(location) && isWriteAccess(location.parent) ? getWriteTypeOfSymbol(symbol) : getNonMissingTypeOfSymbol(symbol);
  }
  function getControlFlowContainer(node) {
    return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === SyntaxKind.ModuleBlock || node2.kind === SyntaxKind.SourceFile || node2.kind === SyntaxKind.PropertyDeclaration);
  }
  function isSymbolAssigned(symbol) {
    return !isPastLastAssignment(
      symbol,
      /*location*/
      void 0
    );
  }
  function isPastLastAssignment(symbol, location) {
    const parent = findAncestor(symbol.valueDeclaration, isFunctionOrSourceFile);
    if (!parent) {
      return false;
    }
    const links = getNodeLinks(parent);
    if (!(links.flags & NodeCheckFlags.AssignmentsMarked)) {
      links.flags |= NodeCheckFlags.AssignmentsMarked;
      if (!hasParentWithAssignmentsMarked(parent)) {
        markNodeAssignments(parent);
      }
    }
    return !symbol.lastAssignmentPos || location && symbol.lastAssignmentPos < location.pos;
  }
  function isSomeSymbolAssigned(rootDeclaration) {
    Debug.assert(isVariableDeclaration(rootDeclaration) || isParameter(rootDeclaration));
    return isSomeSymbolAssignedWorker(rootDeclaration.name);
  }
  function isSomeSymbolAssignedWorker(node) {
    if (node.kind === SyntaxKind.Identifier) {
      return isSymbolAssigned(getSymbolOfDeclaration(node.parent));
    }
    return some(node.elements, (e) => e.kind !== SyntaxKind.OmittedExpression && isSomeSymbolAssignedWorker(e.name));
  }
  function hasParentWithAssignmentsMarked(node) {
    return !!findAncestor(node.parent, (node2) => isFunctionOrSourceFile(node2) && !!(getNodeLinks(node2).flags & NodeCheckFlags.AssignmentsMarked));
  }
  function isFunctionOrSourceFile(node) {
    return isFunctionLikeDeclaration(node) || isSourceFile(node);
  }
  function markNodeAssignments(node) {
    switch (node.kind) {
      case SyntaxKind.Identifier:
        if (isAssignmentTarget(node)) {
          const symbol = getResolvedSymbol(node);
          if (isParameterOrMutableLocalVariable(symbol) && symbol.lastAssignmentPos !== Number.MAX_VALUE) {
            const referencingFunction = findAncestor(node, isFunctionOrSourceFile);
            const declaringFunction = findAncestor(symbol.valueDeclaration, isFunctionOrSourceFile);
            symbol.lastAssignmentPos = referencingFunction === declaringFunction ? extendAssignmentPosition(node, symbol.valueDeclaration) : Number.MAX_VALUE;
          }
        }
        return;
      case SyntaxKind.ExportSpecifier:
        const exportDeclaration = node.parent.parent;
        const name = node.propertyName || node.name;
        if (!node.isTypeOnly && !exportDeclaration.isTypeOnly && !exportDeclaration.moduleSpecifier && name.kind !== SyntaxKind.StringLiteral) {
          const symbol = resolveEntityName(
            name,
            SymbolFlags.Value,
            /*ignoreErrors*/
            true,
            /*dontResolveAlias*/
            true
          );
          if (symbol && isParameterOrMutableLocalVariable(symbol)) {
            symbol.lastAssignmentPos = Number.MAX_VALUE;
          }
        }
        return;
      case SyntaxKind.InterfaceDeclaration:
      case SyntaxKind.TypeAliasDeclaration:
      case SyntaxKind.EnumDeclaration:
        return;
    }
    if (isTypeNode(node)) {
      return;
    }
    forEachChild(node, markNodeAssignments);
  }
  function extendAssignmentPosition(node, declaration) {
    let pos = node.pos;
    while (node && node.pos > declaration.pos) {
      switch (node.kind) {
        case SyntaxKind.VariableStatement:
        case SyntaxKind.ExpressionStatement:
        case SyntaxKind.IfStatement:
        case SyntaxKind.DoStatement:
        case SyntaxKind.WhileStatement:
        case SyntaxKind.ForStatement:
        case SyntaxKind.ForInStatement:
        case SyntaxKind.ForOfStatement:
        case SyntaxKind.WithStatement:
        case SyntaxKind.SwitchStatement:
        case SyntaxKind.TryStatement:
        case SyntaxKind.ClassDeclaration:
          pos = node.end;
      }
      node = node.parent;
    }
    return pos;
  }
  function isConstantVariable(symbol) {
    return symbol.flags & SymbolFlags.Variable && (getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Constant) !== 0;
  }
  function isParameterOrMutableLocalVariable(symbol) {
    const declaration = symbol.valueDeclaration && getRootDeclaration(symbol.valueDeclaration);
    return !!declaration && (isParameter(declaration) || isVariableDeclaration(declaration) && (isCatchClause(declaration.parent) || isMutableLocalVariableDeclaration(declaration)));
  }
  function isMutableLocalVariableDeclaration(declaration) {
    return !!(declaration.parent.flags & NodeFlags.Let) && !(getCombinedModifierFlags(declaration) & ModifierFlags.Export || declaration.parent.parent.kind === SyntaxKind.VariableStatement && isGlobalSourceFile(declaration.parent.parent.parent));
  }
  function parameterInitializerContainsUndefined(declaration) {
    const links = getNodeLinks(declaration);
    if (links.parameterInitializerContainsUndefined === void 0) {
      if (!pushTypeResolution(declaration, 8 /* ParameterInitializerContainsUndefined */)) {
        reportCircularityError(declaration.symbol);
        return true;
      }
      const containsUndefined = !!hasTypeFacts(checkDeclarationInitializer(declaration, 0 /* Normal */), 16777216 /* IsUndefined */);
      if (!popTypeResolution()) {
        reportCircularityError(declaration.symbol);
        return true;
      }
      links.parameterInitializerContainsUndefined ??= containsUndefined;
    }
    return links.parameterInitializerContainsUndefined;
  }
  function removeOptionalityFromDeclaredType(declaredType, declaration) {
    const removeUndefined = strictNullChecks && declaration.kind === SyntaxKind.Parameter && declaration.initializer && hasTypeFacts(declaredType, 16777216 /* IsUndefined */) && !parameterInitializerContainsUndefined(declaration);
    return removeUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
  }
  function isConstraintPosition(type, node) {
    const parent = node.parent;
    return parent.kind === SyntaxKind.PropertyAccessExpression || parent.kind === SyntaxKind.QualifiedName || parent.kind === SyntaxKind.CallExpression && parent.expression === node || parent.kind === SyntaxKind.NewExpression && parent.expression === node || parent.kind === SyntaxKind.ElementAccessExpression && parent.expression === node && !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression)));
  }
  function isGenericTypeWithUnionConstraint(type) {
    return type.flags & TypeFlags.Intersection ? some(type.types, isGenericTypeWithUnionConstraint) : !!(type.flags & TypeFlags.Instantiable && getBaseConstraintOrType(type).flags & (TypeFlags.Nullable | TypeFlags.Union));
  }
  function isGenericTypeWithoutNullableConstraint(type) {
    return type.flags & TypeFlags.Intersection ? some(type.types, isGenericTypeWithoutNullableConstraint) : !!(type.flags & TypeFlags.Instantiable && !maybeTypeOfKind(getBaseConstraintOrType(type), TypeFlags.Nullable));
  }
  function hasContextualTypeWithNoGenericTypes(node, checkMode) {
    const contextualType = (isIdentifier(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node)) && !((isJsxOpeningElement(node.parent) || isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 32 /* RestBindingElement */ ? getContextualType(node, ContextFlags.SkipBindingPatterns) : getContextualType(
      node,
      /*contextFlags*/
      void 0
    ));
    return contextualType && !isGenericType(contextualType);
  }
  function getNarrowableTypeForReference(type, reference, checkMode) {
    if (isNoInferType(type)) {
      type = type.baseType;
    }
    const substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode));
    return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type;
  }
  function isExportOrExportExpression(location) {
    return !!findAncestor(location, (n) => {
      const parent = n.parent;
      if (parent === void 0) {
        return "quit";
      }
      if (isExportAssignment(parent)) {
        return parent.expression === n && isEntityNameExpression(n);
      }
      if (isExportSpecifier(parent)) {
        return parent.name === n || parent.propertyName === n;
      }
      return false;
    });
  }
  function markLinkedReferences(location, hint, propSymbol, parentType) {
    if (!canCollectSymbolAliasAccessabilityData) {
      return;
    }
    if (location.flags & NodeFlags.Ambient && !isPropertySignature(location) && !isPropertyDeclaration(location)) {
      return;
    }
    switch (hint) {
      case 1 /* Identifier */:
        return markIdentifierAliasReferenced(location);
      case 2 /* Property */:
        return markPropertyAliasReferenced(location, propSymbol, parentType);
      case 3 /* ExportAssignment */:
        return markExportAssignmentAliasReferenced(location);
      case 4 /* Jsx */:
        return markJsxAliasReferenced(location);
      case 5 /* AsyncFunction */:
        return markAsyncFunctionAliasReferenced(location);
      case 6 /* ExportImportEquals */:
        return markImportEqualsAliasReferenced(location);
      case 7 /* ExportSpecifier */:
        return markExportSpecifierAliasReferenced(location);
      case 8 /* Decorator */:
        return markDecoratorAliasReferenced(location);
      case 0 /* Unspecified */: {
        if (isIdentifier(location) && (isExpressionNode(location) || isShorthandPropertyAssignment(location.parent) || isImportEqualsDeclaration(location.parent) && location.parent.moduleReference === location) && shouldMarkIdentifierAliasReferenced(location)) {
          if (isPropertyAccessOrQualifiedName(location.parent)) {
            const left = isPropertyAccessExpression(location.parent) ? location.parent.expression : location.parent.left;
            if (left !== location) return;
          }
          markIdentifierAliasReferenced(location);
          return;
        }
        if (isPropertyAccessOrQualifiedName(location)) {
          let topProp = location;
          while (isPropertyAccessOrQualifiedName(topProp)) {
            if (isPartOfTypeNode(topProp)) return;
            topProp = topProp.parent;
          }
          return markPropertyAliasReferenced(location);
        }
        if (isExportAssignment(location)) {
          return markExportAssignmentAliasReferenced(location);
        }
        if (isJsxOpeningLikeElement(location) || isJsxOpeningFragment(location)) {
          return markJsxAliasReferenced(location);
        }
        if (isImportEqualsDeclaration(location)) {
          if (isInternalModuleImportEqualsDeclaration(location) || checkExternalImportOrExportDeclaration(location)) {
            return markImportEqualsAliasReferenced(location);
          }
          return;
        }
        if (isExportSpecifier(location)) {
          return markExportSpecifierAliasReferenced(location);
        }
        if (isFunctionLikeDeclaration(location) || isMethodSignature(location)) {
          markAsyncFunctionAliasReferenced(location);
        }
        if (!compilerOptions.emitDecoratorMetadata) {
          return;
        }
        if (!canHaveDecorators(location) || !hasDecorators(location) || !location.modifiers || !nodeCanBeDecorated(legacyDecorators, location, location.parent, location.parent.parent)) {
          return;
        }
        return markDecoratorAliasReferenced(location);
      }
      default:
        Debug.assertNever(hint, `Unhandled reference hint: ${hint}`);
    }
  }
  function markIdentifierAliasReferenced(location) {
    const symbol = getResolvedSymbol(location);
    if (symbol && symbol !== argumentsSymbol && symbol !== unknownSymbol && !isThisInTypeQuery(location)) {
      markAliasReferenced(symbol, location);
    }
  }
  function markPropertyAliasReferenced(location, propSymbol, parentType) {
    const left = isPropertyAccessExpression(location) ? location.expression : location.left;
    if (isThisIdentifier(left) || !isIdentifier(left)) {
      return;
    }
    const parentSymbol = getResolvedSymbol(left);
    if (!parentSymbol || parentSymbol === unknownSymbol) {
      return;
    }
    if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location)) {
      markAliasReferenced(parentSymbol, location);
      return;
    }
    const leftType = parentType || checkExpressionCached(left);
    if (isTypeAny(leftType) || leftType === silentNeverType) {
      markAliasReferenced(parentSymbol, location);
      return;
    }
    let prop = propSymbol;
    if (!prop && !parentType) {
      const right = isPropertyAccessExpression(location) ? location.name : location.right;
      const lexicallyScopedSymbol = isPrivateIdentifier(right) && lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
      const assignmentKind = getAssignmentTargetKind(location);
      const apparentType = getApparentType(assignmentKind !== AssignmentKind.None || isMethodAccessForCall(location) ? getWidenedType(leftType) : leftType);
      prop = isPrivateIdentifier(right) ? lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(apparentType, lexicallyScopedSymbol) || void 0 : getPropertyOfType(apparentType, right.escapedText);
    }
    if (!(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & SymbolFlags.EnumMember && location.parent.kind === SyntaxKind.EnumMember))) {
      markAliasReferenced(parentSymbol, location);
    }
    return;
  }
  function markExportAssignmentAliasReferenced(location) {
    if (isIdentifier(location.expression)) {
      const id = location.expression;
      const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName(
        id,
        SymbolFlags.All,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true,
        location
      ));
      if (sym) {
        markAliasReferenced(sym, id);
      }
    }
  }
  function markJsxAliasReferenced(node) {
    if (!getJsxNamespaceContainerForImplicitImport(node)) {
      const jsxFactoryRefErr = diagnostics && compilerOptions.jsx === JsxEmit.React ? Diagnostics.Cannot_find_name_0 : void 0;
      const jsxFactoryNamespace = getJsxNamespace(node);
      const jsxFactoryLocation = isJsxOpeningLikeElement(node) ? node.tagName : node;
      let jsxFactorySym;
      if (!(isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) {
        jsxFactorySym = resolveName(
          jsxFactoryLocation,
          jsxFactoryNamespace,
          SymbolFlags.Value,
          jsxFactoryRefErr,
          /*isUse*/
          true
        );
      }
      if (jsxFactorySym) {
        jsxFactorySym.isReferenced = SymbolFlags.All;
        if (canCollectSymbolAliasAccessabilityData && jsxFactorySym.flags & SymbolFlags.Alias && !getTypeOnlyAliasDeclaration(jsxFactorySym)) {
          markAliasSymbolAsReferenced(jsxFactorySym);
        }
      }
      if (isJsxOpeningFragment(node)) {
        const file = getSourceFileOfNode(node);
        const localJsxNamespace = getLocalJsxNamespace(file);
        if (localJsxNamespace) {
          resolveName(
            jsxFactoryLocation,
            localJsxNamespace,
            SymbolFlags.Value,
            jsxFactoryRefErr,
            /*isUse*/
            true
          );
        }
      }
    }
    return;
  }
  function markAsyncFunctionAliasReferenced(location) {
    if (languageVersion < ScriptTarget.ES2015) {
      if (getFunctionFlags(location) & FunctionFlags.Async) {
        const returnTypeNode = getEffectiveReturnTypeNode(location);
        markTypeNodeAsReferenced(returnTypeNode);
      }
    }
  }
  function markImportEqualsAliasReferenced(location) {
    if (hasSyntacticModifier(location, ModifierFlags.Export)) {
      markExportAsReferenced(location);
    }
  }
  function markExportSpecifierAliasReferenced(location) {
    if (!location.parent.parent.moduleSpecifier && !location.isTypeOnly && !location.parent.parent.isTypeOnly) {
      const exportedName = location.propertyName || location.name;
      if (exportedName.kind === SyntaxKind.StringLiteral) {
        return;
      }
      const symbol = resolveName(
        exportedName,
        exportedName.escapedText,
        SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        true
      );
      if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
      } else {
        const target = symbol && (symbol.flags & SymbolFlags.Alias ? resolveAlias(symbol) : symbol);
        if (!target || getSymbolFlags(target) & SymbolFlags.Value) {
          markExportAsReferenced(location);
          markIdentifierAliasReferenced(exportedName);
        }
      }
      return;
    }
  }
  function markDecoratorAliasReferenced(node) {
    if (compilerOptions.emitDecoratorMetadata) {
      const firstDecorator = find(node.modifiers, isDecorator);
      if (!firstDecorator) {
        return;
      }
      checkExternalEmitHelpers(firstDecorator, ExternalEmitHelpers.Metadata);
      switch (node.kind) {
        case SyntaxKind.ClassDeclaration:
          const constructor = getFirstConstructorWithBody(node);
          if (constructor) {
            for (const parameter of constructor.parameters) {
              markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
            }
          }
          break;
        case SyntaxKind.GetAccessor:
        case SyntaxKind.SetAccessor:
          const otherKind = node.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor;
          const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(node), otherKind);
          markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
          break;
        case SyntaxKind.MethodDeclaration:
          for (const parameter of node.parameters) {
            markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
          }
          markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(node));
          break;
        case SyntaxKind.PropertyDeclaration:
          markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveTypeAnnotationNode(node));
          break;
        case SyntaxKind.Parameter:
          markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
          const containingSignature = node.parent;
          for (const parameter of containingSignature.parameters) {
            markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
          }
          markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature));
          break;
      }
    }
  }
  function markAliasReferenced(symbol, location) {
    if (!canCollectSymbolAliasAccessabilityData) {
      return;
    }
    if (isNonLocalAlias(
      symbol,
      /*excludes*/
      SymbolFlags.Value
    ) && !isInTypeQuery(location)) {
      const target = resolveAlias(symbol);
      if (getSymbolFlags(
        symbol,
        /*excludeTypeOnlyMeanings*/
        true
      ) & (SymbolFlags.Value | SymbolFlags.ExportValue)) {
        if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) {
          markAliasSymbolAsReferenced(symbol);
        }
      }
    }
  }
  function markAliasSymbolAsReferenced(symbol) {
    Debug.assert(canCollectSymbolAliasAccessabilityData);
    const links = getSymbolLinks(symbol);
    if (!links.referenced) {
      links.referenced = true;
      const node = getDeclarationOfAliasSymbol(symbol);
      if (!node) return Debug.fail();
      if (isInternalModuleImportEqualsDeclaration(node)) {
        if (getSymbolFlags(resolveSymbol(symbol)) & SymbolFlags.Value) {
          const left = getFirstIdentifier(node.moduleReference);
          markIdentifierAliasReferenced(left);
        }
      }
    }
  }
  function markExportAsReferenced(node) {
    const symbol = getSymbolOfDeclaration(node);
    const target = resolveAlias(symbol);
    if (target) {
      const markAlias = target === unknownSymbol || getSymbolFlags(
        symbol,
        /*excludeTypeOnlyMeanings*/
        true
      ) & SymbolFlags.Value && !isConstEnumOrConstEnumOnlyModule(target);
      if (markAlias) {
        markAliasSymbolAsReferenced(symbol);
      }
    }
  }
  function markEntityNameOrEntityExpressionAsReference(typeName, forDecoratorMetadata) {
    if (!typeName) return;
    const rootName = getFirstIdentifier(typeName);
    const meaning = (typeName.kind === SyntaxKind.Identifier ? SymbolFlags.Type : SymbolFlags.Namespace) | SymbolFlags.Alias;
    const rootSymbol = resolveName(
      rootName,
      rootName.escapedText,
      meaning,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
    if (rootSymbol && rootSymbol.flags & SymbolFlags.Alias) {
      if (canCollectSymbolAliasAccessabilityData && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) && !getTypeOnlyAliasDeclaration(rootSymbol)) {
        markAliasSymbolAsReferenced(rootSymbol);
      } else if (forDecoratorMetadata && getIsolatedModules(compilerOptions) && getEmitModuleKind(compilerOptions) >= ModuleKind.ES2015 && !symbolIsValue(rootSymbol) && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) {
        const diag = error(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled);
        const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration);
        if (aliasDeclaration) {
          addRelatedInfo(diag, createDiagnosticForNode(aliasDeclaration, Diagnostics._0_was_imported_here, idText(rootName)));
        }
      }
    }
  }
  function markTypeNodeAsReferenced(node) {
    markEntityNameOrEntityExpressionAsReference(
      node && getEntityNameFromTypeNode(node),
      /*forDecoratorMetadata*/
      false
    );
  }
  function markDecoratorMedataDataTypeNodeAsReferenced(node) {
    const entityName = getEntityNameForDecoratorMetadata(node);
    if (entityName && isEntityName(entityName)) {
      markEntityNameOrEntityExpressionAsReference(
        entityName,
        /*forDecoratorMetadata*/
        true
      );
    }
  }
  function getNarrowedTypeOfSymbol(symbol, location) {
    const type = getTypeOfSymbol(symbol);
    const declaration = symbol.valueDeclaration;
    if (declaration) {
      if (isBindingElement(declaration) && !declaration.initializer && !declaration.dotDotDotToken && declaration.parent.elements.length >= 2) {
        const parent = declaration.parent.parent;
        const rootDeclaration = getRootDeclaration(parent);
        if (rootDeclaration.kind === SyntaxKind.VariableDeclaration && getCombinedNodeFlagsCached(rootDeclaration) & NodeFlags.Constant || rootDeclaration.kind === SyntaxKind.Parameter) {
          const links = getNodeLinks(parent);
          if (!(links.flags & NodeCheckFlags.InCheckIdentifier)) {
            links.flags |= NodeCheckFlags.InCheckIdentifier;
            const parentType = getTypeForBindingElementParent(parent, 0 /* Normal */);
            const parentTypeConstraint = parentType && mapType(parentType, getBaseConstraintOrType);
            links.flags &= ~NodeCheckFlags.InCheckIdentifier;
            if (parentTypeConstraint && parentTypeConstraint.flags & TypeFlags.Union && !(rootDeclaration.kind === SyntaxKind.Parameter && isSomeSymbolAssigned(rootDeclaration))) {
              const pattern = declaration.parent;
              const narrowedType = getFlowTypeOfReference(
                pattern,
                parentTypeConstraint,
                parentTypeConstraint,
                /*flowContainer*/
                void 0,
                location.flowNode
              );
              if (narrowedType.flags & TypeFlags.Never) {
                return neverType;
              }
              return getBindingElementTypeFromParentType(
                declaration,
                narrowedType,
                /*noTupleBoundsCheck*/
                true
              );
            }
          }
        }
      }
      if (isParameter(declaration) && !declaration.type && !declaration.initializer && !declaration.dotDotDotToken) {
        const func = declaration.parent;
        if (func.parameters.length >= 2 && isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
          const contextualSignature = getContextualSignature(func);
          if (contextualSignature && contextualSignature.parameters.length === 1 && signatureHasRestParameter(contextualSignature)) {
            const restType = getReducedApparentType(instantiateType(getTypeOfSymbol(contextualSignature.parameters[0]), getInferenceContext(func)?.nonFixingMapper));
            if (restType.flags & TypeFlags.Union && everyType(restType, isTupleType) && !some(func.parameters, isSomeSymbolAssigned)) {
              const narrowedType = getFlowTypeOfReference(
                func,
                restType,
                restType,
                /*flowContainer*/
                void 0,
                location.flowNode
              );
              const index = func.parameters.indexOf(declaration) - (getThisParameter(func) ? 1 : 0);
              return getIndexedAccessType(narrowedType, getNumberLiteralType(index));
            }
          }
        }
      }
    }
    return type;
  }
  function checkIdentifierCalculateNodeCheckFlags(node, symbol) {
    if (isThisInTypeQuery(node)) return;
    if (symbol === argumentsSymbol) {
      if (isInPropertyInitializerOrClassStaticBlock(node)) {
        error(node, Diagnostics.arguments_cannot_be_referenced_in_property_initializers);
        return;
      }
      let container = getContainingFunction(node);
      if (container) {
        if (languageVersion < ScriptTarget.ES2015) {
          if (container.kind === SyntaxKind.ArrowFunction) {
            error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_function_expression);
          } else if (hasSyntacticModifier(container, ModifierFlags.Async)) {
            error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_standard_function_or_method);
          }
        }
        getNodeLinks(container).flags |= NodeCheckFlags.CaptureArguments;
        while (container && isArrowFunction(container)) {
          container = getContainingFunction(container);
          if (container) {
            getNodeLinks(container).flags |= NodeCheckFlags.CaptureArguments;
          }
        }
      }
      return;
    }
    const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
    const targetSymbol = resolveAliasWithDeprecationCheck(localOrExportSymbol, node);
    if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) {
      addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText);
    }
    const declaration = localOrExportSymbol.valueDeclaration;
    if (declaration && localOrExportSymbol.flags & SymbolFlags.Class) {
      if (isClassLike(declaration) && declaration.name !== node) {
        let container = getThisContainer(
          node,
          /*includeArrowFunctions*/
          false,
          /*includeClassComputedPropertyName*/
          false
        );
        while (container.kind !== SyntaxKind.SourceFile && container.parent !== declaration) {
          container = getThisContainer(
            container,
            /*includeArrowFunctions*/
            false,
            /*includeClassComputedPropertyName*/
            false
          );
        }
        if (container.kind !== SyntaxKind.SourceFile) {
          getNodeLinks(declaration).flags |= NodeCheckFlags.ContainsConstructorReference;
          getNodeLinks(container).flags |= NodeCheckFlags.ContainsConstructorReference;
          getNodeLinks(node).flags |= NodeCheckFlags.ConstructorReference;
        }
      }
    }
    checkNestedBlockScopedBinding(node, symbol);
  }
  function checkIdentifier(node, checkMode) {
    if (isThisInTypeQuery(node)) {
      return checkThisExpression(node);
    }
    const symbol = getResolvedSymbol(node);
    if (symbol === unknownSymbol) {
      return errorType;
    }
    checkIdentifierCalculateNodeCheckFlags(node, symbol);
    if (symbol === argumentsSymbol) {
      if (isInPropertyInitializerOrClassStaticBlock(node)) {
        return errorType;
      }
      return getTypeOfSymbol(symbol);
    }
    if (shouldMarkIdentifierAliasReferenced(node)) {
      markLinkedReferences(node, 1 /* Identifier */);
    }
    const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
    let declaration = localOrExportSymbol.valueDeclaration;
    if (declaration && declaration.kind === SyntaxKind.BindingElement && contains(contextualBindingPatterns, declaration.parent) && findAncestor(node, (parent) => parent === declaration.parent)) {
      return nonInferrableAnyType;
    }
    let type = getNarrowedTypeOfSymbol(localOrExportSymbol, node);
    const assignmentKind = getAssignmentTargetKind(node);
    if (assignmentKind) {
      if (!(localOrExportSymbol.flags & SymbolFlags.Variable) && !(isInJSFile(node) && localOrExportSymbol.flags & SymbolFlags.ValueModule)) {
        const assignmentError = localOrExportSymbol.flags & SymbolFlags.Enum ? Diagnostics.Cannot_assign_to_0_because_it_is_an_enum : localOrExportSymbol.flags & SymbolFlags.Class ? Diagnostics.Cannot_assign_to_0_because_it_is_a_class : localOrExportSymbol.flags & SymbolFlags.Module ? Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace : localOrExportSymbol.flags & SymbolFlags.Function ? Diagnostics.Cannot_assign_to_0_because_it_is_a_function : localOrExportSymbol.flags & SymbolFlags.Alias ? Diagnostics.Cannot_assign_to_0_because_it_is_an_import : Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable;
        error(node, assignmentError, symbolToString(symbol));
        return errorType;
      }
      if (isReadonlySymbol(localOrExportSymbol)) {
        if (localOrExportSymbol.flags & SymbolFlags.Variable) {
          error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
        } else {
          error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
        }
        return errorType;
      }
    }
    const isAlias = localOrExportSymbol.flags & SymbolFlags.Alias;
    if (localOrExportSymbol.flags & SymbolFlags.Variable) {
      if (assignmentKind === AssignmentKind.Definite) {
        return isInCompoundLikeAssignment(node) ? getBaseTypeOfLiteralType(type) : type;
      }
    } else if (isAlias) {
      declaration = getDeclarationOfAliasSymbol(symbol);
    } else {
      return type;
    }
    if (!declaration) {
      return type;
    }
    type = getNarrowableTypeForReference(type, node, checkMode);
    const isParameter2 = getRootDeclaration(declaration).kind === SyntaxKind.Parameter;
    const declarationContainer = getControlFlowContainer(declaration);
    let flowContainer = getControlFlowContainer(node);
    const isOuterVariable = flowContainer !== declarationContainer;
    const isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
    const isModuleExports = symbol.flags & SymbolFlags.ModuleExports;
    const typeIsAutomatic = type === autoType || type === autoArrayType;
    const isAutomaticTypeInNonNull = typeIsAutomatic && node.parent.kind === SyntaxKind.NonNullExpression;
    while (flowContainer !== declarationContainer && (flowContainer.kind === SyntaxKind.FunctionExpression || flowContainer.kind === SyntaxKind.ArrowFunction || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstantVariable(localOrExportSymbol) && type !== autoArrayType || isParameterOrMutableLocalVariable(localOrExportSymbol) && isPastLastAssignment(localOrExportSymbol, node))) {
      flowContainer = getControlFlowContainer(flowContainer);
    }
    const assumeInitialized = isParameter2 || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Void)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === SyntaxKind.ExportSpecifier) || node.parent.kind === SyntaxKind.NonNullExpression || declaration.kind === SyntaxKind.VariableDeclaration && declaration.exclamationToken || declaration.flags & NodeFlags.Ambient;
    const initialType = isAutomaticTypeInNonNull ? undefinedType : assumeInitialized ? isParameter2 ? removeOptionalityFromDeclaredType(type, declaration) : type : typeIsAutomatic ? undefinedType : getOptionalType(type);
    const flowType = isAutomaticTypeInNonNull ? getNonNullableType(getFlowTypeOfReference(node, type, initialType, flowContainer)) : getFlowTypeOfReference(node, type, initialType, flowContainer);
    if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
      if (flowType === autoType || flowType === autoArrayType) {
        if (noImplicitAny) {
          error(getNameOfDeclaration(declaration), Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType));
          error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
        }
        return convertAutoToAny(flowType);
      }
    } else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) {
      error(node, Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
      return type;
    }
    return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
  }
  function isSameScopedBindingElement(node, declaration) {
    if (isBindingElement(declaration)) {
      const bindingElement = findAncestor(node, isBindingElement);
      return bindingElement && getRootDeclaration(bindingElement) === getRootDeclaration(declaration);
    }
  }
  function shouldMarkIdentifierAliasReferenced(node) {
    const parent = node.parent;
    if (parent) {
      if (isPropertyAccessExpression(parent) && parent.expression === node) {
        return false;
      }
      if (isExportSpecifier(parent) && parent.isTypeOnly) {
        return false;
      }
      const greatGrandparent = parent.parent?.parent;
      if (greatGrandparent && isExportDeclaration(greatGrandparent) && greatGrandparent.isTypeOnly) {
        return false;
      }
    }
    return true;
  }
  function isInsideFunctionOrInstancePropertyInitializer(node, threshold) {
    return !!findAncestor(node, (n) => n === threshold ? "quit" : isFunctionLike(n) || n.parent && isPropertyDeclaration(n.parent) && !hasStaticModifier(n.parent) && n.parent.initializer === n);
  }
  function getPartOfForStatementContainingNode(node, container) {
    return findAncestor(node, (n) => n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement);
  }
  function getEnclosingIterationStatement(node) {
    return findAncestor(node, (n) => !n || nodeStartsNewLexicalEnvironment(n) ? "quit" : isIterationStatement(
      n,
      /*lookInLabeledStatements*/
      false
    ));
  }
  function checkNestedBlockScopedBinding(node, symbol) {
    if (languageVersion >= ScriptTarget.ES2015 || (symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.Class)) === 0 || !symbol.valueDeclaration || isSourceFile(symbol.valueDeclaration) || symbol.valueDeclaration.parent.kind === SyntaxKind.CatchClause) {
      return;
    }
    const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration);
    const isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container);
    const enclosingIterationStatement = getEnclosingIterationStatement(container);
    if (enclosingIterationStatement) {
      if (isCaptured) {
        let capturesBlockScopeBindingInLoopBody = true;
        if (isForStatement(container)) {
          const varDeclList = getAncestor(symbol.valueDeclaration, SyntaxKind.VariableDeclarationList);
          if (varDeclList && varDeclList.parent === container) {
            const part = getPartOfForStatementContainingNode(node.parent, container);
            if (part) {
              const links = getNodeLinks(part);
              links.flags |= NodeCheckFlags.ContainsCapturedBlockScopeBinding;
              const capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
              pushIfUnique(capturedBindings, symbol);
              if (part === container.initializer) {
                capturesBlockScopeBindingInLoopBody = false;
              }
            }
          }
        }
        if (capturesBlockScopeBindingInLoopBody) {
          getNodeLinks(enclosingIterationStatement).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding;
        }
      }
      if (isForStatement(container)) {
        const varDeclList = getAncestor(symbol.valueDeclaration, SyntaxKind.VariableDeclarationList);
        if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
          getNodeLinks(symbol.valueDeclaration).flags |= NodeCheckFlags.NeedsLoopOutParameter;
        }
      }
      getNodeLinks(symbol.valueDeclaration).flags |= NodeCheckFlags.BlockScopedBindingInLoop;
    }
    if (isCaptured) {
      getNodeLinks(symbol.valueDeclaration).flags |= NodeCheckFlags.CapturedBlockScopedBinding;
    }
  }
  function isBindingCapturedByNode(node, decl) {
    const links = getNodeLinks(node);
    return !!links && contains(links.capturedBlockScopeBindings, getSymbolOfDeclaration(decl));
  }
  function isAssignedInBodyOfForStatement(node, container) {
    let current = node;
    while (current.parent.kind === SyntaxKind.ParenthesizedExpression) {
      current = current.parent;
    }
    let isAssigned = false;
    if (isAssignmentTarget(current)) {
      isAssigned = true;
    } else if (current.parent.kind === SyntaxKind.PrefixUnaryExpression || current.parent.kind === SyntaxKind.PostfixUnaryExpression) {
      const expr = current.parent;
      isAssigned = expr.operator === SyntaxKind.PlusPlusToken || expr.operator === SyntaxKind.MinusMinusToken;
    }
    if (!isAssigned) {
      return false;
    }
    return !!findAncestor(current, (n) => n === container ? "quit" : n === container.statement);
  }
  function captureLexicalThis(node, container) {
    getNodeLinks(node).flags |= NodeCheckFlags.LexicalThis;
    if (container.kind === SyntaxKind.PropertyDeclaration || container.kind === SyntaxKind.Constructor) {
      const classNode = container.parent;
      getNodeLinks(classNode).flags |= NodeCheckFlags.CaptureThis;
    } else {
      getNodeLinks(container).flags |= NodeCheckFlags.CaptureThis;
    }
  }
  function findFirstSuperCall(node) {
    return isSuperCall(node) ? node : isFunctionLike(node) ? void 0 : forEachChild(node, findFirstSuperCall);
  }
  function classDeclarationExtendsNull(classDecl) {
    const classSymbol = getSymbolOfDeclaration(classDecl);
    const classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
    const baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
    return baseConstructorType === nullWideningType;
  }
  function checkThisBeforeSuper(node, container, diagnosticMessage) {
    const containingClassDecl = container.parent;
    const baseTypeNode = getClassExtendsHeritageElement(containingClassDecl);
    if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
      if (canHaveFlowNode(node) && node.flowNode && !isPostSuperFlowNode(
        node.flowNode,
        /*noCacheCheck*/
        false
      )) {
        error(node, diagnosticMessage);
      }
    }
  }
  function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) {
    if (isPropertyDeclaration(container) && hasStaticModifier(container) && legacyDecorators && container.initializer && textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && hasDecorators(container.parent)) {
      error(thisExpression, Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class);
    }
  }
  function checkThisExpression(node) {
    const isNodeInTypeQuery = isInTypeQuery(node);
    let container = getThisContainer(
      node,
      /*includeArrowFunctions*/
      true,
      /*includeClassComputedPropertyName*/
      true
    );
    let capturedByArrowFunction = false;
    let thisInComputedPropertyName = false;
    if (container.kind === SyntaxKind.Constructor) {
      checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
    }
    while (true) {
      if (container.kind === SyntaxKind.ArrowFunction) {
        container = getThisContainer(
          container,
          /*includeArrowFunctions*/
          false,
          !thisInComputedPropertyName
        );
        capturedByArrowFunction = true;
      }
      if (container.kind === SyntaxKind.ComputedPropertyName) {
        container = getThisContainer(
          container,
          !capturedByArrowFunction,
          /*includeClassComputedPropertyName*/
          false
        );
        thisInComputedPropertyName = true;
        continue;
      }
      break;
    }
    checkThisInStaticClassFieldInitializerInDecoratedClass(node, container);
    if (thisInComputedPropertyName) {
      error(node, Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
    } else {
      switch (container.kind) {
        case SyntaxKind.ModuleDeclaration:
          error(node, Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
          break;
        case SyntaxKind.EnumDeclaration:
          error(node, Diagnostics.this_cannot_be_referenced_in_current_location);
          break;
      }
    }
    if (!isNodeInTypeQuery && capturedByArrowFunction && languageVersion < ScriptTarget.ES2015) {
      captureLexicalThis(node, container);
    }
    const type = tryGetThisTypeAt(
      node,
      /*includeGlobalThis*/
      true,
      container
    );
    if (noImplicitThis) {
      const globalThisType2 = getTypeOfSymbol(globalThisSymbol);
      if (type === globalThisType2 && capturedByArrowFunction) {
        error(node, Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
      } else if (!type) {
        const diag = error(node, Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
        if (!isSourceFile(container)) {
          const outsideThis = tryGetThisTypeAt(container);
          if (outsideThis && outsideThis !== globalThisType2) {
            addRelatedInfo(diag, createDiagnosticForNode(container, Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
          }
        }
      }
    }
    return type || anyType;
  }
  function tryGetThisTypeAt(node, includeGlobalThis = true, container = getThisContainer(
    node,
    /*includeArrowFunctions*/
    false,
    /*includeClassComputedPropertyName*/
    false
  )) {
    const isInJS = isInJSFile(node);
    if (isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || getThisParameter(container))) {
      let thisType = getThisTypeOfDeclaration(container) || isInJS && getTypeForThisExpressionFromJSDoc(container);
      if (!thisType) {
        const className = getClassNameFromPrototypeMethod(container);
        if (isInJS && className) {
          const classSymbol = checkExpression(className).symbol;
          if (classSymbol && classSymbol.members && classSymbol.flags & SymbolFlags.Function) {
            thisType = getDeclaredTypeOfSymbol(classSymbol).thisType;
          }
        } else if (isJSConstructor(container)) {
          thisType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
        }
        thisType ||= getContextualThisParameterType(container);
      }
      if (thisType) {
        return getFlowTypeOfReference(node, thisType);
      }
    }
    if (isClassLike(container.parent)) {
      const symbol = getSymbolOfDeclaration(container.parent);
      const type = isStatic(container) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
      return getFlowTypeOfReference(node, type);
    }
    if (isSourceFile(container)) {
      if (container.commonJsModuleIndicator) {
        const fileSymbol = getSymbolOfDeclaration(container);
        return fileSymbol && getTypeOfSymbol(fileSymbol);
      } else if (container.externalModuleIndicator) {
        return undefinedType;
      } else if (includeGlobalThis) {
        return getTypeOfSymbol(globalThisSymbol);
      }
    }
  }
  function getExplicitThisType(node) {
    const container = getThisContainer(
      node,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    if (isFunctionLike(container)) {
      const signature = getSignatureFromDeclaration(container);
      if (signature.thisParameter) {
        return getExplicitTypeOfSymbol(signature.thisParameter);
      }
    }
    if (isClassLike(container.parent)) {
      const symbol = getSymbolOfDeclaration(container.parent);
      return isStatic(container) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
    }
  }
  function getClassNameFromPrototypeMethod(container) {
    if (container.kind === SyntaxKind.FunctionExpression && isBinaryExpression(container.parent) && getAssignmentDeclarationKind(container.parent) === AssignmentDeclarationKind.PrototypeProperty) {
      return container.parent.left.expression.expression;
    } else if (container.kind === SyntaxKind.MethodDeclaration && container.parent.kind === SyntaxKind.ObjectLiteralExpression && isBinaryExpression(container.parent.parent) && getAssignmentDeclarationKind(container.parent.parent) === AssignmentDeclarationKind.Prototype) {
      return container.parent.parent.left.expression;
    } else if (container.kind === SyntaxKind.FunctionExpression && container.parent.kind === SyntaxKind.PropertyAssignment && container.parent.parent.kind === SyntaxKind.ObjectLiteralExpression && isBinaryExpression(container.parent.parent.parent) && getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.Prototype) {
      return container.parent.parent.parent.left.expression;
    } else if (container.kind === SyntaxKind.FunctionExpression && isPropertyAssignment(container.parent) && isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && isObjectLiteralExpression(container.parent.parent) && isCallExpression(container.parent.parent.parent) && container.parent.parent.parent.arguments[2] === container.parent.parent && getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.ObjectDefinePrototypeProperty) {
      return container.parent.parent.parent.arguments[0].expression;
    } else if (isMethodDeclaration(container) && isIdentifier(container.name) && (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && isObjectLiteralExpression(container.parent) && isCallExpression(container.parent.parent) && container.parent.parent.arguments[2] === container.parent && getAssignmentDeclarationKind(container.parent.parent) === AssignmentDeclarationKind.ObjectDefinePrototypeProperty) {
      return container.parent.parent.arguments[0].expression;
    }
  }
  function getTypeForThisExpressionFromJSDoc(node) {
    const thisTag = getJSDocThisTag(node);
    if (thisTag && thisTag.typeExpression) {
      return getTypeFromTypeNode(thisTag.typeExpression);
    }
    const signature = getSignatureOfTypeTag(node);
    if (signature) {
      return getThisTypeOfSignature(signature);
    }
  }
  function isInConstructorArgumentInitializer(node, constructorDecl) {
    return !!findAncestor(node, (n) => isFunctionLikeDeclaration(n) ? "quit" : n.kind === SyntaxKind.Parameter && n.parent === constructorDecl);
  }
  function checkSuperExpression(node) {
    const isCallExpression2 = node.parent.kind === SyntaxKind.CallExpression && node.parent.expression === node;
    const immediateContainer = getSuperContainer(
      node,
      /*stopOnFunctions*/
      true
    );
    let container = immediateContainer;
    let needToCaptureLexicalThis = false;
    let inAsyncFunction = false;
    if (!isCallExpression2) {
      while (container && container.kind === SyntaxKind.ArrowFunction) {
        if (hasSyntacticModifier(container, ModifierFlags.Async)) inAsyncFunction = true;
        container = getSuperContainer(
          container,
          /*stopOnFunctions*/
          true
        );
        needToCaptureLexicalThis = languageVersion < ScriptTarget.ES2015;
      }
      if (container && hasSyntacticModifier(container, ModifierFlags.Async)) inAsyncFunction = true;
    }
    let nodeCheckFlag = 0;
    if (!container || !isLegalUsageOfSuperExpression(container)) {
      const current = findAncestor(node, (n) => n === container ? "quit" : n.kind === SyntaxKind.ComputedPropertyName);
      if (current && current.kind === SyntaxKind.ComputedPropertyName) {
        error(node, Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
      } else if (isCallExpression2) {
        error(node, Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
      } else if (!container || !container.parent || !(isClassLike(container.parent) || container.parent.kind === SyntaxKind.ObjectLiteralExpression)) {
        error(node, Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
      } else {
        error(node, Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
      }
      return errorType;
    }
    if (!isCallExpression2 && immediateContainer.kind === SyntaxKind.Constructor) {
      checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
    }
    if (isStatic(container) || isCallExpression2) {
      nodeCheckFlag = NodeCheckFlags.SuperStatic;
      if (!isCallExpression2 && languageVersion >= ScriptTarget.ES2015 && languageVersion <= ScriptTarget.ES2021 && (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container))) {
        forEachEnclosingBlockScopeContainer(node.parent, (current) => {
          if (!isSourceFile(current) || isExternalOrCommonJsModule(current)) {
            getNodeLinks(current).flags |= NodeCheckFlags.ContainsSuperPropertyInStaticInitializer;
          }
        });
      }
    } else {
      nodeCheckFlag = NodeCheckFlags.SuperInstance;
    }
    getNodeLinks(node).flags |= nodeCheckFlag;
    if (container.kind === SyntaxKind.MethodDeclaration && inAsyncFunction) {
      if (isSuperProperty(node.parent) && isAssignmentTarget(node.parent)) {
        getNodeLinks(container).flags |= NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync;
      } else {
        getNodeLinks(container).flags |= NodeCheckFlags.MethodWithSuperPropertyAccessInAsync;
      }
    }
    if (needToCaptureLexicalThis) {
      captureLexicalThis(node.parent, container);
    }
    if (container.parent.kind === SyntaxKind.ObjectLiteralExpression) {
      if (languageVersion < ScriptTarget.ES2015) {
        error(node, Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
        return errorType;
      } else {
        return anyType;
      }
    }
    const classLikeDeclaration = container.parent;
    if (!getClassExtendsHeritageElement(classLikeDeclaration)) {
      error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class);
      return errorType;
    }
    if (classDeclarationExtendsNull(classLikeDeclaration)) {
      return isCallExpression2 ? errorType : nullWideningType;
    }
    const classType = getDeclaredTypeOfSymbol(getSymbolOfDeclaration(classLikeDeclaration));
    const baseClassType = classType && getBaseTypes(classType)[0];
    if (!baseClassType) {
      return errorType;
    }
    if (container.kind === SyntaxKind.Constructor && isInConstructorArgumentInitializer(node, container)) {
      error(node, Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
      return errorType;
    }
    return nodeCheckFlag === NodeCheckFlags.SuperStatic ? getBaseConstructorTypeOfClass(classType) : getTypeWithThisArgument(baseClassType, classType.thisType);
    function isLegalUsageOfSuperExpression(container2) {
      if (isCallExpression2) {
        return container2.kind === SyntaxKind.Constructor;
      } else {
        if (isClassLike(container2.parent) || container2.parent.kind === SyntaxKind.ObjectLiteralExpression) {
          if (isStatic(container2)) {
            return container2.kind === SyntaxKind.MethodDeclaration || container2.kind === SyntaxKind.MethodSignature || container2.kind === SyntaxKind.GetAccessor || container2.kind === SyntaxKind.SetAccessor || container2.kind === SyntaxKind.PropertyDeclaration || container2.kind === SyntaxKind.ClassStaticBlockDeclaration;
          } else {
            return container2.kind === SyntaxKind.MethodDeclaration || container2.kind === SyntaxKind.MethodSignature || container2.kind === SyntaxKind.GetAccessor || container2.kind === SyntaxKind.SetAccessor || container2.kind === SyntaxKind.PropertyDeclaration || container2.kind === SyntaxKind.PropertySignature || container2.kind === SyntaxKind.Constructor;
          }
        }
      }
      return false;
    }
  }
  function getContainingObjectLiteral(func) {
    return (func.kind === SyntaxKind.MethodDeclaration || func.kind === SyntaxKind.GetAccessor || func.kind === SyntaxKind.SetAccessor) && func.parent.kind === SyntaxKind.ObjectLiteralExpression ? func.parent : func.kind === SyntaxKind.FunctionExpression && func.parent.kind === SyntaxKind.PropertyAssignment ? func.parent.parent : void 0;
  }
  function getThisTypeArgument(type) {
    return getObjectFlags(type) & ObjectFlags.Reference && type.target === globalThisType ? getTypeArguments(type)[0] : void 0;
  }
  function getThisTypeFromContextualType(type) {
    return mapType(type, (t) => {
      return t.flags & TypeFlags.Intersection ? forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
    });
  }
  function getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType) {
    let literal = containingLiteral;
    let type = contextualType;
    while (type) {
      const thisType = getThisTypeFromContextualType(type);
      if (thisType) {
        return thisType;
      }
      if (literal.parent.kind !== SyntaxKind.PropertyAssignment) {
        break;
      }
      literal = literal.parent.parent;
      type = getApparentTypeOfContextualType(
        literal,
        /*contextFlags*/
        void 0
      );
    }
  }
  function getContextualThisParameterType(func) {
    if (func.kind === SyntaxKind.ArrowFunction) {
      return void 0;
    }
    if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
      const contextualSignature = getContextualSignature(func);
      if (contextualSignature) {
        const thisParameter = contextualSignature.thisParameter;
        if (thisParameter) {
          return getTypeOfSymbol(thisParameter);
        }
      }
    }
    const inJs = isInJSFile(func);
    if (noImplicitThis || inJs) {
      const containingLiteral = getContainingObjectLiteral(func);
      if (containingLiteral) {
        const contextualType = getApparentTypeOfContextualType(
          containingLiteral,
          /*contextFlags*/
          void 0
        );
        const thisType = getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType);
        if (thisType) {
          return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
        }
        return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
      }
      const parent = walkUpParenthesizedExpressions(func.parent);
      if (isAssignmentExpression(parent)) {
        const target = parent.left;
        if (isAccessExpression(target)) {
          const { expression } = target;
          if (inJs && isIdentifier(expression)) {
            const sourceFile = getSourceFileOfNode(parent);
            if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
              return void 0;
            }
          }
          return getWidenedType(checkExpressionCached(expression));
        }
      }
    }
    return void 0;
  }
  function getContextuallyTypedParameterType(parameter) {
    const func = parameter.parent;
    if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
      return void 0;
    }
    const iife = getImmediatelyInvokedFunctionExpression(func);
    if (iife && iife.arguments) {
      const args = getEffectiveCallArguments(iife);
      const indexOfParameter = func.parameters.indexOf(parameter);
      if (parameter.dotDotDotToken) {
        return getSpreadArgumentType(
          args,
          indexOfParameter,
          args.length,
          anyType,
          /*context*/
          void 0,
          0 /* Normal */
        );
      }
      const links = getNodeLinks(iife);
      const cached = links.resolvedSignature;
      links.resolvedSignature = anySignature;
      const type = indexOfParameter < args.length ? getWidenedLiteralType(checkExpression(args[indexOfParameter])) : parameter.initializer ? void 0 : undefinedWideningType;
      links.resolvedSignature = cached;
      return type;
    }
    const contextualSignature = getContextualSignature(func);
    if (contextualSignature) {
      const index = func.parameters.indexOf(parameter) - (getThisParameter(func) ? 1 : 0);
      return parameter.dotDotDotToken && lastOrUndefined(func.parameters) === parameter ? getRestTypeAtPosition(contextualSignature, index) : tryGetTypeAtPosition(contextualSignature, index);
    }
  }
  function getContextualTypeForVariableLikeDeclaration(declaration, contextFlags) {
    const typeNode = getEffectiveTypeAnnotationNode(declaration) || (isInJSFile(declaration) ? tryGetJSDocSatisfiesTypeNode(declaration) : void 0);
    if (typeNode) {
      return getTypeFromTypeNode(typeNode);
    }
    switch (declaration.kind) {
      case SyntaxKind.Parameter:
        return getContextuallyTypedParameterType(declaration);
      case SyntaxKind.BindingElement:
        return getContextualTypeForBindingElement(declaration, contextFlags);
      case SyntaxKind.PropertyDeclaration:
        if (isStatic(declaration)) {
          return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags);
        }
    }
  }
  function getContextualTypeForBindingElement(declaration, contextFlags) {
    const parent = declaration.parent.parent;
    const name = declaration.propertyName || declaration.name;
    const parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || parent.kind !== SyntaxKind.BindingElement && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */);
    if (!parentType || isBindingPattern(name) || isComputedNonLiteralName(name)) return void 0;
    if (parent.name.kind === SyntaxKind.ArrayBindingPattern) {
      const index = indexOfNode(declaration.parent.elements, declaration);
      if (index < 0) return void 0;
      return getContextualTypeForElementExpression(parentType, index);
    }
    const nameType = getLiteralTypeFromPropertyName(name);
    if (isTypeUsableAsPropertyName(nameType)) {
      const text = getPropertyNameFromType(nameType);
      return getTypeOfPropertyOfType(parentType, text);
    }
  }
  function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) {
    const parentType = isExpression(declaration.parent) && getContextualType(declaration.parent, contextFlags);
    if (!parentType) return void 0;
    return getTypeOfPropertyOfContextualType(parentType, getSymbolOfDeclaration(declaration).escapedName);
  }
  function getContextualTypeForInitializerExpression(node, contextFlags) {
    const declaration = node.parent;
    if (hasInitializer(declaration) && node === declaration.initializer) {
      const result = getContextualTypeForVariableLikeDeclaration(declaration, contextFlags);
      if (result) {
        return result;
      }
      if (!(contextFlags & ContextFlags.SkipBindingPatterns) && isBindingPattern(declaration.name) && declaration.name.elements.length > 0) {
        return getTypeFromBindingPattern(
          declaration.name,
          /*includePatternInType*/
          true,
          /*reportErrors*/
          false
        );
      }
    }
    return void 0;
  }
  function getContextualTypeForReturnExpression(node, contextFlags) {
    const func = getContainingFunction(node);
    if (func) {
      let contextualReturnType = getContextualReturnType(func, contextFlags);
      if (contextualReturnType) {
        const functionFlags = getFunctionFlags(func);
        if (functionFlags & FunctionFlags.Generator) {
          const isAsyncGenerator = (functionFlags & FunctionFlags.Async) !== 0;
          if (contextualReturnType.flags & TypeFlags.Union) {
            contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator));
          }
          const iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, contextualReturnType, (functionFlags & FunctionFlags.Async) !== 0);
          if (!iterationReturnType) {
            return void 0;
          }
          contextualReturnType = iterationReturnType;
        }
        if (functionFlags & FunctionFlags.Async) {
          const contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeNoAlias);
          return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
        }
        return contextualReturnType;
      }
    }
    return void 0;
  }
  function getContextualTypeForAwaitOperand(node, contextFlags) {
    const contextualType = getContextualType(node, contextFlags);
    if (contextualType) {
      const contextualAwaitedType = getAwaitedTypeNoAlias(contextualType);
      return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
    }
    return void 0;
  }
  function getContextualTypeForYieldOperand(node, contextFlags) {
    const func = getContainingFunction(node);
    if (func) {
      const functionFlags = getFunctionFlags(func);
      let contextualReturnType = getContextualReturnType(func, contextFlags);
      if (contextualReturnType) {
        const isAsyncGenerator = (functionFlags & FunctionFlags.Async) !== 0;
        if (!node.asteriskToken && contextualReturnType.flags & TypeFlags.Union) {
          contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator));
        }
        if (node.asteriskToken) {
          const iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(contextualReturnType, isAsyncGenerator);
          const yieldType = iterationTypes?.yieldType ?? silentNeverType;
          const returnType = getContextualType(node, contextFlags) ?? silentNeverType;
          const nextType = iterationTypes?.nextType ?? unknownType;
          const generatorType = createGeneratorType(
            yieldType,
            returnType,
            nextType,
            /*isAsyncGenerator*/
            false
          );
          if (isAsyncGenerator) {
            const asyncGeneratorType = createGeneratorType(
              yieldType,
              returnType,
              nextType,
              /*isAsyncGenerator*/
              true
            );
            return getUnionType([generatorType, asyncGeneratorType]);
          }
          return generatorType;
        }
        return getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, isAsyncGenerator);
      }
    }
    return void 0;
  }
  function isInParameterInitializerBeforeContainingFunction(node) {
    let inBindingInitializer = false;
    while (node.parent && !isFunctionLike(node.parent)) {
      if (isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
        return true;
      }
      if (isBindingElement(node.parent) && node.parent.initializer === node) {
        inBindingInitializer = true;
      }
      node = node.parent;
    }
    return false;
  }
  function getContextualIterationType(kind, functionDecl) {
    const isAsync = !!(getFunctionFlags(functionDecl) & FunctionFlags.Async);
    const contextualReturnType = getContextualReturnType(
      functionDecl,
      /*contextFlags*/
      void 0
    );
    if (contextualReturnType) {
      return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync) || void 0;
    }
    return void 0;
  }
  function getContextualReturnType(functionDecl, contextFlags) {
    const returnType = getReturnTypeFromAnnotation(functionDecl);
    if (returnType) {
      return returnType;
    }
    const signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
    if (signature && !isResolvingReturnTypeOfSignature(signature)) {
      const returnType2 = getReturnTypeOfSignature(signature);
      const functionFlags = getFunctionFlags(functionDecl);
      if (functionFlags & FunctionFlags.Generator) {
        return filterType(returnType2, (t) => {
          return !!(t.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Void | TypeFlags.InstantiableNonPrimitive)) || checkGeneratorInstantiationAssignabilityToReturnType(
            t,
            functionFlags,
            /*errorNode*/
            void 0
          );
        });
      }
      if (functionFlags & FunctionFlags.Async) {
        return filterType(returnType2, (t) => {
          return !!(t.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Void | TypeFlags.InstantiableNonPrimitive)) || !!getAwaitedTypeOfPromise(t);
        });
      }
      return returnType2;
    }
    const iife = getImmediatelyInvokedFunctionExpression(functionDecl);
    if (iife) {
      return getContextualType(iife, contextFlags);
    }
    return void 0;
  }
  function getContextualTypeForArgument(callTarget, arg) {
    const args = getEffectiveCallArguments(callTarget);
    const argIndex = args.indexOf(arg);
    return argIndex === -1 ? void 0 : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
  }
  function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
    if (isImportCall(callTarget)) {
      return argIndex === 0 ? stringType : argIndex === 1 ? getGlobalImportCallOptionsType(
        /*reportErrors*/
        false
      ) : anyType;
    }
    const signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
    if (isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
      return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
    }
    const restIndex = signature.parameters.length - 1;
    return signatureHasRestParameter(signature) && argIndex >= restIndex ? getIndexedAccessType(getTypeOfSymbol(signature.parameters[restIndex]), getNumberLiteralType(argIndex - restIndex), AccessFlags.Contextual) : getTypeAtPosition(signature, argIndex);
  }
  function getContextualTypeForDecorator(decorator) {
    const signature = getDecoratorCallSignature(decorator);
    return signature ? getOrCreateTypeFromSignature(signature) : void 0;
  }
  function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
    if (template.parent.kind === SyntaxKind.TaggedTemplateExpression) {
      return getContextualTypeForArgument(template.parent, substitutionExpression);
    }
    return void 0;
  }
  function getContextualTypeForBinaryOperand(node, contextFlags) {
    const binaryExpression = node.parent;
    const { left, operatorToken, right } = binaryExpression;
    switch (operatorToken.kind) {
      case SyntaxKind.EqualsToken:
      case SyntaxKind.AmpersandAmpersandEqualsToken:
      case SyntaxKind.BarBarEqualsToken:
      case SyntaxKind.QuestionQuestionEqualsToken:
        return node === right ? getContextualTypeForAssignmentDeclaration(binaryExpression) : void 0;
      case SyntaxKind.BarBarToken:
      case SyntaxKind.QuestionQuestionToken:
        const type = getContextualType(binaryExpression, contextFlags);
        return node === right && (type && type.pattern || !type && !isDefaultedExpandoInitializer(binaryExpression)) ? getTypeOfExpression(left) : type;
      case SyntaxKind.AmpersandAmpersandToken:
      case SyntaxKind.CommaToken:
        return node === right ? getContextualType(binaryExpression, contextFlags) : void 0;
      default:
        return void 0;
    }
  }
  function getSymbolForExpression(e) {
    if (canHaveSymbol(e) && e.symbol) {
      return e.symbol;
    }
    if (isIdentifier(e)) {
      return getResolvedSymbol(e);
    }
    if (isPropertyAccessExpression(e)) {
      const lhsType = getTypeOfExpression(e.expression);
      return isPrivateIdentifier(e.name) ? tryGetPrivateIdentifierPropertyOfType(lhsType, e.name) : getPropertyOfType(lhsType, e.name.escapedText);
    }
    if (isElementAccessExpression(e)) {
      const propType = checkExpressionCached(e.argumentExpression);
      if (!isTypeUsableAsPropertyName(propType)) {
        return void 0;
      }
      const lhsType = getTypeOfExpression(e.expression);
      return getPropertyOfType(lhsType, getPropertyNameFromType(propType));
    }
    return void 0;
    function tryGetPrivateIdentifierPropertyOfType(type, id) {
      const lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(id.escapedText, id);
      return lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(type, lexicallyScopedSymbol);
    }
  }
  function getContextualTypeForAssignmentDeclaration(binaryExpression) {
    const kind = getAssignmentDeclarationKind(binaryExpression);
    switch (kind) {
      case AssignmentDeclarationKind.None:
      case AssignmentDeclarationKind.ThisProperty:
        const lhsSymbol = getSymbolForExpression(binaryExpression.left);
        const decl = lhsSymbol && lhsSymbol.valueDeclaration;
        if (decl && (isPropertyDeclaration(decl) || isPropertySignature(decl))) {
          const overallAnnotation = getEffectiveTypeAnnotationNode(decl);
          return overallAnnotation && instantiateType(getTypeFromTypeNode(overallAnnotation), getSymbolLinks(lhsSymbol).mapper) || (isPropertyDeclaration(decl) ? decl.initializer && getTypeOfExpression(binaryExpression.left) : void 0);
        }
        if (kind === AssignmentDeclarationKind.None) {
          return getTypeOfExpression(binaryExpression.left);
        }
        return getContextualTypeForThisPropertyAssignment(binaryExpression);
      case AssignmentDeclarationKind.Property:
        if (isPossiblyAliasedThisProperty(binaryExpression, kind)) {
          return getContextualTypeForThisPropertyAssignment(binaryExpression);
        } else if (!canHaveSymbol(binaryExpression.left) || !binaryExpression.left.symbol) {
          return getTypeOfExpression(binaryExpression.left);
        } else {
          const decl2 = binaryExpression.left.symbol.valueDeclaration;
          if (!decl2) {
            return void 0;
          }
          const lhs = cast(binaryExpression.left, isAccessExpression);
          const overallAnnotation = getEffectiveTypeAnnotationNode(decl2);
          if (overallAnnotation) {
            return getTypeFromTypeNode(overallAnnotation);
          } else if (isIdentifier(lhs.expression)) {
            const id = lhs.expression;
            const parentSymbol = resolveName(
              id,
              id.escapedText,
              SymbolFlags.Value,
              /*nameNotFoundMessage*/
              void 0,
              /*isUse*/
              true
            );
            if (parentSymbol) {
              const annotated2 = parentSymbol.valueDeclaration && getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
              if (annotated2) {
                const nameStr = getElementOrPropertyAccessName(lhs);
                if (nameStr !== void 0) {
                  return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated2), nameStr);
                }
              }
              return void 0;
            }
          }
          return isInJSFile(decl2) || decl2 === binaryExpression.left ? void 0 : getTypeOfExpression(binaryExpression.left);
        }
      case AssignmentDeclarationKind.ExportsProperty:
      case AssignmentDeclarationKind.Prototype:
      case AssignmentDeclarationKind.PrototypeProperty:
      case AssignmentDeclarationKind.ModuleExports:
        let valueDeclaration;
        if (kind !== AssignmentDeclarationKind.ModuleExports) {
          valueDeclaration = canHaveSymbol(binaryExpression.left) ? binaryExpression.left.symbol?.valueDeclaration : void 0;
        }
        valueDeclaration ||= binaryExpression.symbol?.valueDeclaration;
        const annotated = valueDeclaration && getEffectiveTypeAnnotationNode(valueDeclaration);
        return annotated ? getTypeFromTypeNode(annotated) : void 0;
      case AssignmentDeclarationKind.ObjectDefinePropertyValue:
      case AssignmentDeclarationKind.ObjectDefinePropertyExports:
      case AssignmentDeclarationKind.ObjectDefinePrototypeProperty:
        return Debug.fail("Does not apply");
      default:
        return Debug.assertNever(kind);
    }
  }
  function isPossiblyAliasedThisProperty(declaration, kind = getAssignmentDeclarationKind(declaration)) {
    if (kind === AssignmentDeclarationKind.ThisProperty) {
      return true;
    }
    if (!isInJSFile(declaration) || kind !== AssignmentDeclarationKind.Property || !isIdentifier(declaration.left.expression)) {
      return false;
    }
    const name = declaration.left.expression.escapedText;
    const symbol = resolveName(
      declaration.left,
      name,
      SymbolFlags.Value,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true,
      /*excludeGlobals*/
      true
    );
    return isThisInitializedDeclaration(symbol?.valueDeclaration);
  }
  function getContextualTypeForThisPropertyAssignment(binaryExpression) {
    if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left);
    if (binaryExpression.symbol.valueDeclaration) {
      const annotated = getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
      if (annotated) {
        const type = getTypeFromTypeNode(annotated);
        if (type) {
          return type;
        }
      }
    }
    const thisAccess = cast(binaryExpression.left, isAccessExpression);
    if (!isObjectLiteralMethod(getThisContainer(
      thisAccess.expression,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    ))) {
      return void 0;
    }
    const thisType = checkThisExpression(thisAccess.expression);
    const nameStr = getElementOrPropertyAccessName(thisAccess);
    return nameStr !== void 0 && getTypeOfPropertyOfContextualType(thisType, nameStr) || void 0;
  }
  function isCircularMappedProperty(symbol) {
    return !!(getCheckFlags(symbol) & CheckFlags.Mapped && !symbol.links.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
  }
  function getTypeOfPropertyOfContextualType(type, name, nameType) {
    return mapType(
      type,
      (t) => {
        if (isGenericMappedType(t) && getMappedTypeNameTypeKind(t) !== 2 /* Remapping */) {
          const constraint = getConstraintTypeFromMappedType(t);
          const constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
          const propertyNameType = nameType || getStringLiteralType(unescapeLeadingUnderscores(name));
          if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
            return substituteIndexedMappedType(t, propertyNameType);
          }
        } else if (t.flags & TypeFlags.StructuredType) {
          const prop = getPropertyOfType(t, name);
          if (prop) {
            return isCircularMappedProperty(prop) ? void 0 : removeMissingType(getTypeOfSymbol(prop), !!(prop.flags & SymbolFlags.Optional));
          }
          if (isTupleType(t) && isNumericLiteralName(name) && +name >= 0) {
            const restType = getElementTypeOfSliceOfTupleType(
              t,
              t.target.fixedLength,
              /*endSkipCount*/
              0,
              /*writing*/
              false,
              /*noReductions*/
              true
            );
            if (restType) {
              return restType;
            }
          }
          return findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType || getStringLiteralType(unescapeLeadingUnderscores(name)))?.type;
        }
        return void 0;
      },
      /*noReductions*/
      true
    );
  }
  function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
    Debug.assert(isObjectLiteralMethod(node));
    if (node.flags & NodeFlags.InWithStatement) {
      return void 0;
    }
    return getContextualTypeForObjectLiteralElement(node, contextFlags);
  }
  function getContextualTypeForObjectLiteralElement(element, contextFlags) {
    const objectLiteral = element.parent;
    const propertyAssignmentType = isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element, contextFlags);
    if (propertyAssignmentType) {
      return propertyAssignmentType;
    }
    const type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
    if (type) {
      if (hasBindableName(element)) {
        const symbol = getSymbolOfDeclaration(element);
        return getTypeOfPropertyOfContextualType(type, symbol.escapedName, getSymbolLinks(symbol).nameType);
      }
      if (hasDynamicName(element)) {
        const name = getNameOfDeclaration(element);
        if (name && isComputedPropertyName(name)) {
          const exprType = checkExpression(name.expression);
          const propType = isTypeUsableAsPropertyName(exprType) && getTypeOfPropertyOfContextualType(type, getPropertyNameFromType(exprType));
          if (propType) {
            return propType;
          }
        }
      }
      if (element.name) {
        const nameType = getLiteralTypeFromPropertyName(element.name);
        return mapType(
          type,
          (t) => findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType)?.type,
          /*noReductions*/
          true
        );
      }
    }
    return void 0;
  }
  function getSpreadIndices(elements) {
    let first2, last2;
    for (let i = 0; i < elements.length; i++) {
      if (isSpreadElement(elements[i])) {
        first2 ??= i;
        last2 = i;
      }
    }
    return { first: first2, last: last2 };
  }
  function getContextualTypeForElementExpression(type, index, length2, firstSpreadIndex, lastSpreadIndex) {
    return type && mapType(
      type,
      (t) => {
        if (isTupleType(t)) {
          if ((firstSpreadIndex === void 0 || index < firstSpreadIndex) && index < t.target.fixedLength) {
            return removeMissingType(getTypeArguments(t)[index], !!(t.target.elementFlags[index] && ElementFlags.Optional));
          }
          const offset = length2 !== void 0 && (lastSpreadIndex === void 0 || index > lastSpreadIndex) ? length2 - index : 0;
          const fixedEndLength = offset > 0 && t.target.combinedFlags & ElementFlags.Variable ? getEndElementCount(t.target, ElementFlags.Fixed) : 0;
          if (offset > 0 && offset <= fixedEndLength) {
            return getTypeArguments(t)[getTypeReferenceArity(t) - offset];
          }
          return getElementTypeOfSliceOfTupleType(
            t,
            firstSpreadIndex === void 0 ? t.target.fixedLength : Math.min(t.target.fixedLength, firstSpreadIndex),
            length2 === void 0 || lastSpreadIndex === void 0 ? fixedEndLength : Math.min(fixedEndLength, length2 - lastSpreadIndex),
            /*writing*/
            false,
            /*noReductions*/
            true
          );
        }
        return (!firstSpreadIndex || index < firstSpreadIndex) && getTypeOfPropertyOfContextualType(t, "" + index) || getIteratedTypeOrElementType(
          1 /* Element */,
          t,
          undefinedType,
          /*errorNode*/
          void 0,
          /*checkAssignability*/
          false
        );
      },
      /*noReductions*/
      true
    );
  }
  function getContextualTypeForConditionalOperand(node, contextFlags) {
    const conditional = node.parent;
    return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : void 0;
  }
  function getContextualTypeForChildJsxExpression(node, child, contextFlags) {
    const attributesType = getApparentTypeOfContextualType(node.openingElement.attributes, contextFlags);
    const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
    if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
      return void 0;
    }
    const realChildren = getSemanticJsxChildren(node.children);
    const childIndex = realChildren.indexOf(child);
    const childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
    return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(
      childFieldType,
      (t) => {
        if (isArrayLikeType(t)) {
          return getIndexedAccessType(t, getNumberLiteralType(childIndex));
        } else {
          return t;
        }
      },
      /*noReductions*/
      true
    ));
  }
  function getContextualTypeForJsxExpression(node, contextFlags) {
    const exprParent = node.parent;
    return isJsxAttributeLike(exprParent) ? getContextualType(node, contextFlags) : isJsxElement(exprParent) ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) : void 0;
  }
  function getContextualTypeForJsxAttribute(attribute, contextFlags) {
    if (isJsxAttribute(attribute)) {
      const attributesType = getApparentTypeOfContextualType(attribute.parent, contextFlags);
      if (!attributesType || isTypeAny(attributesType)) {
        return void 0;
      }
      return getTypeOfPropertyOfContextualType(attributesType, getEscapedTextOfJsxAttributeName(attribute.name));
    } else {
      return getContextualType(attribute.parent, contextFlags);
    }
  }
  function isPossiblyDiscriminantValue(node) {
    switch (node.kind) {
      case SyntaxKind.StringLiteral:
      case SyntaxKind.NumericLiteral:
      case SyntaxKind.BigIntLiteral:
      case SyntaxKind.NoSubstitutionTemplateLiteral:
      case SyntaxKind.TemplateExpression:
      case SyntaxKind.TrueKeyword:
      case SyntaxKind.FalseKeyword:
      case SyntaxKind.NullKeyword:
      case SyntaxKind.Identifier:
      case SyntaxKind.UndefinedKeyword:
        return true;
      case SyntaxKind.PropertyAccessExpression:
      case SyntaxKind.ParenthesizedExpression:
        return isPossiblyDiscriminantValue(node.expression);
      case SyntaxKind.JsxExpression:
        return !node.expression || isPossiblyDiscriminantValue(node.expression);
    }
    return false;
  }
  function discriminateContextualTypeByObjectMembers(node, contextualType) {
    const key = `D${getNodeId(node)},${getTypeId(contextualType)}`;
    return getCachedType(key) ?? setCachedType(
      key,
      getMatchingUnionConstituentForObjectLiteral(contextualType, node) ?? discriminateTypeByDiscriminableItems(
        contextualType,
        concatenate(
          map(
            filter(node.properties, (p) => {
              if (!p.symbol) {
                return false;
              }
              if (p.kind === SyntaxKind.PropertyAssignment) {
                return isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName);
              }
              if (p.kind === SyntaxKind.ShorthandPropertyAssignment) {
                return isDiscriminantProperty(contextualType, p.symbol.escapedName);
              }
              return false;
            }),
            (prop) => [() => getContextFreeTypeOfExpression(prop.kind === SyntaxKind.PropertyAssignment ? prop.initializer : prop.name), prop.symbol.escapedName]
          ),
          map(
            filter(getPropertiesOfType(contextualType), (s) => !!(s.flags & SymbolFlags.Optional) && !!node?.symbol?.members && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName)),
            (s) => [() => undefinedType, s.escapedName]
          )
        ),
        isTypeAssignableTo
      )
    );
  }
  function discriminateContextualTypeByJSXAttributes(node, contextualType) {
    const key = `D${getNodeId(node)},${getTypeId(contextualType)}`;
    const cached = getCachedType(key);
    if (cached) return cached;
    const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
    return setCachedType(
      key,
      discriminateTypeByDiscriminableItems(
        contextualType,
        concatenate(
          map(
            filter(node.properties, (p) => !!p.symbol && p.kind === SyntaxKind.JsxAttribute && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))),
            (prop) => [!prop.initializer ? () => trueType : () => getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName]
          ),
          map(
            filter(getPropertiesOfType(contextualType), (s) => {
              if (!(s.flags & SymbolFlags.Optional) || !node?.symbol?.members) {
                return false;
              }
              const element = node.parent.parent;
              if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) {
                return false;
              }
              return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName);
            }),
            (s) => [() => undefinedType, s.escapedName]
          )
        ),
        isTypeAssignableTo
      )
    );
  }
  function getApparentTypeOfContextualType(node, contextFlags) {
    const contextualType = isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node, contextFlags) : getContextualType(node, contextFlags);
    const instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
    if (instantiatedType && !(contextFlags && contextFlags & ContextFlags.NoConstraints && instantiatedType.flags & TypeFlags.TypeVariable)) {
      const apparentType = mapType(
        instantiatedType,
        // When obtaining apparent type of *contextual* type we don't want to get apparent type of mapped types.
        // That would evaluate mapped types with array or tuple type constraints too eagerly
        // and thus it would prevent `getTypeOfPropertyOfContextualType` from obtaining per-position contextual type for elements of array literal expressions.
        // Apparent type of other mapped types is already the mapped type itself so we can just avoid calling `getApparentType` here for all mapped types.
        (t) => getObjectFlags(t) & ObjectFlags.Mapped ? t : getApparentType(t),
        /*noReductions*/
        true
      );
      return apparentType.flags & TypeFlags.Union && isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : apparentType.flags & TypeFlags.Union && isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : apparentType;
    }
  }
  function instantiateContextualType(contextualType, node, contextFlags) {
    if (contextualType && maybeTypeOfKind(contextualType, TypeFlags.Instantiable)) {
      const inferenceContext = getInferenceContext(node);
      if (inferenceContext && contextFlags & ContextFlags.Signature && some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) {
        return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
      }
      if (inferenceContext?.returnMapper) {
        const type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
        return type.flags & TypeFlags.Union && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? filterType(type, (t) => t !== regularFalseType && t !== regularTrueType) : type;
      }
    }
    return contextualType;
  }
  function instantiateInstantiableTypes(type, mapper) {
    if (type.flags & TypeFlags.Instantiable) {
      return instantiateType(type, mapper);
    }
    if (type.flags & TypeFlags.Union) {
      return getUnionType(map(type.types, (t) => instantiateInstantiableTypes(t, mapper)), UnionReduction.None);
    }
    if (type.flags & TypeFlags.Intersection) {
      return getIntersectionType(map(type.types, (t) => instantiateInstantiableTypes(t, mapper)));
    }
    return type;
  }
  function getContextualType(node, contextFlags) {
    if (node.flags & NodeFlags.InWithStatement) {
      return void 0;
    }
    const index = findContextualNode(
      node,
      /*includeCaches*/
      !contextFlags
    );
    if (index >= 0) {
      return contextualTypes[index];
    }
    const { parent } = node;
    switch (parent.kind) {
      case SyntaxKind.VariableDeclaration:
      case SyntaxKind.Parameter:
      case SyntaxKind.PropertyDeclaration:
      case SyntaxKind.PropertySignature:
      case SyntaxKind.BindingElement:
        return getContextualTypeForInitializerExpression(node, contextFlags);
      case SyntaxKind.ArrowFunction:
      case SyntaxKind.ReturnStatement:
        return getContextualTypeForReturnExpression(node, contextFlags);
      case SyntaxKind.YieldExpression:
        return getContextualTypeForYieldOperand(parent, contextFlags);
      case SyntaxKind.AwaitExpression:
        return getContextualTypeForAwaitOperand(parent, contextFlags);
      case SyntaxKind.CallExpression:
      case SyntaxKind.NewExpression:
        return getContextualTypeForArgument(parent, node);
      case SyntaxKind.Decorator:
        return getContextualTypeForDecorator(parent);
      case SyntaxKind.TypeAssertionExpression:
      case SyntaxKind.AsExpression:
        return isConstTypeReference(parent.type) ? getContextualType(parent, contextFlags) : getTypeFromTypeNode(parent.type);
      case SyntaxKind.BinaryExpression:
        return getContextualTypeForBinaryOperand(node, contextFlags);
      case SyntaxKind.PropertyAssignment:
      case SyntaxKind.ShorthandPropertyAssignment:
        return getContextualTypeForObjectLiteralElement(parent, contextFlags);
      case SyntaxKind.SpreadAssignment:
        return getContextualType(parent.parent, contextFlags);
      case SyntaxKind.ArrayLiteralExpression: {
        const arrayLiteral = parent;
        const type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
        const elementIndex = indexOfNode(arrayLiteral.elements, node);
        const spreadIndices = getNodeLinks(arrayLiteral).spreadIndices ??= getSpreadIndices(arrayLiteral.elements);
        return getContextualTypeForElementExpression(type, elementIndex, arrayLiteral.elements.length, spreadIndices.first, spreadIndices.last);
      }
      case SyntaxKind.ConditionalExpression:
        return getContextualTypeForConditionalOperand(node, contextFlags);
      case SyntaxKind.TemplateSpan:
        Debug.assert(parent.parent.kind === SyntaxKind.TemplateExpression);
        return getContextualTypeForSubstitutionExpression(parent.parent, node);
      case SyntaxKind.ParenthesizedExpression: {
        if (isInJSFile(parent)) {
          if (isJSDocSatisfiesExpression(parent)) {
            return getTypeFromTypeNode(getJSDocSatisfiesExpressionType(parent));
          }
          const typeTag = getJSDocTypeTag(parent);
          if (typeTag && !isConstTypeReference(typeTag.typeExpression.type)) {
            return getTypeFromTypeNode(typeTag.typeExpression.type);
          }
        }
        return getContextualType(parent, contextFlags);
      }
      case SyntaxKind.NonNullExpression:
        return getContextualType(parent, contextFlags);
      case SyntaxKind.SatisfiesExpression:
        return getTypeFromTypeNode(parent.type);
      case SyntaxKind.ExportAssignment:
        return tryGetTypeFromEffectiveTypeNode(parent);
      case SyntaxKind.JsxExpression:
        return getContextualTypeForJsxExpression(parent, contextFlags);
      case SyntaxKind.JsxAttribute:
      case SyntaxKind.JsxSpreadAttribute:
        return getContextualTypeForJsxAttribute(parent, contextFlags);
      case SyntaxKind.JsxOpeningElement:
      case SyntaxKind.JsxSelfClosingElement:
        return getContextualJsxElementAttributesType(parent, contextFlags);
      case SyntaxKind.ImportAttribute:
        return getContextualImportAttributeType(parent);
    }
    return void 0;
  }
  function pushCachedContextualType(node) {
    pushContextualType(
      node,
      getContextualType(
        node,
        /*contextFlags*/
        void 0
      ),
      /*isCache*/
      true
    );
  }
  function pushContextualType(node, type, isCache) {
    contextualTypeNodes[contextualTypeCount] = node;
    contextualTypes[contextualTypeCount] = type;
    contextualIsCache[contextualTypeCount] = isCache;
    contextualTypeCount++;
  }
  function popContextualType() {
    contextualTypeCount--;
  }
  function findContextualNode(node, includeCaches) {
    for (let i = contextualTypeCount - 1; i >= 0; i--) {
      if (node === contextualTypeNodes[i] && (includeCaches || !contextualIsCache[i])) {
        return i;
      }
    }
    return -1;
  }
  function pushInferenceContext(node, inferenceContext) {
    inferenceContextNodes[inferenceContextCount] = node;
    inferenceContexts[inferenceContextCount] = inferenceContext;
    inferenceContextCount++;
  }
  function popInferenceContext() {
    inferenceContextCount--;
  }
  function getInferenceContext(node) {
    for (let i = inferenceContextCount - 1; i >= 0; i--) {
      if (isNodeDescendantOf(node, inferenceContextNodes[i])) {
        return inferenceContexts[i];
      }
    }
  }
  function getContextualImportAttributeType(node) {
    return getTypeOfPropertyOfContextualType(getGlobalImportAttributesType(
      /*reportErrors*/
      false
    ), getNameFromImportAttribute(node));
  }
  function getContextualJsxElementAttributesType(node, contextFlags) {
    if (isJsxOpeningElement(node) && contextFlags !== ContextFlags.Completions) {
      const index = findContextualNode(
        node.parent,
        /*includeCaches*/
        !contextFlags
      );
      if (index >= 0) {
        return contextualTypes[index];
      }
    }
    return getContextualTypeForArgumentAtIndex(node, 0);
  }
  function getEffectiveFirstArgumentForJsxSignature(signature, node) {
    return getJsxReferenceKind(node) !== JsxReferenceKind.Component ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node);
  }
  function getJsxPropsTypeFromCallSignature(sig, context) {
    let propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
    propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
    const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
    if (!isErrorType(intrinsicAttribs)) {
      propsType = intersectTypes(intrinsicAttribs, propsType);
    }
    return propsType;
  }
  function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
    if (sig.compositeSignatures) {
      const results = [];
      for (const signature of sig.compositeSignatures) {
        const instance = getReturnTypeOfSignature(signature);
        if (isTypeAny(instance)) {
          return instance;
        }
        const propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
        if (!propType) {
          return;
        }
        results.push(propType);
      }
      return getIntersectionType(results);
    }
    const instanceType = getReturnTypeOfSignature(sig);
    return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
  }
  function getStaticTypeOfReferencedJsxConstructor(context) {
    if (isJsxIntrinsicTagName(context.tagName)) {
      const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
      const fakeSignature = createSignatureForJSXIntrinsic(context, result);
      return getOrCreateTypeFromSignature(fakeSignature);
    }
    const tagType = checkExpressionCached(context.tagName);
    if (tagType.flags & TypeFlags.StringLiteral) {
      const result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
      if (!result) {
        return errorType;
      }
      const fakeSignature = createSignatureForJSXIntrinsic(context, result);
      return getOrCreateTypeFromSignature(fakeSignature);
    }
    return tagType;
  }
  function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
    const managedSym = getJsxLibraryManagedAttributes(ns);
    if (managedSym) {
      const ctorType = getStaticTypeOfReferencedJsxConstructor(context);
      const result = instantiateAliasOrInterfaceWithDefaults(managedSym, isInJSFile(context), ctorType, attributesType);
      if (result) {
        return result;
      }
    }
    return attributesType;
  }
  function getJsxPropsTypeFromClassType(sig, context) {
    const ns = getJsxNamespaceAt(context);
    const forcedLookupLocation = getJsxElementPropertiesName(ns);
    let attributesType = forcedLookupLocation === void 0 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType) : forcedLookupLocation === "" ? getReturnTypeOfSignature(sig) : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
    if (!attributesType) {
      if (!!forcedLookupLocation && !!length(context.attributes.properties)) {
        error(context, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, unescapeLeadingUnderscores(forcedLookupLocation));
      }
      return unknownType;
    }
    attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
    if (isTypeAny(attributesType)) {
      return attributesType;
    } else {
      let apparentAttributesType = attributesType;
      const intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
      if (!isErrorType(intrinsicClassAttribs)) {
        const typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
        const hostClassType = getReturnTypeOfSignature(sig);
        let libraryManagedAttributeType;
        if (typeParams) {
          const inferredArgs = fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isInJSFile(context));
          libraryManagedAttributeType = instantiateType(intrinsicClassAttribs, createTypeMapper(typeParams, inferredArgs));
        } else libraryManagedAttributeType = intrinsicClassAttribs;
        apparentAttributesType = intersectTypes(libraryManagedAttributeType, apparentAttributesType);
      }
      const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
      if (!isErrorType(intrinsicAttribs)) {
        apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
      }
      return apparentAttributesType;
    }
  }
  function getIntersectedSignatures(signatures) {
    return getStrictOptionValue(compilerOptions, "noImplicitAny") ? reduceLeft(
      signatures,
      (left, right) => left === right || !left ? left : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) : void 0
    ) : void 0;
  }
  function combineIntersectionThisParam(left, right, mapper) {
    if (!left || !right) {
      return left || right;
    }
    const thisType = getUnionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]);
    return createSymbolWithType(left, thisType);
  }
  function combineIntersectionParameters(left, right, mapper) {
    const leftCount = getParameterCount(left);
    const rightCount = getParameterCount(right);
    const longest = leftCount >= rightCount ? left : right;
    const shorter = longest === left ? right : left;
    const longestCount = longest === left ? leftCount : rightCount;
    const eitherHasEffectiveRest = hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right);
    const needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
    const params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
    for (let i = 0; i < longestCount; i++) {
      let longestParamType = tryGetTypeAtPosition(longest, i);
      if (longest === right) {
        longestParamType = instantiateType(longestParamType, mapper);
      }
      let shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
      if (shorter === right) {
        shorterParamType = instantiateType(shorterParamType, mapper);
      }
      const unionParamType = getUnionType([longestParamType, shorterParamType]);
      const isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === longestCount - 1;
      const isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
      const leftName = i >= leftCount ? void 0 : getParameterNameAtPosition(left, i);
      const rightName = i >= rightCount ? void 0 : getParameterNameAtPosition(right, i);
      const paramName = leftName === rightName ? leftName : !leftName ? rightName : !rightName ? leftName : void 0;
      const paramSymbol = createSymbol(
        SymbolFlags.FunctionScopedVariable | (isOptional && !isRestParam ? SymbolFlags.Optional : 0),
        paramName || `arg${i}`
      );
      paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
      params[i] = paramSymbol;
    }
    if (needsExtraRestElement) {
      const restParamSymbol = createSymbol(SymbolFlags.FunctionScopedVariable, "args");
      restParamSymbol.links.type = createArrayType(getTypeAtPosition(shorter, longestCount));
      if (shorter === right) {
        restParamSymbol.links.type = instantiateType(restParamSymbol.links.type, mapper);
      }
      params[longestCount] = restParamSymbol;
    }
    return params;
  }
  function combineSignaturesOfIntersectionMembers(left, right) {
    const typeParams = left.typeParameters || right.typeParameters;
    let paramMapper;
    if (left.typeParameters && right.typeParameters) {
      paramMapper = createTypeMapper(right.typeParameters, left.typeParameters);
    }
    const declaration = left.declaration;
    const params = combineIntersectionParameters(left, right, paramMapper);
    const thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper);
    const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
    const result = createSignature(
      declaration,
      typeParams,
      thisParam,
      params,
      /*resolvedReturnType*/
      void 0,
      /*resolvedTypePredicate*/
      void 0,
      minArgCount,
      (left.flags | right.flags) & SignatureFlags.PropagatingFlags
    );
    result.compositeKind = TypeFlags.Intersection;
    result.compositeSignatures = concatenate(left.compositeKind === TypeFlags.Intersection && left.compositeSignatures || [left], [right]);
    if (paramMapper) {
      result.mapper = left.compositeKind === TypeFlags.Intersection && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper;
    }
    return result;
  }
  function getContextualCallSignature(type, node) {
    const signatures = getSignaturesOfType(type, SignatureKind.Call);
    const applicableByArity = filter(signatures, (s) => !isAritySmaller(s, node));
    return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity);
  }
  function isAritySmaller(signature, target) {
    let targetParameterCount = 0;
    for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
      const param = target.parameters[targetParameterCount];
      if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
        break;
      }
    }
    if (target.parameters.length && parameterIsThisKeyword(target.parameters[0])) {
      targetParameterCount--;
    }
    return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
  }
  function getContextualSignatureForFunctionLikeDeclaration(node) {
    return isFunctionExpressionOrArrowFunction(node) || isObjectLiteralMethod(node) ? getContextualSignature(node) : void 0;
  }
  function getContextualSignature(node) {
    Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node));
    const typeTagSignature = getSignatureOfTypeTag(node);
    if (typeTagSignature) {
      return typeTagSignature;
    }
    const type = getApparentTypeOfContextualType(node, ContextFlags.Signature);
    if (!type) {
      return void 0;
    }
    if (!(type.flags & TypeFlags.Union)) {
      return getContextualCallSignature(type, node);
    }
    let signatureList;
    const types = type.types;
    for (const current of types) {
      const signature = getContextualCallSignature(current, node);
      if (signature) {
        if (!signatureList) {
          signatureList = [signature];
        } else if (!compareSignaturesIdentical(
          signatureList[0],
          signature,
          /*partialMatch*/
          false,
          /*ignoreThisTypes*/
          true,
          /*ignoreReturnTypes*/
          true,
          compareTypesIdentical
        )) {
          return void 0;
        } else {
          signatureList.push(signature);
        }
      }
    }
    if (signatureList) {
      return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
    }
  }
  function checkGrammarRegularExpressionLiteral(node) {
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile) && !node.isUnterminated) {
      let lastError;
      scanner ??= createScanner(
        ScriptTarget.ESNext,
        /*skipTrivia*/
        true
      );
      scanner.setScriptTarget(sourceFile.languageVersion);
      scanner.setLanguageVariant(sourceFile.languageVariant);
      scanner.setOnError((message, length2, arg0) => {
        const start = scanner.getTokenEnd();
        if (message.category === DiagnosticCategory.Message && lastError && start === lastError.start && length2 === lastError.length) {
          const error2 = createDetachedDiagnostic(sourceFile.fileName, sourceFile.text, start, length2, message, arg0);
          addRelatedInfo(lastError, error2);
        } else if (!lastError || start !== lastError.start) {
          lastError = createFileDiagnostic(sourceFile, start, length2, message, arg0);
          diagnostics.add(lastError);
        }
      });
      scanner.setText(sourceFile.text, node.pos, node.end - node.pos);
      try {
        scanner.scan();
        Debug.assert(scanner.reScanSlashToken(
          /*reportErrors*/
          true
        ) === SyntaxKind.RegularExpressionLiteral, "Expected scanner to rescan RegularExpressionLiteral");
        return !!lastError;
      } finally {
        scanner.setText("");
        scanner.setOnError(
          /*onError*/
          void 0
        );
      }
    }
    return false;
  }
  function checkRegularExpressionLiteral(node) {
    const nodeLinks2 = getNodeLinks(node);
    if (!(nodeLinks2.flags & NodeCheckFlags.TypeChecked)) {
      nodeLinks2.flags |= NodeCheckFlags.TypeChecked;
      addLazyDiagnostic(() => checkGrammarRegularExpressionLiteral(node));
    }
    return globalRegExpType;
  }
  function checkSpreadExpression(node, checkMode) {
    if (languageVersion < LanguageFeatureMinimumTarget.SpreadElements) {
      checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? ExternalEmitHelpers.SpreadIncludes : ExternalEmitHelpers.SpreadArray);
    }
    const arrayOrIterableType = checkExpression(node.expression, checkMode);
    return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
  }
  function checkSyntheticExpression(node) {
    return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type;
  }
  function hasDefaultValue(node) {
    return node.kind === SyntaxKind.BindingElement && !!node.initializer || node.kind === SyntaxKind.PropertyAssignment && hasDefaultValue(node.initializer) || node.kind === SyntaxKind.ShorthandPropertyAssignment && !!node.objectAssignmentInitializer || node.kind === SyntaxKind.BinaryExpression && node.operatorToken.kind === SyntaxKind.EqualsToken;
  }
  function isSpreadIntoCallOrNew(node) {
    const parent = walkUpParenthesizedExpressions(node.parent);
    return isSpreadElement(parent) && isCallOrNewExpression(parent.parent);
  }
  function checkArrayLiteral(node, checkMode, forceTuple) {
    const elements = node.elements;
    const elementCount = elements.length;
    const elementTypes = [];
    const elementFlags = [];
    pushCachedContextualType(node);
    const inDestructuringPattern = isAssignmentTarget(node);
    const inConstContext = isConstContext(node);
    const contextualType = getApparentTypeOfContextualType(
      node,
      /*contextFlags*/
      void 0
    );
    const inTupleContext = isSpreadIntoCallOrNew(node) || !!contextualType && someType(contextualType, (t) => isTupleLikeType(t) || isGenericMappedType(t) && !t.nameType && !!getHomomorphicTypeVariable(t.target || t));
    let hasOmittedExpression = false;
    for (let i = 0; i < elementCount; i++) {
      const e = elements[i];
      if (e.kind === SyntaxKind.SpreadElement) {
        if (languageVersion < LanguageFeatureMinimumTarget.SpreadElements) {
          checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? ExternalEmitHelpers.SpreadIncludes : ExternalEmitHelpers.SpreadArray);
        }
        const spreadType = checkExpression(e.expression, checkMode, forceTuple);
        if (isArrayLikeType(spreadType)) {
          elementTypes.push(spreadType);
          elementFlags.push(ElementFlags.Variadic);
        } else if (inDestructuringPattern) {
          const restElementType = getIndexTypeOfType(spreadType, numberType) || getIteratedTypeOrElementType(
            65 /* Destructuring */,
            spreadType,
            undefinedType,
            /*errorNode*/
            void 0,
            /*checkAssignability*/
            false
          ) || unknownType;
          elementTypes.push(restElementType);
          elementFlags.push(ElementFlags.Rest);
        } else {
          elementTypes.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, e.expression));
          elementFlags.push(ElementFlags.Rest);
        }
      } else if (exactOptionalPropertyTypes && e.kind === SyntaxKind.OmittedExpression) {
        hasOmittedExpression = true;
        elementTypes.push(undefinedOrMissingType);
        elementFlags.push(ElementFlags.Optional);
      } else {
        const type = checkExpressionForMutableLocation(e, checkMode, forceTuple);
        elementTypes.push(addOptionality(
          type,
          /*isProperty*/
          true,
          hasOmittedExpression
        ));
        elementFlags.push(hasOmittedExpression ? ElementFlags.Optional : ElementFlags.Required);
        if (inTupleContext && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(e)) {
          const inferenceContext = getInferenceContext(node);
          Debug.assert(inferenceContext);
          addIntraExpressionInferenceSite(inferenceContext, e, type);
        }
      }
    }
    popContextualType();
    if (inDestructuringPattern) {
      return createTupleType(elementTypes, elementFlags);
    }
    if (forceTuple || inConstContext || inTupleContext) {
      return createArrayLiteralType(createTupleType(
        elementTypes,
        elementFlags,
        /*readonly*/
        inConstContext && !(contextualType && someType(contextualType, isMutableArrayLikeType))
      ));
    }
    return createArrayLiteralType(createArrayType(
      elementTypes.length ? getUnionType(sameMap(elementTypes, (t, i) => elementFlags[i] & ElementFlags.Variadic ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t), UnionReduction.Subtype) : strictNullChecks ? implicitNeverType : undefinedWideningType,
      inConstContext
    ));
  }
  function createArrayLiteralType(type) {
    if (!(getObjectFlags(type) & ObjectFlags.Reference)) {
      return type;
    }
    let literalType = type.literalType;
    if (!literalType) {
      literalType = type.literalType = cloneTypeReference(type);
      literalType.objectFlags |= ObjectFlags.ArrayLiteral | ObjectFlags.ContainsObjectOrArrayLiteral;
    }
    return literalType;
  }
  function isNumericName(name) {
    switch (name.kind) {
      case SyntaxKind.ComputedPropertyName:
        return isNumericComputedName(name);
      case SyntaxKind.Identifier:
        return isNumericLiteralName(name.escapedText);
      case SyntaxKind.NumericLiteral:
      case SyntaxKind.StringLiteral:
        return isNumericLiteralName(name.text);
      default:
        return false;
    }
  }
  function isNumericComputedName(name) {
    return isTypeAssignableToKind(checkComputedPropertyName(name), TypeFlags.NumberLike);
  }
  function checkComputedPropertyName(node) {
    const links = getNodeLinks(node.expression);
    if (!links.resolvedType) {
      if ((isTypeLiteralNode(node.parent.parent) || isClassLike(node.parent.parent) || isInterfaceDeclaration(node.parent.parent)) && isBinaryExpression(node.expression) && node.expression.operatorToken.kind === SyntaxKind.InKeyword && node.parent.kind !== SyntaxKind.GetAccessor && node.parent.kind !== SyntaxKind.SetAccessor) {
        return links.resolvedType = errorType;
      }
      links.resolvedType = checkExpression(node.expression);
      if (isPropertyDeclaration(node.parent) && !hasStaticModifier(node.parent) && isClassExpression(node.parent.parent)) {
        const container = getEnclosingBlockScopeContainer(node.parent.parent);
        const enclosingIterationStatement = getEnclosingIterationStatement(container);
        if (enclosingIterationStatement) {
          getNodeLinks(enclosingIterationStatement).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding;
          getNodeLinks(node).flags |= NodeCheckFlags.BlockScopedBindingInLoop;
          getNodeLinks(node.parent.parent).flags |= NodeCheckFlags.BlockScopedBindingInLoop;
        }
      }
      if (links.resolvedType.flags & TypeFlags.Nullable || !isTypeAssignableToKind(links.resolvedType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
        error(node, Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
      }
    }
    return links.resolvedType;
  }
  function isSymbolWithNumericName(symbol) {
    const firstDecl = symbol.declarations?.[0];
    return isNumericLiteralName(symbol.escapedName) || firstDecl && isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name);
  }
  function isSymbolWithSymbolName(symbol) {
    const firstDecl = symbol.declarations?.[0];
    return isKnownSymbol(symbol) || firstDecl && isNamedDeclaration(firstDecl) && isComputedPropertyName(firstDecl.name) && isTypeAssignableToKind(checkComputedPropertyName(firstDecl.name), TypeFlags.ESSymbol);
  }
  function getObjectLiteralIndexInfo(node, offset, properties, keyType) {
    const propTypes = [];
    for (let i = offset; i < properties.length; i++) {
      const prop = properties[i];
      if (keyType === stringType && !isSymbolWithSymbolName(prop) || keyType === numberType && isSymbolWithNumericName(prop) || keyType === esSymbolType && isSymbolWithSymbolName(prop)) {
        propTypes.push(getTypeOfSymbol(properties[i]));
      }
    }
    const unionType = propTypes.length ? getUnionType(propTypes, UnionReduction.Subtype) : undefinedType;
    return createIndexInfo(keyType, unionType, isConstContext(node));
  }
  function getImmediateAliasedSymbol(symbol) {
    Debug.assert((symbol.flags & SymbolFlags.Alias) !== 0, "Should only get Alias here.");
    const links = getSymbolLinks(symbol);
    if (!links.immediateTarget) {
      const node = getDeclarationOfAliasSymbol(symbol);
      if (!node) return Debug.fail();
      links.immediateTarget = getTargetOfAliasDeclaration(
        node,
        /*dontRecursivelyResolve*/
        true
      );
    }
    return links.immediateTarget;
  }
  function checkObjectLiteral(node, checkMode = 0 /* Normal */) {
    const inDestructuringPattern = isAssignmentTarget(node);
    checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
    const allPropertiesTable = strictNullChecks ? createSymbolTable() : void 0;
    let propertiesTable = createSymbolTable();
    let propertiesArray = [];
    let spread = emptyObjectType;
    pushCachedContextualType(node);
    const contextualType = getApparentTypeOfContextualType(
      node,
      /*contextFlags*/
      void 0
    );
    const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === SyntaxKind.ObjectBindingPattern || contextualType.pattern.kind === SyntaxKind.ObjectLiteralExpression);
    const inConstContext = isConstContext(node);
    const checkFlags = inConstContext ? CheckFlags.Readonly : 0;
    const isInJavascript = isInJSFile(node) && !isInJsonFile(node);
    const enumTag = isInJavascript ? getJSDocEnumTag(node) : void 0;
    const isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
    let objectFlags = ObjectFlags.FreshLiteral;
    let patternWithComputedProperties = false;
    let hasComputedStringProperty = false;
    let hasComputedNumberProperty = false;
    let hasComputedSymbolProperty = false;
    for (const elem of node.properties) {
      if (elem.name && isComputedPropertyName(elem.name)) {
        checkComputedPropertyName(elem.name);
      }
    }
    let offset = 0;
    for (const memberDecl of node.properties) {
      let member = getSymbolOfDeclaration(memberDecl);
      const computedNameType = memberDecl.name && memberDecl.name.kind === SyntaxKind.ComputedPropertyName ? checkComputedPropertyName(memberDecl.name) : void 0;
      if (memberDecl.kind === SyntaxKind.PropertyAssignment || memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment || isObjectLiteralMethod(memberDecl)) {
        let type = memberDecl.kind === SyntaxKind.PropertyAssignment ? checkPropertyAssignment(memberDecl, checkMode) : (
          // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring
          // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`.
          // we don't want to say "could not find 'a'".
          memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode)
        );
        if (isInJavascript) {
          const jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
          if (jsDocType) {
            checkTypeAssignableTo(type, jsDocType, memberDecl);
            type = jsDocType;
          } else if (enumTag && enumTag.typeExpression) {
            checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
          }
        }
        objectFlags |= getObjectFlags(type) & ObjectFlags.PropagatingFlags;
        const nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : void 0;
        const prop = nameType ? createSymbol(SymbolFlags.Property | member.flags, getPropertyNameFromType(nameType), checkFlags | CheckFlags.Late) : createSymbol(SymbolFlags.Property | member.flags, member.escapedName, checkFlags);
        if (nameType) {
          prop.links.nameType = nameType;
        }
        if (inDestructuringPattern && hasDefaultValue(memberDecl)) {
          prop.flags |= SymbolFlags.Optional;
        } else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & ObjectFlags.ObjectLiteralPatternWithComputedProperties)) {
          const impliedProp = getPropertyOfType(contextualType, member.escapedName);
          if (impliedProp) {
            prop.flags |= impliedProp.flags & SymbolFlags.Optional;
          } else if (!getIndexInfoOfType(contextualType, stringType)) {
            error(memberDecl.name, Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
          }
        }
        prop.declarations = member.declarations;
        prop.parent = member.parent;
        if (member.valueDeclaration) {
          prop.valueDeclaration = member.valueDeclaration;
        }
        prop.links.type = type;
        prop.links.target = member;
        member = prop;
        allPropertiesTable?.set(prop.escapedName, prop);
        if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === SyntaxKind.PropertyAssignment || memberDecl.kind === SyntaxKind.MethodDeclaration) && isContextSensitive(memberDecl)) {
          const inferenceContext = getInferenceContext(node);
          Debug.assert(inferenceContext);
          const inferenceNode = memberDecl.kind === SyntaxKind.PropertyAssignment ? memberDecl.initializer : memberDecl;
          addIntraExpressionInferenceSite(inferenceContext, inferenceNode, type);
        }
      } else if (memberDecl.kind === SyntaxKind.SpreadAssignment) {
        if (languageVersion < LanguageFeatureMinimumTarget.ObjectAssign) {
          checkExternalEmitHelpers(memberDecl, ExternalEmitHelpers.Assign);
        }
        if (propertiesArray.length > 0) {
          spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
          propertiesArray = [];
          propertiesTable = createSymbolTable();
          hasComputedStringProperty = false;
          hasComputedNumberProperty = false;
          hasComputedSymbolProperty = false;
        }
        const type = getReducedType(checkExpression(memberDecl.expression, checkMode & 2 /* Inferential */));
        if (isValidSpreadType(type)) {
          const mergedType = tryMergeUnionOfObjectTypeAndEmptyObject(type, inConstContext);
          if (allPropertiesTable) {
            checkSpreadPropOverrides(mergedType, allPropertiesTable, memberDecl);
          }
          offset = propertiesArray.length;
          if (isErrorType(spread)) {
            continue;
          }
          spread = getSpreadType(spread, mergedType, node.symbol, objectFlags, inConstContext);
        } else {
          error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types);
          spread = errorType;
        }
        continue;
      } else {
        Debug.assert(memberDecl.kind === SyntaxKind.GetAccessor || memberDecl.kind === SyntaxKind.SetAccessor);
        checkNodeDeferred(memberDecl);
      }
      if (computedNameType && !(computedNameType.flags & TypeFlags.StringOrNumberLiteralOrUnique)) {
        if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
          if (isTypeAssignableTo(computedNameType, numberType)) {
            hasComputedNumberProperty = true;
          } else if (isTypeAssignableTo(computedNameType, esSymbolType)) {
            hasComputedSymbolProperty = true;
          } else {
            hasComputedStringProperty = true;
          }
          if (inDestructuringPattern) {
            patternWithComputedProperties = true;
          }
        }
      } else {
        propertiesTable.set(member.escapedName, member);
      }
      propertiesArray.push(member);
    }
    popContextualType();
    if (isErrorType(spread)) {
      return errorType;
    }
    if (spread !== emptyObjectType) {
      if (propertiesArray.length > 0) {
        spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
        propertiesArray = [];
        propertiesTable = createSymbolTable();
        hasComputedStringProperty = false;
        hasComputedNumberProperty = false;
      }
      return mapType(spread, (t) => t === emptyObjectType ? createObjectLiteralType() : t);
    }
    return createObjectLiteralType();
    function createObjectLiteralType() {
      const indexInfos = [];
      if (hasComputedStringProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, stringType));
      if (hasComputedNumberProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, numberType));
      if (hasComputedSymbolProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, esSymbolType));
      const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, indexInfos);
      result.objectFlags |= objectFlags | ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectOrArrayLiteral;
      if (isJSObjectLiteral) {
        result.objectFlags |= ObjectFlags.JSLiteral;
      }
      if (patternWithComputedProperties) {
        result.objectFlags |= ObjectFlags.ObjectLiteralPatternWithComputedProperties;
      }
      if (inDestructuringPattern) {
        result.pattern = node;
      }
      return result;
    }
  }
  function isValidSpreadType(type) {
    const t = removeDefinitelyFalsyTypes(mapType(type, getBaseConstraintOrType));
    return !!(t.flags & (TypeFlags.Any | TypeFlags.NonPrimitive | TypeFlags.Object | TypeFlags.InstantiableNonPrimitive) || t.flags & TypeFlags.UnionOrIntersection && every(t.types, isValidSpreadType));
  }
  function checkJsxSelfClosingElementDeferred(node) {
    checkJsxOpeningLikeElementOrOpeningFragment(node);
  }
  function checkJsxSelfClosingElement(node, _checkMode) {
    checkNodeDeferred(node);
    return getJsxElementTypeAt(node) || anyType;
  }
  function checkJsxElementDeferred(node) {
    checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
    if (isJsxIntrinsicTagName(node.closingElement.tagName)) {
      getIntrinsicTagSymbol(node.closingElement);
    } else {
      checkExpression(node.closingElement.tagName);
    }
    checkJsxChildren(node);
  }
  function checkJsxElement(node, _checkMode) {
    checkNodeDeferred(node);
    return getJsxElementTypeAt(node) || anyType;
  }
  function checkJsxFragment(node) {
    checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
    const nodeSourceFile = getSourceFileOfNode(node);
    if (getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx")) && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) {
      error(
        node,
        compilerOptions.jsxFactory ? Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option : Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments
      );
    }
    checkJsxChildren(node);
    return getJsxElementTypeAt(node) || anyType;
  }
  function isHyphenatedJsxName(name) {
    return name.includes("-");
  }
  function isJsxIntrinsicTagName(tagName) {
    return isIdentifier(tagName) && isIntrinsicJsxName(tagName.escapedText) || isJsxNamespacedName(tagName);
  }
  function checkJsxAttribute(node, checkMode) {
    return node.initializer ? checkExpressionForMutableLocation(node.initializer, checkMode) : trueType;
  }
  function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode = 0 /* Normal */) {
    const attributes = openingLikeElement.attributes;
    const contextualType = getContextualType(attributes, ContextFlags.None);
    const allAttributesTable = strictNullChecks ? createSymbolTable() : void 0;
    let attributesTable = createSymbolTable();
    let spread = emptyJsxObjectType;
    let hasSpreadAnyType = false;
    let typeToIntersect;
    let explicitlySpecifyChildrenAttribute = false;
    let objectFlags = ObjectFlags.JsxAttributes;
    const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
    for (const attributeDecl of attributes.properties) {
      const member = attributeDecl.symbol;
      if (isJsxAttribute(attributeDecl)) {
        const exprType = checkJsxAttribute(attributeDecl, checkMode);
        objectFlags |= getObjectFlags(exprType) & ObjectFlags.PropagatingFlags;
        const attributeSymbol = createSymbol(SymbolFlags.Property | member.flags, member.escapedName);
        attributeSymbol.declarations = member.declarations;
        attributeSymbol.parent = member.parent;
        if (member.valueDeclaration) {
          attributeSymbol.valueDeclaration = member.valueDeclaration;
        }
        attributeSymbol.links.type = exprType;
        attributeSymbol.links.target = member;
        attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
        allAttributesTable?.set(attributeSymbol.escapedName, attributeSymbol);
        if (getEscapedTextOfJsxAttributeName(attributeDecl.name) === jsxChildrenPropertyName) {
          explicitlySpecifyChildrenAttribute = true;
        }
        if (contextualType) {
          const prop = getPropertyOfType(contextualType, member.escapedName);
          if (prop && prop.declarations && isDeprecatedSymbol(prop) && isIdentifier(attributeDecl.name)) {
            addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText);
          }
        }
        if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) {
          const inferenceContext = getInferenceContext(attributes);
          Debug.assert(inferenceContext);
          const inferenceNode = attributeDecl.initializer.expression;
          addIntraExpressionInferenceSite(inferenceContext, inferenceNode, exprType);
        }
      } else {
        Debug.assert(attributeDecl.kind === SyntaxKind.JsxSpreadAttribute);
        if (attributesTable.size > 0) {
          spread = getSpreadType(
            spread,
            createJsxAttributesType(),
            attributes.symbol,
            objectFlags,
            /*readonly*/
            false
          );
          attributesTable = createSymbolTable();
        }
        const exprType = getReducedType(checkExpression(attributeDecl.expression, checkMode & 2 /* Inferential */));
        if (isTypeAny(exprType)) {
          hasSpreadAnyType = true;
        }
        if (isValidSpreadType(exprType)) {
          spread = getSpreadType(
            spread,
            exprType,
            attributes.symbol,
            objectFlags,
            /*readonly*/
            false
          );
          if (allAttributesTable) {
            checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
          }
        } else {
          error(attributeDecl.expression, Diagnostics.Spread_types_may_only_be_created_from_object_types);
          typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
        }
      }
    }
    if (!hasSpreadAnyType) {
      if (attributesTable.size > 0) {
        spread = getSpreadType(
          spread,
          createJsxAttributesType(),
          attributes.symbol,
          objectFlags,
          /*readonly*/
          false
        );
      }
    }
    const parent = openingLikeElement.parent.kind === SyntaxKind.JsxElement ? openingLikeElement.parent : void 0;
    if (parent && parent.openingElement === openingLikeElement && getSemanticJsxChildren(parent.children).length > 0) {
      const childrenTypes = checkJsxChildren(parent, checkMode);
      if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
        if (explicitlySpecifyChildrenAttribute) {
          error(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName));
        }
        const contextualType2 = getApparentTypeOfContextualType(
          openingLikeElement.attributes,
          /*contextFlags*/
          void 0
        );
        const childrenContextualType = contextualType2 && getTypeOfPropertyOfContextualType(contextualType2, jsxChildrenPropertyName);
        const childrenPropSymbol = createSymbol(SymbolFlags.Property, jsxChildrenPropertyName);
        childrenPropSymbol.links.type = childrenTypes.length === 1 ? childrenTypes[0] : childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes));
        childrenPropSymbol.valueDeclaration = factory.createPropertySignature(
          /*modifiers*/
          void 0,
          unescapeLeadingUnderscores(jsxChildrenPropertyName),
          /*questionToken*/
          void 0,
          /*type*/
          void 0
        );
        setParent(childrenPropSymbol.valueDeclaration, attributes);
        childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
        const childPropMap = createSymbolTable();
        childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
        spread = getSpreadType(
          spread,
          createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, emptyArray),
          attributes.symbol,
          objectFlags,
          /*readonly*/
          false
        );
      }
    }
    if (hasSpreadAnyType) {
      return anyType;
    }
    if (typeToIntersect && spread !== emptyJsxObjectType) {
      return getIntersectionType([typeToIntersect, spread]);
    }
    return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
    function createJsxAttributesType() {
      objectFlags |= ObjectFlags.FreshLiteral;
      const result = createAnonymousType(attributes.symbol, attributesTable, emptyArray, emptyArray, emptyArray);
      result.objectFlags |= objectFlags | ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectOrArrayLiteral;
      return result;
    }
  }
  function checkJsxChildren(node, checkMode) {
    const childrenTypes = [];
    for (const child of node.children) {
      if (child.kind === SyntaxKind.JsxText) {
        if (!child.containsOnlyTriviaWhiteSpaces) {
          childrenTypes.push(stringType);
        }
      } else if (child.kind === SyntaxKind.JsxExpression && !child.expression) {
        continue;
      } else {
        childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
      }
    }
    return childrenTypes;
  }
  function checkSpreadPropOverrides(type, props, spread) {
    for (const right of getPropertiesOfType(type)) {
      if (!(right.flags & SymbolFlags.Optional)) {
        const left = props.get(right.escapedName);
        if (left) {
          const diagnostic = error(left.valueDeclaration, Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, unescapeLeadingUnderscores(left.escapedName));
          addRelatedInfo(diagnostic, createDiagnosticForNode(spread, Diagnostics.This_spread_always_overwrites_this_property));
        }
      }
    }
  }
  function checkJsxAttributes(node, checkMode) {
    return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
  }
  function getJsxType(name, location) {
    const namespace = getJsxNamespaceAt(location);
    const exports = namespace && getExportsOfSymbol(namespace);
    const typeSymbol = exports && getSymbol(exports, name, SymbolFlags.Type);
    return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
  }
  function getIntrinsicTagSymbol(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedSymbol) {
      const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
      if (!isErrorType(intrinsicElementsType)) {
        if (!isIdentifier(node.tagName) && !isJsxNamespacedName(node.tagName)) return Debug.fail();
        const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText;
        const intrinsicProp = getPropertyOfType(intrinsicElementsType, propName);
        if (intrinsicProp) {
          links.jsxFlags |= JsxFlags.IntrinsicNamedElement;
          return links.resolvedSymbol = intrinsicProp;
        }
        const indexSymbol = getApplicableIndexSymbol(intrinsicElementsType, getStringLiteralType(unescapeLeadingUnderscores(propName)));
        if (indexSymbol) {
          links.jsxFlags |= JsxFlags.IntrinsicIndexedElement;
          return links.resolvedSymbol = indexSymbol;
        }
        if (getTypeOfPropertyOrIndexSignatureOfType(intrinsicElementsType, propName)) {
          links.jsxFlags |= JsxFlags.IntrinsicIndexedElement;
          return links.resolvedSymbol = intrinsicElementsType.symbol;
        }
        error(node, Diagnostics.Property_0_does_not_exist_on_type_1, intrinsicTagNameToString(node.tagName), "JSX." + JsxNames.IntrinsicElements);
        return links.resolvedSymbol = unknownSymbol;
      } else {
        if (noImplicitAny) {
          error(node, Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
        }
        return links.resolvedSymbol = unknownSymbol;
      }
    }
    return links.resolvedSymbol;
  }
  function getJsxNamespaceContainerForImplicitImport(location) {
    const file = location && getSourceFileOfNode(location);
    const links = file && getNodeLinks(file);
    if (links && links.jsxImplicitImportContainer === false) {
      return void 0;
    }
    if (links && links.jsxImplicitImportContainer) {
      return links.jsxImplicitImportContainer;
    }
    const runtimeImportSpecifier = getJSXRuntimeImport(getJSXImplicitImportBase(compilerOptions, file), compilerOptions);
    if (!runtimeImportSpecifier) {
      return void 0;
    }
    const isClassic = getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Classic;
    const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
    const specifier = getJSXRuntimeImportSpecifier(file, runtimeImportSpecifier);
    const mod = resolveExternalModule(specifier || location, runtimeImportSpecifier, errorMessage, location);
    const result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : void 0;
    if (links) {
      links.jsxImplicitImportContainer = result || false;
    }
    return result;
  }
  function getJsxNamespaceAt(location) {
    const links = location && getNodeLinks(location);
    if (links && links.jsxNamespace) {
      return links.jsxNamespace;
    }
    if (!links || links.jsxNamespace !== false) {
      let resolvedNamespace = getJsxNamespaceContainerForImplicitImport(location);
      if (!resolvedNamespace || resolvedNamespace === unknownSymbol) {
        const namespaceName = getJsxNamespace(location);
        resolvedNamespace = resolveName(
          location,
          namespaceName,
          SymbolFlags.Namespace,
          /*nameNotFoundMessage*/
          void 0,
          /*isUse*/
          false
        );
      }
      if (resolvedNamespace) {
        const candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, SymbolFlags.Namespace));
        if (candidate && candidate !== unknownSymbol) {
          if (links) {
            links.jsxNamespace = candidate;
          }
          return candidate;
        }
      }
      if (links) {
        links.jsxNamespace = false;
      }
    }
    const s = resolveSymbol(getGlobalSymbol(
      JsxNames.JSX,
      SymbolFlags.Namespace,
      /*diagnostic*/
      void 0
    ));
    if (s === unknownSymbol) {
      return void 0;
    }
    return s;
  }
  function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
    const jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, SymbolFlags.Type);
    const jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
    const propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
    if (propertiesOfJsxElementAttribPropInterface) {
      if (propertiesOfJsxElementAttribPropInterface.length === 0) {
        return "";
      } else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
        return propertiesOfJsxElementAttribPropInterface[0].escapedName;
      } else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) {
        error(jsxElementAttribPropInterfaceSym.declarations[0], Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, unescapeLeadingUnderscores(nameOfAttribPropContainer));
      }
    }
    return void 0;
  }
  function getJsxLibraryManagedAttributes(jsxNamespace) {
    return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, SymbolFlags.Type);
  }
  function getJsxElementTypeSymbol(jsxNamespace) {
    return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementType, SymbolFlags.Type);
  }
  function getJsxElementPropertiesName(jsxNamespace) {
    return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
  }
  function getJsxElementChildrenPropertyName(jsxNamespace) {
    return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
  }
  function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
    if (elementType.flags & TypeFlags.String) {
      return [anySignature];
    } else if (elementType.flags & TypeFlags.StringLiteral) {
      const intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
      if (!intrinsicType) {
        error(caller, Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
        return emptyArray;
      } else {
        const fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
        return [fakeSignature];
      }
    }
    const apparentElemType = getApparentType(elementType);
    let signatures = getSignaturesOfType(apparentElemType, SignatureKind.Construct);
    if (signatures.length === 0) {
      signatures = getSignaturesOfType(apparentElemType, SignatureKind.Call);
    }
    if (signatures.length === 0 && apparentElemType.flags & TypeFlags.Union) {
      signatures = getUnionSignatures(map(apparentElemType.types, (t) => getUninstantiatedJsxSignaturesOfType(t, caller)));
    }
    return signatures;
  }
  function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
    const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
    if (!isErrorType(intrinsicElementsType)) {
      const stringLiteralTypeName = type.value;
      const intrinsicProp = getPropertyOfType(intrinsicElementsType, escapeLeadingUnderscores(stringLiteralTypeName));
      if (intrinsicProp) {
        return getTypeOfSymbol(intrinsicProp);
      }
      const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, stringType);
      if (indexSignatureType) {
        return indexSignatureType;
      }
      return void 0;
    }
    return anyType;
  }
  function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
    if (refKind === JsxReferenceKind.Function) {
      const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
      if (sfcReturnConstraint) {
        checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
      }
    } else if (refKind === JsxReferenceKind.Component) {
      const classConstraint = getJsxElementClassTypeAt(openingLikeElement);
      if (classConstraint) {
        checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
      }
    } else {
      const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
      const classConstraint = getJsxElementClassTypeAt(openingLikeElement);
      if (!sfcReturnConstraint || !classConstraint) {
        return;
      }
      const combined = getUnionType([sfcReturnConstraint, classConstraint]);
      checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
    }
    function generateInitialErrorChain() {
      const componentName = getTextOfNode(openingLikeElement.tagName);
      return chainDiagnosticMessages(
        /*details*/
        void 0,
        Diagnostics._0_cannot_be_used_as_a_JSX_component,
        componentName
      );
    }
  }
  function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
    Debug.assert(isJsxIntrinsicTagName(node.tagName));
    const links = getNodeLinks(node);
    if (!links.resolvedJsxElementAttributesType) {
      const symbol = getIntrinsicTagSymbol(node);
      if (links.jsxFlags & JsxFlags.IntrinsicNamedElement) {
        return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType;
      } else if (links.jsxFlags & JsxFlags.IntrinsicIndexedElement) {
        const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText;
        return links.resolvedJsxElementAttributesType = getApplicableIndexInfoForName(getJsxType(JsxNames.IntrinsicElements, node), propName)?.type || errorType;
      } else {
        return links.resolvedJsxElementAttributesType = errorType;
      }
    }
    return links.resolvedJsxElementAttributesType;
  }
  function getJsxElementClassTypeAt(location) {
    const type = getJsxType(JsxNames.ElementClass, location);
    if (isErrorType(type)) return void 0;
    return type;
  }
  function getJsxElementTypeAt(location) {
    return getJsxType(JsxNames.Element, location);
  }
  function getJsxStatelessElementTypeAt(location) {
    const jsxElementType = getJsxElementTypeAt(location);
    if (jsxElementType) {
      return getUnionType([jsxElementType, nullType]);
    }
  }
  function getJsxElementTypeTypeAt(location) {
    const ns = getJsxNamespaceAt(location);
    if (!ns) return void 0;
    const sym = getJsxElementTypeSymbol(ns);
    if (!sym) return void 0;
    const type = instantiateAliasOrInterfaceWithDefaults(sym, isInJSFile(location));
    if (!type || isErrorType(type)) return void 0;
    return type;
  }
  function instantiateAliasOrInterfaceWithDefaults(managedSym, inJs, ...typeArguments) {
    const declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
    if (managedSym.flags & SymbolFlags.TypeAlias) {
      const params = getSymbolLinks(managedSym).typeParameters;
      if (length(params) >= typeArguments.length) {
        const args = fillMissingTypeArguments(typeArguments, params, typeArguments.length, inJs);
        return length(args) === 0 ? declaredManagedType : getTypeAliasInstantiation(managedSym, args);
      }
    }
    if (length(declaredManagedType.typeParameters) >= typeArguments.length) {
      const args = fillMissingTypeArguments(typeArguments, declaredManagedType.typeParameters, typeArguments.length, inJs);
      return createTypeReference(declaredManagedType, args);
    }
    return void 0;
  }
  function getJsxIntrinsicTagNamesAt(location) {
    const intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
    return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray;
  }
  function checkJsxPreconditions(errorNode) {
    if ((compilerOptions.jsx || JsxEmit.None) === JsxEmit.None) {
      error(errorNode, Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
    }
    if (getJsxElementTypeAt(errorNode) === void 0) {
      if (noImplicitAny) {
        error(errorNode, Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
      }
    }
  }
  function checkJsxOpeningLikeElementOrOpeningFragment(node) {
    const isNodeOpeningLikeElement = isJsxOpeningLikeElement(node);
    if (isNodeOpeningLikeElement) {
      checkGrammarJsxElement(node);
    }
    checkJsxPreconditions(node);
    markJsxAliasReferenced(node);
    if (isNodeOpeningLikeElement) {
      const jsxOpeningLikeNode = node;
      const sig = getResolvedSignature(jsxOpeningLikeNode);
      checkDeprecatedSignature(sig, node);
      const elementTypeConstraint = getJsxElementTypeTypeAt(jsxOpeningLikeNode);
      if (elementTypeConstraint !== void 0) {
        const tagName = jsxOpeningLikeNode.tagName;
        const tagType = isJsxIntrinsicTagName(tagName) ? getStringLiteralType(intrinsicTagNameToString(tagName)) : checkExpression(tagName);
        checkTypeRelatedTo(tagType, elementTypeConstraint, assignableRelation, tagName, Diagnostics.Its_type_0_is_not_a_valid_JSX_element_type, () => {
          const componentName = getTextOfNode(tagName);
          return chainDiagnosticMessages(
            /*details*/
            void 0,
            Diagnostics._0_cannot_be_used_as_a_JSX_component,
            componentName
          );
        });
      } else {
        checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
      }
    }
  }
  function isKnownProperty(targetType, name, isComparingJsxAttributes) {
    if (targetType.flags & TypeFlags.Object) {
      if (getPropertyOfObjectType(targetType, name) || getApplicableIndexInfoForName(targetType, name) || isLateBoundName(name) && getIndexInfoOfType(targetType, stringType) || isComparingJsxAttributes && isHyphenatedJsxName(name)) {
        return true;
      }
    }
    if (targetType.flags & TypeFlags.Substitution) {
      return isKnownProperty(targetType.baseType, name, isComparingJsxAttributes);
    }
    if (targetType.flags & TypeFlags.UnionOrIntersection && isExcessPropertyCheckTarget(targetType)) {
      for (const t of targetType.types) {
        if (isKnownProperty(t, name, isComparingJsxAttributes)) {
          return true;
        }
      }
    }
    return false;
  }
  function isExcessPropertyCheckTarget(type) {
    return !!(type.flags & TypeFlags.Object && !(getObjectFlags(type) & ObjectFlags.ObjectLiteralPatternWithComputedProperties) || type.flags & TypeFlags.NonPrimitive || type.flags & TypeFlags.Substitution && isExcessPropertyCheckTarget(type.baseType) || type.flags & TypeFlags.Union && some(type.types, isExcessPropertyCheckTarget) || type.flags & TypeFlags.Intersection && every(type.types, isExcessPropertyCheckTarget));
  }
  function checkJsxExpression(node, checkMode) {
    checkGrammarJsxExpression(node);
    if (node.expression) {
      const type = checkExpression(node.expression, checkMode);
      if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
        error(node, Diagnostics.JSX_spread_child_must_be_an_array_type);
      }
      return type;
    } else {
      return errorType;
    }
  }
  function getDeclarationNodeFlagsFromSymbol(s) {
    return s.valueDeclaration ? getCombinedNodeFlagsCached(s.valueDeclaration) : 0;
  }
  function isPrototypeProperty(symbol) {
    if (symbol.flags & SymbolFlags.Method || getCheckFlags(symbol) & CheckFlags.SyntheticMethod) {
      return true;
    }
    if (isInJSFile(symbol.valueDeclaration)) {
      const parent = symbol.valueDeclaration.parent;
      return parent && isBinaryExpression(parent) && getAssignmentDeclarationKind(parent) === AssignmentDeclarationKind.PrototypeProperty;
    }
  }
  function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError = true) {
    const errorNode = !reportError ? void 0 : node.kind === SyntaxKind.QualifiedName ? node.right : node.kind === SyntaxKind.ImportType ? node : node.kind === SyntaxKind.BindingElement && node.propertyName ? node.propertyName : node.name;
    return checkPropertyAccessibilityAtLocation(node, isSuper, writing, type, prop, errorNode);
  }
  function checkPropertyAccessibilityAtLocation(location, isSuper, writing, containingType, prop, errorNode) {
    const flags = getDeclarationModifierFlagsFromSymbol(prop, writing);
    if (isSuper) {
      if (languageVersion < ScriptTarget.ES2015) {
        if (symbolHasNonMethodDeclaration(prop)) {
          if (errorNode) {
            error(errorNode, Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
          }
          return false;
        }
      }
      if (flags & ModifierFlags.Abstract) {
        if (errorNode) {
          error(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
        }
        return false;
      }
      if (!(flags & ModifierFlags.Static) && prop.declarations?.some(isClassInstanceProperty)) {
        if (errorNode) {
          error(errorNode, Diagnostics.Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super, symbolToString(prop));
        }
        return false;
      }
    }
    if (flags & ModifierFlags.Abstract && symbolHasNonMethodDeclaration(prop) && (isThisProperty(location) || isThisInitializedObjectBindingExpression(location) || isObjectBindingPattern(location.parent) && isThisInitializedDeclaration(location.parent.parent))) {
      const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
      if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(location)) {
        if (errorNode) {
          error(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name));
        }
        return false;
      }
    }
    if (!(flags & ModifierFlags.NonPublicAccessibilityModifier)) {
      return true;
    }
    if (flags & ModifierFlags.Private) {
      const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
      if (!isNodeWithinClass(location, declaringClassDeclaration)) {
        if (errorNode) {
          error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
        }
        return false;
      }
      return true;
    }
    if (isSuper) {
      return true;
    }
    let enclosingClass = forEachEnclosingClass(location, (enclosingDeclaration) => {
      const enclosingClass2 = getDeclaredTypeOfSymbol(getSymbolOfDeclaration(enclosingDeclaration));
      return isClassDerivedFromDeclaringClasses(enclosingClass2, prop, writing);
    });
    if (!enclosingClass) {
      enclosingClass = getEnclosingClassFromThisParameter(location);
      enclosingClass = enclosingClass && isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing);
      if (flags & ModifierFlags.Static || !enclosingClass) {
        if (errorNode) {
          error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || containingType));
        }
        return false;
      }
    }
    if (flags & ModifierFlags.Static) {
      return true;
    }
    if (containingType.flags & TypeFlags.TypeParameter) {
      containingType = containingType.isThisType ? getConstraintOfTypeParameter(containingType) : getBaseConstraintOfType(containingType);
    }
    if (!containingType || !hasBaseType(containingType, enclosingClass)) {
      if (errorNode) {
        error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(containingType));
      }
      return false;
    }
    return true;
  }
  function getEnclosingClassFromThisParameter(node) {
    const thisParameter = getThisParameterFromNodeContext(node);
    let thisType = thisParameter?.type && getTypeFromTypeNode(thisParameter.type);
    if (thisType) {
      if (thisType.flags & TypeFlags.TypeParameter) {
        thisType = getConstraintOfTypeParameter(thisType);
      }
    } else {
      const thisContainer = getThisContainer(
        node,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      );
      if (isFunctionLike(thisContainer)) {
        thisType = getContextualThisParameterType(thisContainer);
      }
    }
    if (thisType && getObjectFlags(thisType) & (ObjectFlags.ClassOrInterface | ObjectFlags.Reference)) {
      return getTargetType(thisType);
    }
    return void 0;
  }
  function getThisParameterFromNodeContext(node) {
    const thisContainer = getThisContainer(
      node,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    return thisContainer && isFunctionLike(thisContainer) ? getThisParameter(thisContainer) : void 0;
  }
  function symbolHasNonMethodDeclaration(symbol) {
    return !!forEachProperty(symbol, (prop) => !(prop.flags & SymbolFlags.Method));
  }
  function checkNonNullExpression(node) {
    return checkNonNullType(checkExpression(node), node);
  }
  function isNullableType(type) {
    return hasTypeFacts(type, 50331648 /* IsUndefinedOrNull */);
  }
  function getNonNullableTypeIfNeeded(type) {
    return isNullableType(type) ? getNonNullableType(type) : type;
  }
  function reportObjectPossiblyNullOrUndefinedError(node, facts) {
    const nodeText = isEntityNameExpression(node) ? entityNameToString(node) : void 0;
    if (node.kind === SyntaxKind.NullKeyword) {
      error(node, Diagnostics.The_value_0_cannot_be_used_here, "null");
      return;
    }
    if (nodeText !== void 0 && nodeText.length < 100) {
      if (isIdentifier(node) && nodeText === "undefined") {
        error(node, Diagnostics.The_value_0_cannot_be_used_here, "undefined");
        return;
      }
      error(
        node,
        facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics._0_is_possibly_null_or_undefined : Diagnostics._0_is_possibly_undefined : Diagnostics._0_is_possibly_null,
        nodeText
      );
    } else {
      error(
        node,
        facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Object_is_possibly_null_or_undefined : Diagnostics.Object_is_possibly_undefined : Diagnostics.Object_is_possibly_null
      );
    }
  }
  function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) {
    error(
      node,
      facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_null
    );
  }
  function checkNonNullTypeWithReporter(type, node, reportError) {
    if (strictNullChecks && type.flags & TypeFlags.Unknown) {
      if (isEntityNameExpression(node)) {
        const nodeText = entityNameToString(node);
        if (nodeText.length < 100) {
          error(node, Diagnostics._0_is_of_type_unknown, nodeText);
          return errorType;
        }
      }
      error(node, Diagnostics.Object_is_of_type_unknown);
      return errorType;
    }
    const facts = getTypeFacts(type, 50331648 /* IsUndefinedOrNull */);
    if (facts & 50331648 /* IsUndefinedOrNull */) {
      reportError(node, facts);
      const t = getNonNullableType(type);
      return t.flags & (TypeFlags.Nullable | TypeFlags.Never) ? errorType : t;
    }
    return type;
  }
  function checkNonNullType(type, node) {
    return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
  }
  function checkNonNullNonVoidType(type, node) {
    const nonNullType = checkNonNullType(type, node);
    if (nonNullType.flags & TypeFlags.Void) {
      if (isEntityNameExpression(node)) {
        const nodeText = entityNameToString(node);
        if (isIdentifier(node) && nodeText === "undefined") {
          error(node, Diagnostics.The_value_0_cannot_be_used_here, nodeText);
          return nonNullType;
        }
        if (nodeText.length < 100) {
          error(node, Diagnostics._0_is_possibly_undefined, nodeText);
          return nonNullType;
        }
      }
      error(node, Diagnostics.Object_is_possibly_undefined);
    }
    return nonNullType;
  }
  function checkPropertyAccessExpression(node, checkMode, writeOnly) {
    return node.flags & NodeFlags.OptionalChain ? checkPropertyAccessChain(node, checkMode) : checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode, writeOnly);
  }
  function checkPropertyAccessChain(node, checkMode) {
    const leftType = checkExpression(node.expression);
    const nonOptionalType = getOptionalExpressionType(leftType, node.expression);
    return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name, checkMode), node, nonOptionalType !== leftType);
  }
  function checkQualifiedName(node, checkMode) {
    const leftType = isPartOfTypeQuery(node) && isThisIdentifier(node.left) ? checkNonNullType(checkThisExpression(node.left), node.left) : checkNonNullExpression(node.left);
    return checkPropertyAccessExpressionOrQualifiedName(node, node.left, leftType, node.right, checkMode);
  }
  function isMethodAccessForCall(node) {
    while (node.parent.kind === SyntaxKind.ParenthesizedExpression) {
      node = node.parent;
    }
    return isCallOrNewExpression(node.parent) && node.parent.expression === node;
  }
  function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
    for (let containingClass = getContainingClassExcludingClassDecorators(location); !!containingClass; containingClass = getContainingClass(containingClass)) {
      const { symbol } = containingClass;
      const name = getSymbolNameForPrivateIdentifier(symbol, propName);
      const prop = symbol.members && symbol.members.get(name) || symbol.exports && symbol.exports.get(name);
      if (prop) {
        return prop;
      }
    }
  }
  function checkGrammarPrivateIdentifierExpression(privId) {
    if (!getContainingClass(privId)) {
      return grammarErrorOnNode(privId, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
    }
    if (!isForInStatement(privId.parent)) {
      if (!isExpressionNode(privId)) {
        return grammarErrorOnNode(privId, 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);
      }
      const isInOperation = isBinaryExpression(privId.parent) && privId.parent.operatorToken.kind === SyntaxKind.InKeyword;
      if (!getSymbolForPrivateIdentifierExpression(privId) && !isInOperation) {
        return grammarErrorOnNode(privId, Diagnostics.Cannot_find_name_0, idText(privId));
      }
    }
    return false;
  }
  function checkPrivateIdentifierExpression(privId) {
    checkGrammarPrivateIdentifierExpression(privId);
    const symbol = getSymbolForPrivateIdentifierExpression(privId);
    if (symbol) {
      markPropertyAsReferenced(
        symbol,
        /*nodeForCheckWriteOnly*/
        void 0,
        /*isSelfTypeAccess*/
        false
      );
    }
    return anyType;
  }
  function getSymbolForPrivateIdentifierExpression(privId) {
    if (!isExpressionNode(privId)) {
      return void 0;
    }
    const links = getNodeLinks(privId);
    if (links.resolvedSymbol === void 0) {
      links.resolvedSymbol = lookupSymbolForPrivateIdentifierDeclaration(privId.escapedText, privId);
    }
    return links.resolvedSymbol;
  }
  function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
    return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
  }
  function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
    let propertyOnType;
    const properties = getPropertiesOfType(leftType);
    if (properties) {
      forEach(properties, (symbol) => {
        const decl = symbol.valueDeclaration;
        if (decl && isNamedDeclaration(decl) && isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
          propertyOnType = symbol;
          return true;
        }
      });
    }
    const diagName = diagnosticName(right);
    if (propertyOnType) {
      const typeValueDecl = Debug.checkDefined(propertyOnType.valueDeclaration);
      const typeClass = Debug.checkDefined(getContainingClass(typeValueDecl));
      if (lexicallyScopedIdentifier?.valueDeclaration) {
        const lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
        const lexicalClass = getContainingClass(lexicalValueDecl);
        Debug.assert(!!lexicalClass);
        if (findAncestor(lexicalClass, (n) => typeClass === n)) {
          const diagnostic = error(
            right,
            Diagnostics.The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling,
            diagName,
            typeToString(leftType)
          );
          addRelatedInfo(
            diagnostic,
            createDiagnosticForNode(
              lexicalValueDecl,
              Diagnostics.The_shadowing_declaration_of_0_is_defined_here,
              diagName
            ),
            createDiagnosticForNode(
              typeValueDecl,
              Diagnostics.The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here,
              diagName
            )
          );
          return true;
        }
      }
      error(
        right,
        Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier,
        diagName,
        diagnosticName(typeClass.name || anon)
      );
      return true;
    }
    return false;
  }
  function isThisPropertyAccessInConstructor(node, prop) {
    return (isConstructorDeclaredProperty(prop) || isThisProperty(node) && isAutoTypedProperty(prop)) && getThisContainer(
      node,
      /*includeArrowFunctions*/
      true,
      /*includeClassComputedPropertyName*/
      false
    ) === getDeclaringConstructor(prop);
  }
  function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode, writeOnly) {
    const parentSymbol = getNodeLinks(left).resolvedSymbol;
    const assignmentKind = getAssignmentTargetKind(node);
    const apparentType = getApparentType(assignmentKind !== AssignmentKind.None || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
    const isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
    let prop;
    if (isPrivateIdentifier(right)) {
      if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) {
        if (assignmentKind !== AssignmentKind.None) {
          checkExternalEmitHelpers(node, ExternalEmitHelpers.ClassPrivateFieldSet);
        }
        if (assignmentKind !== AssignmentKind.Definite) {
          checkExternalEmitHelpers(node, ExternalEmitHelpers.ClassPrivateFieldGet);
        }
      }
      const lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
      if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) {
        grammarErrorOnNode(right, Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, idText(right));
      }
      if (isAnyLike) {
        if (lexicallyScopedSymbol) {
          return isErrorType(apparentType) ? errorType : apparentType;
        }
        if (getContainingClassExcludingClassDecorators(right) === void 0) {
          grammarErrorOnNode(right, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
          return anyType;
        }
      }
      prop = lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol);
      if (prop === void 0) {
        if (checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
          return errorType;
        }
        const containingClass = getContainingClassExcludingClassDecorators(right);
        if (containingClass && isPlainJsFile(getSourceFileOfNode(containingClass), compilerOptions.checkJs)) {
          grammarErrorOnNode(right, Diagnostics.Private_field_0_must_be_declared_in_an_enclosing_class, idText(right));
        }
      } else {
        const isSetonlyAccessor = prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor);
        if (isSetonlyAccessor && assignmentKind !== AssignmentKind.Definite) {
          error(node, Diagnostics.Private_accessor_was_defined_without_a_getter);
        }
      }
    } else {
      if (isAnyLike) {
        if (isIdentifier(left) && parentSymbol) {
          markLinkedReferences(
            node,
            2 /* Property */,
            /*propSymbol*/
            void 0,
            leftType
          );
        }
        return isErrorType(apparentType) ? errorType : apparentType;
      }
      prop = getPropertyOfType(
        apparentType,
        right.escapedText,
        /*skipObjectFunctionPropertyAugment*/
        isConstEnumObjectType(apparentType),
        /*includeTypeOnlyMembers*/
        node.kind === SyntaxKind.QualifiedName
      );
    }
    markLinkedReferences(node, 2 /* Property */, prop, leftType);
    let propType;
    if (!prop) {
      const indexInfo = !isPrivateIdentifier(right) && (assignmentKind === AssignmentKind.None || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getApplicableIndexInfoForName(apparentType, right.escapedText) : void 0;
      if (!(indexInfo && indexInfo.type)) {
        const isUncheckedJS = isUncheckedJSSuggestion(
          node,
          leftType.symbol,
          /*excludeClasses*/
          true
        );
        if (!isUncheckedJS && isJSLiteralType(leftType)) {
          return anyType;
        }
        if (leftType.symbol === globalThisSymbol) {
          if (globalThisSymbol.exports.has(right.escapedText) && globalThisSymbol.exports.get(right.escapedText).flags & SymbolFlags.BlockScoped) {
            error(right, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
          } else if (noImplicitAny) {
            error(right, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
          }
          return anyType;
        }
        if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
          reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS);
        }
        return errorType;
      }
      if (indexInfo.isReadonly && (isAssignmentTarget(node) || isDeleteTarget(node))) {
        error(node, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
      }
      propType = indexInfo.type;
      if (compilerOptions.noUncheckedIndexedAccess && getAssignmentTargetKind(node) !== AssignmentKind.Definite) {
        propType = getUnionType([propType, missingType]);
      }
      if (compilerOptions.noPropertyAccessFromIndexSignature && isPropertyAccessExpression(node)) {
        error(right, Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, unescapeLeadingUnderscores(right.escapedText));
      }
      if (indexInfo.declaration && isDeprecatedDeclaration(indexInfo.declaration)) {
        addDeprecatedSuggestion(right, [indexInfo.declaration], right.escapedText);
      }
    } else {
      const targetPropSymbol = resolveAliasWithDeprecationCheck(prop, right);
      if (isDeprecatedSymbol(targetPropSymbol) && isUncalledFunctionReference(node, targetPropSymbol) && targetPropSymbol.declarations) {
        addDeprecatedSuggestion(right, targetPropSymbol.declarations, right.escapedText);
      }
      checkPropertyNotUsedBeforeDeclaration(prop, node, right);
      markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol));
      getNodeLinks(node).resolvedSymbol = prop;
      checkPropertyAccessibility(node, left.kind === SyntaxKind.SuperKeyword, isWriteAccess(node), apparentType, prop);
      if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
        error(right, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, idText(right));
        return errorType;
      }
      propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writeOnly || isWriteOnlyAccess(node) ? getWriteTypeOfSymbol(prop) : getTypeOfSymbol(prop);
    }
    return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode);
  }
  function isUncheckedJSSuggestion(node, suggestion, excludeClasses) {
    const file = getSourceFileOfNode(node);
    if (file) {
      if (compilerOptions.checkJs === void 0 && file.checkJsDirective === void 0 && (file.scriptKind === ScriptKind.JS || file.scriptKind === ScriptKind.JSX)) {
        const declarationFile = forEach(suggestion?.declarations, getSourceFileOfNode);
        const suggestionHasNoExtendsOrDecorators = !suggestion?.valueDeclaration || !isClassLike(suggestion.valueDeclaration) || suggestion.valueDeclaration.heritageClauses?.length || classOrConstructorParameterIsDecorated(
          /*useLegacyDecorators*/
          false,
          suggestion.valueDeclaration
        );
        return !(file !== declarationFile && !!declarationFile && isGlobalSourceFile(declarationFile)) && !(excludeClasses && suggestion && suggestion.flags & SymbolFlags.Class && suggestionHasNoExtendsOrDecorators) && !(!!node && excludeClasses && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.ThisKeyword && suggestionHasNoExtendsOrDecorators);
      }
    }
    return false;
  }
  function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) {
    const assignmentKind = getAssignmentTargetKind(node);
    if (assignmentKind === AssignmentKind.Definite) {
      return removeMissingType(propType, !!(prop && prop.flags & SymbolFlags.Optional));
    }
    if (prop && !(prop.flags & (SymbolFlags.Variable | SymbolFlags.Property | SymbolFlags.Accessor)) && !(prop.flags & SymbolFlags.Method && propType.flags & TypeFlags.Union) && !isDuplicatedCommonJSExport(prop.declarations)) {
      return propType;
    }
    if (propType === autoType) {
      return getFlowTypeOfProperty(node, prop);
    }
    propType = getNarrowableTypeForReference(propType, node, checkMode);
    let assumeUninitialized = false;
    if (strictNullChecks && strictPropertyInitialization && isAccessExpression(node) && node.expression.kind === SyntaxKind.ThisKeyword) {
      const declaration = prop && prop.valueDeclaration;
      if (declaration && isPropertyWithoutInitializer(declaration)) {
        if (!isStatic(declaration)) {
          const flowContainer = getControlFlowContainer(node);
          if (flowContainer.kind === SyntaxKind.Constructor && flowContainer.parent === declaration.parent && !(declaration.flags & NodeFlags.Ambient)) {
            assumeUninitialized = true;
          }
        }
      }
    } else if (strictNullChecks && prop && prop.valueDeclaration && isPropertyAccessExpression(prop.valueDeclaration) && getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
      assumeUninitialized = true;
    }
    const flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
    if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) {
      error(errorNode, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop));
      return propType;
    }
    return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
  }
  function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
    const { valueDeclaration } = prop;
    if (!valueDeclaration || getSourceFileOfNode(node).isDeclarationFile) {
      return;
    }
    let diagnosticMessage;
    const declarationName = idText(right);
    if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & ModifierFlags.Static) && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) {
      diagnosticMessage = error(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
    } else if (valueDeclaration.kind === SyntaxKind.ClassDeclaration && node.parent.kind !== SyntaxKind.TypeReference && !(valueDeclaration.flags & NodeFlags.Ambient) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
      diagnosticMessage = error(right, Diagnostics.Class_0_used_before_its_declaration, declarationName);
    }
    if (diagnosticMessage) {
      addRelatedInfo(diagnosticMessage, createDiagnosticForNode(valueDeclaration, Diagnostics._0_is_declared_here, declarationName));
    }
  }
  function isInPropertyInitializerOrClassStaticBlock(node) {
    return !!findAncestor(node, (node2) => {
      switch (node2.kind) {
        case SyntaxKind.PropertyDeclaration:
          return true;
        case SyntaxKind.PropertyAssignment:
        case SyntaxKind.MethodDeclaration:
        case SyntaxKind.GetAccessor:
        case SyntaxKind.SetAccessor:
        case SyntaxKind.SpreadAssignment:
        case SyntaxKind.ComputedPropertyName:
        case SyntaxKind.TemplateSpan:
        case SyntaxKind.JsxExpression:
        case SyntaxKind.JsxAttribute:
        case SyntaxKind.JsxAttributes:
        case SyntaxKind.JsxSpreadAttribute:
        case SyntaxKind.JsxOpeningElement:
        case SyntaxKind.ExpressionWithTypeArguments:
        case SyntaxKind.HeritageClause:
          return false;
        case SyntaxKind.ArrowFunction:
        case SyntaxKind.ExpressionStatement:
          return isBlock(node2.parent) && isClassStaticBlockDeclaration(node2.parent.parent) ? true : "quit";
        default:
          return isExpressionNode(node2) ? false : "quit";
      }
    });
  }
  function isPropertyDeclaredInAncestorClass(prop) {
    if (!(prop.parent.flags & SymbolFlags.Class)) {
      return false;
    }
    let classType = getTypeOfSymbol(prop.parent);
    while (true) {
      classType = classType.symbol && getSuperClass(classType);
      if (!classType) {
        return false;
      }
      const superProperty = getPropertyOfType(classType, prop.escapedName);
      if (superProperty && superProperty.valueDeclaration) {
        return true;
      }
    }
  }
  function getSuperClass(classType) {
    const x = getBaseTypes(classType);
    if (x.length === 0) {
      return void 0;
    }
    return getIntersectionType(x);
  }
  function reportNonexistentProperty(propNode, containingType, isUncheckedJS) {
    let errorInfo;
    let relatedInfo;
    if (!isPrivateIdentifier(propNode) && containingType.flags & TypeFlags.Union && !(containingType.flags & TypeFlags.Primitive)) {
      for (const subtype of containingType.types) {
        if (!getPropertyOfType(subtype, propNode.escapedText) && !getApplicableIndexInfoForName(subtype, propNode.escapedText)) {
          errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype));
          break;
        }
      }
    }
    if (typeHasStaticProperty(propNode.escapedText, containingType)) {
      const propName = declarationNameToString(propNode);
      const typeName = typeToString(containingType);
      errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "." + propName);
    } else {
      const promisedType = getPromisedTypeOfPromise(containingType);
      if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
        errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(containingType));
        relatedInfo = createDiagnosticForNode(propNode, Diagnostics.Did_you_forget_to_use_await);
      } else {
        const missingProperty = declarationNameToString(propNode);
        const container = typeToString(containingType);
        const libSuggestion = getSuggestedLibForNonExistentProperty(missingProperty, containingType);
        if (libSuggestion !== void 0) {
          errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later, missingProperty, container, libSuggestion);
        } else {
          const suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
          if (suggestion !== void 0) {
            const suggestedName = symbolName(suggestion);
            const message = isUncheckedJS ? Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2 : Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2;
            errorInfo = chainDiagnosticMessages(errorInfo, message, missingProperty, container, suggestedName);
            relatedInfo = suggestion.valueDeclaration && createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestedName);
          } else {
            const diagnostic = containerSeemsToBeEmptyDomElement(containingType) ? Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom : Diagnostics.Property_0_does_not_exist_on_type_1;
            errorInfo = chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container);
          }
        }
      }
    }
    const resultDiagnostic = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(propNode), propNode, errorInfo);
    if (relatedInfo) {
      addRelatedInfo(resultDiagnostic, relatedInfo);
    }
    addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic);
  }
  function containerSeemsToBeEmptyDomElement(containingType) {
    return compilerOptions.lib && !compilerOptions.lib.includes("dom") && everyContainedType(containingType, (type) => type.symbol && /^(?:EventTarget|Node|(?:HTML[a-zA-Z]*)?Element)$/.test(unescapeLeadingUnderscores(type.symbol.escapedName))) && isEmptyObjectType(containingType);
  }
  function typeHasStaticProperty(propName, containingType) {
    const prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
    return prop !== void 0 && !!prop.valueDeclaration && isStatic(prop.valueDeclaration);
  }
  function getSuggestedLibForNonExistentName(name) {
    const missingName = diagnosticName(name);
    const allFeatures = getScriptTargetFeatures();
    const typeFeatures = allFeatures.get(missingName);
    return typeFeatures && firstIterator(typeFeatures.keys());
  }
  function getSuggestedLibForNonExistentProperty(missingProperty, containingType) {
    const container = getApparentType(containingType).symbol;
    if (!container) {
      return void 0;
    }
    const containingTypeName = symbolName(container);
    const allFeatures = getScriptTargetFeatures();
    const typeFeatures = allFeatures.get(containingTypeName);
    if (typeFeatures) {
      for (const [libTarget, featuresOfType] of typeFeatures) {
        if (contains(featuresOfType, missingProperty)) {
          return libTarget;
        }
      }
    }
  }
  function getSuggestedSymbolForNonexistentClassMember(name, baseType) {
    return getSpellingSuggestionForName(name, getPropertiesOfType(baseType), SymbolFlags.ClassMember);
  }
  function getSuggestedSymbolForNonexistentProperty(name, containingType) {
    let props = getPropertiesOfType(containingType);
    if (typeof name !== "string") {
      const parent = name.parent;
      if (isPropertyAccessExpression(parent)) {
        props = filter(props, (prop) => isValidPropertyAccessForCompletions(parent, containingType, prop));
      }
      name = idText(name);
    }
    return getSpellingSuggestionForName(name, props, SymbolFlags.Value);
  }
  function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) {
    const strName = isString(name) ? name : idText(name);
    const properties = getPropertiesOfType(containingType);
    const jsxSpecific = strName === "for" ? find(properties, (x) => symbolName(x) === "htmlFor") : strName === "class" ? find(properties, (x) => symbolName(x) === "className") : void 0;
    return jsxSpecific ?? getSpellingSuggestionForName(strName, properties, SymbolFlags.Value);
  }
  function getSuggestionForNonexistentProperty(name, containingType) {
    const suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
    return suggestion && symbolName(suggestion);
  }
  function getSuggestionForSymbolNameLookup(symbols, name, meaning) {
    const symbol = getSymbol(symbols, name, meaning);
    if (symbol) return symbol;
    let candidates;
    if (symbols === globals) {
      const primitives = mapDefined(
        ["string", "number", "boolean", "object", "bigint", "symbol"],
        (s) => symbols.has(s.charAt(0).toUpperCase() + s.slice(1)) ? createSymbol(SymbolFlags.TypeAlias, s) : void 0
      );
      candidates = primitives.concat(arrayFrom(symbols.values()));
    } else {
      candidates = arrayFrom(symbols.values());
    }
    return getSpellingSuggestionForName(unescapeLeadingUnderscores(name), candidates, meaning);
  }
  function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
    Debug.assert(outerName !== void 0, "outername should always be defined");
    const result = resolveNameForSymbolSuggestion(
      location,
      outerName,
      meaning,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false,
      /*excludeGlobals*/
      false
    );
    return result;
  }
  function getSuggestedSymbolForNonexistentModule(name, targetModule) {
    return targetModule.exports && getSpellingSuggestionForName(idText(name), getExportsOfModuleAsArray(targetModule), SymbolFlags.ModuleMember);
  }
  function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
    function hasProp(name) {
      const prop = getPropertyOfObjectType(objectType, name);
      if (prop) {
        const s = getSingleCallSignature(getTypeOfSymbol(prop));
        return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
      }
      return false;
    }
    const suggestedMethod = isAssignmentTarget(expr) ? "set" : "get";
    if (!hasProp(suggestedMethod)) {
      return void 0;
    }
    let suggestion = tryGetPropertyAccessOrIdentifierToString(expr.expression);
    if (suggestion === void 0) {
      suggestion = suggestedMethod;
    } else {
      suggestion += "." + suggestedMethod;
    }
    return suggestion;
  }
  function getSuggestedTypeForNonexistentStringLiteralType(source, target) {
    const candidates = target.types.filter((type) => !!(type.flags & TypeFlags.StringLiteral));
    return getSpellingSuggestion(source.value, candidates, (type) => type.value);
  }
  function getSpellingSuggestionForName(name, symbols, meaning) {
    return getSpellingSuggestion(name, symbols, getCandidateName);
    function getCandidateName(candidate) {
      const candidateName = symbolName(candidate);
      if (startsWith(candidateName, '"')) {
        return void 0;
      }
      if (candidate.flags & meaning) {
        return candidateName;
      }
      if (candidate.flags & SymbolFlags.Alias) {
        const alias = tryResolveAlias(candidate);
        if (alias && alias.flags & meaning) {
          return candidateName;
        }
      }
      return void 0;
    }
  }
  function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isSelfTypeAccess2) {
    const valueDeclaration = prop && prop.flags & SymbolFlags.ClassMember && prop.valueDeclaration;
    if (!valueDeclaration) {
      return;
    }
    const hasPrivateModifier = hasEffectiveModifier(valueDeclaration, ModifierFlags.Private);
    const hasPrivateIdentifier = prop.valueDeclaration && isNamedDeclaration(prop.valueDeclaration) && isPrivateIdentifier(prop.valueDeclaration.name);
    if (!hasPrivateModifier && !hasPrivateIdentifier) {
      return;
    }
    if (nodeForCheckWriteOnly && isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & SymbolFlags.SetAccessor)) {
      return;
    }
    if (isSelfTypeAccess2) {
      const containingMethod = findAncestor(nodeForCheckWriteOnly, isFunctionLikeDeclaration);
      if (containingMethod && containingMethod.symbol === prop) {
        return;
      }
    }
    (getCheckFlags(prop) & CheckFlags.Instantiated ? getSymbolLinks(prop).target : prop).isReferenced = SymbolFlags.All;
  }
  function isSelfTypeAccess(name, parent) {
    return name.kind === SyntaxKind.ThisKeyword || !!parent && isEntityNameExpression(name) && parent === getResolvedSymbol(getFirstIdentifier(name));
  }
  function isValidPropertyAccess(node, propertyName) {
    switch (node.kind) {
      case SyntaxKind.PropertyAccessExpression:
        return isValidPropertyAccessWithType(node, node.expression.kind === SyntaxKind.SuperKeyword, propertyName, getWidenedType(checkExpression(node.expression)));
      case SyntaxKind.QualifiedName:
        return isValidPropertyAccessWithType(
          node,
          /*isSuper*/
          false,
          propertyName,
          getWidenedType(checkExpression(node.left))
        );
      case SyntaxKind.ImportType:
        return isValidPropertyAccessWithType(
          node,
          /*isSuper*/
          false,
          propertyName,
          getTypeFromTypeNode(node)
        );
    }
  }
  function isValidPropertyAccessForCompletions(node, type, property) {
    return isPropertyAccessible(
      node,
      node.kind === SyntaxKind.PropertyAccessExpression && node.expression.kind === SyntaxKind.SuperKeyword,
      /*isWrite*/
      false,
      type,
      property
    );
  }
  function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
    if (isTypeAny(type)) {
      return true;
    }
    const prop = getPropertyOfType(type, propertyName);
    return !!prop && isPropertyAccessible(
      node,
      isSuper,
      /*isWrite*/
      false,
      type,
      prop
    );
  }
  function isPropertyAccessible(node, isSuper, isWrite, containingType, property) {
    if (isTypeAny(containingType)) {
      return true;
    }
    if (property.valueDeclaration && isPrivateIdentifierClassElementDeclaration(property.valueDeclaration)) {
      const declClass = getContainingClass(property.valueDeclaration);
      return !isOptionalChain(node) && !!findAncestor(node, (parent) => parent === declClass);
    }
    return checkPropertyAccessibilityAtLocation(node, isSuper, isWrite, containingType, property);
  }
  function getForInVariableSymbol(node) {
    const initializer = node.initializer;
    if (initializer.kind === SyntaxKind.VariableDeclarationList) {
      const variable = initializer.declarations[0];
      if (variable && !isBindingPattern(variable.name)) {
        return getSymbolOfDeclaration(variable);
      }
    } else if (initializer.kind === SyntaxKind.Identifier) {
      return getResolvedSymbol(initializer);
    }
    return void 0;
  }
  function hasNumericPropertyNames(type) {
    return getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, numberType);
  }
  function isForInVariableForNumericPropertyNames(expr) {
    const e = skipParentheses(expr);
    if (e.kind === SyntaxKind.Identifier) {
      const symbol = getResolvedSymbol(e);
      if (symbol.flags & SymbolFlags.Variable) {
        let child = expr;
        let node = expr.parent;
        while (node) {
          if (node.kind === SyntaxKind.ForInStatement && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
            return true;
          }
          child = node;
          node = node.parent;
        }
      }
    }
    return false;
  }
  function checkIndexedAccess(node, checkMode) {
    return node.flags & NodeFlags.OptionalChain ? checkElementAccessChain(node, checkMode) : checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode);
  }
  function checkElementAccessChain(node, checkMode) {
    const exprType = checkExpression(node.expression);
    const nonOptionalType = getOptionalExpressionType(exprType, node.expression);
    return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression), checkMode), node, nonOptionalType !== exprType);
  }
  function checkElementAccessExpression(node, exprType, checkMode) {
    const objectType = getAssignmentTargetKind(node) !== AssignmentKind.None || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
    const indexExpression = node.argumentExpression;
    const indexType = checkExpression(indexExpression);
    if (isErrorType(objectType) || objectType === silentNeverType) {
      return objectType;
    }
    if (isConstEnumObjectType(objectType) && !isStringLiteralLike(indexExpression)) {
      error(indexExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
      return errorType;
    }
    const effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
    const assignmentTargetKind = getAssignmentTargetKind(node);
    let accessFlags;
    if (assignmentTargetKind === AssignmentKind.None) {
      accessFlags = AccessFlags.ExpressionPosition;
    } else {
      accessFlags = AccessFlags.Writing | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? AccessFlags.NoIndexSignatures : 0);
      if (assignmentTargetKind === AssignmentKind.Compound) {
        accessFlags |= AccessFlags.ExpressionPosition;
      }
    }
    const indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, accessFlags, node) || errorType;
    return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node);
  }
  function callLikeExpressionMayHaveTypeArguments(node) {
    return isCallOrNewExpression(node) || isTaggedTemplateExpression(node) || isJsxOpeningLikeElement(node);
  }
  function resolveUntypedCall(node) {
    if (callLikeExpressionMayHaveTypeArguments(node)) {
      forEach(node.typeArguments, checkSourceElement);
    }
    if (node.kind === SyntaxKind.TaggedTemplateExpression) {
      checkExpression(node.template);
    } else if (isJsxOpeningLikeElement(node)) {
      checkExpression(node.attributes);
    } else if (isBinaryExpression(node)) {
      checkExpression(node.left);
    } else if (isCallOrNewExpression(node)) {
      forEach(node.arguments, (argument) => {
        checkExpression(argument);
      });
    }
    return anySignature;
  }
  function resolveErrorCall(node) {
    resolveUntypedCall(node);
    return unknownSignature;
  }
  function reorderCandidates(signatures, result, callChainFlags) {
    let lastParent;
    let lastSymbol;
    let cutoffIndex = 0;
    let index;
    let specializedIndex = -1;
    let spliceIndex;
    Debug.assert(!result.length);
    for (const signature of signatures) {
      const symbol = signature.declaration && getSymbolOfDeclaration(signature.declaration);
      const parent = signature.declaration && signature.declaration.parent;
      if (!lastSymbol || symbol === lastSymbol) {
        if (lastParent && parent === lastParent) {
          index = index + 1;
        } else {
          lastParent = parent;
          index = cutoffIndex;
        }
      } else {
        index = cutoffIndex = result.length;
        lastParent = parent;
      }
      lastSymbol = symbol;
      if (signatureHasLiteralTypes(signature)) {
        specializedIndex++;
        spliceIndex = specializedIndex;
        cutoffIndex++;
      } else {
        spliceIndex = index;
      }
      result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
    }
  }
  function isSpreadArgument(arg) {
    return !!arg && (arg.kind === SyntaxKind.SpreadElement || arg.kind === SyntaxKind.SyntheticExpression && arg.isSpread);
  }
  function getSpreadArgumentIndex(args) {
    return findIndex(args, isSpreadArgument);
  }
  function acceptsVoid(t) {
    return !!(t.flags & TypeFlags.Void);
  }
  function acceptsVoidUndefinedUnknownOrAny(t) {
    return !!(t.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Unknown | TypeFlags.Any));
  }
  function hasCorrectArity(node, args, signature, signatureHelpTrailingComma = false) {
    let argCount;
    let callIsIncomplete = false;
    let effectiveParameterCount = getParameterCount(signature);
    let effectiveMinimumArguments = getMinArgumentCount(signature);
    if (node.kind === SyntaxKind.TaggedTemplateExpression) {
      argCount = args.length;
      if (node.template.kind === SyntaxKind.TemplateExpression) {
        const lastSpan = last(node.template.templateSpans);
        callIsIncomplete = nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
      } else {
        const templateLiteral = node.template;
        Debug.assert(templateLiteral.kind === SyntaxKind.NoSubstitutionTemplateLiteral);
        callIsIncomplete = !!templateLiteral.isUnterminated;
      }
    } else if (node.kind === SyntaxKind.Decorator) {
      argCount = getDecoratorArgumentCount(node, signature);
    } else if (node.kind === SyntaxKind.BinaryExpression) {
      argCount = 1;
    } else if (isJsxOpeningLikeElement(node)) {
      callIsIncomplete = node.attributes.end === node.end;
      if (callIsIncomplete) {
        return true;
      }
      argCount = effectiveMinimumArguments === 0 ? args.length : 1;
      effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1;
      effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1);
    } else if (!node.arguments) {
      Debug.assert(node.kind === SyntaxKind.NewExpression);
      return getMinArgumentCount(signature) === 0;
    } else {
      argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
      callIsIncomplete = node.arguments.end === node.end;
      const spreadArgIndex = getSpreadArgumentIndex(args);
      if (spreadArgIndex >= 0) {
        return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
      }
    }
    if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
      return false;
    }
    if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
      return true;
    }
    for (let i = argCount; i < effectiveMinimumArguments; i++) {
      const type = getTypeAtPosition(signature, i);
      if (filterType(type, isInJSFile(node) && !strictNullChecks ? acceptsVoidUndefinedUnknownOrAny : acceptsVoid).flags & TypeFlags.Never) {
        return false;
      }
    }
    return true;
  }
  function hasCorrectTypeArgumentArity(signature, typeArguments) {
    const numTypeParameters = length(signature.typeParameters);
    const minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
    return !some(typeArguments) || typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters;
  }
  function isInstantiatedGenericParameter(signature, pos) {
    let type;
    return !!(signature.target && (type = tryGetTypeAtPosition(signature.target, pos)) && isGenericType(type));
  }
  function getSingleCallSignature(type) {
    return getSingleSignature(
      type,
      SignatureKind.Call,
      /*allowMembers*/
      false
    );
  }
  function getSingleCallOrConstructSignature(type) {
    return getSingleSignature(
      type,
      SignatureKind.Call,
      /*allowMembers*/
      false
    ) || getSingleSignature(
      type,
      SignatureKind.Construct,
      /*allowMembers*/
      false
    );
  }
  function getSingleSignature(type, kind, allowMembers) {
    if (type.flags & TypeFlags.Object) {
      const resolved = resolveStructuredTypeMembers(type);
      if (allowMembers || resolved.properties.length === 0 && resolved.indexInfos.length === 0) {
        if (kind === SignatureKind.Call && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
          return resolved.callSignatures[0];
        }
        if (kind === SignatureKind.Construct && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
          return resolved.constructSignatures[0];
        }
      }
    }
    return void 0;
  }
  function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
    const context = createInferenceContext(getTypeParametersForMapper(signature), signature, InferenceFlags.None, compareTypes);
    const restType = getEffectiveRestType(contextualSignature);
    const mapper = inferenceContext && (restType && restType.flags & TypeFlags.TypeParameter ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
    const sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
    applyToParameterTypes(sourceSignature, signature, (source, target) => {
      inferTypes(context.inferences, source, target);
    });
    if (!inferenceContext) {
      applyToReturnTypes(contextualSignature, signature, (source, target) => {
        inferTypes(context.inferences, source, target, InferencePriority.ReturnType);
      });
    }
    return getSignatureInstantiation(signature, getInferredTypes(context), isInJSFile(contextualSignature.declaration));
  }
  function inferJsxTypeArguments(node, signature, checkMode, context) {
    const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
    const checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
    inferTypes(context.inferences, checkAttrType, paramType);
    return getInferredTypes(context);
  }
  function getThisArgumentType(thisArgumentNode) {
    if (!thisArgumentNode) {
      return voidType;
    }
    const thisArgumentType = checkExpression(thisArgumentNode);
    return isRightSideOfInstanceofExpression(thisArgumentNode) ? thisArgumentType : isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : thisArgumentType;
  }
  function inferTypeArguments(node, signature, args, checkMode, context) {
    if (isJsxOpeningLikeElement(node)) {
      return inferJsxTypeArguments(node, signature, checkMode, context);
    }
    if (node.kind !== SyntaxKind.Decorator && node.kind !== SyntaxKind.BinaryExpression) {
      const skipBindingPatterns = every(signature.typeParameters, (p) => !!getDefaultFromTypeParameter(p));
      const contextualType = getContextualType(node, skipBindingPatterns ? ContextFlags.SkipBindingPatterns : ContextFlags.None);
      if (contextualType) {
        const inferenceTargetType = getReturnTypeOfSignature(signature);
        if (couldContainTypeVariables(inferenceTargetType)) {
          const outerContext = getInferenceContext(node);
          const isFromBindingPattern = !skipBindingPatterns && getContextualType(node, ContextFlags.SkipBindingPatterns) !== contextualType;
          if (!isFromBindingPattern) {
            const outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, InferenceFlags.NoDefault));
            const instantiatedType = instantiateType(contextualType, outerMapper);
            const contextualSignature = getSingleCallSignature(instantiatedType);
            const inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : instantiatedType;
            inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, InferencePriority.ReturnType);
          }
          const returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
          const returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
          inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
          context.returnMapper = some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : void 0;
        }
      }
    }
    const restType = getNonArrayRestType(signature);
    const argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
    if (restType && restType.flags & TypeFlags.TypeParameter) {
      const info = find(context.inferences, (info2) => info2.typeParameter === restType);
      if (info) {
        info.impliedArity = findIndex(args, isSpreadArgument, argCount) < 0 ? args.length - argCount : void 0;
      }
    }
    const thisType = getThisTypeOfSignature(signature);
    if (thisType && couldContainTypeVariables(thisType)) {
      const thisArgumentNode = getThisArgumentOfCall(node);
      inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType);
    }
    for (let i = 0; i < argCount; i++) {
      const arg = args[i];
      if (arg.kind !== SyntaxKind.OmittedExpression) {
        const paramType = getTypeAtPosition(signature, i);
        if (couldContainTypeVariables(paramType)) {
          const argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
          inferTypes(context.inferences, argType, paramType);
        }
      }
    }
    if (restType && couldContainTypeVariables(restType)) {
      const spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context, checkMode);
      inferTypes(context.inferences, spreadType, restType);
    }
    return getInferredTypes(context);
  }
  function getMutableArrayOrTupleType(type) {
    return type.flags & TypeFlags.Union ? mapType(type, getMutableArrayOrTupleType) : type.flags & TypeFlags.Any || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType(
      getElementTypes(type),
      type.target.elementFlags,
      /*readonly*/
      false,
      type.target.labeledElementDeclarations
    ) : createTupleType([type], [ElementFlags.Variadic]);
  }
  function getSpreadArgumentType(args, index, argCount, restType, context, checkMode) {
    const inConstContext = isConstTypeVariable(restType);
    if (index >= argCount - 1) {
      const arg = args[argCount - 1];
      if (isSpreadArgument(arg)) {
        const spreadType = arg.kind === SyntaxKind.SyntheticExpression ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode);
        if (isArrayLikeType(spreadType)) {
          return getMutableArrayOrTupleType(spreadType);
        }
        return createArrayType(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === SyntaxKind.SpreadElement ? arg.expression : arg), inConstContext);
      }
    }
    const types = [];
    const flags = [];
    const names = [];
    for (let i = index; i < argCount; i++) {
      const arg = args[i];
      if (isSpreadArgument(arg)) {
        const spreadType = arg.kind === SyntaxKind.SyntheticExpression ? arg.type : checkExpression(arg.expression);
        if (isArrayLikeType(spreadType)) {
          types.push(spreadType);
          flags.push(ElementFlags.Variadic);
        } else {
          types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === SyntaxKind.SpreadElement ? arg.expression : arg));
          flags.push(ElementFlags.Rest);
        }
      } else {
        const contextualType = isTupleType(restType) ? getContextualTypeForElementExpression(restType, i - index, argCount - index) || unknownType : getIndexedAccessType(restType, getNumberLiteralType(i - index), AccessFlags.Contextual);
        const argType = checkExpressionWithContextualType(arg, contextualType, context, checkMode);
        const hasPrimitiveContextualType = inConstContext || maybeTypeOfKind(contextualType, TypeFlags.Primitive | TypeFlags.Index | TypeFlags.TemplateLiteral | TypeFlags.StringMapping);
        types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
        flags.push(ElementFlags.Required);
      }
      if (arg.kind === SyntaxKind.SyntheticExpression && arg.tupleNameSource) {
        names.push(arg.tupleNameSource);
      } else {
        names.push(void 0);
      }
    }
    return createTupleType(types, flags, inConstContext && !someType(restType, isMutableArrayLikeType), names);
  }
  function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
    const isJavascript = isInJSFile(signature.declaration);
    const typeParameters = signature.typeParameters;
    const typeArgumentTypes = fillMissingTypeArguments(map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
    let mapper;
    for (let i = 0; i < typeArgumentNodes.length; i++) {
      Debug.assert(typeParameters[i] !== void 0, "Should not call checkTypeArguments with too many type arguments");
      const constraint = getConstraintOfTypeParameter(typeParameters[i]);
      if (constraint) {
        const errorInfo = reportErrors && headMessage ? () => chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.Type_0_does_not_satisfy_the_constraint_1
        ) : void 0;
        const typeArgumentHeadMessage = headMessage || Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
        if (!mapper) {
          mapper = createTypeMapper(typeParameters, typeArgumentTypes);
        }
        const typeArgument = typeArgumentTypes[i];
        if (!checkTypeAssignableTo(
          typeArgument,
          getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument),
          reportErrors ? typeArgumentNodes[i] : void 0,
          typeArgumentHeadMessage,
          errorInfo
        )) {
          return void 0;
        }
      }
    }
    return typeArgumentTypes;
  }
  function getJsxReferenceKind(node) {
    if (isJsxIntrinsicTagName(node.tagName)) {
      return JsxReferenceKind.Mixed;
    }
    const tagType = getApparentType(checkExpression(node.tagName));
    if (length(getSignaturesOfType(tagType, SignatureKind.Construct))) {
      return JsxReferenceKind.Component;
    }
    if (length(getSignaturesOfType(tagType, SignatureKind.Call))) {
      return JsxReferenceKind.Function;
    }
    return JsxReferenceKind.Mixed;
  }
  function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
    const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
    const attributesType = checkExpressionWithContextualType(
      node.attributes,
      paramType,
      /*inferenceContext*/
      void 0,
      checkMode
    );
    const checkAttributesType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(attributesType) : attributesType;
    return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(
      checkAttributesType,
      paramType,
      relation,
      reportErrors ? node.tagName : void 0,
      node.attributes,
      /*headMessage*/
      void 0,
      containingMessageChain,
      errorOutputContainer
    );
    function checkTagNameDoesNotExpectTooManyArguments() {
      if (getJsxNamespaceContainerForImplicitImport(node)) {
        return true;
      }
      const tagType = (isJsxOpeningElement(node) || isJsxSelfClosingElement(node)) && !(isJsxIntrinsicTagName(node.tagName) || isJsxNamespacedName(node.tagName)) ? checkExpression(node.tagName) : void 0;
      if (!tagType) {
        return true;
      }
      const tagCallSignatures = getSignaturesOfType(tagType, SignatureKind.Call);
      if (!length(tagCallSignatures)) {
        return true;
      }
      const factory2 = getJsxFactoryEntity(node);
      if (!factory2) {
        return true;
      }
      const factorySymbol = resolveEntityName(
        factory2,
        SymbolFlags.Value,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        false,
        node
      );
      if (!factorySymbol) {
        return true;
      }
      const factoryType = getTypeOfSymbol(factorySymbol);
      const callSignatures = getSignaturesOfType(factoryType, SignatureKind.Call);
      if (!length(callSignatures)) {
        return true;
      }
      let hasFirstParamSignatures = false;
      let maxParamCount = 0;
      for (const sig of callSignatures) {
        const firstparam = getTypeAtPosition(sig, 0);
        const signaturesOfParam = getSignaturesOfType(firstparam, SignatureKind.Call);
        if (!length(signaturesOfParam)) continue;
        for (const paramSig of signaturesOfParam) {
          hasFirstParamSignatures = true;
          if (hasEffectiveRestParameter(paramSig)) {
            return true;
          }
          const paramCount = getParameterCount(paramSig);
          if (paramCount > maxParamCount) {
            maxParamCount = paramCount;
          }
        }
      }
      if (!hasFirstParamSignatures) {
        return true;
      }
      let absoluteMinArgCount = Infinity;
      for (const tagSig of tagCallSignatures) {
        const tagRequiredArgCount = getMinArgumentCount(tagSig);
        if (tagRequiredArgCount < absoluteMinArgCount) {
          absoluteMinArgCount = tagRequiredArgCount;
        }
      }
      if (absoluteMinArgCount <= maxParamCount) {
        return true;
      }
      if (reportErrors) {
        const diag = createDiagnosticForNode(node.tagName, Diagnostics.Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3, entityNameToString(node.tagName), absoluteMinArgCount, entityNameToString(factory2), maxParamCount);
        const tagNameDeclaration = getSymbolAtLocation(node.tagName)?.valueDeclaration;
        if (tagNameDeclaration) {
          addRelatedInfo(diag, createDiagnosticForNode(tagNameDeclaration, Diagnostics._0_is_declared_here, entityNameToString(node.tagName)));
        }
        if (errorOutputContainer && errorOutputContainer.skipLogging) {
          (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
        }
        if (!errorOutputContainer.skipLogging) {
          diagnostics.add(diag);
        }
      }
      return false;
    }
  }
  function getEffectiveCheckNode(argument) {
    argument = skipParentheses(argument);
    return isSatisfiesExpression(argument) ? skipParentheses(argument.expression) : argument;
  }
  function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain, inferenceContext) {
    const errorOutputContainer = { errors: void 0, skipLogging: true };
    if (isJsxOpeningLikeElement(node)) {
      if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
        Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
        return errorOutputContainer.errors || emptyArray;
      }
      return void 0;
    }
    const thisType = getThisTypeOfSignature(signature);
    if (thisType && thisType !== voidType && !(isNewExpression(node) || isCallExpression(node) && isSuperProperty(node.expression))) {
      const thisArgumentNode = getThisArgumentOfCall(node);
      const thisArgumentType = getThisArgumentType(thisArgumentNode);
      const errorNode = reportErrors ? thisArgumentNode || node : void 0;
      const headMessage2 = Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
      if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage2, containingMessageChain, errorOutputContainer)) {
        Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
        return errorOutputContainer.errors || emptyArray;
      }
    }
    const headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
    const restType = getNonArrayRestType(signature);
    const argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
    for (let i = 0; i < argCount; i++) {
      const arg = args[i];
      if (arg.kind !== SyntaxKind.OmittedExpression) {
        const paramType = getTypeAtPosition(signature, i);
        const argType = checkExpressionWithContextualType(
          arg,
          paramType,
          /*inferenceContext*/
          void 0,
          checkMode
        );
        const regularArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
        const checkArgType = inferenceContext ? instantiateType(regularArgType, inferenceContext.nonFixingMapper) : regularArgType;
        const effectiveCheckArgumentNode = getEffectiveCheckNode(arg);
        if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? effectiveCheckArgumentNode : void 0, effectiveCheckArgumentNode, headMessage, containingMessageChain, errorOutputContainer)) {
          Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
          maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
          return errorOutputContainer.errors || emptyArray;
        }
      }
    }
    if (restType) {
      const spreadType = getSpreadArgumentType(
        args,
        argCount,
        args.length,
        restType,
        /*context*/
        void 0,
        checkMode
      );
      const restArgCount = args.length - argCount;
      const errorNode = !reportErrors ? void 0 : restArgCount === 0 ? node : restArgCount === 1 ? getEffectiveCheckNode(args[argCount]) : setTextRangePosEnd(createSyntheticExpression(node, spreadType), args[argCount].pos, args[args.length - 1].end);
      if (!checkTypeRelatedTo(
        spreadType,
        restType,
        relation,
        errorNode,
        headMessage,
        /*containingMessageChain*/
        void 0,
        errorOutputContainer
      )) {
        Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
        maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
        return errorOutputContainer.errors || emptyArray;
      }
    }
    return void 0;
    function maybeAddMissingAwaitInfo(errorNode, source, target) {
      if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
        if (getAwaitedTypeOfPromise(target)) {
          return;
        }
        const awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
        if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
          addRelatedInfo(errorOutputContainer.errors[0], createDiagnosticForNode(errorNode, Diagnostics.Did_you_forget_to_use_await));
        }
      }
    }
  }
  function getThisArgumentOfCall(node) {
    if (node.kind === SyntaxKind.BinaryExpression) {
      return node.right;
    }
    const expression = node.kind === SyntaxKind.CallExpression ? node.expression : node.kind === SyntaxKind.TaggedTemplateExpression ? node.tag : node.kind === SyntaxKind.Decorator && !legacyDecorators ? node.expression : void 0;
    if (expression) {
      const callee = skipOuterExpressions(expression);
      if (isAccessExpression(callee)) {
        return callee.expression;
      }
    }
  }
  function createSyntheticExpression(parent, type, isSpread, tupleNameSource) {
    const result = parseNodeFactory.createSyntheticExpression(type, isSpread, tupleNameSource);
    setTextRangeWorker(result, parent);
    setParent(result, parent);
    return result;
  }
  function getEffectiveCallArguments(node) {
    if (node.kind === SyntaxKind.TaggedTemplateExpression) {
      const template = node.template;
      const args2 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
      if (template.kind === SyntaxKind.TemplateExpression) {
        forEach(template.templateSpans, (span) => {
          args2.push(span.expression);
        });
      }
      return args2;
    }
    if (node.kind === SyntaxKind.Decorator) {
      return getEffectiveDecoratorArguments(node);
    }
    if (node.kind === SyntaxKind.BinaryExpression) {
      return [node.left];
    }
    if (isJsxOpeningLikeElement(node)) {
      return node.attributes.properties.length > 0 || isJsxOpeningElement(node) && node.parent.children.length > 0 ? [node.attributes] : emptyArray;
    }
    const args = node.arguments || emptyArray;
    const spreadIndex = getSpreadArgumentIndex(args);
    if (spreadIndex >= 0) {
      const effectiveArgs = args.slice(0, spreadIndex);
      for (let i = spreadIndex; i < args.length; i++) {
        const arg = args[i];
        const spreadType = arg.kind === SyntaxKind.SpreadElement && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression));
        if (spreadType && isTupleType(spreadType)) {
          forEach(getElementTypes(spreadType), (t, i2) => {
            const flags = spreadType.target.elementFlags[i2];
            const syntheticArg = createSyntheticExpression(arg, flags & ElementFlags.Rest ? createArrayType(t) : t, !!(flags & ElementFlags.Variable), spreadType.target.labeledElementDeclarations?.[i2]);
            effectiveArgs.push(syntheticArg);
          });
        } else {
          effectiveArgs.push(arg);
        }
      }
      return effectiveArgs;
    }
    return args;
  }
  function getEffectiveDecoratorArguments(node) {
    const expr = node.expression;
    const signature = getDecoratorCallSignature(node);
    if (signature) {
      const args = [];
      for (const param of signature.parameters) {
        const type = getTypeOfSymbol(param);
        args.push(createSyntheticExpression(expr, type));
      }
      return args;
    }
    return Debug.fail();
  }
  function getDecoratorArgumentCount(node, signature) {
    return compilerOptions.experimentalDecorators ? getLegacyDecoratorArgumentCount(node, signature) : (
      // Allow the runtime to oversupply arguments to an ES decorator as long as there's at least one parameter.
      Math.min(Math.max(getParameterCount(signature), 1), 2)
    );
  }
  function getLegacyDecoratorArgumentCount(node, signature) {
    switch (node.parent.kind) {
      case SyntaxKind.ClassDeclaration:
      case SyntaxKind.ClassExpression:
        return 1;
      case SyntaxKind.PropertyDeclaration:
        return hasAccessorModifier(node.parent) ? 3 : 2;
      case SyntaxKind.MethodDeclaration:
      case SyntaxKind.GetAccessor:
      case SyntaxKind.SetAccessor:
        return signature.parameters.length <= 2 ? 2 : 3;
      case SyntaxKind.Parameter:
        return 3;
      default:
        return Debug.fail();
    }
  }
  function getDiagnosticSpanForCallNode(node) {
    const sourceFile = getSourceFileOfNode(node);
    const { start, length: length2 } = getErrorSpanForNode(sourceFile, isPropertyAccessExpression(node.expression) ? node.expression.name : node.expression);
    return { start, length: length2, sourceFile };
  }
  function getDiagnosticForCallNode(node, message, ...args) {
    if (isCallExpression(node)) {
      const { sourceFile, start, length: length2 } = getDiagnosticSpanForCallNode(node);
      if ("message" in message) {
        return createFileDiagnostic(sourceFile, start, length2, message, ...args);
      }
      return createDiagnosticForFileFromMessageChain(sourceFile, message);
    } else {
      if ("message" in message) {
        return createDiagnosticForNode(node, message, ...args);
      }
      return createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node), node, message);
    }
  }
  function getErrorNodeForCallNode(callLike) {
    if (isCallOrNewExpression(callLike)) {
      return isPropertyAccessExpression(callLike.expression) ? callLike.expression.name : callLike.expression;
    }
    if (isTaggedTemplateExpression(callLike)) {
      return isPropertyAccessExpression(callLike.tag) ? callLike.tag.name : callLike.tag;
    }
    if (isJsxOpeningLikeElement(callLike)) {
      return callLike.tagName;
    }
    return callLike;
  }
  function isPromiseResolveArityError(node) {
    if (!isCallExpression(node) || !isIdentifier(node.expression)) return false;
    const symbol = resolveName(
      node.expression,
      node.expression.escapedText,
      SymbolFlags.Value,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false
    );
    const decl = symbol?.valueDeclaration;
    if (!decl || !isParameter(decl) || !isFunctionExpressionOrArrowFunction(decl.parent) || !isNewExpression(decl.parent.parent) || !isIdentifier(decl.parent.parent.expression)) {
      return false;
    }
    const globalPromiseSymbol = getGlobalPromiseConstructorSymbol(
      /*reportErrors*/
      false
    );
    if (!globalPromiseSymbol) return false;
    const constructorSymbol = getSymbolAtLocation(
      decl.parent.parent.expression,
      /*ignoreErrors*/
      true
    );
    return constructorSymbol === globalPromiseSymbol;
  }
  function getArgumentArityError(node, signatures, args, headMessage) {
    const spreadIndex = getSpreadArgumentIndex(args);
    if (spreadIndex > -1) {
      return createDiagnosticForNode(args[spreadIndex], Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter);
    }
    let min = Number.POSITIVE_INFINITY;
    let max = Number.NEGATIVE_INFINITY;
    let maxBelow = Number.NEGATIVE_INFINITY;
    let minAbove = Number.POSITIVE_INFINITY;
    let closestSignature;
    for (const sig of signatures) {
      const minParameter = getMinArgumentCount(sig);
      const maxParameter = getParameterCount(sig);
      if (minParameter < min) {
        min = minParameter;
        closestSignature = sig;
      }
      max = Math.max(max, maxParameter);
      if (minParameter < args.length && minParameter > maxBelow) maxBelow = minParameter;
      if (args.length < maxParameter && maxParameter < minAbove) minAbove = maxParameter;
    }
    const hasRestParameter2 = some(signatures, hasEffectiveRestParameter);
    const parameterRange = hasRestParameter2 ? min : min < max ? min + "-" + max : min;
    const isVoidPromiseError = !hasRestParameter2 && parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node);
    if (isVoidPromiseError && isInJSFile(node)) {
      return getDiagnosticForCallNode(node, Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments);
    }
    const error2 = isDecorator(node) ? hasRestParameter2 ? Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0 : Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0 : hasRestParameter2 ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : isVoidPromiseError ? Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : Diagnostics.Expected_0_arguments_but_got_1;
    if (min < args.length && args.length < max) {
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments,
          args.length,
          maxBelow,
          minAbove
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        return getDiagnosticForCallNode(node, chain);
      }
      return getDiagnosticForCallNode(node, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove);
    } else if (args.length < min) {
      let diagnostic;
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          error2,
          parameterRange,
          args.length
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        diagnostic = getDiagnosticForCallNode(node, chain);
      } else {
        diagnostic = getDiagnosticForCallNode(node, error2, parameterRange, args.length);
      }
      const parameter = closestSignature?.declaration?.parameters[closestSignature.thisParameter ? args.length + 1 : args.length];
      if (parameter) {
        const messageAndArgs = isBindingPattern(parameter.name) ? [Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided] : isRestParameter(parameter) ? [Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided, idText(getFirstIdentifier(parameter.name))] : [Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : idText(getFirstIdentifier(parameter.name))];
        const parameterError = createDiagnosticForNode(parameter, ...messageAndArgs);
        return addRelatedInfo(diagnostic, parameterError);
      }
      return diagnostic;
    } else {
      const errorSpan = factory.createNodeArray(args.slice(max));
      const pos = first(errorSpan).pos;
      let end = last(errorSpan).end;
      if (end === pos) {
        end++;
      }
      setTextRangePosEnd(errorSpan, pos, end);
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          error2,
          parameterRange,
          args.length
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), errorSpan, chain);
      }
      return createDiagnosticForNodeArray(getSourceFileOfNode(node), errorSpan, error2, parameterRange, args.length);
    }
  }
  function getTypeArgumentArityError(node, signatures, typeArguments, headMessage) {
    const argCount = typeArguments.length;
    if (signatures.length === 1) {
      const sig = signatures[0];
      const min = getMinTypeArgumentCount(sig.typeParameters);
      const max = length(sig.typeParameters);
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.Expected_0_type_arguments_but_got_1,
          min < max ? min + "-" + max : min,
          argCount
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain);
      }
      return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, min < max ? min + "-" + max : min, argCount);
    }
    let belowArgCount = -Infinity;
    let aboveArgCount = Infinity;
    for (const sig of signatures) {
      const min = getMinTypeArgumentCount(sig.typeParameters);
      const max = length(sig.typeParameters);
      if (min > argCount) {
        aboveArgCount = Math.min(aboveArgCount, min);
      } else if (max < argCount) {
        belowArgCount = Math.max(belowArgCount, max);
      }
    }
    if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments,
          argCount,
          belowArgCount,
          aboveArgCount
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain);
      }
      return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount);
    }
    if (headMessage) {
      let chain = chainDiagnosticMessages(
        /*details*/
        void 0,
        Diagnostics.Expected_0_type_arguments_but_got_1,
        belowArgCount === -Infinity ? aboveArgCount : belowArgCount,
        argCount
      );
      chain = chainDiagnosticMessages(chain, headMessage);
      return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain);
    }
    return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
  }
  function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, headMessage) {
    const isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression;
    const isDecorator2 = node.kind === SyntaxKind.Decorator;
    const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node);
    const isInstanceof = node.kind === SyntaxKind.BinaryExpression;
    const reportErrors = !isInferencePartiallyBlocked && !candidatesOutArray;
    let typeArguments;
    if (!isDecorator2 && !isInstanceof && !isSuperCall(node)) {
      typeArguments = node.typeArguments;
      if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== SyntaxKind.SuperKeyword) {
        forEach(typeArguments, checkSourceElement);
      }
    }
    const candidates = candidatesOutArray || [];
    reorderCandidates(signatures, candidates, callChainFlags);
    Debug.assert(candidates.length, "Revert #54442 and add a testcase with whatever triggered this");
    const args = getEffectiveCallArguments(node);
    const isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
    let argCheckMode = !isDecorator2 && !isSingleNonGenericCandidate && some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
    let candidatesForArgumentError;
    let candidateForArgumentArityError;
    let candidateForTypeArgumentError;
    let result;
    const signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === SyntaxKind.CallExpression && node.arguments.hasTrailingComma;
    if (candidates.length > 1) {
      result = chooseOverload(candidates, subtypeRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
    }
    if (!result) {
      result = chooseOverload(candidates, assignableRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
    }
    if (result) {
      return result;
    }
    result = getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode);
    getNodeLinks(node).resolvedSignature = result;
    if (reportErrors) {
      if (!headMessage && isInstanceof) {
        headMessage = Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_hand_side_s_Symbol_hasInstance_method;
      }
      if (candidatesForArgumentError) {
        if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
          const last2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
          let chain;
          if (candidatesForArgumentError.length > 3) {
            chain = chainDiagnosticMessages(chain, Diagnostics.The_last_overload_gave_the_following_error);
            chain = chainDiagnosticMessages(chain, Diagnostics.No_overload_matches_this_call);
          }
          if (headMessage) {
            chain = chainDiagnosticMessages(chain, headMessage);
          }
          const diags = getSignatureApplicabilityError(
            node,
            args,
            last2,
            assignableRelation,
            0 /* Normal */,
            /*reportErrors*/
            true,
            () => chain,
            /*inferenceContext*/
            void 0
          );
          if (diags) {
            for (const d of diags) {
              if (last2.declaration && candidatesForArgumentError.length > 3) {
                addRelatedInfo(d, createDiagnosticForNode(last2.declaration, Diagnostics.The_last_overload_is_declared_here));
              }
              addImplementationSuccessElaboration(last2, d);
              diagnostics.add(d);
            }
          } else {
            Debug.fail("No error for last overload signature");
          }
        } else {
          const allDiagnostics = [];
          let max = 0;
          let min = Number.MAX_VALUE;
          let minIndex = 0;
          let i = 0;
          for (const c of candidatesForArgumentError) {
            const chain2 = () => chainDiagnosticMessages(
              /*details*/
              void 0,
              Diagnostics.Overload_0_of_1_2_gave_the_following_error,
              i + 1,
              candidates.length,
              signatureToString(c)
            );
            const diags2 = getSignatureApplicabilityError(
              node,
              args,
              c,
              assignableRelation,
              0 /* Normal */,
              /*reportErrors*/
              true,
              chain2,
              /*inferenceContext*/
              void 0
            );
            if (diags2) {
              if (diags2.length <= min) {
                min = diags2.length;
                minIndex = i;
              }
              max = Math.max(max, diags2.length);
              allDiagnostics.push(diags2);
            } else {
              Debug.fail("No error for 3 or fewer overload signatures");
            }
            i++;
          }
          const diags = max > 1 ? allDiagnostics[minIndex] : flatten(allDiagnostics);
          Debug.assert(diags.length > 0, "No errors reported for 3 or fewer overload signatures");
          let chain = chainDiagnosticMessages(
            map(diags, createDiagnosticMessageChainFromDiagnostic),
            Diagnostics.No_overload_matches_this_call
          );
          if (headMessage) {
            chain = chainDiagnosticMessages(chain, headMessage);
          }
          const related = [...flatMap(diags, (d) => d.relatedInformation)];
          let diag;
          if (every(diags, (d) => d.start === diags[0].start && d.length === diags[0].length && d.file === diags[0].file)) {
            const { file, start, length: length2 } = diags[0];
            diag = { file, start, length: length2, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related };
          } else {
            diag = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node), getErrorNodeForCallNode(node), chain, related);
          }
          addImplementationSuccessElaboration(candidatesForArgumentError[0], diag);
          diagnostics.add(diag);
        }
      } else if (candidateForArgumentArityError) {
        diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args, headMessage));
      } else if (candidateForTypeArgumentError) {
        checkTypeArguments(
          candidateForTypeArgumentError,
          node.typeArguments,
          /*reportErrors*/
          true,
          headMessage
        );
      } else {
        const signaturesWithCorrectTypeArgumentArity = filter(signatures, (s) => hasCorrectTypeArgumentArity(s, typeArguments));
        if (signaturesWithCorrectTypeArgumentArity.length === 0) {
          diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments, headMessage));
        } else {
          diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args, headMessage));
        }
      }
    }
    return result;
    function addImplementationSuccessElaboration(failed, diagnostic) {
      const oldCandidatesForArgumentError = candidatesForArgumentError;
      const oldCandidateForArgumentArityError = candidateForArgumentArityError;
      const oldCandidateForTypeArgumentError = candidateForTypeArgumentError;
      const failedSignatureDeclarations = failed.declaration?.symbol?.declarations || emptyArray;
      const isOverload = failedSignatureDeclarations.length > 1;
      const implDecl = isOverload ? find(failedSignatureDeclarations, (d) => isFunctionLikeDeclaration(d) && nodeIsPresent(d.body)) : void 0;
      if (implDecl) {
        const candidate = getSignatureFromDeclaration(implDecl);
        const isSingleNonGenericCandidate2 = !candidate.typeParameters;
        if (chooseOverload([candidate], assignableRelation, isSingleNonGenericCandidate2)) {
          addRelatedInfo(diagnostic, createDiagnosticForNode(implDecl, Diagnostics.The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_are_not_externally_visible));
        }
      }
      candidatesForArgumentError = oldCandidatesForArgumentError;
      candidateForArgumentArityError = oldCandidateForArgumentArityError;
      candidateForTypeArgumentError = oldCandidateForTypeArgumentError;
    }
    function chooseOverload(candidates2, relation, isSingleNonGenericCandidate2, signatureHelpTrailingComma2 = false) {
      candidatesForArgumentError = void 0;
      candidateForArgumentArityError = void 0;
      candidateForTypeArgumentError = void 0;
      if (isSingleNonGenericCandidate2) {
        const candidate = candidates2[0];
        if (some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma2)) {
          return void 0;
        }
        if (getSignatureApplicabilityError(
          node,
          args,
          candidate,
          relation,
          0 /* Normal */,
          /*reportErrors*/
          false,
          /*containingMessageChain*/
          void 0,
          /*inferenceContext*/
          void 0
        )) {
          candidatesForArgumentError = [candidate];
          return void 0;
        }
        return candidate;
      }
      for (let candidateIndex = 0; candidateIndex < candidates2.length; candidateIndex++) {
        let candidate = candidates2[candidateIndex];
        if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma2)) {
          continue;
        }
        let checkCandidate;
        let inferenceContext;
        if (candidate.typeParameters) {
          const paramLocation = candidate.typeParameters[0].symbol.declarations?.[0]?.parent;
          const candidateParameterContext = paramLocation || (candidate.declaration && isConstructorDeclaration(candidate.declaration) ? candidate.declaration.parent : candidate.declaration);
          if (candidateParameterContext && findAncestor(node, (a) => a === candidateParameterContext)) {
            candidate = getImplementationSignature(candidate);
          }
          let typeArgumentTypes;
          if (some(typeArguments)) {
            typeArgumentTypes = checkTypeArguments(
              candidate,
              typeArguments,
              /*reportErrors*/
              false
            );
            if (!typeArgumentTypes) {
              candidateForTypeArgumentError = candidate;
              continue;
            }
          } else {
            inferenceContext = createInferenceContext(
              candidate.typeParameters,
              candidate,
              /*flags*/
              isInJSFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None
            );
            typeArgumentTypes = instantiateTypes(inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext), inferenceContext.nonFixingMapper);
            argCheckMode |= inferenceContext.flags & InferenceFlags.SkippedGenericFunction ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
          }
          checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
          if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma2)) {
            candidateForArgumentArityError = checkCandidate;
            continue;
          }
        } else {
          checkCandidate = candidate;
        }
        if (getSignatureApplicabilityError(
          node,
          args,
          checkCandidate,
          relation,
          argCheckMode,
          /*reportErrors*/
          false,
          /*containingMessageChain*/
          void 0,
          inferenceContext
        )) {
          (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
          continue;
        }
        if (argCheckMode) {
          argCheckMode = 0 /* Normal */;
          if (inferenceContext) {
            const typeArgumentTypes = instantiateTypes(inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext), inferenceContext.mapper);
            checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration), inferenceContext.inferredTypeParameters);
            if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma2)) {
              candidateForArgumentArityError = checkCandidate;
              continue;
            }
          }
          if (getSignatureApplicabilityError(
            node,
            args,
            checkCandidate,
            relation,
            argCheckMode,
            /*reportErrors*/
            false,
            /*containingMessageChain*/
            void 0,
            inferenceContext
          )) {
            (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
            continue;
          }
        }
        candidates2[candidateIndex] = checkCandidate;
        return checkCandidate;
      }
      return void 0;
    }
  }
  function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray, checkMode) {
    Debug.assert(candidates.length > 0);
    checkNodeDeferred(node);
    return hasCandidatesOutArray || candidates.length === 1 || candidates.some((c) => !!c.typeParameters) ? pickLongestCandidateSignature(node, candidates, args, checkMode) : createUnionOfSignaturesForOverloadFailure(candidates);
  }
  function createUnionOfSignaturesForOverloadFailure(candidates) {
    const thisParameters = mapDefined(candidates, (c) => c.thisParameter);
    let thisParameter;
    if (thisParameters.length) {
      thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
    }
    const { min: minArgumentCount, max: maxNonRestParam } = minAndMax(candidates, getNumNonRestParameters);
    const parameters = [];
    for (let i = 0; i < maxNonRestParam; i++) {
      const symbols = mapDefined(candidates, (s) => signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : last(s.parameters) : i < s.parameters.length ? s.parameters[i] : void 0);
      Debug.assert(symbols.length !== 0);
      parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, (candidate) => tryGetTypeAtPosition(candidate, i))));
    }
    const restParameterSymbols = mapDefined(candidates, (c) => signatureHasRestParameter(c) ? last(c.parameters) : void 0);
    let flags = SignatureFlags.IsSignatureCandidateForOverloadFailure;
    if (restParameterSymbols.length !== 0) {
      const type = createArrayType(getUnionType(mapDefined(candidates, tryGetRestTypeOfSignature), UnionReduction.Subtype));
      parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
      flags |= SignatureFlags.HasRestParameter;
    }
    if (candidates.some(signatureHasLiteralTypes)) {
      flags |= SignatureFlags.HasLiteralTypes;
    }
    return createSignature(
      candidates[0].declaration,
      /*typeParameters*/
      void 0,
      // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
      thisParameter,
      parameters,
      /*resolvedReturnType*/
      getIntersectionType(candidates.map(getReturnTypeOfSignature)),
      /*resolvedTypePredicate*/
      void 0,
      minArgumentCount,
      flags
    );
  }
  function getNumNonRestParameters(signature) {
    const numParams = signature.parameters.length;
    return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
  }
  function createCombinedSymbolFromTypes(sources, types) {
    return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, UnionReduction.Subtype));
  }
  function createCombinedSymbolForOverloadFailure(sources, type) {
    return createSymbolWithType(first(sources), type);
  }
  function pickLongestCandidateSignature(node, candidates, args, checkMode) {
    const bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === void 0 ? args.length : apparentArgumentCount);
    const candidate = candidates[bestIndex];
    const { typeParameters } = candidate;
    if (!typeParameters) {
      return candidate;
    }
    const typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : void 0;
    const instantiated = typeArgumentNodes ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isInJSFile(node))) : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args, checkMode);
    candidates[bestIndex] = instantiated;
    return instantiated;
  }
  function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
    const typeArguments = typeArgumentNodes.map(getTypeOfNode);
    while (typeArguments.length > typeParameters.length) {
      typeArguments.pop();
    }
    while (typeArguments.length < typeParameters.length) {
      typeArguments.push(getDefaultFromTypeParameter(typeParameters[typeArguments.length]) || getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
    }
    return typeArguments;
  }
  function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args, checkMode) {
    const inferenceContext = createInferenceContext(
      typeParameters,
      candidate,
      /*flags*/
      isInJSFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None
    );
    const typeArgumentTypes = inferTypeArguments(node, candidate, args, checkMode | 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
    return createSignatureInstantiation(candidate, typeArgumentTypes);
  }
  function getLongestCandidateIndex(candidates, argsCount) {
    let maxParamsIndex = -1;
    let maxParams = -1;
    for (let i = 0; i < candidates.length; i++) {
      const candidate = candidates[i];
      const paramCount = getParameterCount(candidate);
      if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
        return i;
      }
      if (paramCount > maxParams) {
        maxParams = paramCount;
        maxParamsIndex = i;
      }
    }
    return maxParamsIndex;
  }
  function resolveCallExpression(node, candidatesOutArray, checkMode) {
    if (node.expression.kind === SyntaxKind.SuperKeyword) {
      const superType = checkSuperExpression(node.expression);
      if (isTypeAny(superType)) {
        for (const arg of node.arguments) {
          checkExpression(arg);
        }
        return anySignature;
      }
      if (!isErrorType(superType)) {
        const baseTypeNode = getEffectiveBaseTypeNode(getContainingClass(node));
        if (baseTypeNode) {
          const baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
          return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, SignatureFlags.None);
        }
      }
      return resolveUntypedCall(node);
    }
    let callChainFlags;
    let funcType = checkExpression(node.expression);
    if (isCallChain(node)) {
      const nonOptionalType = getOptionalExpressionType(funcType, node.expression);
      callChainFlags = nonOptionalType === funcType ? SignatureFlags.None : isOutermostOptionalChain(node) ? SignatureFlags.IsOuterCallChain : SignatureFlags.IsInnerCallChain;
      funcType = nonOptionalType;
    } else {
      callChainFlags = SignatureFlags.None;
    }
    funcType = checkNonNullTypeWithReporter(
      funcType,
      node.expression,
      reportCannotInvokePossiblyNullOrUndefinedError
    );
    if (funcType === silentNeverType) {
      return silentNeverSignature;
    }
    const apparentType = getApparentType(funcType);
    if (isErrorType(apparentType)) {
      return resolveErrorCall(node);
    }
    const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call);
    const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length;
    if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
      if (!isErrorType(funcType) && node.typeArguments) {
        error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
      }
      return resolveUntypedCall(node);
    }
    if (!callSignatures.length) {
      if (numConstructSignatures) {
        error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
      } else {
        let relatedInformation;
        if (node.arguments.length === 1) {
          const text = getSourceFileOfNode(node).text;
          if (isLineBreak(text.charCodeAt(skipTrivia(
            text,
            node.expression.end,
            /*stopAfterLineBreak*/
            true
          ) - 1))) {
            relatedInformation = createDiagnosticForNode(node.expression, Diagnostics.Are_you_missing_a_semicolon);
          }
        }
        invocationError(node.expression, apparentType, SignatureKind.Call, relatedInformation);
      }
      return resolveErrorCall(node);
    }
    if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
      skippedGenericFunction(node, checkMode);
      return resolvingSignature;
    }
    if (callSignatures.some((sig) => isInJSFile(sig.declaration) && !!getJSDocClassTag(sig.declaration))) {
      error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
      return resolveErrorCall(node);
    }
    return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
  }
  function isGenericFunctionReturningFunction(signature) {
    return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
  }
  function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
    return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & TypeFlags.TypeParameter) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & TypeFlags.Union) && !(getReducedType(apparentFuncType).flags & TypeFlags.Never) && isTypeAssignableTo(funcType, globalFunctionType);
  }
  function resolveNewExpression(node, candidatesOutArray, checkMode) {
    let expressionType = checkNonNullExpression(node.expression);
    if (expressionType === silentNeverType) {
      return silentNeverSignature;
    }
    expressionType = getApparentType(expressionType);
    if (isErrorType(expressionType)) {
      return resolveErrorCall(node);
    }
    if (isTypeAny(expressionType)) {
      if (node.typeArguments) {
        error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
      }
      return resolveUntypedCall(node);
    }
    const constructSignatures = getSignaturesOfType(expressionType, SignatureKind.Construct);
    if (constructSignatures.length) {
      if (!isConstructorAccessible(node, constructSignatures[0])) {
        return resolveErrorCall(node);
      }
      if (someSignature(constructSignatures, (signature) => !!(signature.flags & SignatureFlags.Abstract))) {
        error(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
        return resolveErrorCall(node);
      }
      const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol);
      if (valueDecl && hasSyntacticModifier(valueDecl, ModifierFlags.Abstract)) {
        error(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
        return resolveErrorCall(node);
      }
      return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, SignatureFlags.None);
    }
    const callSignatures = getSignaturesOfType(expressionType, SignatureKind.Call);
    if (callSignatures.length) {
      const signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, SignatureFlags.None);
      if (!noImplicitAny) {
        if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
          error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
        }
        if (getThisTypeOfSignature(signature) === voidType) {
          error(node, Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
        }
      }
      return signature;
    }
    invocationError(node.expression, expressionType, SignatureKind.Construct);
    return resolveErrorCall(node);
  }
  function someSignature(signatures, f) {
    if (isArray(signatures)) {
      return some(signatures, (signature) => someSignature(signature, f));
    }
    return signatures.compositeKind === TypeFlags.Union ? some(signatures.compositeSignatures, f) : f(signatures);
  }
  function typeHasProtectedAccessibleBase(target, type) {
    const baseTypes = getBaseTypes(type);
    if (!length(baseTypes)) {
      return false;
    }
    const firstBase = baseTypes[0];
    if (firstBase.flags & TypeFlags.Intersection) {
      const types = firstBase.types;
      const mixinFlags = findMixins(types);
      let i = 0;
      for (const intersectionMember of firstBase.types) {
        if (!mixinFlags[i]) {
          if (getObjectFlags(intersectionMember) & (ObjectFlags.Class | ObjectFlags.Interface)) {
            if (intersectionMember.symbol === target) {
              return true;
            }
            if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
              return true;
            }
          }
        }
        i++;
      }
      return false;
    }
    if (firstBase.symbol === target) {
      return true;
    }
    return typeHasProtectedAccessibleBase(target, firstBase);
  }
  function isConstructorAccessible(node, signature) {
    if (!signature || !signature.declaration) {
      return true;
    }
    const declaration = signature.declaration;
    const modifiers = getSelectedEffectiveModifierFlags(declaration, ModifierFlags.NonPublicAccessibilityModifier);
    if (!modifiers || declaration.kind !== SyntaxKind.Constructor) {
      return true;
    }
    const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
    const declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
    if (!isNodeWithinClass(node, declaringClassDeclaration)) {
      const containingClass = getContainingClass(node);
      if (containingClass && modifiers & ModifierFlags.Protected) {
        const containingType = getTypeOfNode(containingClass);
        if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
          return true;
        }
      }
      if (modifiers & ModifierFlags.Private) {
        error(node, Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
      }
      if (modifiers & ModifierFlags.Protected) {
        error(node, Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
      }
      return false;
    }
    return true;
  }
  function invocationErrorDetails(errorTarget, apparentType, kind) {
    let errorInfo;
    const isCall = kind === SignatureKind.Call;
    const awaitedType = getAwaitedType(apparentType);
    const maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
    if (apparentType.flags & TypeFlags.Union) {
      const types = apparentType.types;
      let hasSignatures = false;
      for (const constituent of types) {
        const signatures = getSignaturesOfType(constituent, kind);
        if (signatures.length !== 0) {
          hasSignatures = true;
          if (errorInfo) {
            break;
          }
        } else {
          if (!errorInfo) {
            errorInfo = chainDiagnosticMessages(
              errorInfo,
              isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures,
              typeToString(constituent)
            );
            errorInfo = chainDiagnosticMessages(
              errorInfo,
              isCall ? Diagnostics.Not_all_constituents_of_type_0_are_callable : Diagnostics.Not_all_constituents_of_type_0_are_constructable,
              typeToString(apparentType)
            );
          }
          if (hasSignatures) {
            break;
          }
        }
      }
      if (!hasSignatures) {
        errorInfo = chainDiagnosticMessages(
          /*details*/
          void 0,
          isCall ? Diagnostics.No_constituent_of_type_0_is_callable : Diagnostics.No_constituent_of_type_0_is_constructable,
          typeToString(apparentType)
        );
      }
      if (!errorInfo) {
        errorInfo = chainDiagnosticMessages(
          errorInfo,
          isCall ? Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other : Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other,
          typeToString(apparentType)
        );
      }
    } else {
      errorInfo = chainDiagnosticMessages(
        errorInfo,
        isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures,
        typeToString(apparentType)
      );
    }
    let headMessage = isCall ? Diagnostics.This_expression_is_not_callable : Diagnostics.This_expression_is_not_constructable;
    if (isCallExpression(errorTarget.parent) && errorTarget.parent.arguments.length === 0) {
      const { resolvedSymbol } = getNodeLinks(errorTarget);
      if (resolvedSymbol && resolvedSymbol.flags & SymbolFlags.GetAccessor) {
        headMessage = Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without;
      }
    }
    return {
      messageChain: chainDiagnosticMessages(errorInfo, headMessage),
      relatedMessage: maybeMissingAwait ? Diagnostics.Did_you_forget_to_use_await : void 0
    };
  }
  function invocationError(errorTarget, apparentType, kind, relatedInformation) {
    const { messageChain, relatedMessage: relatedInfo } = invocationErrorDetails(errorTarget, apparentType, kind);
    const diagnostic = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorTarget), errorTarget, messageChain);
    if (relatedInfo) {
      addRelatedInfo(diagnostic, createDiagnosticForNode(errorTarget, relatedInfo));
    }
    if (isCallExpression(errorTarget.parent)) {
      const { start, length: length2 } = getDiagnosticSpanForCallNode(errorTarget.parent);
      diagnostic.start = start;
      diagnostic.length = length2;
    }
    diagnostics.add(diagnostic);
    invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
  }
  function invocationErrorRecovery(apparentType, kind, diagnostic) {
    if (!apparentType.symbol) {
      return;
    }
    const importNode = getSymbolLinks(apparentType.symbol).originatingImport;
    if (importNode && !isImportCall(importNode)) {
      const sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
      if (!sigs || !sigs.length) return;
      addRelatedInfo(diagnostic, createDiagnosticForNode(importNode, Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
    }
  }
  function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
    const tagType = checkExpression(node.tag);
    const apparentType = getApparentType(tagType);
    if (isErrorType(apparentType)) {
      return resolveErrorCall(node);
    }
    const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call);
    const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length;
    if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
      return resolveUntypedCall(node);
    }
    if (!callSignatures.length) {
      if (isArrayLiteralExpression(node.parent)) {
        const diagnostic = createDiagnosticForNode(node.tag, Diagnostics.It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked);
        diagnostics.add(diagnostic);
        return resolveErrorCall(node);
      }
      invocationError(node.tag, apparentType, SignatureKind.Call);
      return resolveErrorCall(node);
    }
    return resolveCall(node, callSignatures, candidatesOutArray, checkMode, SignatureFlags.None);
  }
  function getDiagnosticHeadMessageForDecoratorResolution(node) {
    switch (node.parent.kind) {
      case SyntaxKind.ClassDeclaration:
      case SyntaxKind.ClassExpression:
        return Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
      case SyntaxKind.Parameter:
        return Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
      case SyntaxKind.PropertyDeclaration:
        return Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
      case SyntaxKind.MethodDeclaration:
      case SyntaxKind.GetAccessor:
      case SyntaxKind.SetAccessor:
        return Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
      default:
        return Debug.fail();
    }
  }
  function resolveDecorator(node, candidatesOutArray, checkMode) {
    const funcType = checkExpression(node.expression);
    const apparentType = getApparentType(funcType);
    if (isErrorType(apparentType)) {
      return resolveErrorCall(node);
    }
    const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call);
    const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length;
    if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
      return resolveUntypedCall(node);
    }
    if (isPotentiallyUncalledDecorator(node, callSignatures) && !isParenthesizedExpression(node.expression)) {
      const nodeStr = getTextOfNode(
        node.expression,
        /*includeTrivia*/
        false
      );
      error(node, Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr);
      return resolveErrorCall(node);
    }
    const headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
    if (!callSignatures.length) {
      const errorDetails = invocationErrorDetails(node.expression, apparentType, SignatureKind.Call);
      const messageChain = chainDiagnosticMessages(errorDetails.messageChain, headMessage);
      const diag = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node.expression), node.expression, messageChain);
      if (errorDetails.relatedMessage) {
        addRelatedInfo(diag, createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
      }
      diagnostics.add(diag);
      invocationErrorRecovery(apparentType, SignatureKind.Call, diag);
      return resolveErrorCall(node);
    }
    return resolveCall(node, callSignatures, candidatesOutArray, checkMode, SignatureFlags.None, headMessage);
  }
  function createSignatureForJSXIntrinsic(node, result) {
    const namespace = getJsxNamespaceAt(node);
    const exports = namespace && getExportsOfSymbol(namespace);
    const typeSymbol = exports && getSymbol(exports, JsxNames.Element, SymbolFlags.Type);
    const returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, SymbolFlags.Type, node);
    const declaration = factory.createFunctionTypeNode(
      /*typeParameters*/
      void 0,
      [factory.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        "props",
        /*questionToken*/
        void 0,
        nodeBuilder.typeToTypeNode(result, node)
      )],
      returnNode ? factory.createTypeReferenceNode(
        returnNode,
        /*typeArguments*/
        void 0
      ) : factory.createKeywordTypeNode(SyntaxKind.AnyKeyword)
    );
    const parameterSymbol = createSymbol(SymbolFlags.FunctionScopedVariable, "props");
    parameterSymbol.links.type = result;
    return createSignature(
      declaration,
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      [parameterSymbol],
      typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType,
      /*resolvedTypePredicate*/
      void 0,
      1,
      SignatureFlags.None
    );
  }
  function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
    if (isJsxIntrinsicTagName(node.tagName)) {
      const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
      const fakeSignature = createSignatureForJSXIntrinsic(node, result);
      checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(
        node.attributes,
        getEffectiveFirstArgumentForJsxSignature(fakeSignature, node),
        /*inferenceContext*/
        void 0,
        0 /* Normal */
      ), result, node.tagName, node.attributes);
      if (length(node.typeArguments)) {
        forEach(node.typeArguments, checkSourceElement);
        diagnostics.add(createDiagnosticForNodeArray(getSourceFileOfNode(node), node.typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, 0, length(node.typeArguments)));
      }
      return fakeSignature;
    }
    const exprTypes = checkExpression(node.tagName);
    const apparentType = getApparentType(exprTypes);
    if (isErrorType(apparentType)) {
      return resolveErrorCall(node);
    }
    const signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
    if (isUntypedFunctionCall(
      exprTypes,
      apparentType,
      signatures.length,
      /*constructSignatures*/
      0
    )) {
      return resolveUntypedCall(node);
    }
    if (signatures.length === 0) {
      error(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName));
      return resolveErrorCall(node);
    }
    return resolveCall(node, signatures, candidatesOutArray, checkMode, SignatureFlags.None);
  }
  function resolveInstanceofExpression(node, candidatesOutArray, checkMode) {
    const rightType = checkExpression(node.right);
    if (!isTypeAny(rightType)) {
      const hasInstanceMethodType = getSymbolHasInstanceMethodOfObjectType(rightType);
      if (hasInstanceMethodType) {
        const apparentType = getApparentType(hasInstanceMethodType);
        if (isErrorType(apparentType)) {
          return resolveErrorCall(node);
        }
        const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call);
        const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct);
        if (isUntypedFunctionCall(hasInstanceMethodType, apparentType, callSignatures.length, constructSignatures.length)) {
          return resolveUntypedCall(node);
        }
        if (callSignatures.length) {
          return resolveCall(node, callSignatures, candidatesOutArray, checkMode, SignatureFlags.None);
        }
      } else if (!(typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
        error(node.right, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_type_assignable_to_the_Function_interface_type_or_an_object_type_with_a_Symbol_hasInstance_method);
        return resolveErrorCall(node);
      }
    }
    return anySignature;
  }
  function isPotentiallyUncalledDecorator(decorator, signatures) {
    return signatures.length && every(signatures, (signature) => signature.minArgumentCount === 0 && !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature));
  }
  function resolveSignature(node, candidatesOutArray, checkMode) {
    switch (node.kind) {
      case SyntaxKind.CallExpression:
        return resolveCallExpression(node, candidatesOutArray, checkMode);
      case SyntaxKind.NewExpression:
        return resolveNewExpression(node, candidatesOutArray, checkMode);
      case SyntaxKind.TaggedTemplateExpression:
        return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
      case SyntaxKind.Decorator:
        return resolveDecorator(node, candidatesOutArray, checkMode);
      case SyntaxKind.JsxOpeningElement:
      case SyntaxKind.JsxSelfClosingElement:
        return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
      case SyntaxKind.BinaryExpression:
        return resolveInstanceofExpression(node, candidatesOutArray, checkMode);
    }
    Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
  }
  function getResolvedSignature(node, candidatesOutArray, checkMode) {
    const links = getNodeLinks(node);
    const cached = links.resolvedSignature;
    if (cached && cached !== resolvingSignature && !candidatesOutArray) {
      return cached;
    }
    const saveResolutionStart = resolutionStart;
    if (!cached) {
      resolutionStart = resolutionTargets.length;
    }
    links.resolvedSignature = resolvingSignature;
    let result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
    resolutionStart = saveResolutionStart;
    if (result !== resolvingSignature) {
      if (links.resolvedSignature !== resolvingSignature) {
        result = links.resolvedSignature;
      }
      links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
    }
    return result;
  }
  function isJSConstructor(node) {
    if (!node || !isInJSFile(node)) {
      return false;
    }
    const func = isFunctionDeclaration(node) || isFunctionExpression(node) ? node : (isVariableDeclaration(node) || isPropertyAssignment(node)) && node.initializer && isFunctionExpression(node.initializer) ? node.initializer : void 0;
    if (func) {
      if (getJSDocClassTag(node)) return true;
      if (isPropertyAssignment(walkUpParenthesizedExpressions(func.parent))) return false;
      const symbol = getSymbolOfDeclaration(func);
      return !!symbol?.members?.size;
    }
    return false;
  }
  function mergeJSSymbols(target, source) {
    if (source) {
      const links = getSymbolLinks(source);
      if (!links.inferredClassSymbol || !links.inferredClassSymbol.has(getSymbolId(target))) {
        const inferred = isTransientSymbol(target) ? target : cloneSymbol(target);
        inferred.exports = inferred.exports || createSymbolTable();
        inferred.members = inferred.members || createSymbolTable();
        inferred.flags |= source.flags & SymbolFlags.Class;
        if (source.exports?.size) {
          mergeSymbolTable(inferred.exports, source.exports);
        }
        if (source.members?.size) {
          mergeSymbolTable(inferred.members, source.members);
        }
        (links.inferredClassSymbol || (links.inferredClassSymbol = /* @__PURE__ */ new Map())).set(getSymbolId(inferred), inferred);
        return inferred;
      }
      return links.inferredClassSymbol.get(getSymbolId(target));
    }
  }
  function getAssignedClassSymbol(decl) {
    const assignmentSymbol = decl && getSymbolOfExpando(
      decl,
      /*allowDeclaration*/
      true
    );
    const prototype = assignmentSymbol?.exports?.get("prototype");
    const init = prototype?.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration);
    return init ? getSymbolOfDeclaration(init) : void 0;
  }
  function getSymbolOfExpando(node, allowDeclaration) {
    if (!node.parent) {
      return void 0;
    }
    let name;
    let decl;
    if (isVariableDeclaration(node.parent) && node.parent.initializer === node) {
      if (!isInJSFile(node) && !(isVarConstLike(node.parent) && isFunctionLikeDeclaration(node))) {
        return void 0;
      }
      name = node.parent.name;
      decl = node.parent;
    } else if (isBinaryExpression(node.parent)) {
      const parentNode = node.parent;
      const parentNodeOperator = node.parent.operatorToken.kind;
      if (parentNodeOperator === SyntaxKind.EqualsToken && (allowDeclaration || parentNode.right === node)) {
        name = parentNode.left;
        decl = name;
      } else if (parentNodeOperator === SyntaxKind.BarBarToken || parentNodeOperator === SyntaxKind.QuestionQuestionToken) {
        if (isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
          name = parentNode.parent.name;
          decl = parentNode.parent;
        } else if (isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === SyntaxKind.EqualsToken && (allowDeclaration || parentNode.parent.right === parentNode)) {
          name = parentNode.parent.left;
          decl = name;
        }
        if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) {
          return void 0;
        }
      }
    } else if (allowDeclaration && isFunctionDeclaration(node)) {
      name = node.name;
      decl = node;
    }
    if (!decl || !name || !allowDeclaration && !getExpandoInitializer(node, isPrototypeAccess(name))) {
      return void 0;
    }
    return getSymbolOfNode(decl);
  }
  function getAssignedJSPrototype(node) {
    if (!node.parent) {
      return false;
    }
    let parent = node.parent;
    while (parent && parent.kind === SyntaxKind.PropertyAccessExpression) {
      parent = parent.parent;
    }
    if (parent && isBinaryExpression(parent) && isPrototypeAccess(parent.left) && parent.operatorToken.kind === SyntaxKind.EqualsToken) {
      const right = getInitializerOfBinaryExpression(parent);
      return isObjectLiteralExpression(right) && right;
    }
  }
  function checkCallExpression(node, checkMode) {
    checkGrammarTypeArguments(node, node.typeArguments);
    const signature = getResolvedSignature(
      node,
      /*candidatesOutArray*/
      void 0,
      checkMode
    );
    if (signature === resolvingSignature) {
      return silentNeverType;
    }
    checkDeprecatedSignature(signature, node);
    if (node.expression.kind === SyntaxKind.SuperKeyword) {
      return voidType;
    }
    if (node.kind === SyntaxKind.NewExpression) {
      const declaration = signature.declaration;
      if (declaration && declaration.kind !== SyntaxKind.Constructor && declaration.kind !== SyntaxKind.ConstructSignature && declaration.kind !== SyntaxKind.ConstructorType && !(isJSDocSignature(declaration) && getJSDocRoot(declaration)?.parent?.kind === SyntaxKind.Constructor) && !isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) {
        if (noImplicitAny) {
          error(node, Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
        }
        return anyType;
      }
    }
    if (isInJSFile(node) && isCommonJsRequire(node)) {
      return resolveExternalModuleTypeByLiteral(node.arguments[0]);
    }
    const returnType = getReturnTypeOfSignature(signature);
    if (returnType.flags & TypeFlags.ESSymbolLike && isSymbolOrSymbolForCall(node)) {
      return getESSymbolLikeTypeForNode(walkUpParenthesizedExpressions(node.parent));
    }
    if (node.kind === SyntaxKind.CallExpression && !node.questionDotToken && node.parent.kind === SyntaxKind.ExpressionStatement && returnType.flags & TypeFlags.Void && getTypePredicateOfSignature(signature)) {
      if (!isDottedName(node.expression)) {
        error(node.expression, Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
      } else if (!getEffectsSignature(node)) {
        const diagnostic = error(node.expression, Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
        getTypeOfDottedName(node.expression, diagnostic);
      }
    }
    if (isInJSFile(node)) {
      const jsSymbol = getSymbolOfExpando(
        node,
        /*allowDeclaration*/
        false
      );
      if (jsSymbol?.exports?.size) {
        const jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, emptyArray, emptyArray, emptyArray);
        jsAssignmentType.objectFlags |= ObjectFlags.JSLiteral;
        return getIntersectionType([returnType, jsAssignmentType]);
      }
    }
    return returnType;
  }
  function checkDeprecatedSignature(signature, node) {
    if (signature.flags & SignatureFlags.IsSignatureCandidateForOverloadFailure) return;
    if (signature.declaration && signature.declaration.flags & NodeFlags.Deprecated) {
      const suggestionNode = getDeprecatedSuggestionNode(node);
      const name = tryGetPropertyAccessOrIdentifierToString(getInvokedExpression(node));
      addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature));
    }
  }
  function getDeprecatedSuggestionNode(node) {
    node = skipParentheses(node);
    switch (node.kind) {
      case SyntaxKind.CallExpression:
      case SyntaxKind.Decorator:
      case SyntaxKind.NewExpression:
        return getDeprecatedSuggestionNode(node.expression);
      case SyntaxKind.TaggedTemplateExpression:
        return getDeprecatedSuggestionNode(node.tag);
      case SyntaxKind.JsxOpeningElement:
      case SyntaxKind.JsxSelfClosingElement:
        return getDeprecatedSuggestionNode(node.tagName);
      case SyntaxKind.ElementAccessExpression:
        return node.argumentExpression;
      case SyntaxKind.PropertyAccessExpression:
        return node.name;
      case SyntaxKind.TypeReference:
        const typeReference = node;
        return isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference;
      default:
        return node;
    }
  }
  function isSymbolOrSymbolForCall(node) {
    if (!isCallExpression(node)) return false;
    let left = node.expression;
    if (isPropertyAccessExpression(left) && left.name.escapedText === "for") {
      left = left.expression;
    }
    if (!isIdentifier(left) || left.escapedText !== "Symbol") {
      return false;
    }
    const globalESSymbol = getGlobalESSymbolConstructorSymbol(
      /*reportErrors*/
      false
    );
    if (!globalESSymbol) {
      return false;
    }
    return globalESSymbol === resolveName(
      left,
      "Symbol",
      SymbolFlags.Value,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false
    );
  }
  function checkImportCallExpression(node) {
    checkGrammarImportCallExpression(node);
    if (node.arguments.length === 0) {
      return createPromiseReturnType(node, anyType);
    }
    const specifier = node.arguments[0];
    const specifierType = checkExpressionCached(specifier);
    const optionsType = node.arguments.length > 1 ? checkExpressionCached(node.arguments[1]) : void 0;
    for (let i = 2; i < node.arguments.length; ++i) {
      checkExpressionCached(node.arguments[i]);
    }
    if (specifierType.flags & TypeFlags.Undefined || specifierType.flags & TypeFlags.Null || !isTypeAssignableTo(specifierType, stringType)) {
      error(specifier, Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
    }
    if (optionsType) {
      const importCallOptionsType = getGlobalImportCallOptionsType(
        /*reportErrors*/
        true
      );
      if (importCallOptionsType !== emptyObjectType) {
        checkTypeAssignableTo(optionsType, getNullableType(importCallOptionsType, TypeFlags.Undefined), node.arguments[1]);
      }
    }
    const moduleSymbol = resolveExternalModuleName(node, specifier);
    if (moduleSymbol) {
      const esModuleSymbol = resolveESModuleSymbol(
        moduleSymbol,
        specifier,
        /*dontResolveAlias*/
        true,
        /*suppressInteropError*/
        false
      );
      if (esModuleSymbol) {
        return createPromiseReturnType(
          node,
          getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)
        );
      }
    }
    return createPromiseReturnType(node, anyType);
  }
  function createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol) {
    const memberTable = createSymbolTable();
    const newSymbol = createSymbol(SymbolFlags.Alias, InternalSymbolName.Default);
    newSymbol.parent = originalSymbol;
    newSymbol.links.nameType = getStringLiteralType("default");
    newSymbol.links.aliasTarget = resolveSymbol(symbol);
    memberTable.set(InternalSymbolName.Default, newSymbol);
    return createAnonymousType(anonymousSymbol, memberTable, emptyArray, emptyArray, emptyArray);
  }
  function getTypeWithSyntheticDefaultOnly(type, symbol, originalSymbol, moduleSpecifier) {
    const hasDefaultOnly = isOnlyImportableAsDefault(moduleSpecifier);
    if (hasDefaultOnly && type && !isErrorType(type)) {
      const synthType = type;
      if (!synthType.defaultOnlyType) {
        const type2 = createDefaultPropertyWrapperForModule(symbol, originalSymbol);
        synthType.defaultOnlyType = type2;
      }
      return synthType.defaultOnlyType;
    }
    return void 0;
  }
  function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol, moduleSpecifier) {
    if (allowSyntheticDefaultImports && type && !isErrorType(type)) {
      const synthType = type;
      if (!synthType.syntheticType) {
        const file = originalSymbol.declarations?.find(isSourceFile);
        const hasSyntheticDefault = canHaveSyntheticDefault(
          file,
          originalSymbol,
          /*dontResolveAlias*/
          false,
          moduleSpecifier
        );
        if (hasSyntheticDefault) {
          const anonymousSymbol = createSymbol(SymbolFlags.TypeLiteral, InternalSymbolName.Type);
          const defaultContainingObject = createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol);
          anonymousSymbol.links.type = defaultContainingObject;
          synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(
            type,
            defaultContainingObject,
            anonymousSymbol,
            /*objectFlags*/
            0,
            /*readonly*/
            false
          ) : defaultContainingObject;
        } else {
          synthType.syntheticType = type;
        }
      }
      return synthType.syntheticType;
    }
    return type;
  }
  function isCommonJsRequire(node) {
    if (!isRequireCall(
      node,
      /*requireStringLiteralLikeArgument*/
      true
    )) {
      return false;
    }
    if (!isIdentifier(node.expression)) return Debug.fail();
    const resolvedRequire = resolveName(
      node.expression,
      node.expression.escapedText,
      SymbolFlags.Value,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
    if (resolvedRequire === requireSymbol) {
      return true;
    }
    if (resolvedRequire.flags & SymbolFlags.Alias) {
      return false;
    }
    const targetDeclarationKind = resolvedRequire.flags & SymbolFlags.Function ? SyntaxKind.FunctionDeclaration : resolvedRequire.flags & SymbolFlags.Variable ? SyntaxKind.VariableDeclaration : SyntaxKind.Unknown;
    if (targetDeclarationKind !== SyntaxKind.Unknown) {
      const decl = getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
      return !!decl && !!(decl.flags & NodeFlags.Ambient);
    }
    return false;
  }
  function checkTaggedTemplateExpression(node) {
    if (!checkGrammarTaggedTemplateChain(node)) checkGrammarTypeArguments(node, node.typeArguments);
    if (languageVersion < LanguageFeatureMinimumTarget.TaggedTemplates) {
      checkExternalEmitHelpers(node, ExternalEmitHelpers.MakeTemplateObject);
    }
    const signature = getResolvedSignature(node);
    checkDeprecatedSignature(signature, node);
    return getReturnTypeOfSignature(signature);
  }
  function checkAssertion(node, checkMode) {
    if (node.kind === SyntaxKind.TypeAssertionExpression) {
      const file = getSourceFileOfNode(node);
      if (file && fileExtensionIsOneOf(file.fileName, [Extension.Cts, Extension.Mts])) {
        grammarErrorOnNode(node, Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead);
      }
    }
    return checkAssertionWorker(node, checkMode);
  }
  function isValidConstAssertionArgument(node) {
    switch (node.kind) {
      case SyntaxKind.StringLiteral:
      case SyntaxKind.NoSubstitutionTemplateLiteral:
      case SyntaxKind.NumericLiteral:
      case SyntaxKind.BigIntLiteral:
      case SyntaxKind.TrueKeyword:
      case SyntaxKind.FalseKeyword:
      case SyntaxKind.ArrayLiteralExpression:
      case SyntaxKind.ObjectLiteralExpression:
      case SyntaxKind.TemplateExpression:
        return true;
      case SyntaxKind.ParenthesizedExpression:
        return isValidConstAssertionArgument(node.expression);
      case SyntaxKind.PrefixUnaryExpression:
        const op = node.operator;
        const arg = node.operand;
        return op === SyntaxKind.MinusToken && (arg.kind === SyntaxKind.NumericLiteral || arg.kind === SyntaxKind.BigIntLiteral) || op === SyntaxKind.PlusToken && arg.kind === SyntaxKind.NumericLiteral;
      case SyntaxKind.PropertyAccessExpression:
      case SyntaxKind.ElementAccessExpression:
        const expr = skipParentheses(node.expression);
        const symbol = isEntityNameExpression(expr) ? resolveEntityName(
          expr,
          SymbolFlags.Value,
          /*ignoreErrors*/
          true
        ) : void 0;
        return !!(symbol && symbol.flags & SymbolFlags.Enum);
    }
    return false;
  }
  function checkAssertionWorker(node, checkMode) {
    const { type, expression } = getAssertionTypeAndExpression(node);
    const exprType = checkExpression(expression, checkMode);
    if (isConstTypeReference(type)) {
      if (!isValidConstAssertionArgument(expression)) {
        error(expression, Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
      }
      return getRegularTypeOfLiteralType(exprType);
    }
    const links = getNodeLinks(node);
    links.assertionExpressionType = exprType;
    checkSourceElement(type);
    checkNodeDeferred(node);
    return getTypeFromTypeNode(type);
  }
  function getAssertionTypeAndExpression(node) {
    let type;
    let expression;
    switch (node.kind) {
      case SyntaxKind.AsExpression:
      case SyntaxKind.TypeAssertionExpression:
        type = node.type;
        expression = node.expression;
        break;
      case SyntaxKind.ParenthesizedExpression:
        type = getJSDocTypeAssertionType(node);
        expression = node.expression;
        break;
    }
    return { type, expression };
  }
  function checkAssertionDeferred(node) {
    const { type } = getAssertionTypeAndExpression(node);
    const errNode = isParenthesizedExpression(node) ? type : node;
    const links = getNodeLinks(node);
    Debug.assertIsDefined(links.assertionExpressionType);
    const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(links.assertionExpressionType));
    const targetType = getTypeFromTypeNode(type);
    if (!isErrorType(targetType)) {
      addLazyDiagnostic(() => {
        const widenedType = getWidenedType(exprType);
        if (!isTypeComparableTo(targetType, widenedType)) {
          checkTypeComparableTo(exprType, targetType, errNode, Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first);
        }
      });
    }
  }
  function checkNonNullChain(node) {
    const leftType = checkExpression(node.expression);
    const nonOptionalType = getOptionalExpressionType(leftType, node.expression);
    return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
  }
  function checkNonNullAssertion(node) {
    return node.flags & NodeFlags.OptionalChain ? checkNonNullChain(node) : getNonNullableType(checkExpression(node.expression));
  }
  function checkExpressionWithTypeArguments(node) {
    checkGrammarExpressionWithTypeArguments(node);
    forEach(node.typeArguments, checkSourceElement);
    if (node.kind === SyntaxKind.ExpressionWithTypeArguments) {
      const parent = walkUpParenthesizedExpressions(node.parent);
      if (parent.kind === SyntaxKind.BinaryExpression && parent.operatorToken.kind === SyntaxKind.InstanceOfKeyword && isNodeDescendantOf(node, parent.right)) {
        error(node, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression);
      }
    }
    const exprType = node.kind === SyntaxKind.ExpressionWithTypeArguments ? checkExpression(node.expression) : isThisIdentifier(node.exprName) ? checkThisExpression(node.exprName) : checkExpression(node.exprName);
    return getInstantiationExpressionType(exprType, node);
  }
  function getInstantiationExpressionType(exprType, node) {
    const typeArguments = node.typeArguments;
    if (exprType === silentNeverType || isErrorType(exprType) || !some(typeArguments)) {
      return exprType;
    }
    let hasSomeApplicableSignature = false;
    let nonApplicableType;
    const result = getInstantiatedType(exprType);
    const errorType2 = hasSomeApplicableSignature ? nonApplicableType : exprType;
    if (errorType2) {
      diagnostics.add(createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable, typeToString(errorType2)));
    }
    return result;
    function getInstantiatedType(type) {
      let hasSignatures = false;
      let hasApplicableSignature = false;
      const result2 = getInstantiatedTypePart(type);
      hasSomeApplicableSignature ||= hasApplicableSignature;
      if (hasSignatures && !hasApplicableSignature) {
        nonApplicableType ??= type;
      }
      return result2;
      function getInstantiatedTypePart(type2) {
        if (type2.flags & TypeFlags.Object) {
          const resolved = resolveStructuredTypeMembers(type2);
          const callSignatures = getInstantiatedSignatures(resolved.callSignatures);
          const constructSignatures = getInstantiatedSignatures(resolved.constructSignatures);
          hasSignatures ||= resolved.callSignatures.length !== 0 || resolved.constructSignatures.length !== 0;
          hasApplicableSignature ||= callSignatures.length !== 0 || constructSignatures.length !== 0;
          if (callSignatures !== resolved.callSignatures || constructSignatures !== resolved.constructSignatures) {
            const result3 = createAnonymousType(createSymbol(SymbolFlags.None, InternalSymbolName.InstantiationExpression), resolved.members, callSignatures, constructSignatures, resolved.indexInfos);
            result3.objectFlags |= ObjectFlags.InstantiationExpressionType;
            result3.node = node;
            return result3;
          }
        } else if (type2.flags & TypeFlags.InstantiableNonPrimitive) {
          const constraint = getBaseConstraintOfType(type2);
          if (constraint) {
            const instantiated = getInstantiatedTypePart(constraint);
            if (instantiated !== constraint) {
              return instantiated;
            }
          }
        } else if (type2.flags & TypeFlags.Union) {
          return mapType(type2, getInstantiatedType);
        } else if (type2.flags & TypeFlags.Intersection) {
          return getIntersectionType(sameMap(type2.types, getInstantiatedTypePart));
        }
        return type2;
      }
    }
    function getInstantiatedSignatures(signatures) {
      const applicableSignatures = filter(signatures, (sig) => !!sig.typeParameters && hasCorrectTypeArgumentArity(sig, typeArguments));
      return sameMap(applicableSignatures, (sig) => {
        const typeArgumentTypes = checkTypeArguments(
          sig,
          typeArguments,
          /*reportErrors*/
          true
        );
        return typeArgumentTypes ? getSignatureInstantiation(sig, typeArgumentTypes, isInJSFile(sig.declaration)) : sig;
      });
    }
  }
  function checkSatisfiesExpression(node) {
    checkSourceElement(node.type);
    return checkSatisfiesExpressionWorker(node.expression, node.type);
  }
  function checkSatisfiesExpressionWorker(expression, target, checkMode) {
    const exprType = checkExpression(expression, checkMode);
    const targetType = getTypeFromTypeNode(target);
    if (isErrorType(targetType)) {
      return targetType;
    }
    const errorNode = findAncestor(target.parent, (n) => n.kind === SyntaxKind.SatisfiesExpression || n.kind === SyntaxKind.JSDocSatisfiesTag);
    checkTypeAssignableToAndOptionallyElaborate(exprType, targetType, errorNode, expression, Diagnostics.Type_0_does_not_satisfy_the_expected_type_1);
    return exprType;
  }
  function checkMetaProperty(node) {
    checkGrammarMetaProperty(node);
    if (node.keywordToken === SyntaxKind.NewKeyword) {
      return checkNewTargetMetaProperty(node);
    }
    if (node.keywordToken === SyntaxKind.ImportKeyword) {
      return checkImportMetaProperty(node);
    }
    return Debug.assertNever(node.keywordToken);
  }
  function checkMetaPropertyKeyword(node) {
    switch (node.keywordToken) {
      case SyntaxKind.ImportKeyword:
        return getGlobalImportMetaExpressionType();
      case SyntaxKind.NewKeyword:
        const type = checkNewTargetMetaProperty(node);
        return isErrorType(type) ? errorType : createNewTargetExpressionType(type);
      default:
        Debug.assertNever(node.keywordToken);
    }
  }
  function checkNewTargetMetaProperty(node) {
    const container = getNewTargetContainer(node);
    if (!container) {
      error(node, Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
      return errorType;
    } else if (container.kind === SyntaxKind.Constructor) {
      const symbol = getSymbolOfDeclaration(container.parent);
      return getTypeOfSymbol(symbol);
    } else {
      const symbol = getSymbolOfDeclaration(container);
      return getTypeOfSymbol(symbol);
    }
  }
  function checkImportMetaProperty(node) {
    if (moduleKind === ModuleKind.Node16 || moduleKind === ModuleKind.NodeNext) {
      if (getSourceFileOfNode(node).impliedNodeFormat !== ModuleKind.ESNext) {
        error(node, Diagnostics.The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output);
      }
    } else if (moduleKind < ModuleKind.ES2020 && moduleKind !== ModuleKind.System) {
      error(node, Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_or_nodenext);
    }
    const file = getSourceFileOfNode(node);
    Debug.assert(!!(file.flags & NodeFlags.PossiblyContainsImportMeta), "Containing file is missing import meta node flag.");
    return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
  }
  function getTypeOfParameter(symbol) {
    const declaration = symbol.valueDeclaration;
    return addOptionality(
      getTypeOfSymbol(symbol),
      /*isProperty*/
      false,
      /*isOptional*/
      !!declaration && (hasInitializer(declaration) || isOptionalDeclaration(declaration))
    );
  }
  function getTupleElementLabelFromBindingElement(node, index, elementFlags) {
    switch (node.name.kind) {
      case SyntaxKind.Identifier: {
        const name = node.name.escapedText;
        if (node.dotDotDotToken) {
          return elementFlags & ElementFlags.Variable ? name : `${name}_${index}`;
        } else {
          return elementFlags & ElementFlags.Fixed ? name : `${name}_n`;
        }
      }
      case SyntaxKind.ArrayBindingPattern: {
        if (node.dotDotDotToken) {
          const elements = node.name.elements;
          const lastElement = tryCast(lastOrUndefined(elements), isBindingElement);
          const elementCount = elements.length - (lastElement?.dotDotDotToken ? 1 : 0);
          if (index < elementCount) {
            const element = elements[index];
            if (isBindingElement(element)) {
              return getTupleElementLabelFromBindingElement(element, index, elementFlags);
            }
          } else if (lastElement?.dotDotDotToken) {
            return getTupleElementLabelFromBindingElement(lastElement, index - elementCount, elementFlags);
          }
        }
        break;
      }
    }
    return `arg_${index}`;
  }
  function getTupleElementLabel(d, index = 0, elementFlags = ElementFlags.Fixed, restSymbol) {
    if (!d) {
      const restParameter = tryCast(restSymbol?.valueDeclaration, isParameter);
      return restParameter ? getTupleElementLabelFromBindingElement(restParameter, index, elementFlags) : `${restSymbol?.escapedName ?? "arg"}_${index}`;
    }
    Debug.assert(isIdentifier(d.name));
    return d.name.escapedText;
  }
  function getParameterNameAtPosition(signature, pos, overrideRestType) {
    const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    if (pos < paramCount) {
      return signature.parameters[pos].escapedName;
    }
    const restParameter = signature.parameters[paramCount] || unknownSymbol;
    const restType = overrideRestType || getTypeOfSymbol(restParameter);
    if (isTupleType(restType)) {
      const tupleType = restType.target;
      const index = pos - paramCount;
      const associatedName = tupleType.labeledElementDeclarations?.[index];
      const elementFlags = tupleType.elementFlags[index];
      return getTupleElementLabel(associatedName, index, elementFlags, restParameter);
    }
    return restParameter.escapedName;
  }
  function getParameterIdentifierInfoAtPosition(signature, pos) {
    if (signature.declaration?.kind === SyntaxKind.JSDocFunctionType) {
      return void 0;
    }
    const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    if (pos < paramCount) {
      const param = signature.parameters[pos];
      const paramIdent = getParameterDeclarationIdentifier(param);
      return paramIdent ? {
        parameter: paramIdent,
        parameterName: param.escapedName,
        isRestParameter: false
      } : void 0;
    }
    const restParameter = signature.parameters[paramCount] || unknownSymbol;
    const restIdent = getParameterDeclarationIdentifier(restParameter);
    if (!restIdent) {
      return void 0;
    }
    const restType = getTypeOfSymbol(restParameter);
    if (isTupleType(restType)) {
      const associatedNames = restType.target.labeledElementDeclarations;
      const index = pos - paramCount;
      const associatedName = associatedNames?.[index];
      const isRestTupleElement = !!associatedName?.dotDotDotToken;
      if (associatedName) {
        Debug.assert(isIdentifier(associatedName.name));
        return { parameter: associatedName.name, parameterName: associatedName.name.escapedText, isRestParameter: isRestTupleElement };
      }
      return void 0;
    }
    if (pos === paramCount) {
      return { parameter: restIdent, parameterName: restParameter.escapedName, isRestParameter: true };
    }
    return void 0;
  }
  function getParameterDeclarationIdentifier(symbol) {
    return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name) && symbol.valueDeclaration.name;
  }
  function isValidDeclarationForTupleLabel(d) {
    return d.kind === SyntaxKind.NamedTupleMember || isParameter(d) && d.name && isIdentifier(d.name);
  }
  function getNameableDeclarationAtPosition(signature, pos) {
    const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    if (pos < paramCount) {
      const decl = signature.parameters[pos].valueDeclaration;
      return decl && isValidDeclarationForTupleLabel(decl) ? decl : void 0;
    }
    const restParameter = signature.parameters[paramCount] || unknownSymbol;
    const restType = getTypeOfSymbol(restParameter);
    if (isTupleType(restType)) {
      const associatedNames = restType.target.labeledElementDeclarations;
      const index = pos - paramCount;
      return associatedNames && associatedNames[index];
    }
    return restParameter.valueDeclaration && isValidDeclarationForTupleLabel(restParameter.valueDeclaration) ? restParameter.valueDeclaration : void 0;
  }
  function getTypeAtPosition(signature, pos) {
    return tryGetTypeAtPosition(signature, pos) || anyType;
  }
  function tryGetTypeAtPosition(signature, pos) {
    const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    if (pos < paramCount) {
      return getTypeOfParameter(signature.parameters[pos]);
    }
    if (signatureHasRestParameter(signature)) {
      const restType = getTypeOfSymbol(signature.parameters[paramCount]);
      const index = pos - paramCount;
      if (!isTupleType(restType) || restType.target.combinedFlags & ElementFlags.Variable || index < restType.target.fixedLength) {
        return getIndexedAccessType(restType, getNumberLiteralType(index));
      }
    }
    return void 0;
  }
  function getRestTypeAtPosition(source, pos, readonly) {
    const parameterCount = getParameterCount(source);
    const minArgumentCount = getMinArgumentCount(source);
    const restType = getEffectiveRestType(source);
    if (restType && pos >= parameterCount - 1) {
      return pos === parameterCount - 1 ? restType : createArrayType(getIndexedAccessType(restType, numberType));
    }
    const types = [];
    const flags = [];
    const names = [];
    for (let i = pos; i < parameterCount; i++) {
      if (!restType || i < parameterCount - 1) {
        types.push(getTypeAtPosition(source, i));
        flags.push(i < minArgumentCount ? ElementFlags.Required : ElementFlags.Optional);
      } else {
        types.push(restType);
        flags.push(ElementFlags.Variadic);
      }
      names.push(getNameableDeclarationAtPosition(source, i));
    }
    return createTupleType(types, flags, readonly, names);
  }
  function getRestOrAnyTypeAtPosition(source, pos) {
    const restType = getRestTypeAtPosition(source, pos);
    const elementType = restType && getElementTypeOfArrayType(restType);
    return elementType && isTypeAny(elementType) ? anyType : restType;
  }
  function getParameterCount(signature) {
    const length2 = signature.parameters.length;
    if (signatureHasRestParameter(signature)) {
      const restType = getTypeOfSymbol(signature.parameters[length2 - 1]);
      if (isTupleType(restType)) {
        return length2 + restType.target.fixedLength - (restType.target.combinedFlags & ElementFlags.Variable ? 0 : 1);
      }
    }
    return length2;
  }
  function getMinArgumentCount(signature, flags) {
    const strongArityForUntypedJS = flags & 1 /* StrongArityForUntypedJS */;
    const voidIsNonOptional = flags & 2 /* VoidIsNonOptional */;
    if (voidIsNonOptional || signature.resolvedMinArgumentCount === void 0) {
      let minArgumentCount;
      if (signatureHasRestParameter(signature)) {
        const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
        if (isTupleType(restType)) {
          const firstOptionalIndex = findIndex(restType.target.elementFlags, (f) => !(f & ElementFlags.Required));
          const requiredCount = firstOptionalIndex < 0 ? restType.target.fixedLength : firstOptionalIndex;
          if (requiredCount > 0) {
            minArgumentCount = signature.parameters.length - 1 + requiredCount;
          }
        }
      }
      if (minArgumentCount === void 0) {
        if (!strongArityForUntypedJS && signature.flags & SignatureFlags.IsUntypedSignatureInJSFile) {
          return 0;
        }
        minArgumentCount = signature.minArgumentCount;
      }
      if (voidIsNonOptional) {
        return minArgumentCount;
      }
      for (let i = minArgumentCount - 1; i >= 0; i--) {
        const type = getTypeAtPosition(signature, i);
        if (filterType(type, acceptsVoid).flags & TypeFlags.Never) {
          break;
        }
        minArgumentCount = i;
      }
      signature.resolvedMinArgumentCount = minArgumentCount;
    }
    return signature.resolvedMinArgumentCount;
  }
  function hasEffectiveRestParameter(signature) {
    if (signatureHasRestParameter(signature)) {
      const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
      return !isTupleType(restType) || !!(restType.target.combinedFlags & ElementFlags.Variable);
    }
    return false;
  }
  function getEffectiveRestType(signature) {
    if (signatureHasRestParameter(signature)) {
      const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
      if (!isTupleType(restType)) {
        return isTypeAny(restType) ? anyArrayType : restType;
      }
      if (restType.target.combinedFlags & ElementFlags.Variable) {
        return sliceTupleType(restType, restType.target.fixedLength);
      }
    }
    return void 0;
  }
  function getNonArrayRestType(signature) {
    const restType = getEffectiveRestType(signature);
    return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : void 0;
  }
  function getTypeOfFirstParameterOfSignature(signature) {
    return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
  }
  function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
    return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
  }
  function inferFromAnnotatedParameters(signature, context, inferenceContext) {
    const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    for (let i = 0; i < len; i++) {
      const declaration = signature.parameters[i].valueDeclaration;
      const typeNode = getEffectiveTypeAnnotationNode(declaration);
      if (typeNode) {
        const source = addOptionality(
          getTypeFromTypeNode(typeNode),
          /*isProperty*/
          false,
          isOptionalDeclaration(declaration)
        );
        const target = getTypeAtPosition(context, i);
        inferTypes(inferenceContext.inferences, source, target);
      }
    }
  }
  function assignContextualParameterTypes(signature, context) {
    if (context.typeParameters) {
      if (!signature.typeParameters) {
        signature.typeParameters = context.typeParameters;
      } else {
        return;
      }
    }
    if (context.thisParameter) {
      const parameter = signature.thisParameter;
      if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
        if (!parameter) {
          signature.thisParameter = createSymbolWithType(
            context.thisParameter,
            /*type*/
            void 0
          );
        }
        assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
      }
    }
    const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    for (let i = 0; i < len; i++) {
      const parameter = signature.parameters[i];
      const declaration = parameter.valueDeclaration;
      if (!getEffectiveTypeAnnotationNode(declaration)) {
        let type = tryGetTypeAtPosition(context, i);
        if (type && declaration.initializer) {
          let initializerType = checkDeclarationInitializer(declaration, 0 /* Normal */);
          if (!isTypeAssignableTo(initializerType, type) && isTypeAssignableTo(type, initializerType = widenTypeInferredFromInitializer(declaration, initializerType))) {
            type = initializerType;
          }
        }
        assignParameterType(parameter, type);
      }
    }
    if (signatureHasRestParameter(signature)) {
      const parameter = last(signature.parameters);
      if (parameter.valueDeclaration ? !getEffectiveTypeAnnotationNode(parameter.valueDeclaration) : !!(getCheckFlags(parameter) & CheckFlags.DeferredType)) {
        const contextualParameterType = getRestTypeAtPosition(context, len);
        assignParameterType(parameter, contextualParameterType);
      }
    }
  }
  function assignNonContextualParameterTypes(signature) {
    if (signature.thisParameter) {
      assignParameterType(signature.thisParameter);
    }
    for (const parameter of signature.parameters) {
      assignParameterType(parameter);
    }
  }
  function assignParameterType(parameter, contextualType) {
    const links = getSymbolLinks(parameter);
    if (!links.type) {
      const declaration = parameter.valueDeclaration;
      links.type = addOptionality(
        contextualType || (declaration ? getWidenedTypeForVariableLikeDeclaration(
          declaration,
          /*reportErrors*/
          true
        ) : getTypeOfSymbol(parameter)),
        /*isProperty*/
        false,
        /*isOptional*/
        !!declaration && !declaration.initializer && isOptionalDeclaration(declaration)
      );
      if (declaration && declaration.name.kind !== SyntaxKind.Identifier) {
        if (links.type === unknownType) {
          links.type = getTypeFromBindingPattern(declaration.name);
        }
        assignBindingElementTypes(declaration.name, links.type);
      }
    } else if (contextualType) {
      Debug.assertEqual(links.type, contextualType, "Parameter symbol already has a cached type which differs from newly assigned type");
    }
  }
  function assignBindingElementTypes(pattern, parentType) {
    for (const element of pattern.elements) {
      if (!isOmittedExpression(element)) {
        const type = getBindingElementTypeFromParentType(
          element,
          parentType,
          /*noTupleBoundsCheck*/
          false
        );
        if (element.name.kind === SyntaxKind.Identifier) {
          getSymbolLinks(getSymbolOfDeclaration(element)).type = type;
        } else {
          assignBindingElementTypes(element.name, type);
        }
      }
    }
  }
  function createClassDecoratorContextType(classType) {
    return tryCreateTypeReference(getGlobalClassDecoratorContextType(
      /*reportErrors*/
      true
    ), [classType]);
  }
  function createClassMethodDecoratorContextType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassMethodDecoratorContextType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassGetterDecoratorContextType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassGetterDecoratorContextType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassSetterDecoratorContextType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassSetterDecoratorContextType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassAccessorDecoratorContextType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassAccessorDecoratorContextType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassFieldDecoratorContextType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassFieldDecoratorContextType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function getClassMemberDecoratorContextOverrideType(nameType, isPrivate, isStatic2) {
    const key = `${isPrivate ? "p" : "P"}${isStatic2 ? "s" : "S"}${nameType.id}`;
    let overrideType = decoratorContextOverrideTypeCache.get(key);
    if (!overrideType) {
      const members = createSymbolTable();
      members.set("name", createProperty("name", nameType));
      members.set("private", createProperty("private", isPrivate ? trueType : falseType));
      members.set("static", createProperty("static", isStatic2 ? trueType : falseType));
      overrideType = createAnonymousType(
        /*symbol*/
        void 0,
        members,
        emptyArray,
        emptyArray,
        emptyArray
      );
      decoratorContextOverrideTypeCache.set(key, overrideType);
    }
    return overrideType;
  }
  function createClassMemberDecoratorContextTypeForNode(node, thisType, valueType) {
    const isStatic2 = hasStaticModifier(node);
    const isPrivate = isPrivateIdentifier(node.name);
    const nameType = isPrivate ? getStringLiteralType(idText(node.name)) : getLiteralTypeFromPropertyName(node.name);
    const contextType = isMethodDeclaration(node) ? createClassMethodDecoratorContextType(thisType, valueType) : isGetAccessorDeclaration(node) ? createClassGetterDecoratorContextType(thisType, valueType) : isSetAccessorDeclaration(node) ? createClassSetterDecoratorContextType(thisType, valueType) : isAutoAccessorPropertyDeclaration(node) ? createClassAccessorDecoratorContextType(thisType, valueType) : isPropertyDeclaration(node) ? createClassFieldDecoratorContextType(thisType, valueType) : Debug.failBadSyntaxKind(node);
    const overrideType = getClassMemberDecoratorContextOverrideType(nameType, isPrivate, isStatic2);
    return getIntersectionType([contextType, overrideType]);
  }
  function createClassAccessorDecoratorTargetType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassAccessorDecoratorTargetType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassAccessorDecoratorResultType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassAccessorDecoratorResultType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassFieldDecoratorInitializerMutatorType(thisType, valueType) {
    const thisParam = createParameter("this", thisType);
    const valueParam = createParameter("value", valueType);
    return createFunctionType(
      /*typeParameters*/
      void 0,
      thisParam,
      [valueParam],
      valueType,
      /*typePredicate*/
      void 0,
      1
    );
  }
  function createESDecoratorCallSignature(targetType, contextType, nonOptionalReturnType) {
    const targetParam = createParameter("target", targetType);
    const contextParam = createParameter("context", contextType);
    const returnType = getUnionType([nonOptionalReturnType, voidType]);
    return createCallSignature(
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      [targetParam, contextParam],
      returnType
    );
  }
  function getESDecoratorCallSignature(decorator) {
    const { parent } = decorator;
    const links = getNodeLinks(parent);
    if (!links.decoratorSignature) {
      links.decoratorSignature = anySignature;
      switch (parent.kind) {
        case SyntaxKind.ClassDeclaration:
        case SyntaxKind.ClassExpression: {
          const node = parent;
          const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node));
          const contextType = createClassDecoratorContextType(targetType);
          links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, targetType);
          break;
        }
        case SyntaxKind.MethodDeclaration:
        case SyntaxKind.GetAccessor:
        case SyntaxKind.SetAccessor: {
          const node = parent;
          if (!isClassLike(node.parent)) break;
          const valueType = isMethodDeclaration(node) ? getOrCreateTypeFromSignature(getSignatureFromDeclaration(node)) : getTypeOfNode(node);
          const thisType = hasStaticModifier(node) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent)) : getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node.parent));
          const targetType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType;
          const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType);
          const returnType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType;
          links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType);
          break;
        }
        case SyntaxKind.PropertyDeclaration: {
          const node = parent;
          if (!isClassLike(node.parent)) break;
          const valueType = getTypeOfNode(node);
          const thisType = hasStaticModifier(node) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent)) : getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node.parent));
          const targetType = hasAccessorModifier(node) ? createClassAccessorDecoratorTargetType(thisType, valueType) : undefinedType;
          const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType);
          const returnType = hasAccessorModifier(node) ? createClassAccessorDecoratorResultType(thisType, valueType) : createClassFieldDecoratorInitializerMutatorType(thisType, valueType);
          links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType);
          break;
        }
      }
    }
    return links.decoratorSignature === anySignature ? void 0 : links.decoratorSignature;
  }
  function getLegacyDecoratorCallSignature(decorator) {
    const { parent } = decorator;
    const links = getNodeLinks(parent);
    if (!links.decoratorSignature) {
      links.decoratorSignature = anySignature;
      switch (parent.kind) {
        case SyntaxKind.ClassDeclaration:
        case SyntaxKind.ClassExpression: {
          const node = parent;
          const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node));
          const targetParam = createParameter("target", targetType);
          links.decoratorSignature = createCallSignature(
            /*typeParameters*/
            void 0,
            /*thisParameter*/
            void 0,
            [targetParam],
            getUnionType([targetType, voidType])
          );
          break;
        }
        case SyntaxKind.Parameter: {
          const node = parent;
          if (!isConstructorDeclaration(node.parent) && !(isMethodDeclaration(node.parent) || isSetAccessorDeclaration(node.parent) && isClassLike(node.parent.parent))) {
            break;
          }
          if (getThisParameter(node.parent) === node) {
            break;
          }
          const index = getThisParameter(node.parent) ? node.parent.parameters.indexOf(node) - 1 : node.parent.parameters.indexOf(node);
          Debug.assert(index >= 0);
          const targetType = isConstructorDeclaration(node.parent) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent.parent)) : getParentTypeOfClassElement(node.parent);
          const keyType = isConstructorDeclaration(node.parent) ? undefinedType : getClassElementPropertyKeyType(node.parent);
          const indexType = getNumberLiteralType(index);
          const targetParam = createParameter("target", targetType);
          const keyParam = createParameter("propertyKey", keyType);
          const indexParam = createParameter("parameterIndex", indexType);
          links.decoratorSignature = createCallSignature(
            /*typeParameters*/
            void 0,
            /*thisParameter*/
            void 0,
            [targetParam, keyParam, indexParam],
            voidType
          );
          break;
        }
        case SyntaxKind.MethodDeclaration:
        case SyntaxKind.GetAccessor:
        case SyntaxKind.SetAccessor:
        case SyntaxKind.PropertyDeclaration: {
          const node = parent;
          if (!isClassLike(node.parent)) break;
          const targetType = getParentTypeOfClassElement(node);
          const targetParam = createParameter("target", targetType);
          const keyType = getClassElementPropertyKeyType(node);
          const keyParam = createParameter("propertyKey", keyType);
          const returnType = isPropertyDeclaration(node) ? voidType : createTypedPropertyDescriptorType(getTypeOfNode(node));
          const hasPropDesc = !isPropertyDeclaration(parent) || hasAccessorModifier(parent);
          if (hasPropDesc) {
            const descriptorType = createTypedPropertyDescriptorType(getTypeOfNode(node));
            const descriptorParam = createParameter("descriptor", descriptorType);
            links.decoratorSignature = createCallSignature(
              /*typeParameters*/
              void 0,
              /*thisParameter*/
              void 0,
              [targetParam, keyParam, descriptorParam],
              getUnionType([returnType, voidType])
            );
          } else {
            links.decoratorSignature = createCallSignature(
              /*typeParameters*/
              void 0,
              /*thisParameter*/
              void 0,
              [targetParam, keyParam],
              getUnionType([returnType, voidType])
            );
          }
          break;
        }
      }
    }
    return links.decoratorSignature === anySignature ? void 0 : links.decoratorSignature;
  }
  function getDecoratorCallSignature(decorator) {
    return legacyDecorators ? getLegacyDecoratorCallSignature(decorator) : getESDecoratorCallSignature(decorator);
  }
  function createPromiseType(promisedType) {
    const globalPromiseType = getGlobalPromiseType(
      /*reportErrors*/
      true
    );
    if (globalPromiseType !== emptyGenericType) {
      promisedType = getAwaitedTypeNoAlias(unwrapAwaitedType(promisedType)) || unknownType;
      return createTypeReference(globalPromiseType, [promisedType]);
    }
    return unknownType;
  }
  function createPromiseLikeType(promisedType) {
    const globalPromiseLikeType = getGlobalPromiseLikeType(
      /*reportErrors*/
      true
    );
    if (globalPromiseLikeType !== emptyGenericType) {
      promisedType = getAwaitedTypeNoAlias(unwrapAwaitedType(promisedType)) || unknownType;
      return createTypeReference(globalPromiseLikeType, [promisedType]);
    }
    return unknownType;
  }
  function createPromiseReturnType(func, promisedType) {
    const promiseType = createPromiseType(promisedType);
    if (promiseType === unknownType) {
      error(
        func,
        isImportCall(func) ? Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option
      );
      return errorType;
    } else if (!getGlobalPromiseConstructorSymbol(
      /*reportErrors*/
      true
    )) {
      error(
        func,
        isImportCall(func) ? Diagnostics.A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option
      );
    }
    return promiseType;
  }
  function createNewTargetExpressionType(targetType) {
    const symbol = createSymbol(SymbolFlags.None, "NewTargetExpression");
    const targetPropertySymbol = createSymbol(SymbolFlags.Property, "target", CheckFlags.Readonly);
    targetPropertySymbol.parent = symbol;
    targetPropertySymbol.links.type = targetType;
    const members = createSymbolTable([targetPropertySymbol]);
    symbol.members = members;
    return createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
  }
  function getReturnTypeFromBody(func, checkMode) {
    if (!func.body) {
      return errorType;
    }
    const functionFlags = getFunctionFlags(func);
    const isAsync = (functionFlags & FunctionFlags.Async) !== 0;
    const isGenerator = (functionFlags & FunctionFlags.Generator) !== 0;
    let returnType;
    let yieldType;
    let nextType;
    let fallbackReturnType = voidType;
    if (func.body.kind !== SyntaxKind.Block) {
      returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
      if (isAsync) {
        returnType = unwrapAwaitedType(checkAwaitedType(
          returnType,
          /*withAlias*/
          false,
          /*errorNode*/
          func,
          Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
        ));
      }
    } else if (isGenerator) {
      const returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
      if (!returnTypes) {
        fallbackReturnType = neverType;
      } else if (returnTypes.length > 0) {
        returnType = getUnionType(returnTypes, UnionReduction.Subtype);
      }
      const { yieldTypes, nextTypes } = checkAndAggregateYieldOperandTypes(func, checkMode);
      yieldType = some(yieldTypes) ? getUnionType(yieldTypes, UnionReduction.Subtype) : void 0;
      nextType = some(nextTypes) ? getIntersectionType(nextTypes) : void 0;
    } else {
      const types = checkAndAggregateReturnExpressionTypes(func, checkMode);
      if (!types) {
        return functionFlags & FunctionFlags.Async ? createPromiseReturnType(func, neverType) : neverType;
      }
      if (types.length === 0) {
        const contextualReturnType = getContextualReturnType(
          func,
          /*contextFlags*/
          void 0
        );
        const returnType2 = contextualReturnType && (unwrapReturnType(contextualReturnType, functionFlags) || voidType).flags & TypeFlags.Undefined ? undefinedType : voidType;
        return functionFlags & FunctionFlags.Async ? createPromiseReturnType(func, returnType2) : (
          // Async function
          returnType2
        );
      }
      returnType = getUnionType(types, UnionReduction.Subtype);
    }
    if (returnType || yieldType || nextType) {
      if (yieldType) reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
      if (returnType) reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
      if (nextType) reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
      if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) {
        const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
        const contextualType = !contextualSignature ? void 0 : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? void 0 : returnType : instantiateContextualType(
          getReturnTypeOfSignature(contextualSignature),
          func,
          /*contextFlags*/
          void 0
        );
        if (isGenerator) {
          yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
          returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
          nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
        } else {
          returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
        }
      }
      if (yieldType) yieldType = getWidenedType(yieldType);
      if (returnType) returnType = getWidenedType(returnType);
      if (nextType) nextType = getWidenedType(nextType);
    }
    if (isGenerator) {
      return createGeneratorType(
        yieldType || neverType,
        returnType || fallbackReturnType,
        nextType || getContextualIterationType(2 /* Next */, func) || unknownType,
        isAsync
      );
    } else {
      return isAsync ? createPromiseType(returnType || fallbackReturnType) : returnType || fallbackReturnType;
    }
  }
  function createGeneratorType(yieldType, returnType, nextType, isAsyncGenerator) {
    const resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
    const globalGeneratorType = resolver.getGlobalGeneratorType(
      /*reportErrors*/
      false
    );
    yieldType = resolver.resolveIterationType(
      yieldType,
      /*errorNode*/
      void 0
    ) || unknownType;
    returnType = resolver.resolveIterationType(
      returnType,
      /*errorNode*/
      void 0
    ) || unknownType;
    if (globalGeneratorType === emptyGenericType) {
      const globalIterableIteratorType = resolver.getGlobalIterableIteratorType(
        /*reportErrors*/
        false
      );
      if (globalIterableIteratorType !== emptyGenericType) {
        return createTypeFromGenericGlobalType(globalIterableIteratorType, [yieldType, returnType, nextType]);
      }
      resolver.getGlobalIterableIteratorType(
        /*reportErrors*/
        true
      );
      return emptyObjectType;
    }
    return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
  }
  function checkAndAggregateYieldOperandTypes(func, checkMode) {
    const yieldTypes = [];
    const nextTypes = [];
    const isAsync = (getFunctionFlags(func) & FunctionFlags.Async) !== 0;
    forEachYieldExpression(func.body, (yieldExpression) => {
      const yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
      pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
      let nextType;
      if (yieldExpression.asteriskToken) {
        const iterationTypes = getIterationTypesOfIterable(
          yieldExpressionType,
          isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */,
          yieldExpression.expression
        );
        nextType = iterationTypes && iterationTypes.nextType;
      } else {
        nextType = getContextualType(
          yieldExpression,
          /*contextFlags*/
          void 0
        );
      }
      if (nextType) pushIfUnique(nextTypes, nextType);
    });
    return { yieldTypes, nextTypes };
  }
  function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
    const errorNode = node.expression || node;
    const yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
    return !isAsync ? yieldedType : getAwaitedType(
      yieldedType,
      errorNode,
      node.asteriskToken ? Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
    );
  }
  function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) {
    let facts = 0 /* None */;
    for (let i = 0; i < witnesses.length; i++) {
      const witness = i < start || i >= end ? witnesses[i] : void 0;
      facts |= witness !== void 0 ? typeofNEFacts.get(witness) || 32768 /* TypeofNEHostObject */ : 0;
    }
    return facts;
  }
  function isExhaustiveSwitchStatement(node) {
    const links = getNodeLinks(node);
    if (links.isExhaustive === void 0) {
      links.isExhaustive = 0;
      const exhaustive = computeExhaustiveSwitchStatement(node);
      if (links.isExhaustive === 0) {
        links.isExhaustive = exhaustive;
      }
    } else if (links.isExhaustive === 0) {
      links.isExhaustive = false;
    }
    return links.isExhaustive;
  }
  function computeExhaustiveSwitchStatement(node) {
    if (node.expression.kind === SyntaxKind.TypeOfExpression) {
      const witnesses = getSwitchClauseTypeOfWitnesses(node);
      if (!witnesses) {
        return false;
      }
      const operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression));
      const notEqualFacts = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses);
      if (operandConstraint.flags & TypeFlags.AnyOrUnknown) {
        return (556800 /* AllTypeofNE */ & notEqualFacts) === 556800 /* AllTypeofNE */;
      }
      return !someType(operandConstraint, (t) => getTypeFacts(t, notEqualFacts) === notEqualFacts);
    }
    const type = checkExpressionCached(node.expression);
    if (!isLiteralType(type)) {
      return false;
    }
    const switchTypes = getSwitchClauseTypes(node);
    if (!switchTypes.length || some(switchTypes, isNeitherUnitTypeNorNever)) {
      return false;
    }
    return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
  }
  function functionHasImplicitReturn(func) {
    return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
  }
  function checkAndAggregateReturnExpressionTypes(func, checkMode) {
    const functionFlags = getFunctionFlags(func);
    const aggregatedTypes = [];
    let hasReturnWithNoExpression = functionHasImplicitReturn(func);
    let hasReturnOfTypeNever = false;
    forEachReturnStatement(func.body, (returnStatement) => {
      let expr = returnStatement.expression;
      if (expr) {
        expr = skipParentheses(
          expr,
          /*excludeJSDocTypeAssertions*/
          true
        );
        if (functionFlags & FunctionFlags.Async && expr.kind === SyntaxKind.AwaitExpression) {
          expr = skipParentheses(
            expr.expression,
            /*excludeJSDocTypeAssertions*/
            true
          );
        }
        if (expr.kind === SyntaxKind.CallExpression && expr.expression.kind === SyntaxKind.Identifier && checkExpressionCached(expr.expression).symbol === getMergedSymbol(func.symbol) && (!isFunctionExpressionOrArrowFunction(func.symbol.valueDeclaration) || isConstantReference(expr.expression))) {
          hasReturnOfTypeNever = true;
          return;
        }
        let type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
        if (functionFlags & FunctionFlags.Async) {
          type = unwrapAwaitedType(checkAwaitedType(
            type,
            /*withAlias*/
            false,
            func,
            Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
          ));
        }
        if (type.flags & TypeFlags.Never) {
          hasReturnOfTypeNever = true;
        }
        pushIfUnique(aggregatedTypes, type);
      } else {
        hasReturnWithNoExpression = true;
      }
    });
    if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
      return void 0;
    }
    if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && !(isJSConstructor(func) && aggregatedTypes.some((t) => t.symbol === func.symbol))) {
      pushIfUnique(aggregatedTypes, undefinedType);
    }
    return aggregatedTypes;
  }
  function mayReturnNever(func) {
    switch (func.kind) {
      case SyntaxKind.FunctionExpression:
      case SyntaxKind.ArrowFunction:
        return true;
      case SyntaxKind.MethodDeclaration:
        return func.parent.kind === SyntaxKind.ObjectLiteralExpression;
      default:
        return false;
    }
  }
  function getTypePredicateFromBody(func) {
    switch (func.kind) {
      case SyntaxKind.Constructor:
      case SyntaxKind.GetAccessor:
      case SyntaxKind.SetAccessor:
        return void 0;
    }
    const functionFlags = getFunctionFlags(func);
    if (functionFlags !== FunctionFlags.Normal) return void 0;
    let singleReturn;
    if (func.body && func.body.kind !== SyntaxKind.Block) {
      singleReturn = func.body;
    } else {
      const bailedEarly = forEachReturnStatement(func.body, (returnStatement) => {
        if (singleReturn || !returnStatement.expression) return true;
        singleReturn = returnStatement.expression;
      });
      if (bailedEarly || !singleReturn || functionHasImplicitReturn(func)) return void 0;
    }
    return checkIfExpressionRefinesAnyParameter(func, singleReturn);
  }
  function checkIfExpressionRefinesAnyParameter(func, expr) {
    expr = skipParentheses(
      expr,
      /*excludeJSDocTypeAssertions*/
      true
    );
    const returnType = checkExpressionCached(expr);
    if (!(returnType.flags & TypeFlags.Boolean)) return void 0;
    return forEach(func.parameters, (param, i) => {
      const initType = getTypeOfSymbol(param.symbol);
      if (!initType || initType.flags & TypeFlags.Boolean || !isIdentifier(param.name) || isSymbolAssigned(param.symbol) || isRestParameter(param)) {
        return;
      }
      const trueType2 = checkIfExpressionRefinesParameter(func, expr, param, initType);
      if (trueType2) {
        return createTypePredicate(TypePredicateKind.Identifier, unescapeLeadingUnderscores(param.name.escapedText), i, trueType2);
      }
    });
  }
  function checkIfExpressionRefinesParameter(func, expr, param, initType) {
    const antecedent = expr.flowNode || expr.parent.kind === SyntaxKind.ReturnStatement && expr.parent.flowNode || createFlowNode(
      FlowFlags.Start,
      /*node*/
      void 0,
      /*antecedent*/
      void 0
    );
    const trueCondition = createFlowNode(FlowFlags.TrueCondition, expr, antecedent);
    const trueType2 = getFlowTypeOfReference(param.name, initType, initType, func, trueCondition);
    if (trueType2 === initType) return void 0;
    const falseCondition = createFlowNode(FlowFlags.FalseCondition, expr, antecedent);
    const falseSubtype = getFlowTypeOfReference(param.name, initType, trueType2, func, falseCondition);
    return falseSubtype.flags & TypeFlags.Never ? trueType2 : void 0;
  }
  function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
    addLazyDiagnostic(checkAllCodePathsInNonVoidFunctionReturnOrThrowDiagnostics);
    return;
    function checkAllCodePathsInNonVoidFunctionReturnOrThrowDiagnostics() {
      const functionFlags = getFunctionFlags(func);
      const type = returnType && unwrapReturnType(returnType, functionFlags);
      if (type && (maybeTypeOfKind(type, TypeFlags.Void) || type.flags & (TypeFlags.Any | TypeFlags.Undefined))) {
        return;
      }
      if (func.kind === SyntaxKind.MethodSignature || nodeIsMissing(func.body) || func.body.kind !== SyntaxKind.Block || !functionHasImplicitReturn(func)) {
        return;
      }
      const hasExplicitReturn = func.flags & NodeFlags.HasExplicitReturn;
      const errorNode = getEffectiveReturnTypeNode(func) || func;
      if (type && type.flags & TypeFlags.Never) {
        error(errorNode, Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
      } else if (type && !hasExplicitReturn) {
        error(errorNode, Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value);
      } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
        error(errorNode, Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
      } else if (compilerOptions.noImplicitReturns) {
        if (!type) {
          if (!hasExplicitReturn) {
            return;
          }
          const inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
          if (isUnwrappedReturnTypeUndefinedVoidOrAny(func, inferredReturnType)) {
            return;
          }
        }
        error(errorNode, Diagnostics.Not_all_code_paths_return_a_value);
      }
    }
  }
  function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
    Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node));
    checkNodeDeferred(node);
    if (isFunctionExpression(node)) {
      checkCollisionsForDeclarationName(node, node.name);
    }
    if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
      if (!getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
        const contextualSignature = getContextualSignature(node);
        if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
          const links = getNodeLinks(node);
          if (links.contextFreeType) {
            return links.contextFreeType;
          }
          const returnType = getReturnTypeFromBody(node, checkMode);
          const returnOnlySignature = createSignature(
            /*declaration*/
            void 0,
            /*typeParameters*/
            void 0,
            /*thisParameter*/
            void 0,
            emptyArray,
            returnType,
            /*resolvedTypePredicate*/
            void 0,
            0,
            SignatureFlags.IsNonInferrable
          );
          const returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], emptyArray, emptyArray);
          returnOnlyType.objectFlags |= ObjectFlags.NonInferrableType;
          return links.contextFreeType = returnOnlyType;
        }
      }
      return anyFunctionType;
    }
    const hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
    if (!hasGrammarError && node.kind === SyntaxKind.FunctionExpression) {
      checkGrammarForGenerator(node);
    }
    contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
    return getTypeOfSymbol(getSymbolOfDeclaration(node));
  }
  function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
    const links = getNodeLinks(node);
    if (!(links.flags & NodeCheckFlags.ContextChecked)) {
      const contextualSignature = getContextualSignature(node);
      if (!(links.flags & NodeCheckFlags.ContextChecked)) {
        links.flags |= NodeCheckFlags.ContextChecked;
        const signature = firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfDeclaration(node)), SignatureKind.Call));
        if (!signature) {
          return;
        }
        if (isContextSensitive(node)) {
          if (contextualSignature) {
            const inferenceContext = getInferenceContext(node);
            let instantiatedContextualSignature;
            if (checkMode && checkMode & 2 /* Inferential */) {
              inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
              const restType = getEffectiveRestType(contextualSignature);
              if (restType && restType.flags & TypeFlags.TypeParameter) {
                instantiatedContextualSignature = instantiateSignature(contextualSignature, inferenceContext.nonFixingMapper);
              }
            }
            instantiatedContextualSignature ||= inferenceContext ? instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
            assignContextualParameterTypes(signature, instantiatedContextualSignature);
          } else {
            assignNonContextualParameterTypes(signature);
          }
        } else if (contextualSignature && !node.typeParameters && contextualSignature.parameters.length > node.parameters.length) {
          const inferenceContext = getInferenceContext(node);
          if (checkMode && checkMode & 2 /* Inferential */) {
            inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
          }
        }
        if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
          const returnType = getReturnTypeFromBody(node, checkMode);
          if (!signature.resolvedReturnType) {
            signature.resolvedReturnType = returnType;
          }
        }
        checkSignatureDeclaration(node);
      }
    }
  }
  function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
    Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node));
    const functionFlags = getFunctionFlags(node);
    const returnType = getReturnTypeFromAnnotation(node);
    checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
    if (node.body) {
      if (!getEffectiveReturnTypeNode(node)) {
        getReturnTypeOfSignature(getSignatureFromDeclaration(node));
      }
      if (node.body.kind === SyntaxKind.Block) {
        checkSourceElement(node.body);
      } else {
        const exprType = checkExpression(node.body);
        const returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
        if (returnOrPromisedType) {
          const effectiveCheckNode = getEffectiveCheckNode(node.body);
          if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async) {
            const awaitedType = checkAwaitedType(
              exprType,
              /*withAlias*/
              false,
              effectiveCheckNode,
              Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
            );
            checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, effectiveCheckNode, effectiveCheckNode);
          } else {
            checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, effectiveCheckNode, effectiveCheckNode);
          }
        }
      }
    }
  }
  function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid = false) {
    if (!isTypeAssignableTo(type, numberOrBigIntType)) {
      const awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
      errorAndMaybeSuggestAwait(
        operand,
        !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType),
        diagnostic
      );
      return false;
    }
    return true;
  }
  function isReadonlyAssignmentDeclaration(d) {
    if (!isCallExpression(d)) {
      return false;
    }
    if (!isBindableObjectDefinePropertyCall(d)) {
      return false;
    }
    const objectLitType = checkExpressionCached(d.arguments[2]);
    const valueType = getTypeOfPropertyOfType(objectLitType, "value");
    if (valueType) {
      const writableProp = getPropertyOfType(objectLitType, "writable");
      const writableType = writableProp && getTypeOfSymbol(writableProp);
      if (!writableType || writableType === falseType || writableType === regularFalseType) {
        return true;
      }
      if (writableProp && writableProp.valueDeclaration && isPropertyAssignment(writableProp.valueDeclaration)) {
        const initializer = writableProp.valueDeclaration.initializer;
        const rawOriginalType = checkExpression(initializer);
        if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
          return true;
        }
      }
      return false;
    }
    const setProp = getPropertyOfType(objectLitType, "set");
    return !setProp;
  }
  function isReadonlySymbol(symbol) {
    return !!(getCheckFlags(symbol) & CheckFlags.Readonly || symbol.flags & SymbolFlags.Property && getDeclarationModifierFlagsFromSymbol(symbol) & ModifierFlags.Readonly || symbol.flags & SymbolFlags.Variable && getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Constant || symbol.flags & SymbolFlags.Accessor && !(symbol.flags & SymbolFlags.SetAccessor) || symbol.flags & SymbolFlags.EnumMember || some(symbol.declarations, isReadonlyAssignmentDeclaration));
  }
  function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
    if (assignmentKind === AssignmentKind.None) {
      return false;
    }
    if (isReadonlySymbol(symbol)) {
      if (symbol.flags & SymbolFlags.Property && isAccessExpression(expr) && expr.expression.kind === SyntaxKind.ThisKeyword) {
        const ctor = getContainingFunction(expr);
        if (!(ctor && (ctor.kind === SyntaxKind.Constructor || isJSConstructor(ctor)))) {
          return true;
        }
        if (symbol.valueDeclaration) {
          const isAssignmentDeclaration2 = isBinaryExpression(symbol.valueDeclaration);
          const isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
          const isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
          const isLocalThisPropertyAssignment = isAssignmentDeclaration2 && symbol.parent?.valueDeclaration === ctor.parent;
          const isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration2 && symbol.parent?.valueDeclaration === ctor;
          const isWriteableSymbol = isLocalPropertyDeclaration || isLocalParameterProperty || isLocalThisPropertyAssignment || isLocalThisPropertyAssignmentConstructorFunction;
          return !isWriteableSymbol;
        }
      }
      return true;
    }
    if (isAccessExpression(expr)) {
      const node = skipParentheses(expr.expression);
      if (node.kind === SyntaxKind.Identifier) {
        const symbol2 = getNodeLinks(node).resolvedSymbol;
        if (symbol2.flags & SymbolFlags.Alias) {
          const declaration = getDeclarationOfAliasSymbol(symbol2);
          return !!declaration && declaration.kind === SyntaxKind.NamespaceImport;
        }
      }
    }
    return false;
  }
  function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
    const node = skipOuterExpressions(expr, OuterExpressionKinds.Assertions | OuterExpressionKinds.Parentheses);
    if (node.kind !== SyntaxKind.Identifier && !isAccessExpression(node)) {
      error(expr, invalidReferenceMessage);
      return false;
    }
    if (node.flags & NodeFlags.OptionalChain) {
      error(expr, invalidOptionalChainMessage);
      return false;
    }
    return true;
  }
  function checkDeleteExpression(node) {
    checkExpression(node.expression);
    const expr = skipParentheses(node.expression);
    if (!isAccessExpression(expr)) {
      error(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
      return booleanType;
    }
    if (isPropertyAccessExpression(expr) && isPrivateIdentifier(expr.name)) {
      error(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
    }
    const links = getNodeLinks(expr);
    const symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
    if (symbol) {
      if (isReadonlySymbol(symbol)) {
        error(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
      } else {
        checkDeleteExpressionMustBeOptional(expr, symbol);
      }
    }
    return booleanType;
  }
  function checkDeleteExpressionMustBeOptional(expr, symbol) {
    const type = getTypeOfSymbol(symbol);
    if (strictNullChecks && !(type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Never)) && !(exactOptionalPropertyTypes ? symbol.flags & SymbolFlags.Optional : hasTypeFacts(type, 16777216 /* IsUndefined */))) {
      error(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_optional);
    }
  }
  function checkTypeOfExpression(node) {
    checkExpression(node.expression);
    return typeofType;
  }
  function checkVoidExpression(node) {
    checkNodeDeferred(node);
    return undefinedWideningType;
  }
  function checkAwaitGrammar(node) {
    let hasError = false;
    const container = getContainingFunctionOrClassStaticBlock(node);
    if (container && isClassStaticBlockDeclaration(container)) {
      const message = isAwaitExpression(node) ? Diagnostics.await_expression_cannot_be_used_inside_a_class_static_block : Diagnostics.await_using_statements_cannot_be_used_inside_a_class_static_block;
      error(node, message);
      hasError = true;
    } else if (!(node.flags & NodeFlags.AwaitContext)) {
      if (isInTopLevelContext(node)) {
        const sourceFile = getSourceFileOfNode(node);
        if (!hasParseDiagnostics(sourceFile)) {
          let span;
          if (!isEffectiveExternalModule(sourceFile, compilerOptions)) {
            span ??= getSpanOfTokenAtPosition(sourceFile, node.pos);
            const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module : Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module;
            const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message);
            diagnostics.add(diagnostic);
            hasError = true;
          }
          switch (moduleKind) {
            case ModuleKind.Node16:
            case ModuleKind.NodeNext:
              if (sourceFile.impliedNodeFormat === ModuleKind.CommonJS) {
                span ??= getSpanOfTokenAtPosition(sourceFile, node.pos);
                diagnostics.add(
                  createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level)
                );
                hasError = true;
                break;
              }
            // fallthrough
            case ModuleKind.ES2022:
            case ModuleKind.ESNext:
            case ModuleKind.Preserve:
            case ModuleKind.System:
              if (languageVersion >= ScriptTarget.ES2017) {
                break;
              }
            // fallthrough
            default:
              span ??= getSpanOfTokenAtPosition(sourceFile, node.pos);
              const message = isAwaitExpression(node) ? 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 : 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;
              diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message));
              hasError = true;
              break;
          }
        }
      } else {
        const sourceFile = getSourceFileOfNode(node);
        if (!hasParseDiagnostics(sourceFile)) {
          const span = getSpanOfTokenAtPosition(sourceFile, node.pos);
          const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules : Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules;
          const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message);
          if (container && container.kind !== SyntaxKind.Constructor && (getFunctionFlags(container) & FunctionFlags.Async) === 0) {
            const relatedInfo = createDiagnosticForNode(container, Diagnostics.Did_you_mean_to_mark_this_function_as_async);
            addRelatedInfo(diagnostic, relatedInfo);
          }
          diagnostics.add(diagnostic);
          hasError = true;
        }
      }
    }
    if (isAwaitExpression(node) && isInParameterInitializerBeforeContainingFunction(node)) {
      error(node, Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
      hasError = true;
    }
    return hasError;
  }
  function checkAwaitExpression(node) {
    addLazyDiagnostic(() => checkAwaitGrammar(node));
    const operandType = checkExpression(node.expression);
    const awaitedType = checkAwaitedType(
      operandType,
      /*withAlias*/
      true,
      node,
      Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
    );
    if (awaitedType === operandType && !isErrorType(awaitedType) && !(operandType.flags & TypeFlags.AnyOrUnknown)) {
      addErrorOrSuggestion(
        /*isError*/
        false,
        createDiagnosticForNode(node, Diagnostics.await_has_no_effect_on_the_type_of_this_expression)
      );
    }
    return awaitedType;
  }
  function checkPrefixUnaryExpression(node) {
    const operandType = checkExpression(node.operand);
    if (operandType === silentNeverType) {
      return silentNeverType;
    }
    switch (node.operand.kind) {
      case SyntaxKind.NumericLiteral:
        switch (node.operator) {
          case SyntaxKind.MinusToken:
            return getFreshTypeOfLiteralType(getNumberLiteralType(-node.operand.text));
          case SyntaxKind.PlusToken:
            return getFreshTypeOfLiteralType(getNumberLiteralType(+node.operand.text));
        }
        break;
      case SyntaxKind.BigIntLiteral:
        if (node.operator === SyntaxKind.MinusToken) {
          return getFreshTypeOfLiteralType(getBigIntLiteralType({
            negative: true,
            base10Value: parsePseudoBigInt(node.operand.text)
          }));
        }
    }
    switch (node.operator) {
      case SyntaxKind.PlusToken:
      case SyntaxKind.MinusToken:
      case SyntaxKind.TildeToken:
        checkNonNullType(operandType, node.operand);
        if (maybeTypeOfKindConsideringBaseConstraint(operandType, TypeFlags.ESSymbolLike)) {
          error(node.operand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(node.operator));
        }
        if (node.operator === SyntaxKind.PlusToken) {
          if (maybeTypeOfKindConsideringBaseConstraint(operandType, TypeFlags.BigIntLike)) {
            error(node.operand, Diagnostics.Operator_0_cannot_be_applied_to_type_1, tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
          }
          return numberType;
        }
        return getUnaryResultType(operandType);
      case SyntaxKind.ExclamationToken:
        checkTruthinessOfType(operandType, node.operand);
        const facts = getTypeFacts(operandType, 4194304 /* Truthy */ | 8388608 /* Falsy */);
        return facts === 4194304 /* Truthy */ ? falseType : facts === 8388608 /* Falsy */ ? trueType : booleanType;
      case SyntaxKind.PlusPlusToken:
      case SyntaxKind.MinusMinusToken:
        const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type);
        if (ok) {
          checkReferenceExpression(
            node.operand,
            Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access,
            Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access
          );
        }
        return getUnaryResultType(operandType);
    }
    return errorType;
  }
  function checkPostfixUnaryExpression(node) {
    const operandType = checkExpression(node.operand);
    if (operandType === silentNeverType) {
      return silentNeverType;
    }
    const ok = checkArithmeticOperandType(
      node.operand,
      checkNonNullType(operandType, node.operand),
      Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type
    );
    if (ok) {
      checkReferenceExpression(
        node.operand,
        Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access,
        Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access
      );
    }
    return getUnaryResultType(operandType);
  }
  function getUnaryResultType(operandType) {
    if (maybeTypeOfKind(operandType, TypeFlags.BigIntLike)) {
      return isTypeAssignableToKind(operandType, TypeFlags.AnyOrUnknown) || maybeTypeOfKind(operandType, TypeFlags.NumberLike) ? numberOrBigIntType : bigintType;
    }
    return numberType;
  }
  function maybeTypeOfKindConsideringBaseConstraint(type, kind) {
    if (maybeTypeOfKind(type, kind)) {
      return true;
    }
    const baseConstraint = getBaseConstraintOrType(type);
    return !!baseConstraint && maybeTypeOfKind(baseConstraint, kind);
  }
  function maybeTypeOfKind(type, kind) {
    if (type.flags & kind) {
      return true;
    }
    if (type.flags & TypeFlags.UnionOrIntersection) {
      const types = type.types;
      for (const t of types) {
        if (maybeTypeOfKind(t, kind)) {
          return true;
        }
      }
    }
    return false;
  }
  function isTypeAssignableToKind(source, kind, strict) {
    if (source.flags & kind) {
      return true;
    }
    if (strict && source.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null)) {
      return false;
    }
    return !!(kind & TypeFlags.NumberLike) && isTypeAssignableTo(source, numberType) || !!(kind & TypeFlags.BigIntLike) && isTypeAssignableTo(source, bigintType) || !!(kind & TypeFlags.StringLike) && isTypeAssignableTo(source, stringType) || !!(kind & TypeFlags.BooleanLike) && isTypeAssignableTo(source, booleanType) || !!(kind & TypeFlags.Void) && isTypeAssignableTo(source, voidType) || !!(kind & TypeFlags.Never) && isTypeAssignableTo(source, neverType) || !!(kind & TypeFlags.Null) && isTypeAssignableTo(source, nullType) || !!(kind & TypeFlags.Undefined) && isTypeAssignableTo(source, undefinedType) || !!(kind & TypeFlags.ESSymbol) && isTypeAssignableTo(source, esSymbolType) || !!(kind & TypeFlags.NonPrimitive) && isTypeAssignableTo(source, nonPrimitiveType);
  }
  function allTypesAssignableToKind(source, kind, strict) {
    return source.flags & TypeFlags.Union ? every(source.types, (subType) => allTypesAssignableToKind(subType, kind, strict)) : isTypeAssignableToKind(source, kind, strict);
  }
  function isConstEnumObjectType(type) {
    return !!(getObjectFlags(type) & ObjectFlags.Anonymous) && !!type.symbol && isConstEnumSymbol(type.symbol);
  }
  function isConstEnumSymbol(symbol) {
    return (symbol.flags & SymbolFlags.ConstEnum) !== 0;
  }
  function getSymbolHasInstanceMethodOfObjectType(type) {
    const hasInstancePropertyName = getPropertyNameForKnownSymbolName("hasInstance");
    if (allTypesAssignableToKind(type, TypeFlags.NonPrimitive)) {
      const hasInstanceProperty = getPropertyOfType(type, hasInstancePropertyName);
      if (hasInstanceProperty) {
        const hasInstancePropertyType = getTypeOfSymbol(hasInstanceProperty);
        if (hasInstancePropertyType && getSignaturesOfType(hasInstancePropertyType, SignatureKind.Call).length !== 0) {
          return hasInstancePropertyType;
        }
      }
    }
  }
  function checkInstanceOfExpression(left, right, leftType, rightType, checkMode) {
    if (leftType === silentNeverType || rightType === silentNeverType) {
      return silentNeverType;
    }
    if (!isTypeAny(leftType) && allTypesAssignableToKind(leftType, TypeFlags.Primitive)) {
      error(left, Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
    }
    Debug.assert(isInstanceOfExpression(left.parent));
    const signature = getResolvedSignature(
      left.parent,
      /*candidatesOutArray*/
      void 0,
      checkMode
    );
    if (signature === resolvingSignature) {
      return silentNeverType;
    }
    const returnType = getReturnTypeOfSignature(signature);
    checkTypeAssignableTo(returnType, booleanType, right, Diagnostics.An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_hand_side_of_an_instanceof_expression);
    return booleanType;
  }
  function hasEmptyObjectIntersection(type) {
    return someType(type, (t) => t === unknownEmptyObjectType || !!(t.flags & TypeFlags.Intersection) && isEmptyAnonymousObjectType(getBaseConstraintOrType(t)));
  }
  function checkInExpression(left, right, leftType, rightType) {
    if (leftType === silentNeverType || rightType === silentNeverType) {
      return silentNeverType;
    }
    if (isPrivateIdentifier(left)) {
      if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) {
        checkExternalEmitHelpers(left, ExternalEmitHelpers.ClassPrivateFieldIn);
      }
      if (!getNodeLinks(left).resolvedSymbol && getContainingClass(left)) {
        const isUncheckedJS = isUncheckedJSSuggestion(
          left,
          rightType.symbol,
          /*excludeClasses*/
          true
        );
        reportNonexistentProperty(left, rightType, isUncheckedJS);
      }
    } else {
      checkTypeAssignableTo(checkNonNullType(leftType, left), stringNumberSymbolType, left);
    }
    if (checkTypeAssignableTo(checkNonNullType(rightType, right), nonPrimitiveType, right)) {
      if (hasEmptyObjectIntersection(rightType)) {
        error(right, Diagnostics.Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operator, typeToString(rightType));
      }
    }
    return booleanType;
  }
  function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
    const properties = node.properties;
    if (strictNullChecks && properties.length === 0) {
      return checkNonNullType(sourceType, node);
    }
    for (let i = 0; i < properties.length; i++) {
      checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
    }
    return sourceType;
  }
  function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis = false) {
    const properties = node.properties;
    const property = properties[propertyIndex];
    if (property.kind === SyntaxKind.PropertyAssignment || property.kind === SyntaxKind.ShorthandPropertyAssignment) {
      const name = property.name;
      const exprType = getLiteralTypeFromPropertyName(name);
      if (isTypeUsableAsPropertyName(exprType)) {
        const text = getPropertyNameFromType(exprType);
        const prop = getPropertyOfType(objectLiteralType, text);
        if (prop) {
          markPropertyAsReferenced(prop, property, rightIsThis);
          checkPropertyAccessibility(
            property,
            /*isSuper*/
            false,
            /*writing*/
            true,
            objectLiteralType,
            prop
          );
        }
      }
      const elementType = getIndexedAccessType(objectLiteralType, exprType, AccessFlags.ExpressionPosition | (hasDefaultValue(property) ? AccessFlags.AllowMissing : 0), name);
      const type = getFlowTypeOfDestructuring(property, elementType);
      return checkDestructuringAssignment(property.kind === SyntaxKind.ShorthandPropertyAssignment ? property : property.initializer, type);
    } else if (property.kind === SyntaxKind.SpreadAssignment) {
      if (propertyIndex < properties.length - 1) {
        error(property, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
      } else {
        if (languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest) {
          checkExternalEmitHelpers(property, ExternalEmitHelpers.Rest);
        }
        const nonRestNames = [];
        if (allProperties) {
          for (const otherProperty of allProperties) {
            if (!isSpreadAssignment(otherProperty)) {
              nonRestNames.push(otherProperty.name);
            }
          }
        }
        const type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
        checkGrammarForDisallowedTrailingComma(allProperties, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
        return checkDestructuringAssignment(property.expression, type);
      }
    } else {
      error(property, Diagnostics.Property_assignment_expected);
    }
  }
  function checkArrayLiteralAssignment(node, sourceType, checkMode) {
    const elements = node.elements;
    if (languageVersion < LanguageFeatureMinimumTarget.DestructuringAssignment && compilerOptions.downlevelIteration) {
      checkExternalEmitHelpers(node, ExternalEmitHelpers.Read);
    }
    const possiblyOutOfBoundsType = checkIteratedTypeOrElementType(65 /* Destructuring */ | 128 /* PossiblyOutOfBounds */, sourceType, undefinedType, node) || errorType;
    let inBoundsType = compilerOptions.noUncheckedIndexedAccess ? void 0 : possiblyOutOfBoundsType;
    for (let i = 0; i < elements.length; i++) {
      let type = possiblyOutOfBoundsType;
      if (node.elements[i].kind === SyntaxKind.SpreadElement) {
        type = inBoundsType = inBoundsType ?? (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType);
      }
      checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode);
    }
    return sourceType;
  }
  function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
    const elements = node.elements;
    const element = elements[elementIndex];
    if (element.kind !== SyntaxKind.OmittedExpression) {
      if (element.kind !== SyntaxKind.SpreadElement) {
        const indexType = getNumberLiteralType(elementIndex);
        if (isArrayLikeType(sourceType)) {
          const accessFlags = AccessFlags.ExpressionPosition | (hasDefaultValue(element) ? AccessFlags.AllowMissing : 0);
          const elementType2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, accessFlags, createSyntheticExpression(element, indexType)) || errorType;
          const assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType2, 524288 /* NEUndefined */) : elementType2;
          const type = getFlowTypeOfDestructuring(element, assignedType);
          return checkDestructuringAssignment(element, type, checkMode);
        }
        return checkDestructuringAssignment(element, elementType, checkMode);
      }
      if (elementIndex < elements.length - 1) {
        error(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
      } else {
        const restExpression = element.expression;
        if (restExpression.kind === SyntaxKind.BinaryExpression && restExpression.operatorToken.kind === SyntaxKind.EqualsToken) {
          error(restExpression.operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer);
        } else {
          checkGrammarForDisallowedTrailingComma(node.elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
          const type = everyType(sourceType, isTupleType) ? mapType(sourceType, (t) => sliceTupleType(t, elementIndex)) : createArrayType(elementType);
          return checkDestructuringAssignment(restExpression, type, checkMode);
        }
      }
    }
    return void 0;
  }
  function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
    let target;
    if (exprOrAssignment.kind === SyntaxKind.ShorthandPropertyAssignment) {
      const prop = exprOrAssignment;
      if (prop.objectAssignmentInitializer) {
        if (strictNullChecks && !hasTypeFacts(checkExpression(prop.objectAssignmentInitializer), 16777216 /* IsUndefined */)) {
          sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
        }
        checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
      }
      target = exprOrAssignment.name;
    } else {
      target = exprOrAssignment;
    }
    if (target.kind === SyntaxKind.BinaryExpression && target.operatorToken.kind === SyntaxKind.EqualsToken) {
      checkBinaryExpression(target, checkMode);
      target = target.left;
      if (strictNullChecks) {
        sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
      }
    }
    if (target.kind === SyntaxKind.ObjectLiteralExpression) {
      return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
    }
    if (target.kind === SyntaxKind.ArrayLiteralExpression) {
      return checkArrayLiteralAssignment(target, sourceType, checkMode);
    }
    return checkReferenceAssignment(target, sourceType, checkMode);
  }
  function checkReferenceAssignment(target, sourceType, checkMode) {
    const targetType = checkExpression(target, checkMode);
    const error2 = target.parent.kind === SyntaxKind.SpreadAssignment ? Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
    const optionalError = target.parent.kind === SyntaxKind.SpreadAssignment ? Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
    if (checkReferenceExpression(target, error2, optionalError)) {
      checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
    }
    if (isPrivateIdentifierPropertyAccessExpression(target)) {
      checkExternalEmitHelpers(target.parent, ExternalEmitHelpers.ClassPrivateFieldSet);
    }
    return sourceType;
  }
  function isSideEffectFree(node) {
    node = skipParentheses(node);
    switch (node.kind) {
      case SyntaxKind.Identifier:
      case SyntaxKind.StringLiteral:
      case SyntaxKind.RegularExpressionLiteral:
      case SyntaxKind.TaggedTemplateExpression:
      case SyntaxKind.TemplateExpression:
      case SyntaxKind.NoSubstitutionTemplateLiteral:
      case SyntaxKind.NumericLiteral:
      case SyntaxKind.BigIntLiteral:
      case SyntaxKind.TrueKeyword:
      case SyntaxKind.FalseKeyword:
      case SyntaxKind.NullKeyword:
      case SyntaxKind.UndefinedKeyword:
      case SyntaxKind.FunctionExpression:
      case SyntaxKind.ClassExpression:
      case SyntaxKind.ArrowFunction:
      case SyntaxKind.ArrayLiteralExpression:
      case SyntaxKind.ObjectLiteralExpression:
      case SyntaxKind.TypeOfExpression:
      case SyntaxKind.NonNullExpression:
      case SyntaxKind.JsxSelfClosingElement:
      case SyntaxKind.JsxElement:
        return true;
      case SyntaxKind.ConditionalExpression:
        return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse);
      case SyntaxKind.BinaryExpression:
        if (isAssignmentOperator(node.operatorToken.kind)) {
          return false;
        }
        return isSideEffectFree(node.left) && isSideEffectFree(node.right);
      case SyntaxKind.PrefixUnaryExpression:
      case SyntaxKind.PostfixUnaryExpression:
        switch (node.operator) {
          case SyntaxKind.ExclamationToken:
          case SyntaxKind.PlusToken:
          case SyntaxKind.MinusToken:
          case SyntaxKind.TildeToken:
            return true;
        }
        return false;
      // Some forms listed here for clarity
      case SyntaxKind.VoidExpression:
      // Explicit opt-out
      case SyntaxKind.TypeAssertionExpression:
      // Not SEF, but can produce useful type warnings
      case SyntaxKind.AsExpression:
      // Not SEF, but can produce useful type warnings
      default:
        return false;
    }
  }
  function isTypeEqualityComparableTo(source, target) {
    return (target.flags & TypeFlags.Nullable) !== 0 || isTypeComparableTo(source, target);
  }
  function createCheckBinaryExpression() {
    const trampoline = createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState);
    return (node, checkMode) => {
      const result = trampoline(node, checkMode);
      Debug.assertIsDefined(result);
      return result;
    };
    function onEnter(node, state, checkMode) {
      if (state) {
        state.stackIndex++;
        state.skip = false;
        setLeftType(
          state,
          /*type*/
          void 0
        );
        setLastResult(
          state,
          /*type*/
          void 0
        );
      } else {
        state = {
          checkMode,
          skip: false,
          stackIndex: 0,
          typeStack: [void 0, void 0]
        };
      }
      if (isInJSFile(node) && getAssignedExpandoInitializer(node)) {
        state.skip = true;
        setLastResult(state, checkExpression(node.right, checkMode));
        return state;
      }
      checkNullishCoalesceOperands(node);
      const operator = node.operatorToken.kind;
      if (operator === SyntaxKind.EqualsToken && (node.left.kind === SyntaxKind.ObjectLiteralExpression || node.left.kind === SyntaxKind.ArrayLiteralExpression)) {
        state.skip = true;
        setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === SyntaxKind.ThisKeyword));
        return state;
      }
      return state;
    }
    function onLeft(left, state, _node) {
      if (!state.skip) {
        return maybeCheckExpression(state, left);
      }
    }
    function onOperator(operatorToken, state, node) {
      if (!state.skip) {
        const leftType = getLastResult(state);
        Debug.assertIsDefined(leftType);
        setLeftType(state, leftType);
        setLastResult(
          state,
          /*type*/
          void 0
        );
        const operator = operatorToken.kind;
        if (isLogicalOrCoalescingBinaryOperator(operator)) {
          let parent = node.parent;
          while (parent.kind === SyntaxKind.ParenthesizedExpression || isLogicalOrCoalescingBinaryExpression(parent)) {
            parent = parent.parent;
          }
          if (operator === SyntaxKind.AmpersandAmpersandToken || isIfStatement(parent)) {
            checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.left, leftType, isIfStatement(parent) ? parent.thenStatement : void 0);
          }
          if (isBinaryLogicalOperator(operator)) {
            checkTruthinessOfType(leftType, node.left);
          }
        }
      }
    }
    function onRight(right, state, _node) {
      if (!state.skip) {
        return maybeCheckExpression(state, right);
      }
    }
    function onExit(node, state) {
      let result;
      if (state.skip) {
        result = getLastResult(state);
      } else {
        const leftType = getLeftType(state);
        Debug.assertIsDefined(leftType);
        const rightType = getLastResult(state);
        Debug.assertIsDefined(rightType);
        result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, state.checkMode, node);
      }
      state.skip = false;
      setLeftType(
        state,
        /*type*/
        void 0
      );
      setLastResult(
        state,
        /*type*/
        void 0
      );
      state.stackIndex--;
      return result;
    }
    function foldState(state, result, _side) {
      setLastResult(state, result);
      return state;
    }
    function maybeCheckExpression(state, node) {
      if (isBinaryExpression(node)) {
        return node;
      }
      setLastResult(state, checkExpression(node, state.checkMode));
    }
    function getLeftType(state) {
      return state.typeStack[state.stackIndex];
    }
    function setLeftType(state, type) {
      state.typeStack[state.stackIndex] = type;
    }
    function getLastResult(state) {
      return state.typeStack[state.stackIndex + 1];
    }
    function setLastResult(state, type) {
      state.typeStack[state.stackIndex + 1] = type;
    }
  }
  function checkNullishCoalesceOperands(node) {
    const { left, operatorToken, right } = node;
    if (operatorToken.kind === SyntaxKind.QuestionQuestionToken) {
      if (isBinaryExpression(left) && (left.operatorToken.kind === SyntaxKind.BarBarToken || left.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken)) {
        grammarErrorOnNode(left, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(left.operatorToken.kind), tokenToString(operatorToken.kind));
      }
      if (isBinaryExpression(right) && (right.operatorToken.kind === SyntaxKind.BarBarToken || right.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken)) {
        grammarErrorOnNode(right, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(right.operatorToken.kind), tokenToString(operatorToken.kind));
      }
      const leftTarget = skipOuterExpressions(left, OuterExpressionKinds.All);
      const nullishSemantics = getSyntacticNullishnessSemantics(leftTarget);
      if (nullishSemantics !== PredicateSemantics.Sometimes) {
        if (node.parent.kind === SyntaxKind.BinaryExpression) {
          error(leftTarget, Diagnostics.This_binary_expression_is_never_nullish_Are_you_missing_parentheses);
        } else {
          if (nullishSemantics === PredicateSemantics.Always) {
            error(leftTarget, Diagnostics.This_expression_is_always_nullish);
          } else {
            error(leftTarget, Diagnostics.Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish);
          }
        }
      }
    }
  }
  function getSyntacticNullishnessSemantics(node) {
    node = skipOuterExpressions(node);
    switch (node.kind) {
      case SyntaxKind.AwaitExpression:
      case SyntaxKind.CallExpression:
      case SyntaxKind.ElementAccessExpression:
      case SyntaxKind.NewExpression:
      case SyntaxKind.PropertyAccessExpression:
      case SyntaxKind.YieldExpression:
      case SyntaxKind.ThisKeyword:
        return PredicateSemantics.Sometimes;
      case SyntaxKind.BinaryExpression:
        switch (node.operatorToken.kind) {
          case SyntaxKind.EqualsToken:
          case SyntaxKind.QuestionQuestionToken:
          case SyntaxKind.QuestionQuestionEqualsToken:
          case SyntaxKind.BarBarToken:
          case SyntaxKind.BarBarEqualsToken:
          case SyntaxKind.AmpersandAmpersandToken:
          case SyntaxKind.AmpersandAmpersandEqualsToken:
            return PredicateSemantics.Sometimes;
        }
        return PredicateSemantics.Never;
      case SyntaxKind.ConditionalExpression:
        return getSyntacticNullishnessSemantics(node.whenTrue) | getSyntacticNullishnessSemantics(node.whenFalse);
      case SyntaxKind.NullKeyword:
        return PredicateSemantics.Always;
      case SyntaxKind.Identifier:
        if (getResolvedSymbol(node) === undefinedSymbol) {
          return PredicateSemantics.Always;
        }
        return PredicateSemantics.Sometimes;
    }
    return PredicateSemantics.Never;
  }
  function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
    const operator = operatorToken.kind;
    if (operator === SyntaxKind.EqualsToken && (left.kind === SyntaxKind.ObjectLiteralExpression || left.kind === SyntaxKind.ArrayLiteralExpression)) {
      return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === SyntaxKind.ThisKeyword);
    }
    let leftType;
    if (isBinaryLogicalOperator(operator)) {
      leftType = checkTruthinessExpression(left, checkMode);
    } else {
      leftType = checkExpression(left, checkMode);
    }
    const rightType = checkExpression(right, checkMode);
    return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, checkMode, errorNode);
  }
  function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, checkMode, errorNode) {
    const operator = operatorToken.kind;
    switch (operator) {
      case SyntaxKind.AsteriskToken:
      case SyntaxKind.AsteriskAsteriskToken:
      case SyntaxKind.AsteriskEqualsToken:
      case SyntaxKind.AsteriskAsteriskEqualsToken:
      case SyntaxKind.SlashToken:
      case SyntaxKind.SlashEqualsToken:
      case SyntaxKind.PercentToken:
      case SyntaxKind.PercentEqualsToken:
      case SyntaxKind.MinusToken:
      case SyntaxKind.MinusEqualsToken:
      case SyntaxKind.LessThanLessThanToken:
      case SyntaxKind.LessThanLessThanEqualsToken:
      case SyntaxKind.GreaterThanGreaterThanToken:
      case SyntaxKind.GreaterThanGreaterThanEqualsToken:
      case SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
      case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:
      case SyntaxKind.BarToken:
      case SyntaxKind.BarEqualsToken:
      case SyntaxKind.CaretToken:
      case SyntaxKind.CaretEqualsToken:
      case SyntaxKind.AmpersandToken:
      case SyntaxKind.AmpersandEqualsToken:
        if (leftType === silentNeverType || rightType === silentNeverType) {
          return silentNeverType;
        }
        leftType = checkNonNullType(leftType, left);
        rightType = checkNonNullType(rightType, right);
        let suggestedOperator;
        if (leftType.flags & TypeFlags.BooleanLike && rightType.flags & TypeFlags.BooleanLike && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== void 0) {
          error(errorNode || operatorToken, Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, tokenToString(operatorToken.kind), tokenToString(suggestedOperator));
          return numberType;
        } else {
          const leftOk = checkArithmeticOperandType(
            left,
            leftType,
            Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type,
            /*isAwaitValid*/
            true
          );
          const rightOk = checkArithmeticOperandType(
            right,
            rightType,
            Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type,
            /*isAwaitValid*/
            true
          );
          let resultType2;
          if (isTypeAssignableToKind(leftType, TypeFlags.AnyOrUnknown) && isTypeAssignableToKind(rightType, TypeFlags.AnyOrUnknown) || // Or, if neither could be bigint, implicit coercion results in a number result
          !(maybeTypeOfKind(leftType, TypeFlags.BigIntLike) || maybeTypeOfKind(rightType, TypeFlags.BigIntLike))) {
            resultType2 = numberType;
          } else if (bothAreBigIntLike(leftType, rightType)) {
            switch (operator) {
              case SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
              case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:
                reportOperatorError();
                break;
              case SyntaxKind.AsteriskAsteriskToken:
              case SyntaxKind.AsteriskAsteriskEqualsToken:
                if (languageVersion < ScriptTarget.ES2016) {
                  error(errorNode, Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later);
                }
            }
            resultType2 = bigintType;
          } else {
            reportOperatorError(bothAreBigIntLike);
            resultType2 = errorType;
          }
          if (leftOk && rightOk) {
            checkAssignmentOperator(resultType2);
            switch (operator) {
              case SyntaxKind.LessThanLessThanToken:
              case SyntaxKind.LessThanLessThanEqualsToken:
              case SyntaxKind.GreaterThanGreaterThanToken:
              case SyntaxKind.GreaterThanGreaterThanEqualsToken:
              case SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
              case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:
                const rhsEval = evaluate(right);
                if (typeof rhsEval.value === "number" && Math.abs(rhsEval.value) >= 32) {
                  errorOrSuggestion(
                    isEnumMember(walkUpParenthesizedExpressions(right.parent.parent)),
                    // elevate from suggestion to error within an enum member
                    errorNode || operatorToken,
                    Diagnostics.This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2,
                    getTextOfNode(left),
                    tokenToString(operator),
                    rhsEval.value % 32
                  );
                }
                break;
              default:
                break;
            }
          }
          return resultType2;
        }
      case SyntaxKind.PlusToken:
      case SyntaxKind.PlusEqualsToken:
        if (leftType === silentNeverType || rightType === silentNeverType) {
          return silentNeverType;
        }
        if (!isTypeAssignableToKind(leftType, TypeFlags.StringLike) && !isTypeAssignableToKind(rightType, TypeFlags.StringLike)) {
          leftType = checkNonNullType(leftType, left);
          rightType = checkNonNullType(rightType, right);
        }
        let resultType;
        if (isTypeAssignableToKind(
          leftType,
          TypeFlags.NumberLike,
          /*strict*/
          true
        ) && isTypeAssignableToKind(
          rightType,
          TypeFlags.NumberLike,
          /*strict*/
          true
        )) {
          resultType = numberType;
        } else if (isTypeAssignableToKind(
          leftType,
          TypeFlags.BigIntLike,
          /*strict*/
          true
        ) && isTypeAssignableToKind(
          rightType,
          TypeFlags.BigIntLike,
          /*strict*/
          true
        )) {
          resultType = bigintType;
        } else if (isTypeAssignableToKind(
          leftType,
          TypeFlags.StringLike,
          /*strict*/
          true
        ) || isTypeAssignableToKind(
          rightType,
          TypeFlags.StringLike,
          /*strict*/
          true
        )) {
          resultType = stringType;
        } else if (isTypeAny(leftType) || isTypeAny(rightType)) {
          resultType = isErrorType(leftType) || isErrorType(rightType) ? errorType : anyType;
        }
        if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
          return resultType;
        }
        if (!resultType) {
          const closeEnoughKind = TypeFlags.NumberLike | TypeFlags.BigIntLike | TypeFlags.StringLike | TypeFlags.AnyOrUnknown;
          reportOperatorError(
            (left2, right2) => isTypeAssignableToKind(left2, closeEnoughKind) && isTypeAssignableToKind(right2, closeEnoughKind)
          );
          return anyType;
        }
        if (operator === SyntaxKind.PlusEqualsToken) {
          checkAssignmentOperator(resultType);
        }
        return resultType;
      case SyntaxKind.LessThanToken:
      case SyntaxKind.GreaterThanToken:
      case SyntaxKind.LessThanEqualsToken:
      case SyntaxKind.GreaterThanEqualsToken:
        if (checkForDisallowedESSymbolOperand(operator)) {
          leftType = getBaseTypeOfLiteralTypeForComparison(checkNonNullType(leftType, left));
          rightType = getBaseTypeOfLiteralTypeForComparison(checkNonNullType(rightType, right));
          reportOperatorErrorUnless((left2, right2) => {
            if (isTypeAny(left2) || isTypeAny(right2)) {
              return true;
            }
            const leftAssignableToNumber = isTypeAssignableTo(left2, numberOrBigIntType);
            const rightAssignableToNumber = isTypeAssignableTo(right2, numberOrBigIntType);
            return leftAssignableToNumber && rightAssignableToNumber || !leftAssignableToNumber && !rightAssignableToNumber && areTypesComparable(left2, right2);
          });
        }
        return booleanType;
      case SyntaxKind.EqualsEqualsToken:
      case SyntaxKind.ExclamationEqualsToken:
      case SyntaxKind.EqualsEqualsEqualsToken:
      case SyntaxKind.ExclamationEqualsEqualsToken:
        if (!(checkMode && checkMode & 64 /* TypeOnly */)) {
          if ((isLiteralExpressionOfObject(left) || isLiteralExpressionOfObject(right)) && // only report for === and !== in JS, not == or !=
          (!isInJSFile(left) || (operator === SyntaxKind.EqualsEqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken))) {
            const eqType = operator === SyntaxKind.EqualsEqualsToken || operator === SyntaxKind.EqualsEqualsEqualsToken;
            error(errorNode, Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true");
          }
          checkNaNEquality(errorNode, operator, left, right);
          reportOperatorErrorUnless((left2, right2) => isTypeEqualityComparableTo(left2, right2) || isTypeEqualityComparableTo(right2, left2));
        }
        return booleanType;
      case SyntaxKind.InstanceOfKeyword:
        return checkInstanceOfExpression(left, right, leftType, rightType, checkMode);
      case SyntaxKind.InKeyword:
        return checkInExpression(left, right, leftType, rightType);
      case SyntaxKind.AmpersandAmpersandToken:
      case SyntaxKind.AmpersandAmpersandEqualsToken: {
        const resultType2 = hasTypeFacts(leftType, 4194304 /* Truthy */) ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType;
        if (operator === SyntaxKind.AmpersandAmpersandEqualsToken) {
          checkAssignmentOperator(rightType);
        }
        return resultType2;
      }
      case SyntaxKind.BarBarToken:
      case SyntaxKind.BarBarEqualsToken: {
        const resultType2 = hasTypeFacts(leftType, 8388608 /* Falsy */) ? getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], UnionReduction.Subtype) : leftType;
        if (operator === SyntaxKind.BarBarEqualsToken) {
          checkAssignmentOperator(rightType);
        }
        return resultType2;
      }
      case SyntaxKind.QuestionQuestionToken:
      case SyntaxKind.QuestionQuestionEqualsToken: {
        const resultType2 = hasTypeFacts(leftType, 262144 /* EQUndefinedOrNull */) ? getUnionType([getNonNullableType(leftType), rightType], UnionReduction.Subtype) : leftType;
        if (operator === SyntaxKind.QuestionQuestionEqualsToken) {
          checkAssignmentOperator(rightType);
        }
        return resultType2;
      }
      case SyntaxKind.EqualsToken:
        const declKind = isBinaryExpression(left.parent) ? getAssignmentDeclarationKind(left.parent) : AssignmentDeclarationKind.None;
        checkAssignmentDeclaration(declKind, rightType);
        if (isAssignmentDeclaration2(declKind)) {
          if (!(rightType.flags & TypeFlags.Object) || declKind !== AssignmentDeclarationKind.ModuleExports && declKind !== AssignmentDeclarationKind.Prototype && !isEmptyObjectType(rightType) && !isFunctionObjectType(rightType) && !(getObjectFlags(rightType) & ObjectFlags.Class)) {
            checkAssignmentOperator(rightType);
          }
          return leftType;
        } else {
          checkAssignmentOperator(rightType);
          return rightType;
        }
      case SyntaxKind.CommaToken:
        if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isIndirectCall(left.parent)) {
          const sf = getSourceFileOfNode(left);
          const sourceText = sf.text;
          const start = skipTrivia(sourceText, left.pos);
          const isInDiag2657 = sf.parseDiagnostics.some((diag) => {
            if (diag.code !== Diagnostics.JSX_expressions_must_have_one_parent_element.code) return false;
            return textSpanContainsPosition(diag, start);
          });
          if (!isInDiag2657) error(left, Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
        }
        return rightType;
      default:
        return Debug.fail();
    }
    function bothAreBigIntLike(left2, right2) {
      return isTypeAssignableToKind(left2, TypeFlags.BigIntLike) && isTypeAssignableToKind(right2, TypeFlags.BigIntLike);
    }
    function checkAssignmentDeclaration(kind, rightType2) {
      if (kind === AssignmentDeclarationKind.ModuleExports) {
        for (const prop of getPropertiesOfObjectType(rightType2)) {
          const propType = getTypeOfSymbol(prop);
          if (propType.symbol && propType.symbol.flags & SymbolFlags.Class) {
            const name = prop.escapedName;
            const symbol = resolveName(
              prop.valueDeclaration,
              name,
              SymbolFlags.Type,
              /*nameNotFoundMessage*/
              void 0,
              /*isUse*/
              false
            );
            if (symbol?.declarations && symbol.declarations.some(isJSDocTypedefTag)) {
              addDuplicateDeclarationErrorsForSymbols(symbol, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), prop);
              addDuplicateDeclarationErrorsForSymbols(prop, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), symbol);
            }
          }
        }
      }
    }
    function isIndirectCall(node) {
      return node.parent.kind === SyntaxKind.ParenthesizedExpression && isNumericLiteral(node.left) && node.left.text === "0" && (isCallExpression(node.parent.parent) && node.parent.parent.expression === node.parent || node.parent.parent.kind === SyntaxKind.TaggedTemplateExpression) && // special-case for "eval" because it's the only non-access case where an indirect call actually affects behavior.
      (isAccessExpression(node.right) || isIdentifier(node.right) && node.right.escapedText === "eval");
    }
    function checkForDisallowedESSymbolOperand(operator2) {
      const offendingSymbolOperand = maybeTypeOfKindConsideringBaseConstraint(leftType, TypeFlags.ESSymbolLike) ? left : maybeTypeOfKindConsideringBaseConstraint(rightType, TypeFlags.ESSymbolLike) ? right : void 0;
      if (offendingSymbolOperand) {
        error(offendingSymbolOperand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(operator2));
        return false;
      }
      return true;
    }
    function getSuggestedBooleanOperator(operator2) {
      switch (operator2) {
        case SyntaxKind.BarToken:
        case SyntaxKind.BarEqualsToken:
          return SyntaxKind.BarBarToken;
        case SyntaxKind.CaretToken:
        case SyntaxKind.CaretEqualsToken:
          return SyntaxKind.ExclamationEqualsEqualsToken;
        case SyntaxKind.AmpersandToken:
        case SyntaxKind.AmpersandEqualsToken:
          return SyntaxKind.AmpersandAmpersandToken;
        default:
          return void 0;
      }
    }
    function checkAssignmentOperator(valueType) {
      if (isAssignmentOperator(operator)) {
        addLazyDiagnostic(checkAssignmentOperatorWorker);
      }
      function checkAssignmentOperatorWorker() {
        let assigneeType = leftType;
        if (isCompoundAssignment(operatorToken.kind) && left.kind === SyntaxKind.PropertyAccessExpression) {
          assigneeType = checkPropertyAccessExpression(
            left,
            /*checkMode*/
            void 0,
            /*writeOnly*/
            true
          );
        }
        if (checkReferenceExpression(left, Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access)) {
          let headMessage;
          if (exactOptionalPropertyTypes && isPropertyAccessExpression(left) && maybeTypeOfKind(valueType, TypeFlags.Undefined)) {
            const target = getTypeOfPropertyOfType(getTypeOfExpression(left.expression), left.name.escapedText);
            if (isExactOptionalPropertyMismatch(valueType, target)) {
              headMessage = Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target;
            }
          }
          checkTypeAssignableToAndOptionallyElaborate(valueType, assigneeType, left, right, headMessage);
        }
      }
    }
    function isAssignmentDeclaration2(kind) {
      switch (kind) {
        case AssignmentDeclarationKind.ModuleExports:
          return true;
        case AssignmentDeclarationKind.ExportsProperty:
        case AssignmentDeclarationKind.Property:
        case AssignmentDeclarationKind.Prototype:
        case AssignmentDeclarationKind.PrototypeProperty:
        case AssignmentDeclarationKind.ThisProperty:
          const symbol = getSymbolOfNode(left);
          const init = getAssignedExpandoInitializer(right);
          return !!init && isObjectLiteralExpression(init) && !!symbol?.exports?.size;
        default:
          return false;
      }
    }
    function reportOperatorErrorUnless(typesAreCompatible) {
      if (!typesAreCompatible(leftType, rightType)) {
        reportOperatorError(typesAreCompatible);
        return true;
      }
      return false;
    }
    function reportOperatorError(isRelated) {
      let wouldWorkWithAwait = false;
      const errNode = errorNode || operatorToken;
      if (isRelated) {
        const awaitedLeftType = getAwaitedTypeNoAlias(leftType);
        const awaitedRightType = getAwaitedTypeNoAlias(rightType);
        wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType) && !!(awaitedLeftType && awaitedRightType) && isRelated(awaitedLeftType, awaitedRightType);
      }
      let effectiveLeft = leftType;
      let effectiveRight = rightType;
      if (!wouldWorkWithAwait && isRelated) {
        [effectiveLeft, effectiveRight] = getBaseTypesIfUnrelated(leftType, rightType, isRelated);
      }
      const [leftStr, rightStr] = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight);
      if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
        errorAndMaybeSuggestAwait(
          errNode,
          wouldWorkWithAwait,
          Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2,
          tokenToString(operatorToken.kind),
          leftStr,
          rightStr
        );
      }
    }
    function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
      switch (operatorToken.kind) {
        case SyntaxKind.EqualsEqualsEqualsToken:
        case SyntaxKind.EqualsEqualsToken:
        case SyntaxKind.ExclamationEqualsEqualsToken:
        case SyntaxKind.ExclamationEqualsToken:
          return errorAndMaybeSuggestAwait(
            errNode,
            maybeMissingAwait,
            Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap,
            leftStr,
            rightStr
          );
        default:
          return void 0;
      }
    }
    function checkNaNEquality(errorNode2, operator2, left2, right2) {
      const isLeftNaN = isGlobalNaN(skipParentheses(left2));
      const isRightNaN = isGlobalNaN(skipParentheses(right2));
      if (isLeftNaN || isRightNaN) {
        const err = error(errorNode2, Diagnostics.This_condition_will_always_return_0, tokenToString(operator2 === SyntaxKind.EqualsEqualsEqualsToken || operator2 === SyntaxKind.EqualsEqualsToken ? SyntaxKind.FalseKeyword : SyntaxKind.TrueKeyword));
        if (isLeftNaN && isRightNaN) return;
        const operatorString = operator2 === SyntaxKind.ExclamationEqualsEqualsToken || operator2 === SyntaxKind.ExclamationEqualsToken ? tokenToString(SyntaxKind.ExclamationToken) : "";
        const location = isLeftNaN ? right2 : left2;
        const expression = skipParentheses(location);
        addRelatedInfo(err, createDiagnosticForNode(location, Diagnostics.Did_you_mean_0, `${operatorString}Number.isNaN(${isEntityNameExpression(expression) ? entityNameToString(expression) : "..."})`));
      }
    }
    function isGlobalNaN(expr) {
      if (isIdentifier(expr) && expr.escapedText === "NaN") {
        const globalNaNSymbol = getGlobalNaNSymbol();
        return !!globalNaNSymbol && globalNaNSymbol === getResolvedSymbol(expr);
      }
      return false;
    }
  }
  function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
    let effectiveLeft = leftType;
    let effectiveRight = rightType;
    const leftBase = getBaseTypeOfLiteralType(leftType);
    const rightBase = getBaseTypeOfLiteralType(rightType);
    if (!isRelated(leftBase, rightBase)) {
      effectiveLeft = leftBase;
      effectiveRight = rightBase;
    }
    return [effectiveLeft, effectiveRight];
  }
  function checkYieldExpression(node) {
    addLazyDiagnostic(checkYieldExpressionGrammar);
    const func = getContainingFunction(node);
    if (!func) return anyType;
    const functionFlags = getFunctionFlags(func);
    if (!(functionFlags & FunctionFlags.Generator)) {
      return anyType;
    }
    const isAsync = (functionFlags & FunctionFlags.Async) !== 0;
    if (node.asteriskToken) {
      if (isAsync && languageVersion < LanguageFeatureMinimumTarget.AsyncGenerators) {
        checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncDelegatorIncludes);
      }
      if (!isAsync && languageVersion < LanguageFeatureMinimumTarget.Generators && compilerOptions.downlevelIteration) {
        checkExternalEmitHelpers(node, ExternalEmitHelpers.Values);
      }
    }
    let returnType = getReturnTypeFromAnnotation(func);
    if (returnType && returnType.flags & TypeFlags.Union) {
      returnType = filterType(returnType, (t) => checkGeneratorInstantiationAssignabilityToReturnType(
        t,
        functionFlags,
        /*errorNode*/
        void 0
      ));
    }
    const iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
    const signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
    const signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
    const yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
    const yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, signatureNextType, isAsync);
    if (returnType && yieldedType) {
      checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
    }
    if (node.asteriskToken) {
      const use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
      return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression) || anyType;
    } else if (returnType) {
      return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync) || anyType;
    }
    let type = getContextualIterationType(2 /* Next */, func);
    if (!type) {
      type = anyType;
      addLazyDiagnostic(() => {
        if (noImplicitAny && !expressionResultIsUnused(node)) {
          const contextualType = getContextualType(
            node,
            /*contextFlags*/
            void 0
          );
          if (!contextualType || isTypeAny(contextualType)) {
            error(node, Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation);
          }
        }
      });
    }
    return type;
    function checkYieldExpressionGrammar() {
      if (!(node.flags & NodeFlags.YieldContext)) {
        grammarErrorOnFirstToken(node, Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
      }
      if (isInParameterInitializerBeforeContainingFunction(node)) {
        error(node, Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
      }
    }
  }
  function checkConditionalExpression(node, checkMode) {
    const type = checkTruthinessExpression(node.condition, checkMode);
    checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.condition, type, node.whenTrue);
    const type1 = checkExpression(node.whenTrue, checkMode);
    const type2 = checkExpression(node.whenFalse, checkMode);
    return getUnionType([type1, type2], UnionReduction.Subtype);
  }
  function isTemplateLiteralContext(node) {
    const parent = node.parent;
    return isParenthesizedExpression(parent) && isTemplateLiteralContext(parent) || isElementAccessExpression(parent) && parent.argumentExpression === node;
  }
  function checkTemplateExpression(node) {
    const texts = [node.head.text];
    const types = [];
    for (const span of node.templateSpans) {
      const type = checkExpression(span.expression);
      if (maybeTypeOfKindConsideringBaseConstraint(type, TypeFlags.ESSymbolLike)) {
        error(span.expression, Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
      }
      texts.push(span.literal.text);
      types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType);
    }
    const evaluated = node.parent.kind !== SyntaxKind.TaggedTemplateExpression && evaluate(node).value;
    if (evaluated) {
      return getFreshTypeOfLiteralType(getStringLiteralType(evaluated));
    }
    if (isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(
      node,
      /*contextFlags*/
      void 0
    ) || unknownType, isTemplateLiteralContextualType)) {
      return getTemplateLiteralType(texts, types);
    }
    return stringType;
  }
  function isTemplateLiteralContextualType(type) {
    return !!(type.flags & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral) || type.flags & TypeFlags.InstantiableNonPrimitive && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, TypeFlags.StringLike));
  }
  function getContextNode(node) {
    if (isJsxAttributes(node) && !isJsxSelfClosingElement(node.parent)) {
      return node.parent.parent;
    }
    return node;
  }
  function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
    const contextNode = getContextNode(node);
    pushContextualType(
      contextNode,
      contextualType,
      /*isCache*/
      false
    );
    pushInferenceContext(contextNode, inferenceContext);
    const type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
    if (inferenceContext && inferenceContext.intraExpressionInferenceSites) {
      inferenceContext.intraExpressionInferenceSites = void 0;
    }
    const result = maybeTypeOfKind(type, TypeFlags.Literal) && isLiteralOfContextualType(type, instantiateContextualType(
      contextualType,
      node,
      /*contextFlags*/
      void 0
    )) ? getRegularTypeOfLiteralType(type) : type;
    popInferenceContext();
    popContextualType();
    return result;
  }
  function checkExpressionCached(node, checkMode) {
    if (checkMode) {
      return checkExpression(node, checkMode);
    }
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const saveFlowLoopStart = flowLoopStart;
      const saveFlowTypeCache = flowTypeCache;
      flowLoopStart = flowLoopCount;
      flowTypeCache = void 0;
      links.resolvedType = checkExpression(node, checkMode);
      flowTypeCache = saveFlowTypeCache;
      flowLoopStart = saveFlowLoopStart;
    }
    return links.resolvedType;
  }
  function isTypeAssertion(node) {
    node = skipParentheses(
      node,
      /*excludeJSDocTypeAssertions*/
      true
    );
    return node.kind === SyntaxKind.TypeAssertionExpression || node.kind === SyntaxKind.AsExpression || isJSDocTypeAssertion(node);
  }
  function checkDeclarationInitializer(declaration, checkMode, contextualType) {
    const initializer = getEffectiveInitializer(declaration);
    if (isInJSFile(declaration)) {
      const typeNode = tryGetJSDocSatisfiesTypeNode(declaration);
      if (typeNode) {
        return checkSatisfiesExpressionWorker(initializer, typeNode, checkMode);
      }
    }
    const type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType(
      initializer,
      contextualType,
      /*inferenceContext*/
      void 0,
      checkMode || 0 /* Normal */
    ) : checkExpressionCached(initializer, checkMode));
    if (isParameter(isBindingElement(declaration) ? walkUpBindingElementsAndPatterns(declaration) : declaration)) {
      if (declaration.name.kind === SyntaxKind.ObjectBindingPattern && isObjectLiteralType(type)) {
        return padObjectLiteralType(type, declaration.name);
      }
      if (declaration.name.kind === SyntaxKind.ArrayBindingPattern && isTupleType(type)) {
        return padTupleType(type, declaration.name);
      }
    }
    return type;
  }
  function padObjectLiteralType(type, pattern) {
    let missingElements;
    for (const e of pattern.elements) {
      if (e.initializer) {
        const name = getPropertyNameFromBindingElement(e);
        if (name && !getPropertyOfType(type, name)) {
          missingElements = append(missingElements, e);
        }
      }
    }
    if (!missingElements) {
      return type;
    }
    const members = createSymbolTable();
    for (const prop of getPropertiesOfObjectType(type)) {
      members.set(prop.escapedName, prop);
    }
    for (const e of missingElements) {
      const symbol = createSymbol(SymbolFlags.Property | SymbolFlags.Optional, getPropertyNameFromBindingElement(e));
      symbol.links.type = getTypeFromBindingElement(
        e,
        /*includePatternInType*/
        false,
        /*reportErrors*/
        false
      );
      members.set(symbol.escapedName, symbol);
    }
    const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, getIndexInfosOfType(type));
    result.objectFlags = type.objectFlags;
    return result;
  }
  function getPropertyNameFromBindingElement(e) {
    const exprType = getLiteralTypeFromPropertyName(e.propertyName || e.name);
    return isTypeUsableAsPropertyName(exprType) ? getPropertyNameFromType(exprType) : void 0;
  }
  function padTupleType(type, pattern) {
    if (type.target.combinedFlags & ElementFlags.Variable || getTypeReferenceArity(type) >= pattern.elements.length) {
      return type;
    }
    const patternElements = pattern.elements;
    const elementTypes = getElementTypes(type).slice();
    const elementFlags = type.target.elementFlags.slice();
    for (let i = getTypeReferenceArity(type); i < patternElements.length; i++) {
      const e = patternElements[i];
      if (i < patternElements.length - 1 || !(e.kind === SyntaxKind.BindingElement && e.dotDotDotToken)) {
        elementTypes.push(!isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(
          e,
          /*includePatternInType*/
          false,
          /*reportErrors*/
          false
        ) : anyType);
        elementFlags.push(ElementFlags.Optional);
        if (!isOmittedExpression(e) && !hasDefaultValue(e)) {
          reportImplicitAny(e, anyType);
        }
      }
    }
    return createTupleType(elementTypes, elementFlags, type.target.readonly);
  }
  function widenTypeInferredFromInitializer(declaration, type) {
    const widened = getCombinedNodeFlagsCached(declaration) & NodeFlags.Constant || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
    if (isInJSFile(declaration)) {
      if (isEmptyLiteralType(widened)) {
        reportImplicitAny(declaration, anyType);
        return anyType;
      } else if (isEmptyArrayLiteralType(widened)) {
        reportImplicitAny(declaration, anyArrayType);
        return anyArrayType;
      }
    }
    return widened;
  }
  function isLiteralOfContextualType(candidateType, contextualType) {
    if (contextualType) {
      if (contextualType.flags & TypeFlags.UnionOrIntersection) {
        const types = contextualType.types;
        return some(types, (t) => isLiteralOfContextualType(candidateType, t));
      }
      if (contextualType.flags & TypeFlags.InstantiableNonPrimitive) {
        const constraint = getBaseConstraintOfType(contextualType) || unknownType;
        return maybeTypeOfKind(constraint, TypeFlags.String) && maybeTypeOfKind(candidateType, TypeFlags.StringLiteral) || maybeTypeOfKind(constraint, TypeFlags.Number) && maybeTypeOfKind(candidateType, TypeFlags.NumberLiteral) || maybeTypeOfKind(constraint, TypeFlags.BigInt) && maybeTypeOfKind(candidateType, TypeFlags.BigIntLiteral) || maybeTypeOfKind(constraint, TypeFlags.ESSymbol) && maybeTypeOfKind(candidateType, TypeFlags.UniqueESSymbol) || isLiteralOfContextualType(candidateType, constraint);
      }
      return !!(contextualType.flags & (TypeFlags.StringLiteral | TypeFlags.Index | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) && maybeTypeOfKind(candidateType, TypeFlags.StringLiteral) || contextualType.flags & TypeFlags.NumberLiteral && maybeTypeOfKind(candidateType, TypeFlags.NumberLiteral) || contextualType.flags & TypeFlags.BigIntLiteral && maybeTypeOfKind(candidateType, TypeFlags.BigIntLiteral) || contextualType.flags & TypeFlags.BooleanLiteral && maybeTypeOfKind(candidateType, TypeFlags.BooleanLiteral) || contextualType.flags & TypeFlags.UniqueESSymbol && maybeTypeOfKind(candidateType, TypeFlags.UniqueESSymbol));
    }
    return false;
  }
  function isConstContext(node) {
    const parent = node.parent;
    return isAssertionExpression(parent) && isConstTypeReference(parent.type) || isJSDocTypeAssertion(parent) && isConstTypeReference(getJSDocTypeAssertionType(parent)) || isValidConstAssertionArgument(node) && isConstTypeVariable(getContextualType(node, ContextFlags.None)) || (isParenthesizedExpression(parent) || isArrayLiteralExpression(parent) || isSpreadElement(parent)) && isConstContext(parent) || (isPropertyAssignment(parent) || isShorthandPropertyAssignment(parent) || isTemplateSpan(parent)) && isConstContext(parent.parent);
  }
  function checkExpressionForMutableLocation(node, checkMode, forceTuple) {
    const type = checkExpression(node, checkMode, forceTuple);
    return isConstContext(node) || isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(
      getContextualType(
        node,
        /*contextFlags*/
        void 0
      ),
      node,
      /*contextFlags*/
      void 0
    ));
  }
  function checkPropertyAssignment(node, checkMode) {
    if (node.name.kind === SyntaxKind.ComputedPropertyName) {
      checkComputedPropertyName(node.name);
    }
    return checkExpressionForMutableLocation(node.initializer, checkMode);
  }
  function checkObjectLiteralMethod(node, checkMode) {
    checkGrammarMethod(node);
    if (node.name.kind === SyntaxKind.ComputedPropertyName) {
      checkComputedPropertyName(node.name);
    }
    const uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
    return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
  }
  function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
    if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
      const callSignature = getSingleSignature(
        type,
        SignatureKind.Call,
        /*allowMembers*/
        true
      );
      const constructSignature = getSingleSignature(
        type,
        SignatureKind.Construct,
        /*allowMembers*/
        true
      );
      const signature = callSignature || constructSignature;
      if (signature && signature.typeParameters) {
        const contextualType = getApparentTypeOfContextualType(node, ContextFlags.NoConstraints);
        if (contextualType) {
          const contextualSignature = getSingleSignature(
            getNonNullableType(contextualType),
            callSignature ? SignatureKind.Call : SignatureKind.Construct,
            /*allowMembers*/
            false
          );
          if (contextualSignature && !contextualSignature.typeParameters) {
            if (checkMode & 8 /* SkipGenericFunctions */) {
              skippedGenericFunction(node, checkMode);
              return anyFunctionType;
            }
            const context = getInferenceContext(node);
            const returnType = context.signature && getReturnTypeOfSignature(context.signature);
            const returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
            if (returnSignature && !returnSignature.typeParameters && !every(context.inferences, hasInferenceCandidates)) {
              const uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
              const instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
              const inferences = map(context.inferences, (info) => createInferenceInfo(info.typeParameter));
              applyToParameterTypes(instantiatedSignature, contextualSignature, (source, target) => {
                inferTypes(
                  inferences,
                  source,
                  target,
                  /*priority*/
                  0,
                  /*contravariant*/
                  true
                );
              });
              if (some(inferences, hasInferenceCandidates)) {
                applyToReturnTypes(instantiatedSignature, contextualSignature, (source, target) => {
                  inferTypes(inferences, source, target);
                });
                if (!hasOverlappingInferences(context.inferences, inferences)) {
                  mergeInferences(context.inferences, inferences);
                  context.inferredTypeParameters = concatenate(context.inferredTypeParameters, uniqueTypeParameters);
                  return getOrCreateTypeFromSignature(instantiatedSignature);
                }
              }
            }
            return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context), flatMap(inferenceContexts, (c) => c && map(c.inferences, (i) => i.typeParameter)).slice());
          }
        }
      }
    }
    return type;
  }
  function skippedGenericFunction(node, checkMode) {
    if (checkMode & 2 /* Inferential */) {
      const context = getInferenceContext(node);
      context.flags |= InferenceFlags.SkippedGenericFunction;
    }
  }
  function hasInferenceCandidates(info) {
    return !!(info.candidates || info.contraCandidates);
  }
  function hasInferenceCandidatesOrDefault(info) {
    return !!(info.candidates || info.contraCandidates || hasTypeParameterDefault(info.typeParameter));
  }
  function hasOverlappingInferences(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
        return true;
      }
    }
    return false;
  }
  function mergeInferences(target, source) {
    for (let i = 0; i < target.length; i++) {
      if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
        target[i] = source[i];
      }
    }
  }
  function getUniqueTypeParameters(context, typeParameters) {
    const result = [];
    let oldTypeParameters;
    let newTypeParameters;
    for (const tp of typeParameters) {
      const name = tp.symbol.escapedName;
      if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
        const newName = getUniqueTypeParameterName(concatenate(context.inferredTypeParameters, result), name);
        const symbol = createSymbol(SymbolFlags.TypeParameter, newName);
        const newTypeParameter = createTypeParameter(symbol);
        newTypeParameter.target = tp;
        oldTypeParameters = append(oldTypeParameters, tp);
        newTypeParameters = append(newTypeParameters, newTypeParameter);
        result.push(newTypeParameter);
      } else {
        result.push(tp);
      }
    }
    if (newTypeParameters) {
      const mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
      for (const tp of newTypeParameters) {
        tp.mapper = mapper;
      }
    }
    return result;
  }
  function hasTypeParameterByName(typeParameters, name) {
    return some(typeParameters, (tp) => tp.symbol.escapedName === name);
  }
  function getUniqueTypeParameterName(typeParameters, baseName) {
    let len = baseName.length;
    while (len > 1 && baseName.charCodeAt(len - 1) >= CharacterCodes._0 && baseName.charCodeAt(len - 1) <= CharacterCodes._9) len--;
    const s = baseName.slice(0, len);
    for (let index = 1; true; index++) {
      const augmentedName = s + index;
      if (!hasTypeParameterByName(typeParameters, augmentedName)) {
        return augmentedName;
      }
    }
  }
  function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
    const signature = getSingleCallSignature(funcType);
    if (signature && !signature.typeParameters) {
      return getReturnTypeOfSignature(signature);
    }
  }
  function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
    const funcType = checkExpression(expr.expression);
    const nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
    const returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
    return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
  }
  function getTypeOfExpression(node) {
    const quickType = getQuickTypeOfExpression(node);
    if (quickType) {
      return quickType;
    }
    if (node.flags & NodeFlags.TypeCached && flowTypeCache) {
      const cachedType = flowTypeCache[getNodeId(node)];
      if (cachedType) {
        return cachedType;
      }
    }
    const startInvocationCount = flowInvocationCount;
    const type = checkExpression(node, 64 /* TypeOnly */);
    if (flowInvocationCount !== startInvocationCount) {
      const cache = flowTypeCache || (flowTypeCache = []);
      cache[getNodeId(node)] = type;
      setNodeFlags(node, node.flags | NodeFlags.TypeCached);
    }
    return type;
  }
  function getQuickTypeOfExpression(node) {
    let expr = skipParentheses(
      node,
      /*excludeJSDocTypeAssertions*/
      true
    );
    if (isJSDocTypeAssertion(expr)) {
      const type = getJSDocTypeAssertionType(expr);
      if (!isConstTypeReference(type)) {
        return getTypeFromTypeNode(type);
      }
    }
    expr = skipParentheses(node);
    if (isAwaitExpression(expr)) {
      const type = getQuickTypeOfExpression(expr.expression);
      return type ? getAwaitedType(type) : void 0;
    }
    if (isCallExpression(expr) && expr.expression.kind !== SyntaxKind.SuperKeyword && !isRequireCall(
      expr,
      /*requireStringLiteralLikeArgument*/
      true
    ) && !isSymbolOrSymbolForCall(expr)) {
      return isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
    } else if (isAssertionExpression(expr) && !isConstTypeReference(expr.type)) {
      return getTypeFromTypeNode(expr.type);
    } else if (isLiteralExpression(node) || isBooleanLiteral(node)) {
      return checkExpression(node);
    }
    return void 0;
  }
  function getContextFreeTypeOfExpression(node) {
    const links = getNodeLinks(node);
    if (links.contextFreeType) {
      return links.contextFreeType;
    }
    pushContextualType(
      node,
      anyType,
      /*isCache*/
      false
    );
    const type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
    popContextualType();
    return type;
  }
  function checkExpression(node, checkMode, forceTuple) {
    tracing?.push(tracing.Phase.Check, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath });
    const saveCurrentNode = currentNode;
    currentNode = node;
    instantiationCount = 0;
    const uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
    const type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
    if (isConstEnumObjectType(type)) {
      checkConstEnumAccess(node, type);
    }
    currentNode = saveCurrentNode;
    tracing?.pop();
    return type;
  }
  function checkConstEnumAccess(node, type) {
    const ok = node.parent.kind === SyntaxKind.PropertyAccessExpression && node.parent.expression === node || node.parent.kind === SyntaxKind.ElementAccessExpression && node.parent.expression === node || ((node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName) && isInRightSideOfImportOrExportAssignment(node) || node.parent.kind === SyntaxKind.TypeQuery && node.parent.exprName === node) || node.parent.kind === SyntaxKind.ExportSpecifier;
    if (!ok) {
      error(node, Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query);
    }
    if (compilerOptions.isolatedModules || compilerOptions.verbatimModuleSyntax && ok && !resolveName(
      node,
      getFirstIdentifier(node),
      SymbolFlags.Alias,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false,
      /*excludeGlobals*/
      true
    )) {
      Debug.assert(!!(type.symbol.flags & SymbolFlags.ConstEnum));
      const constEnumDeclaration = type.symbol.valueDeclaration;
      const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(getSourceFileOfNode(constEnumDeclaration).resolvedPath);
      if (constEnumDeclaration.flags & NodeFlags.Ambient && !isValidTypeOnlyAliasUseSite(node) && (!redirect || !shouldPreserveConstEnums(redirect.commandLine.options))) {
        error(node, Diagnostics.Cannot_access_ambient_const_enums_when_0_is_enabled, isolatedModulesLikeFlagName);
      }
    }
  }
  function checkParenthesizedExpression(node, checkMode) {
    if (hasJSDocNodes(node)) {
      if (isJSDocSatisfiesExpression(node)) {
        return checkSatisfiesExpressionWorker(node.expression, getJSDocSatisfiesExpressionType(node), checkMode);
      }
      if (isJSDocTypeAssertion(node)) {
        return checkAssertionWorker(node, checkMode);
      }
    }
    return checkExpression(node.expression, checkMode);
  }
  function checkExpressionWorker(node, checkMode, forceTuple) {
    const kind = node.kind;
    if (cancellationToken) {
      switch (kind) {
        case SyntaxKind.ClassExpression:
        case SyntaxKind.FunctionExpression:
        case SyntaxKind.ArrowFunction:
          cancellationToken.throwIfCancellationRequested();
      }
    }
    switch (kind) {
      case SyntaxKind.Identifier:
        return checkIdentifier(node, checkMode);
      case SyntaxKind.PrivateIdentifier:
        return checkPrivateIdentifierExpression(node);
      case SyntaxKind.ThisKeyword:
        return checkThisExpression(node);
      case SyntaxKind.SuperKeyword:
        return checkSuperExpression(node);
      case SyntaxKind.NullKeyword:
        return nullWideningType;
      case SyntaxKind.NoSubstitutionTemplateLiteral:
      case SyntaxKind.StringLiteral:
        return hasSkipDirectInferenceFlag(node) ? blockedStringType : getFreshTypeOfLiteralType(getStringLiteralType(node.text));
      case SyntaxKind.NumericLiteral:
        checkGrammarNumericLiteral(node);
        return getFreshTypeOfLiteralType(getNumberLiteralType(+node.text));
      case SyntaxKind.BigIntLiteral:
        checkGrammarBigIntLiteral(node);
        return getFreshTypeOfLiteralType(getBigIntLiteralType({
          negative: false,
          base10Value: parsePseudoBigInt(node.text)
        }));
      case SyntaxKind.TrueKeyword:
        return trueType;
      case SyntaxKind.FalseKeyword:
        return falseType;
      case SyntaxKind.TemplateExpression:
        return checkTemplateExpression(node);
      case SyntaxKind.RegularExpressionLiteral:
        return checkRegularExpressionLiteral(node);
      case SyntaxKind.ArrayLiteralExpression:
        return checkArrayLiteral(node, checkMode, forceTuple);
      case SyntaxKind.ObjectLiteralExpression:
        return checkObjectLiteral(node, checkMode);
      case SyntaxKind.PropertyAccessExpression:
        return checkPropertyAccessExpression(node, checkMode);
      case SyntaxKind.QualifiedName:
        return checkQualifiedName(node, checkMode);
      case SyntaxKind.ElementAccessExpression:
        return checkIndexedAccess(node, checkMode);
      case SyntaxKind.CallExpression:
        if (node.expression.kind === SyntaxKind.ImportKeyword) {
          return checkImportCallExpression(node);
        }
      // falls through
      case SyntaxKind.NewExpression:
        return checkCallExpression(node, checkMode);
      case SyntaxKind.TaggedTemplateExpression:
        return checkTaggedTemplateExpression(node);
      case SyntaxKind.ParenthesizedExpression:
        return checkParenthesizedExpression(node, checkMode);
      case SyntaxKind.ClassExpression:
        return checkClassExpression(node);
      case SyntaxKind.FunctionExpression:
      case SyntaxKind.ArrowFunction:
        return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
      case SyntaxKind.TypeOfExpression:
        return checkTypeOfExpression(node);
      case SyntaxKind.TypeAssertionExpression:
      case SyntaxKind.AsExpression:
        return checkAssertion(node, checkMode);
      case SyntaxKind.NonNullExpression:
        return checkNonNullAssertion(node);
      case SyntaxKind.ExpressionWithTypeArguments:
        return checkExpressionWithTypeArguments(node);
      case SyntaxKind.SatisfiesExpression:
        return checkSatisfiesExpression(node);
      case SyntaxKind.MetaProperty:
        return checkMetaProperty(node);
      case SyntaxKind.DeleteExpression:
        return checkDeleteExpression(node);
      case SyntaxKind.VoidExpression:
        return checkVoidExpression(node);
      case SyntaxKind.AwaitExpression:
        return checkAwaitExpression(node);
      case SyntaxKind.PrefixUnaryExpression:
        return checkPrefixUnaryExpression(node);
      case SyntaxKind.PostfixUnaryExpression:
        return checkPostfixUnaryExpression(node);
      case SyntaxKind.BinaryExpression:
        return checkBinaryExpression(node, checkMode);
      case SyntaxKind.ConditionalExpression:
        return checkConditionalExpression(node, checkMode);
      case SyntaxKind.SpreadElement:
        return checkSpreadExpression(node, checkMode);
      case SyntaxKind.OmittedExpression:
        return undefinedWideningType;
      case SyntaxKind.YieldExpression:
        return checkYieldExpression(node);
      case SyntaxKind.SyntheticExpression:
        return checkSyntheticExpression(node);
      case SyntaxKind.JsxExpression:
        return checkJsxExpression(node, checkMode);
      case SyntaxKind.JsxElement:
        return checkJsxElement(node, checkMode);
      case SyntaxKind.JsxSelfClosingElement:
        return checkJsxSelfClosingElement(node, checkMode);
      case SyntaxKind.JsxFragment:
        return checkJsxFragment(node);
      case SyntaxKind.JsxAttributes:
        return checkJsxAttributes(node, checkMode);
      case SyntaxKind.JsxOpeningElement:
        Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
    }
    return errorType;
  }
  function checkTypeParameter(node) {
    checkGrammarModifiers(node);
    if (node.expression) {
      grammarErrorOnFirstToken(node.expression, Diagnostics.Type_expected);
    }
    checkSourceElement(node.constraint);
    checkSourceElement(node.default);
    const typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node));
    getBaseConstraintOfType(typeParameter);
    if (!hasNonCircularTypeParameterDefault(typeParameter)) {
      error(node.default, Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
    }
    const constraintType = getConstraintOfTypeParameter(typeParameter);
    const defaultType = getDefaultFromTypeParameter(typeParameter);
    if (constraintType && defaultType) {
      checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
    }
    checkNodeDeferred(node);
    addLazyDiagnostic(() => checkTypeNameIsReserved(node.name, Diagnostics.Type_parameter_name_cannot_be_0));
  }
  function checkTypeParameterDeferred(node) {
    if (isInterfaceDeclaration(node.parent) || isClassLike(node.parent) || isTypeAliasDeclaration(node.parent)) {
      const typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node));
      const modifiers = getTypeParameterModifiers(typeParameter) & (ModifierFlags.In | ModifierFlags.Out);
      if (modifiers) {
        const symbol = getSymbolOfDeclaration(node.parent);
        if (isTypeAliasDeclaration(node.parent) && !(getObjectFlags(getDeclaredTypeOfSymbol(symbol)) & (ObjectFlags.Reference | ObjectFlags.Anonymous | ObjectFlags.Mapped))) {
          error(node, Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types);
        } else if (modifiers === ModifierFlags.In || modifiers === ModifierFlags.Out) {
          tracing?.push(tracing.Phase.CheckTypes, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) });
          const source = createMarkerType(symbol, typeParameter, modifiers === ModifierFlags.Out ? markerSubTypeForCheck : markerSuperTypeForCheck);
          const target = createMarkerType(symbol, typeParameter, modifiers === ModifierFlags.Out ? markerSuperTypeForCheck : markerSubTypeForCheck);
          const saveVarianceTypeParameter = typeParameter;
          varianceTypeParameter = typeParameter;
          checkTypeAssignableTo(source, target, node, Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation);
          varianceTypeParameter = saveVarianceTypeParameter;
          tracing?.pop();
        }
      }
    }
  }
  function checkParameter(node) {
    checkGrammarModifiers(node);
    checkVariableLikeDeclaration(node);
    const func = getContainingFunction(node);
    if (hasSyntacticModifier(node, ModifierFlags.ParameterPropertyModifier)) {
      if (!(func.kind === SyntaxKind.Constructor && nodeIsPresent(func.body))) {
        error(node, Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
      }
      if (func.kind === SyntaxKind.Constructor && isIdentifier(node.name) && node.name.escapedText === "constructor") {
        error(node.name, Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
      }
    }
    if (!node.initializer && isOptionalDeclaration(node) && isBindingPattern(node.name) && func.body) {
      error(node, Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
    }
    if (node.name && isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
      if (func.parameters.indexOf(node) !== 0) {
        error(node, Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
      }
      if (func.kind === SyntaxKind.Constructor || func.kind === SyntaxKind.ConstructSignature || func.kind === SyntaxKind.ConstructorType) {
        error(node, Diagnostics.A_constructor_cannot_have_a_this_parameter);
      }
      if (func.kind === SyntaxKind.ArrowFunction) {
        error(node, Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
      }
      if (func.kind === SyntaxKind.GetAccessor || func.kind === SyntaxKind.SetAccessor) {
        error(node, Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
      }
    }
    if (node.dotDotDotToken && !isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
      error(node, Diagnostics.A_rest_parameter_must_be_of_an_array_type);
    }
  }
  function checkTypePredicate(node) {
    const parent = getTypePredicateParent(node);
    if (!parent) {
      error(node, Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
      return;
    }
    const signature = getSignatureFromDeclaration(parent);
    const typePredicate = getTypePredicateOfSignature(signature);
    if (!typePredicate) {
      return;
    }
    checkSourceElement(node.type);
    const { parameterName } = node;
    if (typePredicate.kind !== TypePredicateKind.This && typePredicate.kind !== TypePredicateKind.AssertsThis) {
      if (typePredicate.parameterIndex >= 0) {
        if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
          error(parameterName, Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
        } else {
          if (typePredicate.type) {
            const leadingError = () => chainDiagnosticMessages(
              /*details*/
              void 0,
              Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type
            );
            checkTypeAssignableTo(
              typePredicate.type,
              getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]),
              node.type,
              /*headMessage*/
              void 0,
              leadingError
            );
          }
        }
      } else if (parameterName) {
        let hasReportedError = false;
        for (const { name } of parent.parameters) {
          if (isBindingPattern(name) && checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
            hasReportedError = true;
            break;
          }
        }
        if (!hasReportedError) {
          error(node.parameterName, Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
        }
      }
    }
  }
  function getTypePredicateParent(node) {
    switch (node.parent.kind) {
      case SyntaxKind.ArrowFunction:
      case SyntaxKind.CallSignature:
      case SyntaxKind.FunctionDeclaration:
      case SyntaxKind.FunctionExpression:
      case SyntaxKind.FunctionType:
      case SyntaxKind.MethodDeclaration:
      case SyntaxKind.MethodSignature:
        const parent = node.parent;
        if (node === parent.type) {
          return parent;
        }
    }
  }
  function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
    for (const element of pattern.elements) {
      if (isOmittedExpression(element)) {
        continue;
      }
      const name = element.name;
      if (name.kind === SyntaxKind.Identifier && name.escapedText === predicateVariableName) {
        error(predicateVariableNode, Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
        return true;
      } else if (name.kind === SyntaxKind.ArrayBindingPattern || name.kind === SyntaxKind.ObjectBindingPattern) {
        if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(
          name,
          predicateVariableNode,
          predicateVariableName
        )) {
          return true;
        }
      }
    }
  }
  function checkSignatureDeclaration(node) {
    if (node.kind === SyntaxKind.IndexSignature) {
      checkGrammarIndexSignature(node);
    } else if (node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.ConstructorType || node.kind === SyntaxKind.CallSignature || node.kind === SyntaxKind.Constructor || node.kind === SyntaxKind.ConstructSignature) {
      checkGrammarFunctionLikeDeclaration(node);
    }
    const functionFlags = getFunctionFlags(node);
    if (!(functionFlags & FunctionFlags.Invalid)) {
      if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.AsyncGenerator && languageVersion < LanguageFeatureMinimumTarget.AsyncGenerators) {
        checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncGeneratorIncludes);
      }
      if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async && languageVersion < LanguageFeatureMinimumTarget.AsyncFunctions) {
        checkExternalEmitHelpers(node, ExternalEmitHelpers.Awaiter);
      }
      if ((functionFlags & FunctionFlags.AsyncGenerator) !== FunctionFlags.Normal && languageVersion < LanguageFeatureMinimumTarget.Generators) {
        checkExternalEmitHelpers(node, ExternalEmitHelpers.Generator);
      }
    }
    checkTypeParameters(getEffectiveTypeParameterDeclarations(node));
    checkUnmatchedJSDocParameters(node);
    forEach(node.parameters, checkParameter);
    if (node.type) {
      checkSourceElement(node.type);
    }
    addLazyDiagnostic(checkSignatureDeclarationDiagnostics);
    function checkSignatureDeclarationDiagnostics() {
      checkCollisionWithArgumentsInGeneratedCode(node);
      let returnTypeNode = getEffectiveReturnTypeNode(node);
      let returnTypeErrorLocation = returnTypeNode;
      if (isInJSFile(node)) {
        const typeTag = getJSDocTypeTag(node);
        if (typeTag && typeTag.typeExpression && isTypeReferenceNode(typeTag.typeExpression.type)) {
          const signature = getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
          if (signature && signature.declaration) {
            returnTypeNode = getEffectiveReturnTypeNode(signature.declaration);
            returnTypeErrorLocation = typeTag.typeExpression.type;
          }
        }
      }
      if (noImplicitAny && !returnTypeNode) {
        switch (node.kind) {
          case SyntaxKind.ConstructSignature:
            error(node, Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
            break;
          case SyntaxKind.CallSignature:
            error(node, Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
            break;
        }
      }
      if (returnTypeNode && returnTypeErrorLocation) {
        const functionFlags2 = getFunctionFlags(node);
        if ((functionFlags2 & (FunctionFlags.Invalid | FunctionFlags.Generator)) === FunctionFlags.Generator) {
          const returnType = getTypeFromTypeNode(returnTypeNode);
          if (returnType === voidType) {
            error(returnTypeErrorLocation, Diagnostics.A_generator_cannot_have_a_void_type_annotation);
          } else {
            checkGeneratorInstantiationAssignabilityToReturnType(returnType, functionFlags2, returnTypeErrorLocation);
          }
        } else if ((functionFlags2 & FunctionFlags.AsyncGenerator) === FunctionFlags.Async) {
          checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation);
        }
      }
      if (node.kind !== SyntaxKind.IndexSignature && node.kind !== SyntaxKind.JSDocFunctionType) {
        registerForUnusedIdentifiersCheck(node);
      }
    }
  }
  function checkGeneratorInstantiationAssignabilityToReturnType(returnType, functionFlags, errorNode) {
    const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags & FunctionFlags.Async) !== 0) || anyType;
    const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags & FunctionFlags.Async) !== 0) || generatorYieldType;
    const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags & FunctionFlags.Async) !== 0) || unknownType;
    const generatorInstantiation = createGeneratorType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags & FunctionFlags.Async));
    return checkTypeAssignableTo(generatorInstantiation, returnType, errorNode);
  }
  function checkClassForDuplicateDeclarations(node) {
    const instanceNames = /* @__PURE__ */ new Map();
    const staticNames = /* @__PURE__ */ new Map();
    const privateIdentifiers = /* @__PURE__ */ new Map();
    for (const member of node.members) {
      if (member.kind === SyntaxKind.Constructor) {
        for (const param of member.parameters) {
          if (isParameterPropertyDeclaration(param, member) && !isBindingPattern(param.name)) {
            addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
          }
        }
      } else {
        const isStaticMember = isStatic(member);
        const name = member.name;
        if (!name) {
          continue;
        }
        const isPrivate = isPrivateIdentifier(name);
        const privateStaticFlags = isPrivate && isStaticMember ? 16 /* PrivateStatic */ : 0;
        const names = isPrivate ? privateIdentifiers : isStaticMember ? staticNames : instanceNames;
        const memberName = name && getEffectivePropertyNameForPropertyNameNode(name);
        if (memberName) {
          switch (member.kind) {
            case SyntaxKind.GetAccessor:
              addName(names, name, memberName, 1 /* GetAccessor */ | privateStaticFlags);
              break;
            case SyntaxKind.SetAccessor:
              addName(names, name, memberName, 2 /* SetAccessor */ | privateStaticFlags);
              break;
            case SyntaxKind.PropertyDeclaration:
              addName(names, name, memberName, 3 /* GetOrSetAccessor */ | privateStaticFlags);
              break;
            case SyntaxKind.MethodDeclaration:
              addName(names, name, memberName, 8 /* Method */ | privateStaticFlags);
              break;
          }
        }
      }
    }
    function addName(names, location, name, meaning) {
      const prev = names.get(name);
      if (prev) {
        if ((prev & 16 /* PrivateStatic */) !== (meaning & 16 /* PrivateStatic */)) {
          error(location, Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, getTextOfNode(location));
        } else {
          const prevIsMethod = !!(prev & 8 /* Method */);
          const isMethod = !!(meaning & 8 /* Method */);
          if (prevIsMethod || isMethod) {
            if (prevIsMethod !== isMethod) {
              error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location));
            }
          } else if (prev & meaning & ~16 /* PrivateStatic */) {
            error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location));
          } else {
            names.set(name, prev | meaning);
          }
        }
      } else {
        names.set(name, meaning);
      }
    }
  }
  function checkClassForStaticPropertyNameConflicts(node) {
    for (const member of node.members) {
      const memberNameNode = member.name;
      const isStaticMember = isStatic(member);
      if (isStaticMember && memberNameNode) {
        const memberName = getEffectivePropertyNameForPropertyNameNode(memberNameNode);
        switch (memberName) {
          case "name":
          case "length":
          case "caller":
          case "arguments":
            if (useDefineForClassFields) {
              break;
            }
          // fall through
          case "prototype":
            const message = Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
            const className = getNameOfSymbolAsWritten(getSymbolOfDeclaration(node));
            error(memberNameNode, message, memberName, className);
            break;
        }
      }
    }
  }
  function checkObjectTypeForDuplicateDeclarations(node) {
    const names = /* @__PURE__ */ new Map();
    for (const member of node.members) {
      if (member.kind === SyntaxKind.PropertySignature) {
        let memberName;
        const name = member.name;
        switch (name.kind) {
          case SyntaxKind.StringLiteral:
          case SyntaxKind.NumericLiteral:
            memberName = name.text;
            break;
          case SyntaxKind.Identifier:
            memberName = idText(name);
            break;
          default:
            continue;
        }
        if (names.get(memberName)) {
          error(getNameOfDeclaration(member.symbol.valueDeclaration), Diagnostics.Duplicate_identifier_0, memberName);
          error(member.name, Diagnostics.Duplicate_identifier_0, memberName);
        } else {
          names.set(memberName, true);
        }
      }
    }
  }
  function checkTypeForDuplicateIndexSignatures(node) {
    if (node.kind === SyntaxKind.InterfaceDeclaration) {
      const nodeSymbol = getSymbolOfDeclaration(node);
      if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
        return;
      }
    }
    const indexSymbol = getIndexSymbol(getSymbolOfDeclaration(node));
    if (indexSymbol?.declarations) {
      const indexSignatureMap = /* @__PURE__ */ new Map();
      for (const declaration of indexSymbol.declarations) {
        if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
          forEachType(getTypeFromTypeNode(declaration.parameters[0].type), (type) => {
            const entry = indexSignatureMap.get(getTypeId(type));
            if (entry) {
              entry.declarations.push(declaration);
            } else {
              indexSignatureMap.set(getTypeId(type), { type, declarations: [declaration] });
            }
          });
        }
      }
      indexSignatureMap.forEach((entry) => {
        if (entry.declarations.length > 1) {
          for (const declaration of entry.declarations) {
            error(declaration, Diagnostics.Duplicate_index_signature_for_type_0, typeToString(entry.type));
          }
        }
      });
    }
  }
  function checkPropertyDeclaration(node) {
    if (!checkGrammarModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name);
    checkVariableLikeDeclaration(node);
    setNodeLinksForPrivateIdentifierScope(node);
    if (hasSyntacticModifier(node, ModifierFlags.Abstract) && node.kind === SyntaxKind.PropertyDeclaration && node.initializer) {
      error(node, Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, declarationNameToString(node.name));
    }
  }
  function checkPropertySignature(node) {
    if (isPrivateIdentifier(node.name)) {
      error(node, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
    }
    return checkPropertyDeclaration(node);
  }
  function checkMethodDeclaration(node) {
    if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name);
    if (isMethodDeclaration(node) && node.asteriskToken && isIdentifier(node.name) && idText(node.name) === "constructor") {
      error(node.name, Diagnostics.Class_constructor_may_not_be_a_generator);
    }
    checkFunctionOrMethodDeclaration(node);
    if (hasSyntacticModifier(node, ModifierFlags.Abstract) && node.kind === SyntaxKind.MethodDeclaration && node.body) {
      error(node, Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, declarationNameToString(node.name));
    }
    if (isPrivateIdentifier(node.name) && !getContainingClass(node)) {
      error(node, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
    }
    setNodeLinksForPrivateIdentifierScope(node);
  }
  function setNodeLinksForPrivateIdentifierScope(node) {
    if (isPrivateIdentifier(node.name)) {
      if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) {
        for (let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope)) {
          getNodeLinks(lexicalScope).flags |= NodeCheckFlags.ContainsClassWithPrivateIdentifiers;
        }
        if (isClassExpression(node.parent)) {
          const enclosingIterationStatement = getEnclosingIterationStatement(node.parent);
          if (enclosingIterationStatement) {
            getNodeLinks(node.name).flags |= NodeCheckFlags.BlockScopedBindingInLoop;
            getNodeLinks(enclosingIterationStatement).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding;
          }
        }
      }
    }
  }
  function checkClassStaticBlockDeclaration(node) {
    checkGrammarModifiers(node);
    forEachChild(node, checkSourceElement);
  }
  function checkConstructorDeclaration(node) {
    checkSignatureDeclaration(node);
    if (!checkGrammarConstructorTypeParameters(node)) checkGrammarConstructorTypeAnnotation(node);
    checkSourceElement(node.body);
    const symbol = getSymbolOfDeclaration(node);
    const firstDeclaration = getDeclarationOfKind(symbol, node.kind);
    if (node === firstDeclaration) {
      checkFunctionOrConstructorSymbol(symbol);
    }
    if (nodeIsMissing(node.body)) {
      return;
    }
    addLazyDiagnostic(checkConstructorDeclarationDiagnostics);
    return;
    function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
      if (isPrivateIdentifierClassElementDeclaration(n)) {
        return true;
      }
      return n.kind === SyntaxKind.PropertyDeclaration && !isStatic(n) && !!n.initializer;
    }
    function checkConstructorDeclarationDiagnostics() {
      const containingClassDecl = node.parent;
      if (getClassExtendsHeritageElement(containingClassDecl)) {
        captureLexicalThis(node.parent, containingClassDecl);
        const classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
        const superCall = findFirstSuperCall(node.body);
        if (superCall) {
          if (classExtendsNull) {
            error(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
          }
          const superCallShouldBeRootLevel = !emitStandardClassFields && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, ModifierFlags.ParameterPropertyModifier)));
          if (superCallShouldBeRootLevel) {
            if (!superCallIsRootLevelInConstructor(superCall, node.body)) {
              error(superCall, Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers);
            } else {
              let superCallStatement;
              for (const statement of node.body.statements) {
                if (isExpressionStatement(statement) && isSuperCall(skipOuterExpressions(statement.expression))) {
                  superCallStatement = statement;
                  break;
                }
                if (nodeImmediatelyReferencesSuperOrThis(statement)) {
                  break;
                }
              }
              if (superCallStatement === void 0) {
                error(node, Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_class_contains_initialized_properties_parameter_properties_or_private_identifiers);
              }
            }
          }
        } else if (!classExtendsNull) {
          error(node, Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
        }
      }
    }
  }
  function superCallIsRootLevelInConstructor(superCall, body) {
    const superCallParent = walkUpParenthesizedExpressions(superCall.parent);
    return isExpressionStatement(superCallParent) && superCallParent.parent === body;
  }
  function nodeImmediatelyReferencesSuperOrThis(node) {
    if (node.kind === SyntaxKind.SuperKeyword || node.kind === SyntaxKind.ThisKeyword) {
      return true;
    }
    if (isThisContainerOrFunctionBlock(node)) {
      return false;
    }
    return !!forEachChild(node, nodeImmediatelyReferencesSuperOrThis);
  }
  function checkAccessorDeclaration(node) {
    if (isIdentifier(node.name) && idText(node.name) === "constructor" && isClassLike(node.parent)) {
      error(node.name, Diagnostics.Class_constructor_may_not_be_an_accessor);
    }
    addLazyDiagnostic(checkAccessorDeclarationDiagnostics);
    checkSourceElement(node.body);
    setNodeLinksForPrivateIdentifierScope(node);
    function checkAccessorDeclarationDiagnostics() {
      if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) checkGrammarComputedPropertyName(node.name);
      checkDecorators(node);
      checkSignatureDeclaration(node);
      if (node.kind === SyntaxKind.GetAccessor) {
        if (!(node.flags & NodeFlags.Ambient) && nodeIsPresent(node.body) && node.flags & NodeFlags.HasImplicitReturn) {
          if (!(node.flags & NodeFlags.HasExplicitReturn)) {
            error(node.name, Diagnostics.A_get_accessor_must_return_a_value);
          }
        }
      }
      if (node.name.kind === SyntaxKind.ComputedPropertyName) {
        checkComputedPropertyName(node.name);
      }
      if (hasBindableName(node)) {
        const symbol = getSymbolOfDeclaration(node);
        const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor);
        const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor);
        if (getter && setter && !(getNodeCheckFlags(getter) & NodeCheckFlags.TypeChecked)) {
          getNodeLinks(getter).flags |= NodeCheckFlags.TypeChecked;
          const getterFlags = getEffectiveModifierFlags(getter);
          const setterFlags = getEffectiveModifierFlags(setter);
          if ((getterFlags & ModifierFlags.Abstract) !== (setterFlags & ModifierFlags.Abstract)) {
            error(getter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
            error(setter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
          }
          if (getterFlags & ModifierFlags.Protected && !(setterFlags & (ModifierFlags.Protected | ModifierFlags.Private)) || getterFlags & ModifierFlags.Private && !(setterFlags & ModifierFlags.Private)) {
            error(getter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter);
            error(setter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter);
          }
        }
      }
      const returnType = getTypeOfAccessors(getSymbolOfDeclaration(node));
      if (node.kind === SyntaxKind.GetAccessor) {
        checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
      }
    }
  }
  function checkMissingDeclaration(node) {
    checkDecorators(node);
  }
  function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) {
    if (node.typeArguments && index < node.typeArguments.length) {
      return getTypeFromTypeNode(node.typeArguments[index]);
    }
    return getEffectiveTypeArguments(node, typeParameters)[index];
  }
  function getEffectiveTypeArguments(node, typeParameters) {
    return fillMissingTypeArguments(map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(node));
  }
  function checkTypeArgumentConstraints(node, typeParameters) {
    let typeArguments;
    let mapper;
    let result = true;
    for (let i = 0; i < typeParameters.length; i++) {
      const constraint = getConstraintOfTypeParameter(typeParameters[i]);
      if (constraint) {
        if (!typeArguments) {
          typeArguments = getEffectiveTypeArguments(node, typeParameters);
          mapper = createTypeMapper(typeParameters, typeArguments);
        }
        result = result && checkTypeAssignableTo(
          typeArguments[i],
          instantiateType(constraint, mapper),
          node.typeArguments[i],
          Diagnostics.Type_0_does_not_satisfy_the_constraint_1
        );
      }
    }
    return result;
  }
  function getTypeParametersForTypeAndSymbol(type, symbol) {
    if (!isErrorType(type)) {
      return symbol.flags & SymbolFlags.TypeAlias && getSymbolLinks(symbol).typeParameters || (getObjectFlags(type) & ObjectFlags.Reference ? type.target.localTypeParameters : void 0);
    }
    return void 0;
  }
  function getTypeParametersForTypeReferenceOrImport(node) {
    const type = getTypeFromTypeNode(node);
    if (!isErrorType(type)) {
      const symbol = getNodeLinks(node).resolvedSymbol;
      if (symbol) {
        return getTypeParametersForTypeAndSymbol(type, symbol);
      }
    }
    return void 0;
  }
  function checkTypeReferenceNode(node) {
    checkGrammarTypeArguments(node, node.typeArguments);
    if (node.kind === SyntaxKind.TypeReference && !isInJSFile(node) && !isInJSDoc(node) && node.typeArguments && node.typeName.end !== node.typeArguments.pos) {
      const sourceFile = getSourceFileOfNode(node);
      if (scanTokenAtPosition(sourceFile, node.typeName.end) === SyntaxKind.DotToken) {
        grammarErrorAtPos(node, skipTrivia(sourceFile.text, node.typeName.end), 1, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
      }
    }
    forEach(node.typeArguments, checkSourceElement);
    checkTypeReferenceOrImport(node);
  }
  function checkTypeReferenceOrImport(node) {
    const type = getTypeFromTypeNode(node);
    if (!isErrorType(type)) {
      if (node.typeArguments) {
        addLazyDiagnostic(() => {
          const typeParameters = getTypeParametersForTypeReferenceOrImport(node);
          if (typeParameters) {
            checkTypeArgumentConstraints(node, typeParameters);
          }
        });
      }
      const symbol = getNodeLinks(node).resolvedSymbol;
      if (symbol) {
        if (some(symbol.declarations, (d) => isTypeDeclaration(d) && !!(d.flags & NodeFlags.Deprecated))) {
          addDeprecatedSuggestion(
            getDeprecatedSuggestionNode(node),
            symbol.declarations,
            symbol.escapedName
          );
        }
      }
    }
  }
  function getTypeArgumentConstraint(node) {
    const typeReferenceNode = tryCast(node.parent, isTypeReferenceType);
    if (!typeReferenceNode) return void 0;
    const typeParameters = getTypeParametersForTypeReferenceOrImport(typeReferenceNode);
    if (!typeParameters) return void 0;
    const constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
    return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
  }
  function checkTypeQuery(node) {
    getTypeFromTypeQueryNode(node);
  }
  function checkTypeLiteral(node) {
    forEach(node.members, checkSourceElement);
    addLazyDiagnostic(checkTypeLiteralDiagnostics);
    function checkTypeLiteralDiagnostics() {
      const type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
      checkIndexConstraints(type, type.symbol);
      checkTypeForDuplicateIndexSignatures(node);
      checkObjectTypeForDuplicateDeclarations(node);
    }
  }
  function checkArrayType(node) {
    checkSourceElement(node.elementType);
  }
  function checkTupleType(node) {
    let seenOptionalElement = false;
    let seenRestElement = false;
    for (const e of node.elements) {
      let flags = getTupleElementFlags(e);
      if (flags & ElementFlags.Variadic) {
        const type = getTypeFromTypeNode(e.type);
        if (!isArrayLikeType(type)) {
          error(e, Diagnostics.A_rest_element_type_must_be_an_array_type);
          break;
        }
        if (isArrayType(type) || isTupleType(type) && type.target.combinedFlags & ElementFlags.Rest) {
          flags |= ElementFlags.Rest;
        }
      }
      if (flags & ElementFlags.Rest) {
        if (seenRestElement) {
          grammarErrorOnNode(e, Diagnostics.A_rest_element_cannot_follow_another_rest_element);
          break;
        }
        seenRestElement = true;
      } else if (flags & ElementFlags.Optional) {
        if (seenRestElement) {
          grammarErrorOnNode(e, Diagnostics.An_optional_element_cannot_follow_a_rest_element);
          break;
        }
        seenOptionalElement = true;
      } else if (flags & ElementFlags.Required && seenOptionalElement) {
        grammarErrorOnNode(e, Diagnostics.A_required_element_cannot_follow_an_optional_element);
        break;
      }
    }
    forEach(node.elements, checkSourceElement);
    getTypeFromTypeNode(node);
  }
  function checkUnionOrIntersectionType(node) {
    forEach(node.types, checkSourceElement);
    getTypeFromTypeNode(node);
  }
  function checkIndexedAccessIndexType(type, accessNode) {
    if (!(type.flags & TypeFlags.IndexedAccess)) {
      return type;
    }
    const objectType = type.objectType;
    const indexType = type.indexType;
    const objectIndexType = isGenericMappedType(objectType) && getMappedTypeNameTypeKind(objectType) === 2 /* Remapping */ ? getIndexTypeForMappedType(objectType, IndexFlags.None) : getIndexType(objectType, IndexFlags.None);
    const hasNumberIndexInfo = !!getIndexInfoOfType(objectType, numberType);
    if (everyType(indexType, (t) => isTypeAssignableTo(t, objectIndexType) || hasNumberIndexInfo && isApplicableIndexType(t, numberType))) {
      if (accessNode.kind === SyntaxKind.ElementAccessExpression && isAssignmentTarget(accessNode) && getObjectFlags(objectType) & ObjectFlags.Mapped && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
        error(accessNode, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
      }
      return type;
    }
    if (isGenericObjectType(objectType)) {
      const propertyName = getPropertyNameFromIndex(indexType, accessNode);
      if (propertyName) {
        const propertySymbol = forEachType(getApparentType(objectType), (t) => getPropertyOfType(t, propertyName));
        if (propertySymbol && getDeclarationModifierFlagsFromSymbol(propertySymbol) & ModifierFlags.NonPublicAccessibilityModifier) {
          error(accessNode, Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, unescapeLeadingUnderscores(propertyName));
          return errorType;
        }
      }
    }
    error(accessNode, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
    return errorType;
  }
  function checkIndexedAccessType(node) {
    checkSourceElement(node.objectType);
    checkSourceElement(node.indexType);
    checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
  }
  function checkMappedType(node) {
    checkGrammarMappedType(node);
    checkSourceElement(node.typeParameter);
    checkSourceElement(node.nameType);
    checkSourceElement(node.type);
    if (!node.type) {
      reportImplicitAny(node, anyType);
    }
    const type = getTypeFromMappedTypeNode(node);
    const nameType = getNameTypeFromMappedType(type);
    if (nameType) {
      checkTypeAssignableTo(nameType, stringNumberSymbolType, node.nameType);
    } else {
      const constraintType = getConstraintTypeFromMappedType(type);
      checkTypeAssignableTo(constraintType, stringNumberSymbolType, getEffectiveConstraintOfTypeParameter(node.typeParameter));
    }
  }
  function checkGrammarMappedType(node) {
    if (node.members?.length) {
      return grammarErrorOnNode(node.members[0], Diagnostics.A_mapped_type_may_not_declare_properties_or_methods);
    }
  }
  function checkThisType(node) {
    getTypeFromThisTypeNode(node);
  }
  function checkTypeOperator(node) {
    checkGrammarTypeOperatorNode(node);
    checkSourceElement(node.type);
  }
  function checkConditionalType(node) {
    forEachChild(node, checkSourceElement);
  }
  function checkInferType(node) {
    if (!findAncestor(node, (n) => n.parent && n.parent.kind === SyntaxKind.ConditionalType && n.parent.extendsType === n)) {
      grammarErrorOnNode(node, Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
    }
    checkSourceElement(node.typeParameter);
    const symbol = getSymbolOfDeclaration(node.typeParameter);
    if (symbol.declarations && symbol.declarations.length > 1) {
      const links = getSymbolLinks(symbol);
      if (!links.typeParametersChecked) {
        links.typeParametersChecked = true;
        const typeParameter = getDeclaredTypeOfTypeParameter(symbol);
        const declarations = getDeclarationsOfKind(symbol, SyntaxKind.TypeParameter);
        if (!areTypeParametersIdentical(declarations, [typeParameter], (decl) => [decl])) {
          const name = symbolToString(symbol);
          for (const declaration of declarations) {
            error(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_constraints, name);
          }
        }
      }
    }
    registerForUnusedIdentifiersCheck(node);
  }
  function checkTemplateLiteralType(node) {
    for (const span of node.templateSpans) {
      checkSourceElement(span.type);
      const type = getTypeFromTypeNode(span.type);
      checkTypeAssignableTo(type, templateConstraintType, span.type);
    }
    getTypeFromTypeNode(node);
  }
  function checkImportType(node) {
    checkSourceElement(node.argument);
    if (node.attributes) {
      getResolutionModeOverride(node.attributes, grammarErrorOnNode);
    }
    checkTypeReferenceOrImport(node);
  }
  function checkNamedTupleMember(node) {
    if (node.dotDotDotToken && node.questionToken) {
      grammarErrorOnNode(node, Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest);
    }
    if (node.type.kind === SyntaxKind.OptionalType) {
      grammarErrorOnNode(node.type, Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type);
    }
    if (node.type.kind === SyntaxKind.RestType) {
      grammarErrorOnNode(node.type, Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type);
    }
    checkSourceElement(node.type);
    getTypeFromTypeNode(node);
  }
  function isPrivateWithinAmbient(node) {
    return (hasEffectiveModifier(node, ModifierFlags.Private) || isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & NodeFlags.Ambient);
  }
  function getEffectiveDeclarationFlags(n, flagsToCheck) {
    let flags = getCombinedModifierFlagsCached(n);
    if (n.parent.kind !== SyntaxKind.InterfaceDeclaration && n.parent.kind !== SyntaxKind.ClassDeclaration && n.parent.kind !== SyntaxKind.ClassExpression && n.flags & NodeFlags.Ambient) {
      const container = getEnclosingContainer(n);
      if (container && container.flags & NodeFlags.ExportContext && !(flags & ModifierFlags.Ambient) && !(isModuleBlock(n.parent) && isModuleDeclaration(n.parent.parent) && isGlobalScopeAugmentation(n.parent.parent))) {
        flags |= ModifierFlags.Export;
      }
      flags |= ModifierFlags.Ambient;
    }
    return flags & flagsToCheck;
  }
  function checkFunctionOrConstructorSymbol(symbol) {
    addLazyDiagnostic(() => checkFunctionOrConstructorSymbolWorker(symbol));
  }
  function checkFunctionOrConstructorSymbolWorker(symbol) {
    function getCanonicalOverload(overloads, implementation) {
      const implementationSharesContainerWithFirstOverload = implementation !== void 0 && implementation.parent === overloads[0].parent;
      return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
    }
    function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck2, someOverloadFlags, allOverloadFlags) {
      const someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
      if (someButNotAllOverloadFlags !== 0) {
        const canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck2);
        group(overloads, (o) => getSourceFileOfNode(o).fileName).forEach((overloadsInFile) => {
          const canonicalFlagsForFile = getEffectiveDeclarationFlags(getCanonicalOverload(overloadsInFile, implementation), flagsToCheck2);
          for (const o of overloadsInFile) {
            const deviation = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlags;
            const deviationInFile = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlagsForFile;
            if (deviationInFile & ModifierFlags.Export) {
              error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
            } else if (deviationInFile & ModifierFlags.Ambient) {
              error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
            } else if (deviation & (ModifierFlags.Private | ModifierFlags.Protected)) {
              error(getNameOfDeclaration(o) || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
            } else if (deviation & ModifierFlags.Abstract) {
              error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
            }
          }
        });
      }
    }
    function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken2, allHaveQuestionToken2) {
      if (someHaveQuestionToken2 !== allHaveQuestionToken2) {
        const canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation));
        forEach(overloads, (o) => {
          const deviation = hasQuestionToken(o) !== canonicalHasQuestionToken;
          if (deviation) {
            error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_optional_or_required);
          }
        });
      }
    }
    const flagsToCheck = ModifierFlags.Export | ModifierFlags.Ambient | ModifierFlags.Private | ModifierFlags.Protected | ModifierFlags.Abstract;
    let someNodeFlags = ModifierFlags.None;
    let allNodeFlags = flagsToCheck;
    let someHaveQuestionToken = false;
    let allHaveQuestionToken = true;
    let hasOverloads = false;
    let bodyDeclaration;
    let lastSeenNonAmbientDeclaration;
    let previousDeclaration;
    const declarations = symbol.declarations;
    const isConstructor = (symbol.flags & SymbolFlags.Constructor) !== 0;
    function reportImplementationExpectedError(node) {
      if (node.name && nodeIsMissing(node.name)) {
        return;
      }
      let seen = false;
      const subsequentNode = forEachChild(node.parent, (c) => {
        if (seen) {
          return c;
        } else {
          seen = c === node;
        }
      });
      if (subsequentNode && subsequentNode.pos === node.end) {
        if (subsequentNode.kind === node.kind) {
          const errorNode2 = subsequentNode.name || subsequentNode;
          const subsequentName = subsequentNode.name;
          if (node.name && subsequentName && // both are private identifiers
          (isPrivateIdentifier(node.name) && isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText || // Both are computed property names
          isComputedPropertyName(node.name) && isComputedPropertyName(subsequentName) && isTypeIdenticalTo(checkComputedPropertyName(node.name), checkComputedPropertyName(subsequentName)) || // Both are literal property names that are the same.
          isPropertyNameLiteral(node.name) && isPropertyNameLiteral(subsequentName) && getEscapedTextOfIdentifierOrLiteral(node.name) === getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
            const reportError = (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature) && isStatic(node) !== isStatic(subsequentNode);
            if (reportError) {
              const diagnostic = isStatic(node) ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static;
              error(errorNode2, diagnostic);
            }
            return;
          }
          if (nodeIsPresent(subsequentNode.body)) {
            error(errorNode2, Diagnostics.Function_implementation_name_must_be_0, declarationNameToString(node.name));
            return;
          }
        }
      }
      const errorNode = node.name || node;
      if (isConstructor) {
        error(errorNode, Diagnostics.Constructor_implementation_is_missing);
      } else {
        if (hasSyntacticModifier(node, ModifierFlags.Abstract)) {
          error(errorNode, Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
        } else {
          error(errorNode, Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
        }
      }
    }
    let duplicateFunctionDeclaration = false;
    let multipleConstructorImplementation = false;
    let hasNonAmbientClass = false;
    const functionDeclarations = [];
    if (declarations) {
      for (const current of declarations) {
        const node = current;
        const inAmbientContext = node.flags & NodeFlags.Ambient;
        const inAmbientContextOrInterface = node.parent && (node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral) || inAmbientContext;
        if (inAmbientContextOrInterface) {
          previousDeclaration = void 0;
        }
        if ((node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression) && !inAmbientContext) {
          hasNonAmbientClass = true;
        }
        if (node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature || node.kind === SyntaxKind.Constructor) {
          functionDeclarations.push(node);
          const currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
          someNodeFlags |= currentNodeFlags;
          allNodeFlags &= currentNodeFlags;
          someHaveQuestionToken = someHaveQuestionToken || hasQuestionToken(node);
          allHaveQuestionToken = allHaveQuestionToken && hasQuestionToken(node);
          const bodyIsPresent = nodeIsPresent(node.body);
          if (bodyIsPresent && bodyDeclaration) {
            if (isConstructor) {
              multipleConstructorImplementation = true;
            } else {
              duplicateFunctionDeclaration = true;
            }
          } else if (previousDeclaration?.parent === node.parent && previousDeclaration.end !== node.pos) {
            reportImplementationExpectedError(previousDeclaration);
          }
          if (bodyIsPresent) {
            if (!bodyDeclaration) {
              bodyDeclaration = node;
            }
          } else {
            hasOverloads = true;
          }
          previousDeclaration = node;
          if (!inAmbientContextOrInterface) {
            lastSeenNonAmbientDeclaration = node;
          }
        }
        if (isInJSFile(current) && isFunctionLike(current) && current.jsDoc) {
          hasOverloads = length(getJSDocOverloadTags(current)) > 0;
        }
      }
    }
    if (multipleConstructorImplementation) {
      forEach(functionDeclarations, (declaration) => {
        error(declaration, Diagnostics.Multiple_constructor_implementations_are_not_allowed);
      });
    }
    if (duplicateFunctionDeclaration) {
      forEach(functionDeclarations, (declaration) => {
        error(getNameOfDeclaration(declaration) || declaration, Diagnostics.Duplicate_function_implementation);
      });
    }
    if (hasNonAmbientClass && !isConstructor && symbol.flags & SymbolFlags.Function && declarations) {
      const relatedDiagnostics = filter(declarations, (d) => d.kind === SyntaxKind.ClassDeclaration).map((d) => createDiagnosticForNode(d, Diagnostics.Consider_adding_a_declare_modifier_to_this_class));
      forEach(declarations, (declaration) => {
        const diagnostic = declaration.kind === SyntaxKind.ClassDeclaration ? Diagnostics.Class_declaration_cannot_implement_overload_list_for_0 : declaration.kind === SyntaxKind.FunctionDeclaration ? Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient : void 0;
        if (diagnostic) {
          addRelatedInfo(
            error(getNameOfDeclaration(declaration) || declaration, diagnostic, symbolName(symbol)),
            ...relatedDiagnostics
          );
        }
      });
    }
    if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !hasSyntacticModifier(lastSeenNonAmbientDeclaration, ModifierFlags.Abstract) && !lastSeenNonAmbientDeclaration.questionToken) {
      reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
    }
    if (hasOverloads) {
      if (declarations) {
        checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
        checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
      }
      if (bodyDeclaration) {
        const signatures = getSignaturesOfSymbol(symbol);
        const bodySignature = getSignatureFromDeclaration(bodyDeclaration);
        for (const signature of signatures) {
          if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
            const errorNode = signature.declaration && isJSDocSignature(signature.declaration) ? signature.declaration.parent.tagName : signature.declaration;
            addRelatedInfo(
              error(errorNode, Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature),
              createDiagnosticForNode(bodyDeclaration, Diagnostics.The_implementation_signature_is_declared_here)
            );
            break;
          }
        }
      }
    }
  }
  function checkExportsOnMergedDeclarations(node) {
    addLazyDiagnostic(() => checkExportsOnMergedDeclarationsWorker(node));
  }
  function checkExportsOnMergedDeclarationsWorker(node) {
    let symbol = node.localSymbol;
    if (!symbol) {
      symbol = getSymbolOfDeclaration(node);
      if (!symbol.exportSymbol) {
        return;
      }
    }
    if (getDeclarationOfKind(symbol, node.kind) !== node) {
      return;
    }
    let exportedDeclarationSpaces = 0 /* None */;
    let nonExportedDeclarationSpaces = 0 /* None */;
    let defaultExportedDeclarationSpaces = 0 /* None */;
    for (const d of symbol.declarations) {
      const declarationSpaces = getDeclarationSpaces(d);
      const effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, ModifierFlags.Export | ModifierFlags.Default);
      if (effectiveDeclarationFlags & ModifierFlags.Export) {
        if (effectiveDeclarationFlags & ModifierFlags.Default) {
          defaultExportedDeclarationSpaces |= declarationSpaces;
        } else {
          exportedDeclarationSpaces |= declarationSpaces;
        }
      } else {
        nonExportedDeclarationSpaces |= declarationSpaces;
      }
    }
    const nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
    const commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
    const commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
    if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
      for (const d of symbol.declarations) {
        const declarationSpaces = getDeclarationSpaces(d);
        const name = getNameOfDeclaration(d);
        if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
          error(name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(name));
        } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
          error(name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(name));
        }
      }
    }
    function getDeclarationSpaces(decl) {
      let d = decl;
      switch (d.kind) {
        case SyntaxKind.InterfaceDeclaration:
        case SyntaxKind.TypeAliasDeclaration:
        // A jsdoc typedef and callback are, by definition, type aliases.
        // falls through
        case SyntaxKind.JSDocTypedefTag:
        case SyntaxKind.JSDocCallbackTag:
        case SyntaxKind.JSDocEnumTag:
          return 2 /* ExportType */;
        case SyntaxKind.ModuleDeclaration:
          return isAmbientModule(d) || getModuleInstanceState(d) !== ModuleInstanceState.NonInstantiated ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */;
        case SyntaxKind.ClassDeclaration:
        case SyntaxKind.EnumDeclaration:
        case SyntaxKind.EnumMember:
          return 2 /* ExportType */ | 1 /* ExportValue */;
        case SyntaxKind.SourceFile:
          return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
        case SyntaxKind.ExportAssignment:
        case SyntaxKind.BinaryExpression:
          const node2 = d;
          const expression = isExportAssignment(node2) ? node2.expression : node2.right;
          if (!isEntityNameExpression(expression)) {
            return 1 /* ExportValue */;
          }
          d = expression;
        // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
        // falls through
        case SyntaxKind.ImportEqualsDeclaration:
        case SyntaxKind.NamespaceImport:
        case SyntaxKind.ImportClause:
          let result = 0 /* None */;
          const target = resolveAlias(getSymbolOfDeclaration(d));
          forEach(target.declarations, (d2) => {
            result |= getDeclarationSpaces(d2);
          });
          return result;
        case SyntaxKind.VariableDeclaration:
        case SyntaxKind.BindingElement:
        case SyntaxKind.FunctionDeclaration:
        case SyntaxKind.ImportSpecifier:
        // https://github.com/Microsoft/TypeScript/pull/7591
        case SyntaxKind.Identifier:
          return 1 /* ExportValue */;
        case SyntaxKind.MethodSignature:
        case SyntaxKind.PropertySignature:
          return 2 /* ExportType */;
        default:
          return Debug.failBadSyntaxKind(d);
      }
    }
  }
  function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, ...args) {
    const promisedType = getPromisedTypeOfPromise(type, errorNode);
    return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, ...args);
  }
  function getPromisedTypeOfPromise(type, errorNode, thisTypeForErrorOut) {
    if (isTypeAny(type)) {
      return void 0;
    }
    const typeAsPromise = type;
    if (typeAsPromise.promisedTypeOfPromise) {
      return typeAsPromise.promisedTypeOfPromise;
    }
    if (isReferenceToType(type, getGlobalPromiseType(
      /*reportErrors*/
      false
    ))) {
      return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
    }
    if (allTypesAssignableToKind(getBaseConstraintOrType(type), TypeFlags.Primitive | TypeFlags.Never)) {
      return void 0;
    }
    const thenFunction = getTypeOfPropertyOfType(type, "then");
    if (isTypeAny(thenFunction)) {
      return void 0;
    }
    const thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, SignatureKind.Call) : emptyArray;
    if (thenSignatures.length === 0) {
      if (errorNode) {
        error(errorNode, Diagnostics.A_promise_must_have_a_then_method);
      }
      return void 0;
    }
    let thisTypeForError;
    let candidates;
    for (const thenSignature of thenSignatures) {
      const thisType = getThisTypeOfSignature(thenSignature);
      if (thisType && thisType !== voidType && !isTypeRelatedTo(type, thisType, subtypeRelation)) {
        thisTypeForError = thisType;
      } else {
        candidates = append(candidates, thenSignature);
      }
    }
    if (!candidates) {
      Debug.assertIsDefined(thisTypeForError);
      if (thisTypeForErrorOut) {
        thisTypeForErrorOut.value = thisTypeForError;
      }
      if (errorNode) {
        error(errorNode, Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError));
      }
      return void 0;
    }
    const onfulfilledParameterType = getTypeWithFacts(getUnionType(map(candidates, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
    if (isTypeAny(onfulfilledParameterType)) {
      return void 0;
    }
    const onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, SignatureKind.Call);
    if (onfulfilledParameterSignatures.length === 0) {
      if (errorNode) {
        error(errorNode, Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
      }
      return void 0;
    }
    return typeAsPromise.promisedTypeOfPromise = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), UnionReduction.Subtype);
  }
  function checkAwaitedType(type, withAlias, errorNode, diagnosticMessage, ...args) {
    const awaitedType = withAlias ? getAwaitedType(type, errorNode, diagnosticMessage, ...args) : getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args);
    return awaitedType || errorType;
  }
  function isThenableType(type) {
    if (allTypesAssignableToKind(getBaseConstraintOrType(type), TypeFlags.Primitive | TypeFlags.Never)) {
      return false;
    }
    const thenFunction = getTypeOfPropertyOfType(type, "then");
    return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), SignatureKind.Call).length > 0;
  }
  function isAwaitedTypeInstantiation(type) {
    if (type.flags & TypeFlags.Conditional) {
      const awaitedSymbol = getGlobalAwaitedSymbol(
        /*reportErrors*/
        false
      );
      return !!awaitedSymbol && type.aliasSymbol === awaitedSymbol && type.aliasTypeArguments?.length === 1;
    }
    return false;
  }
  function unwrapAwaitedType(type) {
    return type.flags & TypeFlags.Union ? mapType(type, unwrapAwaitedType) : isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] : type;
  }
  function isAwaitedTypeNeeded(type) {
    if (isTypeAny(type) || isAwaitedTypeInstantiation(type)) {
      return false;
    }
    if (isGenericObjectType(type)) {
      const baseConstraint = getBaseConstraintOfType(type);
      if (baseConstraint ? baseConstraint.flags & TypeFlags.AnyOrUnknown || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : maybeTypeOfKind(type, TypeFlags.TypeVariable)) {
        return true;
      }
    }
    return false;
  }
  function tryCreateAwaitedType(type) {
    const awaitedSymbol = getGlobalAwaitedSymbol(
      /*reportErrors*/
      true
    );
    if (awaitedSymbol) {
      return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]);
    }
    return void 0;
  }
  function createAwaitedTypeIfNeeded(type) {
    if (isAwaitedTypeNeeded(type)) {
      return tryCreateAwaitedType(type) ?? type;
    }
    Debug.assert(isAwaitedTypeInstantiation(type) || getPromisedTypeOfPromise(type) === void 0, "type provided should not be a non-generic 'promise'-like.");
    return type;
  }
  function getAwaitedType(type, errorNode, diagnosticMessage, ...args) {
    const awaitedType = getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args);
    return awaitedType && createAwaitedTypeIfNeeded(awaitedType);
  }
  function getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args) {
    if (isTypeAny(type)) {
      return type;
    }
    if (isAwaitedTypeInstantiation(type)) {
      return type;
    }
    const typeAsAwaitable = type;
    if (typeAsAwaitable.awaitedTypeOfType) {
      return typeAsAwaitable.awaitedTypeOfType;
    }
    if (type.flags & TypeFlags.Union) {
      if (awaitedTypeStack.lastIndexOf(type.id) >= 0) {
        if (errorNode) {
          error(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
        }
        return void 0;
      }
      const mapper = errorNode ? (constituentType) => getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, ...args) : getAwaitedTypeNoAlias;
      awaitedTypeStack.push(type.id);
      const mapped = mapType(type, mapper);
      awaitedTypeStack.pop();
      return typeAsAwaitable.awaitedTypeOfType = mapped;
    }
    if (isAwaitedTypeNeeded(type)) {
      return typeAsAwaitable.awaitedTypeOfType = type;
    }
    const thisTypeForErrorOut = { value: void 0 };
    const promisedType = getPromisedTypeOfPromise(
      type,
      /*errorNode*/
      void 0,
      thisTypeForErrorOut
    );
    if (promisedType) {
      if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
        if (errorNode) {
          error(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
        }
        return void 0;
      }
      awaitedTypeStack.push(type.id);
      const awaitedType = getAwaitedTypeNoAlias(promisedType, errorNode, diagnosticMessage, ...args);
      awaitedTypeStack.pop();
      if (!awaitedType) {
        return void 0;
      }
      return typeAsAwaitable.awaitedTypeOfType = awaitedType;
    }
    if (isThenableType(type)) {
      if (errorNode) {
        Debug.assertIsDefined(diagnosticMessage);
        let chain;
        if (thisTypeForErrorOut.value) {
          chain = chainDiagnosticMessages(chain, Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForErrorOut.value));
        }
        chain = chainDiagnosticMessages(chain, diagnosticMessage, ...args);
        diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorNode), errorNode, chain));
      }
      return void 0;
    }
    return typeAsAwaitable.awaitedTypeOfType = type;
  }
  function checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation) {
    const returnType = getTypeFromTypeNode(returnTypeNode);
    if (languageVersion >= ScriptTarget.ES2015) {
      if (isErrorType(returnType)) {
        return;
      }
      const globalPromiseType = getGlobalPromiseType(
        /*reportErrors*/
        true
      );
      if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
        reportErrorForInvalidReturnType(Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, returnTypeNode, returnTypeErrorLocation, typeToString(getAwaitedTypeNoAlias(returnType) || voidType));
        return;
      }
    } else {
      markLinkedReferences(node, 5 /* AsyncFunction */);
      if (isErrorType(returnType)) {
        return;
      }
      const promiseConstructorName = getEntityNameFromTypeNode(returnTypeNode);
      if (promiseConstructorName === void 0) {
        reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, typeToString(returnType));
        return;
      }
      const promiseConstructorSymbol = resolveEntityName(
        promiseConstructorName,
        SymbolFlags.Value,
        /*ignoreErrors*/
        true
      );
      const promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
      if (isErrorType(promiseConstructorType)) {
        if (promiseConstructorName.kind === SyntaxKind.Identifier && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(
          /*reportErrors*/
          false
        )) {
          error(returnTypeErrorLocation, Diagnostics.An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option);
        } else {
          reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName));
        }
        return;
      }
      const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(
        /*reportErrors*/
        true
      );
      if (globalPromiseConstructorLikeType === emptyObjectType) {
        reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName));
        return;
      }
      const headMessage = Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value;
      const errorInfo = () => returnTypeNode === returnTypeErrorLocation ? void 0 : chainDiagnosticMessages(
        /*details*/
        void 0,
        Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type
      );
      if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeErrorLocation, headMessage, errorInfo)) {
        return;
      }
      const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName);
      const collidingSymbol = getSymbol(node.locals, rootName.escapedText, SymbolFlags.Value);
      if (collidingSymbol) {
        error(collidingSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, idText(rootName), entityNameToString(promiseConstructorName));
        return;
      }
    }
    checkAwaitedType(
      returnType,
      /*withAlias*/
      false,
      node,
      Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
    );
    function reportErrorForInvalidReturnType(message, returnTypeNode2, returnTypeErrorLocation2, typeName) {
      if (returnTypeNode2 === returnTypeErrorLocation2) {
        error(returnTypeErrorLocation2, message, typeName);
      } else {
        const diag = error(returnTypeErrorLocation2, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
        addRelatedInfo(diag, createDiagnosticForNode(returnTypeNode2, message, typeName));
      }
    }
  }
  function checkGrammarDecorator(decorator) {
    const sourceFile = getSourceFileOfNode(decorator);
    if (!hasParseDiagnostics(sourceFile)) {
      let node = decorator.expression;
      if (isParenthesizedExpression(node)) {
        return false;
      }
      let canHaveCallExpression = true;
      let errorNode;
      while (true) {
        if (isExpressionWithTypeArguments(node) || isNonNullExpression(node)) {
          node = node.expression;
          continue;
        }
        if (isCallExpression(node)) {
          if (!canHaveCallExpression) {
            errorNode = node;
          }
          if (node.questionDotToken) {
            errorNode = node.questionDotToken;
          }
          node = node.expression;
          canHaveCallExpression = false;
          continue;
        }
        if (isPropertyAccessExpression(node)) {
          if (node.questionDotToken) {
            errorNode = node.questionDotToken;
          }
          node = node.expression;
          canHaveCallExpression = false;
          continue;
        }
        if (!isIdentifier(node)) {
          errorNode = node;
        }
        break;
      }
      if (errorNode) {
        addRelatedInfo(
          error(decorator.expression, Diagnostics.Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator),
          createDiagnosticForNode(errorNode, Diagnostics.Invalid_syntax_in_decorator)
        );
        return true;
      }
    }
    return false;
  }
  function checkDecorator(node) {
    checkGrammarDecorator(node);
    const signature = getResolvedSignature(node);
    checkDeprecatedSignature(signature, node);
    const returnType = getReturnTypeOfSignature(signature);
    if (returnType.flags & TypeFlags.Any) {
      return;
    }
    const decoratorSignature = getDecoratorCallSignature(node);
    if (!decoratorSignature?.resolvedReturnType) return;
    let headMessage;
    const expectedReturnType = decoratorSignature.resolvedReturnType;
    switch (node.parent.kind) {
      case SyntaxKind.ClassDeclaration:
      case SyntaxKind.ClassExpression:
        headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1;
        break;
      case SyntaxKind.PropertyDeclaration:
        if (!legacyDecorators) {
          headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1;
          break;
        }
      // falls through
      case SyntaxKind.Parameter:
        headMessage = Diagnostics.Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any;
        break;
      case SyntaxKind.MethodDeclaration:
      case SyntaxKind.GetAccessor:
      case SyntaxKind.SetAccessor:
        headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1;
        break;
      default:
        return Debug.failBadSyntaxKind(node.parent);
    }
    checkTypeAssignableTo(returnType, expectedReturnType, node.expression, headMessage);
  }
  function createCallSignature(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount = parameters.length, flags = SignatureFlags.None) {
    const decl = factory.createFunctionTypeNode(
      /*typeParameters*/
      void 0,
      emptyArray,
      factory.createKeywordTypeNode(SyntaxKind.AnyKeyword)
    );
    return createSignature(decl, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags);
  }
  function createFunctionType(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags) {
    const signature = createCallSignature(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags);
    return getOrCreateTypeFromSignature(signature);
  }
  function createGetterFunctionType(type) {
    return createFunctionType(
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      emptyArray,
      type
    );
  }
  function createSetterFunctionType(type) {
    const valueParam = createParameter("value", type);
    return createFunctionType(
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      [valueParam],
      voidType
    );
  }
  function getEntityNameForDecoratorMetadata(node) {
    if (node) {
      switch (node.kind) {
        case SyntaxKind.IntersectionType:
        case SyntaxKind.UnionType:
          return getEntityNameForDecoratorMetadataFromTypeList(node.types);
        case SyntaxKind.ConditionalType:
          return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
        case SyntaxKind.ParenthesizedType:
        case SyntaxKind.NamedTupleMember:
          return getEntityNameForDecoratorMetadata(node.type);
        case SyntaxKind.TypeReference:
          return node.typeName;
      }
    }
  }
  function getEntityNameForDecoratorMetadataFromTypeList(types) {
    let commonEntityName;
    for (let typeNode of types) {
      while (typeNode.kind === SyntaxKind.ParenthesizedType || typeNode.kind === SyntaxKind.NamedTupleMember) {
        typeNode = typeNode.type;
      }
      if (typeNode.kind === SyntaxKind.NeverKeyword) {
        continue;
      }
      if (!strictNullChecks && (typeNode.kind === SyntaxKind.LiteralType && typeNode.literal.kind === SyntaxKind.NullKeyword || typeNode.kind === SyntaxKind.UndefinedKeyword)) {
        continue;
      }
      const individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
      if (!individualEntityName) {
        return void 0;
      }
      if (commonEntityName) {
        if (!isIdentifier(commonEntityName) || !isIdentifier(individualEntityName) || commonEntityName.escapedText !== individualEntityName.escapedText) {
          return void 0;
        }
      } else {
        commonEntityName = individualEntityName;
      }
    }
    return commonEntityName;
  }
  function getParameterTypeNodeForDecoratorCheck(node) {
    const typeNode = getEffectiveTypeAnnotationNode(node);
    return isRestParameter(node) ? getRestParameterElementType(typeNode) : typeNode;
  }
  function checkDecorators(node) {
    if (!canHaveDecorators(node) || !hasDecorators(node) || !node.modifiers || !nodeCanBeDecorated(legacyDecorators, node, node.parent, node.parent.parent)) {
      return;
    }
    const firstDecorator = find(node.modifiers, isDecorator);
    if (!firstDecorator) {
      return;
    }
    if (legacyDecorators) {
      checkExternalEmitHelpers(firstDecorator, ExternalEmitHelpers.Decorate);
      if (node.kind === SyntaxKind.Parameter) {
        checkExternalEmitHelpers(firstDecorator, ExternalEmitHelpers.Param);
      }
    } else if (languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators) {
      checkExternalEmitHelpers(firstDecorator, ExternalEmitHelpers.ESDecorateAndRunInitializers);
      if (isClassDeclaration(node)) {
        if (!node.name) {
          checkExternalEmitHelpers(firstDecorator, ExternalEmitHelpers.SetFunctionName);
        } else {
          const member = getFirstTransformableStaticClassElement(node);
          if (member) {
            checkExternalEmitHelpers(firstDecorator, ExternalEmitHelpers.SetFunctionName);
          }
        }
      } else if (!isClassExpression(node)) {
        if (isPrivateIdentifier(node.name) && (isMethodDeclaration(node) || isAccessor(node) || isAutoAccessorPropertyDeclaration(node))) {
          checkExternalEmitHelpers(firstDecorator, ExternalEmitHelpers.SetFunctionName);
        }
        if (isComputedPropertyName(node.name)) {
          checkExternalEmitHelpers(firstDecorator, ExternalEmitHelpers.PropKey);
        }
      }
    }
    markLinkedReferences(node, 8 /* Decorator */);
    for (const modifier of node.modifiers) {
      if (isDecorator(modifier)) {
        checkDecorator(modifier);
      }
    }
  }
  function checkFunctionDeclaration(node) {
    addLazyDiagnostic(checkFunctionDeclarationDiagnostics);
    function checkFunctionDeclarationDiagnostics() {
      checkFunctionOrMethodDeclaration(node);
      checkGrammarForGenerator(node);
      checkCollisionsForDeclarationName(node, node.name);
    }
  }
  function checkJSDocTypeAliasTag(node) {
    if (!node.typeExpression) {
      error(node.name, Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
    }
    if (node.name) {
      checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0);
    }
    checkSourceElement(node.typeExpression);
    checkTypeParameters(getEffectiveTypeParameterDeclarations(node));
  }
  function checkJSDocTemplateTag(node) {
    checkSourceElement(node.constraint);
    for (const tp of node.typeParameters) {
      checkSourceElement(tp);
    }
  }
  function checkJSDocTypeTag(node) {
    checkSourceElement(node.typeExpression);
  }
  function checkJSDocSatisfiesTag(node) {
    checkSourceElement(node.typeExpression);
    const host2 = getEffectiveJSDocHost(node);
    if (host2) {
      const tags = getAllJSDocTags(host2, isJSDocSatisfiesTag);
      if (length(tags) > 1) {
        for (let i = 1; i < length(tags); i++) {
          const tagName = tags[i].tagName;
          error(tagName, Diagnostics._0_tag_already_specified, idText(tagName));
        }
      }
    }
  }
  function checkJSDocLinkLikeTag(node) {
    if (node.name) {
      resolveJSDocMemberName(
        node.name,
        /*ignoreErrors*/
        true
      );
    }
  }
  function checkJSDocParameterTag(node) {
    checkSourceElement(node.typeExpression);
  }
  function checkJSDocPropertyTag(node) {
    checkSourceElement(node.typeExpression);
  }
  function checkJSDocFunctionType(node) {
    addLazyDiagnostic(checkJSDocFunctionTypeImplicitAny);
    checkSignatureDeclaration(node);
    function checkJSDocFunctionTypeImplicitAny() {
      if (!node.type && !isJSDocConstructSignature(node)) {
        reportImplicitAny(node, anyType);
      }
    }
  }
  function checkJSDocThisTag(node) {
    const host2 = getEffectiveJSDocHost(node);
    if (host2 && isArrowFunction(host2)) {
      error(node.tagName, Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
    }
  }
  function checkJSDocImportTag(node) {
    checkImportAttributes(node);
  }
  function checkJSDocImplementsTag(node) {
    const classLike = getEffectiveJSDocHost(node);
    if (!classLike || !isClassDeclaration(classLike) && !isClassExpression(classLike)) {
      error(classLike, Diagnostics.JSDoc_0_is_not_attached_to_a_class, idText(node.tagName));
    }
  }
  function checkJSDocAugmentsTag(node) {
    const classLike = getEffectiveJSDocHost(node);
    if (!classLike || !isClassDeclaration(classLike) && !isClassExpression(classLike)) {
      error(classLike, Diagnostics.JSDoc_0_is_not_attached_to_a_class, idText(node.tagName));
      return;
    }
    const augmentsTags = getJSDocTags(classLike).filter(isJSDocAugmentsTag);
    Debug.assert(augmentsTags.length > 0);
    if (augmentsTags.length > 1) {
      error(augmentsTags[1], Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
    }
    const name = getIdentifierFromEntityNameExpression(node.class.expression);
    const extend = getClassExtendsHeritageElement(classLike);
    if (extend) {
      const className = getIdentifierFromEntityNameExpression(extend.expression);
      if (className && name.escapedText !== className.escapedText) {
        error(name, Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, idText(node.tagName), idText(name), idText(className));
      }
    }
  }
  function checkJSDocAccessibilityModifiers(node) {
    const host2 = getJSDocHost(node);
    if (host2 && isPrivateIdentifierClassElementDeclaration(host2)) {
      error(node, Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
    }
  }
  function getIdentifierFromEntityNameExpression(node) {
    switch (node.kind) {
      case SyntaxKind.Identifier:
        return node;
      case SyntaxKind.PropertyAccessExpression:
        return node.name;
      default:
        return void 0;
    }
  }
  function checkFunctionOrMethodDeclaration(node) {
    checkDecorators(node);
    checkSignatureDeclaration(node);
    const functionFlags = getFunctionFlags(node);
    if (node.name && node.name.kind === SyntaxKind.ComputedPropertyName) {
      checkComputedPropertyName(node.name);
    }
    if (hasBindableName(node)) {
      const symbol = getSymbolOfDeclaration(node);
      const localSymbol = node.localSymbol || symbol;
      const firstDeclaration = localSymbol.declarations?.find(
        // Get first non javascript function declaration
        (declaration) => declaration.kind === node.kind && !(declaration.flags & NodeFlags.JavaScriptFile)
      );
      if (node === firstDeclaration) {
        checkFunctionOrConstructorSymbol(localSymbol);
      }
      if (symbol.parent) {
        checkFunctionOrConstructorSymbol(symbol);
      }
    }
    const body = node.kind === SyntaxKind.MethodSignature ? void 0 : node.body;
    checkSourceElement(body);
    checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
    addLazyDiagnostic(checkFunctionOrMethodDeclarationDiagnostics);
    if (isInJSFile(node)) {
      const typeTag = getJSDocTypeTag(node);
      if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
        error(typeTag.typeExpression.type, Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
      }
    }
    function checkFunctionOrMethodDeclarationDiagnostics() {
      if (!getEffectiveReturnTypeNode(node)) {
        if (nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
          reportImplicitAny(node, anyType);
        }
        if (functionFlags & FunctionFlags.Generator && nodeIsPresent(body)) {
          getReturnTypeOfSignature(getSignatureFromDeclaration(node));
        }
      }
    }
  }
  function registerForUnusedIdentifiersCheck(node) {
    addLazyDiagnostic(registerForUnusedIdentifiersCheckDiagnostics);
    function registerForUnusedIdentifiersCheckDiagnostics() {
      const sourceFile = getSourceFileOfNode(node);
      let potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
      if (!potentiallyUnusedIdentifiers) {
        potentiallyUnusedIdentifiers = [];
        allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
      }
      potentiallyUnusedIdentifiers.push(node);
    }
  }
  function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
    for (const node of potentiallyUnusedIdentifiers) {
      switch (node.kind) {
        case SyntaxKind.ClassDeclaration:
        case SyntaxKind.ClassExpression:
          checkUnusedClassMembers(node, addDiagnostic);
          checkUnusedTypeParameters(node, addDiagnostic);
          break;
        case SyntaxKind.SourceFile:
        case SyntaxKind.ModuleDeclaration:
        case SyntaxKind.Block:
        case SyntaxKind.CaseBlock:
        case SyntaxKind.ForStatement:
        case SyntaxKind.ForInStatement:
        case SyntaxKind.ForOfStatement:
          checkUnusedLocalsAndParameters(node, addDiagnostic);
          break;
        case SyntaxKind.Constructor:
        case SyntaxKind.FunctionExpression:
        case SyntaxKind.FunctionDeclaration:
        case SyntaxKind.ArrowFunction:
        case SyntaxKind.MethodDeclaration:
        case SyntaxKind.GetAccessor:
        case SyntaxKind.SetAccessor:
          if (node.body) {
            checkUnusedLocalsAndParameters(node, addDiagnostic);
          }
          checkUnusedTypeParameters(node, addDiagnostic);
          break;
        case SyntaxKind.MethodSignature:
        case SyntaxKind.CallSignature:
        case SyntaxKind.ConstructSignature:
        case SyntaxKind.FunctionType:
        case SyntaxKind.ConstructorType:
        case SyntaxKind.TypeAliasDeclaration:
        case SyntaxKind.InterfaceDeclaration:
          checkUnusedTypeParameters(node, addDiagnostic);
          break;
        case SyntaxKind.InferType:
          checkUnusedInferTypeParameter(node, addDiagnostic);
          break;
        default:
          Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
      }
    }
  }
  function errorUnusedLocal(declaration, name, addDiagnostic) {
    const node = getNameOfDeclaration(declaration) || declaration;
    const message = isTypeDeclaration(declaration) ? Diagnostics._0_is_declared_but_never_used : Diagnostics._0_is_declared_but_its_value_is_never_read;
    addDiagnostic(declaration, 0 /* Local */, createDiagnosticForNode(node, message, name));
  }
  function isIdentifierThatStartsWithUnderscore(node) {
    return isIdentifier(node) && idText(node).charCodeAt(0) === CharacterCodes._;
  }
  function checkUnusedClassMembers(node, addDiagnostic) {
    for (const member of node.members) {
      switch (member.kind) {
        case SyntaxKind.MethodDeclaration:
        case SyntaxKind.PropertyDeclaration:
        case SyntaxKind.GetAccessor:
        case SyntaxKind.SetAccessor:
          if (member.kind === SyntaxKind.SetAccessor && member.symbol.flags & SymbolFlags.GetAccessor) {
            break;
          }
          const symbol = getSymbolOfDeclaration(member);
          if (!symbol.isReferenced && (hasEffectiveModifier(member, ModifierFlags.Private) || isNamedDeclaration(member) && isPrivateIdentifier(member.name)) && !(member.flags & NodeFlags.Ambient)) {
            addDiagnostic(member, 0 /* Local */, createDiagnosticForNode(member.name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
          }
          break;
        case SyntaxKind.Constructor:
          for (const parameter of member.parameters) {
            if (!parameter.symbol.isReferenced && hasSyntacticModifier(parameter, ModifierFlags.Private)) {
              addDiagnostic(parameter, 0 /* Local */, createDiagnosticForNode(parameter.name, Diagnostics.Property_0_is_declared_but_its_value_is_never_read, symbolName(parameter.symbol)));
            }
          }
          break;
        case SyntaxKind.IndexSignature:
        case SyntaxKind.SemicolonClassElement:
        case SyntaxKind.ClassStaticBlockDeclaration:
          break;
        default:
          Debug.fail("Unexpected class member");
      }
    }
  }
  function checkUnusedInferTypeParameter(node, addDiagnostic) {
    const { typeParameter } = node;
    if (isTypeParameterUnused(typeParameter)) {
      addDiagnostic(node, 1 /* Parameter */, createDiagnosticForNode(node, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(typeParameter.name)));
    }
  }
  function checkUnusedTypeParameters(node, addDiagnostic) {
    const declarations = getSymbolOfDeclaration(node).declarations;
    if (!declarations || last(declarations) !== node) return;
    const typeParameters = getEffectiveTypeParameterDeclarations(node);
    const seenParentsWithEveryUnused = /* @__PURE__ */ new Set();
    for (const typeParameter of typeParameters) {
      if (!isTypeParameterUnused(typeParameter)) continue;
      const name = idText(typeParameter.name);
      const { parent } = typeParameter;
      if (parent.kind !== SyntaxKind.InferType && parent.typeParameters.every(isTypeParameterUnused)) {
        if (tryAddToSet(seenParentsWithEveryUnused, parent)) {
          const sourceFile = getSourceFileOfNode(parent);
          const range = isJSDocTemplateTag(parent) ? rangeOfNode(parent) : rangeOfTypeParameters(sourceFile, parent.typeParameters);
          const only = parent.typeParameters.length === 1;
          const messageAndArg = only ? [Diagnostics._0_is_declared_but_its_value_is_never_read, name] : [Diagnostics.All_type_parameters_are_unused];
          addDiagnostic(typeParameter, 1 /* Parameter */, createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ...messageAndArg));
        }
      } else {
        addDiagnostic(typeParameter, 1 /* Parameter */, createDiagnosticForNode(typeParameter, Diagnostics._0_is_declared_but_its_value_is_never_read, name));
      }
    }
  }
  function isTypeParameterUnused(typeParameter) {
    return !(getMergedSymbol(typeParameter.symbol).isReferenced & SymbolFlags.TypeParameter) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
  }
  function addToGroup(map2, key, value, getKey) {
    const keyString = String(getKey(key));
    const group2 = map2.get(keyString);
    if (group2) {
      group2[1].push(value);
    } else {
      map2.set(keyString, [key, [value]]);
    }
  }
  function tryGetRootParameterDeclaration(node) {
    return tryCast(getRootDeclaration(node), isParameter);
  }
  function isValidUnusedLocalDeclaration(declaration) {
    if (isBindingElement(declaration)) {
      if (isObjectBindingPattern(declaration.parent)) {
        return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name));
      }
      return isIdentifierThatStartsWithUnderscore(declaration.name);
    }
    return isAmbientModule(declaration) || (isVariableDeclaration(declaration) && isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
  }
  function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
    const unusedImports = /* @__PURE__ */ new Map();
    const unusedDestructures = /* @__PURE__ */ new Map();
    const unusedVariables = /* @__PURE__ */ new Map();
    nodeWithLocals.locals.forEach((local) => {
      if (local.flags & SymbolFlags.TypeParameter ? !(local.flags & SymbolFlags.Variable && !(local.isReferenced & SymbolFlags.Variable)) : local.isReferenced || local.exportSymbol) {
        return;
      }
      if (local.declarations) {
        for (const declaration of local.declarations) {
          if (isValidUnusedLocalDeclaration(declaration)) {
            continue;
          }
          if (isImportedDeclaration(declaration)) {
            addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
          } else if (isBindingElement(declaration) && isObjectBindingPattern(declaration.parent)) {
            const lastElement = last(declaration.parent.elements);
            if (declaration === lastElement || !last(declaration.parent.elements).dotDotDotToken) {
              addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
            }
          } else if (isVariableDeclaration(declaration)) {
            const blockScopeKind = getCombinedNodeFlagsCached(declaration) & NodeFlags.BlockScoped;
            const name = getNameOfDeclaration(declaration);
            if (blockScopeKind !== NodeFlags.Using && blockScopeKind !== NodeFlags.AwaitUsing || !name || !isIdentifierThatStartsWithUnderscore(name)) {
              addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
            }
          } else {
            const parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
            const name = local.valueDeclaration && getNameOfDeclaration(local.valueDeclaration);
            if (parameter && name) {
              if (!isParameterPropertyDeclaration(parameter, parameter.parent) && !parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
                if (isBindingElement(declaration) && isArrayBindingPattern(declaration.parent)) {
                  addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
                } else {
                  addDiagnostic(parameter, 1 /* Parameter */, createDiagnosticForNode(name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolName(local)));
                }
              }
            } else {
              errorUnusedLocal(declaration, symbolName(local), addDiagnostic);
            }
          }
        }
      }
    });
    unusedImports.forEach(([importClause, unuseds]) => {
      const importDecl = importClause.parent;
      const nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? importClause.namedBindings.kind === SyntaxKind.NamespaceImport ? 1 : importClause.namedBindings.elements.length : 0);
      if (nDeclarations === unuseds.length) {
        addDiagnostic(
          importDecl,
          0 /* Local */,
          unuseds.length === 1 ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name)) : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused)
        );
      } else {
        for (const unused of unuseds) errorUnusedLocal(unused, idText(unused.name), addDiagnostic);
      }
    });
    unusedDestructures.forEach(([bindingPattern, bindingElements]) => {
      const kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
      if (bindingPattern.elements.length === bindingElements.length) {
        if (bindingElements.length === 1 && bindingPattern.parent.kind === SyntaxKind.VariableDeclaration && bindingPattern.parent.parent.kind === SyntaxKind.VariableDeclarationList) {
          addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
        } else {
          addDiagnostic(
            bindingPattern,
            kind,
            bindingElements.length === 1 ? createDiagnosticForNode(bindingPattern, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(bindingElements).name)) : createDiagnosticForNode(bindingPattern, Diagnostics.All_destructured_elements_are_unused)
          );
        }
      } else {
        for (const e of bindingElements) {
          addDiagnostic(e, kind, createDiagnosticForNode(e, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
        }
      }
    });
    unusedVariables.forEach(([declarationList, declarations]) => {
      if (declarationList.declarations.length === declarations.length) {
        addDiagnostic(
          declarationList,
          0 /* Local */,
          declarations.length === 1 ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) : createDiagnosticForNode(declarationList.parent.kind === SyntaxKind.VariableStatement ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused)
        );
      } else {
        for (const decl of declarations) {
          addDiagnostic(decl, 0 /* Local */, createDiagnosticForNode(decl, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
        }
      }
    });
  }
  function checkPotentialUncheckedRenamedBindingElementsInTypes() {
    for (const node of potentialUnusedRenamedBindingElementsInTypes) {
      if (!getSymbolOfDeclaration(node)?.isReferenced) {
        const wrappingDeclaration = walkUpBindingElementsAndPatterns(node);
        Debug.assert(isPartOfParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here");
        const diagnostic = createDiagnosticForNode(node.name, Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, declarationNameToString(node.name), declarationNameToString(node.propertyName));
        if (!wrappingDeclaration.type) {
          addRelatedInfo(
            diagnostic,
            createFileDiagnostic(getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 0, Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, declarationNameToString(node.propertyName))
          );
        }
        diagnostics.add(diagnostic);
      }
    }
  }
  function bindingNameText(name) {
    switch (name.kind) {
      case SyntaxKind.Identifier:
        return idText(name);
      case SyntaxKind.ArrayBindingPattern:
      case SyntaxKind.ObjectBindingPattern:
        return bindingNameText(cast(first(name.elements), isBindingElement).name);
      default:
        return Debug.assertNever(name);
    }
  }
  function isImportedDeclaration(node) {
    return node.kind === SyntaxKind.ImportClause || node.kind === SyntaxKind.ImportSpecifier || node.kind === SyntaxKind.NamespaceImport;
  }
  function importClauseFromImported(decl) {
    return decl.kind === SyntaxKind.ImportClause ? decl : decl.kind === SyntaxKind.NamespaceImport ? decl.parent : decl.parent.parent;
  }
  function checkBlock(node) {
    if (node.kind === SyntaxKind.Block) {
      checkGrammarStatementInAmbientContext(node);
    }
    if (isFunctionOrModuleBlock(node)) {
      const saveFlowAnalysisDisabled = flowAnalysisDisabled;
      forEach(node.statements, checkSourceElement);
      flowAnalysisDisabled = saveFlowAnalysisDisabled;
    } else {
      forEach(node.statements, checkSourceElement);
    }
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkCollisionWithArgumentsInGeneratedCode(node) {
    if (languageVersion >= ScriptTarget.ES2015 || !hasRestParameter(node) || node.flags & NodeFlags.Ambient || nodeIsMissing(node.body)) {
      return;
    }
    forEach(node.parameters, (p) => {
      if (p.name && !isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
        errorSkippedOn("noEmit", p, Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
      }
    });
  }
  function needCollisionCheckForIdentifier(node, identifier, name) {
    if (identifier?.escapedText !== name) {
      return false;
    }
    if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature || node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor || node.kind === SyntaxKind.PropertyAssignment) {
      return false;
    }
    if (node.flags & NodeFlags.Ambient) {
      return false;
    }
    if (isImportClause(node) || isImportEqualsDeclaration(node) || isImportSpecifier(node)) {
      if (isTypeOnlyImportOrExportDeclaration(node)) {
        return false;
      }
    }
    const root = getRootDeclaration(node);
    if (isParameter(root) && nodeIsMissing(root.parent.body)) {
      return false;
    }
    return true;
  }
  function checkIfThisIsCapturedInEnclosingScope(node) {
    findAncestor(node, (current) => {
      if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureThis) {
        const isDeclaration2 = node.kind !== SyntaxKind.Identifier;
        if (isDeclaration2) {
          error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
        } else {
          error(node, Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
        }
        return true;
      }
      return false;
    });
  }
  function checkIfNewTargetIsCapturedInEnclosingScope(node) {
    findAncestor(node, (current) => {
      if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureNewTarget) {
        const isDeclaration2 = node.kind !== SyntaxKind.Identifier;
        if (isDeclaration2) {
          error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
        } else {
          error(node, Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
        }
        return true;
      }
      return false;
    });
  }
  function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
    if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) >= ModuleKind.ES2015) {
      return;
    }
    if (!name || !needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
      return;
    }
    if (isModuleDeclaration(node) && getModuleInstanceState(node) !== ModuleInstanceState.Instantiated) {
      return;
    }
    const parent = getDeclarationContainer(node);
    if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent)) {
      errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, declarationNameToString(name), declarationNameToString(name));
    }
  }
  function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
    if (!name || languageVersion >= ScriptTarget.ES2017 || !needCollisionCheckForIdentifier(node, name, "Promise")) {
      return;
    }
    if (isModuleDeclaration(node) && getModuleInstanceState(node) !== ModuleInstanceState.Instantiated) {
      return;
    }
    const parent = getDeclarationContainer(node);
    if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent) && parent.flags & NodeFlags.HasAsyncFunctions) {
      errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, declarationNameToString(name), declarationNameToString(name));
    }
  }
  function recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name) {
    if (languageVersion <= ScriptTarget.ES2021 && (needCollisionCheckForIdentifier(node, name, "WeakMap") || needCollisionCheckForIdentifier(node, name, "WeakSet"))) {
      potentialWeakMapSetCollisions.push(node);
    }
  }
  function checkWeakMapSetCollision(node) {
    const enclosingBlockScope = getEnclosingBlockScopeContainer(node);
    if (getNodeCheckFlags(enclosingBlockScope) & NodeCheckFlags.ContainsClassWithPrivateIdentifiers) {
      Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier");
      errorSkippedOn("noEmit", node, Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText);
    }
  }
  function recordPotentialCollisionWithReflectInGeneratedCode(node, name) {
    if (name && languageVersion >= ScriptTarget.ES2015 && languageVersion <= ScriptTarget.ES2021 && needCollisionCheckForIdentifier(node, name, "Reflect")) {
      potentialReflectCollisions.push(node);
    }
  }
  function checkReflectCollision(node) {
    let hasCollision = false;
    if (isClassExpression(node)) {
      for (const member of node.members) {
        if (getNodeCheckFlags(member) & NodeCheckFlags.ContainsSuperPropertyInStaticInitializer) {
          hasCollision = true;
          break;
        }
      }
    } else if (isFunctionExpression(node)) {
      if (getNodeCheckFlags(node) & NodeCheckFlags.ContainsSuperPropertyInStaticInitializer) {
        hasCollision = true;
      }
    } else {
      const container = getEnclosingBlockScopeContainer(node);
      if (container && getNodeCheckFlags(container) & NodeCheckFlags.ContainsSuperPropertyInStaticInitializer) {
        hasCollision = true;
      }
    }
    if (hasCollision) {
      Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name), "The target of a Reflect collision check should be an identifier");
      errorSkippedOn("noEmit", node, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers, declarationNameToString(node.name), "Reflect");
    }
  }
  function checkCollisionsForDeclarationName(node, name) {
    if (!name) return;
    checkCollisionWithRequireExportsInGeneratedCode(node, name);
    checkCollisionWithGlobalPromiseInGeneratedCode(node, name);
    recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name);
    recordPotentialCollisionWithReflectInGeneratedCode(node, name);
    if (isClassLike(node)) {
      checkTypeNameIsReserved(name, Diagnostics.Class_name_cannot_be_0);
      if (!(node.flags & NodeFlags.Ambient)) {
        checkClassNameCollisionWithObject(name);
      }
    } else if (isEnumDeclaration(node)) {
      checkTypeNameIsReserved(name, Diagnostics.Enum_name_cannot_be_0);
    }
  }
  function checkVarDeclaredNamesNotShadowed(node) {
    if ((getCombinedNodeFlagsCached(node) & NodeFlags.BlockScoped) !== 0 || isPartOfParameterDeclaration(node)) {
      return;
    }
    const symbol = getSymbolOfDeclaration(node);
    if (symbol.flags & SymbolFlags.FunctionScopedVariable) {
      if (!isIdentifier(node.name)) return Debug.fail();
      const localDeclarationSymbol = resolveName(
        node,
        node.name.escapedText,
        SymbolFlags.Variable,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      );
      if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & SymbolFlags.BlockScopedVariable) {
        if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & NodeFlags.BlockScoped) {
          const varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, SyntaxKind.VariableDeclarationList);
          const container = varDeclList.parent.kind === SyntaxKind.VariableStatement && varDeclList.parent.parent ? varDeclList.parent.parent : void 0;
          const namesShareScope = container && (container.kind === SyntaxKind.Block && isFunctionLike(container.parent) || container.kind === SyntaxKind.ModuleBlock || container.kind === SyntaxKind.ModuleDeclaration || container.kind === SyntaxKind.SourceFile);
          if (!namesShareScope) {
            const name = symbolToString(localDeclarationSymbol);
            error(node, Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
          }
        }
      }
    }
  }
  function convertAutoToAny(type) {
    return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
  }
  function checkVariableLikeDeclaration(node) {
    checkDecorators(node);
    if (!isBindingElement(node)) {
      checkSourceElement(node.type);
    }
    if (!node.name) {
      return;
    }
    if (node.name.kind === SyntaxKind.ComputedPropertyName) {
      checkComputedPropertyName(node.name);
      if (hasOnlyExpressionInitializer(node) && node.initializer) {
        checkExpressionCached(node.initializer);
      }
    }
    if (isBindingElement(node)) {
      if (node.propertyName && isIdentifier(node.name) && isPartOfParameterDeclaration(node) && nodeIsMissing(getContainingFunction(node).body)) {
        potentialUnusedRenamedBindingElementsInTypes.push(node);
        return;
      }
      if (isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest) {
        checkExternalEmitHelpers(node, ExternalEmitHelpers.Rest);
      }
      if (node.propertyName && node.propertyName.kind === SyntaxKind.ComputedPropertyName) {
        checkComputedPropertyName(node.propertyName);
      }
      const parent = node.parent.parent;
      const parentCheckMode = node.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */;
      const parentType = getTypeForBindingElementParent(parent, parentCheckMode);
      const name = node.propertyName || node.name;
      if (parentType && !isBindingPattern(name)) {
        const exprType = getLiteralTypeFromPropertyName(name);
        if (isTypeUsableAsPropertyName(exprType)) {
          const nameText = getPropertyNameFromType(exprType);
          const property = getPropertyOfType(parentType, nameText);
          if (property) {
            markPropertyAsReferenced(
              property,
              /*nodeForCheckWriteOnly*/
              void 0,
              /*isSelfTypeAccess*/
              false
            );
            checkPropertyAccessibility(
              node,
              !!parent.initializer && parent.initializer.kind === SyntaxKind.SuperKeyword,
              /*writing*/
              false,
              parentType,
              property
            );
          }
        }
      }
    }
    if (isBindingPattern(node.name)) {
      if (node.name.kind === SyntaxKind.ArrayBindingPattern && languageVersion < LanguageFeatureMinimumTarget.BindingPatterns && compilerOptions.downlevelIteration) {
        checkExternalEmitHelpers(node, ExternalEmitHelpers.Read);
      }
      forEach(node.name.elements, checkSourceElement);
    }
    if (node.initializer && isPartOfParameterDeclaration(node) && nodeIsMissing(getContainingFunction(node).body)) {
      error(node, Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
      return;
    }
    if (isBindingPattern(node.name)) {
      if (isInAmbientOrTypeNode(node)) {
        return;
      }
      const needCheckInitializer = hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== SyntaxKind.ForInStatement;
      const needCheckWidenedType = !some(node.name.elements, not(isOmittedExpression));
      if (needCheckInitializer || needCheckWidenedType) {
        const widenedType = getWidenedTypeForVariableLikeDeclaration(node);
        if (needCheckInitializer) {
          const initializerType = checkExpressionCached(node.initializer);
          if (strictNullChecks && needCheckWidenedType) {
            checkNonNullNonVoidType(initializerType, node);
          } else {
            checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
          }
        }
        if (needCheckWidenedType) {
          if (isArrayBindingPattern(node.name)) {
            checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
          } else if (strictNullChecks) {
            checkNonNullNonVoidType(widenedType, node);
          }
        }
      }
      return;
    }
    const symbol = getSymbolOfDeclaration(node);
    if (symbol.flags & SymbolFlags.Alias && (isVariableDeclarationInitializedToBareOrAccessedRequire(node) || isBindingElementOfBareOrAccessedRequire(node))) {
      checkAliasSymbol(node);
      return;
    }
    if (node.name.kind === SyntaxKind.BigIntLiteral) {
      error(node.name, Diagnostics.A_bigint_literal_cannot_be_used_as_a_property_name);
    }
    const type = convertAutoToAny(getTypeOfSymbol(symbol));
    if (node === symbol.valueDeclaration) {
      const initializer = hasOnlyExpressionInitializer(node) && getEffectiveInitializer(node);
      if (initializer) {
        const isJSObjectLiteralInitializer = isInJSFile(node) && isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && !!symbol.exports?.size;
        if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== SyntaxKind.ForInStatement) {
          const initializerType = checkExpressionCached(initializer);
          checkTypeAssignableToAndOptionallyElaborate(
            initializerType,
            type,
            node,
            initializer,
            /*headMessage*/
            void 0
          );
          const blockScopeKind = getCombinedNodeFlagsCached(node) & NodeFlags.BlockScoped;
          if (blockScopeKind === NodeFlags.AwaitUsing) {
            const globalAsyncDisposableType = getGlobalAsyncDisposableType(
              /*reportErrors*/
              true
            );
            const globalDisposableType = getGlobalDisposableType(
              /*reportErrors*/
              true
            );
            if (globalAsyncDisposableType !== emptyObjectType && globalDisposableType !== emptyObjectType) {
              const optionalDisposableType = getUnionType([globalAsyncDisposableType, globalDisposableType, nullType, undefinedType]);
              checkTypeAssignableTo(widenTypeForVariableLikeDeclaration(initializerType, node), optionalDisposableType, initializer, Diagnostics.The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined);
            }
          } else if (blockScopeKind === NodeFlags.Using) {
            const globalDisposableType = getGlobalDisposableType(
              /*reportErrors*/
              true
            );
            if (globalDisposableType !== emptyObjectType) {
              const optionalDisposableType = getUnionType([globalDisposableType, nullType, undefinedType]);
              checkTypeAssignableTo(widenTypeForVariableLikeDeclaration(initializerType, node), optionalDisposableType, initializer, Diagnostics.The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined);
            }
          }
        }
      }
      if (symbol.declarations && symbol.declarations.length > 1) {
        if (some(symbol.declarations, (d) => d !== node && isVariableLike(d) && !areDeclarationFlagsIdentical(d, node))) {
          error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name));
        }
      }
    } else {
      const declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
      if (!isErrorType(type) && !isErrorType(declarationType) && !isTypeIdenticalTo(type, declarationType) && !(symbol.flags & SymbolFlags.Assignment)) {
        errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
      }
      if (hasOnlyExpressionInitializer(node) && node.initializer) {
        checkTypeAssignableToAndOptionallyElaborate(
          checkExpressionCached(node.initializer),
          declarationType,
          node,
          node.initializer,
          /*headMessage*/
          void 0
        );
      }
      if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
        error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name));
      }
    }
    if (node.kind !== SyntaxKind.PropertyDeclaration && node.kind !== SyntaxKind.PropertySignature) {
      checkExportsOnMergedDeclarations(node);
      if (node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement) {
        checkVarDeclaredNamesNotShadowed(node);
      }
      checkCollisionsForDeclarationName(node, node.name);
    }
  }
  function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
    const nextDeclarationName = getNameOfDeclaration(nextDeclaration);
    const message = nextDeclaration.kind === SyntaxKind.PropertyDeclaration || nextDeclaration.kind === SyntaxKind.PropertySignature ? Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
    const declName = declarationNameToString(nextDeclarationName);
    const err = error(
      nextDeclarationName,
      message,
      declName,
      typeToString(firstType),
      typeToString(nextType)
    );
    if (firstDeclaration) {
      addRelatedInfo(err, createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName));
    }
  }
  function areDeclarationFlagsIdentical(left, right) {
    if (left.kind === SyntaxKind.Parameter && right.kind === SyntaxKind.VariableDeclaration || left.kind === SyntaxKind.VariableDeclaration && right.kind === SyntaxKind.Parameter) {
      return true;
    }
    if (hasQuestionToken(left) !== hasQuestionToken(right)) {
      return false;
    }
    const interestingFlags = ModifierFlags.Private | ModifierFlags.Protected | ModifierFlags.Async | ModifierFlags.Abstract | ModifierFlags.Readonly | ModifierFlags.Static;
    return getSelectedEffectiveModifierFlags(left, interestingFlags) === getSelectedEffectiveModifierFlags(right, interestingFlags);
  }
  function checkVariableDeclaration(node) {
    tracing?.push(tracing.Phase.Check, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath });
    checkGrammarVariableDeclaration(node);
    checkVariableLikeDeclaration(node);
    tracing?.pop();
  }
  function checkBindingElement(node) {
    checkGrammarBindingElement(node);
    return checkVariableLikeDeclaration(node);
  }
  function checkVariableDeclarationList(node) {
    const blockScopeKind = getCombinedNodeFlags(node) & NodeFlags.BlockScoped;
    if ((blockScopeKind === NodeFlags.Using || blockScopeKind === NodeFlags.AwaitUsing) && languageVersion < LanguageFeatureMinimumTarget.UsingAndAwaitUsing) {
      checkExternalEmitHelpers(node, ExternalEmitHelpers.AddDisposableResourceAndDisposeResources);
    }
    forEach(node.declarations, checkSourceElement);
  }
  function checkVariableStatement(node) {
    if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedBlockScopedVariableStatement(node);
    checkVariableDeclarationList(node.declarationList);
  }
  function checkExpressionStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkExpression(node.expression);
  }
  function checkIfStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    const type = checkTruthinessExpression(node.expression);
    checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.expression, type, node.thenStatement);
    checkSourceElement(node.thenStatement);
    if (node.thenStatement.kind === SyntaxKind.EmptyStatement) {
      error(node.thenStatement, Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
    }
    checkSourceElement(node.elseStatement);
  }
  function checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(condExpr, condType, body) {
    if (!strictNullChecks) return;
    bothHelper(condExpr, body);
    function bothHelper(condExpr2, body2) {
      condExpr2 = skipParentheses(condExpr2);
      helper(condExpr2, body2);
      while (isBinaryExpression(condExpr2) && (condExpr2.operatorToken.kind === SyntaxKind.BarBarToken || condExpr2.operatorToken.kind === SyntaxKind.QuestionQuestionToken)) {
        condExpr2 = skipParentheses(condExpr2.left);
        helper(condExpr2, body2);
      }
    }
    function helper(condExpr2, body2) {
      const location = isLogicalOrCoalescingBinaryExpression(condExpr2) ? skipParentheses(condExpr2.right) : condExpr2;
      if (isModuleExportsAccessExpression(location)) {
        return;
      }
      if (isLogicalOrCoalescingBinaryExpression(location)) {
        bothHelper(location, body2);
        return;
      }
      const type = location === condExpr2 ? condType : checkExpression(location);
      if (type.flags & TypeFlags.EnumLiteral && isPropertyAccessExpression(location) && (getNodeLinks(location.expression).resolvedSymbol ?? unknownSymbol).flags & SymbolFlags.Enum) {
        error(location, Diagnostics.This_condition_will_always_return_0, !!type.value ? "true" : "false");
        return;
      }
      const isPropertyExpressionCast = isPropertyAccessExpression(location) && isTypeAssertion(location.expression);
      if (!hasTypeFacts(type, 4194304 /* Truthy */) || isPropertyExpressionCast) return;
      const callSignatures = getSignaturesOfType(type, SignatureKind.Call);
      const isPromise = !!getAwaitedTypeOfPromise(type);
      if (callSignatures.length === 0 && !isPromise) {
        return;
      }
      const testedNode = isIdentifier(location) ? location : isPropertyAccessExpression(location) ? location.name : void 0;
      const testedSymbol = testedNode && getSymbolAtLocation(testedNode);
      if (!testedSymbol && !isPromise) {
        return;
      }
      const isUsed = testedSymbol && isBinaryExpression(condExpr2.parent) && isSymbolUsedInBinaryExpressionChain(condExpr2.parent, testedSymbol) || testedSymbol && body2 && isSymbolUsedInConditionBody(condExpr2, body2, testedNode, testedSymbol);
      if (!isUsed) {
        if (isPromise) {
          errorAndMaybeSuggestAwait(
            location,
            /*maybeMissingAwait*/
            true,
            Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined,
            getTypeNameForErrorDisplay(type)
          );
        } else {
          error(location, Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead);
        }
      }
    }
  }
  function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) {
    return !!forEachChild(body, function check(childNode) {
      if (isIdentifier(childNode)) {
        const childSymbol = getSymbolAtLocation(childNode);
        if (childSymbol && childSymbol === testedSymbol) {
          if (isIdentifier(expr) || isIdentifier(testedNode) && isBinaryExpression(testedNode.parent)) {
            return true;
          }
          let testedExpression = testedNode.parent;
          let childExpression = childNode.parent;
          while (testedExpression && childExpression) {
            if (isIdentifier(testedExpression) && isIdentifier(childExpression) || testedExpression.kind === SyntaxKind.ThisKeyword && childExpression.kind === SyntaxKind.ThisKeyword) {
              return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
            } else if (isPropertyAccessExpression(testedExpression) && isPropertyAccessExpression(childExpression)) {
              if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
                return false;
              }
              childExpression = childExpression.expression;
              testedExpression = testedExpression.expression;
            } else if (isCallExpression(testedExpression) && isCallExpression(childExpression)) {
              childExpression = childExpression.expression;
              testedExpression = testedExpression.expression;
            } else {
              return false;
            }
          }
        }
      }
      return forEachChild(childNode, check);
    });
  }
  function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) {
    while (isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) {
      const isUsed = forEachChild(node.right, function visit(child) {
        if (isIdentifier(child)) {
          const symbol = getSymbolAtLocation(child);
          if (symbol && symbol === testedSymbol) {
            return true;
          }
        }
        return forEachChild(child, visit);
      });
      if (isUsed) {
        return true;
      }
      node = node.parent;
    }
    return false;
  }
  function checkDoStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkSourceElement(node.statement);
    checkTruthinessExpression(node.expression);
  }
  function checkWhileStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkTruthinessExpression(node.expression);
    checkSourceElement(node.statement);
  }
  function checkTruthinessOfType(type, node) {
    if (type.flags & TypeFlags.Void) {
      error(node, Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
    } else {
      const semantics = getSyntacticTruthySemantics(node);
      if (semantics !== PredicateSemantics.Sometimes) {
        error(
          node,
          semantics === PredicateSemantics.Always ? Diagnostics.This_kind_of_expression_is_always_truthy : Diagnostics.This_kind_of_expression_is_always_falsy
        );
      }
    }
    return type;
  }
  function getSyntacticTruthySemantics(node) {
    node = skipOuterExpressions(node);
    switch (node.kind) {
      case SyntaxKind.NumericLiteral:
        if (node.text === "0" || node.text === "1") {
          return PredicateSemantics.Sometimes;
        }
        return PredicateSemantics.Always;
      case SyntaxKind.ArrayLiteralExpression:
      case SyntaxKind.ArrowFunction:
      case SyntaxKind.BigIntLiteral:
      case SyntaxKind.ClassExpression:
      case SyntaxKind.FunctionExpression:
      case SyntaxKind.JsxElement:
      case SyntaxKind.JsxSelfClosingElement:
      case SyntaxKind.ObjectLiteralExpression:
      case SyntaxKind.RegularExpressionLiteral:
        return PredicateSemantics.Always;
      case SyntaxKind.VoidExpression:
      case SyntaxKind.NullKeyword:
        return PredicateSemantics.Never;
      case SyntaxKind.NoSubstitutionTemplateLiteral:
      case SyntaxKind.StringLiteral:
        return !!node.text ? PredicateSemantics.Always : PredicateSemantics.Never;
      case SyntaxKind.ConditionalExpression:
        return getSyntacticTruthySemantics(node.whenTrue) | getSyntacticTruthySemantics(node.whenFalse);
      case SyntaxKind.Identifier:
        if (getResolvedSymbol(node) === undefinedSymbol) {
          return PredicateSemantics.Never;
        }
        return PredicateSemantics.Sometimes;
    }
    return PredicateSemantics.Sometimes;
  }
  function checkTruthinessExpression(node, checkMode) {
    return checkTruthinessOfType(checkExpression(node, checkMode), node);
  }
  function checkForStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      if (node.initializer && node.initializer.kind === SyntaxKind.VariableDeclarationList) {
        checkGrammarVariableDeclarationList(node.initializer);
      }
    }
    if (node.initializer) {
      if (node.initializer.kind === SyntaxKind.VariableDeclarationList) {
        checkVariableDeclarationList(node.initializer);
      } else {
        checkExpression(node.initializer);
      }
    }
    if (node.condition) checkTruthinessExpression(node.condition);
    if (node.incrementor) checkExpression(node.incrementor);
    checkSourceElement(node.statement);
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkForOfStatement(node) {
    checkGrammarForInOrForOfStatement(node);
    const container = getContainingFunctionOrClassStaticBlock(node);
    if (node.awaitModifier) {
      if (container && isClassStaticBlockDeclaration(container)) {
        grammarErrorOnNode(node.awaitModifier, Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block);
      } else {
        const functionFlags = getFunctionFlags(container);
        if ((functionFlags & (FunctionFlags.Invalid | FunctionFlags.Async)) === FunctionFlags.Async && languageVersion < LanguageFeatureMinimumTarget.ForAwaitOf) {
          checkExternalEmitHelpers(node, ExternalEmitHelpers.ForAwaitOfIncludes);
        }
      }
    } else if (compilerOptions.downlevelIteration && languageVersion < LanguageFeatureMinimumTarget.ForOf) {
      checkExternalEmitHelpers(node, ExternalEmitHelpers.ForOfIncludes);
    }
    if (node.initializer.kind === SyntaxKind.VariableDeclarationList) {
      checkVariableDeclarationList(node.initializer);
    } else {
      const varExpr = node.initializer;
      const iteratedType = checkRightHandSideOfForOf(node);
      if (varExpr.kind === SyntaxKind.ArrayLiteralExpression || varExpr.kind === SyntaxKind.ObjectLiteralExpression) {
        checkDestructuringAssignment(varExpr, iteratedType || errorType);
      } else {
        const leftType = checkExpression(varExpr);
        checkReferenceExpression(
          varExpr,
          Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access,
          Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access
        );
        if (iteratedType) {
          checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
        }
      }
    }
    checkSourceElement(node.statement);
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkForInStatement(node) {
    checkGrammarForInOrForOfStatement(node);
    const rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
    if (node.initializer.kind === SyntaxKind.VariableDeclarationList) {
      const variable = node.initializer.declarations[0];
      if (variable && isBindingPattern(variable.name)) {
        error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
      }
      checkVariableDeclarationList(node.initializer);
    } else {
      const varExpr = node.initializer;
      const leftType = checkExpression(varExpr);
      if (varExpr.kind === SyntaxKind.ArrayLiteralExpression || varExpr.kind === SyntaxKind.ObjectLiteralExpression) {
        error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
      } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
        error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
      } else {
        checkReferenceExpression(
          varExpr,
          Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access,
          Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access
        );
      }
    }
    if (rightType === neverType || !isTypeAssignableToKind(rightType, TypeFlags.NonPrimitive | TypeFlags.InstantiableNonPrimitive)) {
      error(node.expression, Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType));
    }
    checkSourceElement(node.statement);
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkRightHandSideOfForOf(statement) {
    const use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
    return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
  }
  function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
    if (isTypeAny(inputType)) {
      return inputType;
    }
    return getIteratedTypeOrElementType(
      use,
      inputType,
      sentType,
      errorNode,
      /*checkAssignability*/
      true
    ) || anyType;
  }
  function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
    const allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
    if (inputType === neverType) {
      if (errorNode) {
        reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables);
      }
      return void 0;
    }
    const uplevelIteration = languageVersion >= ScriptTarget.ES2015;
    const downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
    const possibleOutOfBounds = compilerOptions.noUncheckedIndexedAccess && !!(use & 128 /* PossiblyOutOfBounds */);
    if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
      const iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : void 0);
      if (checkAssignability) {
        if (iterationTypes) {
          const diagnostic = use & 8 /* ForOfFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0 : use & 32 /* SpreadFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0 : use & 64 /* DestructuringFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0 : use & 16 /* YieldStarFlag */ ? Diagnostics.Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0 : void 0;
          if (diagnostic) {
            checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
          }
        }
      }
      if (iterationTypes || uplevelIteration) {
        return possibleOutOfBounds ? includeUndefinedInIndexSignature(iterationTypes && iterationTypes.yieldType) : iterationTypes && iterationTypes.yieldType;
      }
    }
    let arrayType = inputType;
    let hasStringConstituent = false;
    if (use & 4 /* AllowsStringInputFlag */) {
      if (arrayType.flags & TypeFlags.Union) {
        const arrayTypes = inputType.types;
        const filteredTypes = filter(arrayTypes, (t) => !(t.flags & TypeFlags.StringLike));
        if (filteredTypes !== arrayTypes) {
          arrayType = getUnionType(filteredTypes, UnionReduction.Subtype);
        }
      } else if (arrayType.flags & TypeFlags.StringLike) {
        arrayType = neverType;
      }
      hasStringConstituent = arrayType !== inputType;
      if (hasStringConstituent) {
        if (arrayType.flags & TypeFlags.Never) {
          return possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType;
        }
      }
    }
    if (!isArrayLikeType(arrayType)) {
      if (errorNode) {
        const allowsStrings = !!(use & 4 /* AllowsStringInputFlag */) && !hasStringConstituent;
        const [defaultDiagnostic, maybeMissingAwait] = getIterationDiagnosticDetails(allowsStrings, downlevelIteration);
        errorAndMaybeSuggestAwait(
          errorNode,
          maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType),
          defaultDiagnostic,
          typeToString(arrayType)
        );
      }
      return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : void 0;
    }
    const arrayElementType = getIndexTypeOfType(arrayType, numberType);
    if (hasStringConstituent && arrayElementType) {
      if (arrayElementType.flags & TypeFlags.StringLike && !compilerOptions.noUncheckedIndexedAccess) {
        return stringType;
      }
      return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], UnionReduction.Subtype);
    }
    return use & 128 /* PossiblyOutOfBounds */ ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType;
    function getIterationDiagnosticDetails(allowsStrings, downlevelIteration2) {
      if (downlevelIteration2) {
        return allowsStrings ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] : [Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true];
      }
      const yieldType = getIterationTypeOfIterable(
        use,
        0 /* Yield */,
        inputType,
        /*errorNode*/
        void 0
      );
      if (yieldType) {
        return [Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, false];
      }
      if (isES2015OrLaterIterable(inputType.symbol?.escapedName)) {
        return [Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true];
      }
      return allowsStrings ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true] : [Diagnostics.Type_0_is_not_an_array_type, true];
    }
  }
  function isES2015OrLaterIterable(n) {
    switch (n) {
      case "Float32Array":
      case "Float64Array":
      case "Int16Array":
      case "Int32Array":
      case "Int8Array":
      case "NodeList":
      case "Uint16Array":
      case "Uint32Array":
      case "Uint8Array":
      case "Uint8ClampedArray":
        return true;
    }
    return false;
  }
  function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
    if (isTypeAny(inputType)) {
      return void 0;
    }
    const iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
    return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
  }
  function createIterationTypes(yieldType = neverType, returnType = neverType, nextType = unknownType) {
    if (yieldType.flags & TypeFlags.Intrinsic && returnType.flags & (TypeFlags.Any | TypeFlags.Never | TypeFlags.Unknown | TypeFlags.Void | TypeFlags.Undefined) && nextType.flags & (TypeFlags.Any | TypeFlags.Never | TypeFlags.Unknown | TypeFlags.Void | TypeFlags.Undefined)) {
      const id = getTypeListId([yieldType, returnType, nextType]);
      let iterationTypes = iterationTypesCache.get(id);
      if (!iterationTypes) {
        iterationTypes = { yieldType, returnType, nextType };
        iterationTypesCache.set(id, iterationTypes);
      }
      return iterationTypes;
    }
    return { yieldType, returnType, nextType };
  }
  function combineIterationTypes(array) {
    let yieldTypes;
    let returnTypes;
    let nextTypes;
    for (const iterationTypes of array) {
      if (iterationTypes === void 0 || iterationTypes === noIterationTypes) {
        continue;
      }
      if (iterationTypes === anyIterationTypes) {
        return anyIterationTypes;
      }
      yieldTypes = append(yieldTypes, iterationTypes.yieldType);
      returnTypes = append(returnTypes, iterationTypes.returnType);
      nextTypes = append(nextTypes, iterationTypes.nextType);
    }
    if (yieldTypes || returnTypes || nextTypes) {
      return createIterationTypes(
        yieldTypes && getUnionType(yieldTypes),
        returnTypes && getUnionType(returnTypes),
        nextTypes && getIntersectionType(nextTypes)
      );
    }
    return noIterationTypes;
  }
  function getCachedIterationTypes(type, cacheKey) {
    return type[cacheKey];
  }
  function setCachedIterationTypes(type, cacheKey, cachedTypes2) {
    return type[cacheKey] = cachedTypes2;
  }
  function getIterationTypesOfIterable(type, use, errorNode) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    if (!(type.flags & TypeFlags.Union)) {
      const errorOutputContainer = errorNode ? { errors: void 0 } : void 0;
      const iterationTypes2 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer);
      if (iterationTypes2 === noIterationTypes) {
        if (errorNode) {
          const rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
          if (errorOutputContainer?.errors) {
            addRelatedInfo(rootDiag, ...errorOutputContainer.errors);
          }
        }
        return void 0;
      } else if (errorOutputContainer?.errors?.length) {
        for (const diag of errorOutputContainer.errors) {
          diagnostics.add(diag);
        }
      }
      return iterationTypes2;
    }
    const cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
    const cachedTypes2 = getCachedIterationTypes(type, cacheKey);
    if (cachedTypes2) return cachedTypes2 === noIterationTypes ? void 0 : cachedTypes2;
    let allIterationTypes;
    for (const constituent of type.types) {
      const errorOutputContainer = errorNode ? { errors: void 0 } : void 0;
      const iterationTypes2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer);
      if (iterationTypes2 === noIterationTypes) {
        if (errorNode) {
          const rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
          if (errorOutputContainer?.errors) {
            addRelatedInfo(rootDiag, ...errorOutputContainer.errors);
          }
        }
        setCachedIterationTypes(type, cacheKey, noIterationTypes);
        return void 0;
      } else if (errorOutputContainer?.errors?.length) {
        for (const diag of errorOutputContainer.errors) {
          diagnostics.add(diag);
        }
      }
      allIterationTypes = append(allIterationTypes, iterationTypes2);
    }
    const iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
    setCachedIterationTypes(type, cacheKey, iterationTypes);
    return iterationTypes === noIterationTypes ? void 0 : iterationTypes;
  }
  function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
    if (iterationTypes === noIterationTypes) return noIterationTypes;
    if (iterationTypes === anyIterationTypes) return anyIterationTypes;
    const { yieldType, returnType, nextType } = iterationTypes;
    if (errorNode) {
      getGlobalAwaitedSymbol(
        /*reportErrors*/
        true
      );
    }
    return createIterationTypes(
      getAwaitedType(yieldType, errorNode) || anyType,
      getAwaitedType(returnType, errorNode) || anyType,
      nextType
    );
  }
  function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    let noCache = false;
    if (use & 2 /* AllowsAsyncIterablesFlag */) {
      const iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
      if (iterationTypes) {
        if (iterationTypes === noIterationTypes && errorNode) {
          noCache = true;
        } else {
          return use & 8 /* ForOfFlag */ ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : iterationTypes;
        }
      }
    }
    if (use & 1 /* AllowsSyncIterablesFlag */) {
      let iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
      if (iterationTypes) {
        if (iterationTypes === noIterationTypes && errorNode) {
          noCache = true;
        } else {
          if (use & 2 /* AllowsAsyncIterablesFlag */) {
            if (iterationTypes !== noIterationTypes) {
              iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode);
              return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes);
            }
          } else {
            return iterationTypes;
          }
        }
      }
    }
    if (use & 2 /* AllowsAsyncIterablesFlag */) {
      const iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode, errorOutputContainer, noCache);
      if (iterationTypes !== noIterationTypes) {
        return iterationTypes;
      }
    }
    if (use & 1 /* AllowsSyncIterablesFlag */) {
      let iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode, errorOutputContainer, noCache);
      if (iterationTypes !== noIterationTypes) {
        if (use & 2 /* AllowsAsyncIterablesFlag */) {
          iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode);
          return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes);
        } else {
          return iterationTypes;
        }
      }
    }
    return noIterationTypes;
  }
  function getIterationTypesOfIterableCached(type, resolver) {
    return getCachedIterationTypes(type, resolver.iterableCacheKey);
  }
  function getIterationTypesOfIterableFast(type, resolver) {
    if (isReferenceToType(type, resolver.getGlobalIterableType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIteratorObjectType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIterableIteratorType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalGeneratorType(
      /*reportErrors*/
      false
    ))) {
      const [yieldType, returnType, nextType] = getTypeArguments(type);
      return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType(
        yieldType,
        /*errorNode*/
        void 0
      ) || yieldType, resolver.resolveIterationType(
        returnType,
        /*errorNode*/
        void 0
      ) || returnType, nextType));
    }
    if (isReferenceToSomeType(type, resolver.getGlobalBuiltinIteratorTypes())) {
      const [yieldType] = getTypeArguments(type);
      const returnType = getBuiltinIteratorReturnType();
      const nextType = unknownType;
      return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType(
        yieldType,
        /*errorNode*/
        void 0
      ) || yieldType, resolver.resolveIterationType(
        returnType,
        /*errorNode*/
        void 0
      ) || returnType, nextType));
    }
  }
  function getPropertyNameForKnownSymbolName(symbolName2) {
    const ctorType = getGlobalESSymbolConstructorSymbol(
      /*reportErrors*/
      false
    );
    const uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), escapeLeadingUnderscores(symbolName2));
    return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : `__@${symbolName2}`;
  }
  function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) {
    const method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
    const methodType = method && !(method.flags & SymbolFlags.Optional) ? getTypeOfSymbol(method) : void 0;
    if (isTypeAny(methodType)) {
      return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
    }
    const signatures = methodType ? getSignaturesOfType(methodType, SignatureKind.Call) : void 0;
    if (!some(signatures)) {
      return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
    }
    const iteratorType = getIntersectionType(map(signatures, getReturnTypeOfSignature));
    const iterationTypes = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache) ?? noIterationTypes;
    return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
  }
  function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
    const message = allowAsyncIterables ? Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
    const suggestAwait = (
      // for (const x of Promise<...>) or [...Promise<...>]
      !!getAwaitedTypeOfPromise(type) || !allowAsyncIterables && isForOfStatement(errorNode.parent) && errorNode.parent.expression === errorNode && getGlobalAsyncIterableType(
        /*reportErrors*/
        false
      ) !== emptyGenericType && isTypeAssignableTo(type, createTypeFromGenericGlobalType(getGlobalAsyncIterableType(
        /*reportErrors*/
        false
      ), [anyType, anyType, anyType]))
    );
    return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type));
  }
  function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) {
    return getIterationTypesOfIteratorWorker(
      type,
      resolver,
      errorNode,
      errorOutputContainer,
      /*noCache*/
      false
    );
  }
  function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    let iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || getIterationTypesOfIteratorFast(type, resolver);
    if (iterationTypes === noIterationTypes && errorNode) {
      iterationTypes = void 0;
      noCache = true;
    }
    iterationTypes ??= getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache);
    return iterationTypes === noIterationTypes ? void 0 : iterationTypes;
  }
  function getIterationTypesOfIteratorCached(type, resolver) {
    return getCachedIterationTypes(type, resolver.iteratorCacheKey);
  }
  function getIterationTypesOfIteratorFast(type, resolver) {
    if (isReferenceToType(type, resolver.getGlobalIterableIteratorType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIteratorType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIteratorObjectType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalGeneratorType(
      /*reportErrors*/
      false
    ))) {
      const [yieldType, returnType, nextType] = getTypeArguments(type);
      return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
    }
    if (isReferenceToSomeType(type, resolver.getGlobalBuiltinIteratorTypes())) {
      const [yieldType] = getTypeArguments(type);
      const returnType = getBuiltinIteratorReturnType();
      const nextType = unknownType;
      return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
    }
  }
  function isIteratorResult(type, kind) {
    const doneType = getTypeOfPropertyOfType(type, "done") || falseType;
    return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
  }
  function isYieldIteratorResult(type) {
    return isIteratorResult(type, 0 /* Yield */);
  }
  function isReturnIteratorResult(type) {
    return isIteratorResult(type, 1 /* Return */);
  }
  function getIterationTypesOfIteratorResult(type) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    const cachedTypes2 = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
    if (cachedTypes2) {
      return cachedTypes2;
    }
    if (isReferenceToType(type, getGlobalIteratorYieldResultType(
      /*reportErrors*/
      false
    ))) {
      const yieldType2 = getTypeArguments(type)[0];
      return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(
        yieldType2,
        /*returnType*/
        void 0,
        /*nextType*/
        void 0
      ));
    }
    if (isReferenceToType(type, getGlobalIteratorReturnResultType(
      /*reportErrors*/
      false
    ))) {
      const returnType2 = getTypeArguments(type)[0];
      return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(
        /*yieldType*/
        void 0,
        returnType2,
        /*nextType*/
        void 0
      ));
    }
    const yieldIteratorResult = filterType(type, isYieldIteratorResult);
    const yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : void 0;
    const returnIteratorResult = filterType(type, isReturnIteratorResult);
    const returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : void 0;
    if (!yieldType && !returnType) {
      return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
    }
    return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(
      yieldType,
      returnType || voidType,
      /*nextType*/
      void 0
    ));
  }
  function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) {
    const method = getPropertyOfType(type, methodName);
    if (!method && methodName !== "next") {
      return void 0;
    }
    const methodType = method && !(methodName === "next" && method.flags & SymbolFlags.Optional) ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */) : void 0;
    if (isTypeAny(methodType)) {
      return anyIterationTypes;
    }
    const methodSignatures = methodType ? getSignaturesOfType(methodType, SignatureKind.Call) : emptyArray;
    if (methodSignatures.length === 0) {
      if (errorNode) {
        const diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic;
        if (errorOutputContainer) {
          errorOutputContainer.errors ??= [];
          errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, diagnostic, methodName));
        } else {
          error(errorNode, diagnostic, methodName);
        }
      }
      return methodName === "next" ? noIterationTypes : void 0;
    }
    if (methodType?.symbol && methodSignatures.length === 1) {
      const globalGeneratorType = resolver.getGlobalGeneratorType(
        /*reportErrors*/
        false
      );
      const globalIteratorType = resolver.getGlobalIteratorType(
        /*reportErrors*/
        false
      );
      const isGeneratorMethod = globalGeneratorType.symbol?.members?.get(methodName) === methodType.symbol;
      const isIteratorMethod = !isGeneratorMethod && globalIteratorType.symbol?.members?.get(methodName) === methodType.symbol;
      if (isGeneratorMethod || isIteratorMethod) {
        const globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType;
        const { mapper } = methodType;
        return createIterationTypes(
          getMappedType(globalType.typeParameters[0], mapper),
          getMappedType(globalType.typeParameters[1], mapper),
          methodName === "next" ? getMappedType(globalType.typeParameters[2], mapper) : void 0
        );
      }
    }
    let methodParameterTypes;
    let methodReturnTypes;
    for (const signature of methodSignatures) {
      if (methodName !== "throw" && some(signature.parameters)) {
        methodParameterTypes = append(methodParameterTypes, getTypeAtPosition(signature, 0));
      }
      methodReturnTypes = append(methodReturnTypes, getReturnTypeOfSignature(signature));
    }
    let returnTypes;
    let nextType;
    if (methodName !== "throw") {
      const methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
      if (methodName === "next") {
        nextType = methodParameterType;
      } else if (methodName === "return") {
        const resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
        returnTypes = append(returnTypes, resolvedMethodParameterType);
      }
    }
    let yieldType;
    const methodReturnType = methodReturnTypes ? getIntersectionType(methodReturnTypes) : neverType;
    const resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
    const iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
    if (iterationTypes === noIterationTypes) {
      if (errorNode) {
        if (errorOutputContainer) {
          errorOutputContainer.errors ??= [];
          errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName));
        } else {
          error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
        }
      }
      yieldType = anyType;
      returnTypes = append(returnTypes, anyType);
    } else {
      yieldType = iterationTypes.yieldType;
      returnTypes = append(returnTypes, iterationTypes.returnType);
    }
    return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
  }
  function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) {
    const iterationTypes = combineIterationTypes([
      getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer),
      getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer),
      getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer)
    ]);
    return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
  }
  function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
    if (isTypeAny(returnType)) {
      return void 0;
    }
    const iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
    return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
  }
  function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    const use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
    const resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
    return getIterationTypesOfIterable(
      type,
      use,
      /*errorNode*/
      void 0
    ) || getIterationTypesOfIterator(
      type,
      resolver,
      /*errorNode*/
      void 0,
      /*errorOutputContainer*/
      void 0
    );
  }
  function checkBreakOrContinueStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) checkGrammarBreakOrContinueStatement(node);
  }
  function unwrapReturnType(returnType, functionFlags) {
    const isGenerator = !!(functionFlags & FunctionFlags.Generator);
    const isAsync = !!(functionFlags & FunctionFlags.Async);
    if (isGenerator) {
      const returnIterationType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync);
      if (!returnIterationType) {
        return errorType;
      }
      return isAsync ? getAwaitedTypeNoAlias(unwrapAwaitedType(returnIterationType)) : returnIterationType;
    }
    return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType;
  }
  function isUnwrappedReturnTypeUndefinedVoidOrAny(func, returnType) {
    const type = unwrapReturnType(returnType, getFunctionFlags(func));
    return !!(type && (maybeTypeOfKind(type, TypeFlags.Void) || type.flags & (TypeFlags.Any | TypeFlags.Undefined)));
  }
  function checkReturnStatement(node) {
    if (checkGrammarStatementInAmbientContext(node)) {
      return;
    }
    const container = getContainingFunctionOrClassStaticBlock(node);
    if (container && isClassStaticBlockDeclaration(container)) {
      grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block);
      return;
    }
    if (!container) {
      grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
      return;
    }
    const signature = getSignatureFromDeclaration(container);
    const returnType = getReturnTypeOfSignature(signature);
    const functionFlags = getFunctionFlags(container);
    if (strictNullChecks || node.expression || returnType.flags & TypeFlags.Never) {
      const exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
      if (container.kind === SyntaxKind.SetAccessor) {
        if (node.expression) {
          error(node, Diagnostics.Setters_cannot_return_a_value);
        }
      } else if (container.kind === SyntaxKind.Constructor) {
        if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
          error(node, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
        }
      } else if (getReturnTypeFromAnnotation(container)) {
        const unwrappedReturnType = unwrapReturnType(returnType, functionFlags) ?? returnType;
        const unwrappedExprType = functionFlags & FunctionFlags.Async ? checkAwaitedType(
          exprType,
          /*withAlias*/
          false,
          node,
          Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
        ) : exprType;
        if (unwrappedReturnType) {
          checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
        }
      }
    } else if (container.kind !== SyntaxKind.Constructor && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeUndefinedVoidOrAny(container, returnType)) {
      error(node, Diagnostics.Not_all_code_paths_return_a_value);
    }
  }
  function checkWithStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      if (node.flags & NodeFlags.AwaitContext) {
        grammarErrorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
      }
    }
    checkExpression(node.expression);
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile)) {
      const start = getSpanOfTokenAtPosition(sourceFile, node.pos).start;
      const end = node.statement.pos;
      grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
    }
  }
  function checkSwitchStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    let firstDefaultClause;
    let hasDuplicateDefaultClause = false;
    const expressionType = checkExpression(node.expression);
    forEach(node.caseBlock.clauses, (clause) => {
      if (clause.kind === SyntaxKind.DefaultClause && !hasDuplicateDefaultClause) {
        if (firstDefaultClause === void 0) {
          firstDefaultClause = clause;
        } else {
          grammarErrorOnNode(clause, Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
          hasDuplicateDefaultClause = true;
        }
      }
      if (clause.kind === SyntaxKind.CaseClause) {
        addLazyDiagnostic(createLazyCaseClauseDiagnostics(clause));
      }
      forEach(clause.statements, checkSourceElement);
      if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
        error(clause, Diagnostics.Fallthrough_case_in_switch);
      }
      function createLazyCaseClauseDiagnostics(clause2) {
        return () => {
          const caseType = checkExpression(clause2.expression);
          if (!isTypeEqualityComparableTo(expressionType, caseType)) {
            checkTypeComparableTo(
              caseType,
              expressionType,
              clause2.expression,
              /*headMessage*/
              void 0
            );
          }
        };
      }
    });
    if (node.caseBlock.locals) {
      registerForUnusedIdentifiersCheck(node.caseBlock);
    }
  }
  function checkLabeledStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      findAncestor(node.parent, (current) => {
        if (isFunctionLike(current)) {
          return "quit";
        }
        if (current.kind === SyntaxKind.LabeledStatement && current.label.escapedText === node.label.escapedText) {
          grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNode(node.label));
          return true;
        }
        return false;
      });
    }
    checkSourceElement(node.statement);
  }
  function checkThrowStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      if (isIdentifier(node.expression) && !node.expression.escapedText) {
        grammarErrorAfterFirstToken(node, Diagnostics.Line_break_not_permitted_here);
      }
    }
    if (node.expression) {
      checkExpression(node.expression);
    }
  }
  function checkTryStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkBlock(node.tryBlock);
    const catchClause = node.catchClause;
    if (catchClause) {
      if (catchClause.variableDeclaration) {
        const declaration = catchClause.variableDeclaration;
        checkVariableLikeDeclaration(declaration);
        const typeNode = getEffectiveTypeAnnotationNode(declaration);
        if (typeNode) {
          const type = getTypeFromTypeNode(typeNode);
          if (type && !(type.flags & TypeFlags.AnyOrUnknown)) {
            grammarErrorOnFirstToken(typeNode, Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified);
          }
        } else if (declaration.initializer) {
          grammarErrorOnFirstToken(declaration.initializer, Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
        } else {
          const blockLocals = catchClause.block.locals;
          if (blockLocals) {
            forEachKey(catchClause.locals, (caughtName) => {
              const blockLocal = blockLocals.get(caughtName);
              if (blockLocal?.valueDeclaration && (blockLocal.flags & SymbolFlags.BlockScopedVariable) !== 0) {
                grammarErrorOnNode(blockLocal.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, unescapeLeadingUnderscores(caughtName));
              }
            });
          }
        }
      }
      checkBlock(catchClause.block);
    }
    if (node.finallyBlock) {
      checkBlock(node.finallyBlock);
    }
  }
  function checkIndexConstraints(type, symbol, isStaticIndex) {
    const indexInfos = getIndexInfosOfType(type);
    if (indexInfos.length === 0) {
      return;
    }
    for (const prop of getPropertiesOfObjectType(type)) {
      if (!(isStaticIndex && prop.flags & SymbolFlags.Prototype)) {
        checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty(
          prop,
          TypeFlags.StringOrNumberLiteralOrUnique,
          /*includeNonPublic*/
          true
        ), getNonMissingTypeOfSymbol(prop));
      }
    }
    const typeDeclaration = symbol.valueDeclaration;
    if (typeDeclaration && isClassLike(typeDeclaration)) {
      for (const member of typeDeclaration.members) {
        if (!isStatic(member) && !hasBindableName(member)) {
          const symbol2 = getSymbolOfDeclaration(member);
          checkIndexConstraintForProperty(type, symbol2, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol2));
        }
      }
    }
    if (indexInfos.length > 1) {
      for (const info of indexInfos) {
        checkIndexConstraintForIndexSignature(type, info);
      }
    }
  }
  function checkIndexConstraintForProperty(type, prop, propNameType, propType) {
    const declaration = prop.valueDeclaration;
    const name = getNameOfDeclaration(declaration);
    if (name && isPrivateIdentifier(name)) {
      return;
    }
    const indexInfos = getApplicableIndexInfos(type, propNameType);
    const interfaceDeclaration = getObjectFlags(type) & ObjectFlags.Interface ? getDeclarationOfKind(type.symbol, SyntaxKind.InterfaceDeclaration) : void 0;
    const propDeclaration = declaration && declaration.kind === SyntaxKind.BinaryExpression || name && name.kind === SyntaxKind.ComputedPropertyName ? declaration : void 0;
    const localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : void 0;
    for (const info of indexInfos) {
      const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0;
      const errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0);
      if (errorNode && !isTypeAssignableTo(propType, info.type)) {
        const diagnostic = createError(errorNode, Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type));
        if (propDeclaration && errorNode !== propDeclaration) {
          addRelatedInfo(diagnostic, createDiagnosticForNode(propDeclaration, Diagnostics._0_is_declared_here, symbolToString(prop)));
        }
        diagnostics.add(diagnostic);
      }
    }
  }
  function checkIndexConstraintForIndexSignature(type, checkInfo) {
    const declaration = checkInfo.declaration;
    const indexInfos = getApplicableIndexInfos(type, checkInfo.keyType);
    const interfaceDeclaration = getObjectFlags(type) & ObjectFlags.Interface ? getDeclarationOfKind(type.symbol, SyntaxKind.InterfaceDeclaration) : void 0;
    const localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfDeclaration(declaration)) === type.symbol ? declaration : void 0;
    for (const info of indexInfos) {
      if (info === checkInfo) continue;
      const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0;
      const errorNode = localCheckDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getIndexInfoOfType(base, checkInfo.keyType) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0);
      if (errorNode && !isTypeAssignableTo(checkInfo.type, info.type)) {
        error(errorNode, Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, typeToString(checkInfo.keyType), typeToString(checkInfo.type), typeToString(info.keyType), typeToString(info.type));
      }
    }
  }
  function checkTypeNameIsReserved(name, message) {
    switch (name.escapedText) {
      case "any":
      case "unknown":
      case "never":
      case "number":
      case "bigint":
      case "boolean":
      case "string":
      case "symbol":
      case "void":
      case "object":
      case "undefined":
        error(name, message, name.escapedText);
    }
  }
  function checkClassNameCollisionWithObject(name) {
    if (languageVersion >= ScriptTarget.ES5 && name.escapedText === "Object" && host.getEmitModuleFormatOfFile(getSourceFileOfNode(name)) < ModuleKind.ES2015) {
      error(name, Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ModuleKind[moduleKind]);
    }
  }
  function checkUnmatchedJSDocParameters(node) {
    const jsdocParameters = filter(getJSDocTags(node), isJSDocParameterTag);
    if (!length(jsdocParameters)) return;
    const isJs = isInJSFile(node);
    const parameters = /* @__PURE__ */ new Set();
    const excludedParameters = /* @__PURE__ */ new Set();
    forEach(node.parameters, ({ name }, index) => {
      if (isIdentifier(name)) {
        parameters.add(name.escapedText);
      }
      if (isBindingPattern(name)) {
        excludedParameters.add(index);
      }
    });
    const containsArguments = containsArgumentsReference(node);
    if (containsArguments) {
      const lastJSDocParamIndex = jsdocParameters.length - 1;
      const lastJSDocParam = jsdocParameters[lastJSDocParamIndex];
      if (isJs && lastJSDocParam && isIdentifier(lastJSDocParam.name) && lastJSDocParam.typeExpression && lastJSDocParam.typeExpression.type && !parameters.has(lastJSDocParam.name.escapedText) && !excludedParameters.has(lastJSDocParamIndex) && !isArrayType(getTypeFromTypeNode(lastJSDocParam.typeExpression.type))) {
        error(lastJSDocParam.name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, idText(lastJSDocParam.name));
      }
    } else {
      forEach(jsdocParameters, ({ name, isNameFirst }, index) => {
        if (excludedParameters.has(index) || isIdentifier(name) && parameters.has(name.escapedText)) {
          return;
        }
        if (isQualifiedName(name)) {
          if (isJs) {
            error(name, Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, entityNameToString(name), entityNameToString(name.left));
          }
        } else {
          if (!isNameFirst) {
            errorOrSuggestion(isJs, name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, idText(name));
          }
        }
      });
    }
  }
  function checkTypeParameters(typeParameterDeclarations) {
    let seenDefault = false;
    if (typeParameterDeclarations) {
      for (let i = 0; i < typeParameterDeclarations.length; i++) {
        const node = typeParameterDeclarations[i];
        checkTypeParameter(node);
        addLazyDiagnostic(createCheckTypeParameterDiagnostic(node, i));
      }
    }
    function createCheckTypeParameterDiagnostic(node, i) {
      return () => {
        if (node.default) {
          seenDefault = true;
          checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
        } else if (seenDefault) {
          error(node, Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
        }
        for (let j = 0; j < i; j++) {
          if (typeParameterDeclarations[j].symbol === node.symbol) {
            error(node.name, Diagnostics.Duplicate_identifier_0, declarationNameToString(node.name));
          }
        }
      };
    }
  }
  function checkTypeParametersNotReferenced(root, typeParameters, index) {
    visit(root);
    function visit(node) {
      if (node.kind === SyntaxKind.TypeReference) {
        const type = getTypeFromTypeReference(node);
        if (type.flags & TypeFlags.TypeParameter) {
          for (let i = index; i < typeParameters.length; i++) {
            if (type.symbol === getSymbolOfDeclaration(typeParameters[i])) {
              error(node, Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
            }
          }
        }
      }
      forEachChild(node, visit);
    }
  }
  function checkTypeParameterListsIdentical(symbol) {
    if (symbol.declarations && symbol.declarations.length === 1) {
      return;
    }
    const links = getSymbolLinks(symbol);
    if (!links.typeParametersChecked) {
      links.typeParametersChecked = true;
      const declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
      if (!declarations || declarations.length <= 1) {
        return;
      }
      const type = getDeclaredTypeOfSymbol(symbol);
      if (!areTypeParametersIdentical(declarations, type.localTypeParameters, getEffectiveTypeParameterDeclarations)) {
        const name = symbolToString(symbol);
        for (const declaration of declarations) {
          error(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
        }
      }
    }
  }
  function areTypeParametersIdentical(declarations, targetParameters, getTypeParameterDeclarations) {
    const maxTypeArgumentCount = length(targetParameters);
    const minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
    for (const declaration of declarations) {
      const sourceParameters = getTypeParameterDeclarations(declaration);
      const numTypeParameters = sourceParameters.length;
      if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
        return false;
      }
      for (let i = 0; i < numTypeParameters; i++) {
        const source = sourceParameters[i];
        const target = targetParameters[i];
        if (source.name.escapedText !== target.symbol.escapedName) {
          return false;
        }
        const constraint = getEffectiveConstraintOfTypeParameter(source);
        const sourceConstraint = constraint && getTypeFromTypeNode(constraint);
        const targetConstraint = getConstraintOfTypeParameter(target);
        if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
          return false;
        }
        const sourceDefault = source.default && getTypeFromTypeNode(source.default);
        const targetDefault = getDefaultFromTypeParameter(target);
        if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
          return false;
        }
      }
    }
    return true;
  }
  function getFirstTransformableStaticClassElement(node) {
    const willTransformStaticElementsOfDecoratedClass = !legacyDecorators && languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators && classOrConstructorParameterIsDecorated(
      /*useLegacyDecorators*/
      false,
      node
    );
    const willTransformPrivateElementsOrClassStaticBlocks = languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators;
    const willTransformInitializers = !emitStandardClassFields;
    if (willTransformStaticElementsOfDecoratedClass || willTransformPrivateElementsOrClassStaticBlocks) {
      for (const member of node.members) {
        if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated(
          /*useLegacyDecorators*/
          false,
          member,
          node
        )) {
          return firstOrUndefined(getDecorators(node)) ?? node;
        } else if (willTransformPrivateElementsOrClassStaticBlocks) {
          if (isClassStaticBlockDeclaration(member)) {
            return member;
          } else if (isStatic(member)) {
            if (isPrivateIdentifierClassElementDeclaration(member) || willTransformInitializers && isInitializedProperty(member)) {
              return member;
            }
          }
        }
      }
    }
  }
  function checkClassExpressionExternalHelpers(node) {
    if (node.name) return;
    const parent = walkUpOuterExpressions(node);
    if (!isNamedEvaluationSource(parent)) return;
    const willTransformESDecorators = !legacyDecorators && languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators;
    let location;
    if (willTransformESDecorators && classOrConstructorParameterIsDecorated(
      /*useLegacyDecorators*/
      false,
      node
    )) {
      location = firstOrUndefined(getDecorators(node)) ?? node;
    } else {
      location = getFirstTransformableStaticClassElement(node);
    }
    if (location) {
      checkExternalEmitHelpers(location, ExternalEmitHelpers.SetFunctionName);
      if ((isPropertyAssignment(parent) || isPropertyDeclaration(parent) || isBindingElement(parent)) && isComputedPropertyName(parent.name)) {
        checkExternalEmitHelpers(location, ExternalEmitHelpers.PropKey);
      }
    }
  }
  function checkClassExpression(node) {
    checkClassLikeDeclaration(node);
    checkNodeDeferred(node);
    checkClassExpressionExternalHelpers(node);
    return getTypeOfSymbol(getSymbolOfDeclaration(node));
  }
  function checkClassExpressionDeferred(node) {
    forEach(node.members, checkSourceElement);
    registerForUnusedIdentifiersCheck(node);
  }
  function checkClassDeclaration(node) {
    const firstDecorator = find(node.modifiers, isDecorator);
    if (legacyDecorators && firstDecorator && some(node.members, (p) => hasStaticModifier(p) && isPrivateIdentifierClassElementDeclaration(p))) {
      grammarErrorOnNode(firstDecorator, Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator);
    }
    if (!node.name && !hasSyntacticModifier(node, ModifierFlags.Default)) {
      grammarErrorOnFirstToken(node, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
    }
    checkClassLikeDeclaration(node);
    forEach(node.members, checkSourceElement);
    registerForUnusedIdentifiersCheck(node);
  }
  function checkClassLikeDeclaration(node) {
    checkGrammarClassLikeDeclaration(node);
    checkDecorators(node);
    checkCollisionsForDeclarationName(node, node.name);
    checkTypeParameters(getEffectiveTypeParameterDeclarations(node));
    checkExportsOnMergedDeclarations(node);
    const symbol = getSymbolOfDeclaration(node);
    const type = getDeclaredTypeOfSymbol(symbol);
    const typeWithThis = getTypeWithThisArgument(type);
    const staticType = getTypeOfSymbol(symbol);
    checkTypeParameterListsIdentical(symbol);
    checkFunctionOrConstructorSymbol(symbol);
    checkClassForDuplicateDeclarations(node);
    const nodeInAmbientContext = !!(node.flags & NodeFlags.Ambient);
    if (!nodeInAmbientContext) {
      checkClassForStaticPropertyNameConflicts(node);
    }
    const baseTypeNode = getEffectiveBaseTypeNode(node);
    if (baseTypeNode) {
      forEach(baseTypeNode.typeArguments, checkSourceElement);
      if (languageVersion < LanguageFeatureMinimumTarget.Classes) {
        checkExternalEmitHelpers(baseTypeNode.parent, ExternalEmitHelpers.Extends);
      }
      const extendsNode = getClassExtendsHeritageElement(node);
      if (extendsNode && extendsNode !== baseTypeNode) {
        checkExpression(extendsNode.expression);
      }
      const baseTypes = getBaseTypes(type);
      if (baseTypes.length) {
        addLazyDiagnostic(() => {
          const baseType = baseTypes[0];
          const baseConstructorType = getBaseConstructorTypeOfClass(type);
          const staticBaseType = getApparentType(baseConstructorType);
          checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
          checkSourceElement(baseTypeNode.expression);
          if (some(baseTypeNode.typeArguments)) {
            forEach(baseTypeNode.typeArguments, checkSourceElement);
            for (const constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode)) {
              if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
                break;
              }
            }
          }
          const baseWithThis = getTypeWithThisArgument(baseType, type.thisType);
          if (!checkTypeAssignableTo(
            typeWithThis,
            baseWithThis,
            /*errorNode*/
            void 0
          )) {
            issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1);
          } else {
            checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
          }
          if (baseConstructorType.flags & TypeFlags.TypeVariable) {
            if (!isMixinConstructorType(staticType)) {
              error(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
            } else {
              const constructSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct);
              if (constructSignatures.some((signature) => signature.flags & SignatureFlags.Abstract) && !hasSyntacticModifier(node, ModifierFlags.Abstract)) {
                error(node.name || node, Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract);
              }
            }
          }
          if (!(staticBaseType.symbol && staticBaseType.symbol.flags & SymbolFlags.Class) && !(baseConstructorType.flags & TypeFlags.TypeVariable)) {
            const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
            if (forEach(constructors, (sig) => !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType))) {
              error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type);
            }
          }
          checkKindsOfPropertyMemberOverrides(type, baseType);
        });
      }
    }
    checkMembersForOverrideModifier(node, type, typeWithThis, staticType);
    const implementedTypeNodes = getEffectiveImplementsTypeNodes(node);
    if (implementedTypeNodes) {
      for (const typeRefNode of implementedTypeNodes) {
        if (!isEntityNameExpression(typeRefNode.expression) || isOptionalChain(typeRefNode.expression)) {
          error(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
        }
        checkTypeReferenceNode(typeRefNode);
        addLazyDiagnostic(createImplementsDiagnostics(typeRefNode));
      }
    }
    addLazyDiagnostic(() => {
      checkIndexConstraints(type, symbol);
      checkIndexConstraints(
        staticType,
        symbol,
        /*isStaticIndex*/
        true
      );
      checkTypeForDuplicateIndexSignatures(node);
      checkPropertyInitialization(node);
    });
    function createImplementsDiagnostics(typeRefNode) {
      return () => {
        const t = getReducedType(getTypeFromTypeNode(typeRefNode));
        if (!isErrorType(t)) {
          if (isValidBaseType(t)) {
            const genericDiag = t.symbol && t.symbol.flags & SymbolFlags.Class ? Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : Diagnostics.Class_0_incorrectly_implements_interface_1;
            const baseWithThis = getTypeWithThisArgument(t, type.thisType);
            if (!checkTypeAssignableTo(
              typeWithThis,
              baseWithThis,
              /*errorNode*/
              void 0
            )) {
              issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
            }
          } else {
            error(typeRefNode, Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
          }
        }
      };
    }
  }
  function checkMembersForOverrideModifier(node, type, typeWithThis, staticType) {
    const baseTypeNode = getEffectiveBaseTypeNode(node);
    const baseTypes = baseTypeNode && getBaseTypes(type);
    const baseWithThis = baseTypes?.length ? getTypeWithThisArgument(first(baseTypes), type.thisType) : void 0;
    const baseStaticType = getBaseConstructorTypeOfClass(type);
    for (const member of node.members) {
      if (hasAmbientModifier(member)) {
        continue;
      }
      if (isConstructorDeclaration(member)) {
        forEach(member.parameters, (param) => {
          if (isParameterPropertyDeclaration(param, member)) {
            checkExistingMemberForOverrideModifier(
              node,
              staticType,
              baseStaticType,
              baseWithThis,
              type,
              typeWithThis,
              param,
              /*memberIsParameterProperty*/
              true
            );
          }
        });
      }
      checkExistingMemberForOverrideModifier(
        node,
        staticType,
        baseStaticType,
        baseWithThis,
        type,
        typeWithThis,
        member,
        /*memberIsParameterProperty*/
        false
      );
    }
  }
  function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors = true) {
    const declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
    if (!declaredProp) {
      return MemberOverrideStatus.Ok;
    }
    return checkMemberForOverrideModifier(
      node,
      staticType,
      baseStaticType,
      baseWithThis,
      type,
      typeWithThis,
      hasOverrideModifier(member),
      hasAbstractModifier(member),
      isStatic(member),
      memberIsParameterProperty,
      declaredProp,
      reportErrors ? member : void 0
    );
  }
  function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, member, errorNode) {
    const isJs = isInJSFile(node);
    const nodeInAmbientContext = !!(node.flags & NodeFlags.Ambient);
    if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) {
      const thisType = memberIsStatic ? staticType : typeWithThis;
      const baseType = memberIsStatic ? baseStaticType : baseWithThis;
      const prop = getPropertyOfType(thisType, member.escapedName);
      const baseProp = getPropertyOfType(baseType, member.escapedName);
      const baseClassName = typeToString(baseWithThis);
      if (prop && !baseProp && memberHasOverrideModifier) {
        if (errorNode) {
          const suggestion = getSuggestedSymbolForNonexistentClassMember(symbolName(member), baseType);
          suggestion ? error(
            errorNode,
            isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1,
            baseClassName,
            symbolToString(suggestion)
          ) : error(
            errorNode,
            isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0,
            baseClassName
          );
        }
        return MemberOverrideStatus.HasInvalidOverride;
      } else if (prop && baseProp?.declarations && compilerOptions.noImplicitOverride && !nodeInAmbientContext) {
        const baseHasAbstract = some(baseProp.declarations, hasAbstractModifier);
        if (memberHasOverrideModifier) {
          return MemberOverrideStatus.Ok;
        }
        if (!baseHasAbstract) {
          if (errorNode) {
            const diag = memberIsParameterProperty ? isJs ? Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : isJs ? Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0;
            error(errorNode, diag, baseClassName);
          }
          return MemberOverrideStatus.NeedsOverride;
        } else if (memberHasAbstractModifier && baseHasAbstract) {
          if (errorNode) {
            error(errorNode, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName);
          }
          return MemberOverrideStatus.NeedsOverride;
        }
      }
    } else if (memberHasOverrideModifier) {
      if (errorNode) {
        const className = typeToString(type);
        error(
          errorNode,
          isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class,
          className
        );
      }
      return MemberOverrideStatus.HasInvalidOverride;
    }
    return MemberOverrideStatus.Ok;
  }
  function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
    let issuedMemberError = false;
    for (const member of node.members) {
      if (isStatic(member)) {
        continue;
      }
      const declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
      if (declaredProp) {
        const prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
        const baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
        if (prop && baseProp) {
          const rootChain = () => chainDiagnosticMessages(
            /*details*/
            void 0,
            Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2,
            symbolToString(declaredProp),
            typeToString(typeWithThis),
            typeToString(baseWithThis)
          );
          if (!checkTypeAssignableTo(
            getTypeOfSymbol(prop),
            getTypeOfSymbol(baseProp),
            member.name || member,
            /*headMessage*/
            void 0,
            rootChain
          )) {
            issuedMemberError = true;
          }
        }
      }
    }
    if (!issuedMemberError) {
      checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
    }
  }
  function checkBaseTypeAccessibility(type, node) {
    const signatures = getSignaturesOfType(type, SignatureKind.Construct);
    if (signatures.length) {
      const declaration = signatures[0].declaration;
      if (declaration && hasEffectiveModifier(declaration, ModifierFlags.Private)) {
        const typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol);
        if (!isNodeWithinClass(node, typeClassDeclaration)) {
          error(node, Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
        }
      }
    }
  }
  function getMemberOverrideModifierStatus(node, member, memberSymbol) {
    if (!member.name) {
      return MemberOverrideStatus.Ok;
    }
    const classSymbol = getSymbolOfDeclaration(node);
    const type = getDeclaredTypeOfSymbol(classSymbol);
    const typeWithThis = getTypeWithThisArgument(type);
    const staticType = getTypeOfSymbol(classSymbol);
    const baseTypeNode = getEffectiveBaseTypeNode(node);
    const baseTypes = baseTypeNode && getBaseTypes(type);
    const baseWithThis = baseTypes?.length ? getTypeWithThisArgument(first(baseTypes), type.thisType) : void 0;
    const baseStaticType = getBaseConstructorTypeOfClass(type);
    const memberHasOverrideModifier = member.parent ? hasOverrideModifier(member) : hasSyntacticModifier(member, ModifierFlags.Override);
    return checkMemberForOverrideModifier(
      node,
      staticType,
      baseStaticType,
      baseWithThis,
      type,
      typeWithThis,
      memberHasOverrideModifier,
      hasAbstractModifier(member),
      isStatic(member),
      /*memberIsParameterProperty*/
      false,
      memberSymbol
    );
  }
  function getTargetSymbol(s) {
    return getCheckFlags(s) & CheckFlags.Instantiated ? s.links.target : s;
  }
  function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
    return filter(symbol.declarations, (d) => d.kind === SyntaxKind.ClassDeclaration || d.kind === SyntaxKind.InterfaceDeclaration);
  }
  function checkKindsOfPropertyMemberOverrides(type, baseType) {
    const baseProperties = getPropertiesOfType(baseType);
    const notImplementedInfo = /* @__PURE__ */ new Map();
    basePropertyCheck: for (const baseProperty of baseProperties) {
      const base = getTargetSymbol(baseProperty);
      if (base.flags & SymbolFlags.Prototype) {
        continue;
      }
      const baseSymbol = getPropertyOfObjectType(type, base.escapedName);
      if (!baseSymbol) {
        continue;
      }
      const derived = getTargetSymbol(baseSymbol);
      const baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base);
      Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
      if (derived === base) {
        const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol);
        if (baseDeclarationFlags & ModifierFlags.Abstract && (!derivedClassDecl || !hasSyntacticModifier(derivedClassDecl, ModifierFlags.Abstract))) {
          for (const otherBaseType of getBaseTypes(type)) {
            if (otherBaseType === baseType) continue;
            const baseSymbol2 = getPropertyOfObjectType(otherBaseType, base.escapedName);
            const derivedElsewhere = baseSymbol2 && getTargetSymbol(baseSymbol2);
            if (derivedElsewhere && derivedElsewhere !== base) {
              continue basePropertyCheck;
            }
          }
          const baseTypeName = typeToString(baseType);
          const typeName = typeToString(type);
          const basePropertyName = symbolToString(baseProperty);
          const missedProperties = append(notImplementedInfo.get(derivedClassDecl)?.missedProperties, basePropertyName);
          notImplementedInfo.set(derivedClassDecl, { baseTypeName, typeName, missedProperties });
        }
      } else {
        const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived);
        if (baseDeclarationFlags & ModifierFlags.Private || derivedDeclarationFlags & ModifierFlags.Private) {
          continue;
        }
        let errorMessage;
        const basePropertyFlags = base.flags & SymbolFlags.PropertyOrAccessor;
        const derivedPropertyFlags = derived.flags & SymbolFlags.PropertyOrAccessor;
        if (basePropertyFlags && derivedPropertyFlags) {
          if ((getCheckFlags(base) & CheckFlags.Synthetic ? base.declarations?.some((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : base.declarations?.every((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & CheckFlags.Mapped || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) {
            continue;
          }
          const overriddenInstanceProperty = basePropertyFlags !== SymbolFlags.Property && derivedPropertyFlags === SymbolFlags.Property;
          const overriddenInstanceAccessor = basePropertyFlags === SymbolFlags.Property && derivedPropertyFlags !== SymbolFlags.Property;
          if (overriddenInstanceProperty || overriddenInstanceAccessor) {
            const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
            error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type));
          } else if (useDefineForClassFields) {
            const uninitialized = derived.declarations?.find((d) => d.kind === SyntaxKind.PropertyDeclaration && !d.initializer);
            if (uninitialized && !(derived.flags & SymbolFlags.Transient) && !(baseDeclarationFlags & ModifierFlags.Abstract) && !(derivedDeclarationFlags & ModifierFlags.Abstract) && !derived.declarations?.some((d) => !!(d.flags & NodeFlags.Ambient))) {
              const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol));
              const propName = uninitialized.name;
              if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) {
                const errorMessage2 = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration;
                error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType));
              }
            }
          }
          continue;
        } else if (isPrototypeProperty(base)) {
          if (isPrototypeProperty(derived) || derived.flags & SymbolFlags.Property) {
            continue;
          } else {
            Debug.assert(!!(derived.flags & SymbolFlags.Accessor));
            errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
          }
        } else if (base.flags & SymbolFlags.Accessor) {
          errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
        } else {
          errorMessage = Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
        }
        error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
      }
    }
    for (const [errorNode, memberInfo] of notImplementedInfo) {
      if (length(memberInfo.missedProperties) === 1) {
        if (isClassExpression(errorNode)) {
          error(errorNode, Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, first(memberInfo.missedProperties), memberInfo.baseTypeName);
        } else {
          error(errorNode, Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, memberInfo.typeName, first(memberInfo.missedProperties), memberInfo.baseTypeName);
        }
      } else if (length(memberInfo.missedProperties) > 5) {
        const missedProperties = map(memberInfo.missedProperties.slice(0, 4), (prop) => `'${prop}'`).join(", ");
        const remainingMissedProperties = length(memberInfo.missedProperties) - 4;
        if (isClassExpression(errorNode)) {
          error(errorNode, Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and_2_more, memberInfo.baseTypeName, missedProperties, remainingMissedProperties);
        } else {
          error(errorNode, Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more, memberInfo.typeName, memberInfo.baseTypeName, missedProperties, remainingMissedProperties);
        }
      } else {
        const missedProperties = map(memberInfo.missedProperties, (prop) => `'${prop}'`).join(", ");
        if (isClassExpression(errorNode)) {
          error(errorNode, Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1, memberInfo.baseTypeName, missedProperties);
        } else {
          error(errorNode, Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2, memberInfo.typeName, memberInfo.baseTypeName, missedProperties);
        }
      }
    }
  }
  function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) {
    return baseDeclarationFlags & ModifierFlags.Abstract && (!isPropertyDeclaration(declaration) || !declaration.initializer) || isInterfaceDeclaration(declaration.parent);
  }
  function getNonInheritedProperties(type, baseTypes, properties) {
    if (!length(baseTypes)) {
      return properties;
    }
    const seen = /* @__PURE__ */ new Map();
    forEach(properties, (p) => {
      seen.set(p.escapedName, p);
    });
    for (const base of baseTypes) {
      const properties2 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
      for (const prop of properties2) {
        const existing = seen.get(prop.escapedName);
        if (existing && prop.parent === existing.parent) {
          seen.delete(prop.escapedName);
        }
      }
    }
    return arrayFrom(seen.values());
  }
  function checkInheritedPropertiesAreIdentical(type, typeNode) {
    const baseTypes = getBaseTypes(type);
    if (baseTypes.length < 2) {
      return true;
    }
    const seen = /* @__PURE__ */ new Map();
    forEach(resolveDeclaredMembers(type).declaredProperties, (p) => {
      seen.set(p.escapedName, { prop: p, containingType: type });
    });
    let ok = true;
    for (const base of baseTypes) {
      const properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
      for (const prop of properties) {
        const existing = seen.get(prop.escapedName);
        if (!existing) {
          seen.set(prop.escapedName, { prop, containingType: base });
        } else {
          const isInheritedProperty = existing.containingType !== type;
          if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
            ok = false;
            const typeName1 = typeToString(existing.containingType);
            const typeName2 = typeToString(base);
            let errorInfo = chainDiagnosticMessages(
              /*details*/
              void 0,
              Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical,
              symbolToString(prop),
              typeName1,
              typeName2
            );
            errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
            diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(typeNode), typeNode, errorInfo));
          }
        }
      }
    }
    return ok;
  }
  function checkPropertyInitialization(node) {
    if (!strictNullChecks || !strictPropertyInitialization || node.flags & NodeFlags.Ambient) {
      return;
    }
    const constructor = findConstructorDeclaration(node);
    for (const member of node.members) {
      if (getEffectiveModifierFlags(member) & ModifierFlags.Ambient) {
        continue;
      }
      if (!isStatic(member) && isPropertyWithoutInitializer(member)) {
        const propName = member.name;
        if (isIdentifier(propName) || isPrivateIdentifier(propName) || isComputedPropertyName(propName)) {
          const type = getTypeOfSymbol(getSymbolOfDeclaration(member));
          if (!(type.flags & TypeFlags.AnyOrUnknown || containsUndefinedType(type))) {
            if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
              error(member.name, Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, declarationNameToString(propName));
            }
          }
        }
      }
    }
  }
  function isPropertyWithoutInitializer(node) {
    return node.kind === SyntaxKind.PropertyDeclaration && !hasAbstractModifier(node) && !node.exclamationToken && !node.initializer;
  }
  function isPropertyInitializedInStaticBlocks(propName, propType, staticBlocks, startPos, endPos) {
    for (const staticBlock of staticBlocks) {
      if (staticBlock.pos >= startPos && staticBlock.pos <= endPos) {
        const reference = factory.createPropertyAccessExpression(factory.createThis(), propName);
        setParent(reference.expression, reference);
        setParent(reference, staticBlock);
        reference.flowNode = staticBlock.returnFlowNode;
        const flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
        if (!containsUndefinedType(flowType)) {
          return true;
        }
      }
    }
    return false;
  }
  function isPropertyInitializedInConstructor(propName, propType, constructor) {
    const reference = isComputedPropertyName(propName) ? factory.createElementAccessExpression(factory.createThis(), propName.expression) : factory.createPropertyAccessExpression(factory.createThis(), propName);
    setParent(reference.expression, reference);
    setParent(reference, constructor);
    reference.flowNode = constructor.returnFlowNode;
    const flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
    return !containsUndefinedType(flowType);
  }
  function checkInterfaceDeclaration(node) {
    if (!checkGrammarModifiers(node)) checkGrammarInterfaceDeclaration(node);
    checkTypeParameters(node.typeParameters);
    addLazyDiagnostic(() => {
      checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0);
      checkExportsOnMergedDeclarations(node);
      const symbol = getSymbolOfDeclaration(node);
      checkTypeParameterListsIdentical(symbol);
      const firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration);
      if (node === firstInterfaceDecl) {
        const type = getDeclaredTypeOfSymbol(symbol);
        const typeWithThis = getTypeWithThisArgument(type);
        if (checkInheritedPropertiesAreIdentical(type, node.name)) {
          for (const baseType of getBaseTypes(type)) {
            checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, Diagnostics.Interface_0_incorrectly_extends_interface_1);
          }
          checkIndexConstraints(type, symbol);
        }
      }
      checkObjectTypeForDuplicateDeclarations(node);
    });
    forEach(getInterfaceBaseTypeNodes(node), (heritageElement) => {
      if (!isEntityNameExpression(heritageElement.expression) || isOptionalChain(heritageElement.expression)) {
        error(heritageElement.expression, Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
      }
      checkTypeReferenceNode(heritageElement);
    });
    forEach(node.members, checkSourceElement);
    addLazyDiagnostic(() => {
      checkTypeForDuplicateIndexSignatures(node);
      registerForUnusedIdentifiersCheck(node);
    });
  }
  function checkTypeAliasDeclaration(node) {
    checkGrammarModifiers(node);
    checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0);
    checkExportsOnMergedDeclarations(node);
    checkTypeParameters(node.typeParameters);
    if (node.type.kind === SyntaxKind.IntrinsicKeyword) {
      const typeParameterCount = length(node.typeParameters);
      const valid = typeParameterCount === 0 ? node.name.escapedText === "BuiltinIteratorReturn" : typeParameterCount === 1 && intrinsicTypeKinds.has(node.name.escapedText);
      if (!valid) {
        error(node.type, Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types);
      }
    } else {
      checkSourceElement(node.type);
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function computeEnumMemberValues(node) {
    const nodeLinks2 = getNodeLinks(node);
    if (!(nodeLinks2.flags & NodeCheckFlags.EnumValuesComputed)) {
      nodeLinks2.flags |= NodeCheckFlags.EnumValuesComputed;
      let autoValue = 0;
      let previous;
      for (const member of node.members) {
        const result = computeEnumMemberValue(member, autoValue, previous);
        getNodeLinks(member).enumMemberValue = result;
        autoValue = typeof result.value === "number" ? result.value + 1 : void 0;
        previous = member;
      }
    }
  }
  function computeEnumMemberValue(member, autoValue, previous) {
    if (isComputedNonLiteralName(member.name)) {
      error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums);
    } else {
      const text = getTextOfPropertyName(member.name);
      if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
        error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name);
      }
    }
    if (member.initializer) {
      return computeConstantEnumMemberValue(member);
    }
    if (member.parent.flags & NodeFlags.Ambient && !isEnumConst(member.parent)) {
      return evaluatorResult(
        /*value*/
        void 0
      );
    }
    if (autoValue === void 0) {
      error(member.name, Diagnostics.Enum_member_must_have_initializer);
      return evaluatorResult(
        /*value*/
        void 0
      );
    }
    if (getIsolatedModules(compilerOptions) && previous?.initializer) {
      const prevValue = getEnumMemberValue(previous);
      if (!(typeof prevValue.value === "number" && !prevValue.resolvedOtherFiles)) {
        error(
          member.name,
          Diagnostics.Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is_enabled
        );
      }
    }
    return evaluatorResult(autoValue);
  }
  function computeConstantEnumMemberValue(member) {
    const isConstEnum = isEnumConst(member.parent);
    const initializer = member.initializer;
    const result = evaluate(initializer, member);
    if (result.value !== void 0) {
      if (isConstEnum && typeof result.value === "number" && !isFinite(result.value)) {
        error(
          initializer,
          isNaN(result.value) ? Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value
        );
      } else if (getIsolatedModules(compilerOptions) && typeof result.value === "string" && !result.isSyntacticallyString) {
        error(
          initializer,
          Diagnostics._0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is_enabled,
          `${idText(member.parent.name)}.${getTextOfPropertyName(member.name)}`
        );
      }
    } else if (isConstEnum) {
      error(initializer, Diagnostics.const_enum_member_initializers_must_be_constant_expressions);
    } else if (member.parent.flags & NodeFlags.Ambient) {
      error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
    } else {
      checkTypeAssignableTo(checkExpression(initializer), numberType, initializer, Diagnostics.Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values);
    }
    return result;
  }
  function evaluateEntityNameExpression(expr, location) {
    const symbol = resolveEntityName(
      expr,
      SymbolFlags.Value,
      /*ignoreErrors*/
      true
    );
    if (!symbol) return evaluatorResult(
      /*value*/
      void 0
    );
    if (expr.kind === SyntaxKind.Identifier) {
      const identifier = expr;
      if (isInfinityOrNaNString(identifier.escapedText) && symbol === getGlobalSymbol(
        identifier.escapedText,
        SymbolFlags.Value,
        /*diagnostic*/
        void 0
      )) {
        return evaluatorResult(
          +identifier.escapedText,
          /*isSyntacticallyString*/
          false
        );
      }
    }
    if (symbol.flags & SymbolFlags.EnumMember) {
      return location ? evaluateEnumMember(expr, symbol, location) : getEnumMemberValue(symbol.valueDeclaration);
    }
    if (isConstantVariable(symbol)) {
      const declaration = symbol.valueDeclaration;
      if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && (!location || declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location))) {
        const result = evaluate(declaration.initializer, declaration);
        if (location && getSourceFileOfNode(location) !== getSourceFileOfNode(declaration)) {
          return evaluatorResult(
            result.value,
            /*isSyntacticallyString*/
            false,
            /*resolvedOtherFiles*/
            true,
            /*hasExternalReferences*/
            true
          );
        }
        return evaluatorResult(
          result.value,
          result.isSyntacticallyString,
          result.resolvedOtherFiles,
          /*hasExternalReferences*/
          true
        );
      }
    }
    return evaluatorResult(
      /*value*/
      void 0
    );
  }
  function evaluateElementAccessExpression(expr, location) {
    const root = expr.expression;
    if (isEntityNameExpression(root) && isStringLiteralLike(expr.argumentExpression)) {
      const rootSymbol = resolveEntityName(
        root,
        SymbolFlags.Value,
        /*ignoreErrors*/
        true
      );
      if (rootSymbol && rootSymbol.flags & SymbolFlags.Enum) {
        const name = escapeLeadingUnderscores(expr.argumentExpression.text);
        const member = rootSymbol.exports.get(name);
        if (member) {
          Debug.assert(getSourceFileOfNode(member.valueDeclaration) === getSourceFileOfNode(rootSymbol.valueDeclaration));
          return location ? evaluateEnumMember(expr, member, location) : getEnumMemberValue(member.valueDeclaration);
        }
      }
    }
    return evaluatorResult(
      /*value*/
      void 0
    );
  }
  function evaluateEnumMember(expr, symbol, location) {
    const declaration = symbol.valueDeclaration;
    if (!declaration || declaration === location) {
      error(expr, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(symbol));
      return evaluatorResult(
        /*value*/
        void 0
      );
    }
    if (!isBlockScopedNameDeclaredBeforeUse(declaration, location)) {
      error(expr, Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
      return evaluatorResult(
        /*value*/
        0
      );
    }
    const value = getEnumMemberValue(declaration);
    if (location.parent !== declaration.parent) {
      return evaluatorResult(
        value.value,
        value.isSyntacticallyString,
        value.resolvedOtherFiles,
        /*hasExternalReferences*/
        true
      );
    }
    return value;
  }
  function checkEnumDeclaration(node) {
    addLazyDiagnostic(() => checkEnumDeclarationWorker(node));
  }
  function checkEnumDeclarationWorker(node) {
    checkGrammarModifiers(node);
    checkCollisionsForDeclarationName(node, node.name);
    checkExportsOnMergedDeclarations(node);
    node.members.forEach(checkEnumMember);
    computeEnumMemberValues(node);
    const enumSymbol = getSymbolOfDeclaration(node);
    const firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind);
    if (node === firstDeclaration) {
      if (enumSymbol.declarations && enumSymbol.declarations.length > 1) {
        const enumIsConst = isEnumConst(node);
        forEach(enumSymbol.declarations, (decl) => {
          if (isEnumDeclaration(decl) && isEnumConst(decl) !== enumIsConst) {
            error(getNameOfDeclaration(decl), Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
          }
        });
      }
      let seenEnumMissingInitialInitializer = false;
      forEach(enumSymbol.declarations, (declaration) => {
        if (declaration.kind !== SyntaxKind.EnumDeclaration) {
          return false;
        }
        const enumDeclaration = declaration;
        if (!enumDeclaration.members.length) {
          return false;
        }
        const firstEnumMember = enumDeclaration.members[0];
        if (!firstEnumMember.initializer) {
          if (seenEnumMissingInitialInitializer) {
            error(firstEnumMember.name, Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
          } else {
            seenEnumMissingInitialInitializer = true;
          }
        }
      });
    }
  }
  function checkEnumMember(node) {
    if (isPrivateIdentifier(node.name)) {
      error(node, Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
    }
    if (node.initializer) {
      checkExpression(node.initializer);
    }
  }
  function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
    const declarations = symbol.declarations;
    if (declarations) {
      for (const declaration of declarations) {
        if ((declaration.kind === SyntaxKind.ClassDeclaration || declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent(declaration.body)) && !(declaration.flags & NodeFlags.Ambient)) {
          return declaration;
        }
      }
    }
    return void 0;
  }
  function inSameLexicalScope(node1, node2) {
    const container1 = getEnclosingBlockScopeContainer(node1);
    const container2 = getEnclosingBlockScopeContainer(node2);
    if (isGlobalSourceFile(container1)) {
      return isGlobalSourceFile(container2);
    } else if (isGlobalSourceFile(container2)) {
      return false;
    } else {
      return container1 === container2;
    }
  }
  function checkModuleDeclaration(node) {
    if (node.body) {
      checkSourceElement(node.body);
      if (!isGlobalScopeAugmentation(node)) {
        registerForUnusedIdentifiersCheck(node);
      }
    }
    addLazyDiagnostic(checkModuleDeclarationDiagnostics);
    function checkModuleDeclarationDiagnostics() {
      const isGlobalAugmentation = isGlobalScopeAugmentation(node);
      const inAmbientContext = node.flags & NodeFlags.Ambient;
      if (isGlobalAugmentation && !inAmbientContext) {
        error(node.name, Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
      }
      const isAmbientExternalModule = isAmbientModule(node);
      const contextErrorMessage = isAmbientExternalModule ? Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : Diagnostics.A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module;
      if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
        return;
      }
      if (!checkGrammarModifiers(node)) {
        if (!inAmbientContext && node.name.kind === SyntaxKind.StringLiteral) {
          grammarErrorOnNode(node.name, Diagnostics.Only_ambient_modules_can_use_quoted_names);
        }
      }
      if (isIdentifier(node.name)) {
        checkCollisionsForDeclarationName(node, node.name);
        if (!(node.flags & (NodeFlags.Namespace | NodeFlags.GlobalAugmentation))) {
          const sourceFile = getSourceFileOfNode(node);
          const pos = getNonModifierTokenPosOfNode(node);
          const span = getSpanOfTokenAtPosition(sourceFile, pos);
          suggestionDiagnostics.add(
            createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_keyword_instead)
          );
        }
      }
      checkExportsOnMergedDeclarations(node);
      const symbol = getSymbolOfDeclaration(node);
      if (symbol.flags & SymbolFlags.ValueModule && !inAmbientContext && isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions))) {
        if (getIsolatedModules(compilerOptions) && !getSourceFileOfNode(node).externalModuleIndicator) {
          error(node.name, Diagnostics.Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to_be_a_global_script_set_moduleDetection_to_force_or_add_an_empty_export_statement, isolatedModulesLikeFlagName);
        }
        if (symbol.declarations?.length > 1) {
          const firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
          if (firstNonAmbientClassOrFunc) {
            if (getSourceFileOfNode(node) !== getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
              error(node.name, Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
            } else if (node.pos < firstNonAmbientClassOrFunc.pos) {
              error(node.name, Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
            }
          }
          const mergedClass = getDeclarationOfKind(symbol, SyntaxKind.ClassDeclaration);
          if (mergedClass && inSameLexicalScope(node, mergedClass)) {
            getNodeLinks(node).flags |= NodeCheckFlags.LexicalModuleMergesWithClass;
          }
        }
        if (compilerOptions.verbatimModuleSyntax && node.parent.kind === SyntaxKind.SourceFile && host.getEmitModuleFormatOfFile(node.parent) === ModuleKind.CommonJS) {
          const exportModifier = node.modifiers?.find((m) => m.kind === SyntaxKind.ExportKeyword);
          if (exportModifier) {
            error(exportModifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
          }
        }
      }
      if (isAmbientExternalModule) {
        if (isExternalModuleAugmentation(node)) {
          const checkBody = isGlobalAugmentation || getSymbolOfDeclaration(node).flags & SymbolFlags.Transient;
          if (checkBody && node.body) {
            for (const statement of node.body.statements) {
              checkModuleAugmentationElement(statement, isGlobalAugmentation);
            }
          }
        } else if (isGlobalSourceFile(node.parent)) {
          if (isGlobalAugmentation) {
            error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
          } else if (isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(node.name))) {
            error(node.name, Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
          }
        } else {
          if (isGlobalAugmentation) {
            error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
          } else {
            error(node.name, Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
          }
        }
      }
    }
  }
  function checkModuleAugmentationElement(node, isGlobalAugmentation) {
    switch (node.kind) {
      case SyntaxKind.VariableStatement:
        for (const decl of node.declarationList.declarations) {
          checkModuleAugmentationElement(decl, isGlobalAugmentation);
        }
        break;
      case SyntaxKind.ExportAssignment:
      case SyntaxKind.ExportDeclaration:
        grammarErrorOnFirstToken(node, Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
        break;
      case SyntaxKind.ImportEqualsDeclaration:
        if (isInternalModuleImportEqualsDeclaration(node)) break;
      // falls through
      case SyntaxKind.ImportDeclaration:
        grammarErrorOnFirstToken(node, Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
        break;
      case SyntaxKind.BindingElement:
      case SyntaxKind.VariableDeclaration:
        const name = node.name;
        if (isBindingPattern(name)) {
          for (const el of name.elements) {
            checkModuleAugmentationElement(el, isGlobalAugmentation);
          }
          break;
        }
      // falls through
      case SyntaxKind.ClassDeclaration:
      case SyntaxKind.EnumDeclaration:
      case SyntaxKind.FunctionDeclaration:
      case SyntaxKind.InterfaceDeclaration:
      case SyntaxKind.ModuleDeclaration:
      case SyntaxKind.TypeAliasDeclaration:
        if (isGlobalAugmentation) {
          return;
        }
        break;
    }
  }
  function getFirstNonModuleExportsIdentifier(node) {
    switch (node.kind) {
      case SyntaxKind.Identifier:
        return node;
      case SyntaxKind.QualifiedName:
        do {
          node = node.left;
        } while (node.kind !== SyntaxKind.Identifier);
        return node;
      case SyntaxKind.PropertyAccessExpression:
        do {
          if (isModuleExportsAccessExpression(node.expression) && !isPrivateIdentifier(node.name)) {
            return node.name;
          }
          node = node.expression;
        } while (node.kind !== SyntaxKind.Identifier);
        return node;
    }
  }
  function checkExternalImportOrExportDeclaration(node) {
    const moduleName = getExternalModuleName(node);
    if (!moduleName || nodeIsMissing(moduleName)) {
      return false;
    }
    if (!isStringLiteral(moduleName)) {
      error(moduleName, Diagnostics.String_literal_expected);
      return false;
    }
    const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && isAmbientModule(node.parent.parent);
    if (node.parent.kind !== SyntaxKind.SourceFile && !inAmbientExternalModule) {
      error(
        moduleName,
        node.kind === SyntaxKind.ExportDeclaration ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module
      );
      return false;
    }
    if (inAmbientExternalModule && isExternalModuleNameRelative(moduleName.text)) {
      if (!isTopLevelInExternalModuleAugmentation(node)) {
        error(node, Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
        return false;
      }
    }
    if (!isImportEqualsDeclaration(node) && node.attributes) {
      const diagnostic = node.attributes.token === SyntaxKind.WithKeyword ? Diagnostics.Import_attribute_values_must_be_string_literal_expressions : Diagnostics.Import_assertion_values_must_be_string_literal_expressions;
      let hasError = false;
      for (const attr of node.attributes.elements) {
        if (!isStringLiteral(attr.value)) {
          hasError = true;
          error(attr.value, diagnostic);
        }
      }
      return !hasError;
    }
    return true;
  }
  function checkModuleExportName(name, allowStringLiteral = true) {
    if (name === void 0 || name.kind !== SyntaxKind.StringLiteral) {
      return;
    }
    if (!allowStringLiteral) {
      grammarErrorOnNode(name, Diagnostics.Identifier_expected);
    } else if (moduleKind === ModuleKind.ES2015 || moduleKind === ModuleKind.ES2020) {
      grammarErrorOnNode(name, Diagnostics.String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es2020);
    }
  }
  function checkAliasSymbol(node) {
    let symbol = getSymbolOfDeclaration(node);
    const target = resolveAlias(symbol);
    if (target !== unknownSymbol) {
      symbol = getMergedSymbol(symbol.exportSymbol || symbol);
      if (isInJSFile(node) && !(target.flags & SymbolFlags.Value) && !isTypeOnlyImportOrExportDeclaration(node)) {
        const errorNode = isImportOrExportSpecifier(node) ? node.propertyName || node.name : isNamedDeclaration(node) ? node.name : node;
        Debug.assert(node.kind !== SyntaxKind.NamespaceExport);
        if (node.kind === SyntaxKind.ExportSpecifier) {
          const diag = error(errorNode, Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files);
          const alreadyExportedSymbol = getSourceFileOfNode(node).symbol?.exports?.get(moduleExportNameTextEscaped(node.propertyName || node.name));
          if (alreadyExportedSymbol === target) {
            const exportingDeclaration = alreadyExportedSymbol.declarations?.find(isJSDocNode);
            if (exportingDeclaration) {
              addRelatedInfo(
                diag,
                createDiagnosticForNode(
                  exportingDeclaration,
                  Diagnostics._0_is_automatically_exported_here,
                  unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName)
                )
              );
            }
          }
        } else {
          Debug.assert(node.kind !== SyntaxKind.VariableDeclaration);
          const importDeclaration = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration));
          const moduleSpecifier = (importDeclaration && tryGetModuleSpecifierFromDeclaration(importDeclaration)?.text) ?? "...";
          const importedIdentifier = unescapeLeadingUnderscores(isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName);
          error(
            errorNode,
            Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation,
            importedIdentifier,
            `import("${moduleSpecifier}").${importedIdentifier}`
          );
        }
        return;
      }
      const targetFlags = getSymbolFlags(target);
      const excludedMeanings = (symbol.flags & (SymbolFlags.Value | SymbolFlags.ExportValue) ? SymbolFlags.Value : 0) | (symbol.flags & SymbolFlags.Type ? SymbolFlags.Type : 0) | (symbol.flags & SymbolFlags.Namespace ? SymbolFlags.Namespace : 0);
      if (targetFlags & excludedMeanings) {
        const message = node.kind === SyntaxKind.ExportSpecifier ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
        error(node, message, symbolToString(symbol));
      } else if (node.kind !== SyntaxKind.ExportSpecifier) {
        const appearsValueyToTranspiler = compilerOptions.isolatedModules && !findAncestor(node, isTypeOnlyImportOrExportDeclaration);
        if (appearsValueyToTranspiler && symbol.flags & (SymbolFlags.Value | SymbolFlags.ExportValue)) {
          error(
            node,
            Diagnostics.Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_is_enabled,
            symbolToString(symbol),
            isolatedModulesLikeFlagName
          );
        }
      }
      if (getIsolatedModules(compilerOptions) && !isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & NodeFlags.Ambient)) {
        const typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol);
        const isType = !(targetFlags & SymbolFlags.Value);
        if (isType || typeOnlyAlias) {
          switch (node.kind) {
            case SyntaxKind.ImportClause:
            case SyntaxKind.ImportSpecifier:
            case SyntaxKind.ImportEqualsDeclaration: {
              if (compilerOptions.verbatimModuleSyntax) {
                Debug.assertIsDefined(node.name, "An ImportClause with a symbol should have a name");
                const message = compilerOptions.verbatimModuleSyntax && isInternalModuleImportEqualsDeclaration(node) ? Diagnostics.An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabled : isType ? Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled;
                const name = moduleExportNameTextUnescaped(node.kind === SyntaxKind.ImportSpecifier ? node.propertyName || node.name : node.name);
                addTypeOnlyDeclarationRelatedInfo(
                  error(node, message, name),
                  isType ? void 0 : typeOnlyAlias,
                  name
                );
              }
              if (isType && node.kind === SyntaxKind.ImportEqualsDeclaration && hasEffectiveModifier(node, ModifierFlags.Export)) {
                error(node, Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled, isolatedModulesLikeFlagName);
              }
              break;
            }
            case SyntaxKind.ExportSpecifier: {
              if (compilerOptions.verbatimModuleSyntax || getSourceFileOfNode(typeOnlyAlias) !== getSourceFileOfNode(node)) {
                const name = moduleExportNameTextUnescaped(node.propertyName || node.name);
                const diagnostic = isType ? error(node, Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type, isolatedModulesLikeFlagName) : error(node, Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled, name, isolatedModulesLikeFlagName);
                addTypeOnlyDeclarationRelatedInfo(diagnostic, isType ? void 0 : typeOnlyAlias, name);
                break;
              }
            }
          }
        }
        if (compilerOptions.verbatimModuleSyntax && node.kind !== SyntaxKind.ImportEqualsDeclaration && !isInJSFile(node) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === ModuleKind.CommonJS) {
          error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
        } else if (moduleKind === ModuleKind.Preserve && node.kind !== SyntaxKind.ImportEqualsDeclaration && node.kind !== SyntaxKind.VariableDeclaration && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === ModuleKind.CommonJS) {
          error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve);
        }
        if (compilerOptions.verbatimModuleSyntax && !isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & NodeFlags.Ambient) && targetFlags & SymbolFlags.ConstEnum) {
          const constEnumDeclaration = target.valueDeclaration;
          const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(getSourceFileOfNode(constEnumDeclaration).resolvedPath);
          if (constEnumDeclaration.flags & NodeFlags.Ambient && (!redirect || !shouldPreserveConstEnums(redirect.commandLine.options))) {
            error(node, Diagnostics.Cannot_access_ambient_const_enums_when_0_is_enabled, isolatedModulesLikeFlagName);
          }
        }
      }
      if (isImportSpecifier(node)) {
        const targetSymbol = resolveAliasWithDeprecationCheck(symbol, node);
        if (isDeprecatedSymbol(targetSymbol) && targetSymbol.declarations) {
          addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName);
        }
      }
    }
  }
  function resolveAliasWithDeprecationCheck(symbol, location) {
    if (!(symbol.flags & SymbolFlags.Alias) || isDeprecatedSymbol(symbol) || !getDeclarationOfAliasSymbol(symbol)) {
      return symbol;
    }
    const targetSymbol = resolveAlias(symbol);
    if (targetSymbol === unknownSymbol) return targetSymbol;
    while (symbol.flags & SymbolFlags.Alias) {
      const target = getImmediateAliasedSymbol(symbol);
      if (target) {
        if (target === targetSymbol) break;
        if (target.declarations && length(target.declarations)) {
          if (isDeprecatedSymbol(target)) {
            addDeprecatedSuggestion(location, target.declarations, target.escapedName);
            break;
          } else {
            if (symbol === targetSymbol) break;
            symbol = target;
          }
        }
      } else {
        break;
      }
    }
    return targetSymbol;
  }
  function checkImportBinding(node) {
    checkCollisionsForDeclarationName(node, node.name);
    checkAliasSymbol(node);
    if (node.kind === SyntaxKind.ImportSpecifier) {
      checkModuleExportName(node.propertyName);
      if (moduleExportNameIsDefault(node.propertyName || node.name) && getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < ModuleKind.System) {
        checkExternalEmitHelpers(node, ExternalEmitHelpers.ImportDefault);
      }
    }
  }
  function checkImportAttributes(declaration) {
    const node = declaration.attributes;
    if (node) {
      const importAttributesType = getGlobalImportAttributesType(
        /*reportErrors*/
        true
      );
      if (importAttributesType !== emptyObjectType) {
        checkTypeAssignableTo(getTypeFromImportAttributes(node), getNullableType(importAttributesType, TypeFlags.Undefined), node);
      }
      const validForTypeAttributes = isExclusivelyTypeOnlyImportOrExport(declaration);
      const override = getResolutionModeOverride(node, validForTypeAttributes ? grammarErrorOnNode : void 0);
      const isImportAttributes2 = declaration.attributes.token === SyntaxKind.WithKeyword;
      if (validForTypeAttributes && override) {
        return;
      }
      const mode = moduleKind === ModuleKind.NodeNext && declaration.moduleSpecifier && getEmitSyntaxForModuleSpecifierExpression(declaration.moduleSpecifier);
      if (mode !== ModuleKind.ESNext && moduleKind !== ModuleKind.ESNext && moduleKind !== ModuleKind.Preserve) {
        const message = isImportAttributes2 ? moduleKind === ModuleKind.NodeNext ? Diagnostics.Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls : Diagnostics.Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_nodenext_or_preserve : moduleKind === ModuleKind.NodeNext ? Diagnostics.Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls : Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_nodenext_or_preserve;
        return grammarErrorOnNode(node, message);
      }
      const isTypeOnly = isJSDocImportTag(declaration) || (isImportDeclaration(declaration) ? declaration.importClause?.isTypeOnly : declaration.isTypeOnly);
      if (isTypeOnly) {
        return grammarErrorOnNode(node, isImportAttributes2 ? Diagnostics.Import_attributes_cannot_be_used_with_type_only_imports_or_exports : Diagnostics.Import_assertions_cannot_be_used_with_type_only_imports_or_exports);
      }
      if (override) {
        return grammarErrorOnNode(node, Diagnostics.resolution_mode_can_only_be_set_for_type_only_imports);
      }
    }
  }
  function checkImportAttribute(node) {
    return getRegularTypeOfLiteralType(checkExpressionCached(node.value));
  }
  function checkImportDeclaration(node) {
    if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) {
      return;
    }
    if (!checkGrammarModifiers(node) && node.modifiers) {
      grammarErrorOnFirstToken(node, Diagnostics.An_import_declaration_cannot_have_modifiers);
    }
    if (checkExternalImportOrExportDeclaration(node)) {
      const importClause = node.importClause;
      if (importClause && !checkGrammarImportClause(importClause)) {
        if (importClause.name) {
          checkImportBinding(importClause);
        }
        if (importClause.namedBindings) {
          if (importClause.namedBindings.kind === SyntaxKind.NamespaceImport) {
            checkImportBinding(importClause.namedBindings);
            if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < ModuleKind.System && getESModuleInterop(compilerOptions)) {
              checkExternalEmitHelpers(node, ExternalEmitHelpers.ImportStar);
            }
          } else {
            const moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
            if (moduleExisted) {
              forEach(importClause.namedBindings.elements, checkImportBinding);
            }
          }
        }
      } else if (noUncheckedSideEffectImports && !importClause) {
        void resolveExternalModuleName(node, node.moduleSpecifier);
      }
    }
    checkImportAttributes(node);
  }
  function checkImportEqualsDeclaration(node) {
    if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) {
      return;
    }
    checkGrammarModifiers(node);
    if (isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
      checkImportBinding(node);
      markLinkedReferences(node, 6 /* ExportImportEquals */);
      if (node.moduleReference.kind !== SyntaxKind.ExternalModuleReference) {
        const target = resolveAlias(getSymbolOfDeclaration(node));
        if (target !== unknownSymbol) {
          const targetFlags = getSymbolFlags(target);
          if (targetFlags & SymbolFlags.Value) {
            const moduleName = getFirstIdentifier(node.moduleReference);
            if (!(resolveEntityName(moduleName, SymbolFlags.Value | SymbolFlags.Namespace).flags & SymbolFlags.Namespace)) {
              error(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, declarationNameToString(moduleName));
            }
          }
          if (targetFlags & SymbolFlags.Type) {
            checkTypeNameIsReserved(node.name, Diagnostics.Import_name_cannot_be_0);
          }
        }
        if (node.isTypeOnly) {
          grammarErrorOnNode(node, Diagnostics.An_import_alias_cannot_use_import_type);
        }
      } else {
        if (ModuleKind.ES2015 <= moduleKind && moduleKind <= ModuleKind.ESNext && !node.isTypeOnly && !(node.flags & NodeFlags.Ambient)) {
          grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead);
        }
      }
    }
  }
  function checkExportDeclaration(node) {
    if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) {
      return;
    }
    if (!checkGrammarModifiers(node) && hasSyntacticModifiers(node)) {
      grammarErrorOnFirstToken(node, Diagnostics.An_export_declaration_cannot_have_modifiers);
    }
    checkGrammarExportDeclaration(node);
    if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
      if (node.exportClause && !isNamespaceExport(node.exportClause)) {
        forEach(node.exportClause.elements, checkExportSpecifier);
        const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && isAmbientModule(node.parent.parent);
        const inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === SyntaxKind.ModuleBlock && !node.moduleSpecifier && node.flags & NodeFlags.Ambient;
        if (node.parent.kind !== SyntaxKind.SourceFile && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
          error(node, Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
        }
      } else {
        const moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
        if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
          error(node.moduleSpecifier, Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
        } else if (node.exportClause) {
          checkAliasSymbol(node.exportClause);
          checkModuleExportName(node.exportClause.name);
        }
        if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < ModuleKind.System) {
          if (node.exportClause) {
            if (getESModuleInterop(compilerOptions)) {
              checkExternalEmitHelpers(node, ExternalEmitHelpers.ImportStar);
            }
          } else {
            checkExternalEmitHelpers(node, ExternalEmitHelpers.ExportStar);
          }
        }
      }
    }
    checkImportAttributes(node);
  }
  function checkGrammarExportDeclaration(node) {
    if (node.isTypeOnly && node.exportClause?.kind === SyntaxKind.NamedExports) {
      return checkGrammarNamedImportsOrExports(node.exportClause);
    }
    return false;
  }
  function checkGrammarModuleElementContext(node, errorMessage) {
    const isInAppropriateContext = node.parent.kind === SyntaxKind.SourceFile || node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.ModuleDeclaration;
    if (!isInAppropriateContext) {
      grammarErrorOnFirstToken(node, errorMessage);
    }
    return !isInAppropriateContext;
  }
  function checkExportSpecifier(node) {
    checkAliasSymbol(node);
    const hasModuleSpecifier = node.parent.parent.moduleSpecifier !== void 0;
    checkModuleExportName(node.propertyName, hasModuleSpecifier);
    checkModuleExportName(node.name);
    if (getEmitDeclarations(compilerOptions)) {
      collectLinkedAliases(
        node.propertyName || node.name,
        /*setVisibility*/
        true
      );
    }
    if (!hasModuleSpecifier) {
      const exportedName = node.propertyName || node.name;
      if (exportedName.kind === SyntaxKind.StringLiteral) {
        return;
      }
      const symbol = resolveName(
        exportedName,
        exportedName.escapedText,
        SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        true
      );
      if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
        error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName));
      } else {
        markLinkedReferences(node, 7 /* ExportSpecifier */);
      }
    } else {
      if (getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < ModuleKind.System && moduleExportNameIsDefault(node.propertyName || node.name)) {
        checkExternalEmitHelpers(node, ExternalEmitHelpers.ImportDefault);
      }
    }
  }
  function checkExportAssignment(node) {
    const illegalContextMessage = node.isExportEquals ? Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration : Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration;
    if (checkGrammarModuleElementContext(node, illegalContextMessage)) {
      return;
    }
    const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent;
    if (container.kind === SyntaxKind.ModuleDeclaration && !isAmbientModule(container)) {
      if (node.isExportEquals) {
        error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
      } else {
        error(node, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
      }
      return;
    }
    if (!checkGrammarModifiers(node) && hasEffectiveModifiers(node)) {
      grammarErrorOnFirstToken(node, Diagnostics.An_export_assignment_cannot_have_modifiers);
    }
    const typeAnnotationNode = getEffectiveTypeAnnotationNode(node);
    if (typeAnnotationNode) {
      checkTypeAssignableTo(checkExpressionCached(node.expression), getTypeFromTypeNode(typeAnnotationNode), node.expression);
    }
    const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & NodeFlags.Ambient) && compilerOptions.verbatimModuleSyntax && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === ModuleKind.CommonJS;
    if (node.expression.kind === SyntaxKind.Identifier) {
      const id = node.expression;
      const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName(
        id,
        SymbolFlags.All,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true,
        node
      ));
      if (sym) {
        markLinkedReferences(node, 3 /* ExportAssignment */);
        const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(sym, SymbolFlags.Value);
        if (getSymbolFlags(sym) & SymbolFlags.Value) {
          checkExpressionCached(id);
          if (!isIllegalExportDefaultInCJS && !(node.flags & NodeFlags.Ambient) && compilerOptions.verbatimModuleSyntax && typeOnlyDeclaration) {
            error(
              id,
              node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration : Diagnostics.An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration,
              idText(id)
            );
          }
        } else if (!isIllegalExportDefaultInCJS && !(node.flags & NodeFlags.Ambient) && compilerOptions.verbatimModuleSyntax) {
          error(
            id,
            node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type : Diagnostics.An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type,
            idText(id)
          );
        }
        if (!isIllegalExportDefaultInCJS && !(node.flags & NodeFlags.Ambient) && getIsolatedModules(compilerOptions) && !(sym.flags & SymbolFlags.Value)) {
          const nonLocalMeanings = getSymbolFlags(
            sym,
            /*excludeTypeOnlyMeanings*/
            false,
            /*excludeLocalMeanings*/
            true
          );
          if (sym.flags & SymbolFlags.Alias && nonLocalMeanings & SymbolFlags.Type && !(nonLocalMeanings & SymbolFlags.Value) && (!typeOnlyDeclaration || getSourceFileOfNode(typeOnlyDeclaration) !== getSourceFileOfNode(node))) {
            error(
              id,
              node.isExportEquals ? Diagnostics._0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_import_type_where_0_is_imported : Diagnostics._0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default,
              idText(id),
              isolatedModulesLikeFlagName
            );
          } else if (typeOnlyDeclaration && getSourceFileOfNode(typeOnlyDeclaration) !== getSourceFileOfNode(node)) {
            addTypeOnlyDeclarationRelatedInfo(
              error(
                id,
                node.isExportEquals ? Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_import_type_where_0_is_imported : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default,
                idText(id),
                isolatedModulesLikeFlagName
              ),
              typeOnlyDeclaration,
              idText(id)
            );
          }
        }
      } else {
        checkExpressionCached(id);
      }
      if (getEmitDeclarations(compilerOptions)) {
        collectLinkedAliases(
          id,
          /*setVisibility*/
          true
        );
      }
    } else {
      checkExpressionCached(node.expression);
    }
    if (isIllegalExportDefaultInCJS) {
      error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
    }
    checkExternalModuleExports(container);
    if (node.flags & NodeFlags.Ambient && !isEntityNameExpression(node.expression)) {
      grammarErrorOnNode(node.expression, Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
    }
    if (node.isExportEquals) {
      if (moduleKind >= ModuleKind.ES2015 && moduleKind !== ModuleKind.Preserve && (node.flags & NodeFlags.Ambient && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) === ModuleKind.ESNext || !(node.flags & NodeFlags.Ambient) && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) !== ModuleKind.CommonJS)) {
        grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
      } else if (moduleKind === ModuleKind.System && !(node.flags & NodeFlags.Ambient)) {
        grammarErrorOnNode(node, Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
      }
    }
  }
  function hasExportedMembers(moduleSymbol) {
    return forEachEntry(moduleSymbol.exports, (_, id) => id !== "export=");
  }
  function checkExternalModuleExports(node) {
    const moduleSymbol = getSymbolOfDeclaration(node);
    const links = getSymbolLinks(moduleSymbol);
    if (!links.exportsChecked) {
      const exportEqualsSymbol = moduleSymbol.exports.get("export=");
      if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
        const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
        if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !isInJSFile(declaration)) {
          error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
        }
      }
      const exports = getExportsOfModule(moduleSymbol);
      if (exports) {
        exports.forEach(({ declarations, flags }, id) => {
          if (id === "__export") {
            return;
          }
          if (flags & (SymbolFlags.Namespace | SymbolFlags.Enum)) {
            return;
          }
          const exportedDeclarationsCount = countWhere(declarations, and(isNotOverloadAndNotAccessor, not(isInterfaceDeclaration)));
          if (flags & SymbolFlags.TypeAlias && exportedDeclarationsCount <= 2) {
            return;
          }
          if (exportedDeclarationsCount > 1) {
            if (!isDuplicatedCommonJSExport(declarations)) {
              for (const declaration of declarations) {
                if (isNotOverload(declaration)) {
                  diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Cannot_redeclare_exported_variable_0, unescapeLeadingUnderscores(id)));
                }
              }
            }
          }
        });
      }
      links.exportsChecked = true;
    }
  }
  function isDuplicatedCommonJSExport(declarations) {
    return declarations && declarations.length > 1 && declarations.every((d) => isInJSFile(d) && isAccessExpression(d) && (isExportsIdentifier(d.expression) || isModuleExportsAccessExpression(d.expression)));
  }
  function checkSourceElement(node) {
    if (node) {
      const saveCurrentNode = currentNode;
      currentNode = node;
      instantiationCount = 0;
      checkSourceElementWorker(node);
      currentNode = saveCurrentNode;
    }
  }
  function checkSourceElementWorker(node) {
    if (getNodeCheckFlags(node) & NodeCheckFlags.PartiallyTypeChecked) {
      return;
    }
    if (canHaveJSDoc(node)) {
      forEach(node.jsDoc, ({ comment, tags }) => {
        checkJSDocCommentWorker(comment);
        forEach(tags, (tag) => {
          checkJSDocCommentWorker(tag.comment);
          if (isInJSFile(node)) {
            checkSourceElement(tag);
          }
        });
      });
    }
    const kind = node.kind;
    if (cancellationToken) {
      switch (kind) {
        case SyntaxKind.ModuleDeclaration:
        case SyntaxKind.ClassDeclaration:
        case SyntaxKind.InterfaceDeclaration:
        case SyntaxKind.FunctionDeclaration:
          cancellationToken.throwIfCancellationRequested();
      }
    }
    if (kind >= SyntaxKind.FirstStatement && kind <= SyntaxKind.LastStatement && canHaveFlowNode(node) && node.flowNode && !isReachableFlowNode(node.flowNode)) {
      errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, Diagnostics.Unreachable_code_detected);
    }
    switch (kind) {
      case SyntaxKind.TypeParameter:
        return checkTypeParameter(node);
      case SyntaxKind.Parameter:
        return checkParameter(node);
      case SyntaxKind.PropertyDeclaration:
        return checkPropertyDeclaration(node);
      case SyntaxKind.PropertySignature:
        return checkPropertySignature(node);
      case SyntaxKind.ConstructorType:
      case SyntaxKind.FunctionType:
      case SyntaxKind.CallSignature:
      case SyntaxKind.ConstructSignature:
      case SyntaxKind.IndexSignature:
        return checkSignatureDeclaration(node);
      case SyntaxKind.MethodDeclaration:
      case SyntaxKind.MethodSignature:
        return checkMethodDeclaration(node);
      case SyntaxKind.ClassStaticBlockDeclaration:
        return checkClassStaticBlockDeclaration(node);
      case SyntaxKind.Constructor:
        return checkConstructorDeclaration(node);
      case SyntaxKind.GetAccessor:
      case SyntaxKind.SetAccessor:
        return checkAccessorDeclaration(node);
      case SyntaxKind.TypeReference:
        return checkTypeReferenceNode(node);
      case SyntaxKind.TypePredicate:
        return checkTypePredicate(node);
      case SyntaxKind.TypeQuery:
        return checkTypeQuery(node);
      case SyntaxKind.TypeLiteral:
        return checkTypeLiteral(node);
      case SyntaxKind.ArrayType:
        return checkArrayType(node);
      case SyntaxKind.TupleType:
        return checkTupleType(node);
      case SyntaxKind.UnionType:
      case SyntaxKind.IntersectionType:
        return checkUnionOrIntersectionType(node);
      case SyntaxKind.ParenthesizedType:
      case SyntaxKind.OptionalType:
      case SyntaxKind.RestType:
        return checkSourceElement(node.type);
      case SyntaxKind.ThisType:
        return checkThisType(node);
      case SyntaxKind.TypeOperator:
        return checkTypeOperator(node);
      case SyntaxKind.ConditionalType:
        return checkConditionalType(node);
      case SyntaxKind.InferType:
        return checkInferType(node);
      case SyntaxKind.TemplateLiteralType:
        return checkTemplateLiteralType(node);
      case SyntaxKind.ImportType:
        return checkImportType(node);
      case SyntaxKind.NamedTupleMember:
        return checkNamedTupleMember(node);
      case SyntaxKind.JSDocAugmentsTag:
        return checkJSDocAugmentsTag(node);
      case SyntaxKind.JSDocImplementsTag:
        return checkJSDocImplementsTag(node);
      case SyntaxKind.JSDocTypedefTag:
      case SyntaxKind.JSDocCallbackTag:
      case SyntaxKind.JSDocEnumTag:
        return checkJSDocTypeAliasTag(node);
      case SyntaxKind.JSDocTemplateTag:
        return checkJSDocTemplateTag(node);
      case SyntaxKind.JSDocTypeTag:
        return checkJSDocTypeTag(node);
      case SyntaxKind.JSDocLink:
      case SyntaxKind.JSDocLinkCode:
      case SyntaxKind.JSDocLinkPlain:
        return checkJSDocLinkLikeTag(node);
      case SyntaxKind.JSDocParameterTag:
        return checkJSDocParameterTag(node);
      case SyntaxKind.JSDocPropertyTag:
        return checkJSDocPropertyTag(node);
      case SyntaxKind.JSDocFunctionType:
        checkJSDocFunctionType(node);
      // falls through
      case SyntaxKind.JSDocNonNullableType:
      case SyntaxKind.JSDocNullableType:
      case SyntaxKind.JSDocAllType:
      case SyntaxKind.JSDocUnknownType:
      case SyntaxKind.JSDocTypeLiteral:
        checkJSDocTypeIsInJsFile(node);
        forEachChild(node, checkSourceElement);
        return;
      case SyntaxKind.JSDocVariadicType:
        checkJSDocVariadicType(node);
        return;
      case SyntaxKind.JSDocTypeExpression:
        return checkSourceElement(node.type);
      case SyntaxKind.JSDocPublicTag:
      case SyntaxKind.JSDocProtectedTag:
      case SyntaxKind.JSDocPrivateTag:
        return checkJSDocAccessibilityModifiers(node);
      case SyntaxKind.JSDocSatisfiesTag:
        return checkJSDocSatisfiesTag(node);
      case SyntaxKind.JSDocThisTag:
        return checkJSDocThisTag(node);
      case SyntaxKind.JSDocImportTag:
        return checkJSDocImportTag(node);
      case SyntaxKind.IndexedAccessType:
        return checkIndexedAccessType(node);
      case SyntaxKind.MappedType:
        return checkMappedType(node);
      case SyntaxKind.FunctionDeclaration:
        return checkFunctionDeclaration(node);
      case SyntaxKind.Block:
      case SyntaxKind.ModuleBlock:
        return checkBlock(node);
      case SyntaxKind.VariableStatement:
        return checkVariableStatement(node);
      case SyntaxKind.ExpressionStatement:
        return checkExpressionStatement(node);
      case SyntaxKind.IfStatement:
        return checkIfStatement(node);
      case SyntaxKind.DoStatement:
        return checkDoStatement(node);
      case SyntaxKind.WhileStatement:
        return checkWhileStatement(node);
      case SyntaxKind.ForStatement:
        return checkForStatement(node);
      case SyntaxKind.ForInStatement:
        return checkForInStatement(node);
      case SyntaxKind.ForOfStatement:
        return checkForOfStatement(node);
      case SyntaxKind.ContinueStatement:
      case SyntaxKind.BreakStatement:
        return checkBreakOrContinueStatement(node);
      case SyntaxKind.ReturnStatement:
        return checkReturnStatement(node);
      case SyntaxKind.WithStatement:
        return checkWithStatement(node);
      case SyntaxKind.SwitchStatement:
        return checkSwitchStatement(node);
      case SyntaxKind.LabeledStatement:
        return checkLabeledStatement(node);
      case SyntaxKind.ThrowStatement:
        return checkThrowStatement(node);
      case SyntaxKind.TryStatement:
        return checkTryStatement(node);
      case SyntaxKind.VariableDeclaration:
        return checkVariableDeclaration(node);
      case SyntaxKind.BindingElement:
        return checkBindingElement(node);
      case SyntaxKind.ClassDeclaration:
        return checkClassDeclaration(node);
      case SyntaxKind.InterfaceDeclaration:
        return checkInterfaceDeclaration(node);
      case SyntaxKind.TypeAliasDeclaration:
        return checkTypeAliasDeclaration(node);
      case SyntaxKind.EnumDeclaration:
        return checkEnumDeclaration(node);
      case SyntaxKind.ModuleDeclaration:
        return checkModuleDeclaration(node);
      case SyntaxKind.ImportDeclaration:
        return checkImportDeclaration(node);
      case SyntaxKind.ImportEqualsDeclaration:
        return checkImportEqualsDeclaration(node);
      case SyntaxKind.ExportDeclaration:
        return checkExportDeclaration(node);
      case SyntaxKind.ExportAssignment:
        return checkExportAssignment(node);
      case SyntaxKind.EmptyStatement:
      case SyntaxKind.DebuggerStatement:
        checkGrammarStatementInAmbientContext(node);
        return;
      case SyntaxKind.MissingDeclaration:
        return checkMissingDeclaration(node);
    }
  }
  function checkJSDocCommentWorker(node) {
    if (isArray(node)) {
      forEach(node, (tag) => {
        if (isJSDocLinkLike(tag)) {
          checkSourceElement(tag);
        }
      });
    }
  }
  function checkJSDocTypeIsInJsFile(node) {
    if (!isInJSFile(node)) {
      if (isJSDocNonNullableType(node) || isJSDocNullableType(node)) {
        const token = tokenToString(isJSDocNonNullableType(node) ? SyntaxKind.ExclamationToken : SyntaxKind.QuestionToken);
        const diagnostic = node.postfix ? Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1 : Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1;
        const typeNode = node.type;
        const type = getTypeFromTypeNode(typeNode);
        grammarErrorOnNode(
          node,
          diagnostic,
          token,
          typeToString(
            isJSDocNullableType(node) && !(type === neverType || type === voidType) ? getUnionType(append([type, undefinedType], node.postfix ? void 0 : nullType)) : type
          )
        );
      } else {
        grammarErrorOnNode(node, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
      }
    }
  }
  function checkJSDocVariadicType(node) {
    checkJSDocTypeIsInJsFile(node);
    checkSourceElement(node.type);
    const { parent } = node;
    if (isParameter(parent) && isJSDocFunctionType(parent.parent)) {
      if (last(parent.parent.parameters) !== parent) {
        error(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
      }
      return;
    }
    if (!isJSDocTypeExpression(parent)) {
      error(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
    }
    const paramTag = node.parent.parent;
    if (!isJSDocParameterTag(paramTag)) {
      error(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
      return;
    }
    const param = getParameterSymbolFromJSDoc(paramTag);
    if (!param) {
      return;
    }
    const host2 = getHostSignatureFromJSDoc(paramTag);
    if (!host2 || last(host2.parameters).symbol !== param) {
      error(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
    }
  }
  function getTypeFromJSDocVariadicType(node) {
    const type = getTypeFromTypeNode(node.type);
    const { parent } = node;
    const paramTag = node.parent.parent;
    if (isJSDocTypeExpression(node.parent) && isJSDocParameterTag(paramTag)) {
      const host2 = getHostSignatureFromJSDoc(paramTag);
      const isCallbackTag = isJSDocCallbackTag(paramTag.parent.parent);
      if (host2 || isCallbackTag) {
        const lastParamDeclaration = isCallbackTag ? lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) : lastOrUndefined(host2.parameters);
        const symbol = getParameterSymbolFromJSDoc(paramTag);
        if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && isRestParameter(lastParamDeclaration)) {
          return createArrayType(type);
        }
      }
    }
    if (isParameter(parent) && isJSDocFunctionType(parent.parent)) {
      return createArrayType(type);
    }
    return addOptionality(type);
  }
  function checkNodeDeferred(node) {
    const enclosingFile = getSourceFileOfNode(node);
    const links = getNodeLinks(enclosingFile);
    if (!(links.flags & NodeCheckFlags.TypeChecked)) {
      links.deferredNodes ||= /* @__PURE__ */ new Set();
      links.deferredNodes.add(node);
    } else {
      Debug.assert(!links.deferredNodes, "A type-checked file should have no deferred nodes.");
    }
  }
  function checkDeferredNodes(context) {
    const links = getNodeLinks(context);
    if (links.deferredNodes) {
      links.deferredNodes.forEach(checkDeferredNode);
    }
    links.deferredNodes = void 0;
  }
  function checkDeferredNode(node) {
    tracing?.push(tracing.Phase.Check, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath });
    const saveCurrentNode = currentNode;
    currentNode = node;
    instantiationCount = 0;
    switch (node.kind) {
      case SyntaxKind.CallExpression:
      case SyntaxKind.NewExpression:
      case SyntaxKind.TaggedTemplateExpression:
      case SyntaxKind.Decorator:
      case SyntaxKind.JsxOpeningElement:
        resolveUntypedCall(node);
        break;
      case SyntaxKind.FunctionExpression:
      case SyntaxKind.ArrowFunction:
      case SyntaxKind.MethodDeclaration:
      case SyntaxKind.MethodSignature:
        checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
        break;
      case SyntaxKind.GetAccessor:
      case SyntaxKind.SetAccessor:
        checkAccessorDeclaration(node);
        break;
      case SyntaxKind.ClassExpression:
        checkClassExpressionDeferred(node);
        break;
      case SyntaxKind.TypeParameter:
        checkTypeParameterDeferred(node);
        break;
      case SyntaxKind.JsxSelfClosingElement:
        checkJsxSelfClosingElementDeferred(node);
        break;
      case SyntaxKind.JsxElement:
        checkJsxElementDeferred(node);
        break;
      case SyntaxKind.TypeAssertionExpression:
      case SyntaxKind.AsExpression:
      case SyntaxKind.ParenthesizedExpression:
        checkAssertionDeferred(node);
        break;
      case SyntaxKind.VoidExpression:
        checkExpression(node.expression);
        break;
      case SyntaxKind.BinaryExpression:
        if (isInstanceOfExpression(node)) {
          resolveUntypedCall(node);
        }
        break;
    }
    currentNode = saveCurrentNode;
    tracing?.pop();
  }
  function checkSourceFile(node, nodesToCheck) {
    tracing?.push(
      tracing.Phase.Check,
      nodesToCheck ? "checkSourceFileNodes" : "checkSourceFile",
      { path: node.path },
      /*separateBeginAndEnd*/
      true
    );
    const beforeMark = nodesToCheck ? "beforeCheckNodes" : "beforeCheck";
    const afterMark = nodesToCheck ? "afterCheckNodes" : "afterCheck";
    performance.mark(beforeMark);
    nodesToCheck ? checkSourceFileNodesWorker(node, nodesToCheck) : checkSourceFileWorker(node);
    performance.mark(afterMark);
    performance.measure("Check", beforeMark, afterMark);
    tracing?.pop();
  }
  function unusedIsError(kind, isAmbient) {
    if (isAmbient) {
      return false;
    }
    switch (kind) {
      case 0 /* Local */:
        return !!compilerOptions.noUnusedLocals;
      case 1 /* Parameter */:
        return !!compilerOptions.noUnusedParameters;
      default:
        return Debug.assertNever(kind);
    }
  }
  function getPotentiallyUnusedIdentifiers(sourceFile) {
    return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || emptyArray;
  }
  function checkSourceFileWorker(node) {
    const links = getNodeLinks(node);
    if (!(links.flags & NodeCheckFlags.TypeChecked)) {
      if (skipTypeChecking(node, compilerOptions, host)) {
        return;
      }
      checkGrammarSourceFile(node);
      clear(potentialThisCollisions);
      clear(potentialNewTargetCollisions);
      clear(potentialWeakMapSetCollisions);
      clear(potentialReflectCollisions);
      clear(potentialUnusedRenamedBindingElementsInTypes);
      if (links.flags & NodeCheckFlags.PartiallyTypeChecked) {
        potentialThisCollisions = links.potentialThisCollisions;
        potentialNewTargetCollisions = links.potentialNewTargetCollisions;
        potentialWeakMapSetCollisions = links.potentialWeakMapSetCollisions;
        potentialReflectCollisions = links.potentialReflectCollisions;
        potentialUnusedRenamedBindingElementsInTypes = links.potentialUnusedRenamedBindingElementsInTypes;
      }
      forEach(node.statements, checkSourceElement);
      checkSourceElement(node.endOfFileToken);
      checkDeferredNodes(node);
      if (isExternalOrCommonJsModule(node)) {
        registerForUnusedIdentifiersCheck(node);
      }
      addLazyDiagnostic(() => {
        if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
          checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), (containingNode, kind, diag) => {
            if (!containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & NodeFlags.Ambient))) {
              diagnostics.add(diag);
            }
          });
        }
        if (!node.isDeclarationFile) {
          checkPotentialUncheckedRenamedBindingElementsInTypes();
        }
      });
      if (isExternalOrCommonJsModule(node)) {
        checkExternalModuleExports(node);
      }
      if (potentialThisCollisions.length) {
        forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
        clear(potentialThisCollisions);
      }
      if (potentialNewTargetCollisions.length) {
        forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
        clear(potentialNewTargetCollisions);
      }
      if (potentialWeakMapSetCollisions.length) {
        forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision);
        clear(potentialWeakMapSetCollisions);
      }
      if (potentialReflectCollisions.length) {
        forEach(potentialReflectCollisions, checkReflectCollision);
        clear(potentialReflectCollisions);
      }
      links.flags |= NodeCheckFlags.TypeChecked;
    }
  }
  function checkSourceFileNodesWorker(file, nodes) {
    const links = getNodeLinks(file);
    if (!(links.flags & NodeCheckFlags.TypeChecked)) {
      if (skipTypeChecking(file, compilerOptions, host)) {
        return;
      }
      checkGrammarSourceFile(file);
      clear(potentialThisCollisions);
      clear(potentialNewTargetCollisions);
      clear(potentialWeakMapSetCollisions);
      clear(potentialReflectCollisions);
      clear(potentialUnusedRenamedBindingElementsInTypes);
      forEach(nodes, checkSourceElement);
      checkDeferredNodes(file);
      (links.potentialThisCollisions || (links.potentialThisCollisions = [])).push(...potentialThisCollisions);
      (links.potentialNewTargetCollisions || (links.potentialNewTargetCollisions = [])).push(...potentialNewTargetCollisions);
      (links.potentialWeakMapSetCollisions || (links.potentialWeakMapSetCollisions = [])).push(...potentialWeakMapSetCollisions);
      (links.potentialReflectCollisions || (links.potentialReflectCollisions = [])).push(...potentialReflectCollisions);
      (links.potentialUnusedRenamedBindingElementsInTypes || (links.potentialUnusedRenamedBindingElementsInTypes = [])).push(
        ...potentialUnusedRenamedBindingElementsInTypes
      );
      links.flags |= NodeCheckFlags.PartiallyTypeChecked;
      for (const node of nodes) {
        const nodeLinks2 = getNodeLinks(node);
        nodeLinks2.flags |= NodeCheckFlags.PartiallyTypeChecked;
      }
    }
  }
  function getDiagnostics(sourceFile, ct, nodesToCheck) {
    try {
      cancellationToken = ct;
      return getDiagnosticsWorker(sourceFile, nodesToCheck);
    } finally {
      cancellationToken = void 0;
    }
  }
  function ensurePendingDiagnosticWorkComplete() {
    for (const cb of deferredDiagnosticsCallbacks) {
      cb();
    }
    deferredDiagnosticsCallbacks = [];
  }
  function checkSourceFileWithEagerDiagnostics(sourceFile, nodesToCheck) {
    ensurePendingDiagnosticWorkComplete();
    const oldAddLazyDiagnostics = addLazyDiagnostic;
    addLazyDiagnostic = (cb) => cb();
    checkSourceFile(sourceFile, nodesToCheck);
    addLazyDiagnostic = oldAddLazyDiagnostics;
  }
  function getDiagnosticsWorker(sourceFile, nodesToCheck) {
    if (sourceFile) {
      ensurePendingDiagnosticWorkComplete();
      const previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
      const previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
      checkSourceFileWithEagerDiagnostics(sourceFile, nodesToCheck);
      const semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
      if (nodesToCheck) {
        return semanticDiagnostics;
      }
      const currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
      if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
        const deferredGlobalDiagnostics = relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, compareDiagnostics);
        return concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
      } else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
        return concatenate(currentGlobalDiagnostics, semanticDiagnostics);
      }
      return semanticDiagnostics;
    }
    forEach(host.getSourceFiles(), (file) => checkSourceFileWithEagerDiagnostics(file));
    return diagnostics.getDiagnostics();
  }
  function getGlobalDiagnostics() {
    ensurePendingDiagnosticWorkComplete();
    return diagnostics.getGlobalDiagnostics();
  }
  function getSymbolsInScope(location, meaning) {
    if (location.flags & NodeFlags.InWithStatement) {
      return [];
    }
    const symbols = createSymbolTable();
    let isStaticSymbol = false;
    populateSymbols();
    symbols.delete(InternalSymbolName.This);
    return symbolsToArray(symbols);
    function populateSymbols() {
      while (location) {
        if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) {
          copySymbols(location.locals, meaning);
        }
        switch (location.kind) {
          case SyntaxKind.SourceFile:
            if (!isExternalModule(location)) break;
          // falls through
          case SyntaxKind.ModuleDeclaration:
            copyLocallyVisibleExportSymbols(getSymbolOfDeclaration(location).exports, meaning & SymbolFlags.ModuleMember);
            break;
          case SyntaxKind.EnumDeclaration:
            copySymbols(getSymbolOfDeclaration(location).exports, meaning & SymbolFlags.EnumMember);
            break;
          case SyntaxKind.ClassExpression:
            const className = location.name;
            if (className) {
              copySymbol(location.symbol, meaning);
            }
          // this fall-through is necessary because we would like to handle
          // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
          // falls through
          case SyntaxKind.ClassDeclaration:
          case SyntaxKind.InterfaceDeclaration:
            if (!isStaticSymbol) {
              copySymbols(getMembersOfSymbol(getSymbolOfDeclaration(location)), meaning & SymbolFlags.Type);
            }
            break;
          case SyntaxKind.FunctionExpression:
            const funcName = location.name;
            if (funcName) {
              copySymbol(location.symbol, meaning);
            }
            break;
        }
        if (introducesArgumentsExoticObject(location)) {
          copySymbol(argumentsSymbol, meaning);
        }
        isStaticSymbol = isStatic(location);
        location = location.parent;
      }
      copySymbols(globals, meaning);
    }
    function copySymbol(symbol, meaning2) {
      if (getCombinedLocalAndExportSymbolFlags(symbol) & meaning2) {
        const id = symbol.escapedName;
        if (!symbols.has(id)) {
          symbols.set(id, symbol);
        }
      }
    }
    function copySymbols(source, meaning2) {
      if (meaning2) {
        source.forEach((symbol) => {
          copySymbol(symbol, meaning2);
        });
      }
    }
    function copyLocallyVisibleExportSymbols(source, meaning2) {
      if (meaning2) {
        source.forEach((symbol) => {
          if (!getDeclarationOfKind(symbol, SyntaxKind.ExportSpecifier) && !getDeclarationOfKind(symbol, SyntaxKind.NamespaceExport) && symbol.escapedName !== InternalSymbolName.Default) {
            copySymbol(symbol, meaning2);
          }
        });
      }
    }
  }
  function isTypeDeclarationName(name) {
    return name.kind === SyntaxKind.Identifier && isTypeDeclaration(name.parent) && getNameOfDeclaration(name.parent) === name;
  }
  function isTypeReferenceIdentifier(node) {
    while (node.parent.kind === SyntaxKind.QualifiedName) {
      node = node.parent;
    }
    return node.parent.kind === SyntaxKind.TypeReference;
  }
  function isInNameOfExpressionWithTypeArguments(node) {
    while (node.parent.kind === SyntaxKind.PropertyAccessExpression) {
      node = node.parent;
    }
    return node.parent.kind === SyntaxKind.ExpressionWithTypeArguments;
  }
  function forEachEnclosingClass(node, callback) {
    let result;
    let containingClass = getContainingClass(node);
    while (containingClass) {
      if (result = callback(containingClass)) break;
      containingClass = getContainingClass(containingClass);
    }
    return result;
  }
  function isNodeUsedDuringClassInitialization(node) {
    return !!findAncestor(node, (element) => {
      if (isConstructorDeclaration(element) && nodeIsPresent(element.body) || isPropertyDeclaration(element)) {
        return true;
      } else if (isClassLike(element) || isFunctionLikeDeclaration(element)) {
        return "quit";
      }
      return false;
    });
  }
  function isNodeWithinClass(node, classDeclaration) {
    return !!forEachEnclosingClass(node, (n) => n === classDeclaration);
  }
  function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
    while (nodeOnRightSide.parent.kind === SyntaxKind.QualifiedName) {
      nodeOnRightSide = nodeOnRightSide.parent;
    }
    if (nodeOnRightSide.parent.kind === SyntaxKind.ImportEqualsDeclaration) {
      return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : void 0;
    }
    if (nodeOnRightSide.parent.kind === SyntaxKind.ExportAssignment) {
      return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : void 0;
    }
    return void 0;
  }
  function isInRightSideOfImportOrExportAssignment(node) {
    return getLeftSideOfImportEqualsOrExportAssignment(node) !== void 0;
  }
  function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
    const specialPropertyAssignmentKind = getAssignmentDeclarationKind(entityName.parent.parent);
    switch (specialPropertyAssignmentKind) {
      case AssignmentDeclarationKind.ExportsProperty:
      case AssignmentDeclarationKind.PrototypeProperty:
        return getSymbolOfNode(entityName.parent);
      case AssignmentDeclarationKind.Property:
        if (isPropertyAccessExpression(entityName.parent) && getLeftmostAccessExpression(entityName.parent) === entityName) {
          return void 0;
        }
      // falls through
      case AssignmentDeclarationKind.ThisProperty:
      case AssignmentDeclarationKind.ModuleExports:
        return getSymbolOfDeclaration(entityName.parent.parent);
    }
  }
  function isImportTypeQualifierPart(node) {
    let parent = node.parent;
    while (isQualifiedName(parent)) {
      node = parent;
      parent = parent.parent;
    }
    if (parent && parent.kind === SyntaxKind.ImportType && parent.qualifier === node) {
      return parent;
    }
    return void 0;
  }
  function isThisPropertyAndThisTyped(node) {
    if (node.expression.kind === SyntaxKind.ThisKeyword) {
      const container = getThisContainer(
        node,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      );
      if (isFunctionLike(container)) {
        const containingLiteral = getContainingObjectLiteral(container);
        if (containingLiteral) {
          const contextualType = getApparentTypeOfContextualType(
            containingLiteral,
            /*contextFlags*/
            void 0
          );
          const type = getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType);
          return type && !isTypeAny(type);
        }
      }
    }
  }
  function getSymbolOfNameOrPropertyAccessExpression(name) {
    if (isDeclarationName(name)) {
      return getSymbolOfNode(name.parent);
    }
    if (isInJSFile(name) && name.parent.kind === SyntaxKind.PropertyAccessExpression && name.parent === name.parent.parent.left) {
      if (!isPrivateIdentifier(name) && !isJSDocMemberName(name) && !isThisPropertyAndThisTyped(name.parent)) {
        const specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
        if (specialPropertyAssignmentSymbol) {
          return specialPropertyAssignmentSymbol;
        }
      }
    }
    if (name.parent.kind === SyntaxKind.ExportAssignment && isEntityNameExpression(name)) {
      const success = resolveEntityName(
        name,
        /*all meanings*/
        SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias,
        /*ignoreErrors*/
        true
      );
      if (success && success !== unknownSymbol) {
        return success;
      }
    } else if (isEntityName(name) && isInRightSideOfImportOrExportAssignment(name)) {
      const importEqualsDeclaration = getAncestor(name, SyntaxKind.ImportEqualsDeclaration);
      Debug.assert(importEqualsDeclaration !== void 0);
      return getSymbolOfPartOfRightHandSideOfImportEquals(
        name,
        /*dontResolveAlias*/
        true
      );
    }
    if (isEntityName(name)) {
      const possibleImportNode = isImportTypeQualifierPart(name);
      if (possibleImportNode) {
        getTypeFromTypeNode(possibleImportNode);
        const sym = getNodeLinks(name).resolvedSymbol;
        return sym === unknownSymbol ? void 0 : sym;
      }
    }
    while (isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(name)) {
      name = name.parent;
    }
    if (isInNameOfExpressionWithTypeArguments(name)) {
      let meaning = SymbolFlags.None;
      if (name.parent.kind === SyntaxKind.ExpressionWithTypeArguments) {
        meaning = isPartOfTypeNode(name) ? SymbolFlags.Type : SymbolFlags.Value;
        if (isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
          meaning |= SymbolFlags.Value;
        }
      } else {
        meaning = SymbolFlags.Namespace;
      }
      meaning |= SymbolFlags.Alias;
      const entityNameSymbol = isEntityNameExpression(name) ? resolveEntityName(
        name,
        meaning,
        /*ignoreErrors*/
        true
      ) : void 0;
      if (entityNameSymbol) {
        return entityNameSymbol;
      }
    }
    if (name.parent.kind === SyntaxKind.JSDocParameterTag) {
      return getParameterSymbolFromJSDoc(name.parent);
    }
    if (name.parent.kind === SyntaxKind.TypeParameter && name.parent.parent.kind === SyntaxKind.JSDocTemplateTag) {
      Debug.assert(!isInJSFile(name));
      const typeParameter = getTypeParameterFromJsDoc(name.parent);
      return typeParameter && typeParameter.symbol;
    }
    if (isExpressionNode(name)) {
      if (nodeIsMissing(name)) {
        return void 0;
      }
      const isJSDoc = findAncestor(name, or(isJSDocLinkLike, isJSDocNameReference, isJSDocMemberName));
      const meaning = isJSDoc ? SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Value : SymbolFlags.Value;
      if (name.kind === SyntaxKind.Identifier) {
        if (isJSXTagName(name) && isJsxIntrinsicTagName(name)) {
          const symbol = getIntrinsicTagSymbol(name.parent);
          return symbol === unknownSymbol ? void 0 : symbol;
        }
        const result = resolveEntityName(
          name,
          meaning,
          /*ignoreErrors*/
          true,
          /*dontResolveAlias*/
          true,
          getHostSignatureFromJSDoc(name)
        );
        if (!result && isJSDoc) {
          const container = findAncestor(name, or(isClassLike, isInterfaceDeclaration));
          if (container) {
            return resolveJSDocMemberName(
              name,
              /*ignoreErrors*/
              true,
              getSymbolOfDeclaration(container)
            );
          }
        }
        if (result && isJSDoc) {
          const container = getJSDocHost(name);
          if (container && isEnumMember(container) && container === result.valueDeclaration) {
            return resolveEntityName(
              name,
              meaning,
              /*ignoreErrors*/
              true,
              /*dontResolveAlias*/
              true,
              getSourceFileOfNode(container)
            ) || result;
          }
        }
        return result;
      } else if (isPrivateIdentifier(name)) {
        return getSymbolForPrivateIdentifierExpression(name);
      } else if (name.kind === SyntaxKind.PropertyAccessExpression || name.kind === SyntaxKind.QualifiedName) {
        const links = getNodeLinks(name);
        if (links.resolvedSymbol) {
          return links.resolvedSymbol;
        }
        if (name.kind === SyntaxKind.PropertyAccessExpression) {
          checkPropertyAccessExpression(name, 0 /* Normal */);
          if (!links.resolvedSymbol) {
            links.resolvedSymbol = getApplicableIndexSymbol(checkExpressionCached(name.expression), getLiteralTypeFromPropertyName(name.name));
          }
        } else {
          checkQualifiedName(name, 0 /* Normal */);
        }
        if (!links.resolvedSymbol && isJSDoc && isQualifiedName(name)) {
          return resolveJSDocMemberName(name);
        }
        return links.resolvedSymbol;
      } else if (isJSDocMemberName(name)) {
        return resolveJSDocMemberName(name);
      }
    } else if (isTypeReferenceIdentifier(name)) {
      const meaning = name.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace;
      const symbol = resolveEntityName(
        name,
        meaning,
        /*ignoreErrors*/
        false,
        /*dontResolveAlias*/
        true
      );
      return symbol && symbol !== unknownSymbol ? symbol : getUnresolvedSymbolForEntityName(name);
    }
    if (name.parent.kind === SyntaxKind.TypePredicate) {
      return resolveEntityName(
        name,
        /*meaning*/
        SymbolFlags.FunctionScopedVariable
      );
    }
    return void 0;
  }
  function getApplicableIndexSymbol(type, keyType) {
    const infos = getApplicableIndexInfos(type, keyType);
    if (infos.length && type.members) {
      const symbol = getIndexSymbolFromSymbolTable(resolveStructuredTypeMembers(type).members);
      if (infos === getIndexInfosOfType(type)) {
        return symbol;
      } else if (symbol) {
        const symbolLinks2 = getSymbolLinks(symbol);
        const declarationList = mapDefined(infos, (i) => i.declaration);
        const nodeListId = map(declarationList, getNodeId).join(",");
        if (!symbolLinks2.filteredIndexSymbolCache) {
          symbolLinks2.filteredIndexSymbolCache = /* @__PURE__ */ new Map();
        }
        if (symbolLinks2.filteredIndexSymbolCache.has(nodeListId)) {
          return symbolLinks2.filteredIndexSymbolCache.get(nodeListId);
        } else {
          const copy = createSymbol(SymbolFlags.Signature, InternalSymbolName.Index);
          copy.declarations = mapDefined(infos, (i) => i.declaration);
          copy.parent = type.aliasSymbol ? type.aliasSymbol : type.symbol ? type.symbol : getSymbolAtLocation(copy.declarations[0].parent);
          symbolLinks2.filteredIndexSymbolCache.set(nodeListId, copy);
          return copy;
        }
      }
    }
  }
  function resolveJSDocMemberName(name, ignoreErrors, container) {
    if (isEntityName(name)) {
      const meaning = SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Value;
      let symbol = resolveEntityName(
        name,
        meaning,
        ignoreErrors,
        /*dontResolveAlias*/
        true,
        getHostSignatureFromJSDoc(name)
      );
      if (!symbol && isIdentifier(name) && container) {
        symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning));
      }
      if (symbol) {
        return symbol;
      }
    }
    const left = isIdentifier(name) ? container : resolveJSDocMemberName(name.left, ignoreErrors, container);
    const right = isIdentifier(name) ? name.escapedText : name.right.escapedText;
    if (left) {
      const proto = left.flags & SymbolFlags.Value && getPropertyOfType(getTypeOfSymbol(left), "prototype");
      const t = proto ? getTypeOfSymbol(proto) : getDeclaredTypeOfSymbol(left);
      return getPropertyOfType(t, right);
    }
  }
  function getSymbolAtLocation(node, ignoreErrors) {
    if (isSourceFile(node)) {
      return isExternalModule(node) ? getMergedSymbol(node.symbol) : void 0;
    }
    const { parent } = node;
    const grandParent = parent.parent;
    if (node.flags & NodeFlags.InWithStatement) {
      return void 0;
    }
    if (isDeclarationNameOrImportPropertyName(node)) {
      const parentSymbol = getSymbolOfDeclaration(parent);
      return isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node ? getImmediateAliasedSymbol(parentSymbol) : parentSymbol;
    } else if (isLiteralComputedPropertyDeclarationName(node)) {
      return getSymbolOfDeclaration(parent.parent);
    }
    if (node.kind === SyntaxKind.Identifier) {
      if (isInRightSideOfImportOrExportAssignment(node)) {
        return getSymbolOfNameOrPropertyAccessExpression(node);
      } else if (parent.kind === SyntaxKind.BindingElement && grandParent.kind === SyntaxKind.ObjectBindingPattern && node === parent.propertyName) {
        const typeOfPattern = getTypeOfNode(grandParent);
        const propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
        if (propertyDeclaration) {
          return propertyDeclaration;
        }
      } else if (isMetaProperty(parent) && parent.name === node) {
        if (parent.keywordToken === SyntaxKind.NewKeyword && idText(node) === "target") {
          return checkNewTargetMetaProperty(parent).symbol;
        }
        if (parent.keywordToken === SyntaxKind.ImportKeyword && idText(node) === "meta") {
          return getGlobalImportMetaExpressionType().members.get("meta");
        }
        return void 0;
      }
    }
    switch (node.kind) {
      case SyntaxKind.Identifier:
      case SyntaxKind.PrivateIdentifier:
      case SyntaxKind.PropertyAccessExpression:
      case SyntaxKind.QualifiedName:
        if (!isThisInTypeQuery(node)) {
          return getSymbolOfNameOrPropertyAccessExpression(node);
        }
      // falls through
      case SyntaxKind.ThisKeyword:
        const container = getThisContainer(
          node,
          /*includeArrowFunctions*/
          false,
          /*includeClassComputedPropertyName*/
          false
        );
        if (isFunctionLike(container)) {
          const sig = getSignatureFromDeclaration(container);
          if (sig.thisParameter) {
            return sig.thisParameter;
          }
        }
        if (isInExpressionContext(node)) {
          return checkExpression(node).symbol;
        }
      // falls through
      case SyntaxKind.ThisType:
        return getTypeFromThisTypeNode(node).symbol;
      case SyntaxKind.SuperKeyword:
        return checkExpression(node).symbol;
      case SyntaxKind.ConstructorKeyword:
        const constructorDeclaration = node.parent;
        if (constructorDeclaration && constructorDeclaration.kind === SyntaxKind.Constructor) {
          return constructorDeclaration.parent.symbol;
        }
        return void 0;
      case SyntaxKind.StringLiteral:
      case SyntaxKind.NoSubstitutionTemplateLiteral:
        if (isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node || (node.parent.kind === SyntaxKind.ImportDeclaration || node.parent.kind === SyntaxKind.ExportDeclaration) && node.parent.moduleSpecifier === node || isInJSFile(node) && isJSDocImportTag(node.parent) && node.parent.moduleSpecifier === node || (isInJSFile(node) && isRequireCall(
          node.parent,
          /*requireStringLiteralLikeArgument*/
          false
        ) || isImportCall(node.parent)) || isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) {
          return resolveExternalModuleName(node, node, ignoreErrors);
        }
        if (isCallExpression(parent) && isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
          return getSymbolOfDeclaration(parent);
        }
      // falls through
      case SyntaxKind.NumericLiteral:
        const objectType = isElementAccessExpression(parent) ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : void 0 : isLiteralTypeNode(parent) && isIndexedAccessTypeNode(grandParent) ? getTypeFromTypeNode(grandParent.objectType) : void 0;
        return objectType && getPropertyOfType(objectType, escapeLeadingUnderscores(node.text));
      case SyntaxKind.DefaultKeyword:
      case SyntaxKind.FunctionKeyword:
      case SyntaxKind.EqualsGreaterThanToken:
      case SyntaxKind.ClassKeyword:
        return getSymbolOfNode(node.parent);
      case SyntaxKind.ImportType:
        return isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : void 0;
      case SyntaxKind.ExportKeyword:
        return isExportAssignment(node.parent) ? Debug.checkDefined(node.parent.symbol) : void 0;
      case SyntaxKind.ImportKeyword:
      case SyntaxKind.NewKeyword:
        return isMetaProperty(node.parent) ? checkMetaPropertyKeyword(node.parent).symbol : void 0;
      case SyntaxKind.InstanceOfKeyword:
        if (isBinaryExpression(node.parent)) {
          const type = getTypeOfExpression(node.parent.right);
          const hasInstanceMethodType = getSymbolHasInstanceMethodOfObjectType(type);
          return hasInstanceMethodType?.symbol ?? type.symbol;
        }
        return void 0;
      case SyntaxKind.MetaProperty:
        return checkExpression(node).symbol;
      case SyntaxKind.JsxNamespacedName:
        if (isJSXTagName(node) && isJsxIntrinsicTagName(node)) {
          const symbol = getIntrinsicTagSymbol(node.parent);
          return symbol === unknownSymbol ? void 0 : symbol;
        }
      // falls through
      default:
        return void 0;
    }
  }
  function getIndexInfosAtLocation(node) {
    if (isIdentifier(node) && isPropertyAccessExpression(node.parent) && node.parent.name === node) {
      const keyType = getLiteralTypeFromPropertyName(node);
      const objectType = getTypeOfExpression(node.parent.expression);
      const objectTypes = objectType.flags & TypeFlags.Union ? objectType.types : [objectType];
      return flatMap(objectTypes, (t) => filter(getIndexInfosOfType(t), (info) => isApplicableIndexType(keyType, info.keyType)));
    }
    return void 0;
  }
  function getShorthandAssignmentValueSymbol(location) {
    if (location && location.kind === SyntaxKind.ShorthandPropertyAssignment) {
      return resolveEntityName(location.name, SymbolFlags.Value | SymbolFlags.Alias);
    }
    return void 0;
  }
  function getExportSpecifierLocalTargetSymbol(node) {
    if (isExportSpecifier(node)) {
      const name = node.propertyName || node.name;
      return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : name.kind === SyntaxKind.StringLiteral ? void 0 : (
        // Skip for invalid syntax like this: export { "x" }
        resolveEntityName(name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias)
      );
    } else {
      return resolveEntityName(node, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias);
    }
  }
  function getTypeOfNode(node) {
    if (isSourceFile(node) && !isExternalModule(node)) {
      return errorType;
    }
    if (node.flags & NodeFlags.InWithStatement) {
      return errorType;
    }
    const classDecl = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
    const classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(classDecl.class));
    if (isPartOfTypeNode(node)) {
      const typeFromTypeNode = getTypeFromTypeNode(node);
      return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
    }
    if (isExpressionNode(node)) {
      return getRegularTypeOfExpression(node);
    }
    if (classType && !classDecl.isImplements) {
      const baseType = firstOrUndefined(getBaseTypes(classType));
      return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
    }
    if (isTypeDeclaration(node)) {
      const symbol = getSymbolOfDeclaration(node);
      return getDeclaredTypeOfSymbol(symbol);
    }
    if (isTypeDeclarationName(node)) {
      const symbol = getSymbolAtLocation(node);
      return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
    }
    if (isBindingElement(node)) {
      return getTypeForVariableLikeDeclaration(
        node,
        /*includeOptionality*/
        true,
        0 /* Normal */
      ) || errorType;
    }
    if (isDeclaration(node)) {
      const symbol = getSymbolOfDeclaration(node);
      return symbol ? getTypeOfSymbol(symbol) : errorType;
    }
    if (isDeclarationNameOrImportPropertyName(node)) {
      const symbol = getSymbolAtLocation(node);
      if (symbol) {
        return getTypeOfSymbol(symbol);
      }
      return errorType;
    }
    if (isBindingPattern(node)) {
      return getTypeForVariableLikeDeclaration(
        node.parent,
        /*includeOptionality*/
        true,
        0 /* Normal */
      ) || errorType;
    }
    if (isInRightSideOfImportOrExportAssignment(node)) {
      const symbol = getSymbolAtLocation(node);
      if (symbol) {
        const declaredType = getDeclaredTypeOfSymbol(symbol);
        return !isErrorType(declaredType) ? declaredType : getTypeOfSymbol(symbol);
      }
    }
    if (isMetaProperty(node.parent) && node.parent.keywordToken === node.kind) {
      return checkMetaPropertyKeyword(node.parent);
    }
    if (isImportAttributes(node)) {
      return getGlobalImportAttributesType(
        /*reportErrors*/
        false
      );
    }
    return errorType;
  }
  function getTypeOfAssignmentPattern(expr) {
    Debug.assert(expr.kind === SyntaxKind.ObjectLiteralExpression || expr.kind === SyntaxKind.ArrayLiteralExpression);
    if (expr.parent.kind === SyntaxKind.ForOfStatement) {
      const iteratedType = checkRightHandSideOfForOf(expr.parent);
      return checkDestructuringAssignment(expr, iteratedType || errorType);
    }
    if (expr.parent.kind === SyntaxKind.BinaryExpression) {
      const iteratedType = getTypeOfExpression(expr.parent.right);
      return checkDestructuringAssignment(expr, iteratedType || errorType);
    }
    if (expr.parent.kind === SyntaxKind.PropertyAssignment) {
      const node2 = cast(expr.parent.parent, isObjectLiteralExpression);
      const typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node2) || errorType;
      const propertyIndex = indexOfNode(node2.properties, expr.parent);
      return checkObjectLiteralDestructuringPropertyAssignment(node2, typeOfParentObjectLiteral, propertyIndex);
    }
    const node = cast(expr.parent, isArrayLiteralExpression);
    const typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
    const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
    return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
  }
  function getPropertySymbolOfDestructuringAssignment(location) {
    const typeOfObjectLiteral = getTypeOfAssignmentPattern(cast(location.parent.parent, isAssignmentPattern));
    return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
  }
  function getRegularTypeOfExpression(expr) {
    if (isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
      expr = expr.parent;
    }
    return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
  }
  function getParentTypeOfClassElement(node) {
    const classSymbol = getSymbolOfNode(node.parent);
    return isStatic(node) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol);
  }
  function getClassElementPropertyKeyType(element) {
    const name = element.name;
    switch (name.kind) {
      case SyntaxKind.Identifier:
        return getStringLiteralType(idText(name));
      case SyntaxKind.NumericLiteral:
      case SyntaxKind.StringLiteral:
        return getStringLiteralType(name.text);
      case SyntaxKind.ComputedPropertyName:
        const nameType = checkComputedPropertyName(name);
        return isTypeAssignableToKind(nameType, TypeFlags.ESSymbolLike) ? nameType : stringType;
      default:
        return Debug.fail("Unsupported property name.");
    }
  }
  function getAugmentedPropertiesOfType(type) {
    type = getApparentType(type);
    const propsByName = createSymbolTable(getPropertiesOfType(type));
    const functionType = getSignaturesOfType(type, SignatureKind.Call).length ? globalCallableFunctionType : getSignaturesOfType(type, SignatureKind.Construct).length ? globalNewableFunctionType : void 0;
    if (functionType) {
      forEach(getPropertiesOfType(functionType), (p) => {
        if (!propsByName.has(p.escapedName)) {
          propsByName.set(p.escapedName, p);
        }
      });
    }
    return getNamedMembers(propsByName);
  }
  function typeHasCallOrConstructSignatures(type) {
    return getSignaturesOfType(type, SignatureKind.Call).length !== 0 || getSignaturesOfType(type, SignatureKind.Construct).length !== 0;
  }
  function getRootSymbols(symbol) {
    const roots = getImmediateRootSymbols(symbol);
    return roots ? flatMap(roots, getRootSymbols) : [symbol];
  }
  function getImmediateRootSymbols(symbol) {
    if (getCheckFlags(symbol) & CheckFlags.Synthetic) {
      return mapDefined(getSymbolLinks(symbol).containingType.types, (type) => getPropertyOfType(type, symbol.escapedName));
    } else if (symbol.flags & SymbolFlags.Transient) {
      const { links: { leftSpread, rightSpread, syntheticOrigin } } = symbol;
      return leftSpread ? [leftSpread, rightSpread] : syntheticOrigin ? [syntheticOrigin] : singleElementArray(tryGetTarget(symbol));
    }
    return void 0;
  }
  function tryGetTarget(symbol) {
    let target;
    let next = symbol;
    while (next = getSymbolLinks(next).target) {
      target = next;
    }
    return target;
  }
  function isArgumentsLocalBinding(nodeIn) {
    if (isGeneratedIdentifier(nodeIn)) return false;
    const node = getParseTreeNode(nodeIn, isIdentifier);
    if (!node) return false;
    const parent = node.parent;
    if (!parent) return false;
    const isPropertyName2 = (isPropertyAccessExpression(parent) || isPropertyAssignment(parent)) && parent.name === node;
    return !isPropertyName2 && getReferencedValueSymbol(node) === argumentsSymbol;
  }
  function isNameOfModuleOrEnumDeclaration(node) {
    return isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
  }
  function getReferencedExportContainer(nodeIn, prefixLocals) {
    const node = getParseTreeNode(nodeIn, isIdentifier);
    if (node) {
      let symbol = getReferencedValueSymbol(
        node,
        /*startInDeclarationContainer*/
        isNameOfModuleOrEnumDeclaration(node)
      );
      if (symbol) {
        if (symbol.flags & SymbolFlags.ExportValue) {
          const exportSymbol = getMergedSymbol(symbol.exportSymbol);
          if (!prefixLocals && exportSymbol.flags & SymbolFlags.ExportHasLocal && !(exportSymbol.flags & SymbolFlags.Variable)) {
            return void 0;
          }
          symbol = exportSymbol;
        }
        const parentSymbol = getParentOfSymbol(symbol);
        if (parentSymbol) {
          if (parentSymbol.flags & SymbolFlags.ValueModule && parentSymbol.valueDeclaration?.kind === SyntaxKind.SourceFile) {
            const symbolFile = parentSymbol.valueDeclaration;
            const referenceFile = getSourceFileOfNode(node);
            const symbolIsUmdExport = symbolFile !== referenceFile;
            return symbolIsUmdExport ? void 0 : symbolFile;
          }
          return findAncestor(node.parent, (n) => isModuleOrEnumDeclaration(n) && getSymbolOfDeclaration(n) === parentSymbol);
        }
      }
    }
  }
  function getReferencedImportDeclaration(nodeIn) {
    const specifier = getIdentifierGeneratedImportReference(nodeIn);
    if (specifier) {
      return specifier;
    }
    const node = getParseTreeNode(nodeIn, isIdentifier);
    if (node) {
      const symbol = getReferencedValueOrAliasSymbol(node);
      if (isNonLocalAlias(
        symbol,
        /*excludes*/
        SymbolFlags.Value
      ) && !getTypeOnlyAliasDeclaration(symbol, SymbolFlags.Value)) {
        return getDeclarationOfAliasSymbol(symbol);
      }
    }
    return void 0;
  }
  function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
    return symbol.valueDeclaration && isBindingElement(symbol.valueDeclaration) && walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === SyntaxKind.CatchClause;
  }
  function isSymbolOfDeclarationWithCollidingName(symbol) {
    if (symbol.flags & SymbolFlags.BlockScoped && symbol.valueDeclaration && !isSourceFile(symbol.valueDeclaration)) {
      const links = getSymbolLinks(symbol);
      if (links.isDeclarationWithCollidingName === void 0) {
        const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration);
        if (isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
          if (resolveName(
            container.parent,
            symbol.escapedName,
            SymbolFlags.Value,
            /*nameNotFoundMessage*/
            void 0,
            /*isUse*/
            false
          )) {
            links.isDeclarationWithCollidingName = true;
          } else if (hasNodeCheckFlag(symbol.valueDeclaration, NodeCheckFlags.CapturedBlockScopedBinding)) {
            const isDeclaredInLoop = hasNodeCheckFlag(symbol.valueDeclaration, NodeCheckFlags.BlockScopedBindingInLoop);
            const inLoopInitializer = isIterationStatement(
              container,
              /*lookInLabeledStatements*/
              false
            );
            const inLoopBodyBlock = container.kind === SyntaxKind.Block && isIterationStatement(
              container.parent,
              /*lookInLabeledStatements*/
              false
            );
            links.isDeclarationWithCollidingName = !isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || !inLoopInitializer && !inLoopBodyBlock);
          } else {
            links.isDeclarationWithCollidingName = false;
          }
        }
      }
      return links.isDeclarationWithCollidingName;
    }
    return false;
  }
  function getReferencedDeclarationWithCollidingName(nodeIn) {
    if (!isGeneratedIdentifier(nodeIn)) {
      const node = getParseTreeNode(nodeIn, isIdentifier);
      if (node) {
        const symbol = getReferencedValueSymbol(node);
        if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
          return symbol.valueDeclaration;
        }
      }
    }
    return void 0;
  }
  function isDeclarationWithCollidingName(nodeIn) {
    const node = getParseTreeNode(nodeIn, isDeclaration);
    if (node) {
      const symbol = getSymbolOfDeclaration(node);
      if (symbol) {
        return isSymbolOfDeclarationWithCollidingName(symbol);
      }
    }
    return false;
  }
  function isValueAliasDeclaration(node) {
    Debug.assert(canCollectSymbolAliasAccessabilityData);
    switch (node.kind) {
      case SyntaxKind.ImportEqualsDeclaration:
        return isAliasResolvedToValue(getSymbolOfDeclaration(node));
      case SyntaxKind.ImportClause:
      case SyntaxKind.NamespaceImport:
      case SyntaxKind.ImportSpecifier:
      case SyntaxKind.ExportSpecifier:
        const symbol = getSymbolOfDeclaration(node);
        return !!symbol && isAliasResolvedToValue(
          symbol,
          /*excludeTypeOnlyValues*/
          true
        );
      case SyntaxKind.ExportDeclaration:
        const exportClause = node.exportClause;
        return !!exportClause && (isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration));
      case SyntaxKind.ExportAssignment:
        return node.expression && node.expression.kind === SyntaxKind.Identifier ? isAliasResolvedToValue(
          getSymbolOfDeclaration(node),
          /*excludeTypeOnlyValues*/
          true
        ) : true;
    }
    return false;
  }
  function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
    const node = getParseTreeNode(nodeIn, isImportEqualsDeclaration);
    if (node === void 0 || node.parent.kind !== SyntaxKind.SourceFile || !isInternalModuleImportEqualsDeclaration(node)) {
      return false;
    }
    const isValue = isAliasResolvedToValue(getSymbolOfDeclaration(node));
    return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference);
  }
  function isAliasResolvedToValue(symbol, excludeTypeOnlyValues) {
    if (!symbol) {
      return false;
    }
    const container = getSourceFileOfNode(symbol.valueDeclaration);
    const fileSymbol = container && getSymbolOfDeclaration(container);
    void resolveExternalModuleSymbol(fileSymbol);
    const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol));
    if (target === unknownSymbol) {
      return !excludeTypeOnlyValues || !getTypeOnlyAliasDeclaration(symbol);
    }
    return !!(getSymbolFlags(
      symbol,
      excludeTypeOnlyValues,
      /*excludeLocalMeanings*/
      true
    ) & SymbolFlags.Value) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target));
  }
  function isConstEnumOrConstEnumOnlyModule(s) {
    return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
  }
  function isReferencedAliasDeclaration(node, checkChildren) {
    Debug.assert(canCollectSymbolAliasAccessabilityData);
    if (isAliasSymbolDeclaration(node)) {
      const symbol = getSymbolOfDeclaration(node);
      const links = symbol && getSymbolLinks(symbol);
      if (links?.referenced) {
        return true;
      }
      const target = getSymbolLinks(symbol).aliasTarget;
      if (target && getEffectiveModifierFlags(node) & ModifierFlags.Export && getSymbolFlags(target) & SymbolFlags.Value && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) {
        return true;
      }
    }
    if (checkChildren) {
      return !!forEachChild(node, (node2) => isReferencedAliasDeclaration(node2, checkChildren));
    }
    return false;
  }
  function isImplementationOfOverload(node) {
    if (nodeIsPresent(node.body)) {
      if (isGetAccessor(node) || isSetAccessor(node)) return false;
      const symbol = getSymbolOfDeclaration(node);
      const signaturesOfSymbol = getSignaturesOfSymbol(symbol);
      return signaturesOfSymbol.length > 1 || // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
      // e.g.: function foo(a: string): string;
      //       function foo(a: any) { // This is implementation of the overloads
      //           return a;
      //       }
      signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node;
    }
    return false;
  }
  function declaredParameterTypeContainsUndefined(parameter) {
    const typeNode = getNonlocalEffectiveTypeAnnotationNode(parameter);
    if (!typeNode) return false;
    const type = getTypeFromTypeNode(typeNode);
    return containsUndefinedType(type);
  }
  function requiresAddingImplicitUndefined(parameter, enclosingDeclaration) {
    return (isRequiredInitializedParameter(parameter, enclosingDeclaration) || isOptionalUninitializedParameterProperty(parameter)) && !declaredParameterTypeContainsUndefined(parameter);
  }
  function isRequiredInitializedParameter(parameter, enclosingDeclaration) {
    if (!strictNullChecks || isOptionalParameter(parameter) || isJSDocParameterTag(parameter) || !parameter.initializer) {
      return false;
    }
    if (hasSyntacticModifier(parameter, ModifierFlags.ParameterPropertyModifier)) {
      return !!enclosingDeclaration && isFunctionLikeDeclaration(enclosingDeclaration);
    }
    return true;
  }
  function isOptionalUninitializedParameterProperty(parameter) {
    return strictNullChecks && isOptionalParameter(parameter) && (isJSDocParameterTag(parameter) || !parameter.initializer) && hasSyntacticModifier(parameter, ModifierFlags.ParameterPropertyModifier);
  }
  function isExpandoFunctionDeclaration(node) {
    const declaration = getParseTreeNode(node, (n) => isFunctionDeclaration(n) || isVariableDeclaration(n));
    if (!declaration) {
      return false;
    }
    let symbol;
    if (isVariableDeclaration(declaration)) {
      if (declaration.type || !isInJSFile(declaration) && !isVarConstLike(declaration)) {
        return false;
      }
      const initializer = getDeclaredExpandoInitializer(declaration);
      if (!initializer || !canHaveSymbol(initializer)) {
        return false;
      }
      symbol = getSymbolOfDeclaration(initializer);
    } else {
      symbol = getSymbolOfDeclaration(declaration);
    }
    if (!symbol || !(symbol.flags & SymbolFlags.Function | SymbolFlags.Variable)) {
      return false;
    }
    return !!forEachEntry(getExportsOfSymbol(symbol), (p) => p.flags & SymbolFlags.Value && isExpandoPropertyDeclaration(p.valueDeclaration));
  }
  function getPropertiesOfContainerFunction(node) {
    const declaration = getParseTreeNode(node, isFunctionDeclaration);
    if (!declaration) {
      return emptyArray;
    }
    const symbol = getSymbolOfDeclaration(declaration);
    return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || emptyArray;
  }
  function getNodeCheckFlags(node) {
    const nodeId = node.id || 0;
    if (nodeId < 0 || nodeId >= nodeLinks.length) return 0;
    return nodeLinks[nodeId]?.flags || 0;
  }
  function hasNodeCheckFlag(node, flag) {
    calculateNodeCheckFlagWorker(node, flag);
    return !!(getNodeCheckFlags(node) & flag);
  }
  function calculateNodeCheckFlagWorker(node, flag) {
    if (!compilerOptions.noCheck && canIncludeBindAndCheckDiagnostics(getSourceFileOfNode(node), compilerOptions)) {
      return;
    }
    const links = getNodeLinks(node);
    if (links.calculatedFlags & flag) {
      return;
    }
    switch (flag) {
      case NodeCheckFlags.SuperInstance:
      case NodeCheckFlags.SuperStatic:
        return checkSingleSuperExpression(node);
      case NodeCheckFlags.MethodWithSuperPropertyAccessInAsync:
      case NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync:
      case NodeCheckFlags.ContainsSuperPropertyInStaticInitializer:
        return checkChildSuperExpressions(node);
      case NodeCheckFlags.CaptureArguments:
      case NodeCheckFlags.ContainsCapturedBlockScopeBinding:
      case NodeCheckFlags.NeedsLoopOutParameter:
      case NodeCheckFlags.ContainsConstructorReference:
        return checkChildIdentifiers(node);
      case NodeCheckFlags.ConstructorReference:
        return checkSingleIdentifier(node);
      case NodeCheckFlags.LoopWithCapturedBlockScopedBinding:
      case NodeCheckFlags.BlockScopedBindingInLoop:
      case NodeCheckFlags.CapturedBlockScopedBinding:
        return checkContainingBlockScopeBindingUses(node);
      default:
        return Debug.assertNever(flag, `Unhandled node check flag calculation: ${Debug.formatNodeCheckFlags(flag)}`);
    }
    function forEachNodeRecursively(root, cb) {
      const rootResult = cb(root, root.parent);
      if (rootResult === "skip") return void 0;
      if (rootResult) return rootResult;
      return forEachChildRecursively(root, cb);
    }
    function checkSuperExpressions(node2) {
      const links2 = getNodeLinks(node2);
      if (links2.calculatedFlags & flag) return "skip";
      links2.calculatedFlags |= NodeCheckFlags.MethodWithSuperPropertyAccessInAsync | NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync | NodeCheckFlags.ContainsSuperPropertyInStaticInitializer;
      checkSingleSuperExpression(node2);
      return void 0;
    }
    function checkChildSuperExpressions(node2) {
      forEachNodeRecursively(node2, checkSuperExpressions);
    }
    function checkSingleSuperExpression(node2) {
      const nodeLinks2 = getNodeLinks(node2);
      nodeLinks2.calculatedFlags |= NodeCheckFlags.SuperInstance | NodeCheckFlags.SuperStatic;
      if (node2.kind === SyntaxKind.SuperKeyword) {
        checkSuperExpression(node2);
      }
    }
    function checkIdentifiers(node2) {
      const links2 = getNodeLinks(node2);
      if (links2.calculatedFlags & flag) return "skip";
      links2.calculatedFlags |= NodeCheckFlags.CaptureArguments | NodeCheckFlags.ContainsCapturedBlockScopeBinding | NodeCheckFlags.NeedsLoopOutParameter | NodeCheckFlags.ContainsConstructorReference;
      checkSingleIdentifier(node2);
      return void 0;
    }
    function checkChildIdentifiers(node2) {
      forEachNodeRecursively(node2, checkIdentifiers);
    }
    function isExpressionNodeOrShorthandPropertyAssignmentName(node2) {
      return isExpressionNode(node2) || isShorthandPropertyAssignment(node2.parent) && (node2.parent.objectAssignmentInitializer ?? node2.parent.name) === node2;
    }
    function checkSingleIdentifier(node2) {
      const nodeLinks2 = getNodeLinks(node2);
      nodeLinks2.calculatedFlags |= NodeCheckFlags.ConstructorReference;
      if (isIdentifier(node2)) {
        nodeLinks2.calculatedFlags |= NodeCheckFlags.BlockScopedBindingInLoop | NodeCheckFlags.CapturedBlockScopedBinding;
        if (isExpressionNodeOrShorthandPropertyAssignmentName(node2) && !(isPropertyAccessExpression(node2.parent) && node2.parent.name === node2)) {
          const s = getResolvedSymbol(node2);
          if (s && s !== unknownSymbol) {
            checkIdentifierCalculateNodeCheckFlags(node2, s);
          }
        }
      }
    }
    function checkBlockScopeBindings(node2) {
      const links2 = getNodeLinks(node2);
      if (links2.calculatedFlags & flag) return "skip";
      links2.calculatedFlags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding | NodeCheckFlags.BlockScopedBindingInLoop | NodeCheckFlags.CapturedBlockScopedBinding;
      checkSingleBlockScopeBinding(node2);
      return void 0;
    }
    function checkContainingBlockScopeBindingUses(node2) {
      const scope = getEnclosingBlockScopeContainer(isDeclarationName(node2) ? node2.parent : node2);
      forEachNodeRecursively(scope, checkBlockScopeBindings);
    }
    function checkSingleBlockScopeBinding(node2) {
      checkSingleIdentifier(node2);
      if (isComputedPropertyName(node2)) {
        checkComputedPropertyName(node2);
      }
      if (isPrivateIdentifier(node2) && isClassElement(node2.parent)) {
        setNodeLinksForPrivateIdentifierScope(node2.parent);
      }
    }
  }
  function getEnumMemberValue(node) {
    computeEnumMemberValues(node.parent);
    return getNodeLinks(node).enumMemberValue ?? evaluatorResult(
      /*value*/
      void 0
    );
  }
  function canHaveConstantValue(node) {
    switch (node.kind) {
      case SyntaxKind.EnumMember:
      case SyntaxKind.PropertyAccessExpression:
      case SyntaxKind.ElementAccessExpression:
        return true;
    }
    return false;
  }
  function getConstantValue(node) {
    if (node.kind === SyntaxKind.EnumMember) {
      return getEnumMemberValue(node).value;
    }
    if (!getNodeLinks(node).resolvedSymbol) {
      void checkExpressionCached(node);
    }
    const symbol = getNodeLinks(node).resolvedSymbol || (isEntityNameExpression(node) ? resolveEntityName(
      node,
      SymbolFlags.Value,
      /*ignoreErrors*/
      true
    ) : void 0);
    if (symbol && symbol.flags & SymbolFlags.EnumMember) {
      const member = symbol.valueDeclaration;
      if (isEnumConst(member.parent)) {
        return getEnumMemberValue(member).value;
      }
    }
    return void 0;
  }
  function isFunctionType(type) {
    return !!(type.flags & TypeFlags.Object) && getSignaturesOfType(type, SignatureKind.Call).length > 0;
  }
  function getTypeReferenceSerializationKind(typeNameIn, location) {
    const typeName = getParseTreeNode(typeNameIn, isEntityName);
    if (!typeName) return TypeReferenceSerializationKind.Unknown;
    if (location) {
      location = getParseTreeNode(location);
      if (!location) return TypeReferenceSerializationKind.Unknown;
    }
    let isTypeOnly = false;
    if (isQualifiedName(typeName)) {
      const rootValueSymbol = resolveEntityName(
        getFirstIdentifier(typeName),
        SymbolFlags.Value,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true,
        location
      );
      isTypeOnly = !!rootValueSymbol?.declarations?.every(isTypeOnlyImportOrExportDeclaration);
    }
    const valueSymbol = resolveEntityName(
      typeName,
      SymbolFlags.Value,
      /*ignoreErrors*/
      true,
      /*dontResolveAlias*/
      true,
      location
    );
    const resolvedValueSymbol = valueSymbol && valueSymbol.flags & SymbolFlags.Alias ? resolveAlias(valueSymbol) : valueSymbol;
    isTypeOnly ||= !!(valueSymbol && getTypeOnlyAliasDeclaration(valueSymbol, SymbolFlags.Value));
    const typeSymbol = resolveEntityName(
      typeName,
      SymbolFlags.Type,
      /*ignoreErrors*/
      true,
      /*dontResolveAlias*/
      true,
      location
    );
    const resolvedTypeSymbol = typeSymbol && typeSymbol.flags & SymbolFlags.Alias ? resolveAlias(typeSymbol) : typeSymbol;
    if (!valueSymbol) {
      isTypeOnly ||= !!(typeSymbol && getTypeOnlyAliasDeclaration(typeSymbol, SymbolFlags.Type));
    }
    if (resolvedValueSymbol && resolvedValueSymbol === resolvedTypeSymbol) {
      const globalPromiseSymbol = getGlobalPromiseConstructorSymbol(
        /*reportErrors*/
        false
      );
      if (globalPromiseSymbol && resolvedValueSymbol === globalPromiseSymbol) {
        return TypeReferenceSerializationKind.Promise;
      }
      const constructorType = getTypeOfSymbol(resolvedValueSymbol);
      if (constructorType && isConstructorType(constructorType)) {
        return isTypeOnly ? TypeReferenceSerializationKind.TypeWithCallSignature : TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
      }
    }
    if (!resolvedTypeSymbol) {
      return isTypeOnly ? TypeReferenceSerializationKind.ObjectType : TypeReferenceSerializationKind.Unknown;
    }
    const type = getDeclaredTypeOfSymbol(resolvedTypeSymbol);
    if (isErrorType(type)) {
      return isTypeOnly ? TypeReferenceSerializationKind.ObjectType : TypeReferenceSerializationKind.Unknown;
    } else if (type.flags & TypeFlags.AnyOrUnknown) {
      return TypeReferenceSerializationKind.ObjectType;
    } else if (isTypeAssignableToKind(type, TypeFlags.Void | TypeFlags.Nullable | TypeFlags.Never)) {
      return TypeReferenceSerializationKind.VoidNullableOrNeverType;
    } else if (isTypeAssignableToKind(type, TypeFlags.BooleanLike)) {
      return TypeReferenceSerializationKind.BooleanType;
    } else if (isTypeAssignableToKind(type, TypeFlags.NumberLike)) {
      return TypeReferenceSerializationKind.NumberLikeType;
    } else if (isTypeAssignableToKind(type, TypeFlags.BigIntLike)) {
      return TypeReferenceSerializationKind.BigIntLikeType;
    } else if (isTypeAssignableToKind(type, TypeFlags.StringLike)) {
      return TypeReferenceSerializationKind.StringLikeType;
    } else if (isTupleType(type)) {
      return TypeReferenceSerializationKind.ArrayLikeType;
    } else if (isTypeAssignableToKind(type, TypeFlags.ESSymbolLike)) {
      return TypeReferenceSerializationKind.ESSymbolType;
    } else if (isFunctionType(type)) {
      return TypeReferenceSerializationKind.TypeWithCallSignature;
    } else if (isArrayType(type)) {
      return TypeReferenceSerializationKind.ArrayLikeType;
    } else {
      return TypeReferenceSerializationKind.ObjectType;
    }
  }
  function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, internalFlags, tracker) {
    const declaration = getParseTreeNode(declarationIn, isVariableLikeOrAccessor);
    if (!declaration) {
      return factory.createToken(SyntaxKind.AnyKeyword);
    }
    const symbol = getSymbolOfDeclaration(declaration);
    const type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType;
    return nodeBuilder.serializeTypeForDeclaration(declaration, type, symbol, enclosingDeclaration, flags | NodeBuilderFlags.MultilineObjectLiterals, internalFlags, tracker);
  }
  function isDeclarationWithPossibleInnerTypeNodeReuse(declaration) {
    return isFunctionLike(declaration) || isExportAssignment(declaration) || isVariableLike(declaration);
  }
  function getAllAccessorDeclarationsForDeclaration(accessor) {
    accessor = getParseTreeNode(accessor, isGetOrSetAccessorDeclaration);
    const otherKind = accessor.kind === SyntaxKind.SetAccessor ? SyntaxKind.GetAccessor : SyntaxKind.SetAccessor;
    const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(accessor), otherKind);
    const firstAccessor = otherAccessor && otherAccessor.pos < accessor.pos ? otherAccessor : accessor;
    const secondAccessor = otherAccessor && otherAccessor.pos < accessor.pos ? accessor : otherAccessor;
    const setAccessor = accessor.kind === SyntaxKind.SetAccessor ? accessor : otherAccessor;
    const getAccessor = accessor.kind === SyntaxKind.GetAccessor ? accessor : otherAccessor;
    return {
      firstAccessor,
      secondAccessor,
      setAccessor,
      getAccessor
    };
  }
  function getPossibleTypeNodeReuseExpression(declaration) {
    return isFunctionLike(declaration) && !isSetAccessor(declaration) ? getSingleReturnExpression(declaration) : isExportAssignment(declaration) ? declaration.expression : !!declaration.initializer ? declaration.initializer : isParameter(declaration) && isSetAccessor(declaration.parent) ? getSingleReturnExpression(getAllAccessorDeclarationsForDeclaration(declaration.parent).getAccessor) : void 0;
  }
  function getSingleReturnExpression(declaration) {
    let candidateExpr;
    if (declaration && !nodeIsMissing(declaration.body)) {
      if (getFunctionFlags(declaration) & FunctionFlags.AsyncGenerator) return void 0;
      const body = declaration.body;
      if (body && isBlock(body)) {
        forEachReturnStatement(body, (s) => {
          if (!candidateExpr) {
            candidateExpr = s.expression;
          } else {
            candidateExpr = void 0;
            return true;
          }
        });
      } else {
        candidateExpr = body;
      }
    }
    return candidateExpr;
  }
  function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, internalFlags, tracker) {
    const signatureDeclaration = getParseTreeNode(signatureDeclarationIn, isFunctionLike);
    if (!signatureDeclaration) {
      return factory.createToken(SyntaxKind.AnyKeyword);
    }
    return nodeBuilder.serializeReturnTypeForSignature(getSignatureFromDeclaration(signatureDeclaration), enclosingDeclaration, flags | NodeBuilderFlags.MultilineObjectLiterals, internalFlags, tracker);
  }
  function createTypeOfExpression(exprIn, enclosingDeclaration, flags, internalFlags, tracker) {
    const expr = getParseTreeNode(exprIn, isExpression);
    if (!expr) {
      return factory.createToken(SyntaxKind.AnyKeyword);
    }
    const type = getWidenedType(getRegularTypeOfExpression(expr));
    return nodeBuilder.expressionOrTypeToTypeNode(
      expr,
      type,
      /*addUndefined*/
      void 0,
      enclosingDeclaration,
      flags | NodeBuilderFlags.MultilineObjectLiterals,
      internalFlags,
      tracker
    );
  }
  function hasGlobalName(name) {
    return globals.has(escapeLeadingUnderscores(name));
  }
  function getReferencedValueSymbol(reference, startInDeclarationContainer) {
    const resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
    if (resolvedSymbol) {
      return resolvedSymbol;
    }
    let location = reference;
    if (startInDeclarationContainer) {
      const parent = reference.parent;
      if (isDeclaration(parent) && reference === parent.name) {
        location = getDeclarationContainer(parent);
      }
    }
    return resolveName(
      location,
      reference.escapedText,
      SymbolFlags.Value | SymbolFlags.ExportValue | SymbolFlags.Alias,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
  }
  function getReferencedValueOrAliasSymbol(reference) {
    const resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
    if (resolvedSymbol && resolvedSymbol !== unknownSymbol) {
      return resolvedSymbol;
    }
    return resolveName(
      reference,
      reference.escapedText,
      SymbolFlags.Value | SymbolFlags.ExportValue | SymbolFlags.Alias,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true,
      /*excludeGlobals*/
      void 0
    );
  }
  function getReferencedValueDeclaration(referenceIn) {
    if (!isGeneratedIdentifier(referenceIn)) {
      const reference = getParseTreeNode(referenceIn, isIdentifier);
      if (reference) {
        const symbol = getReferencedValueSymbol(reference);
        if (symbol) {
          return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
        }
      }
    }
    return void 0;
  }
  function getReferencedValueDeclarations(referenceIn) {
    if (!isGeneratedIdentifier(referenceIn)) {
      const reference = getParseTreeNode(referenceIn, isIdentifier);
      if (reference) {
        const symbol = getReferencedValueSymbol(reference);
        if (symbol) {
          return filter(getExportSymbolOfValueSymbolIfExported(symbol).declarations, (declaration) => {
            switch (declaration.kind) {
              case SyntaxKind.VariableDeclaration:
              case SyntaxKind.Parameter:
              case SyntaxKind.BindingElement:
              case SyntaxKind.PropertyDeclaration:
              case SyntaxKind.PropertyAssignment:
              case SyntaxKind.ShorthandPropertyAssignment:
              case SyntaxKind.EnumMember:
              case SyntaxKind.ObjectLiteralExpression:
              case SyntaxKind.FunctionDeclaration:
              case SyntaxKind.FunctionExpression:
              case SyntaxKind.ArrowFunction:
              case SyntaxKind.ClassDeclaration:
              case SyntaxKind.ClassExpression:
              case SyntaxKind.EnumDeclaration:
              case SyntaxKind.MethodDeclaration:
              case SyntaxKind.GetAccessor:
              case SyntaxKind.SetAccessor:
              case SyntaxKind.ModuleDeclaration:
                return true;
            }
            return false;
          });
        }
      }
    }
    return void 0;
  }
  function isLiteralConstDeclaration(node) {
    if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConstLike(node)) {
      return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node)));
    }
    return false;
  }
  function literalTypeToNode(type, enclosing, tracker) {
    const enumResult = type.flags & TypeFlags.EnumLike ? nodeBuilder.symbolToExpression(
      type.symbol,
      SymbolFlags.Value,
      enclosing,
      /*flags*/
      void 0,
      /*internalFlags*/
      void 0,
      tracker
    ) : type === trueType ? factory.createTrue() : type === falseType && factory.createFalse();
    if (enumResult) return enumResult;
    const literalValue = type.value;
    return typeof literalValue === "object" ? factory.createBigIntLiteral(literalValue) : typeof literalValue === "string" ? factory.createStringLiteral(literalValue) : literalValue < 0 ? factory.createPrefixUnaryExpression(SyntaxKind.MinusToken, factory.createNumericLiteral(-literalValue)) : factory.createNumericLiteral(literalValue);
  }
  function createLiteralConstValue(node, tracker) {
    const type = getTypeOfSymbol(getSymbolOfDeclaration(node));
    return literalTypeToNode(type, node, tracker);
  }
  function getJsxFactoryEntity(location) {
    return location ? (getJsxNamespace(location), getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity) : _jsxFactoryEntity;
  }
  function getJsxFragmentFactoryEntity(location) {
    if (location) {
      const file = getSourceFileOfNode(location);
      if (file) {
        if (file.localJsxFragmentFactory) {
          return file.localJsxFragmentFactory;
        }
        const jsxFragPragmas = file.pragmas.get("jsxfrag");
        const jsxFragPragma = isArray(jsxFragPragmas) ? jsxFragPragmas[0] : jsxFragPragmas;
        if (jsxFragPragma) {
          file.localJsxFragmentFactory = parseIsolatedEntityName(jsxFragPragma.arguments.factory, languageVersion);
          return file.localJsxFragmentFactory;
        }
      }
    }
    if (compilerOptions.jsxFragmentFactory) {
      return parseIsolatedEntityName(compilerOptions.jsxFragmentFactory, languageVersion);
    }
  }
  function getNonlocalEffectiveTypeAnnotationNode(node) {
    const direct = getEffectiveTypeAnnotationNode(node);
    if (direct) {
      return direct;
    }
    if (node.kind === SyntaxKind.Parameter && node.parent.kind === SyntaxKind.SetAccessor) {
      const other = getAllAccessorDeclarationsForDeclaration(node.parent).getAccessor;
      if (other) {
        return getEffectiveReturnTypeNode(other);
      }
    }
    return void 0;
  }
  function getNonlocalEffectiveReturnTypeAnnotationNode(node) {
    const direct = getEffectiveReturnTypeNode(node);
    if (direct) {
      return direct;
    }
    if (node.kind === SyntaxKind.GetAccessor) {
      const other = getAllAccessorDeclarationsForDeclaration(node).setAccessor;
      if (other) {
        const param = getSetAccessorValueParameter(other);
        if (param) {
          return getEffectiveTypeAnnotationNode(param);
        }
      }
    }
    return void 0;
  }
  function createResolver() {
    return {
      getReferencedExportContainer,
      getReferencedImportDeclaration,
      getReferencedDeclarationWithCollidingName,
      isDeclarationWithCollidingName,
      isValueAliasDeclaration: (nodeIn) => {
        const node = getParseTreeNode(nodeIn);
        return node && canCollectSymbolAliasAccessabilityData ? isValueAliasDeclaration(node) : true;
      },
      hasGlobalName,
      isReferencedAliasDeclaration: (nodeIn, checkChildren) => {
        const node = getParseTreeNode(nodeIn);
        return node && canCollectSymbolAliasAccessabilityData ? isReferencedAliasDeclaration(node, checkChildren) : true;
      },
      hasNodeCheckFlag: (nodeIn, flag) => {
        const node = getParseTreeNode(nodeIn);
        if (!node) return false;
        return hasNodeCheckFlag(node, flag);
      },
      isTopLevelValueImportEqualsWithEntityName,
      isDeclarationVisible,
      isImplementationOfOverload,
      requiresAddingImplicitUndefined,
      isExpandoFunctionDeclaration,
      getPropertiesOfContainerFunction,
      createTypeOfDeclaration,
      createReturnTypeOfSignatureDeclaration,
      createTypeOfExpression,
      createLiteralConstValue,
      isSymbolAccessible,
      isEntityNameVisible,
      getConstantValue: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, canHaveConstantValue);
        return node ? getConstantValue(node) : void 0;
      },
      getEnumMemberValue: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, isEnumMember);
        return node ? getEnumMemberValue(node) : void 0;
      },
      collectLinkedAliases,
      markLinkedReferences: (nodeIn) => {
        const node = getParseTreeNode(nodeIn);
        return node && markLinkedReferences(node, 0 /* Unspecified */);
      },
      getReferencedValueDeclaration,
      getReferencedValueDeclarations,
      getTypeReferenceSerializationKind,
      isOptionalParameter,
      isArgumentsLocalBinding,
      getExternalModuleFileFromDeclaration: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, hasPossibleExternalModuleReference);
        return node && getExternalModuleFileFromDeclaration(node);
      },
      isLiteralConstDeclaration,
      isLateBound: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, isDeclaration);
        const symbol = node && getSymbolOfDeclaration(node);
        return !!(symbol && getCheckFlags(symbol) & CheckFlags.Late);
      },
      getJsxFactoryEntity,
      getJsxFragmentFactoryEntity,
      isBindingCapturedByNode: (node, decl) => {
        const parseNode = getParseTreeNode(node);
        const parseDecl = getParseTreeNode(decl);
        return !!parseNode && !!parseDecl && (isVariableDeclaration(parseDecl) || isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
      },
      getDeclarationStatementsForSourceFile: (node, flags, internalFlags, tracker) => {
        const n = getParseTreeNode(node);
        Debug.assert(n && n.kind === SyntaxKind.SourceFile, "Non-sourcefile node passed into getDeclarationsForSourceFile");
        const sym = getSymbolOfDeclaration(node);
        if (!sym) {
          return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, internalFlags, tracker);
        }
        resolveExternalModuleSymbol(sym);
        return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, internalFlags, tracker);
      },
      isImportRequiredByAugmentation,
      isDefinitelyReferenceToGlobalSymbolObject
    };
    function isImportRequiredByAugmentation(node) {
      const file = getSourceFileOfNode(node);
      if (!file.symbol) return false;
      const importTarget = getExternalModuleFileFromDeclaration(node);
      if (!importTarget) return false;
      if (importTarget === file) return false;
      const exports = getExportsOfModule(file.symbol);
      for (const s of arrayFrom(exports.values())) {
        if (s.mergeId) {
          const merged = getMergedSymbol(s);
          if (merged.declarations) {
            for (const d of merged.declarations) {
              const declFile = getSourceFileOfNode(d);
              if (declFile === importTarget) {
                return true;
              }
            }
          }
        }
      }
      return false;
    }
  }
  function getExternalModuleFileFromDeclaration(declaration) {
    const specifier = declaration.kind === SyntaxKind.ModuleDeclaration ? tryCast(declaration.name, isStringLiteral) : getExternalModuleName(declaration);
    const moduleSymbol = resolveExternalModuleNameWorker(
      specifier,
      specifier,
      /*moduleNotFoundError*/
      void 0
    );
    if (!moduleSymbol) {
      return void 0;
    }
    return getDeclarationOfKind(moduleSymbol, SyntaxKind.SourceFile);
  }
  function initializeTypeChecker() {
    for (const file of host.getSourceFiles()) {
      bindSourceFile(file, compilerOptions);
    }
    amalgamatedDuplicates = /* @__PURE__ */ new Map();
    let augmentations;
    for (const file of host.getSourceFiles()) {
      if (file.redirectInfo) {
        continue;
      }
      if (!isExternalOrCommonJsModule(file)) {
        const fileGlobalThisSymbol = file.locals.get("globalThis");
        if (fileGlobalThisSymbol?.declarations) {
          for (const declaration of fileGlobalThisSymbol.declarations) {
            diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
          }
        }
        mergeSymbolTable(globals, file.locals);
      }
      if (file.jsGlobalAugmentations) {
        mergeSymbolTable(globals, file.jsGlobalAugmentations);
      }
      if (file.patternAmbientModules && file.patternAmbientModules.length) {
        patternAmbientModules = concatenate(patternAmbientModules, file.patternAmbientModules);
      }
      if (file.moduleAugmentations.length) {
        (augmentations || (augmentations = [])).push(file.moduleAugmentations);
      }
      if (file.symbol && file.symbol.globalExports) {
        const source = file.symbol.globalExports;
        source.forEach((sourceSymbol, id) => {
          if (!globals.has(id)) {
            globals.set(id, sourceSymbol);
          }
        });
      }
    }
    if (augmentations) {
      for (const list of augmentations) {
        for (const augmentation of list) {
          if (!isGlobalScopeAugmentation(augmentation.parent)) continue;
          mergeModuleAugmentation(augmentation);
        }
      }
    }
    addUndefinedToGlobalsOrErrorOnRedeclaration();
    getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
    getSymbolLinks(argumentsSymbol).type = getGlobalType(
      "IArguments",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    getSymbolLinks(unknownSymbol).type = errorType;
    getSymbolLinks(globalThisSymbol).type = createObjectType(ObjectFlags.Anonymous, globalThisSymbol);
    globalArrayType = getGlobalType(
      "Array",
      /*arity*/
      1,
      /*reportErrors*/
      true
    );
    globalObjectType = getGlobalType(
      "Object",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalFunctionType = getGlobalType(
      "Function",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalCallableFunctionType = strictBindCallApply && getGlobalType(
      "CallableFunction",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || globalFunctionType;
    globalNewableFunctionType = strictBindCallApply && getGlobalType(
      "NewableFunction",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || globalFunctionType;
    globalStringType = getGlobalType(
      "String",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalNumberType = getGlobalType(
      "Number",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalBooleanType = getGlobalType(
      "Boolean",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalRegExpType = getGlobalType(
      "RegExp",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    anyArrayType = createArrayType(anyType);
    autoArrayType = createArrayType(autoType);
    if (autoArrayType === emptyObjectType) {
      autoArrayType = createAnonymousType(
        /*symbol*/
        void 0,
        emptySymbols,
        emptyArray,
        emptyArray,
        emptyArray
      );
    }
    globalReadonlyArrayType = getGlobalTypeOrUndefined(
      "ReadonlyArray",
      /*arity*/
      1
    ) || globalArrayType;
    anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
    globalThisType = getGlobalTypeOrUndefined(
      "ThisType",
      /*arity*/
      1
    );
    if (augmentations) {
      for (const list of augmentations) {
        for (const augmentation of list) {
          if (isGlobalScopeAugmentation(augmentation.parent)) continue;
          mergeModuleAugmentation(augmentation);
        }
      }
    }
    amalgamatedDuplicates.forEach(({ firstFile, secondFile, conflictingSymbols }) => {
      if (conflictingSymbols.size < 8) {
        conflictingSymbols.forEach(({ isBlockScoped, firstFileLocations, secondFileLocations }, symbolName2) => {
          const message = isBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0;
          for (const node of firstFileLocations) {
            addDuplicateDeclarationError(node, message, symbolName2, secondFileLocations);
          }
          for (const node of secondFileLocations) {
            addDuplicateDeclarationError(node, message, symbolName2, firstFileLocations);
          }
        });
      } else {
        const list = arrayFrom(conflictingSymbols.keys()).join(", ");
        diagnostics.add(addRelatedInfo(
          createDiagnosticForNode(firstFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list),
          createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file)
        ));
        diagnostics.add(addRelatedInfo(
          createDiagnosticForNode(secondFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list),
          createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file)
        ));
      }
    });
    amalgamatedDuplicates = void 0;
  }
  function checkExternalEmitHelpers(location, helpers) {
    if (compilerOptions.importHelpers) {
      const sourceFile = getSourceFileOfNode(location);
      if (isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & NodeFlags.Ambient)) {
        const helpersModule = resolveHelpersModule(sourceFile, location);
        if (helpersModule !== unknownSymbol) {
          const links = getSymbolLinks(helpersModule);
          links.requestedExternalEmitHelpers ??= 0;
          if ((links.requestedExternalEmitHelpers & helpers) !== helpers) {
            const uncheckedHelpers = helpers & ~links.requestedExternalEmitHelpers;
            for (let helper = ExternalEmitHelpers.FirstEmitHelper; helper <= ExternalEmitHelpers.LastEmitHelper; helper <<= 1) {
              if (uncheckedHelpers & helper) {
                for (const name of getHelperNames(helper)) {
                  const symbol = resolveSymbol(getSymbol(getExportsOfModule(helpersModule), escapeLeadingUnderscores(name), SymbolFlags.Value));
                  if (!symbol) {
                    error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name);
                  } else if (helper & ExternalEmitHelpers.ClassPrivateFieldGet) {
                    if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 3)) {
                      error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4);
                    }
                  } else if (helper & ExternalEmitHelpers.ClassPrivateFieldSet) {
                    if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 4)) {
                      error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5);
                    }
                  } else if (helper & ExternalEmitHelpers.SpreadArray) {
                    if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 2)) {
                      error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 3);
                    }
                  }
                }
              }
            }
          }
          links.requestedExternalEmitHelpers |= helpers;
        }
      }
    }
  }
  function getHelperNames(helper) {
    switch (helper) {
      case ExternalEmitHelpers.Extends:
        return ["__extends"];
      case ExternalEmitHelpers.Assign:
        return ["__assign"];
      case ExternalEmitHelpers.Rest:
        return ["__rest"];
      case ExternalEmitHelpers.Decorate:
        return legacyDecorators ? ["__decorate"] : ["__esDecorate", "__runInitializers"];
      case ExternalEmitHelpers.Metadata:
        return ["__metadata"];
      case ExternalEmitHelpers.Param:
        return ["__param"];
      case ExternalEmitHelpers.Awaiter:
        return ["__awaiter"];
      case ExternalEmitHelpers.Generator:
        return ["__generator"];
      case ExternalEmitHelpers.Values:
        return ["__values"];
      case ExternalEmitHelpers.Read:
        return ["__read"];
      case ExternalEmitHelpers.SpreadArray:
        return ["__spreadArray"];
      case ExternalEmitHelpers.Await:
        return ["__await"];
      case ExternalEmitHelpers.AsyncGenerator:
        return ["__asyncGenerator"];
      case ExternalEmitHelpers.AsyncDelegator:
        return ["__asyncDelegator"];
      case ExternalEmitHelpers.AsyncValues:
        return ["__asyncValues"];
      case ExternalEmitHelpers.ExportStar:
        return ["__exportStar"];
      case ExternalEmitHelpers.ImportStar:
        return ["__importStar"];
      case ExternalEmitHelpers.ImportDefault:
        return ["__importDefault"];
      case ExternalEmitHelpers.MakeTemplateObject:
        return ["__makeTemplateObject"];
      case ExternalEmitHelpers.ClassPrivateFieldGet:
        return ["__classPrivateFieldGet"];
      case ExternalEmitHelpers.ClassPrivateFieldSet:
        return ["__classPrivateFieldSet"];
      case ExternalEmitHelpers.ClassPrivateFieldIn:
        return ["__classPrivateFieldIn"];
      case ExternalEmitHelpers.SetFunctionName:
        return ["__setFunctionName"];
      case ExternalEmitHelpers.PropKey:
        return ["__propKey"];
      case ExternalEmitHelpers.AddDisposableResourceAndDisposeResources:
        return ["__addDisposableResource", "__disposeResources"];
      default:
        return Debug.fail("Unrecognized helper");
    }
  }
  function resolveHelpersModule(file, errorNode) {
    const links = getNodeLinks(file);
    if (!links.externalHelpersModule) {
      links.externalHelpersModule = resolveExternalModule(getImportHelpersImportSpecifier(file), externalHelpersModuleNameText, Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
    }
    return links.externalHelpersModule;
  }
  function checkGrammarModifiers(node) {
    const quickResult = reportObviousDecoratorErrors(node) || reportObviousModifierErrors(node);
    if (quickResult !== void 0) {
      return quickResult;
    }
    if (isParameter(node) && parameterIsThisKeyword(node)) {
      return grammarErrorOnFirstToken(node, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters);
    }
    const blockScopeKind = isVariableStatement(node) ? node.declarationList.flags & NodeFlags.BlockScoped : NodeFlags.None;
    let lastStatic, lastDeclare, lastAsync, lastOverride, firstDecorator;
    let flags = ModifierFlags.None;
    let sawExportBeforeDecorators = false;
    let hasLeadingDecorators = false;
    for (const modifier of node.modifiers) {
      if (isDecorator(modifier)) {
        if (!nodeCanBeDecorated(legacyDecorators, node, node.parent, node.parent.parent)) {
          if (node.kind === SyntaxKind.MethodDeclaration && !nodeIsPresent(node.body)) {
            return grammarErrorOnFirstToken(node, Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
          } else {
            return grammarErrorOnFirstToken(node, Diagnostics.Decorators_are_not_valid_here);
          }
        } else if (legacyDecorators && (node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor)) {
          const accessors = getAllAccessorDeclarationsForDeclaration(node);
          if (hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) {
            return grammarErrorOnFirstToken(node, Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
          }
        }
        if (flags & ~(ModifierFlags.ExportDefault | ModifierFlags.Decorator)) {
          return grammarErrorOnNode(modifier, Diagnostics.Decorators_are_not_valid_here);
        }
        if (hasLeadingDecorators && flags & ModifierFlags.Modifier) {
          Debug.assertIsDefined(firstDecorator);
          const sourceFile = getSourceFileOfNode(modifier);
          if (!hasParseDiagnostics(sourceFile)) {
            addRelatedInfo(
              error(modifier, Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export),
              createDiagnosticForNode(firstDecorator, Diagnostics.Decorator_used_before_export_here)
            );
            return true;
          }
          return false;
        }
        flags |= ModifierFlags.Decorator;
        if (!(flags & ModifierFlags.Modifier)) {
          hasLeadingDecorators = true;
        } else if (flags & ModifierFlags.Export) {
          sawExportBeforeDecorators = true;
        }
        firstDecorator ??= modifier;
      } else {
        if (modifier.kind !== SyntaxKind.ReadonlyKeyword) {
          if (node.kind === SyntaxKind.PropertySignature || node.kind === SyntaxKind.MethodSignature) {
            return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_member, tokenToString(modifier.kind));
          }
          if (node.kind === SyntaxKind.IndexSignature && (modifier.kind !== SyntaxKind.StaticKeyword || !isClassLike(node.parent))) {
            return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_index_signature, tokenToString(modifier.kind));
          }
        }
        if (modifier.kind !== SyntaxKind.InKeyword && modifier.kind !== SyntaxKind.OutKeyword && modifier.kind !== SyntaxKind.ConstKeyword) {
          if (node.kind === SyntaxKind.TypeParameter) {
            return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_parameter, tokenToString(modifier.kind));
          }
        }
        switch (modifier.kind) {
          case SyntaxKind.ConstKeyword: {
            if (node.kind !== SyntaxKind.EnumDeclaration && node.kind !== SyntaxKind.TypeParameter) {
              return grammarErrorOnNode(node, Diagnostics.A_class_member_cannot_have_the_0_keyword, tokenToString(SyntaxKind.ConstKeyword));
            }
            const parent = isJSDocTemplateTag(node.parent) && getEffectiveJSDocHost(node.parent) || node.parent;
            if (node.kind === SyntaxKind.TypeParameter && !(isFunctionLikeDeclaration(parent) || isClassLike(parent) || isFunctionTypeNode(parent) || isConstructorTypeNode(parent) || isCallSignatureDeclaration(parent) || isConstructSignatureDeclaration(parent) || isMethodSignature(parent))) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class, tokenToString(modifier.kind));
            }
            break;
          }
          case SyntaxKind.OverrideKeyword:
            if (flags & ModifierFlags.Override) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "override");
            } else if (flags & ModifierFlags.Ambient) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare");
            } else if (flags & ModifierFlags.Readonly) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly");
            } else if (flags & ModifierFlags.Accessor) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "accessor");
            } else if (flags & ModifierFlags.Async) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "async");
            }
            flags |= ModifierFlags.Override;
            lastOverride = modifier;
            break;
          case SyntaxKind.PublicKeyword:
          case SyntaxKind.ProtectedKeyword:
          case SyntaxKind.PrivateKeyword:
            const text = visibilityToString(modifierToFlag(modifier.kind));
            if (flags & ModifierFlags.AccessibilityModifier) {
              return grammarErrorOnNode(modifier, Diagnostics.Accessibility_modifier_already_seen);
            } else if (flags & ModifierFlags.Override) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "override");
            } else if (flags & ModifierFlags.Static) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
            } else if (flags & ModifierFlags.Accessor) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "accessor");
            } else if (flags & ModifierFlags.Readonly) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
            } else if (flags & ModifierFlags.Async) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
            } else if (node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
            } else if (flags & ModifierFlags.Abstract) {
              if (modifier.kind === SyntaxKind.PrivateKeyword) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
              } else {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
              }
            } else if (isPrivateIdentifierClassElementDeclaration(node)) {
              return grammarErrorOnNode(modifier, Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
            }
            flags |= modifierToFlag(modifier.kind);
            break;
          case SyntaxKind.StaticKeyword:
            if (flags & ModifierFlags.Static) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "static");
            } else if (flags & ModifierFlags.Readonly) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
            } else if (flags & ModifierFlags.Async) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
            } else if (flags & ModifierFlags.Accessor) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "accessor");
            } else if (node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
            } else if (node.kind === SyntaxKind.Parameter) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
            } else if (flags & ModifierFlags.Abstract) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
            } else if (flags & ModifierFlags.Override) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "override");
            }
            flags |= ModifierFlags.Static;
            lastStatic = modifier;
            break;
          case SyntaxKind.AccessorKeyword:
            if (flags & ModifierFlags.Accessor) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "accessor");
            } else if (flags & ModifierFlags.Readonly) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "readonly");
            } else if (flags & ModifierFlags.Ambient) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "declare");
            } else if (node.kind !== SyntaxKind.PropertyDeclaration) {
              return grammarErrorOnNode(modifier, Diagnostics.accessor_modifier_can_only_appear_on_a_property_declaration);
            }
            flags |= ModifierFlags.Accessor;
            break;
          case SyntaxKind.ReadonlyKeyword:
            if (flags & ModifierFlags.Readonly) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "readonly");
            } else if (node.kind !== SyntaxKind.PropertyDeclaration && node.kind !== SyntaxKind.PropertySignature && node.kind !== SyntaxKind.IndexSignature && node.kind !== SyntaxKind.Parameter) {
              return grammarErrorOnNode(modifier, Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
            } else if (flags & ModifierFlags.Accessor) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "readonly", "accessor");
            }
            flags |= ModifierFlags.Readonly;
            break;
          case SyntaxKind.ExportKeyword:
            if (compilerOptions.verbatimModuleSyntax && !(node.flags & NodeFlags.Ambient) && node.kind !== SyntaxKind.TypeAliasDeclaration && node.kind !== SyntaxKind.InterfaceDeclaration && // ModuleDeclaration needs to be checked that it is uninstantiated later
            node.kind !== SyntaxKind.ModuleDeclaration && node.parent.kind === SyntaxKind.SourceFile && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === ModuleKind.CommonJS) {
              return grammarErrorOnNode(modifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
            }
            if (flags & ModifierFlags.Export) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "export");
            } else if (flags & ModifierFlags.Ambient) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
            } else if (flags & ModifierFlags.Abstract) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
            } else if (flags & ModifierFlags.Async) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
            } else if (isClassLike(node.parent)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export");
            } else if (node.kind === SyntaxKind.Parameter) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
            } else if (blockScopeKind === NodeFlags.Using) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "export");
            } else if (blockScopeKind === NodeFlags.AwaitUsing) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "export");
            }
            flags |= ModifierFlags.Export;
            break;
          case SyntaxKind.DefaultKeyword:
            const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent;
            if (container.kind === SyntaxKind.ModuleDeclaration && !isAmbientModule(container)) {
              return grammarErrorOnNode(modifier, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
            } else if (blockScopeKind === NodeFlags.Using) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "default");
            } else if (blockScopeKind === NodeFlags.AwaitUsing) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "default");
            } else if (!(flags & ModifierFlags.Export)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "default");
            } else if (sawExportBeforeDecorators) {
              return grammarErrorOnNode(firstDecorator, Diagnostics.Decorators_are_not_valid_here);
            }
            flags |= ModifierFlags.Default;
            break;
          case SyntaxKind.DeclareKeyword:
            if (flags & ModifierFlags.Ambient) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "declare");
            } else if (flags & ModifierFlags.Async) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
            } else if (flags & ModifierFlags.Override) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override");
            } else if (isClassLike(node.parent) && !isPropertyDeclaration(node)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare");
            } else if (node.kind === SyntaxKind.Parameter) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
            } else if (blockScopeKind === NodeFlags.Using) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "declare");
            } else if (blockScopeKind === NodeFlags.AwaitUsing) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "declare");
            } else if (node.parent.flags & NodeFlags.Ambient && node.parent.kind === SyntaxKind.ModuleBlock) {
              return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
            } else if (isPrivateIdentifierClassElementDeclaration(node)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
            } else if (flags & ModifierFlags.Accessor) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "declare", "accessor");
            }
            flags |= ModifierFlags.Ambient;
            lastDeclare = modifier;
            break;
          case SyntaxKind.AbstractKeyword:
            if (flags & ModifierFlags.Abstract) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "abstract");
            }
            if (node.kind !== SyntaxKind.ClassDeclaration && node.kind !== SyntaxKind.ConstructorType) {
              if (node.kind !== SyntaxKind.MethodDeclaration && node.kind !== SyntaxKind.PropertyDeclaration && node.kind !== SyntaxKind.GetAccessor && node.kind !== SyntaxKind.SetAccessor) {
                return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
              }
              if (!(node.parent.kind === SyntaxKind.ClassDeclaration && hasSyntacticModifier(node.parent, ModifierFlags.Abstract))) {
                const message = node.kind === SyntaxKind.PropertyDeclaration ? Diagnostics.Abstract_properties_can_only_appear_within_an_abstract_class : Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class;
                return grammarErrorOnNode(modifier, message);
              }
              if (flags & ModifierFlags.Static) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
              }
              if (flags & ModifierFlags.Private) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
              }
              if (flags & ModifierFlags.Async && lastAsync) {
                return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
              }
              if (flags & ModifierFlags.Override) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override");
              }
              if (flags & ModifierFlags.Accessor) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "accessor");
              }
            }
            if (isNamedDeclaration(node) && node.name.kind === SyntaxKind.PrivateIdentifier) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
            }
            flags |= ModifierFlags.Abstract;
            break;
          case SyntaxKind.AsyncKeyword:
            if (flags & ModifierFlags.Async) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "async");
            } else if (flags & ModifierFlags.Ambient || node.parent.flags & NodeFlags.Ambient) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
            } else if (node.kind === SyntaxKind.Parameter) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
            }
            if (flags & ModifierFlags.Abstract) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
            }
            flags |= ModifierFlags.Async;
            lastAsync = modifier;
            break;
          case SyntaxKind.InKeyword:
          case SyntaxKind.OutKeyword: {
            const inOutFlag = modifier.kind === SyntaxKind.InKeyword ? ModifierFlags.In : ModifierFlags.Out;
            const inOutText = modifier.kind === SyntaxKind.InKeyword ? "in" : "out";
            const parent = isJSDocTemplateTag(node.parent) && (getEffectiveJSDocHost(node.parent) || find(getJSDocRoot(node.parent)?.tags, isJSDocTypedefTag)) || node.parent;
            if (node.kind !== SyntaxKind.TypeParameter || parent && !(isInterfaceDeclaration(parent) || isClassLike(parent) || isTypeAliasDeclaration(parent) || isJSDocTypedefTag(parent))) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias, inOutText);
            }
            if (flags & inOutFlag) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, inOutText);
            }
            if (inOutFlag & ModifierFlags.In && flags & ModifierFlags.Out) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "in", "out");
            }
            flags |= inOutFlag;
            break;
          }
        }
      }
    }
    if (node.kind === SyntaxKind.Constructor) {
      if (flags & ModifierFlags.Static) {
        return grammarErrorOnNode(lastStatic, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
      }
      if (flags & ModifierFlags.Override) {
        return grammarErrorOnNode(lastOverride, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override");
      }
      if (flags & ModifierFlags.Async) {
        return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
      }
      return false;
    } else if ((node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration) && flags & ModifierFlags.Ambient) {
      return grammarErrorOnNode(lastDeclare, Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
    } else if (node.kind === SyntaxKind.Parameter && flags & ModifierFlags.ParameterPropertyModifier && isBindingPattern(node.name)) {
      return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
    } else if (node.kind === SyntaxKind.Parameter && flags & ModifierFlags.ParameterPropertyModifier && node.dotDotDotToken) {
      return grammarErrorOnNode(node, Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
    }
    if (flags & ModifierFlags.Async) {
      return checkGrammarAsyncModifier(node, lastAsync);
    }
    return false;
  }
  function reportObviousModifierErrors(node) {
    if (!node.modifiers) return false;
    const modifier = findFirstIllegalModifier(node);
    return modifier && grammarErrorOnFirstToken(modifier, Diagnostics.Modifiers_cannot_appear_here);
  }
  function findFirstModifierExcept(node, allowedModifier) {
    const modifier = find(node.modifiers, isModifier);
    return modifier && modifier.kind !== allowedModifier ? modifier : void 0;
  }
  function findFirstIllegalModifier(node) {
    switch (node.kind) {
      case SyntaxKind.GetAccessor:
      case SyntaxKind.SetAccessor:
      case SyntaxKind.Constructor:
      case SyntaxKind.PropertyDeclaration:
      case SyntaxKind.PropertySignature:
      case SyntaxKind.MethodDeclaration:
      case SyntaxKind.MethodSignature:
      case SyntaxKind.IndexSignature:
      case SyntaxKind.ModuleDeclaration:
      case SyntaxKind.ImportDeclaration:
      case SyntaxKind.ImportEqualsDeclaration:
      case SyntaxKind.ExportDeclaration:
      case SyntaxKind.ExportAssignment:
      case SyntaxKind.FunctionExpression:
      case SyntaxKind.ArrowFunction:
      case SyntaxKind.Parameter:
      case SyntaxKind.TypeParameter:
        return void 0;
      case SyntaxKind.ClassStaticBlockDeclaration:
      case SyntaxKind.PropertyAssignment:
      case SyntaxKind.ShorthandPropertyAssignment:
      case SyntaxKind.NamespaceExportDeclaration:
      case SyntaxKind.MissingDeclaration:
        return find(node.modifiers, isModifier);
      default:
        if (node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) {
          return void 0;
        }
        switch (node.kind) {
          case SyntaxKind.FunctionDeclaration:
            return findFirstModifierExcept(node, SyntaxKind.AsyncKeyword);
          case SyntaxKind.ClassDeclaration:
          case SyntaxKind.ConstructorType:
            return findFirstModifierExcept(node, SyntaxKind.AbstractKeyword);
          case SyntaxKind.ClassExpression:
          case SyntaxKind.InterfaceDeclaration:
          case SyntaxKind.TypeAliasDeclaration:
            return find(node.modifiers, isModifier);
          case SyntaxKind.VariableStatement:
            return node.declarationList.flags & NodeFlags.Using ? findFirstModifierExcept(node, SyntaxKind.AwaitKeyword) : find(node.modifiers, isModifier);
          case SyntaxKind.EnumDeclaration:
            return findFirstModifierExcept(node, SyntaxKind.ConstKeyword);
          default:
            Debug.assertNever(node);
        }
    }
  }
  function reportObviousDecoratorErrors(node) {
    const decorator = findFirstIllegalDecorator(node);
    return decorator && grammarErrorOnFirstToken(decorator, Diagnostics.Decorators_are_not_valid_here);
  }
  function findFirstIllegalDecorator(node) {
    return canHaveIllegalDecorators(node) ? find(node.modifiers, isDecorator) : void 0;
  }
  function checkGrammarAsyncModifier(node, asyncModifier) {
    switch (node.kind) {
      case SyntaxKind.MethodDeclaration:
      case SyntaxKind.FunctionDeclaration:
      case SyntaxKind.FunctionExpression:
      case SyntaxKind.ArrowFunction:
        return false;
    }
    return grammarErrorOnNode(asyncModifier, Diagnostics._0_modifier_cannot_be_used_here, "async");
  }
  function checkGrammarForDisallowedTrailingComma(list, diag = Diagnostics.Trailing_comma_not_allowed) {
    if (list && list.hasTrailingComma) {
      return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
    }
    return false;
  }
  function checkGrammarTypeParameterList(typeParameters, file) {
    if (typeParameters && typeParameters.length === 0) {
      const start = typeParameters.pos - "<".length;
      const end = skipTrivia(file.text, typeParameters.end) + ">".length;
      return grammarErrorAtPos(file, start, end - start, Diagnostics.Type_parameter_list_cannot_be_empty);
    }
    return false;
  }
  function checkGrammarParameterList(parameters) {
    let seenOptionalParameter = false;
    const parameterCount = parameters.length;
    for (let i = 0; i < parameterCount; i++) {
      const parameter = parameters[i];
      if (parameter.dotDotDotToken) {
        if (i !== parameterCount - 1) {
          return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
        }
        if (!(parameter.flags & NodeFlags.Ambient)) {
          checkGrammarForDisallowedTrailingComma(parameters, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
        }
        if (parameter.questionToken) {
          return grammarErrorOnNode(parameter.questionToken, Diagnostics.A_rest_parameter_cannot_be_optional);
        }
        if (parameter.initializer) {
          return grammarErrorOnNode(parameter.name, Diagnostics.A_rest_parameter_cannot_have_an_initializer);
        }
      } else if (hasEffectiveQuestionToken(parameter)) {
        seenOptionalParameter = true;
        if (parameter.questionToken && parameter.initializer) {
          return grammarErrorOnNode(parameter.name, Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
        }
      } else if (seenOptionalParameter && !parameter.initializer) {
        return grammarErrorOnNode(parameter.name, Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
      }
    }
  }
  function getNonSimpleParameters(parameters) {
    return filter(parameters, (parameter) => !!parameter.initializer || isBindingPattern(parameter.name) || isRestParameter(parameter));
  }
  function checkGrammarForUseStrictSimpleParameterList(node) {
    if (languageVersion >= ScriptTarget.ES2016) {
      const useStrictDirective = node.body && isBlock(node.body) && findUseStrictPrologue(node.body.statements);
      if (useStrictDirective) {
        const nonSimpleParameters = getNonSimpleParameters(node.parameters);
        if (length(nonSimpleParameters)) {
          forEach(nonSimpleParameters, (parameter) => {
            addRelatedInfo(
              error(parameter, Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive),
              createDiagnosticForNode(useStrictDirective, Diagnostics.use_strict_directive_used_here)
            );
          });
          const diagnostics2 = nonSimpleParameters.map((parameter, index) => index === 0 ? createDiagnosticForNode(parameter, Diagnostics.Non_simple_parameter_declared_here) : createDiagnosticForNode(parameter, Diagnostics.and_here));
          addRelatedInfo(error(useStrictDirective, Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list), ...diagnostics2);
          return true;
        }
      }
    }
    return false;
  }
  function checkGrammarFunctionLikeDeclaration(node) {
    const file = getSourceFileOfNode(node);
    return checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node);
  }
  function checkGrammarClassLikeDeclaration(node) {
    const file = getSourceFileOfNode(node);
    return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
  }
  function checkGrammarArrowFunction(node, file) {
    if (!isArrowFunction(node)) {
      return false;
    }
    if (node.typeParameters && !(length(node.typeParameters) > 1 || node.typeParameters.hasTrailingComma || node.typeParameters[0].constraint)) {
      if (file && fileExtensionIsOneOf(file.fileName, [Extension.Mts, Extension.Cts])) {
        grammarErrorOnNode(node.typeParameters[0], Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint);
      }
    }
    const { equalsGreaterThanToken } = node;
    const startLine = getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
    const endLine = getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
    return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, Diagnostics.Line_terminator_not_permitted_before_arrow);
  }
  function checkGrammarIndexSignatureParameters(node) {
    const parameter = node.parameters[0];
    if (node.parameters.length !== 1) {
      if (parameter) {
        return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_must_have_exactly_one_parameter);
      } else {
        return grammarErrorOnNode(node, Diagnostics.An_index_signature_must_have_exactly_one_parameter);
      }
    }
    checkGrammarForDisallowedTrailingComma(node.parameters, Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
    if (parameter.dotDotDotToken) {
      return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
    }
    if (hasEffectiveModifiers(parameter)) {
      return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
    }
    if (parameter.questionToken) {
      return grammarErrorOnNode(parameter.questionToken, Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
    }
    if (parameter.initializer) {
      return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
    }
    if (!parameter.type) {
      return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
    }
    const type = getTypeFromTypeNode(parameter.type);
    if (someType(type, (t) => !!(t.flags & TypeFlags.StringOrNumberLiteralOrUnique)) || isGenericType(type)) {
      return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead);
    }
    if (!everyType(type, isValidIndexKeyType)) {
      return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type);
    }
    if (!node.type) {
      return grammarErrorOnNode(node, Diagnostics.An_index_signature_must_have_a_type_annotation);
    }
    return false;
  }
  function checkGrammarIndexSignature(node) {
    return checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node);
  }
  function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
    if (typeArguments && typeArguments.length === 0) {
      const sourceFile = getSourceFileOfNode(node);
      const start = typeArguments.pos - "<".length;
      const end = skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
      return grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Type_argument_list_cannot_be_empty);
    }
    return false;
  }
  function checkGrammarTypeArguments(node, typeArguments) {
    return checkGrammarForDisallowedTrailingComma(typeArguments) || checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
  }
  function checkGrammarTaggedTemplateChain(node) {
    if (node.questionDotToken || node.flags & NodeFlags.OptionalChain) {
      return grammarErrorOnNode(node.template, Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
    }
    return false;
  }
  function checkGrammarHeritageClause(node) {
    const types = node.types;
    if (checkGrammarForDisallowedTrailingComma(types)) {
      return true;
    }
    if (types && types.length === 0) {
      const listType = tokenToString(node.token);
      return grammarErrorAtPos(node, types.pos, 0, Diagnostics._0_list_cannot_be_empty, listType);
    }
    return some(types, checkGrammarExpressionWithTypeArguments);
  }
  function checkGrammarExpressionWithTypeArguments(node) {
    if (isExpressionWithTypeArguments(node) && isImportKeyword(node.expression) && node.typeArguments) {
      return grammarErrorOnNode(node, Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments);
    }
    return checkGrammarTypeArguments(node, node.typeArguments);
  }
  function checkGrammarClassDeclarationHeritageClauses(node) {
    let seenExtendsClause = false;
    let seenImplementsClause = false;
    if (!checkGrammarModifiers(node) && node.heritageClauses) {
      for (const heritageClause of node.heritageClauses) {
        if (heritageClause.token === SyntaxKind.ExtendsKeyword) {
          if (seenExtendsClause) {
            return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen);
          }
          if (seenImplementsClause) {
            return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_must_precede_implements_clause);
          }
          if (heritageClause.types.length > 1) {
            return grammarErrorOnFirstToken(heritageClause.types[1], Diagnostics.Classes_can_only_extend_a_single_class);
          }
          seenExtendsClause = true;
        } else {
          Debug.assert(heritageClause.token === SyntaxKind.ImplementsKeyword);
          if (seenImplementsClause) {
            return grammarErrorOnFirstToken(heritageClause, Diagnostics.implements_clause_already_seen);
          }
          seenImplementsClause = true;
        }
        checkGrammarHeritageClause(heritageClause);
      }
    }
  }
  function checkGrammarInterfaceDeclaration(node) {
    let seenExtendsClause = false;
    if (node.heritageClauses) {
      for (const heritageClause of node.heritageClauses) {
        if (heritageClause.token === SyntaxKind.ExtendsKeyword) {
          if (seenExtendsClause) {
            return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen);
          }
          seenExtendsClause = true;
        } else {
          Debug.assert(heritageClause.token === SyntaxKind.ImplementsKeyword);
          return grammarErrorOnFirstToken(heritageClause, Diagnostics.Interface_declaration_cannot_have_implements_clause);
        }
        checkGrammarHeritageClause(heritageClause);
      }
    }
    return false;
  }
  function checkGrammarComputedPropertyName(node) {
    if (node.kind !== SyntaxKind.ComputedPropertyName) {
      return false;
    }
    const computedPropertyName = node;
    if (computedPropertyName.expression.kind === SyntaxKind.BinaryExpression && computedPropertyName.expression.operatorToken.kind === SyntaxKind.CommaToken) {
      return grammarErrorOnNode(computedPropertyName.expression, Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
    }
    return false;
  }
  function checkGrammarForGenerator(node) {
    if (node.asteriskToken) {
      Debug.assert(
        node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.MethodDeclaration
      );
      if (node.flags & NodeFlags.Ambient) {
        return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
      }
      if (!node.body) {
        return grammarErrorOnNode(node.asteriskToken, Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
      }
    }
  }
  function checkGrammarForInvalidQuestionMark(questionToken, message) {
    return !!questionToken && grammarErrorOnNode(questionToken, message);
  }
  function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
    return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
  }
  function checkGrammarObjectLiteralExpression(node, inDestructuring) {
    const seen = /* @__PURE__ */ new Map();
    for (const prop of node.properties) {
      if (prop.kind === SyntaxKind.SpreadAssignment) {
        if (inDestructuring) {
          const expression = skipParentheses(prop.expression);
          if (isArrayLiteralExpression(expression) || isObjectLiteralExpression(expression)) {
            return grammarErrorOnNode(prop.expression, Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
          }
        }
        continue;
      }
      const name = prop.name;
      if (name.kind === SyntaxKind.ComputedPropertyName) {
        checkGrammarComputedPropertyName(name);
      }
      if (prop.kind === SyntaxKind.ShorthandPropertyAssignment && !inDestructuring && prop.objectAssignmentInitializer) {
        grammarErrorOnNode(prop.equalsToken, 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);
      }
      if (name.kind === SyntaxKind.PrivateIdentifier) {
        grammarErrorOnNode(name, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
      }
      if (canHaveModifiers(prop) && prop.modifiers) {
        for (const mod of prop.modifiers) {
          if (isModifier(mod) && (mod.kind !== SyntaxKind.AsyncKeyword || prop.kind !== SyntaxKind.MethodDeclaration)) {
            grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod));
          }
        }
      } else if (canHaveIllegalModifiers(prop) && prop.modifiers) {
        for (const mod of prop.modifiers) {
          if (isModifier(mod)) {
            grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod));
          }
        }
      }
      let currentKind;
      switch (prop.kind) {
        case SyntaxKind.ShorthandPropertyAssignment:
        case SyntaxKind.PropertyAssignment:
          checkGrammarForInvalidExclamationToken(prop.exclamationToken, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
          checkGrammarForInvalidQuestionMark(prop.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional);
          if (name.kind === SyntaxKind.NumericLiteral) {
            checkGrammarNumericLiteral(name);
          }
          if (name.kind === SyntaxKind.BigIntLiteral) {
            addErrorOrSuggestion(
              /*isError*/
              true,
              createDiagnosticForNode(name, Diagnostics.A_bigint_literal_cannot_be_used_as_a_property_name)
            );
          }
          currentKind = 4 /* PropertyAssignment */;
          break;
        case SyntaxKind.MethodDeclaration:
          currentKind = 8 /* Method */;
          break;
        case SyntaxKind.GetAccessor:
          currentKind = 1 /* GetAccessor */;
          break;
        case SyntaxKind.SetAccessor:
          currentKind = 2 /* SetAccessor */;
          break;
        default:
          Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
      }
      if (!inDestructuring) {
        const effectiveName = getEffectivePropertyNameForPropertyNameNode(name);
        if (effectiveName === void 0) {
          continue;
        }
        const existingKind = seen.get(effectiveName);
        if (!existingKind) {
          seen.set(effectiveName, currentKind);
        } else {
          if (currentKind & 8 /* Method */ && existingKind & 8 /* Method */) {
            grammarErrorOnNode(name, Diagnostics.Duplicate_identifier_0, getTextOfNode(name));
          } else if (currentKind & 4 /* PropertyAssignment */ && existingKind & 4 /* PropertyAssignment */) {
            grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name, getTextOfNode(name));
          } else if (currentKind & 3 /* GetOrSetAccessor */ && existingKind & 3 /* GetOrSetAccessor */) {
            if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
              seen.set(effectiveName, currentKind | existingKind);
            } else {
              return grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
            }
          } else {
            return grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
          }
        }
      }
    }
  }
  function checkGrammarJsxElement(node) {
    checkGrammarJsxName(node.tagName);
    checkGrammarTypeArguments(node, node.typeArguments);
    const seen = /* @__PURE__ */ new Map();
    for (const attr of node.attributes.properties) {
      if (attr.kind === SyntaxKind.JsxSpreadAttribute) {
        continue;
      }
      const { name, initializer } = attr;
      const escapedText = getEscapedTextOfJsxAttributeName(name);
      if (!seen.get(escapedText)) {
        seen.set(escapedText, true);
      } else {
        return grammarErrorOnNode(name, Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
      }
      if (initializer && initializer.kind === SyntaxKind.JsxExpression && !initializer.expression) {
        return grammarErrorOnNode(initializer, Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
      }
    }
  }
  function checkGrammarJsxName(node) {
    if (isPropertyAccessExpression(node) && isJsxNamespacedName(node.expression)) {
      return grammarErrorOnNode(node.expression, Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names);
    }
    if (isJsxNamespacedName(node) && getJSXTransformEnabled(compilerOptions) && !isIntrinsicJsxName(node.namespace.escapedText)) {
      return grammarErrorOnNode(node, Diagnostics.React_components_cannot_include_JSX_namespace_names);
    }
  }
  function checkGrammarJsxExpression(node) {
    if (node.expression && isCommaSequence(node.expression)) {
      return grammarErrorOnNode(node.expression, Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
    }
  }
  function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
    if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
      return true;
    }
    if (forInOrOfStatement.kind === SyntaxKind.ForOfStatement && forInOrOfStatement.awaitModifier) {
      if (!(forInOrOfStatement.flags & NodeFlags.AwaitContext)) {
        const sourceFile = getSourceFileOfNode(forInOrOfStatement);
        if (isInTopLevelContext(forInOrOfStatement)) {
          if (!hasParseDiagnostics(sourceFile)) {
            if (!isEffectiveExternalModule(sourceFile, compilerOptions)) {
              diagnostics.add(createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module));
            }
            switch (moduleKind) {
              case ModuleKind.Node16:
              case ModuleKind.NodeNext:
                if (sourceFile.impliedNodeFormat === ModuleKind.CommonJS) {
                  diagnostics.add(
                    createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level)
                  );
                  break;
                }
              // fallthrough
              case ModuleKind.ES2022:
              case ModuleKind.ESNext:
              case ModuleKind.Preserve:
              case ModuleKind.System:
                if (languageVersion >= ScriptTarget.ES2017) {
                  break;
                }
              // fallthrough
              default:
                diagnostics.add(
                  createDiagnosticForNode(forInOrOfStatement.awaitModifier, 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)
                );
                break;
            }
          }
        } else {
          if (!hasParseDiagnostics(sourceFile)) {
            const diagnostic = createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules);
            const func = getContainingFunction(forInOrOfStatement);
            if (func && func.kind !== SyntaxKind.Constructor) {
              Debug.assert((getFunctionFlags(func) & FunctionFlags.Async) === 0, "Enclosing function should never be an async function.");
              const relatedInfo = createDiagnosticForNode(func, Diagnostics.Did_you_mean_to_mark_this_function_as_async);
              addRelatedInfo(diagnostic, relatedInfo);
            }
            diagnostics.add(diagnostic);
            return true;
          }
        }
      }
    }
    if (isForOfStatement(forInOrOfStatement) && !(forInOrOfStatement.flags & NodeFlags.AwaitContext) && isIdentifier(forInOrOfStatement.initializer) && forInOrOfStatement.initializer.escapedText === "async") {
      grammarErrorOnNode(forInOrOfStatement.initializer, Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async);
      return false;
    }
    if (forInOrOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList) {
      const variableList = forInOrOfStatement.initializer;
      if (!checkGrammarVariableDeclarationList(variableList)) {
        const declarations = variableList.declarations;
        if (!declarations.length) {
          return false;
        }
        if (declarations.length > 1) {
          const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement ? Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
          return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
        }
        const firstDeclaration = declarations[0];
        if (firstDeclaration.initializer) {
          const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement ? Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
          return grammarErrorOnNode(firstDeclaration.name, diagnostic);
        }
        if (firstDeclaration.type) {
          const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
          return grammarErrorOnNode(firstDeclaration, diagnostic);
        }
      }
    }
    return false;
  }
  function checkGrammarAccessor(accessor) {
    if (!(accessor.flags & NodeFlags.Ambient) && accessor.parent.kind !== SyntaxKind.TypeLiteral && accessor.parent.kind !== SyntaxKind.InterfaceDeclaration) {
      if (languageVersion < ScriptTarget.ES2015 && isPrivateIdentifier(accessor.name)) {
        return grammarErrorOnNode(accessor.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
      }
      if (accessor.body === void 0 && !hasSyntacticModifier(accessor, ModifierFlags.Abstract)) {
        return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, Diagnostics._0_expected, "{");
      }
    }
    if (accessor.body) {
      if (hasSyntacticModifier(accessor, ModifierFlags.Abstract)) {
        return grammarErrorOnNode(accessor, Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
      }
      if (accessor.parent.kind === SyntaxKind.TypeLiteral || accessor.parent.kind === SyntaxKind.InterfaceDeclaration) {
        return grammarErrorOnNode(accessor.body, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
      }
    }
    if (accessor.typeParameters) {
      return grammarErrorOnNode(accessor.name, Diagnostics.An_accessor_cannot_have_type_parameters);
    }
    if (!doesAccessorHaveCorrectParameterCount(accessor)) {
      return grammarErrorOnNode(
        accessor.name,
        accessor.kind === SyntaxKind.GetAccessor ? Diagnostics.A_get_accessor_cannot_have_parameters : Diagnostics.A_set_accessor_must_have_exactly_one_parameter
      );
    }
    if (accessor.kind === SyntaxKind.SetAccessor) {
      if (accessor.type) {
        return grammarErrorOnNode(accessor.name, Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
      }
      const parameter = Debug.checkDefined(getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
      if (parameter.dotDotDotToken) {
        return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_set_accessor_cannot_have_rest_parameter);
      }
      if (parameter.questionToken) {
        return grammarErrorOnNode(parameter.questionToken, Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
      }
      if (parameter.initializer) {
        return grammarErrorOnNode(accessor.name, Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
      }
    }
    return false;
  }
  function doesAccessorHaveCorrectParameterCount(accessor) {
    return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === SyntaxKind.GetAccessor ? 0 : 1);
  }
  function getAccessorThisParameter(accessor) {
    if (accessor.parameters.length === (accessor.kind === SyntaxKind.GetAccessor ? 1 : 2)) {
      return getThisParameter(accessor);
    }
  }
  function checkGrammarTypeOperatorNode(node) {
    if (node.operator === SyntaxKind.UniqueKeyword) {
      if (node.type.kind !== SyntaxKind.SymbolKeyword) {
        return grammarErrorOnNode(node.type, Diagnostics._0_expected, tokenToString(SyntaxKind.SymbolKeyword));
      }
      let parent = walkUpParenthesizedTypes(node.parent);
      if (isInJSFile(parent) && isJSDocTypeExpression(parent)) {
        const host2 = getJSDocHost(parent);
        if (host2) {
          parent = getSingleVariableOfVariableStatement(host2) || host2;
        }
      }
      switch (parent.kind) {
        case SyntaxKind.VariableDeclaration:
          const decl = parent;
          if (decl.name.kind !== SyntaxKind.Identifier) {
            return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
          }
          if (!isVariableDeclarationInVariableStatement(decl)) {
            return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
          }
          if (!(decl.parent.flags & NodeFlags.Const)) {
            return grammarErrorOnNode(parent.name, Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
          }
          break;
        case SyntaxKind.PropertyDeclaration:
          if (!isStatic(parent) || !hasEffectiveReadonlyModifier(parent)) {
            return grammarErrorOnNode(parent.name, Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
          }
          break;
        case SyntaxKind.PropertySignature:
          if (!hasSyntacticModifier(parent, ModifierFlags.Readonly)) {
            return grammarErrorOnNode(parent.name, Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
          }
          break;
        default:
          return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_are_not_allowed_here);
      }
    } else if (node.operator === SyntaxKind.ReadonlyKeyword) {
      if (node.type.kind !== SyntaxKind.ArrayType && node.type.kind !== SyntaxKind.TupleType) {
        return grammarErrorOnFirstToken(node, Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, tokenToString(SyntaxKind.SymbolKeyword));
      }
    }
  }
  function checkGrammarForInvalidDynamicName(node, message) {
    if (isNonBindableDynamicName(node)) {
      return grammarErrorOnNode(node, message);
    }
  }
  function checkGrammarMethod(node) {
    if (checkGrammarFunctionLikeDeclaration(node)) {
      return true;
    }
    if (node.kind === SyntaxKind.MethodDeclaration) {
      if (node.parent.kind === SyntaxKind.ObjectLiteralExpression) {
        if (node.modifiers && !(node.modifiers.length === 1 && first(node.modifiers).kind === SyntaxKind.AsyncKeyword)) {
          return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here);
        } else if (checkGrammarForInvalidQuestionMark(node.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional)) {
          return true;
        } else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
          return true;
        } else if (node.body === void 0) {
          return grammarErrorAtPos(node, node.end - 1, ";".length, Diagnostics._0_expected, "{");
        }
      }
      if (checkGrammarForGenerator(node)) {
        return true;
      }
    }
    if (isClassLike(node.parent)) {
      if (languageVersion < ScriptTarget.ES2015 && isPrivateIdentifier(node.name)) {
        return grammarErrorOnNode(node.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
      }
      if (node.flags & NodeFlags.Ambient) {
        return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
      } else if (node.kind === SyntaxKind.MethodDeclaration && !node.body) {
        return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
      }
    } else if (node.parent.kind === SyntaxKind.InterfaceDeclaration) {
      return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
    } else if (node.parent.kind === SyntaxKind.TypeLiteral) {
      return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
    }
  }
  function checkGrammarBreakOrContinueStatement(node) {
    let current = node;
    while (current) {
      if (isFunctionLikeOrClassStaticBlockDeclaration(current)) {
        return grammarErrorOnNode(node, Diagnostics.Jump_target_cannot_cross_function_boundary);
      }
      switch (current.kind) {
        case SyntaxKind.LabeledStatement:
          if (node.label && current.label.escapedText === node.label.escapedText) {
            const isMisplacedContinueLabel = node.kind === SyntaxKind.ContinueStatement && !isIterationStatement(
              current.statement,
              /*lookInLabeledStatements*/
              true
            );
            if (isMisplacedContinueLabel) {
              return grammarErrorOnNode(node, Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
            }
            return false;
          }
          break;
        case SyntaxKind.SwitchStatement:
          if (node.kind === SyntaxKind.BreakStatement && !node.label) {
            return false;
          }
          break;
        default:
          if (isIterationStatement(
            current,
            /*lookInLabeledStatements*/
            false
          ) && !node.label) {
            return false;
          }
          break;
      }
      current = current.parent;
    }
    if (node.label) {
      const message = node.kind === SyntaxKind.BreakStatement ? Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
      return grammarErrorOnNode(node, message);
    } else {
      const message = node.kind === SyntaxKind.BreakStatement ? Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
      return grammarErrorOnNode(node, message);
    }
  }
  function checkGrammarBindingElement(node) {
    if (node.dotDotDotToken) {
      const elements = node.parent.elements;
      if (node !== last(elements)) {
        return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
      }
      checkGrammarForDisallowedTrailingComma(elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
      if (node.propertyName) {
        return grammarErrorOnNode(node.name, Diagnostics.A_rest_element_cannot_have_a_property_name);
      }
    }
    if (node.dotDotDotToken && node.initializer) {
      return grammarErrorAtPos(node, node.initializer.pos - 1, 1, Diagnostics.A_rest_element_cannot_have_an_initializer);
    }
  }
  function isStringOrNumberLiteralExpression(expr) {
    return isStringOrNumericLiteralLike(expr) || expr.kind === SyntaxKind.PrefixUnaryExpression && expr.operator === SyntaxKind.MinusToken && expr.operand.kind === SyntaxKind.NumericLiteral;
  }
  function isBigIntLiteralExpression(expr) {
    return expr.kind === SyntaxKind.BigIntLiteral || expr.kind === SyntaxKind.PrefixUnaryExpression && expr.operator === SyntaxKind.MinusToken && expr.operand.kind === SyntaxKind.BigIntLiteral;
  }
  function isSimpleLiteralEnumReference(expr) {
    if ((isPropertyAccessExpression(expr) || isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression)) && isEntityNameExpression(expr.expression)) {
      return !!(checkExpressionCached(expr).flags & TypeFlags.EnumLike);
    }
  }
  function checkAmbientInitializer(node) {
    const initializer = node.initializer;
    if (initializer) {
      const isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || isSimpleLiteralEnumReference(initializer) || initializer.kind === SyntaxKind.TrueKeyword || initializer.kind === SyntaxKind.FalseKeyword || isBigIntLiteralExpression(initializer));
      const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConstLike(node);
      if (isConstOrReadonly && !node.type) {
        if (isInvalidInitializer) {
          return grammarErrorOnNode(initializer, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
        }
      } else {
        return grammarErrorOnNode(initializer, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
      }
    }
  }
  function checkGrammarVariableDeclaration(node) {
    const nodeFlags = getCombinedNodeFlagsCached(node);
    const blockScopeKind = nodeFlags & NodeFlags.BlockScoped;
    if (isBindingPattern(node.name)) {
      switch (blockScopeKind) {
        case NodeFlags.AwaitUsing:
          return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "await using");
        case NodeFlags.Using:
          return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "using");
      }
    }
    if (node.parent.parent.kind !== SyntaxKind.ForInStatement && node.parent.parent.kind !== SyntaxKind.ForOfStatement) {
      if (nodeFlags & NodeFlags.Ambient) {
        checkAmbientInitializer(node);
      } else if (!node.initializer) {
        if (isBindingPattern(node.name) && !isBindingPattern(node.parent)) {
          return grammarErrorOnNode(node, Diagnostics.A_destructuring_declaration_must_have_an_initializer);
        }
        switch (blockScopeKind) {
          case NodeFlags.AwaitUsing:
            return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "await using");
          case NodeFlags.Using:
            return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "using");
          case NodeFlags.Const:
            return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "const");
        }
      }
    }
    if (node.exclamationToken && (node.parent.parent.kind !== SyntaxKind.VariableStatement || !node.type || node.initializer || nodeFlags & NodeFlags.Ambient)) {
      const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context;
      return grammarErrorOnNode(node.exclamationToken, message);
    }
    if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < ModuleKind.System && !(node.parent.parent.flags & NodeFlags.Ambient) && hasSyntacticModifier(node.parent.parent, ModifierFlags.Export)) {
      checkESModuleMarker(node.name);
    }
    return !!blockScopeKind && checkGrammarNameInLetOrConstDeclarations(node.name);
  }
  function checkESModuleMarker(name) {
    if (name.kind === SyntaxKind.Identifier) {
      if (idText(name) === "__esModule") {
        return grammarErrorOnNodeSkippedOn("noEmit", name, Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
      }
    } else {
      const elements = name.elements;
      for (const element of elements) {
        if (!isOmittedExpression(element)) {
          return checkESModuleMarker(element.name);
        }
      }
    }
    return false;
  }
  function checkGrammarNameInLetOrConstDeclarations(name) {
    if (name.kind === SyntaxKind.Identifier) {
      if (name.escapedText === "let") {
        return grammarErrorOnNode(name, Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
      }
    } else {
      const elements = name.elements;
      for (const element of elements) {
        if (!isOmittedExpression(element)) {
          checkGrammarNameInLetOrConstDeclarations(element.name);
        }
      }
    }
    return false;
  }
  function checkGrammarVariableDeclarationList(declarationList) {
    const declarations = declarationList.declarations;
    if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
      return true;
    }
    if (!declarationList.declarations.length) {
      return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, Diagnostics.Variable_declaration_list_cannot_be_empty);
    }
    const blockScopeFlags = declarationList.flags & NodeFlags.BlockScoped;
    if ((blockScopeFlags === NodeFlags.Using || blockScopeFlags === NodeFlags.AwaitUsing) && isForInStatement(declarationList.parent)) {
      return grammarErrorOnNode(
        declarationList,
        blockScopeFlags === NodeFlags.Using ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration : Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration
      );
    }
    if (blockScopeFlags === NodeFlags.AwaitUsing) {
      return checkAwaitGrammar(declarationList);
    }
    return false;
  }
  function allowLetAndConstDeclarations(parent) {
    switch (parent.kind) {
      case SyntaxKind.IfStatement:
      case SyntaxKind.DoStatement:
      case SyntaxKind.WhileStatement:
      case SyntaxKind.WithStatement:
      case SyntaxKind.ForStatement:
      case SyntaxKind.ForInStatement:
      case SyntaxKind.ForOfStatement:
        return false;
      case SyntaxKind.LabeledStatement:
        return allowLetAndConstDeclarations(parent.parent);
    }
    return true;
  }
  function checkGrammarForDisallowedBlockScopedVariableStatement(node) {
    if (!allowLetAndConstDeclarations(node.parent)) {
      const blockScopeKind = getCombinedNodeFlagsCached(node.declarationList) & NodeFlags.BlockScoped;
      if (blockScopeKind) {
        const keyword = blockScopeKind === NodeFlags.Let ? "let" : blockScopeKind === NodeFlags.Const ? "const" : blockScopeKind === NodeFlags.Using ? "using" : blockScopeKind === NodeFlags.AwaitUsing ? "await using" : Debug.fail("Unknown BlockScope flag");
        return grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, keyword);
      }
    }
  }
  function checkGrammarMetaProperty(node) {
    const escapedText = node.name.escapedText;
    switch (node.keywordToken) {
      case SyntaxKind.NewKeyword:
        if (escapedText !== "target") {
          return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, unescapeLeadingUnderscores(node.name.escapedText), tokenToString(node.keywordToken), "target");
        }
        break;
      case SyntaxKind.ImportKeyword:
        if (escapedText !== "meta") {
          return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, unescapeLeadingUnderscores(node.name.escapedText), tokenToString(node.keywordToken), "meta");
        }
        break;
    }
  }
  function hasParseDiagnostics(sourceFile) {
    return sourceFile.parseDiagnostics.length > 0;
  }
  function grammarErrorOnFirstToken(node, message, ...args) {
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile)) {
      const span = getSpanOfTokenAtPosition(sourceFile, node.pos);
      diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message, ...args));
      return true;
    }
    return false;
  }
  function grammarErrorAtPos(nodeForSourceFile, start, length2, message, ...args) {
    const sourceFile = getSourceFileOfNode(nodeForSourceFile);
    if (!hasParseDiagnostics(sourceFile)) {
      diagnostics.add(createFileDiagnostic(sourceFile, start, length2, message, ...args));
      return true;
    }
    return false;
  }
  function grammarErrorOnNodeSkippedOn(key, node, message, ...args) {
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile)) {
      errorSkippedOn(key, node, message, ...args);
      return true;
    }
    return false;
  }
  function grammarErrorOnNode(node, message, ...args) {
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile)) {
      diagnostics.add(createDiagnosticForNode(node, message, ...args));
      return true;
    }
    return false;
  }
  function checkGrammarConstructorTypeParameters(node) {
    const jsdocTypeParameters = isInJSFile(node) ? getJSDocTypeParameterDeclarations(node) : void 0;
    const range = node.typeParameters || jsdocTypeParameters && firstOrUndefined(jsdocTypeParameters);
    if (range) {
      const pos = range.pos === range.end ? range.pos : skipTrivia(getSourceFileOfNode(node).text, range.pos);
      return grammarErrorAtPos(node, pos, range.end - pos, Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
    }
  }
  function checkGrammarConstructorTypeAnnotation(node) {
    const type = node.type || getEffectiveReturnTypeNode(node);
    if (type) {
      return grammarErrorOnNode(type, Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
    }
  }
  function checkGrammarProperty(node) {
    if (isComputedPropertyName(node.name) && isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === SyntaxKind.InKeyword) {
      return grammarErrorOnNode(node.parent.members[0], Diagnostics.A_mapped_type_may_not_declare_properties_or_methods);
    }
    if (isClassLike(node.parent)) {
      if (isStringLiteral(node.name) && node.name.text === "constructor") {
        return grammarErrorOnNode(node.name, Diagnostics.Classes_may_not_have_a_field_named_constructor);
      }
      if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) {
        return true;
      }
      if (languageVersion < ScriptTarget.ES2015 && isPrivateIdentifier(node.name)) {
        return grammarErrorOnNode(node.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
      }
      if (languageVersion < ScriptTarget.ES2015 && isAutoAccessorPropertyDeclaration(node)) {
        return grammarErrorOnNode(node.name, Diagnostics.Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher);
      }
      if (isAutoAccessorPropertyDeclaration(node) && checkGrammarForInvalidQuestionMark(node.questionToken, Diagnostics.An_accessor_property_cannot_be_declared_optional)) {
        return true;
      }
    } else if (node.parent.kind === SyntaxKind.InterfaceDeclaration) {
      if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
        return true;
      }
      Debug.assertNode(node, isPropertySignature);
      if (node.initializer) {
        return grammarErrorOnNode(node.initializer, Diagnostics.An_interface_property_cannot_have_an_initializer);
      }
    } else if (isTypeLiteralNode(node.parent)) {
      if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
        return true;
      }
      Debug.assertNode(node, isPropertySignature);
      if (node.initializer) {
        return grammarErrorOnNode(node.initializer, Diagnostics.A_type_literal_property_cannot_have_an_initializer);
      }
    }
    if (node.flags & NodeFlags.Ambient) {
      checkAmbientInitializer(node);
    }
    if (isPropertyDeclaration(node) && node.exclamationToken && (!isClassLike(node.parent) || !node.type || node.initializer || node.flags & NodeFlags.Ambient || isStatic(node) || hasAbstractModifier(node))) {
      const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context;
      return grammarErrorOnNode(node.exclamationToken, message);
    }
  }
  function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
    if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.TypeAliasDeclaration || node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration || node.kind === SyntaxKind.ExportDeclaration || node.kind === SyntaxKind.ExportAssignment || node.kind === SyntaxKind.NamespaceExportDeclaration || hasSyntacticModifier(node, ModifierFlags.Ambient | ModifierFlags.Export | ModifierFlags.Default)) {
      return false;
    }
    return grammarErrorOnFirstToken(node, Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
  }
  function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
    for (const decl of file.statements) {
      if (isDeclaration(decl) || decl.kind === SyntaxKind.VariableStatement) {
        if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
          return true;
        }
      }
    }
    return false;
  }
  function checkGrammarSourceFile(node) {
    return !!(node.flags & NodeFlags.Ambient) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
  }
  function checkGrammarStatementInAmbientContext(node) {
    if (node.flags & NodeFlags.Ambient) {
      const links = getNodeLinks(node);
      if (!links.hasReportedStatementInAmbientContext && (isFunctionLike(node.parent) || isAccessor(node.parent))) {
        return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
      }
      if (node.parent.kind === SyntaxKind.Block || node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) {
        const links2 = getNodeLinks(node.parent);
        if (!links2.hasReportedStatementInAmbientContext) {
          return links2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
        }
      } else {
      }
    }
    return false;
  }
  function checkGrammarNumericLiteral(node) {
    const isFractional = getTextOfNode(node).includes(".");
    const isScientific = node.numericLiteralFlags & TokenFlags.Scientific;
    if (isFractional || isScientific) {
      return;
    }
    const value = +node.text;
    if (value <= 2 ** 53 - 1) {
      return;
    }
    addErrorOrSuggestion(
      /*isError*/
      false,
      createDiagnosticForNode(node, Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers)
    );
  }
  function checkGrammarBigIntLiteral(node) {
    const literalType = isLiteralTypeNode(node.parent) || isPrefixUnaryExpression(node.parent) && isLiteralTypeNode(node.parent.parent);
    if (!literalType) {
      if (languageVersion < ScriptTarget.ES2020) {
        if (grammarErrorOnNode(node, Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
          return true;
        }
      }
    }
    return false;
  }
  function grammarErrorAfterFirstToken(node, message, ...args) {
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile)) {
      const span = getSpanOfTokenAtPosition(sourceFile, node.pos);
      diagnostics.add(createFileDiagnostic(
        sourceFile,
        textSpanEnd(span),
        /*length*/
        0,
        message,
        ...args
      ));
      return true;
    }
    return false;
  }
  function getAmbientModules() {
    if (!ambientModulesCache) {
      ambientModulesCache = [];
      globals.forEach((global, sym) => {
        if (ambientModuleSymbolRegex.test(sym)) {
          ambientModulesCache.push(global);
        }
      });
    }
    return ambientModulesCache;
  }
  function checkGrammarImportClause(node) {
    if (node.isTypeOnly && node.name && node.namedBindings) {
      return grammarErrorOnNode(node, Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
    }
    if (node.isTypeOnly && node.namedBindings?.kind === SyntaxKind.NamedImports) {
      return checkGrammarNamedImportsOrExports(node.namedBindings);
    }
    return false;
  }
  function checkGrammarNamedImportsOrExports(namedBindings) {
    return !!forEach(namedBindings.elements, (specifier) => {
      if (specifier.isTypeOnly) {
        return grammarErrorOnFirstToken(
          specifier,
          specifier.kind === SyntaxKind.ImportSpecifier ? Diagnostics.The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement : Diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement
        );
      }
    });
  }
  function checkGrammarImportCallExpression(node) {
    if (compilerOptions.verbatimModuleSyntax && moduleKind === ModuleKind.CommonJS) {
      return grammarErrorOnNode(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
    }
    if (moduleKind === ModuleKind.ES2015) {
      return grammarErrorOnNode(node, Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd_system_umd_node16_or_nodenext);
    }
    if (node.typeArguments) {
      return grammarErrorOnNode(node, Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments);
    }
    const nodeArguments = node.arguments;
    if (moduleKind !== ModuleKind.ESNext && moduleKind !== ModuleKind.NodeNext && moduleKind !== ModuleKind.Node16 && moduleKind !== ModuleKind.Preserve) {
      checkGrammarForDisallowedTrailingComma(nodeArguments);
      if (nodeArguments.length > 1) {
        const importAttributesArgument = nodeArguments[1];
        return grammarErrorOnNode(importAttributesArgument, Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_nodenext_or_preserve);
      }
    }
    if (nodeArguments.length === 0 || nodeArguments.length > 2) {
      return grammarErrorOnNode(node, Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments);
    }
    const spreadElement = find(nodeArguments, isSpreadElement);
    if (spreadElement) {
      return grammarErrorOnNode(spreadElement, Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element);
    }
    return false;
  }
  function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
    const sourceObjectFlags = getObjectFlags(source);
    if (sourceObjectFlags & (ObjectFlags.Reference | ObjectFlags.Anonymous) && unionTarget.flags & TypeFlags.Union) {
      return find(unionTarget.types, (target) => {
        if (target.flags & TypeFlags.Object) {
          const overlapObjFlags = sourceObjectFlags & getObjectFlags(target);
          if (overlapObjFlags & ObjectFlags.Reference) {
            return source.target === target.target;
          }
          if (overlapObjFlags & ObjectFlags.Anonymous) {
            return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
          }
        }
        return false;
      });
    }
  }
  function findBestTypeForObjectLiteral(source, unionTarget) {
    if (getObjectFlags(source) & ObjectFlags.ObjectLiteral && someType(unionTarget, isArrayLikeType)) {
      return find(unionTarget.types, (t) => !isArrayLikeType(t));
    }
  }
  function findBestTypeForInvokable(source, unionTarget) {
    let signatureKind = SignatureKind.Call;
    const hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || (signatureKind = SignatureKind.Construct, getSignaturesOfType(source, signatureKind).length > 0);
    if (hasSignatures) {
      return find(unionTarget.types, (t) => getSignaturesOfType(t, signatureKind).length > 0);
    }
  }
  function findMostOverlappyType(source, unionTarget) {
    let bestMatch;
    if (!(source.flags & (TypeFlags.Primitive | TypeFlags.InstantiablePrimitive))) {
      let matchingCount = 0;
      for (const target of unionTarget.types) {
        if (!(target.flags & (TypeFlags.Primitive | TypeFlags.InstantiablePrimitive))) {
          const overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
          if (overlap.flags & TypeFlags.Index) {
            return target;
          } else if (isUnitType(overlap) || overlap.flags & TypeFlags.Union) {
            const len = overlap.flags & TypeFlags.Union ? countWhere(overlap.types, isUnitType) : 1;
            if (len >= matchingCount) {
              bestMatch = target;
              matchingCount = len;
            }
          }
        }
      }
    }
    return bestMatch;
  }
  function filterPrimitivesIfContainsNonPrimitive(type) {
    if (maybeTypeOfKind(type, TypeFlags.NonPrimitive)) {
      const result = filterType(type, (t) => !(t.flags & TypeFlags.Primitive));
      if (!(result.flags & TypeFlags.Never)) {
        return result;
      }
    }
    return type;
  }
  function findMatchingDiscriminantType(source, target, isRelatedTo) {
    if (target.flags & TypeFlags.Union && source.flags & (TypeFlags.Intersection | TypeFlags.Object)) {
      const match = getMatchingUnionConstituentForType(target, source);
      if (match) {
        return match;
      }
      const sourceProperties = getPropertiesOfType(source);
      if (sourceProperties) {
        const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
        if (sourcePropertiesFiltered) {
          const discriminated = discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, (p) => [() => getTypeOfSymbol(p), p.escapedName]), isRelatedTo);
          if (discriminated !== target) {
            return discriminated;
          }
        }
      }
    }
    return void 0;
  }
  function getEffectivePropertyNameForPropertyNameNode(node) {
    const name = getPropertyNameForPropertyNameNode(node);
    return name ? name : isComputedPropertyName(node) ? tryGetNameFromType(getTypeOfExpression(node.expression)) : void 0;
  }
  function getCombinedModifierFlagsCached(node) {
    if (lastGetCombinedModifierFlagsNode === node) {
      return lastGetCombinedModifierFlagsResult;
    }
    lastGetCombinedModifierFlagsNode = node;
    lastGetCombinedModifierFlagsResult = getCombinedModifierFlags(node);
    return lastGetCombinedModifierFlagsResult;
  }
  function getCombinedNodeFlagsCached(node) {
    if (lastGetCombinedNodeFlagsNode === node) {
      return lastGetCombinedNodeFlagsResult;
    }
    lastGetCombinedNodeFlagsNode = node;
    lastGetCombinedNodeFlagsResult = getCombinedNodeFlags(node);
    return lastGetCombinedNodeFlagsResult;
  }
  function isVarConstLike(node) {
    const blockScopeKind = getCombinedNodeFlagsCached(node) & NodeFlags.BlockScoped;
    return blockScopeKind === NodeFlags.Const || blockScopeKind === NodeFlags.Using || blockScopeKind === NodeFlags.AwaitUsing;
  }
  function getJSXRuntimeImportSpecifier(file, specifierText) {
    const jsxImportIndex = compilerOptions.importHelpers ? 1 : 0;
    const specifier = file?.imports[jsxImportIndex];
    if (specifier) {
      Debug.assert(nodeIsSynthesized(specifier) && specifier.text === specifierText, `Expected sourceFile.imports[${jsxImportIndex}] to be the synthesized JSX runtime import`);
    }
    return specifier;
  }
  function getImportHelpersImportSpecifier(file) {
    Debug.assert(compilerOptions.importHelpers, "Expected importHelpers to be enabled");
    const specifier = file.imports[0];
    Debug.assert(specifier && nodeIsSynthesized(specifier) && specifier.text === "tslib", `Expected sourceFile.imports[0] to be the synthesized tslib import`);
    return specifier;
  }
}
function isNotAccessor(declaration) {
  return !isAccessor(declaration);
}
function isNotOverload(declaration) {
  return declaration.kind !== SyntaxKind.FunctionDeclaration && declaration.kind !== SyntaxKind.MethodDeclaration || !!declaration.body;
}
function isDeclarationNameOrImportPropertyName(name) {
  switch (name.parent.kind) {
    case SyntaxKind.ImportSpecifier:
    case SyntaxKind.ExportSpecifier:
      return isIdentifier(name) || name.kind === SyntaxKind.StringLiteral;
    default:
      return isDeclarationName(name);
  }
}
var JsxNames;
((JsxNames2) => {
  JsxNames2.JSX = "JSX";
  JsxNames2.IntrinsicElements = "IntrinsicElements";
  JsxNames2.ElementClass = "ElementClass";
  JsxNames2.ElementAttributesPropertyNameContainer = "ElementAttributesProperty";
  JsxNames2.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
  JsxNames2.Element = "Element";
  JsxNames2.ElementType = "ElementType";
  JsxNames2.IntrinsicAttributes = "IntrinsicAttributes";
  JsxNames2.IntrinsicClassAttributes = "IntrinsicClassAttributes";
  JsxNames2.LibraryManagedAttributes = "LibraryManagedAttributes";
})(JsxNames || (JsxNames = {}));
function getIterationTypesKeyFromIterationTypeKind(typeKind) {
  switch (typeKind) {
    case 0 /* Yield */:
      return "yieldType";
    case 1 /* Return */:
      return "returnType";
    case 2 /* Next */:
      return "nextType";
  }
}
export function signatureHasRestParameter(s) {
  return !!(s.flags & SignatureFlags.HasRestParameter);
}
function signatureHasLiteralTypes(s) {
  return !!(s.flags & SignatureFlags.HasLiteralTypes);
}
function createBasicNodeBuilderModuleSpecifierResolutionHost(host) {
  return {
    getCommonSourceDirectory: !!host.getCommonSourceDirectory ? () => host.getCommonSourceDirectory() : () => "",
    getCurrentDirectory: () => host.getCurrentDirectory(),
    getSymlinkCache: maybeBind(host, host.getSymlinkCache),
    getPackageJsonInfoCache: () => host.getPackageJsonInfoCache?.(),
    useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames),
    redirectTargetsMap: host.redirectTargetsMap,
    getProjectReferenceRedirect: (fileName) => host.getProjectReferenceRedirect(fileName),
    isSourceOfProjectReferenceRedirect: (fileName) => host.isSourceOfProjectReferenceRedirect(fileName),
    fileExists: (fileName) => host.fileExists(fileName),
    getFileIncludeReasons: () => host.getFileIncludeReasons(),
    readFile: host.readFile ? (fileName) => host.readFile(fileName) : void 0,
    getDefaultResolutionModeForFile: (file) => host.getDefaultResolutionModeForFile(file),
    getModeForResolutionAtIndex: (file, index) => host.getModeForResolutionAtIndex(file, index)
  };
}
class SymbolTrackerImpl {
  moduleResolverHost = void 0;
  context;
  inner = void 0;
  canTrackSymbol;
  disableTrackSymbol = false;
  constructor(context, tracker, moduleResolverHost) {
    while (tracker instanceof SymbolTrackerImpl) {
      tracker = tracker.inner;
    }
    this.inner = tracker;
    this.moduleResolverHost = moduleResolverHost;
    this.context = context;
    this.canTrackSymbol = !!this.inner?.trackSymbol;
  }
  trackSymbol(symbol, enclosingDeclaration, meaning) {
    if (this.inner?.trackSymbol && !this.disableTrackSymbol) {
      if (this.inner.trackSymbol(symbol, enclosingDeclaration, meaning)) {
        this.onDiagnosticReported();
        return true;
      }
      if (!(symbol.flags & SymbolFlags.TypeParameter)) (this.context.trackedSymbols ??= []).push([symbol, enclosingDeclaration, meaning]);
    }
    return false;
  }
  reportInaccessibleThisError() {
    if (this.inner?.reportInaccessibleThisError) {
      this.onDiagnosticReported();
      this.inner.reportInaccessibleThisError();
    }
  }
  reportPrivateInBaseOfClassExpression(propertyName) {
    if (this.inner?.reportPrivateInBaseOfClassExpression) {
      this.onDiagnosticReported();
      this.inner.reportPrivateInBaseOfClassExpression(propertyName);
    }
  }
  reportInaccessibleUniqueSymbolError() {
    if (this.inner?.reportInaccessibleUniqueSymbolError) {
      this.onDiagnosticReported();
      this.inner.reportInaccessibleUniqueSymbolError();
    }
  }
  reportCyclicStructureError() {
    if (this.inner?.reportCyclicStructureError) {
      this.onDiagnosticReported();
      this.inner.reportCyclicStructureError();
    }
  }
  reportLikelyUnsafeImportRequiredError(specifier) {
    if (this.inner?.reportLikelyUnsafeImportRequiredError) {
      this.onDiagnosticReported();
      this.inner.reportLikelyUnsafeImportRequiredError(specifier);
    }
  }
  reportTruncationError() {
    if (this.inner?.reportTruncationError) {
      this.onDiagnosticReported();
      this.inner.reportTruncationError();
    }
  }
  reportNonlocalAugmentation(containingFile, parentSymbol, augmentingSymbol) {
    if (this.inner?.reportNonlocalAugmentation) {
      this.onDiagnosticReported();
      this.inner.reportNonlocalAugmentation(containingFile, parentSymbol, augmentingSymbol);
    }
  }
  reportNonSerializableProperty(propertyName) {
    if (this.inner?.reportNonSerializableProperty) {
      this.onDiagnosticReported();
      this.inner.reportNonSerializableProperty(propertyName);
    }
  }
  onDiagnosticReported() {
    this.context.reportedDiagnostic = true;
  }
  reportInferenceFallback(node) {
    if (this.inner?.reportInferenceFallback) {
      this.inner.reportInferenceFallback(node);
    }
  }
}
