Accessor */:
        case 178 /* SetAccessor */:
          return node.name.kind === 167 /* ComputedPropertyName */ && traverse(node.name);
        case 211 /* PropertyAccessExpression */:
        case 212 /* ElementAccessExpression */:
          return traverse(node.expression);
        case 303 /* 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 & 16 /* 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 === 197 /* ThisType */ ? createTypePredicate(
      node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */,
      /*parameterName*/
      void 0,
      /*parameterIndex*/
      void 0,
      type
    ) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, findIndex(signature.parameters, (p) => p.escapedName === parameterName.escapedText), type);
  }
  function getUnionOrIntersectionType(types, kind, unionReduction) {
    return kind !== 2097152 /* 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, 2 /* Subtype */), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration) || (nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
      if (signature.flags & 8 /* IsInnerCallChain */) {
        type = addOptionalTypeMarker(type);
      } else if (signature.flags & 16 /* IsOuterCallChain */) {
        type = getOptionalType(type);
      }
      if (!popTypeResolution()) {
        if (signature.declaration) {
          const typeNode = getEffectiveReturnTypeNode(signature.declaration);
          if (typeNode) {
            error2(typeNode, Diagnostics.Return_type_annotation_circularly_references_itself);
          } else if (noImplicitAny) {
            const declaration = signature.declaration;
            const name = getNameOfDeclaration(declaration);
            if (name) {
              error2(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 {
              error2(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 ?? (signature.resolvedReturnType = type);
    }
    return signature.resolvedReturnType;
  }
  function getReturnTypeFromAnnotation(declaration) {
    if (declaration.kind === 176 /* 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 === 177 /* GetAccessor */ && hasBindableName(declaration)) {
      const jsDocType = isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
      if (jsDocType) {
        return jsDocType;
      }
      const setter = getDeclarationOfKind(getSymbolOfDeclaration(declaration), 178 /* 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 || (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) {
    var _a;
    if (!signature.isolatedSignatureType) {
      const kind = (_a = signature.declaration) == null ? void 0 : _a.kind;
      const isConstructor = kind === void 0 || kind === 176 /* Constructor */ || kind === 180 /* ConstructSignature */ || kind === 185 /* ConstructorType */;
      const type = createObjectType(16 /* Anonymous */ | 134217728 /* SingleSignatureType */, createSymbol(16 /* Function */, "__function" /* Function */));
      if (signature.declaration && !nodeIsSynthesized(signature.declaration)) {
        type.symbol.declarations = [signature.declaration];
        type.symbol.valueDeclaration = signature.declaration;
      }
      outerTypeParameters || (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(getMembersOfSymbol(symbol)) : void 0;
  }
  function getIndexSymbolFromSymbolTable(symbolTable) {
    return symbolTable.get("__index" /* Index */);
  }
  function createIndexInfo(keyType, type, isReadonly, declaration) {
    return { keyType, type, isReadonly, declaration };
  }
  function getIndexInfosOfSymbol(symbol) {
    const indexSymbol = getIndexSymbol(symbol);
    return indexSymbol ? getIndexInfosOfIndexSymbol(indexSymbol, arrayFrom(getMembersOfSymbol(symbol).values())) : emptyArray;
  }
  function getIndexInfosOfIndexSymbol(indexSymbol, siblingSymbols = indexSymbol.parent ? arrayFrom(getMembersOfSymbol(indexSymbol.parent).values()) : void 0) {
    if (indexSymbol.declarations) {
      const indexInfos = [];
      let hasComputedNumberProperty = false;
      let readonlyComputedNumberProperty = true;
      let hasComputedSymbolProperty = false;
      let readonlyComputedSymbolProperty = true;
      let hasComputedStringProperty = false;
      let readonlyComputedStringProperty = true;
      const computedPropertySymbols = [];
      for (const declaration of indexSymbol.declarations) {
        if (isIndexSignatureDeclaration(declaration)) {
          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, 8 /* Readonly */), declaration));
                }
              });
            }
          }
        } else if (hasLateBindableIndexSignature(declaration)) {
          const declName = isBinaryExpression(declaration) ? declaration.left : declaration.name;
          const keyType = isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
          if (findIndexInfo(indexInfos, keyType)) {
            continue;
          }
          if (isTypeAssignableTo(keyType, stringNumberSymbolType)) {
            if (isTypeAssignableTo(keyType, numberType)) {
              hasComputedNumberProperty = true;
              if (!hasEffectiveReadonlyModifier(declaration)) {
                readonlyComputedNumberProperty = false;
              }
            } else if (isTypeAssignableTo(keyType, esSymbolType)) {
              hasComputedSymbolProperty = true;
              if (!hasEffectiveReadonlyModifier(declaration)) {
                readonlyComputedSymbolProperty = false;
              }
            } else {
              hasComputedStringProperty = true;
              if (!hasEffectiveReadonlyModifier(declaration)) {
                readonlyComputedStringProperty = false;
              }
            }
            computedPropertySymbols.push(declaration.symbol);
          }
        }
      }
      const allPropertySymbols = concatenate(computedPropertySymbols, filter(siblingSymbols, (s) => s !== indexSymbol));
      if (hasComputedStringProperty && !findIndexInfo(indexInfos, stringType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedStringProperty, 0, allPropertySymbols, stringType));
      if (hasComputedNumberProperty && !findIndexInfo(indexInfos, numberType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedNumberProperty, 0, allPropertySymbols, numberType));
      if (hasComputedSymbolProperty && !findIndexInfo(indexInfos, esSymbolType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedSymbolProperty, 0, allPropertySymbols, esSymbolType));
      return indexInfos;
    }
    return emptyArray;
  }
  function isValidIndexKeyType(type) {
    return !!(type.flags & (4 /* String */ | 8 /* Number */ | 4096 /* ESSymbol */)) || isPatternLiteralType(type) || !!(type.flags & 2097152 /* 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) {
    var _a;
    let inferences;
    if ((_a = typeParameter.symbol) == null ? void 0 : _a.declarations) {
      for (const declaration of typeParameter.symbol.declarations) {
        if (declaration.parent.kind === 195 /* InferType */) {
          const [childTypeParameter = declaration.parent, grandParent] = walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent);
          if (grandParent.kind === 183 /* 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 === 169 /* Parameter */ && grandParent.dotDotDotToken || grandParent.kind === 191 /* RestType */ || grandParent.kind === 202 /* NamedTupleMember */ && grandParent.dotDotDotToken) {
            inferences = append(inferences, createArrayType(unknownType));
          } else if (grandParent.kind === 204 /* TemplateLiteralTypeSpan */) {
            inferences = append(inferences, stringType);
          } else if (grandParent.kind === 168 /* TypeParameter */ && grandParent.parent.kind === 200 /* MappedType */) {
            inferences = append(inferences, stringNumberSymbolType);
          } else if (grandParent.kind === 200 /* MappedType */ && grandParent.type && skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 194 /* ConditionalType */ && grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 200 /* 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 & 1 /* Any */ && !isErrorType(type)) {
            type = constraintDeclaration.parent.parent.kind === 200 /* MappedType */ ? stringNumberSymbolType : unknownType;
          }
          typeParameter.constraint = type;
        }
      }
    }
    return typeParameter.constraint === noConstraintType ? void 0 : typeParameter.constraint;
  }
  function getParentSymbolOfTypeParameter(typeParameter) {
    const tp = getDeclarationOfKind(typeParameter.symbol, 168 /* 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 & 458752 /* 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(4 /* 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(4 /* Reference */, target.symbol);
    type.target = target;
    type.node = node;
    type.mapper = mapper;
    type.aliasSymbol = aliasSymbol;
    type.aliasTypeArguments = aliasTypeArguments;
    return type;
  }
  function getTypeArguments(type) {
    var _a, _b;
    if (!type.resolvedTypeArguments) {
      if (!pushTypeResolution(type, 5 /* ResolvedTypeArguments */)) {
        return concatenate(type.target.outerTypeParameters, (_a = type.target.localTypeParameters) == null ? void 0 : _a.map(() => errorType)) || emptyArray;
      }
      const node = type.node;
      const typeArguments = !node ? emptyArray : node.kind === 183 /* TypeReference */ ? concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments2(node, type.target.localTypeParameters)) : node.kind === 188 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : map(node.elements, getTypeFromTypeNode);
      if (popTypeResolution()) {
        type.resolvedTypeArguments ?? (type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments);
      } else {
        type.resolvedTypeArguments ?? (type.resolvedTypeArguments = concatenate(type.target.outerTypeParameters, ((_b = type.target.localTypeParameters) == null ? void 0 : _b.map(() => errorType)) || emptyArray));
        error2(
          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 diag2 = 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,
          2 /* WriteArrayAsGenericType */
        );
        error2(node, diag2, typeStr, minTypeArgumentCount, typeParameters.length);
        if (!isJs) {
          return errorType;
        }
      }
      if (node.kind === 183 /* 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) & 1048576 /* Unresolved */) {
      const typeArguments = typeArgumentsFromTypeReferenceNode(node);
      const id = getAliasId(symbol, typeArguments);
      let errorType2 = errorTypes.get(id);
      if (!errorType2) {
        errorType2 = createIntrinsicType(
          1 /* 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) {
        error2(
          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,
          2097152 /* Alias */,
          /*ignoreErrors*/
          true
        );
        if (aliasSymbol2 && aliasSymbol2 !== unknownSymbol) {
          const resolved = resolveAlias(aliasSymbol2);
          if (resolved && resolved.flags & 524288 /* 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) {
    var _a;
    const declaration = (_a = symbol.declarations) == null ? void 0 : _a.find(isTypeAlias);
    return !!(declaration && getContainingFunction(declaration));
  }
  function getTypeReferenceName(node) {
    switch (node.kind) {
      case 183 /* TypeReference */:
        return node.typeName;
      case 233 /* 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 === 166 /* QualifiedName */ ? name.right : name.kind === 211 /* PropertyAccessExpression */ ? name.name : name;
    const text = identifier.escapedText;
    if (text) {
      const parentSymbol = name.kind === 166 /* QualifiedName */ ? getUnresolvedSymbolForEntityName(name.left) : name.kind === 211 /* 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(524288 /* TypeAlias */, text, 1048576 /* 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 & (32 /* Class */ | 64 /* Interface */)) {
      return getTypeFromClassOrInterfaceReference(node, symbol);
    }
    if (symbol.flags & 524288 /* TypeAlias */) {
      return getTypeFromTypeAliasReference(node, symbol);
    }
    const res = tryGetDeclaredTypeOfSymbol(symbol);
    if (res) {
      return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
    }
    if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
      const jsdocType = getTypeFromJSDocValueReference(node, symbol);
      if (jsdocType) {
        return jsdocType;
      } else {
        resolveTypeReferenceName(node, 788968 /* 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 === 205 /* 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 & 3145728 /* UnionOrIntersection */ && some(type.types, isNoInferTargetType) || type.flags & 33554432 /* Substitution */ && !isNoInferType(type) && isNoInferTargetType(type.baseType) || type.flags & 524288 /* Object */ && !isEmptyAnonymousObjectType(type) || type.flags & (465829888 /* Instantiable */ & ~33554432 /* Substitution */) && !isPatternLiteralType(type));
  }
  function isNoInferType(type) {
    return !!(type.flags & 33554432 /* Substitution */ && type.constraint.flags & 2 /* Unknown */);
  }
  function getSubstitutionType(baseType, constraint) {
    return constraint.flags & 3 /* AnyOrUnknown */ || constraint === baseType || baseType.flags & 1 /* 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(33554432 /* 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 === 189 /* 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 !== 320 /* JSDoc */) {
      const parent2 = node.parent;
      if (parent2.kind === 169 /* Parameter */) {
        covariant = !covariant;
      }
      if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent2.kind === 194 /* ConditionalType */ && node === parent2.trueType) {
        const constraint = getImpliedConstraint(type, parent2.checkType, parent2.extendsType);
        if (constraint) {
          constraints = append(constraints, constraint);
        }
      } else if (type.flags & 262144 /* TypeParameter */ && parent2.kind === 200 /* MappedType */ && !parent2.nameType && node === parent2.type) {
        const mappedType = getTypeFromTypeNode(parent2);
        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 = parent2;
    }
    return constraints ? getSubstitutionType(type, getIntersectionType(constraints)) : type;
  }
  function isJSDocTypeReference(node) {
    return !!(node.flags & 16777216 /* JSDoc */) && (node.kind === 183 /* TypeReference */ || node.kind === 205 /* ImportType */);
  }
  function checkNoTypeArguments(node, symbol) {
    if (node.typeArguments) {
      error2(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, 65536 /* 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 = 788968 /* Type */;
      if (isJSDocTypeReference(node)) {
        type = getIntendedTypeFromJSDocTypeReference(node);
        if (!type) {
          symbol = resolveTypeReferenceName(
            node,
            meaning,
            /*ignoreErrors*/
            true
          );
          if (symbol === unknownSymbol) {
            symbol = resolveTypeReferenceName(node, meaning | 111551 /* 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 263 /* ClassDeclaration */:
            case 264 /* InterfaceDeclaration */:
            case 266 /* EnumDeclaration */:
              return declaration;
          }
        }
      }
    }
    if (!symbol) {
      return arity ? emptyGenericType : emptyObjectType;
    }
    const type = getDeclaredTypeOfSymbol(symbol);
    if (!(type.flags & 524288 /* Object */)) {
      error2(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbolName(symbol));
      return arity ? emptyGenericType : emptyObjectType;
    }
    if (length(type.typeParameters) !== arity) {
      error2(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity);
      return arity ? emptyGenericType : emptyObjectType;
    }
    return type;
  }
  function getGlobalValueSymbol(name, reportErrors2) {
    return getGlobalSymbol(name, 111551 /* Value */, reportErrors2 ? Diagnostics.Cannot_find_global_value_0 : void 0);
  }
  function getGlobalTypeSymbol(name, reportErrors2) {
    return getGlobalSymbol(name, 788968 /* Type */, reportErrors2 ? Diagnostics.Cannot_find_global_type_0 : void 0);
  }
  function getGlobalTypeAliasSymbol(name, arity, reportErrors2) {
    const symbol = getGlobalSymbol(name, 788968 /* Type */, reportErrors2 ? 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);
        error2(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, reportErrors2) {
    const symbol = getGlobalTypeSymbol(name, reportErrors2);
    return symbol || reportErrors2 ? 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 || (deferredGlobalTypedPropertyDescriptorType = getGlobalType(
      "TypedPropertyDescriptor",
      /*arity*/
      1,
      /*reportErrors*/
      true
    ) || emptyGenericType);
  }
  function getGlobalTemplateStringsArrayType() {
    return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType(
      "TemplateStringsArray",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || emptyObjectType);
  }
  function getGlobalImportMetaType() {
    return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType(
      "ImportMeta",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || emptyObjectType);
  }
  function getGlobalImportMetaExpressionType() {
    if (!deferredGlobalImportMetaExpressionType) {
      const symbol = createSymbol(0 /* None */, "ImportMetaExpression");
      const importMetaType = getGlobalImportMetaType();
      const metaPropertySymbol = createSymbol(4 /* Property */, "meta", 8 /* 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(reportErrors2) {
    return deferredGlobalImportCallOptionsType || (deferredGlobalImportCallOptionsType = getGlobalType(
      "ImportCallOptions",
      /*arity*/
      0,
      reportErrors2
    )) || emptyObjectType;
  }
  function getGlobalImportAttributesType(reportErrors2) {
    return deferredGlobalImportAttributesType || (deferredGlobalImportAttributesType = getGlobalType(
      "ImportAttributes",
      /*arity*/
      0,
      reportErrors2
    )) || emptyObjectType;
  }
  function getGlobalESSymbolConstructorSymbol(reportErrors2) {
    return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors2));
  }
  function getGlobalESSymbolConstructorTypeSymbol(reportErrors2) {
    return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor", reportErrors2));
  }
  function getGlobalESSymbolType() {
    return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType(
      "Symbol",
      /*arity*/
      0,
      /*reportErrors*/
      false
    )) || emptyObjectType;
  }
  function getGlobalPromiseType(reportErrors2) {
    return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType(
      "Promise",
      /*arity*/
      1,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalPromiseLikeType(reportErrors2) {
    return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType(
      "PromiseLike",
      /*arity*/
      1,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalPromiseConstructorSymbol(reportErrors2) {
    return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors2));
  }
  function getGlobalPromiseConstructorLikeType(reportErrors2) {
    return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType(
      "PromiseConstructorLike",
      /*arity*/
      0,
      reportErrors2
    )) || emptyObjectType;
  }
  function getGlobalAsyncIterableType(reportErrors2) {
    return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType(
      "AsyncIterable",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalAsyncIteratorType(reportErrors2) {
    return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType(
      "AsyncIterator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalAsyncIterableIteratorType(reportErrors2) {
    return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType(
      "AsyncIterableIterator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalBuiltinAsyncIteratorTypes() {
    return deferredGlobalBuiltinAsyncIteratorTypes ?? (deferredGlobalBuiltinAsyncIteratorTypes = getGlobalBuiltinTypes(["ReadableStreamAsyncIterator"], 1));
  }
  function getGlobalAsyncIteratorObjectType(reportErrors2) {
    return deferredGlobalAsyncIteratorObjectType || (deferredGlobalAsyncIteratorObjectType = getGlobalType(
      "AsyncIteratorObject",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalAsyncGeneratorType(reportErrors2) {
    return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType(
      "AsyncGenerator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalIterableType(reportErrors2) {
    return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType(
      "Iterable",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalIteratorType(reportErrors2) {
    return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType(
      "Iterator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalIterableIteratorType(reportErrors2) {
    return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType(
      "IterableIterator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getBuiltinIteratorReturnType() {
    return strictBuiltinIteratorReturn ? undefinedType : anyType;
  }
  function getGlobalBuiltinIteratorTypes() {
    return deferredGlobalBuiltinIteratorTypes ?? (deferredGlobalBuiltinIteratorTypes = getGlobalBuiltinTypes(["ArrayIterator", "MapIterator", "SetIterator", "StringIterator"], 1));
  }
  function getGlobalIteratorObjectType(reportErrors2) {
    return deferredGlobalIteratorObjectType || (deferredGlobalIteratorObjectType = getGlobalType(
      "IteratorObject",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalGeneratorType(reportErrors2) {
    return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType(
      "Generator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalIteratorYieldResultType(reportErrors2) {
    return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType(
      "IteratorYieldResult",
      /*arity*/
      1,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalIteratorReturnResultType(reportErrors2) {
    return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType(
      "IteratorReturnResult",
      /*arity*/
      1,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalDisposableType(reportErrors2) {
    return deferredGlobalDisposableType || (deferredGlobalDisposableType = getGlobalType(
      "Disposable",
      /*arity*/
      0,
      reportErrors2
    )) || emptyObjectType;
  }
  function getGlobalAsyncDisposableType(reportErrors2) {
    return deferredGlobalAsyncDisposableType || (deferredGlobalAsyncDisposableType = getGlobalType(
      "AsyncDisposable",
      /*arity*/
      0,
      reportErrors2
    )) || emptyObjectType;
  }
  function getGlobalTypeOrUndefined(name, arity = 0) {
    const symbol = getGlobalSymbol(
      name,
      788968 /* Type */,
      /*diagnostic*/
      void 0
    );
    return symbol && getTypeOfGlobalSymbol(symbol, arity);
  }
  function getGlobalExtractSymbol() {
    deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalTypeAliasSymbol(
      "Extract",
      /*arity*/
      2,
      /*reportErrors*/
      true
    ) || unknownSymbol);
    return deferredGlobalExtractSymbol === unknownSymbol ? void 0 : deferredGlobalExtractSymbol;
  }
  function getGlobalOmitSymbol() {
    deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalTypeAliasSymbol(
      "Omit",
      /*arity*/
      2,
      /*reportErrors*/
      true
    ) || unknownSymbol);
    return deferredGlobalOmitSymbol === unknownSymbol ? void 0 : deferredGlobalOmitSymbol;
  }
  function getGlobalAwaitedSymbol(reportErrors2) {
    deferredGlobalAwaitedSymbol || (deferredGlobalAwaitedSymbol = getGlobalTypeAliasSymbol(
      "Awaited",
      /*arity*/
      1,
      reportErrors2
    ) || (reportErrors2 ? unknownSymbol : void 0));
    return deferredGlobalAwaitedSymbol === unknownSymbol ? void 0 : deferredGlobalAwaitedSymbol;
  }
  function getGlobalBigIntType() {
    return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType(
      "BigInt",
      /*arity*/
      0,
      /*reportErrors*/
      false
    )) || emptyObjectType;
  }
  function getGlobalClassDecoratorContextType(reportErrors2) {
    return deferredGlobalClassDecoratorContextType ?? (deferredGlobalClassDecoratorContextType = getGlobalType(
      "ClassDecoratorContext",
      /*arity*/
      1,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassMethodDecoratorContextType(reportErrors2) {
    return deferredGlobalClassMethodDecoratorContextType ?? (deferredGlobalClassMethodDecoratorContextType = getGlobalType(
      "ClassMethodDecoratorContext",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassGetterDecoratorContextType(reportErrors2) {
    return deferredGlobalClassGetterDecoratorContextType ?? (deferredGlobalClassGetterDecoratorContextType = getGlobalType(
      "ClassGetterDecoratorContext",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassSetterDecoratorContextType(reportErrors2) {
    return deferredGlobalClassSetterDecoratorContextType ?? (deferredGlobalClassSetterDecoratorContextType = getGlobalType(
      "ClassSetterDecoratorContext",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassAccessorDecoratorContextType(reportErrors2) {
    return deferredGlobalClassAccessorDecoratorContextType ?? (deferredGlobalClassAccessorDecoratorContextType = getGlobalType(
      "ClassAccessorDecoratorContext",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassAccessorDecoratorTargetType(reportErrors2) {
    return deferredGlobalClassAccessorDecoratorTargetType ?? (deferredGlobalClassAccessorDecoratorTargetType = getGlobalType(
      "ClassAccessorDecoratorTarget",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassAccessorDecoratorResultType(reportErrors2) {
    return deferredGlobalClassAccessorDecoratorResultType ?? (deferredGlobalClassAccessorDecoratorResultType = getGlobalType(
      "ClassAccessorDecoratorResult",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassFieldDecoratorContextType(reportErrors2) {
    return deferredGlobalClassFieldDecoratorContextType ?? (deferredGlobalClassFieldDecoratorContextType = getGlobalType(
      "ClassFieldDecoratorContext",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalNaNSymbol() {
    return deferredGlobalNaNSymbol || (deferredGlobalNaNSymbol = getGlobalValueSymbol(
      "NaN",
      /*reportErrors*/
      false
    ));
  }
  function getGlobalRecordSymbol() {
    deferredGlobalRecordSymbol || (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 190 /* OptionalType */:
        return 2 /* Optional */;
      case 191 /* RestType */:
        return getRestTypeElementFlags(node);
      case 202 /* NamedTupleMember */:
        return node.questionToken ? 2 /* Optional */ : node.dotDotDotToken ? getRestTypeElementFlags(node) : 1 /* Required */;
      default:
        return 1 /* Required */;
    }
  }
  function getRestTypeElementFlags(node) {
    return getArrayElementTypeNode(node.type) ? 4 /* Rest */ : 8 /* 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 === 188 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : node.kind === 189 /* TupleType */ ? some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || some(node.typeArguments, mayResolveTypeAlias));
  }
  function isResolvedByTypeAlias(node) {
    const parent2 = node.parent;
    switch (parent2.kind) {
      case 196 /* ParenthesizedType */:
      case 202 /* NamedTupleMember */:
      case 183 /* TypeReference */:
      case 192 /* UnionType */:
      case 193 /* IntersectionType */:
      case 199 /* IndexedAccessType */:
      case 194 /* ConditionalType */:
      case 198 /* TypeOperator */:
      case 188 /* ArrayType */:
      case 189 /* TupleType */:
        return isResolvedByTypeAlias(parent2);
      case 265 /* TypeAliasDeclaration */:
        return true;
    }
    return false;
  }
  function mayResolveTypeAlias(node) {
    switch (node.kind) {
      case 183 /* TypeReference */:
        return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node, 788968 /* Type */).flags & 524288 /* TypeAlias */);
      case 186 /* TypeQuery */:
        return true;
      case 198 /* TypeOperator */:
        return node.operator !== 158 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
      case 196 /* ParenthesizedType */:
      case 190 /* OptionalType */:
      case 202 /* NamedTupleMember */:
      case 316 /* JSDocOptionalType */:
      case 314 /* JSDocNullableType */:
      case 315 /* JSDocNonNullableType */:
      case 309 /* JSDocTypeExpression */:
        return mayResolveTypeAlias(node.type);
      case 191 /* RestType */:
        return node.type.kind !== 188 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
      case 192 /* UnionType */:
      case 193 /* IntersectionType */:
        return some(node.types, mayResolveTypeAlias);
      case 199 /* IndexedAccessType */:
        return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
      case 194 /* 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 === 189 /* TupleType */ && some(node.elements, (e) => !!(getTupleElementFlags(e) & 8 /* Variadic */))) && isDeferredTypeReferenceNode(node)) {
        links.resolvedType = node.kind === 189 /* TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference(
          target,
          node,
          /*mapper*/
          void 0
        );
      } else {
        const elementTypes = node.kind === 188 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : map(node.elements, getTypeFromTypeNode);
        links.resolvedType = createNormalizedTypeReference(target, elementTypes);
      }
    }
    return links.resolvedType;
  }
  function isReadonlyTypeOperator(node) {
    return isTypeOperatorNode(node) && node.operator === 148 /* ReadonlyKeyword */;
  }
  function createTupleType(elementTypes, elementFlags, readonly = false, namedMemberDeclarations = []) {
    const tupleTarget = getTupleTargetType(elementFlags || map(elementTypes, (_) => 1 /* Required */), readonly, namedMemberDeclarations);
    return tupleTarget === emptyGenericType ? emptyObjectType : elementTypes.length ? createNormalizedTypeReference(tupleTarget, elementTypes) : tupleTarget;
  }
  function getTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
    if (elementFlags.length === 1 && elementFlags[0] & 4 /* Rest */) {
      return readonly ? globalReadonlyArrayType : globalArrayType;
    }
    const key = map(elementFlags, (f) => f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* 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 & (1 /* Required */ | 8 /* 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 & 12 /* Variable */)) {
          const property = createSymbol(4 /* Property */ | (flags & 2 /* Optional */ ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
          property.links.tupleLabelDeclaration = namedMemberDeclarations == null ? void 0 : namedMemberDeclarations[i];
          property.links.type = typeParameter;
          properties.push(property);
        }
      }
    }
    const fixedLength = properties.length;
    const lengthSymbol = createSymbol(4 /* Property */, "length", readonly ? 8 /* Readonly */ : 0);
    if (combinedFlags & 12 /* 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(8 /* Tuple */ | 4 /* 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 & 12 /* Variable */);
    type.combinedFlags = combinedFlags;
    type.readonly = readonly;
    type.labeledElementDeclarations = namedMemberDeclarations;
    return type;
  }
  function createNormalizedTypeReference(target, typeArguments) {
    return target.objectFlags & 8 /* Tuple */ ? createNormalizedTupleType(target, typeArguments) : createTypeReference(target, typeArguments);
  }
  function createNormalizedTupleType(target, elementTypes) {
    var _a, _b, _c, _d;
    if (!(target.combinedFlags & 14 /* NonRequired */)) {
      return createTypeReference(target, elementTypes);
    }
    if (target.combinedFlags & 8 /* Variadic */) {
      const unionIndex = findIndex(elementTypes, (t, i) => !!(target.elementFlags[i] & 8 /* Variadic */ && t.flags & (131072 /* Never */ | 1048576 /* Union */)));
      if (unionIndex >= 0) {
        return checkCrossProductUnion(map(elementTypes, (t, i) => target.elementFlags[i] & 8 /* 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 & 8 /* Variadic */) {
        if (type.flags & 1 /* Any */) {
          addElement(type, 4 /* Rest */, (_a = target.labeledElementDeclarations) == null ? void 0 : _a[i]);
        } else if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) {
          addElement(type, 8 /* Variadic */, (_b = target.labeledElementDeclarations) == null ? void 0 : _b[i]);
        } else if (isTupleType(type)) {
          const elements = getElementTypes(type);
          if (elements.length + expandedTypes.length >= 1e4) {
            error2(
              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) => {
            var _a2;
            return addElement(t, type.target.elementFlags[n], (_a2 = type.target.labeledElementDeclarations) == null ? void 0 : _a2[n]);
          });
        } else {
          addElement(isArrayLikeType(type) && getIndexTypeOfType(type, numberType) || errorType, 4 /* Rest */, (_c = target.labeledElementDeclarations) == null ? void 0 : _c[i]);
        }
      } else {
        addElement(type, flags, (_d = target.labeledElementDeclarations) == null ? void 0 : _d[i]);
      }
    }
    for (let i = 0; i < lastRequiredIndex; i++) {
      if (expandedFlags[i] & 2 /* Optional */) expandedFlags[i] = 1 /* Required */;
    }
    if (firstRestIndex >= 0 && firstRestIndex < lastOptionalOrRestIndex) {
      expandedTypes[firstRestIndex] = getUnionType(sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), (t, i) => expandedFlags[firstRestIndex + i] & 8 /* 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 & 1 /* Required */) {
        lastRequiredIndex = expandedFlags.length;
      }
      if (flags & 4 /* Rest */ && firstRestIndex < 0) {
        firstRestIndex = expandedFlags.length;
      }
      if (flags & (2 /* Optional */ | 4 /* Rest */)) {
        lastOptionalOrRestIndex = expandedFlags.length;
      }
      expandedTypes.push(flags & 2 /* 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, 3 /* 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 & 131072 /* Never */)) {
      includes |= flags & 473694207 /* IncludesMask */;
      if (flags & 465829888 /* Instantiable */) includes |= 33554432 /* IncludesInstantiable */;
      if (flags & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) includes |= 536870912 /* IncludesConstrainedTypeVariable */;
      if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */;
      if (isErrorType(type)) includes |= 1073741824 /* IncludesError */;
      if (!strictNullChecks && flags & 98304 /* Nullable */) {
        if (!(getObjectFlags(type) & 65536 /* ContainsWideningType */)) includes |= 4194304 /* 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 & 1048576 /* Union */ ? addTypesToUnion(typeSet, includes | (isNamedUnionType(type) ? 1048576 /* Union */ : 0), type.types) : addTypeToUnion(typeSet, includes, type);
        lastType = type;
      }
    }
    return includes;
  }
  function removeSubtypes(types, hasObjectTypes) {
    var _a;
    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 & 524288 /* 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 & 469499904 /* StructuredOrInstantiable */) {
        if (source.flags & 262144 /* TypeParameter */ && getBaseConstraintOrType(source).flags & 1048576 /* Union */) {
          if (isTypeRelatedTo(source, getUnionType(map(types, (t) => t === source ? neverType : t)), strictSubtypeRelation)) {
            orderedRemoveItemAt(types, i);
          }
          continue;
        }
        const keyProperty = source.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* 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) {
                (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "removeSubtypes_DepthLimit", { typeIds: types.map((t) => t.id) });
                error2(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
                return void 0;
              }
            }
            count++;
            if (keyProperty && target.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) {
              const t = getTypeOfPropertyOfType(target, keyProperty.escapedName);
              if (t && isUnitType(t) && getRegularTypeOfLiteralType(t) !== keyPropertyType) {
                continue;
              }
            }
            if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(getObjectFlags(getTargetType(source)) & 1 /* Class */) || !(getObjectFlags(getTargetType(target)) & 1 /* 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 & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && includes & 4 /* String */ || flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || reduceVoidUndefined && flags & 32768 /* Undefined */ && includes & 16384 /* 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 & 128 /* StringLiteral */ && some(templates, (template) => isTypeMatchedByTemplateLiteralOrStringMapping(t, template))) {
          orderedRemoveItemAt(types, i);
        }
      }
    }
  }
  function isTypeMatchedByTemplateLiteralOrStringMapping(type, template) {
    return template.flags & 134217728 /* TemplateLiteral */ ? isTypeMatchedByTemplateLiteralType(type, template) : isMemberOfStringMapping(type, template);
  }
  function removeConstrainedTypeVariables(types) {
    const typeVariables = [];
    for (const type of types) {
      if (type.flags & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) {
        const index = type.types[0].flags & 8650752 /* TypeVariable */ ? 0 : 1;
        pushIfUnique(typeVariables, type.types[index]);
      }
    }
    for (const typeVariable of typeVariables) {
      const primitives = [];
      for (const type of types) {
        if (type.flags & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) {
          const index = type.types[0].flags & 8650752 /* 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 & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) {
            const index = type.types[0].flags & 8650752 /* 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 & 1048576 /* Union */ && (type.aliasSymbol || type.origin));
  }
  function addNamedUnions(namedUnions, types) {
    for (const t of types) {
      if (t.flags & 1048576 /* Union */) {
        const origin = t.origin;
        if (t.aliasSymbol || origin && !(origin.flags & 1048576 /* Union */)) {
          pushIfUnique(namedUnions, t);
        } else if (origin && origin.flags & 1048576 /* Union */) {
          addNamedUnions(namedUnions, origin.types);
        }
      }
    }
  }
  function createOriginUnionOrIntersectionType(flags, types) {
    const result = createOriginType(flags);
    result.types = types;
    return result;
  }
  function getUnionType(types, unionReduction = 1 /* 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 & 1048576 /* Union */ || types[1].flags & 1048576 /* Union */)) {
      const infix = unionReduction === 0 /* None */ ? "N" : unionReduction === 2 /* 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 !== 0 /* None */) {
      if (includes & 3 /* AnyOrUnknown */) {
        return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : includes & 1073741824 /* IncludesError */ ? errorType : anyType : unknownType;
      }
      if (includes & 32768 /* Undefined */) {
        if (typeSet.length >= 2 && typeSet[0] === undefinedType && typeSet[1] === missingType) {
          orderedRemoveItemAt(typeSet, 1);
        }
      }
      if (includes & (32 /* Enum */ | 2944 /* Literal */ | 8192 /* UniqueESSymbol */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) {
        removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2 /* Subtype */));
      }
      if (includes & 128 /* StringLiteral */ && includes & (134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) {
        removeStringLiteralsMatchedByTemplateLiterals(typeSet);
      }
      if (includes & 536870912 /* IncludesConstrainedTypeVariable */) {
        removeConstrainedTypeVariables(typeSet);
      }
      if (unionReduction === 2 /* Subtype */) {
        typeSet = removeSubtypes(typeSet, !!(includes & 524288 /* Object */));
        if (!typeSet) {
          return errorType;
        }
      }
      if (typeSet.length === 0) {
        return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : neverType;
      }
    }
    if (!origin && includes & 1048576 /* 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(1048576 /* Union */, reducedTypes);
      }
    }
    const objectFlags = (includes & 36323331 /* NotPrimitiveUnion */ ? 0 : 32768 /* PrimitiveUnion */) | (includes & 2097152 /* Intersection */ ? 16777216 /* 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 !== 0 /* This */ && pred.kind !== 1 /* Identifier */ || last2 && !typePredicateKindsMatch(last2, pred)) {
          return void 0;
        }
        last2 = pred;
        types.push(pred.type);
      } else {
        const returnType = kind !== 2097152 /* 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 & 1048576 /* Union */ ? `|${getTypeListId(origin.types)}` : origin.flags & 2097152 /* Intersection */ ? `&${getTypeListId(origin.types)}` : `#${origin.type.id}|${getTypeListId(types)}`;
    const id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments);
    let type = unionTypes.get(id);
    if (!type) {
      type = createType(1048576 /* Union */);
      type.objectFlags = precomputedObjectFlags | getPropagatingFlagsOfTypes(
        types,
        /*excludeKinds*/
        98304 /* Nullable */
      );
      type.types = types;
      type.origin = origin;
      type.aliasSymbol = aliasSymbol;
      type.aliasTypeArguments = aliasTypeArguments;
      if (types.length === 2 && types[0].flags & 512 /* BooleanLiteral */ && types[1].flags & 512 /* BooleanLiteral */) {
        type.flags |= 16 /* 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), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
    }
    return links.resolvedType;
  }
  function addTypeToIntersection(typeSet, includes, type) {
    const flags = type.flags;
    if (flags & 2097152 /* Intersection */) {
      return addTypesToIntersection(typeSet, includes, type.types);
    }
    if (isEmptyAnonymousObjectType(type)) {
      if (!(includes & 16777216 /* IncludesEmptyObject */)) {
        includes |= 16777216 /* IncludesEmptyObject */;
        typeSet.set(type.id.toString(), type);
      }
    } else {
      if (flags & 3 /* AnyOrUnknown */) {
        if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */;
        if (isErrorType(type)) includes |= 1073741824 /* IncludesError */;
      } else if (strictNullChecks || !(flags & 98304 /* Nullable */)) {
        if (type === missingType) {
          includes |= 262144 /* IncludesMissingType */;
          type = undefinedType;
        }
        if (!typeSet.has(type.id.toString())) {
          if (type.flags & 109472 /* Unit */ && includes & 109472 /* Unit */) {
            includes |= 67108864 /* NonPrimitive */;
          }
          typeSet.set(type.id.toString(), type);
        }
      }
      includes |= flags & 473694207 /* 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 & 4 /* String */ && includes & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */ || t.flags & 16384 /* Void */ && includes & 32768 /* Undefined */ || isEmptyAnonymousObjectType(t) && includes & 470302716 /* 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 & 128 /* StringLiteral */ ? stringType : type.flags & (32 /* Enum */ | 256 /* NumberLiteral */) ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 8192 /* 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 & 128 /* StringLiteral */));
    while (i > 0) {
      i--;
      const t = types[i];
      if (!(t.flags & (134217728 /* TemplateLiteral */ | 268435456 /* 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) & 32768 /* PrimitiveUnion */));
    if (index < 0) {
      return false;
    }
    let i = index + 1;
    while (i < types.length) {
      const t = types[i];
      if (getObjectFlags(t) & 32768 /* 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, 32768 /* PrimitiveUnion */);
    return true;
  }
  function createIntersectionType(types, objectFlags, aliasSymbol, aliasTypeArguments) {
    const result = createType(2097152 /* Intersection */);
    result.objectFlags = objectFlags | getPropagatingFlagsOfTypes(
      types,
      /*excludeKinds*/
      98304 /* Nullable */
    );
    result.types = types;
    result.aliasSymbol = aliasSymbol;
    result.aliasTypeArguments = aliasTypeArguments;
    return result;
  }
  function getIntersectionType(types, flags = 0 /* None */, aliasSymbol, aliasTypeArguments) {
    const typeMembershipMap = /* @__PURE__ */ new Map();
    const includes = addTypesToIntersection(typeMembershipMap, 0, types);
    const typeSet = arrayFrom(typeMembershipMap.values());
    let objectFlags = 0 /* None */;
    if (includes & 131072 /* Never */) {
      return contains(typeSet, silentNeverType) ? silentNeverType : neverType;
    }
    if (strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) || includes & 67108864 /* NonPrimitive */ && includes & (469892092 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || includes & 402653316 /* StringLike */ && includes & (469892092 /* DisjointDomains */ & ~402653316 /* StringLike */) || includes & 296 /* NumberLike */ && includes & (469892092 /* DisjointDomains */ & ~296 /* NumberLike */) || includes & 2112 /* BigIntLike */ && includes & (469892092 /* DisjointDomains */ & ~2112 /* BigIntLike */) || includes & 12288 /* ESSymbolLike */ && includes & (469892092 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || includes & 49152 /* VoidLike */ && includes & (469892092 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
      return neverType;
    }
    if (includes & (134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && includes & 128 /* StringLiteral */ && extractRedundantTemplateLiterals(typeSet)) {
      return neverType;
    }
    if (includes & 1 /* Any */) {
      return includes & 8388608 /* IncludesWildcard */ ? wildcardType : includes & 1073741824 /* IncludesError */ ? errorType : anyType;
    }
    if (!strictNullChecks && includes & 98304 /* Nullable */) {
      return includes & 16777216 /* IncludesEmptyObject */ ? neverType : includes & 32768 /* Undefined */ ? undefinedType : nullType;
    }
    if (includes & 4 /* String */ && includes & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */ || includes & 16384 /* Void */ && includes & 32768 /* Undefined */ || includes & 16777216 /* IncludesEmptyObject */ && includes & 470302716 /* DefinitelyNonNullable */) {
      if (!(flags & 1 /* NoSupertypeReduction */)) removeRedundantSupertypes(typeSet, includes);
    }
    if (includes & 262144 /* IncludesMissingType */) {
      typeSet[typeSet.indexOf(undefinedType)] = missingType;
    }
    if (typeSet.length === 0) {
      return unknownType;
    }
    if (typeSet.length === 1) {
      return typeSet[0];
    }
    if (typeSet.length === 2 && !(flags & 2 /* NoConstraintReduction */)) {
      const typeVarIndex = typeSet[0].flags & 8650752 /* TypeVariable */ ? 0 : 1;
      const typeVariable = typeSet[typeVarIndex];
      const primitiveType = typeSet[1 - typeVarIndex];
      if (typeVariable.flags & 8650752 /* TypeVariable */ && (primitiveType.flags & (402784252 /* Primitive */ | 67108864 /* NonPrimitive */) && !isGenericStringLikeType(primitiveType) || includes & 16777216 /* IncludesEmptyObject */)) {
        const constraint = getBaseConstraintOfType(typeVariable);
        if (constraint && everyType(constraint, (t) => !!(t.flags & (402784252 /* Primitive */ | 67108864 /* NonPrimitive */)) || isEmptyAnonymousObjectType(t))) {
          if (isTypeStrictSubtypeOf(constraint, primitiveType)) {
            return typeVariable;
          }
          if (!(constraint.flags & 1048576 /* Union */ && someType(constraint, (c) => isTypeStrictSubtypeOf(c, primitiveType)))) {
            if (!isTypeStrictSubtypeOf(primitiveType, constraint)) {
              return neverType;
            }
          }
          objectFlags = 67108864 /* IsConstrainedTypeVariable */;
        }
      }
    }
    const id = getTypeListId(typeSet) + (flags & 2 /* NoConstraintReduction */ ? "*" : getAliasId(aliasSymbol, aliasTypeArguments));
    let result = intersectionTypes.get(id);
    if (!result) {
      if (includes & 1048576 /* Union */) {
        if (intersectUnionsOfPrimitiveTypes(typeSet)) {
          result = getIntersectionType(typeSet, flags, aliasSymbol, aliasTypeArguments);
        } else if (every(typeSet, (t) => !!(t.flags & 1048576 /* Union */ && t.types[0].flags & 32768 /* Undefined */))) {
          const containedUndefinedType = some(typeSet, containsMissingType) ? missingType : undefinedType;
          removeFromEach(typeSet, 32768 /* Undefined */);
          result = getUnionType([getIntersectionType(typeSet, flags), containedUndefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
        } else if (every(typeSet, (t) => !!(t.flags & 1048576 /* Union */ && (t.types[0].flags & 65536 /* Null */ || t.types[1].flags & 65536 /* Null */)))) {
          removeFromEach(typeSet, 65536 /* Null */);
          result = getUnionType([getIntersectionType(typeSet, flags), nullType], 1 /* 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 & 2097152 /* Intersection */)) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152 /* Intersection */, typeSet) : void 0;
          result = getUnionType(constituents, 1 /* 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 & 1048576 /* Union */ ? n * t.types.length : t.flags & 131072 /* Never */ ? 0 : n, 1);
  }
  function checkCrossProductUnion(types) {
    var _a;
    const size = getCrossProductUnionSize(types);
    if (size >= 1e5) {
      (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "checkCrossProductUnion_DepthLimit", { typeIds: types.map((t) => t.id), size });
      error2(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 & 1048576 /* 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 & 131072 /* Never */)) intersections.push(t);
    }
    return intersections;
  }
  function getConstituentCount(type) {
    return !(type.flags & 3145728 /* UnionOrIntersection */) || type.aliasSymbol ? 1 : type.flags & 1048576 /* 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 & (4 /* String */ | 8 /* Number */ | 64 /* BigInt */) || t.flags & 134217728 /* TemplateLiteral */ && isPatternLiteralType(t));
      links.resolvedType = getIntersectionType(types, noSupertypeReduction ? 1 /* NoSupertypeReduction */ : 0, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
    }
    return links.resolvedType;
  }
  function createIndexType(type, indexFlags) {
    const result = createType(4194304 /* Index */);
    result.type = type;
    result.indexFlags = indexFlags;
    return result;
  }
  function createOriginIndexType(type) {
    const result = createOriginType(4194304 /* Index */);
    result.type = type;
    return result;
  }
  function getIndexTypeForGenericType(type, indexFlags) {
    return indexFlags & 1 /* StringsOnly */ ? type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, 1 /* StringsOnly */)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, 0 /* None */));
  }
  function getIndexTypeForMappedType(type, indexFlags) {
    const typeParameter = getTypeParameterFromMappedType(type);
    const constraintType = getConstraintTypeFromMappedType(type);
    const nameType = getNameTypeFromMappedType(type.target || type);
    if (!nameType && !(indexFlags & 2 /* 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, 8576 /* StringOrNumberLiteralOrUnique */, !!(indexFlags & 1 /* StringsOnly */), addMemberForKeyType);
    } else {
      forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
    }
    const result = indexFlags & 2 /* NoIndexSignatures */ ? filterType(getUnionType(keyTypes), (t) => !(t.flags & (1 /* Any */ | 4 /* String */))) : getUnionType(keyTypes);
    if (result.flags & 1048576 /* Union */ && constraintType.flags & 1048576 /* 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 & (3 /* AnyOrUnknown */ | 402784252 /* Primitive */ | 131072 /* Never */ | 262144 /* TypeParameter */ | 524288 /* Object */ | 67108864 /* NonPrimitive */) ? true : type.flags & 16777216 /* Conditional */ ? type.root.isDistributive && type.checkType === typeVariable : type.flags & (3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */) ? every(type.types, isDistributive) : type.flags & 8388608 /* IndexedAccess */ ? isDistributive(type.objectType) && isDistributive(type.indexType) : type.flags & 33554432 /* Substitution */ ? isDistributive(type.baseType) && isDistributive(type.constraint) : type.flags & 268435456 /* 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) & 6 /* NonPublicAccessibilityModifier */)) {
      let type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
      if (!type) {
        const name = getNameOfDeclaration(prop.valueDeclaration);
        type = prop.escapedName === "default" /* 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 & 2097152 /* Intersection */ && some(keyType.types, (t) => isKeyTypeIncluded(t, include)));
  }
  function getLiteralTypeFromProperties(type, include, includeOrigin) {
    const origin = includeOrigin && (getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* 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 & 8 /* Number */ ? stringOrNumberType : info.keyType : neverType);
    return getUnionType(
      concatenate(propertyTypes, indexKeyTypes),
      1 /* Literal */,
      /*aliasSymbol*/
      void 0,
      /*aliasTypeArguments*/
      void 0,
      origin
    );
  }
  function shouldDeferIndexType(type, indexFlags = 0 /* None */) {
    return !!(type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && (!hasDistributiveNameType(type) || getMappedTypeNameTypeKind(type) === 2 /* Remapping */) || type.flags & 1048576 /* Union */ && !(indexFlags & 4 /* NoReducibleCheck */) && isGenericReducibleType(type) || type.flags & 2097152 /* Intersection */ && maybeTypeOfKind(type, 465829888 /* Instantiable */) && some(type.types, isEmptyAnonymousObjectType));
  }
  function getIndexType(type, indexFlags = 0 /* None */) {
    type = getReducedType(type);
    return isNoInferType(type) ? getNoInferType(getIndexType(type.baseType, indexFlags)) : shouldDeferIndexType(type, indexFlags) ? getIndexTypeForGenericType(type, indexFlags) : type.flags & 1048576 /* Union */ ? getIntersectionType(map(type.types, (t) => getIndexType(t, indexFlags))) : type.flags & 2097152 /* Intersection */ ? getUnionType(map(type.types, (t) => getIndexType(t, indexFlags))) : getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, indexFlags) : type === wildcardType ? wildcardType : type.flags & 2 /* Unknown */ ? neverType : type.flags & (1 /* Any */ | 131072 /* Never */) ? stringNumberSymbolType : getLiteralTypeFromProperties(type, (indexFlags & 2 /* NoIndexSignatures */ ? 128 /* StringLiteral */ : 402653316 /* StringLike */) | (indexFlags & 1 /* StringsOnly */ ? 0 : 296 /* NumberLike */ | 12288 /* ESSymbolLike */), indexFlags === 0 /* 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 & 131072 /* Never */ ? stringType : indexType;
  }
  function getTypeFromTypeOperatorNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      switch (node.operator) {
        case 143 /* KeyOfKeyword */:
          links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
          break;
        case 158 /* UniqueKeyword */:
          links.resolvedType = node.type.kind === 155 /* SymbolKeyword */ ? getESSymbolLikeTypeForNode(walkUpParenthesizedTypes(node.parent)) : errorType;
          break;
        case 148 /* 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 & (131072 /* Never */ | 1048576 /* 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 & 4 /* 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 & (2944 /* Literal */ | 65536 /* Null */ | 32768 /* Undefined */)) {
          text += getTemplateStringForType(t) || "";
          text += texts2[i + 1];
        } else if (t.flags & 134217728 /* 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 & 128 /* StringLiteral */ ? type.value : type.flags & 256 /* NumberLiteral */ ? "" + type.value : type.flags & 2048 /* BigIntLiteral */ ? pseudoBigIntToString(type.value) : type.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) ? type.intrinsicName : void 0;
  }
  function createTemplateLiteralType(texts, types) {
    const type = createType(134217728 /* TemplateLiteral */);
    type.texts = texts;
    type.types = types;
    return type;
  }
  function getStringMappingType(symbol, type) {
    return type.flags & (1048576 /* Union */ | 131072 /* Never */) ? mapType(type, (t) => getStringMappingType(symbol, t)) : type.flags & 128 /* StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : type.flags & 134217728 /* TemplateLiteral */ ? getTemplateLiteralType(...applyTemplateStringMapping(symbol, type.texts, type.types)) : (
      // Mapping<Mapping<T>> === Mapping<T>
      type.flags & 268435456 /* StringMapping */ && symbol === type.symbol ? type : type.flags & (1 /* Any */ | 4 /* String */ | 268435456 /* 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(268435456 /* StringMapping */, symbol);
    result.type = type;
    return result;
  }
  function createIndexedAccessType(objectType, indexType, accessFlags, aliasSymbol, aliasTypeArguments) {
    const type = createType(8388608 /* 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) & 4096 /* JSLiteral */) {
      return true;
    }
    if (type.flags & 1048576 /* Union */) {
      return every(type.types, isJSLiteralType);
    }
    if (type.flags & 2097152 /* Intersection */) {
      return some(type.types, isJSLiteralType);
    }
    if (type.flags & 465829888 /* 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 & (16 /* Function */ | 8192 /* Method */)) {
      const parent2 = findAncestor(node.parent, (n) => !isAccessExpression(n)) || node.parent;
      if (isCallLikeExpression(parent2)) {
        return isCallOrNewExpression(parent2) && isIdentifier(node) && hasMatchingArgument(parent2, node);
      }
      return every(symbol.declarations, (d) => !isFunctionLike(d) || isDeprecatedDeclaration2(d));
    }
    return true;
  }
  function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, accessNode, accessFlags) {
    const accessExpression = accessNode && accessNode.kind === 212 /* ElementAccessExpression */ ? accessNode : void 0;
    const propName = accessNode && isPrivateIdentifier(accessNode) ? void 0 : getPropertyNameFromIndex(indexType, accessNode);
    if (propName !== void 0) {
      if (accessFlags & 256 /* Contextual */) {
        return getTypeOfPropertyOfContextualType(objectType, propName) || anyType;
      }
      const prop = getPropertyOfType(objectType, propName);
      if (prop) {
        if (accessFlags & 64 /* ReportDeprecated */ && accessNode && prop.declarations && isDeprecatedSymbol(prop) && isUncalledFunctionReference(accessNode, prop)) {
          const deprecatedNode = (accessExpression == null ? void 0 : 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))) {
            error2(accessExpression.argumentExpression, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
            return void 0;
          }
          if (accessFlags & 8 /* CacheSymbol */) {
            getNodeLinks(accessNode).resolvedSymbol = prop;
          }
          if (isThisPropertyAccessInConstructor(accessExpression, prop)) {
            return autoType;
          }
        }
        const propType = accessFlags & 4 /* Writing */ ? getWriteTypeOfSymbol(prop) : getTypeOfSymbol(prop);
        return accessExpression && getAssignmentTargetKind(accessExpression) !== 1 /* 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 & 12 /* Variable */)) && !(accessFlags & 16 /* AllowMissing */)) {
          const indexNode = getIndexNodeForAccessExpression(accessNode);
          if (isTupleType(objectType)) {
            if (index < 0) {
              error2(indexNode, Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value);
              return undefinedType;
            }
            error2(indexNode, Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), unescapeLeadingUnderscores(propName));
          } else {
            error2(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 & 1 /* IncludeUndefined */ ? missingType : void 0);
        }
      }
    }
    if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
      if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
        return objectType;
      }
      const indexInfo = getApplicableIndexInfo(objectType, indexType) || getIndexInfoOfType(objectType, stringType);
      if (indexInfo) {
        if (accessFlags & 2 /* NoIndexSignatures */ && indexInfo.keyType !== numberType) {
          if (accessExpression) {
            if (accessFlags & 4 /* Writing */) {
              error2(accessExpression, Diagnostics.Type_0_is_generic_and_can_only_be_indexed_for_reading, typeToString(originalObjectType));
            } else {
              error2(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, 4 /* String */ | 8 /* Number */)) {
          const indexNode = getIndexNodeForAccessExpression(accessNode);
          error2(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
          return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([indexInfo.type, missingType]) : indexInfo.type;
        }
        errorIfWritingToReadonlyIndex(indexInfo);
        if (accessFlags & 1 /* IncludeUndefined */ && !(objectType.symbol && objectType.symbol.flags & (256 /* RegularEnum */ | 128 /* ConstEnum */) && (indexType.symbol && indexType.flags & 1024 /* EnumLiteral */ && getParentOfSymbol(indexType.symbol) === objectType.symbol))) {
          return getUnionType([indexInfo.type, missingType]);
        }
        return indexInfo.type;
      }
      if (indexType.flags & 131072 /* Never */) {
        return neverType;
      }
      if (isJSLiteralType(objectType)) {
        return anyType;
      }
      if (accessExpression && !isConstEnumObjectType(objectType)) {
        if (isObjectLiteralType2(objectType)) {
          if (noImplicitAny && indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
            diagnostics.add(createDiagnosticForNode(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType)));
            return undefinedType;
          } else if (indexType.flags & (8 /* Number */ | 4 /* 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 & 418 /* BlockScoped */) {
          error2(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType));
        } else if (noImplicitAny && !(accessFlags & 128 /* SuppressNoImplicitAnyError */)) {
          if (propName !== void 0 && typeHasStaticProperty(propName, objectType)) {
            const typeName = typeToString(objectType);
            error2(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)) {
            error2(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) {
                error2(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) {
                error2(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 & 1024 /* EnumLiteral */) {
                  errorInfo = chainDiagnosticMessages(
                    /*details*/
                    void 0,
                    Diagnostics.Property_0_does_not_exist_on_type_1,
                    "[" + typeToString(indexType) + "]",
                    typeToString(objectType)
                  );
                } else if (indexType.flags & 8192 /* 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 & 128 /* StringLiteral */) {
                  errorInfo = chainDiagnosticMessages(
                    /*details*/
                    void 0,
                    Diagnostics.Property_0_does_not_exist_on_type_1,
                    indexType.value,
                    typeToString(objectType)
                  );
                } else if (indexType.flags & 256 /* NumberLiteral */) {
                  errorInfo = chainDiagnosticMessages(
                    /*details*/
                    void 0,
                    Diagnostics.Property_0_does_not_exist_on_type_1,
                    indexType.value,
                    typeToString(objectType)
                  );
                } else if (indexType.flags & (8 /* Number */ | 4 /* 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 & 16 /* AllowMissing */ && isObjectLiteralType2(objectType)) {
      return undefinedType;
    }
    if (isJSLiteralType(objectType)) {
      return anyType;
    }
    if (accessNode) {
      const indexNode = getIndexNodeForAccessExpression(accessNode);
      if (indexNode.kind !== 10 /* BigIntLiteral */ && indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
        error2(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
      } else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
        error2(indexNode, Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
      } else {
        const typeString = indexNode.kind === 10 /* BigIntLiteral */ ? "bigint" : typeToString(indexType);
        error2(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))) {
        error2(accessExpression, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
      }
    }
  }
  function getIndexNodeForAccessExpression(accessNode) {
    return accessNode.kind === 212 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.kind === 199 /* IndexedAccessType */ ? accessNode.indexType : accessNode.kind === 167 /* ComputedPropertyName */ ? accessNode.expression : accessNode;
  }
  function isPatternLiteralPlaceholderType(type) {
    if (type.flags & 2097152 /* Intersection */) {
      let seenPlaceholder = false;
      for (const t of type.types) {
        if (t.flags & (2944 /* Literal */ | 98304 /* Nullable */) || isPatternLiteralPlaceholderType(t)) {
          seenPlaceholder = true;
        } else if (!(t.flags & 524288 /* Object */)) {
          return false;
        }
      }
      return seenPlaceholder;
    }
    return !!(type.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 64 /* BigInt */)) || isPatternLiteralType(type);
  }
  function isPatternLiteralType(type) {
    return !!(type.flags & 134217728 /* TemplateLiteral */) && every(type.types, isPatternLiteralPlaceholderType) || !!(type.flags & 268435456 /* StringMapping */) && isPatternLiteralPlaceholderType(type.type);
  }
  function isGenericStringLikeType(type) {
    return !!(type.flags & (134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type);
  }
  function isGenericType(type) {
    return !!getGenericObjectFlags(type);
  }
  function isGenericObjectType(type) {
    return !!(getGenericObjectFlags(type) & 4194304 /* IsGenericObjectType */);
  }
  function isGenericIndexType(type) {
    return !!(getGenericObjectFlags(type) & 8388608 /* IsGenericIndexType */);
  }
  function getGenericObjectFlags(type) {
    if (type.flags & 3145728 /* UnionOrIntersection */) {
      if (!(type.objectFlags & 2097152 /* IsGenericTypeComputed */)) {
        type.objectFlags |= 2097152 /* IsGenericTypeComputed */ | reduceLeft(type.types, (flags, t) => flags | getGenericObjectFlags(t), 0);
      }
      return type.objectFlags & 12582912 /* IsGenericType */;
    }
    if (type.flags & 33554432 /* Substitution */) {
      if (!(type.objectFlags & 2097152 /* IsGenericTypeComputed */)) {
        type.objectFlags |= 2097152 /* IsGenericTypeComputed */ | getGenericObjectFlags(type.baseType) | getGenericObjectFlags(type.constraint);
      }
      return type.objectFlags & 12582912 /* IsGenericType */;
    }
    return (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type) || isGenericTupleType(type) ? 4194304 /* IsGenericObjectType */ : 0) | (type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */) || isGenericStringLikeType(type) ? 8388608 /* IsGenericIndexType */ : 0);
  }
  function getSimplifiedType(type, writing) {
    return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) : type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) : type;
  }
  function distributeIndexOverObjectType(objectType, indexType, writing) {
    if (objectType.flags & 1048576 /* Union */ || objectType.flags & 2097152 /* Intersection */ && !shouldDeferIndexType(objectType)) {
      const types = map(objectType.types, (t) => getSimplifiedType(getIndexedAccessType(t, indexType), writing));
      return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
    }
  }
  function distributeObjectOverIndexType(objectType, indexType, writing) {
    if (indexType.flags & 1048576 /* 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 & 465829888 /* Instantiable */)) {
      const distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
      if (distributedOverObject) {
        return type[cache] = distributedOverObject;
      }
    }
    if (isGenericTupleType(objectType) && indexType.flags & 296 /* NumberLike */) {
      const elementType = getElementTypeOfSliceOfTupleType(
        objectType,
        indexType.flags & 8 /* 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 & 131072 /* Never */ && getActualTypeVariable(trueType2) === getActualTypeVariable(checkType)) {
      if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) {
        return getSimplifiedType(trueType2, writing);
      } else if (isIntersectionEmpty(checkType, extendsType)) {
        return neverType;
      }
    } else if (trueType2.flags & 131072 /* Never */ && getActualTypeVariable(falseType2) === getActualTypeVariable(checkType)) {
      if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) {
        return neverType;
      } else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) {
        return getSimplifiedType(falseType2, writing);
      }
    }
    return type;
  }
  function isIntersectionEmpty(type1, type2) {
    return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* 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 & 16777216 /* Optional */) && isTypeAssignableTo(getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */), indexConstraint));
  }
  function getIndexedAccessType(objectType, indexType, accessFlags = 0 /* 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 & 384 /* StringOrNumberLiteral */) {
        const propName = getPropertyNameFromType(t);
        if (isNumericLiteralName(propName)) {
          const index = +propName;
          return index >= 0 && index < limit;
        }
      }
      return false;
    });
  }
  function getIndexedAccessTypeOrUndefined(objectType, indexType, accessFlags = 0 /* None */, accessNode, aliasSymbol, aliasTypeArguments) {
    if (objectType === wildcardType || indexType === wildcardType) {
      return wildcardType;
    }
    objectType = getReducedType(objectType);
    if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
      indexType = stringType;
    }
    if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */) accessFlags |= 1 /* IncludeUndefined */;
    if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType))) {
      if (objectType.flags & 3 /* AnyOrUnknown */) {
        return objectType;
      }
      const persistentAccessFlags = accessFlags & 1 /* 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 & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
      const propTypes = [];
      let wasMissingProp = false;
      for (const t of indexType.types) {
        const propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, accessNode, accessFlags | (wasMissingProp ? 128 /* SuppressNoImplicitAnyError */ : 0));
        if (propType) {
          propTypes.push(propType);
        } else if (!accessNode) {
          return void 0;
        } else {
          wasMissingProp = true;
        }
      }
      if (wasMissingProp) {
        return void 0;
      }
      return accessFlags & 4 /* Writing */ ? getIntersectionType(propTypes, 0 /* None */, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments);
    }
    return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, accessNode, accessFlags | 8 /* CacheSymbol */ | 64 /* 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, 0 /* None */, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
    }
    return links.resolvedType;
  }
  function getTypeFromMappedTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const type = createObjectType(32 /* 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 & 33554432 /* Substitution */) {
      return getActualTypeVariable(type.baseType);
    }
    if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ || type.indexType.flags & 33554432 /* 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) {
        error2(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,
          0 /* None */
        );
        if (mapper) {
          context.nonFixingMapper = combineTypeMappers(context.nonFixingMapper, mapper);
        }
        if (!checkTypeDeferred) {
          inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* 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 & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
          if (checkType.flags & 1 /* Any */ || forConstraint && !(inferredExtendsType.flags & 131072 /* 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 & 16777216 /* 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 & 3 /* 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(16777216 /* 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 & 16777216 /* 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 & (1048576 /* Union */ | 131072 /* 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 & 262144 /* 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 & 262144 /* 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) {
    var _a;
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      if (!isLiteralImportTypeNode(node)) {
        error2(node.argument, Diagnostics.String_literal_expected);
        links.resolvedSymbol = unknownSymbol;
        return links.resolvedType = errorType;
      }
      const targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 16777216 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
      const innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
      if (!innerModuleSymbol) {
        links.resolvedSymbol = unknownSymbol;
        return links.resolvedType = errorType;
      }
      const isExportEquals = !!((_a = innerModuleSymbol.exports) == null ? void 0 : _a.get("export=" /* 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 ? 1920 /* 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 : getSymbol2(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning);
          const next = symbolFromModule ?? symbolFromVariable;
          if (!next) {
            error2(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 === 111551 /* 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;
          error2(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 === 111551 /* 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 (!node.symbol || getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
        links.resolvedType = emptyTypeLiteralType;
      } else {
        let type = createObjectType(16 /* 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 === 148 /* 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 & 524288 /* Object */) && !isGenericMappedType(type);
  }
  function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
    return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
  }
  function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
    if (!(type.flags & 1048576 /* 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) & (2 /* Private */ | 4 /* Protected */)) {
        } else if (isSpreadableProperty(prop)) {
          const isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
          const flags = 4 /* Property */ | 16777216 /* Optional */;
          const result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? 8 /* 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 |= 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */;
      return spread;
    }
  }
  function getSpreadType(left, right, symbol, objectFlags, readonly) {
    if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
      return anyType;
    }
    if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
      return unknownType;
    }
    if (left.flags & 131072 /* Never */) {
      return right;
    }
    if (right.flags & 131072 /* Never */) {
      return left;
    }
    left = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
    if (left.flags & 1048576 /* Union */) {
      return checkCrossProductUnion([left, right]) ? mapType(left, (t) => getSpreadType(t, right, symbol, objectFlags, readonly)) : errorType;
    }
    right = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
    if (right.flags & 1048576 /* Union */) {
      return checkCrossProductUnion([left, right]) ? mapType(right, (t) => getSpreadType(left, t, symbol, objectFlags, readonly)) : errorType;
    }
    if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
      return left;
    }
    if (isGenericObjectType(left) || isGenericObjectType(right)) {
      if (isEmptyObjectType(left)) {
        return right;
      }
      if (left.flags & 2097152 /* 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) & (2 /* Private */ | 4 /* 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 & 16777216 /* Optional */) {
          const declarations = concatenate(leftProp.declarations, rightProp.declarations);
          const flags = 4 /* Property */ | leftProp.flags & 16777216 /* 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], 2 /* 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 |= 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */ | 2097152 /* ContainsSpread */ | objectFlags;
    return spread;
  }
  function isSpreadableProperty(prop) {
    var _a;
    return !some(prop.declarations, isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || !((_a = prop.declarations) == null ? void 0 : _a.some((decl) => isClassLike(decl.parent))));
  }
  function getSpreadSymbol(prop, readonly) {
    const isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
    if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
      return prop;
    }
    const flags = 4 /* Property */ | prop.flags & 16777216 /* Optional */;
    const result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? 8 /* 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 & 2976 /* 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 & 2976 /* Freshable */ ? type.regularType : type.flags & 1048576 /* Union */ ? type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType)) : type;
  }
  function isFreshLiteralType(type) {
    return !!(type.flags & 2976 /* Freshable */) && type.freshType === type;
  }
  function getStringLiteralType(value) {
    let type;
    return stringLiteralTypes.get(value) || (stringLiteralTypes.set(value, type = createLiteralType(128 /* StringLiteral */, value)), type);
  }
  function getNumberLiteralType(value) {
    let type;
    return numberLiteralTypes.get(value) || (numberLiteralTypes.set(value, type = createLiteralType(256 /* NumberLiteral */, value)), type);
  }
  function getBigIntLiteralType(value) {
    let type;
    const key = pseudoBigIntToString(value);
    return bigIntLiteralTypes.get(key) || (bigIntLiteralTypes.set(key, type = createLiteralType(2048 /* BigIntLiteral */, value)), type);
  }
  function getEnumLiteralType(value, enumId, symbol) {
    let type;
    const key = `${enumId}${typeof value === "string" ? "@" : "#"}${value}`;
    const flags = 1024 /* EnumLiteral */ | (typeof value === "string" ? 128 /* StringLiteral */ : 256 /* NumberLiteral */);
    return enumLiteralTypes.get(key) || (enumLiteralTypes.set(key, type = createLiteralType(flags, value, symbol)), type);
  }
  function getTypeFromLiteralTypeNode(node) {
    if (node.literal.kind === 106 /* 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(8192 /* 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 parent2 = container && container.parent;
    if (parent2 && (isClassLike(parent2) || parent2.kind === 264 /* InterfaceDeclaration */)) {
      if (!isStatic(container) && (!isConstructorDeclaration(container) || isNodeDescendantOf(node, container.body))) {
        return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(parent2)).thisType;
      }
    }
    if (parent2 && isObjectLiteralExpression(parent2) && isBinaryExpression(parent2.parent) && getAssignmentDeclarationKind(parent2.parent) === 6 /* Prototype */) {
      return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent2.parent.left).parent).thisType;
    }
    const host2 = node.flags & 16777216 /* JSDoc */ ? getHostSignatureFromJSDoc(node) : void 0;
    if (host2 && isFunctionExpression(host2) && isBinaryExpression(host2.parent) && getAssignmentDeclarationKind(host2.parent) === 3 /* PrototypeProperty */) {
      return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host2.parent.left).parent).thisType;
    }
    if (isJSConstructor(container) && isNodeDescendantOf(node, container.body)) {
      return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(container)).thisType;
    }
    error2(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 196 /* ParenthesizedType */:
        return getArrayElementTypeNode(node.type);
      case 189 /* TupleType */:
        if (node.elements.length === 1) {
          node = node.elements[0];
          if (node.kind === 191 /* RestType */ || node.kind === 202 /* NamedTupleMember */ && node.dotDotDotToken) {
            return getArrayElementTypeNode(node.type);
          }
        }
        break;
      case 188 /* 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 133 /* AnyKeyword */:
      case 312 /* JSDocAllType */:
      case 313 /* JSDocUnknownType */:
        return anyType;
      case 159 /* UnknownKeyword */:
        return unknownType;
      case 154 /* StringKeyword */:
        return stringType;
      case 150 /* NumberKeyword */:
        return numberType;
      case 163 /* BigIntKeyword */:
        return bigintType;
      case 136 /* BooleanKeyword */:
        return booleanType;
      case 155 /* SymbolKeyword */:
        return esSymbolType;
      case 116 /* VoidKeyword */:
        return voidType;
      case 157 /* UndefinedKeyword */:
        return undefinedType;
      case 106 /* NullKeyword */:
        return nullType;
      case 146 /* NeverKeyword */:
        return neverType;
      case 151 /* ObjectKeyword */:
        return node.flags & 524288 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
      case 141 /* IntrinsicKeyword */:
        return intrinsicMarkerType;
      case 197 /* ThisType */:
      case 110 /* ThisKeyword */:
        return getTypeFromThisTypeNode(node);
      case 201 /* LiteralType */:
        return getTypeFromLiteralTypeNode(node);
      case 183 /* TypeReference */:
        return getTypeFromTypeReference(node);
      case 182 /* TypePredicate */:
        return node.assertsModifier ? voidType : booleanType;
      case 233 /* ExpressionWithTypeArguments */:
        return getTypeFromTypeReference(node);
      case 186 /* TypeQuery */:
        return getTypeFromTypeQueryNode(node);
      case 188 /* ArrayType */:
      case 189 /* TupleType */:
        return getTypeFromArrayOrTupleTypeNode(node);
      case 190 /* OptionalType */:
        return getTypeFromOptionalTypeNode(node);
      case 192 /* UnionType */:
        return getTypeFromUnionTypeNode(node);
      case 193 /* IntersectionType */:
        return getTypeFromIntersectionTypeNode(node);
      case 314 /* JSDocNullableType */:
        return getTypeFromJSDocNullableTypeNode(node);
      case 316 /* JSDocOptionalType */:
        return addOptionality(getTypeFromTypeNode(node.type));
      case 202 /* NamedTupleMember */:
        return getTypeFromNamedTupleTypeNode(node);
      case 196 /* ParenthesizedType */:
      case 315 /* JSDocNonNullableType */:
      case 309 /* JSDocTypeExpression */:
        return getTypeFromTypeNode(node.type);
      case 191 /* RestType */:
        return getTypeFromRestTypeNode(node);
      case 318 /* JSDocVariadicType */:
        return getTypeFromJSDocVariadicType(node);
      case 184 /* FunctionType */:
      case 185 /* ConstructorType */:
      case 187 /* TypeLiteral */:
      case 322 /* JSDocTypeLiteral */:
      case 317 /* JSDocFunctionType */:
      case 323 /* JSDocSignature */:
        return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
      case 198 /* TypeOperator */:
        return getTypeFromTypeOperatorNode(node);
      case 199 /* IndexedAccessType */:
        return getTypeFromIndexedAccessTypeNode(node);
      case 200 /* MappedType */:
        return getTypeFromMappedTypeNode(node);
      case 194 /* ConditionalType */:
        return getTypeFromConditionalTypeNode(node);
      case 195 /* InferType */:
        return getTypeFromInferTypeNode(node);
      case 203 /* TemplateLiteralType */:
        return getTypeFromTemplateTypeNode(node);
      case 205 /* 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 80 /* Identifier */:
      case 166 /* QualifiedName */:
      case 211 /* 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 0 /* Simple */:
        return type === mapper.source ? mapper.target : type;
      case 1 /* 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 2 /* 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 3 /* Function */:
        return mapper.func(type);
      case 4 /* Composite */:
      case 5 /* Merged */:
        const t1 = getMappedType(type, mapper.mapper1);
        return t1 !== type && mapper.kind === 4 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
    }
  }
  function makeUnaryTypeMapper(source, target) {
    return Debug.attachDebugPrototypeIfDebug({ kind: 0 /* Simple */, source, target });
  }
  function makeArrayTypeMapper(sources, targets) {
    return Debug.attachDebugPrototypeIfDebug({ kind: 1 /* Array */, sources, targets });
  }
  function makeFunctionTypeMapper(func, debugInfo) {
    return Debug.attachDebugPrototypeIfDebug({ kind: 3 /* Function */, func, debugInfo: Debug.isDebugging ? debugInfo : void 0 });
  }
  function makeDeferredTypeMapper(sources, targets) {
    return Debug.attachDebugPrototypeIfDebug({ kind: 2 /* 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(4 /* Composite */, mapper1, mapper2) : mapper2;
  }
  function mergeTypeMappers(mapper1, mapper2) {
    return mapper1 ? makeCompositeTypeMapper(5 /* Merged */, mapper1, mapper2) : mapper2;
  }
  function prependTypeMapping(source, target, mapper) {
    return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
  }
  function appendTypeMapping(mapper, source, target) {
    return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* 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 & 167 /* 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 & 65536 /* SetAccessor */)) {
        return symbol;
      }
      if (links.writeType && !couldContainTypeVariables(links.writeType)) {
        return symbol;
      }
    }
    if (getCheckFlags(symbol) & 1 /* Instantiated */) {
      symbol = links.target;
      mapper = combineTypeMappers(links.mapper, mapper);
    }
    const result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* 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 & 4 /* Reference */ ? type.node : type.objectFlags & 8388608 /* InstantiationExpressionType */ ? type.node : type.symbol.declarations[0];
    const links = getNodeLinks(declaration);
    const target = type.objectFlags & 4 /* Reference */ ? links.resolvedType : type.objectFlags & 64 /* Instantiated */ ? type.target : type;
    let typeParameters = type.objectFlags & 134217728 /* 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 & (4 /* Reference */ | 8388608 /* InstantiationExpressionType */) ? [declaration] : type.symbol.declarations;
      typeParameters = (target.objectFlags & (4 /* Reference */ | 8388608 /* InstantiationExpressionType */) || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* 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 & 134217728 /* 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 & 134217728 /* SingleSignatureType */) {
          result = instantiateAnonymousType(type, mapper);
          target.instantiations.set(id, result);
          return result;
        }
        const newMapper = createTypeMapper(typeParameters, typeArguments);
        result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments);
        target.instantiations.set(id, result);
        const resultObjectFlags = getObjectFlags(result);
        if (result.flags & 3899393 /* ObjectFlagsType */ && !(resultObjectFlags & 524288 /* CouldContainTypeVariablesComputed */)) {
          const resultCouldContainTypeVariables = some(typeArguments, couldContainTypeVariables);
          if (!(getObjectFlags(result) & 524288 /* CouldContainTypeVariablesComputed */)) {
            if (resultObjectFlags & (32 /* Mapped */ | 16 /* Anonymous */ | 4 /* Reference */)) {
              result.objectFlags |= 524288 /* CouldContainTypeVariablesComputed */ | (resultCouldContainTypeVariables ? 1048576 /* CouldContainTypeVariables */ : 0);
            } else {
              result.objectFlags |= !resultCouldContainTypeVariables ? 524288 /* CouldContainTypeVariablesComputed */ : 0;
            }
          }
        }
      }
      return result;
    }
    return type;
  }
  function maybeTypeParameterReference(node) {
    return !(node.parent.kind === 183 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || node.parent.kind === 205 /* 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 === 241 /* Block */ || n.kind === 194 /* ConditionalType */ && forEachChild(n.extendsType, containsReference)) {
          return true;
        }
      }
      return containsReference(node);
    }
    return true;
    function containsReference(node2) {
      switch (node2.kind) {
        case 197 /* ThisType */:
          return !!tp.isThisType;
        case 80 /* Identifier */:
          return !tp.isThisType && isPartOfTypeNode(node2) && maybeTypeParameterReference(node2) && getTypeFromTypeNodeWorker(node2) === tp;
        // use worker because we're looking for === equality
        case 186 /* 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 === 168 /* 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 174 /* MethodDeclaration */:
        case 173 /* 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 & 4194304 /* Index */) {
      const typeVariable = getActualTypeVariable(constraintType.type);
      if (typeVariable.flags & 262144 /* 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 & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) {
        if (!type.declaration.nameType) {
          let constraint;
          if (isArrayType(t) || t.flags & 1 /* 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 & 2 /* Optional */), fixedMapper) : flags & 8 /* 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 & 1 /* Required */ ? 2 /* Optional */ : f) : modifiers & 8 /* ExcludeOptional */ ? map(elementFlags, (f) => f & 2 /* Optional */ ? 1 /* 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, 32768 /* Undefined */ | 16384 /* 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 & ~(524288 /* CouldContainTypeVariablesComputed */ | 1048576 /* CouldContainTypeVariables */) | 64 /* Instantiated */, type.symbol);
    if (type.objectFlags & 32 /* 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 & 8388608 /* InstantiationExpressionType */) {
      result.node = type.node;
    }
    if (type.objectFlags & 134217728 /* 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 & (1048576 /* Union */ | 131072 /* 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) {
    var _a;
    if (!couldContainTypeVariables(type)) {
      return type;
    }
    if (instantiationDepth === 100 || instantiationCount >= 5e6) {
      (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth, instantiationCount });
      error2(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 & 262144 /* TypeParameter */) {
      return getMappedType(type, mapper);
    }
    if (flags & 524288 /* Object */) {
      const objectFlags = type.objectFlags;
      if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) {
        if (objectFlags & 4 /* Reference */ && !type.node) {
          const resolvedTypeArguments = type.resolvedTypeArguments;
          const newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
          return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type;
        }
        if (objectFlags & 1024 /* ReverseMapped */) {
          return instantiateReverseMappedType(type, mapper);
        }
        return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments);
      }
      return type;
    }
    if (flags & 3145728 /* UnionOrIntersection */) {
      const origin = type.flags & 1048576 /* Union */ ? type.origin : void 0;
      const types = origin && origin.flags & 3145728 /* 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 & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? getIntersectionType(newTypes, 0 /* None */, newAliasSymbol, newAliasTypeArguments) : getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments);
    }
    if (flags & 4194304 /* Index */) {
      return getIndexType(instantiateType(type.type, mapper));
    }
    if (flags & 134217728 /* TemplateLiteral */) {
      return getTemplateLiteralType(type.texts, instantiateTypes(type.types, mapper));
    }
    if (flags & 268435456 /* StringMapping */) {
      return getStringMappingType(type.symbol, instantiateType(type.type, mapper));
    }
    if (flags & 8388608 /* 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 & 16777216 /* Conditional */) {
      return getConditionalTypeInstantiation(
        type,
        combineTypeMappers(type.mapper, mapper),
        /*forConstraint*/
        false,
        aliasSymbol,
        aliasTypeArguments
      );
    }
    if (flags & 33554432 /* Substitution */) {
      const newBaseType = instantiateType(type.baseType, mapper);
      if (isNoInferType(type)) {
        return getNoInferType(newBaseType);
      }
      const newConstraint = instantiateType(type.constraint, mapper);
      if (newBaseType.flags & 8650752 /* TypeVariable */ && isGenericType(newConstraint)) {
        return getSubstitutionType(newBaseType, newConstraint);
      }
      if (newConstraint.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(newBaseType), getRestrictiveInstantiation(newConstraint))) {
        return newBaseType;
      }
      return newBaseType.flags & 8650752 /* TypeVariable */ ? getSubstitutionType(newBaseType, newConstraint) : getIntersectionType([newConstraint, newBaseType]);
    }
    return type;
  }
  function instantiateReverseMappedType(type, mapper) {
    const innerMappedType = instantiateType(type.mappedType, mapper);
    if (!(getObjectFlags(innerMappedType) & 32 /* Mapped */)) {
      return type;
    }
    const innerIndexType = instantiateType(type.constraintType, mapper);
    if (!(innerIndexType.flags & 4194304 /* Index */)) {
      return type;
    }
    const instantiated = inferTypeForHomomorphicMappedType(
      instantiateType(type.source, mapper),
      innerMappedType,
      innerIndexType
    );
    if (instantiated) {
      return instantiated;
    }
    return type;
  }
  function getPermissiveInstantiation(type) {
    return type.flags & (402784252 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
  }
  function getRestrictiveInstantiation(type) {
    if (type.flags & (402784252 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* 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 !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node));
    switch (node.kind) {
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 174 /* MethodDeclaration */:
      case 262 /* FunctionDeclaration */:
        return isContextSensitiveFunctionLikeDeclaration(node);
      case 210 /* ObjectLiteralExpression */:
        return some(node.properties, isContextSensitive);
      case 209 /* ArrayLiteralExpression */:
        return some(node.elements, isContextSensitive);
      case 227 /* ConditionalExpression */:
        return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse);
      case 226 /* BinaryExpression */:
        return (node.operatorToken.kind === 57 /* BarBarToken */ || node.operatorToken.kind === 61 /* QuestionQuestionToken */) && (isContextSensitive(node.left) || isContextSensitive(node.right));
      case 303 /* PropertyAssignment */:
        return isContextSensitive(node.initializer);
      case 217 /* ParenthesizedExpression */:
        return isContextSensitive(node.expression);
      case 292 /* JsxAttributes */:
        return some(node.properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive);
      case 291 /* JsxAttribute */: {
        const { initializer } = node;
        return !!initializer && isContextSensitive(initializer);
      }
      case 294 /* 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 !== 241 /* 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 & 524288 /* Object */) {
      const resolved = resolveStructuredTypeMembers(type);
      if (resolved.constructSignatures.length || resolved.callSignatures.length) {
        const result = createObjectType(16 /* 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 & 2097152 /* 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) ? -1 /* True */ : 0 /* False */;
  }
  function compareTypesAssignable(source, target) {
    return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
  }
  function compareTypesSubtypeOf(source, target) {
    return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* 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 & 1048576 /* Union */ ? every(source.types, (t) => isTypeDerivedFrom(t, target)) : target.flags & 1048576 /* Union */ ? some(target.types, (t) => isTypeDerivedFrom(source, t)) : source.flags & 2097152 /* Intersection */ ? some(source.types, (t) => isTypeDerivedFrom(t, target)) : source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) : isEmptyAnonymousObjectType(target) ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) && !isEmptyAnonymousObjectType(source) : target === globalFunctionType ? !!(source.flags & 524288 /* 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 & 16777216 /* Conditional */ || type.flags & 2097152 /* 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 234 /* AsExpression */:
        if (!isConstAssertion(node)) {
          break;
        }
      // fallthrough
      case 294 /* JsxExpression */:
      case 217 /* ParenthesizedExpression */:
        return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
      case 226 /* BinaryExpression */:
        switch (node.operatorToken.kind) {
          case 64 /* EqualsToken */:
          case 28 /* CommaToken */:
            return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
        }
        break;
      case 210 /* ObjectLiteralExpression */:
        return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
      case 209 /* ArrayLiteralExpression */:
        return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
      case 292 /* JsxAttributes */:
        return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
      case 219 /* ArrowFunction */:
        return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
    }
    return false;
  }
  function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
    const callSignatures = getSignaturesOfType(source, 0 /* Call */);
    const constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
    for (const signatures of [constructSignatures, callSignatures]) {
      if (some(signatures, (s) => {
        const returnType = getReturnTypeOfSignature(s);
        return !(returnType.flags & (1 /* Any */ | 131072 /* 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, 0 /* 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) & 2 /* 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 & 1048576 /* 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 & 8388608 /* 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 diag2 = 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(diag2);
            resultObj.errors = [diag2];
          } else {
            const targetIsOptional = !!(propName && (getPropertyOfType(target, propName) || unknownSymbol).flags & 16777216 /* Optional */);
            const sourceIsOptional = !!(propName && (getPropertyOfType(source, propName) || unknownSymbol).flags & 16777216 /* 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 & 8192 /* 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 & 8388608 /* 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 diag2 = 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(diag2);
            resultObj.errors = [diag2];
          } else {
            const targetIsOptional = !!(propName && (getPropertyOfType(tupleOrArrayLikeTargetParts, propName) || unknownSymbol).flags & 16777216 /* Optional */);
            const sourceIsOptional = !!(propName && (getPropertyOfType(source, propName) || unknownSymbol).flags & 16777216 /* 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 294 /* JsxExpression */:
        return { errorNode: child, innerExpression: child.expression, nameType };
      case 12 /* JsxText */:
        if (child.containsOnlyTriviaWhiteSpaces) {
          break;
        }
        return { errorNode: child, innerExpression: void 0, nameType, errorMessage: getInvalidTextDiagnostic() };
      case 284 /* JsxElement */:
      case 285 /* JsxSelfClosingElement */:
      case 288 /* 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 diag2 = error2(
            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(diag2);
          }
        }
      } 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 diag2 = error2(
            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(diag2);
          }
        }
      }
    }
    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 & (402784252 /* Primitive */ | 131072 /* 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), 8576 /* StringOrNumberLiteralOrUnique */);
      if (!type || type.flags & 131072 /* Never */) {
        continue;
      }
      switch (prop.kind) {
        case 178 /* SetAccessor */:
        case 177 /* GetAccessor */:
        case 174 /* MethodDeclaration */:
        case 304 /* ShorthandPropertyAssignment */:
          yield { errorNode: prop.name, innerExpression: void 0, nameType: type };
          break;
        case 303 /* 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 & (402784252 /* Primitive */ | 131072 /* 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
    ) !== 0 /* 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 & (1 /* Any */ | 131072 /* Never */) && getReturnTypeOfSignature(s).flags & 3 /* AnyOrUnknown */);
    }
    return false;
  }
  function compareSignaturesRelated(source, target, checkMode, reportErrors2, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
    if (source === target) {
      return -1 /* True */;
    }
    if (!(checkMode & 16 /* StrictTopSignature */ && isTopSignature(source)) && isTopSignature(target)) {
      return -1 /* True */;
    }
    if (checkMode & 16 /* StrictTopSignature */ && isTopSignature(source) && !isTopSignature(target)) {
      return 0 /* False */;
    }
    const targetCount = getParameterCount(target);
    const sourceHasMoreParameters = !hasEffectiveRestParameter(target) && (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
    if (sourceHasMoreParameters) {
      if (reportErrors2 && !(checkMode & 8 /* StrictArity */)) {
        errorReporter(Diagnostics.Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1, getMinArgumentCount(source), targetCount);
      }
      return 0 /* 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 : 0 /* Unknown */;
    const strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 174 /* MethodDeclaration */ && kind !== 173 /* MethodSignature */ && kind !== 176 /* Constructor */;
    let result = -1 /* 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, reportErrors2);
        if (!related) {
          if (reportErrors2) {
            errorReporter(Diagnostics.The_this_types_of_each_signature_are_incompatible);
          }
          return 0 /* 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 */), reportErrors2, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(
          sourceType,
          targetType,
          /*reportErrors*/
          false
        ) || compareTypes(targetType, sourceType, reportErrors2);
        if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(
          sourceType,
          targetType,
          /*reportErrors*/
          false
        )) {
          related = 0 /* False */;
        }
        if (!related) {
          if (reportErrors2) {
            errorReporter(Diagnostics.Types_of_parameters_0_and_1_are_incompatible, unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
          }
          return 0 /* 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, reportErrors2, errorReporter, compareTypes);
        } else if (isIdentifierTypePredicate(targetTypePredicate) || isThisTypePredicate(targetTypePredicate)) {
          if (reportErrors2) {
            errorReporter(Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
          }
          return 0 /* False */;
        }
      } else {
        result &= checkMode & 1 /* BivariantCallback */ && compareTypes(
          targetReturnType,
          sourceReturnType,
          /*reportErrors*/
          false
        ) || compareTypes(sourceReturnType, targetReturnType, reportErrors2);
        if (!result && reportErrors2 && incompatibleErrorReporter) {
          incompatibleErrorReporter(sourceReturnType, targetReturnType);
        }
      }
    }
    return result;
  }
  function compareTypePredicateRelatedTo(source, target, reportErrors2, errorReporter, compareTypes) {
    if (source.kind !== target.kind) {
      if (reportErrors2) {
        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 0 /* False */;
    }
    if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
      if (source.parameterIndex !== target.parameterIndex) {
        if (reportErrors2) {
          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 0 /* False */;
      }
    }
    const related = source.type === target.type ? -1 /* True */ : source.type && target.type ? compareTypes(source.type, target.type, reportErrors2) : 0 /* False */;
    if (related === 0 /* False */ && reportErrors2) {
      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 & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 67108864 /* NonPrimitive */ ? true : type.flags & 1048576 /* Union */ ? some(type.types, isEmptyObjectType) : type.flags & 2097152 /* Intersection */ ? every(type.types, isEmptyObjectType) : false;
  }
  function isEmptyAnonymousObjectType(type) {
    return !!(getObjectFlags(type) & 16 /* Anonymous */ && (type.members && isEmptyResolvedType(type) || type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0));
  }
  function isUnknownLikeUnionType(type) {
    if (strictNullChecks && type.flags & 1048576 /* Union */) {
      if (!(type.objectFlags & 33554432 /* IsUnknownLikeUnionComputed */)) {
        const types = type.types;
        type.objectFlags |= 33554432 /* IsUnknownLikeUnionComputed */ | (types.length >= 3 && types[0].flags & 32768 /* Undefined */ && types[1].flags & 65536 /* Null */ && some(types, isEmptyAnonymousObjectType) ? 67108864 /* IsUnknownLikeUnion */ : 0);
      }
      return !!(type.objectFlags & 67108864 /* IsUnknownLikeUnion */);
    }
    return false;
  }
  function containsUndefinedType(type) {
    return !!((type.flags & 1048576 /* Union */ ? type.types[0] : type).flags & 32768 /* Undefined */);
  }
  function containsNonMissingUndefinedType(type) {
    const candidate = type.flags & 1048576 /* Union */ ? type.types[0] : type;
    return !!(candidate.flags & 32768 /* Undefined */) && candidate !== missingType;
  }
  function isStringIndexSignatureOnlyType(type) {
    return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) || type.flags & 3145728 /* UnionOrIntersection */ && every(type.types, isStringIndexSignatureOnlyType) || false;
  }
  function isEnumTypeRelatedTo(source, target, errorReporter) {
    const sourceSymbol = source.flags & 8 /* EnumMember */ ? getParentOfSymbol(source) : source;
    const targetSymbol = target.flags & 8 /* EnumMember */ ? getParentOfSymbol(target) : target;
    if (sourceSymbol === targetSymbol) {
      return true;
    }
    if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
      return false;
    }
    const id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
    const entry = enumRelation.get(id);
    if (entry !== void 0 && !(entry & 2 /* Failed */ && errorReporter)) {
      return !!(entry & 1 /* Succeeded */);
    }
    const targetEnumType = getTypeOfSymbol(targetSymbol);
    for (const sourceProperty of getPropertiesOfType(getTypeOfSymbol(sourceSymbol))) {
      if (sourceProperty.flags & 8 /* EnumMember */) {
        const targetProperty = getPropertyOfType(targetEnumType, sourceProperty.escapedName);
        if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
          if (errorReporter) {
            errorReporter(Diagnostics.Property_0_is_missing_in_type_1, symbolName(sourceProperty), typeToString(
              getDeclaredTypeOfSymbol(targetSymbol),
              /*enclosingDeclaration*/
              void 0,
              64 /* UseFullyQualifiedType */
            ));
          }
          enumRelation.set(id, 2 /* Failed */);
          return false;
        }
        const sourceValue = getEnumMemberValue(getDeclarationOfKind(sourceProperty, 306 /* EnumMember */)).value;
        const targetValue = getEnumMemberValue(getDeclarationOfKind(targetProperty, 306 /* 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, 2 /* 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, 2 /* Failed */);
            return false;
          }
        }
      }
    }
    enumRelation.set(id, 1 /* Succeeded */);
    return true;
  }
  function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
    const s = source.flags;
    const t = target.flags;
    if (t & 1 /* Any */ || s & 131072 /* Never */ || source === wildcardType) return true;
    if (t & 2 /* Unknown */ && !(relation === strictSubtypeRelation && s & 1 /* Any */)) return true;
    if (t & 131072 /* Never */) return false;
    if (s & 402653316 /* StringLike */ && t & 4 /* String */) return true;
    if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true;
    if (s & 296 /* NumberLike */ && t & 8 /* Number */) return true;
    if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true;
    if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) return true;
    if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) return true;
    if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) return true;
    if (s & 32 /* Enum */ && t & 32 /* Enum */ && source.symbol.escapedName === target.symbol.escapedName && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true;
    if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
      if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true;
      if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true;
    }
    if (s & 32768 /* Undefined */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & (32768 /* Undefined */ | 16384 /* Void */))) return true;
    if (s & 65536 /* Null */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & 65536 /* Null */)) return true;
    if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(getObjectFlags(source) & 8192 /* FreshLiteral */))) return true;
    if (relation === assignableRelation || relation === comparableRelation) {
      if (s & 1 /* Any */) return true;
      if (s & 8 /* Number */ && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true;
      if (s & 256 /* NumberLiteral */ && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* 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 & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
        return true;
      }
    } else if (!((source.flags | target.flags) & (3145728 /* UnionOrIntersection */ | 8388608 /* IndexedAccess */ | 16777216 /* Conditional */ | 33554432 /* Substitution */))) {
      if (source.flags !== target.flags) return false;
      if (source.flags & 67358815 /* Singleton */) return true;
    }
    if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
      const related = relation.get(getRelationKey(
        source,
        target,
        0 /* None */,
        relation,
        /*ignoreConstraints*/
        false
      ));
      if (related !== void 0) {
        return !!(related & 1 /* Succeeded */);
      }
    }
    if (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */) {
      return checkTypeRelatedTo(
        source,
        target,
        relation,
        /*errorNode*/
        void 0
      );
    }
    return false;
  }
  function isIgnoredJsxProperty(source, sourceProp) {
    return getObjectFlags(source) & 2048 /* JsxAttributes */ && isHyphenatedJsxName(sourceProp.escapedName);
  }
  function getNormalizedType(type, writing) {
    while (true) {
      const t = isFreshLiteralType(type) ? type.regularType : isGenericTupleType(type) ? getNormalizedTupleType(type, writing) : getObjectFlags(type) & 4 /* Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : type.flags & 3145728 /* UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : getSubstitutionIntersection(type) : type.flags & 25165824 /* 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 & 2097152 /* 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 || (hasInstantiable = !!(t.flags & 465829888 /* Instantiable */));
      hasNullableOrEmpty || (hasNullableOrEmpty = !!(t.flags & 98304 /* 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 & 25165824 /* Simplifiable */ ? getSimplifiedType(t, writing) : t);
    return elements !== normalizedElements ? createNormalizedTupleType(type.target, normalizedElements) : type;
  }
  function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
    var _a;
    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, 2 /* Failed */ | (relationCount <= 0 ? 32 /* ComplexityOverflow */ : 64 /* StackDepthOverflow */));
      (_a = tracing) == null ? void 0 : _a.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 diag2 = error2(errorNode || currentNode, message, typeToString(source), typeToString(target));
      if (errorOutputContainer) {
        (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2);
      }
    } 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 diag3 = 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, diag3);
          }
        }
      }
      const diag2 = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorNode), errorNode, errorInfo, relatedInformation);
      if (relatedInfo) {
        addRelatedInfo(diag2, ...relatedInfo);
      }
      if (errorOutputContainer) {
        (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2);
      }
      if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
        diagnostics.add(diag2);
      }
    }
    if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
      Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
    }
    return result !== 0 /* 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 == null ? void 0 : incompatibleStack.slice(),
        overrideNextErrorInfo,
        skipParentCounter,
        relatedInfo: relatedInfo == null ? void 0 : relatedInfo.slice()
      };
    }
    function reportIncompatibleError(message, ...args) {
      overrideNextErrorInfo++;
      lastSkippedInfo = void 0;
      (incompatibleStack || (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 (!(target2.flags & 131072 /* Never */) && 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 & 8388608 /* IndexedAccess */ && !(source2.flags & 8388608 /* IndexedAccess */) ? target2.objectType.flags : target2.flags;
      if (targetFlags & 262144 /* 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 & 128 /* StringLiteral */ && target2.flags & 1048576 /* 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, reportErrors2) {
      if (isTupleType(source2)) {
        if (source2.target.readonly && isMutableArrayOrTuple(target2)) {
          if (reportErrors2) {
            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 (reportErrors2) {
          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, reportErrors2) {
      return isRelatedTo(source2, target2, 3 /* Both */, reportErrors2);
    }
    function isRelatedTo(originalSource, originalTarget, recursionFlags = 3 /* Both */, reportErrors2 = false, headMessage2, intersectionState = 0 /* None */) {
      if (originalSource === originalTarget) return -1 /* True */;
      if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 402784252 /* Primitive */) {
        if (relation === comparableRelation && !(originalTarget.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors2 ? reportError : void 0)) {
          return -1 /* True */;
        }
        if (reportErrors2) {
          reportErrorResults(originalSource, originalTarget, originalSource, originalTarget, headMessage2);
        }
        return 0 /* False */;
      }
      const source2 = getNormalizedType(
        originalSource,
        /*writing*/
        false
      );
      let target2 = getNormalizedType(
        originalTarget,
        /*writing*/
        true
      );
      if (source2 === target2) return -1 /* True */;
      if (relation === identityRelation) {
        if (source2.flags !== target2.flags) return 0 /* False */;
        if (source2.flags & 67358815 /* Singleton */) return -1 /* True */;
        traceUnionsOrIntersectionsTooLarge(source2, target2);
        return recursiveTypeRelatedTo(
          source2,
          target2,
          /*reportErrors*/
          false,
          0 /* None */,
          recursionFlags
        );
      }
      if (source2.flags & 262144 /* TypeParameter */ && getConstraintOfType(source2) === target2) {
        return -1 /* True */;
      }
      if (source2.flags & 470302716 /* DefinitelyNonNullable */ && target2.flags & 1048576 /* Union */) {
        const types = target2.types;
        const candidate = types.length === 2 && types[0].flags & 98304 /* Nullable */ ? types[1] : types.length === 3 && types[0].flags & 98304 /* Nullable */ && types[1].flags & 98304 /* Nullable */ ? types[2] : void 0;
        if (candidate && !(candidate.flags & 98304 /* Nullable */)) {
          target2 = getNormalizedType(
            candidate,
            /*writing*/
            true
          );
          if (source2 === target2) return -1 /* True */;
        }
      }
      if (relation === comparableRelation && !(target2.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target2, source2, relation) || isSimpleTypeRelatedTo(source2, target2, relation, reportErrors2 ? reportError : void 0)) return -1 /* True */;
      if (source2.flags & 469499904 /* StructuredOrInstantiable */ || target2.flags & 469499904 /* StructuredOrInstantiable */) {
        const isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType2(source2) && getObjectFlags(source2) & 8192 /* FreshLiteral */);
        if (isPerformingExcessPropertyChecks) {
          if (hasExcessProperties(source2, target2, reportErrors2)) {
            if (reportErrors2) {
              reportRelationError(headMessage2, source2, originalTarget.aliasSymbol ? originalTarget : target2);
            }
            return 0 /* False */;
          }
        }
        const isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source2)) && !(intersectionState & 2 /* Target */) && source2.flags & (402784252 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source2 !== globalObjectType && target2.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target2) && (getPropertiesOfType(source2).length > 0 || typeHasCallOrConstructSignatures(source2));
        const isComparingJsxAttributes = !!(getObjectFlags(source2) & 2048 /* JsxAttributes */);
        if (isPerformingCommonPropertyChecks && !hasCommonProperties(source2, target2, isComparingJsxAttributes)) {
          if (reportErrors2) {
            const sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source2);
            const targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target2);
            const calls = getSignaturesOfType(source2, 0 /* Call */);
            const constructs = getSignaturesOfType(source2, 1 /* 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 0 /* False */;
        }
        traceUnionsOrIntersectionsTooLarge(source2, target2);
        const skipCaching = source2.flags & 1048576 /* Union */ && source2.types.length < 4 && !(target2.flags & 1048576 /* Union */) || target2.flags & 1048576 /* Union */ && target2.types.length < 4 && !(source2.flags & 469499904 /* StructuredOrInstantiable */);
        const result2 = skipCaching ? unionOrIntersectionRelatedTo(source2, target2, reportErrors2, intersectionState) : recursiveTypeRelatedTo(source2, target2, reportErrors2, intersectionState, recursionFlags);
        if (result2) {
          return result2;
        }
      }
      if (reportErrors2) {
        reportErrorResults(originalSource, originalTarget, source2, target2, headMessage2);
      }
      return 0 /* False */;
    }
    function reportErrorResults(originalSource, originalTarget, source2, target2, headMessage2) {
      var _a2, _b;
      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 & 524288 /* Object */ && target2.flags & 524288 /* Object */) {
        const currentError = errorInfo;
        tryElaborateArrayLikeErrors(
          source2,
          target2,
          /*reportErrors*/
          true
        );
        if (errorInfo !== currentError) {
          maybeSuppress = !!errorInfo;
        }
      }
      if (source2.flags & 524288 /* Object */ && target2.flags & 402784252 /* Primitive */) {
        tryElaborateErrorsForPrimitivesAndObjects(source2, target2);
      } else if (source2.symbol && source2.flags & 524288 /* 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) & 2048 /* JsxAttributes */ && target2.flags & 2097152 /* 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 & 262144 /* TypeParameter */ && ((_b = (_a2 = source2.symbol) == null ? void 0 : _a2.declarations) == null ? void 0 : _b[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 & 3145728 /* UnionOrIntersection */ && target2.flags & 3145728 /* UnionOrIntersection */) {
        const sourceUnionOrIntersection = source2;
        const targetUnionOrIntersection = target2;
        if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 32768 /* 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 == null ? void 0 : errorNode.pos,
            end: errorNode == null ? void 0 : errorNode.end
          });
        }
      }
    }
    function getTypeOfPropertyInTypes(types, name) {
      const appendPropType = (propTypes, type) => {
        var _a2;
        type = getApparentType(type);
        const prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
        const propType = prop && getTypeOfSymbol(prop) || ((_a2 = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a2.type) || undefinedType;
        return append(propTypes, propType);
      };
      return getUnionType(reduceLeft(
        types,
        appendPropType,
        /*initial*/
        void 0
      ) || emptyArray);
    }
    function hasExcessProperties(source2, target2, reportErrors2) {
      var _a2;
      if (!isExcessPropertyCheckTarget(target2) || !noImplicitAny && getObjectFlags(target2) & 4096 /* JSLiteral */) {
        return false;
      }
      const isComparingJsxAttributes = !!(getObjectFlags(source2) & 2048 /* JsxAttributes */);
      if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target2) || !isComparingJsxAttributes && isEmptyObjectType(target2))) {
        return false;
      }
      let reducedTarget = target2;
      let checkTypes;
      if (target2.flags & 1048576 /* Union */) {
        reducedTarget = findMatchingDiscriminantType(source2, target2, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target2);
        checkTypes = reducedTarget.flags & 1048576 /* 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 (reportErrors2) {
              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 = ((_a2 = source2.symbol) == null ? void 0 : _a2.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 */, reportErrors2)) {
            if (reportErrors2) {
              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, reportErrors2, intersectionState) {
      if (source2.flags & 1048576 /* Union */) {
        if (target2.flags & 1048576 /* Union */) {
          const sourceOrigin = source2.origin;
          if (sourceOrigin && sourceOrigin.flags & 2097152 /* Intersection */ && target2.aliasSymbol && contains(sourceOrigin.types, target2)) {
            return -1 /* True */;
          }
          const targetOrigin = target2.origin;
          if (targetOrigin && targetOrigin.flags & 1048576 /* Union */ && source2.aliasSymbol && contains(targetOrigin.types, source2)) {
            return -1 /* True */;
          }
        }
        return relation === comparableRelation ? someTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */), intersectionState) : eachTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */), intersectionState);
      }
      if (target2.flags & 1048576 /* Union */) {
        return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source2), target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */) && !(target2.flags & 402784252 /* Primitive */), intersectionState);
      }
      if (target2.flags & 2097152 /* Intersection */) {
        return typeRelatedToEachType(source2, target2, reportErrors2, 2 /* Target */);
      }
      if (relation === comparableRelation && target2.flags & 402784252 /* Primitive */) {
        const constraints = sameMap(source2.types, (t) => t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(t) || unknownType : t);
        if (constraints !== source2.types) {
          source2 = getIntersectionType(constraints);
          if (source2.flags & 131072 /* Never */) {
            return 0 /* False */;
          }
          if (!(source2.flags & 2097152 /* 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 = -1 /* True */;
      const sourceTypes = source2.types;
      for (const sourceType of sourceTypes) {
        const related = typeRelatedToSomeType(
          sourceType,
          target2,
          /*reportErrors*/
          false,
          0 /* None */
        );
        if (!related) {
          return 0 /* False */;
        }
        result2 &= related;
      }
      return result2;
    }
    function typeRelatedToSomeType(source2, target2, reportErrors2, intersectionState) {
      const targetTypes = target2.types;
      if (target2.flags & 1048576 /* Union */) {
        if (containsType(targetTypes, source2)) {
          return -1 /* True */;
        }
        if (relation !== comparableRelation && getObjectFlags(target2) & 32768 /* PrimitiveUnion */ && !(source2.flags & 1024 /* EnumLiteral */) && (source2.flags & (128 /* StringLiteral */ | 512 /* BooleanLiteral */ | 2048 /* BigIntLiteral */) || (relation === subtypeRelation || relation === strictSubtypeRelation) && source2.flags & 256 /* NumberLiteral */)) {
          const alternateForm = source2 === source2.regularType ? source2.freshType : source2.regularType;
          const primitive = source2.flags & 128 /* StringLiteral */ ? stringType : source2.flags & 256 /* NumberLiteral */ ? numberType : source2.flags & 2048 /* BigIntLiteral */ ? bigintType : void 0;
          return primitive && containsType(targetTypes, primitive) || alternateForm && containsType(targetTypes, alternateForm) ? -1 /* True */ : 0 /* 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 (reportErrors2) {
        const bestMatchingType = getBestMatchingType(source2, target2, isRelatedTo);
        if (bestMatchingType) {
          isRelatedTo(
            source2,
            bestMatchingType,
            2 /* Target */,
            /*reportErrors*/
            true,
            /*headMessage*/
            void 0,
            intersectionState
          );
        }
      }
      return 0 /* False */;
    }
    function typeRelatedToEachType(source2, target2, reportErrors2, intersectionState) {
      let result2 = -1 /* True */;
      const targetTypes = target2.types;
      for (const targetType of targetTypes) {
        const related = isRelatedTo(
          source2,
          targetType,
          2 /* Target */,
          reportErrors2,
          /*headMessage*/
          void 0,
          intersectionState
        );
        if (!related) {
          return 0 /* False */;
        }
        result2 &= related;
      }
      return result2;
    }
    function someTypeRelatedToType(source2, target2, reportErrors2, intersectionState) {
      const sourceTypes = source2.types;
      if (source2.flags & 1048576 /* Union */ && containsType(sourceTypes, target2)) {
        return -1 /* True */;
      }
      const len = sourceTypes.length;
      for (let i = 0; i < len; i++) {
        const related = isRelatedTo(
          sourceTypes[i],
          target2,
          1 /* Source */,
          reportErrors2 && i === len - 1,
          /*headMessage*/
          void 0,
          intersectionState
        );
        if (related) {
          return related;
        }
      }
      return 0 /* False */;
    }
    function getUndefinedStrippedTargetIfNeeded(source2, target2) {
      if (source2.flags & 1048576 /* Union */ && target2.flags & 1048576 /* Union */ && !(source2.types[0].flags & 32768 /* Undefined */) && target2.types[0].flags & 32768 /* Undefined */) {
        return extractTypesOfKind(target2, ~32768 /* Undefined */);
      }
      return target2;
    }
    function eachTypeRelatedToType(source2, target2, reportErrors2, intersectionState) {
      let result2 = -1 /* 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 & 1048576 /* 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 */,
          reportErrors2,
          /*headMessage*/
          void 0,
          intersectionState
        );
        if (!related) {
          return 0 /* False */;
        }
        result2 &= related;
      }
      return result2;
    }
    function typeArgumentsRelatedTo(sources = emptyArray, targets = emptyArray, variances = emptyArray, reportErrors2, intersectionState) {
      if (sources.length !== targets.length && relation === identityRelation) {
        return 0 /* False */;
      }
      const length2 = sources.length <= targets.length ? sources.length : targets.length;
      let result2 = -1 /* True */;
      for (let i = 0; i < length2; i++) {
        const varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
        const variance = varianceFlags & 7 /* VarianceMask */;
        if (variance !== 4 /* Independent */) {
          const s = sources[i];
          const t = targets[i];
          let related = -1 /* True */;
          if (varianceFlags & 8 /* Unmeasurable */) {
            related = relation === identityRelation ? isRelatedTo(
              s,
              t,
              3 /* Both */,
              /*reportErrors*/
              false
            ) : compareTypesIdentical(s, t);
          } else if (variance === 1 /* Covariant */) {
            related = isRelatedTo(
              s,
              t,
              3 /* Both */,
              reportErrors2,
              /*headMessage*/
              void 0,
              intersectionState
            );
          } else if (variance === 2 /* Contravariant */) {
            related = isRelatedTo(
              t,
              s,
              3 /* Both */,
              reportErrors2,
              /*headMessage*/
              void 0,
              intersectionState
            );
          } else if (variance === 3 /* Bivariant */) {
            related = isRelatedTo(
              t,
              s,
              3 /* Both */,
              /*reportErrors*/
              false
            );
            if (!related) {
              related = isRelatedTo(
                s,
                t,
                3 /* Both */,
                reportErrors2,
                /*headMessage*/
                void 0,
                intersectionState
              );
            }
          } else {
            related = isRelatedTo(
              s,
              t,
              3 /* Both */,
              reportErrors2,
              /*headMessage*/
              void 0,
              intersectionState
            );
            if (related) {
              related &= isRelatedTo(
                t,
                s,
                3 /* Both */,
                reportErrors2,
                /*headMessage*/
                void 0,
                intersectionState
              );
            }
          }
          if (!related) {
            return 0 /* False */;
          }
          result2 &= related;
        }
      }
      return result2;
    }
    function recursiveTypeRelatedTo(source2, target2, reportErrors2, intersectionState, recursionFlags) {
      var _a2, _b, _c;
      if (overflow) {
        return 0 /* False */;
      }
      const id = getRelationKey(
        source2,
        target2,
        intersectionState,
        relation,
        /*ignoreConstraints*/
        false
      );
      const entry = relation.get(id);
      if (entry !== void 0) {
        if (reportErrors2 && entry & 2 /* Failed */ && !(entry & 96 /* Overflow */)) {
        } else {
          if (outofbandVarianceMarkerHandler) {
            const saved = entry & 24 /* ReportsMask */;
            if (saved & 8 /* ReportsUnmeasurable */) {
              instantiateType(source2, reportUnmeasurableMapper);
            }
            if (saved & 16 /* ReportsUnreliable */) {
              instantiateType(source2, reportUnreliableMapper);
            }
          }
          if (reportErrors2 && entry & 96 /* Overflow */) {
            const message = entry & 32 /* 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 & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
        }
      }
      if (relationCount <= 0) {
        overflow = true;
        return 0 /* False */;
      }
      if (!maybeKeys) {
        maybeKeys = [];
        maybeKeysSet = /* @__PURE__ */ new Set();
        sourceStack = [];
        targetStack = [];
      } else {
        if (maybeKeysSet.has(id)) {
          return 3 /* Maybe */;
        }
        const broadestEquivalentId = id.startsWith("*") ? getRelationKey(
          source2,
          target2,
          intersectionState,
          relation,
          /*ignoreConstraints*/
          true
        ) : void 0;
        if (broadestEquivalentId && maybeKeysSet.has(broadestEquivalentId)) {
          return 3 /* Maybe */;
        }
        if (sourceDepth === 100 || targetDepth === 100) {
          overflow = true;
          return 0 /* 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 ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
          return originalHandler(onlyUnreliable);
        };
      }
      let result2;
      if (expandingFlags === 3 /* Both */) {
        (_a2 = tracing) == null ? void 0 : _a2.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 = 3 /* Maybe */;
      } else {
        (_b = tracing) == null ? void 0 : _b.push(tracing.Phase.CheckTypes, "structuredTypeRelatedTo", { sourceId: source2.id, targetId: target2.id });
        result2 = structuredTypeRelatedTo(source2, target2, reportErrors2, intersectionState);
        (_c = tracing) == null ? void 0 : _c.pop();
      }
      if (outofbandVarianceMarkerHandler) {
        outofbandVarianceMarkerHandler = originalHandler;
      }
      if (recursionFlags & 1 /* Source */) {
        sourceDepth--;
      }
      if (recursionFlags & 2 /* Target */) {
        targetDepth--;
      }
      expandingFlags = saveExpandingFlags;
      if (result2) {
        if (result2 === -1 /* True */ || sourceDepth === 0 && targetDepth === 0) {
          if (result2 === -1 /* True */ || result2 === 3 /* Maybe */) {
            resetMaybeStack(
              /*markAllAsSucceeded*/
              true
            );
          } else {
            resetMaybeStack(
              /*markAllAsSucceeded*/
              false
            );
          }
        }
      } else {
        relation.set(id, 2 /* 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], 1 /* Succeeded */ | propagatingVarianceFlags);
            relationCount--;
          }
        }
        maybeCount = maybeStart;
      }
    }
    function structuredTypeRelatedTo(source2, target2, reportErrors2, intersectionState) {
      const saveErrorInfo = captureErrorCalculationState();
      let result2 = structuredTypeRelatedToWorker(source2, target2, reportErrors2, intersectionState, saveErrorInfo);
      if (relation !== identityRelation) {
        if (!result2 && (source2.flags & 2097152 /* Intersection */ || source2.flags & 262144 /* TypeParameter */ && target2.flags & 1048576 /* Union */)) {
          const constraint = getEffectiveConstraintOfIntersection(source2.flags & 2097152 /* Intersection */ ? source2.types : [source2], !!(target2.flags & 1048576 /* 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 & 2097152 /* Intersection */ && !isGenericObjectType(target2) && source2.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
          result2 &= propertiesRelatedTo(
            source2,
            target2,
            reportErrors2,
            /*excludedProperties*/
            void 0,
            /*optionalsOnly*/
            false,
            0 /* None */
          );
          if (result2 && isObjectLiteralType2(source2) && getObjectFlags(source2) & 8192 /* FreshLiteral */) {
            result2 &= indexSignaturesRelatedTo(
              source2,
              target2,
              /*sourceIsPrimitive*/
              false,
              reportErrors2,
              0 /* None */
            );
          }
        } else if (result2 && isNonGenericObjectType(target2) && !isArrayOrTupleType(target2) && source2.flags & 2097152 /* Intersection */ && getApparentType(source2).flags & 3670016 /* StructuredType */ && !some(source2.types, (t) => t === target2 || !!(getObjectFlags(t) & 262144 /* NonInferrableType */))) {
          result2 &= propertiesRelatedTo(
            source2,
            target2,
            reportErrors2,
            /*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,
        8576 /* StringOrNumberLiteralOrUnique */,
        /*stringsOnly*/
        false,
        (t) => void mappedKeys.push(instantiateType(nameType, appendTypeMapping(targetType.mapper, getTypeParameterFromMappedType(targetType), t)))
      );
      return getUnionType(mappedKeys);
    }
    function structuredTypeRelatedToWorker(source2, target2, reportErrors2, intersectionState, saveErrorInfo) {
      let result2;
      let originalErrorInfo;
      let varianceCheckFailed = false;
      let sourceFlags = source2.flags;
      const targetFlags = target2.flags;
      if (relation === identityRelation) {
        if (sourceFlags & 3145728 /* UnionOrIntersection */) {
          let result3 = eachTypeRelatedToSomeType(source2, target2);
          if (result3) {
            result3 &= eachTypeRelatedToSomeType(target2, source2);
          }
          return result3;
        }
        if (sourceFlags & 4194304 /* Index */) {
          return isRelatedTo(
            source2.type,
            target2.type,
            3 /* Both */,
            /*reportErrors*/
            false
          );
        }
        if (sourceFlags & 8388608 /* 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 & 16777216 /* 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 & 33554432 /* 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 & 524288 /* Object */)) {
          return 0 /* False */;
        }
      } else if (sourceFlags & 3145728 /* UnionOrIntersection */ || targetFlags & 3145728 /* UnionOrIntersection */) {
        if (result2 = unionOrIntersectionRelatedTo(source2, target2, reportErrors2, intersectionState)) {
          return result2;
        }
        if (!(sourceFlags & 465829888 /* Instantiable */ || sourceFlags & 524288 /* Object */ && targetFlags & 1048576 /* Union */ || sourceFlags & 2097152 /* Intersection */ && targetFlags & (524288 /* Object */ | 1048576 /* Union */ | 465829888 /* Instantiable */))) {
          return 0 /* False */;
        }
      }
      if (sourceFlags & (524288 /* Object */ | 16777216 /* Conditional */) && source2.aliasSymbol && source2.aliasTypeArguments && source2.aliasSymbol === target2.aliasSymbol && !(isMarkerType(source2) || isMarkerType(target2))) {
        const variances = getAliasVariances(source2.aliasSymbol);
        if (variances === emptyArray) {
          return 1 /* 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 & 262144 /* TypeParameter */) {
        if (getObjectFlags(source2) & 32 /* 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 */, reportErrors2)) {
              return result2;
            }
          }
        }
        if (relation === comparableRelation && sourceFlags & 262144 /* TypeParameter */) {
          let constraint = getConstraintOfTypeParameter(source2);
          if (constraint) {
            while (constraint && someType(constraint, (c) => !!(c.flags & 262144 /* TypeParameter */))) {
              if (result2 = isRelatedTo(
                constraint,
                target2,
                1 /* Source */,
                /*reportErrors*/
                false
              )) {
                return result2;
              }
              constraint = getConstraintOfTypeParameter(constraint);
            }
          }
          return 0 /* False */;
        }
      } else if (targetFlags & 4194304 /* Index */) {
        const targetType = target2.type;
        if (sourceFlags & 4194304 /* Index */) {
          if (result2 = isRelatedTo(
            targetType,
            source2.type,
            3 /* Both */,
            /*reportErrors*/
            false
          )) {
            return result2;
          }
        }
        if (isTupleType(targetType)) {
          if (result2 = isRelatedTo(source2, getKnownKeysOfTupleType(targetType), 2 /* Target */, reportErrors2)) {
            return result2;
          }
        } else {
          const constraint = getSimplifiedTypeOrConstraint(targetType);
          if (constraint) {
            if (isRelatedTo(source2, getIndexType(constraint, target2.indexFlags | 4 /* NoReducibleCheck */), 2 /* Target */, reportErrors2) === -1 /* True */) {
              return -1 /* 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 */, reportErrors2) === -1 /* True */) {
              return -1 /* True */;
            }
          }
        }
      } else if (targetFlags & 8388608 /* IndexedAccess */) {
        if (sourceFlags & 8388608 /* IndexedAccess */) {
          if (result2 = isRelatedTo(source2.objectType, target2.objectType, 3 /* Both */, reportErrors2)) {
            result2 &= isRelatedTo(source2.indexType, target2.indexType, 3 /* Both */, reportErrors2);
          }
          if (result2) {
            return result2;
          }
          if (reportErrors2) {
            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 = 4 /* Writing */ | (baseObjectType !== objectType ? 2 /* NoIndexSignatures */ : 0);
            const constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, accessFlags);
            if (constraint) {
              if (reportErrors2 && originalErrorInfo) {
                resetErrorInfo(saveErrorInfo);
              }
              if (result2 = isRelatedTo(
                source2,
                constraint,
                2 /* Target */,
                reportErrors2,
                /*headMessage*/
                void 0,
                intersectionState
              )) {
                return result2;
              }
              if (reportErrors2 && originalErrorInfo && errorInfo) {
                errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo;
              }
            }
          }
        }
        if (reportErrors2) {
          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 & 8388608 /* IndexedAccess */ && templateType.objectType === source2 && templateType.indexType === getTypeParameterFromMappedType(target2)) {
            return -1 /* True */;
          }
          if (!isGenericMappedType(source2)) {
            const targetKeys = keysRemapped ? getNameTypeFromMappedType(target2) : getConstraintTypeFromMappedType(target2);
            const sourceKeys = getIndexType(source2, 2 /* NoIndexSignatures */);
            const includeOptional = modifiers & 4 /* IncludeOptional */;
            const filteredByApplicability = includeOptional ? intersectTypes(targetKeys, sourceKeys) : void 0;
            if (includeOptional ? !(filteredByApplicability.flags & 131072 /* Never */) : isRelatedTo(targetKeys, sourceKeys, 3 /* Both */)) {
              const templateType2 = getTemplateTypeFromMappedType(target2);
              const typeParameter = getTypeParameterFromMappedType(target2);
              const nonNullComponent = extractTypesOfKind(templateType2, ~98304 /* Nullable */);
              if (!keysRemapped && nonNullComponent.flags & 8388608 /* IndexedAccess */ && nonNullComponent.indexType === typeParameter) {
                if (result2 = isRelatedTo(source2, nonNullComponent.objectType, 2 /* Target */, reportErrors2)) {
                  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 */, reportErrors2)) {
                  return result2;
                }
              }
            }
            originalErrorInfo = errorInfo;
            resetErrorInfo(saveErrorInfo);
          }
        }
      } else if (targetFlags & 16777216 /* Conditional */) {
        if (isDeeplyNestedType(target2, targetStack, targetDepth, 10)) {
          return 3 /* Maybe */;
        }
        const c = target2;
        if (!c.root.inferTypeParameters && !isDistributionDependent(c.root) && !(source2.flags & 16777216 /* 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 ? -1 /* True */ : isRelatedTo(
            source2,
            getTrueTypeFromConditionalType(c),
            2 /* Target */,
            /*reportErrors*/
            false,
            /*headMessage*/
            void 0,
            intersectionState
          )) {
            result2 &= skipFalse ? -1 /* True */ : isRelatedTo(
              source2,
              getFalseTypeFromConditionalType(c),
              2 /* Target */,
              /*reportErrors*/
              false,
              /*headMessage*/
              void 0,
              intersectionState
            );
            if (result2) {
              return result2;
            }
          }
        }
      } else if (targetFlags & 134217728 /* TemplateLiteral */) {
        if (sourceFlags & 134217728 /* TemplateLiteral */) {
          if (relation === comparableRelation) {
            return templateLiteralTypesDefinitelyUnrelated(source2, target2) ? 0 /* False */ : -1 /* True */;
          }
          instantiateType(source2, reportUnreliableMapper);
        }
        if (isTypeMatchedByTemplateLiteralType(source2, target2)) {
          return -1 /* True */;
        }
      } else if (target2.flags & 268435456 /* StringMapping */) {
        if (!(source2.flags & 268435456 /* StringMapping */)) {
          if (isMemberOfStringMapping(source2, target2)) {
            return -1 /* True */;
          }
        }
      }
      if (sourceFlags & 8650752 /* TypeVariable */) {
        if (!(sourceFlags & 8388608 /* IndexedAccess */ && targetFlags & 8388608 /* 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 */,
            reportErrors2 && constraint !== unknownType && !(targetFlags & sourceFlags & 262144 /* 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 */, reportErrors2)) {
                return result2;
              }
            }
          }
        }
      } else if (sourceFlags & 4194304 /* Index */) {
        const isDeferredMappedIndex = shouldDeferIndexType(source2.type, source2.indexFlags) && getObjectFlags(source2.type) & 32 /* Mapped */;
        if (result2 = isRelatedTo(stringNumberSymbolType, target2, 1 /* Source */, reportErrors2 && !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 */, reportErrors2)) {
            return result2;
          }
        }
      } else if (sourceFlags & 134217728 /* TemplateLiteral */ && !(targetFlags & 524288 /* Object */)) {
        if (!(targetFlags & 134217728 /* TemplateLiteral */)) {
          const constraint = getBaseConstraintOfType(source2);
          if (constraint && constraint !== source2 && (result2 = isRelatedTo(constraint, target2, 1 /* Source */, reportErrors2))) {
            return result2;
          }
        }
      } else if (sourceFlags & 268435456 /* StringMapping */) {
        if (targetFlags & 268435456 /* StringMapping */) {
          if (source2.symbol !== target2.symbol) {
            return 0 /* False */;
          }
          if (result2 = isRelatedTo(source2.type, target2.type, 3 /* Both */, reportErrors2)) {
            return result2;
          }
        } else {
          const constraint = getBaseConstraintOfType(source2);
          if (constraint && (result2 = isRelatedTo(constraint, target2, 1 /* Source */, reportErrors2))) {
            return result2;
          }
        }
      } else if (sourceFlags & 16777216 /* Conditional */) {
        if (isDeeplyNestedType(source2, sourceStack, sourceDepth, 10)) {
          return 3 /* Maybe */;
        }
        if (targetFlags & 16777216 /* Conditional */) {
          const sourceParams = source2.root.inferTypeParameters;
          let sourceExtends = source2.extendsType;
          let mapper;
          if (sourceParams) {
            const ctx = createInferenceContext(
              sourceParams,
              /*signature*/
              void 0,
              0 /* None */,
              isRelatedToWorker
            );
            inferTypes(ctx.inferences, target2.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* 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 */, reportErrors2)) {
              result2 &= isRelatedTo(getFalseTypeFromConditionalType(source2), getFalseTypeFromConditionalType(target2), 3 /* Both */, reportErrors2);
            }
            if (result2) {
              return result2;
            }
          }
        }
        const defaultConstraint = getDefaultConstraintOfConditionalType(source2);
        if (defaultConstraint) {
          if (result2 = isRelatedTo(defaultConstraint, target2, 1 /* Source */, reportErrors2)) {
            return result2;
          }
        }
        const distributiveConstraint = !(targetFlags & 16777216 /* Conditional */) && hasNonCircularBaseConstraint(source2) ? getConstraintOfDistributiveConditionalType(source2) : void 0;
        if (distributiveConstraint) {
          resetErrorInfo(saveErrorInfo);
          if (result2 = isRelatedTo(distributiveConstraint, target2, 1 /* Source */, reportErrors2)) {
            return result2;
          }
        }
      } else {
        if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target2) && isEmptyObjectType(source2)) {
          return -1 /* True */;
        }
        if (isGenericMappedType(target2)) {
          if (isGenericMappedType(source2)) {
            if (result2 = mappedTypeRelatedTo(source2, target2, reportErrors2)) {
              return result2;
            }
          }
          return 0 /* False */;
        }
        const sourceIsPrimitive = !!(sourceFlags & 402784252 /* Primitive */);
        if (relation !== identityRelation) {
          source2 = getApparentType(source2);
          sourceFlags = source2.flags;
        } else if (isGenericMappedType(source2)) {
          return 0 /* False */;
        }
        if (getObjectFlags(source2) & 4 /* Reference */ && getObjectFlags(target2) & 4 /* Reference */ && source2.target === target2.target && !isTupleType(source2) && !(isMarkerType(source2) || isMarkerType(target2))) {
          if (isEmptyArrayLiteralType(source2)) {
            return -1 /* True */;
          }
          const variances = getVariances(source2.target);
          if (variances === emptyArray) {
            return 1 /* 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 */, reportErrors2);
          } else {
            return 0 /* False */;
          }
        } else if (isGenericTupleType(source2) && isTupleType(target2) && !isGenericTupleType(target2)) {
          const constraint = getBaseConstraintOrType(source2);
          if (constraint !== source2) {
            return isRelatedTo(constraint, target2, 1 /* Source */, reportErrors2);
          }
        } else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target2) && getObjectFlags(target2) & 8192 /* FreshLiteral */ && !isEmptyObjectType(source2)) {
          return 0 /* False */;
        }
        if (sourceFlags & (524288 /* Object */ | 2097152 /* Intersection */) && targetFlags & 524288 /* Object */) {
          const reportStructuralErrors = reportErrors2 && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
          result2 = propertiesRelatedTo(
            source2,
            target2,
            reportStructuralErrors,
            /*excludedProperties*/
            void 0,
            /*optionalsOnly*/
            false,
            intersectionState
          );
          if (result2) {
            result2 &= signaturesRelatedTo(source2, target2, 0 /* Call */, reportStructuralErrors, intersectionState);
            if (result2) {
              result2 &= signaturesRelatedTo(source2, target2, 1 /* 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 & (524288 /* Object */ | 2097152 /* Intersection */) && targetFlags & 1048576 /* Union */) {
          const objectOnlyTarget = extractTypesOfKind(target2, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
          if (objectOnlyTarget.flags & 1048576 /* Union */) {
            const result3 = typeRelatedToDiscriminatedType(source2, objectOnlyTarget);
            if (result3) {
              return result3;
            }
          }
        }
      }
      return 0 /* 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, reportErrors2, intersectionState2)) {
          return result2;
        }
        if (some(variances, (v) => !!(v & 24 /* AllowsStructuralFallback */))) {
          originalErrorInfo = void 0;
          resetErrorInfo(saveErrorInfo);
          return void 0;
        }
        const allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
        varianceCheckFailed = !allowStructuralFallback;
        if (variances !== emptyArray && !allowStructuralFallback) {
          if (varianceCheckFailed && !(reportErrors2 && some(variances, (v) => (v & 7 /* VarianceMask */) === 0 /* Invariant */))) {
            return 0 /* False */;
          }
          originalErrorInfo = errorInfo;
          resetErrorInfo(saveErrorInfo);
        }
      }
    }
    function mappedTypeRelatedTo(source2, target2, reportErrors2) {
      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 */, reportErrors2)) {
          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 */, reportErrors2);
          }
        }
      }
      return 0 /* False */;
    }
    function typeRelatedToDiscriminatedType(source2, target2) {
      var _a2;
      const sourceProperties = getPropertiesOfType(source2);
      const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target2);
      if (!sourcePropertiesFiltered) return 0 /* False */;
      let numCombinations = 1;
      for (const sourceProperty of sourcePropertiesFiltered) {
        numCombinations *= countTypes(getNonMissingTypeOfSymbol(sourceProperty));
        if (numCombinations > 25) {
          (_a2 = tracing) == null ? void 0 : _a2.instant(tracing.Phase.CheckTypes, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source2.id, targetId: target2.id, numCombinations });
          return 0 /* 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 & 1048576 /* 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 0 /* False */;
        }
      }
      let result2 = -1 /* True */;
      for (const type of matchingTypes) {
        result2 &= propertiesRelatedTo(
          source2,
          type,
          /*reportErrors*/
          false,
          excludedProperties,
          /*optionalsOnly*/
          false,
          0 /* None */
        );
        if (result2) {
          result2 &= signaturesRelatedTo(
            source2,
            type,
            0 /* Call */,
            /*reportErrors*/
            false,
            0 /* None */
          );
          if (result2) {
            result2 &= signaturesRelatedTo(
              source2,
              type,
              1 /* 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, reportErrors2, intersectionState) {
      const targetIsOptional = strictNullChecks && !!(getCheckFlags(targetProp) & 48 /* Partial */);
      const effectiveTarget = addOptionality(
        getNonMissingTypeOfSymbol(targetProp),
        /*isProperty*/
        false,
        targetIsOptional
      );
      const effectiveSource = getTypeOfSourceProperty(sourceProp);
      return isRelatedTo(
        effectiveSource,
        effectiveTarget,
        3 /* Both */,
        reportErrors2,
        /*headMessage*/
        void 0,
        intersectionState
      );
    }
    function propertyRelatedTo(source2, target2, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors2, intersectionState, skipOptional) {
      const sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp);
      const targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp);
      if (sourcePropFlags & 2 /* Private */ || targetPropFlags & 2 /* Private */) {
        if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
          if (reportErrors2) {
            if (sourcePropFlags & 2 /* Private */ && targetPropFlags & 2 /* 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 & 2 /* Private */ ? source2 : target2), typeToString(sourcePropFlags & 2 /* Private */ ? target2 : source2));
            }
          }
          return 0 /* False */;
        }
      } else if (targetPropFlags & 4 /* Protected */) {
        if (!isValidOverrideOf(sourceProp, targetProp)) {
          if (reportErrors2) {
            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 0 /* False */;
        }
      } else if (sourcePropFlags & 4 /* Protected */) {
        if (reportErrors2) {
          reportError(Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source2), typeToString(target2));
        }
        return 0 /* False */;
      }
      if (relation === strictSubtypeRelation && isReadonlySymbol(sourceProp) && !isReadonlySymbol(targetProp)) {
        return 0 /* False */;
      }
      const related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors2, intersectionState);
      if (!related) {
        if (reportErrors2) {
          reportIncompatibleError(Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
        }
        return 0 /* False */;
      }
      if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && targetProp.flags & 106500 /* ClassMember */ && !(targetProp.flags & 16777216 /* Optional */)) {
        if (reportErrors2) {
          reportError(Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source2), typeToString(target2));
        }
        return 0 /* 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 & 32 /* 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,
          0 /* None */,
          4 /* AllowAnyNodeKind */ | 16 /* 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, reportErrors2, excludedProperties, optionalsOnly, intersectionState) {
      if (relation === identityRelation) {
        return propertiesIdenticalTo(source2, target2, excludedProperties);
      }
      let result2 = -1 /* True */;
      if (isTupleType(target2)) {
        if (isArrayOrTupleType(source2)) {
          if (!target2.target.readonly && (isReadonlyArrayType(source2) || isTupleType(source2) && source2.target.readonly)) {
            return 0 /* False */;
          }
          const sourceArity = getTypeReferenceArity(source2);
          const targetArity = getTypeReferenceArity(target2);
          const sourceRestFlag = isTupleType(source2) ? source2.target.combinedFlags & 4 /* Rest */ : 4 /* Rest */;
          const targetHasRestElement = !!(target2.target.combinedFlags & 12 /* Variable */);
          const sourceMinLength = isTupleType(source2) ? source2.target.minLength : 0;
          const targetMinLength = target2.target.minLength;
          if (!sourceRestFlag && sourceArity < targetMinLength) {
            if (reportErrors2) {
              reportError(Diagnostics.Source_has_0_element_s_but_target_requires_1, sourceArity, targetMinLength);
            }
            return 0 /* False */;
          }
          if (!targetHasRestElement && targetArity < sourceMinLength) {
            if (reportErrors2) {
              reportError(Diagnostics.Source_has_0_element_s_but_target_allows_only_1, sourceMinLength, targetArity);
            }
            return 0 /* False */;
          }
          if (!targetHasRestElement && (sourceRestFlag || targetArity < sourceArity)) {
            if (reportErrors2) {
              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 0 /* False */;
          }
          const sourceTypeArguments = getTypeArguments(source2);
          const targetTypeArguments = getTypeArguments(target2);
          const targetStartCount = getStartElementCount(target2.target, 11 /* NonRest */);
          const targetEndCount = getEndElementCount(target2.target, 11 /* NonRest */);
          let canExcludeDiscriminants = !!excludedProperties;
          for (let sourcePosition = 0; sourcePosition < sourceArity; sourcePosition++) {
            const sourceFlags = isTupleType(source2) ? source2.target.elementFlags[sourcePosition] : 4 /* 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 & 8 /* Variadic */ && !(sourceFlags & 8 /* Variadic */)) {
              if (reportErrors2) {
                reportError(Diagnostics.Source_provides_no_match_for_variadic_element_at_position_0_in_target, targetPosition);
              }
              return 0 /* False */;
            }
            if (sourceFlags & 8 /* Variadic */ && !(targetFlags & 12 /* Variable */)) {
              if (reportErrors2) {
                reportError(Diagnostics.Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target, sourcePosition, targetPosition);
              }
              return 0 /* False */;
            }
            if (targetFlags & 1 /* Required */ && !(sourceFlags & 1 /* Required */)) {
              if (reportErrors2) {
                reportError(Diagnostics.Source_provides_no_match_for_required_element_at_position_0_in_target, targetPosition);
              }
              return 0 /* False */;
            }
            if (canExcludeDiscriminants) {
              if (sourceFlags & 12 /* Variable */ || targetFlags & 12 /* Variable */) {
                canExcludeDiscriminants = false;
              }
              if (canExcludeDiscriminants && (excludedProperties == null ? void 0 : excludedProperties.has("" + sourcePosition))) {
                continue;
              }
            }
            const sourceType = removeMissingType(sourceTypeArguments[sourcePosition], !!(sourceFlags & targetFlags & 2 /* Optional */));
            const targetType = targetTypeArguments[targetPosition];
            const targetCheckType = sourceFlags & 8 /* Variadic */ && targetFlags & 4 /* Rest */ ? createArrayType(targetType) : removeMissingType(targetType, !!(targetFlags & 2 /* Optional */));
            const related = isRelatedTo(
              sourceType,
              targetCheckType,
              3 /* Both */,
              reportErrors2,
              /*headMessage*/
              void 0,
              intersectionState
            );
            if (!related) {
              if (reportErrors2 && (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 0 /* False */;
            }
            result2 &= related;
          }
          return result2;
        }
        if (target2.target.combinedFlags & 12 /* Variable */) {
          return 0 /* False */;
        }
      }
      const requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType2(source2) && !isEmptyArrayLiteralType(source2) && !isTupleType(source2);
      const unmatchedProperty = getUnmatchedProperty(
        source2,
        target2,
        requireOptionalProperties,
        /*matchDiscriminantProperties*/
        false
      );
      if (unmatchedProperty) {
        if (reportErrors2 && shouldReportUnmatchedPropertyError(source2, target2)) {
          reportUnmatchedProperty(source2, target2, unmatchedProperty, requireOptionalProperties);
        }
        return 0 /* False */;
      }
      if (isObjectLiteralType2(target2)) {
        for (const sourceProp of excludeProperties(getPropertiesOfType(source2), excludedProperties)) {
          if (!getPropertyOfObjectType(target2, sourceProp.escapedName)) {
            const sourceType = getTypeOfSymbol(sourceProp);
            if (!(sourceType.flags & 32768 /* Undefined */)) {
              if (reportErrors2) {
                reportError(Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target2));
              }
              return 0 /* 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 & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length") && (!optionalsOnly || targetProp.flags & 16777216 /* Optional */)) {
          const sourceProp = getPropertyOfType(source2, name);
          if (sourceProp && sourceProp !== targetProp) {
            const related = propertyRelatedTo(source2, target2, sourceProp, targetProp, getNonMissingTypeOfSymbol, reportErrors2, intersectionState, relation === comparableRelation);
            if (!related) {
              return 0 /* False */;
            }
            result2 &= related;
          }
        }
      }
      return result2;
    }
    function propertiesIdenticalTo(source2, target2, excludedProperties) {
      if (!(source2.flags & 524288 /* Object */ && target2.flags & 524288 /* Object */)) {
        return 0 /* False */;
      }
      const sourceProperties = excludeProperties(getPropertiesOfObjectType(source2), excludedProperties);
      const targetProperties = excludeProperties(getPropertiesOfObjectType(target2), excludedProperties);
      if (sourceProperties.length !== targetProperties.length) {
        return 0 /* False */;
      }
      let result2 = -1 /* True */;
      for (const sourceProp of sourceProperties) {
        const targetProp = getPropertyOfObjectType(target2, sourceProp.escapedName);
        if (!targetProp) {
          return 0 /* False */;
        }
        const related = compareProperties2(sourceProp, targetProp, isRelatedTo);
        if (!related) {
          return 0 /* False */;
        }
        result2 &= related;
      }
      return result2;
    }
    function signaturesRelatedTo(source2, target2, kind, reportErrors2, intersectionState) {
      var _a2, _b;
      if (relation === identityRelation) {
        return signaturesIdenticalTo(source2, target2, kind);
      }
      if (target2 === anyFunctionType || source2 === anyFunctionType) {
        return -1 /* True */;
      }
      const sourceIsJSConstructor = source2.symbol && isJSConstructor(source2.symbol.valueDeclaration);
      const targetIsJSConstructor = target2.symbol && isJSConstructor(target2.symbol.valueDeclaration);
      const sourceSignatures = getSignaturesOfType(
        source2,
        sourceIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind
      );
      const targetSignatures = getSignaturesOfType(
        target2,
        targetIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind
      );
      if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
        const sourceIsAbstract = !!(sourceSignatures[0].flags & 4 /* Abstract */);
        const targetIsAbstract = !!(targetSignatures[0].flags & 4 /* Abstract */);
        if (sourceIsAbstract && !targetIsAbstract) {
          if (reportErrors2) {
            reportError(Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
          }
          return 0 /* False */;
        }
        if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors2)) {
          return 0 /* False */;
        }
      }
      let result2 = -1 /* True */;
      const incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
      const sourceObjectFlags = getObjectFlags(source2);
      const targetObjectFlags = getObjectFlags(target2);
      if (sourceObjectFlags & 64 /* Instantiated */ && targetObjectFlags & 64 /* Instantiated */ && source2.symbol === target2.symbol || sourceObjectFlags & 4 /* Reference */ && targetObjectFlags & 4 /* 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,
            reportErrors2,
            intersectionState,
            incompatibleReporter(sourceSignatures[i], targetSignatures[i])
          );
          if (!related) {
            return 0 /* 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, reportErrors2, intersectionState, incompatibleReporter(sourceSignature, targetSignature));
        if (!result2 && reportErrors2 && kind === 1 /* Construct */ && sourceObjectFlags & targetObjectFlags && (((_a2 = targetSignature.declaration) == null ? void 0 : _a2.kind) === 176 /* Constructor */ || ((_b = sourceSignature.declaration) == null ? void 0 : _b.kind) === 176 /* Constructor */)) {
          const constructSignatureToString = (signature) => signatureToString(
            signature,
            /*enclosingDeclaration*/
            void 0,
            262144 /* 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 = reportErrors2;
            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 0 /* False */;
          }
      }
      return result2;
    }
    function shouldReportUnmatchedPropertyError(source2, target2) {
      const typeCallSignatures = getSignaturesOfStructuredType(source2, 0 /* Call */);
      const typeConstructSignatures = getSignaturesOfStructuredType(source2, 1 /* Construct */);
      const typeProperties = getPropertiesOfObjectType(source2);
      if ((typeCallSignatures.length || typeConstructSignatures.length) && !typeProperties.length) {
        if (getSignaturesOfType(target2, 0 /* Call */).length && typeCallSignatures.length || getSignaturesOfType(target2, 1 /* 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, reportErrors2, 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, reportErrors2, reportError, incompatibleReporter, isRelatedToWorker2, reportUnreliableMapper);
      function isRelatedToWorker2(source3, target3, reportErrors3) {
        return isRelatedTo(
          source3,
          target3,
          3 /* Both */,
          reportErrors3,
          /*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 0 /* False */;
      }
      let result2 = -1 /* 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 0 /* False */;
        }
        result2 &= related;
      }
      return result2;
    }
    function membersRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState) {
      let result2 = -1 /* True */;
      const keyType = targetInfo.keyType;
      const props = source2.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source2) : getPropertiesOfObjectType(source2);
      for (const prop of props) {
        if (isIgnoredJsxProperty(source2, prop)) {
          continue;
        }
        if (isApplicableIndexType(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), keyType)) {
          const propType = getNonMissingTypeOfSymbol(prop);
          const type = exactOptionalPropertyTypes || propType.flags & 32768 /* Undefined */ || keyType === numberType || !(prop.flags & 16777216 /* Optional */) ? propType : getTypeWithFacts(propType, 524288 /* NEUndefined */);
          const related = isRelatedTo(
            type,
            targetInfo.type,
            3 /* Both */,
            reportErrors2,
            /*headMessage*/
            void 0,
            intersectionState
          );
          if (!related) {
            if (reportErrors2) {
              reportError(Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
            }
            return 0 /* False */;
          }
          result2 &= related;
        }
      }
      for (const info of getIndexInfosOfType(source2)) {
        if (isApplicableIndexType(info.keyType, keyType)) {
          const related = indexInfoRelatedTo(info, targetInfo, reportErrors2, intersectionState);
          if (!related) {
            return 0 /* False */;
          }
          result2 &= related;
        }
      }
      return result2;
    }
    function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors2, intersectionState) {
      const related = isRelatedTo(
        sourceInfo.type,
        targetInfo.type,
        3 /* Both */,
        reportErrors2,
        /*headMessage*/
        void 0,
        intersectionState
      );
      if (!related && reportErrors2) {
        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, reportErrors2, intersectionState) {
      if (relation === identityRelation) {
        return indexSignaturesIdenticalTo(source2, target2);
      }
      const indexInfos = getIndexInfosOfType(target2);
      const targetHasStringIndex = some(indexInfos, (info) => info.keyType === stringType);
      let result2 = -1 /* True */;
      for (const targetInfo of indexInfos) {
        const related = relation !== strictSubtypeRelation && !sourceIsPrimitive && targetHasStringIndex && targetInfo.type.flags & 1 /* Any */ ? -1 /* True */ : isGenericMappedType(source2) && targetHasStringIndex ? isRelatedTo(getTemplateTypeFromMappedType(source2), targetInfo.type, 3 /* Both */, reportErrors2) : typeRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState);
        if (!related) {
          return 0 /* False */;
        }
        result2 &= related;
      }
      return result2;
    }
    function typeRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState) {
      const sourceInfo = getApplicableIndexInfo(source2, targetInfo.keyType);
      if (sourceInfo) {
        return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors2, intersectionState);
      }
      if (!(intersectionState & 1 /* Source */) && (relation !== strictSubtypeRelation || getObjectFlags(source2) & 8192 /* FreshLiteral */) && isObjectTypeWithInferableIndex(source2)) {
        return membersRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState);
      }
      if (reportErrors2) {
        reportError(Diagnostics.Index_signature_for_type_0_is_missing_in_type_1, typeToString(targetInfo.keyType), typeToString(source2));
      }
      return 0 /* False */;
    }
    function indexSignaturesIdenticalTo(source2, target2) {
      const sourceInfos = getIndexInfosOfType(source2);
      const targetInfos = getIndexInfosOfType(target2);
      if (sourceInfos.length !== targetInfos.length) {
        return 0 /* 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 0 /* False */;
        }
      }
      return -1 /* True */;
    }
    function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors2) {
      if (!sourceSignature.declaration || !targetSignature.declaration) {
        return true;
      }
      const sourceAccessibility = getSelectedEffectiveModifierFlags(sourceSignature.declaration, 6 /* NonPublicAccessibilityModifier */);
      const targetAccessibility = getSelectedEffectiveModifierFlags(targetSignature.declaration, 6 /* NonPublicAccessibilityModifier */);
      if (targetAccessibility === 2 /* Private */) {
        return true;
      }
      if (targetAccessibility === 4 /* Protected */ && sourceAccessibility !== 2 /* Private */) {
        return true;
      }
      if (targetAccessibility !== 4 /* Protected */ && !sourceAccessibility) {
        return true;
      }
      if (reportErrors2) {
        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 & 16 /* Boolean */) {
      return false;
    }
    if (type.flags & 3145728 /* UnionOrIntersection */) {
      return !!forEach(type.types, typeCouldHaveTopLevelSingletonTypes);
    }
    if (type.flags & 465829888 /* Instantiable */) {
      const constraint = getConstraintOfType(type);
      if (constraint && constraint !== type) {
        return typeCouldHaveTopLevelSingletonTypes(constraint);
      }
    }
    return isUnitType(type) || !!(type.flags & 134217728 /* TemplateLiteral */) || !!(type.flags & 268435456 /* 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, 32768 /* 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 & 402784252 /* Primitive */ ? 0 /* False */ : -1 /* 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] = 3 /* Maybe */;
          }
        }
      }
      for (let i = 0; i < types.length; i++) {
        if (include[i] === 3 /* Maybe */) {
          include[i] = matched ? 0 /* False */ : -1 /* True */;
        }
      }
    }
    const filtered = contains(include, 0 /* False */) ? getUnionType(types.filter((_, i) => include[i]), 0 /* None */) : target;
    return filtered.flags & 131072 /* Never */ ? target : filtered;
  }
  function isWeakType(type) {
    if (type.flags & 524288 /* 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 & 16777216 /* Optional */));
    }
    if (type.flags & 33554432 /* Substitution */) {
      return isWeakType(type.baseType);
    }
    if (type.flags & 2097152 /* 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 & 8 /* Tuple */ ? arrayVariances : getVariancesWorker(type.symbol, type.typeParameters);
  }
  function getAliasVariances(symbol) {
    return getVariancesWorker(symbol, getSymbolLinks(symbol).typeParameters);
  }
  function getVariancesWorker(symbol, typeParameters = emptyArray) {
    var _a, _b;
    const links = getSymbolLinks(symbol);
    if (!links.variances) {
      (_a = tracing) == null ? void 0 : _a.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 & 16384 /* Out */ ? modifiers & 8192 /* In */ ? 0 /* Invariant */ : 1 /* Covariant */ : modifiers & 8192 /* In */ ? 2 /* 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) ? 1 /* Covariant */ : 0) | (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
          if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(symbol, tp, markerOtherType), typeWithSuper)) {
            variance = 4 /* Independent */;
          }
          outofbandVarianceMarkerHandler = oldHandler;
          if (unmeasurable || unreliable) {
            if (unmeasurable) {
              variance |= 8 /* Unmeasurable */;
            }
            if (unreliable) {
              variance |= 16 /* Unreliable */;
            }
          }
        }
        variances.push(variance);
      }
      if (!oldVarianceComputation) {
        inVarianceComputation = false;
        resolutionStart = saveResolutionStart;
      }
      links.variances = variances;
      (_b = tracing) == null ? void 0 : _b.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 & 524288 /* 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) {
    var _a;
    return reduceLeft((_a = tp.symbol) == null ? void 0 : _a.declarations, (modifiers, d) => modifiers | getEffectiveModifierFlags(d), 0 /* None */) & (8192 /* In */ | 16384 /* Out */ | 4096 /* Const */);
  }
  function hasCovariantVoidArgument(typeArguments, variances) {
    for (let i = 0; i < variances.length; i++) {
      if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
        return true;
      }
    }
    return false;
  }
  function isUnconstrainedTypeParameter(type) {
    return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
  }
  function isNonDeferredTypeReference(type) {
    return !!(getObjectFlags(type) & 4 /* Reference */) && !type.node;
  }
  function isTypeReferenceWithGenericArguments(type) {
    return isNonDeferredTypeReference(type) && some(getTypeArguments(type), (t) => !!(t.flags & 262144 /* 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 & 262144 /* 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 forEachProperty2(prop, callback) {
    if (getCheckFlags(prop) & 6 /* Synthetic */) {
      for (const t of prop.links.containingType.types) {
        const p = getPropertyOfType(t, prop.escapedName);
        const result = p && forEachProperty2(p, callback);
        if (result) {
          return result;
        }
      }
      return void 0;
    }
    return callback(prop);
  }
  function getDeclaringClass(prop) {
    return prop.parent && prop.parent.flags & 32 /* 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 forEachProperty2(prop, (sp) => {
      const sourceClass = getDeclaringClass(sp);
      return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
    });
  }
  function isValidOverrideOf(sourceProp, targetProp) {
    return !forEachProperty2(targetProp, (tp) => getDeclarationModifierFlagsFromSymbol(tp) & 4 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false);
  }
  function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) {
    return forEachProperty2(prop, (p) => getDeclarationModifierFlagsFromSymbol(p, writing) & 4 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? void 0 : checkClass;
  }
  function isDeeplyNestedType(type, stack, depth, maxDepth = 3) {
    if (depth >= maxDepth) {
      if ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */) {
        type = getMappedTargetWithSymbol(type);
      }
      if (type.flags & 2097152 /* Intersection */) {
        return some(type.types, (t) => isDeeplyNestedType(t, stack, depth, maxDepth));
      }
      const identity2 = getRecursionIdentity(type);
      let count = 0;
      let lastTypeId = 0;
      for (let i = 0; i < depth; i++) {
        const t = stack[i];
        if (hasMatchingRecursionIdentity(t, identity2)) {
          if (t.id >= lastTypeId) {
            count++;
            if (count >= maxDepth) {
              return true;
            }
          }
          lastTypeId = t.id;
        }
      }
    }
    return false;
  }
  function getMappedTargetWithSymbol(type) {
    let target;
    while ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */ && (target = getModifiersTypeFromMappedType(type)) && (target.symbol || target.flags & 2097152 /* Intersection */ && some(target.types, (t) => !!t.symbol))) {
      type = target;
    }
    return type;
  }
  function hasMatchingRecursionIdentity(type, identity2) {
    if ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */) {
      type = getMappedTargetWithSymbol(type);
    }
    if (type.flags & 2097152 /* Intersection */) {
      return some(type.types, (t) => hasMatchingRecursionIdentity(t, identity2));
    }
    return getRecursionIdentity(type) === identity2;
  }
  function getRecursionIdentity(type) {
    if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
      if (getObjectFlags(type) & 4 /* Reference */ && type.node) {
        return type.node;
      }
      if (type.symbol && !(getObjectFlags(type) & 16 /* Anonymous */ && type.symbol.flags & 32 /* Class */)) {
        return type.symbol;
      }
      if (isTupleType(type)) {
        return type.target;
      }
    }
    if (type.flags & 262144 /* TypeParameter */) {
      return type.symbol;
    }
    if (type.flags & 8388608 /* IndexedAccess */) {
      do {
        type = type.objectType;
      } while (type.flags & 8388608 /* IndexedAccess */);
      return type;
    }
    if (type.flags & 16777216 /* Conditional */) {
      return type.root;
    }
    return type;
  }
  function isPropertyIdenticalTo(sourceProp, targetProp) {
    return compareProperties2(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
  }
  function compareProperties2(sourceProp, targetProp, compareTypes) {
    if (sourceProp === targetProp) {
      return -1 /* True */;
    }
    const sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 6 /* NonPublicAccessibilityModifier */;
    const targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 6 /* NonPublicAccessibilityModifier */;
    if (sourcePropAccessibility !== targetPropAccessibility) {
      return 0 /* False */;
    }
    if (sourcePropAccessibility) {
      if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
        return 0 /* False */;
      }
    } else {
      if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
        return 0 /* False */;
      }
    }
    if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
      return 0 /* 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 -1 /* True */;
    }
    if (!isMatchingSignature(source, target, partialMatch)) {
      return 0 /* False */;
    }
    if (length(source.typeParameters) !== length(target.typeParameters)) {
      return 0 /* 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 0 /* False */;
        }
      }
      source = instantiateSignature(
        source,
        mapper,
        /*eraseTypeParameters*/
        true
      );
    }
    let result = -1 /* True */;
    if (!ignoreThisTypes) {
      const sourceThisType = getThisTypeOfSignature(source);
      if (sourceThisType) {
        const targetThisType = getThisTypeOfSignature(target);
        if (targetThisType) {
          const related = compareTypes(sourceThisType, targetThisType);
          if (!related) {
            return 0 /* 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 0 /* 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)) ? 0 /* False */ : source.type === target.type ? -1 /* True */ : source.type && target.type ? compareTypes(source.type, target.type) : 0 /* False */;
  }
  function literalTypesWithSameBaseType(types) {
    let commonBaseType;
    for (const t of types) {
      if (!(t.flags & 131072 /* Never */)) {
        const baseType = getBaseTypeOfLiteralType(t);
        commonBaseType ?? (commonBaseType = baseType);
        if (baseType === t || baseType !== commonBaseType) {
          return false;
        }
      }
    }
    return true;
  }
  function getCombinedTypeFlags(types) {
    return reduceLeft(types, (flags, t) => flags | (t.flags & 1048576 /* 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 & 98304 /* 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) & 98304 /* Nullable */);
  }
  function getCommonSubtype(types) {
    return reduceLeft(types, (s, t) => isTypeSubtypeOf(t, s) ? t : s);
  }
  function isArrayType(type) {
    return !!(getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
  }
  function isReadonlyArrayType(type) {
    return !!(getObjectFlags(type) & 4 /* 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 & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
  }
  function isMutableArrayLikeType(type) {
    return isMutableArrayOrTuple(type) || !(type.flags & (1 /* Any */ | 98304 /* Nullable */)) && isTypeAssignableTo(type, anyArrayType);
  }
  function getSingleBaseForNonAugmentingSubtype(type) {
    if (!(getObjectFlags(type) & 4 /* Reference */) || !(getObjectFlags(type.target) & 3 /* ClassOrInterface */)) {
      return void 0;
    }
    if (getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) {
      return getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : void 0;
    }
    type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */;
    const target = type.target;
    if (getObjectFlags(target) & 1 /* Class */) {
      const baseTypeNode = getBaseTypeNodeOfClass(target);
      if (baseTypeNode && baseTypeNode.expression.kind !== 80 /* Identifier */ && baseTypeNode.expression.kind !== 211 /* 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 |= 67108864 /* 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 & 256 /* 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 & (109472 /* Unit */ | 131072 /* Never */));
  }
  function isUnitType(type) {
    return !!(type.flags & 109472 /* Unit */);
  }
  function isUnitLikeType(type) {
    const t = getBaseConstraintOrType(type);
    return t.flags & 2097152 /* Intersection */ ? some(t.types, isUnitType) : isUnitType(t);
  }
  function extractUnitType(type) {
    return type.flags & 2097152 /* Intersection */ ? find(type.types, isUnitType) || type : type;
  }
  function isLiteralType(type) {
    return type.flags & 16 /* Boolean */ ? true : type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : every(type.types, isUnitType) : isUnitType(type);
  }
  function getBaseTypeOfLiteralType(type) {
    return type.flags & 1056 /* EnumLike */ ? getBaseTypeOfEnumLikeType(type) : type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : type.flags & 1048576 /* 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 & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? stringType : type.flags & (256 /* NumberLiteral */ | 32 /* Enum */) ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : type.flags & 1048576 /* Union */ ? mapType(type, getBaseTypeOfLiteralTypeForComparison) : type;
  }
  function getWidenedLiteralType(type) {
    return type.flags & 1056 /* EnumLike */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLikeType(type) : type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : type.flags & 1048576 /* Union */ ? mapType(type, getWidenedLiteralType) : type;
  }
  function getWidenedUniqueESSymbolType(type) {
    return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : type.flags & 1048576 /* 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) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
  }
  function isGenericTupleType(type) {
    return isTupleType(type) && !!(type.target.combinedFlags & 8 /* 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] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t);
      }
      return writing ? getIntersectionType(elementTypes) : getUnionType(elementTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
    }
    return void 0;
  }
  function isTupleTypeStructureMatching(t1, t2) {
    return getTypeReferenceArity(t1) === getTypeReferenceArity(t2) && every(t1.target.elementFlags, (f, i) => (f & 12 /* Variable */) === (t2.target.elementFlags[i] & 12 /* 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 & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : type.flags & 64 /* BigInt */ ? zeroBigIntType : type === regularFalseType || type === falseType || type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */ | 3 /* AnyOrUnknown */) || type.flags & 128 /* StringLiteral */ && type.value === "" || type.flags & 256 /* NumberLiteral */ && type.value === 0 || type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : neverType;
  }
  function getNullableType(type, flags) {
    const missing = flags & ~type.flags & (32768 /* Undefined */ | 65536 /* Null */);
    return missing === 0 ? type : missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : missing === 65536 /* 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 & 1048576 /* Union */ && type.types[0] === missingOrUndefined ? type : getUnionType([type, missingOrUndefined]);
  }
  function getGlobalNonNullableTypeInstantiation(type) {
    if (!deferredGlobalNonNullableTypeAlias) {
      deferredGlobalNonNullableTypeAlias = getGlobalSymbol(
        "NonNullable",
        524288 /* 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 & 1048576 /* Union */) && type.types[0] === missingType;
  }
  function removeMissingOrUndefinedType(type) {
    return exactOptionalPropertyTypes ? removeType(type, missingType) : getTypeWithFacts(type, 524288 /* NEUndefined */);
  }
  function isCoercibleUnderDoubleEquals(source, target) {
    return (source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0 && (target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0;
  }
  function isObjectTypeWithInferableIndex(type) {
    const objectFlags = getObjectFlags(type);
    return type.flags & 2097152 /* Intersection */ ? every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && !(type.symbol.flags & 32 /* Class */) && !typeHasCallOrConstructSignatures(type)) || !!(objectFlags & 4194304 /* ObjectRestType */) || !!(objectFlags & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
  }
  function createSymbolWithType(source, type) {
    const symbol = createSymbol(source.flags, source.escapedName, getCheckFlags(source) & 8 /* 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 (!(isObjectLiteralType2(type) && getObjectFlags(type) & 8192 /* 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 & ~8192 /* FreshLiteral */;
    type.regularType = regularNew;
    return regularNew;
  }
  function createWideningContext(parent2, propertyName, siblings) {
    return { parent: parent2, propertyName, siblings, resolvedProperties: void 0 };
  }
  function getSiblingsOfContext(context) {
    if (!context.siblings) {
      const siblings = [];
      for (const type of getSiblingsOfContext(context.parent)) {
        if (isObjectLiteralType2(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 (isObjectLiteralType2(t) && !(getObjectFlags(t) & 2097152 /* 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 & 4 /* 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 |= 16777216 /* 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) & (4096 /* JSLiteral */ | 262144 /* NonInferrableType */);
    return result;
  }
  function getWidenedType(type) {
    return getWidenedTypeWithContext(
      type,
      /*context*/
      void 0
    );
  }
  function getWidenedTypeWithContext(type, context) {
    if (getObjectFlags(type) & 196608 /* RequiresWidening */) {
      if (context === void 0 && type.widened) {
        return type.widened;
      }
      let result;
      if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
        result = anyType;
      } else if (isObjectLiteralType2(type)) {
        result = getWidenedTypeOfObjectLiteral(type, context);
      } else if (type.flags & 1048576 /* Union */) {
        const unionContext = context || createWideningContext(
          /*parent*/
          void 0,
          /*propertyName*/
          void 0,
          type.types
        );
        const widenedTypes = sameMap(type.types, (t) => t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext));
        result = getUnionType(widenedTypes, some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
      } else if (type.flags & 2097152 /* 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) {
    var _a;
    let errorReported = false;
    if (getObjectFlags(type) & 65536 /* ContainsWideningType */) {
      if (type.flags & 1048576 /* Union */) {
        if (some(type.types, isEmptyObjectType)) {
          errorReported = true;
        } else {
          for (const t of type.types) {
            errorReported || (errorReported = reportWideningErrorsInType(t));
          }
        }
      } else if (isArrayOrTupleType(type)) {
        for (const t of getTypeArguments(type)) {
          errorReported || (errorReported = reportWideningErrorsInType(t));
        }
      } else if (isObjectLiteralType2(type)) {
        for (const p of getPropertiesOfObjectType(type)) {
          const t = getTypeOfSymbol(p);
          if (getObjectFlags(t) & 65536 /* ContainsWideningType */) {
            errorReported = reportWideningErrorsInType(t);
            if (!errorReported) {
              const valueDeclaration = (_a = p.declarations) == null ? void 0 : _a.find((d) => {
                var _a2;
                return ((_a2 = d.symbol.valueDeclaration) == null ? void 0 : _a2.parent) === type.symbol.valueDeclaration;
              });
              if (valueDeclaration) {
                error2(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 226 /* BinaryExpression */:
      case 172 /* PropertyDeclaration */:
      case 171 /* 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 169 /* 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,
            788968 /* 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 208 /* BindingElement */:
        diagnostic = Diagnostics.Binding_element_0_implicitly_has_an_1_type;
        if (!noImplicitAny) {
          return;
        }
        break;
      case 317 /* JSDocFunctionType */:
        error2(declaration, Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
        return;
      case 323 /* JSDocSignature */:
        if (noImplicitAny && isJSDocOverloadTag(declaration.parent)) {
          error2(declaration.parent.tagName, Diagnostics.This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation, typeAsString);
        }
        return;
      case 262 /* FunctionDeclaration */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
        if (noImplicitAny && !declaration.name) {
          if (wideningKind === 3 /* GeneratorYield */) {
            error2(declaration, Diagnostics.Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation, typeAsString);
          } else {
            error2(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 200 /* MappedType */:
        if (noImplicitAny) {
          error2(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 shouldReportErrorsFromWideningWithContextualSignature(declaration, wideningKind) {
    const signature = getContextualSignatureForFunctionLikeDeclaration(declaration);
    if (!signature) {
      return true;
    }
    let returnType = getReturnTypeOfSignature(signature);
    const flags = getFunctionFlags(declaration);
    switch (wideningKind) {
      case 1 /* FunctionReturn */:
        if (flags & 1 /* Generator */) {
          returnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, !!(flags & 2 /* Async */)) ?? returnType;
        } else if (flags & 2 /* Async */) {
          returnType = getAwaitedTypeNoAlias(returnType) ?? returnType;
        }
        return isGenericType(returnType);
      case 3 /* GeneratorYield */:
        const yieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, !!(flags & 2 /* Async */));
        return !!yieldType && isGenericType(yieldType);
      case 2 /* GeneratorNext */:
        const nextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, !!(flags & 2 /* Async */));
        return !!nextType && isGenericType(nextType);
    }
    return false;
  }
  function reportErrorsFromWidening(declaration, type, wideningKind) {
    addLazyDiagnostic(() => {
      if (noImplicitAny && getObjectFlags(type) & 65536 /* ContainsWideningType */) {
        if (!wideningKind || isFunctionLikeDeclaration(declaration) && shouldReportErrorsFromWideningWithContextualSignature(declaration, wideningKind)) {
          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 ?? (context.intraExpressionInferenceSites = [])).push({ node, type });
  }
  function inferFromIntraExpressionSites(context) {
    if (context.intraExpressionInferenceSites) {
      for (const { node, type } of context.intraExpressionInferenceSites) {
        const contextualType = node.kind === 174 /* MethodDeclaration */ ? getContextualTypeForObjectLiteralMethod(node, 2 /* NoConstraints */) : getContextualType2(node, 2 /* 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 & 524288 /* CouldContainTypeVariablesComputed */) {
      return !!(objectFlags & 1048576 /* CouldContainTypeVariables */);
    }
    const result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || some(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 134217728 /* SingleSignatureType */ && !!length(type.outerTypeParameters) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 4194304 /* ObjectRestType */ | 8388608 /* InstantiationExpressionType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && some(type.types, couldContainTypeVariables));
    if (type.flags & 3899393 /* ObjectFlagsType */) {
      type.objectFlags |= 524288 /* CouldContainTypeVariablesComputed */ | (result ? 1048576 /* CouldContainTypeVariables */ : 0);
    }
    return result;
  }
  function isNonGenericTopLevelType(type) {
    if (type.aliasSymbol && !type.aliasTypeArguments) {
      const declaration = getDeclarationOfKind(type.aliasSymbol, 265 /* TypeAliasDeclaration */);
      return !!(declaration && findAncestor(declaration.parent, (n) => n.kind === 307 /* SourceFile */ ? true : n.kind === 267 /* ModuleDeclaration */ ? false : "quit"));
    }
    return false;
  }
  function isTypeParameterAtTopLevel(type, tp, depth = 0) {
    return !!(type === tp || type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, (t) => isTypeParameterAtTopLevel(t, tp, depth)) || depth < 3 && type.flags & 16777216 /* 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 & 128 /* StringLiteral */)) {
        return;
      }
      const name = escapeLeadingUnderscores(t.value);
      const literalProp = createSymbol(4 /* 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 & 4 /* 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) & 262144 /* NonInferrableType */) || isObjectLiteralType2(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 & 2 /* Optional */ ? 1 /* Required */ : f) : source.target.elementFlags;
      return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations);
    }
    const reversed = createObjectType(
      1024 /* ReverseMapped */ | 16 /* 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 & 16777216 /* Optional */ || getCheckFlags(targetProp) & 48 /* Partial */)) {
        const sourceProp = getPropertyOfType(source, targetProp.escapedName);
        if (!sourceProp) {
          yield targetProp;
        } else if (matchDiscriminantProperties) {
          const targetType = getTypeOfSymbol(targetProp);
          if (targetType.flags & 109472 /* Unit */) {
            const sourceType = getTypeOfSymbol(sourceProp);
            if (!(sourceType.flags & 1 /* 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 & 8 /* Variadic */) && target.target.minLength > source.target.minLength || !(target.target.combinedFlags & 12 /* Variable */) && (!!(source.target.combinedFlags & 12 /* 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, 2 /* 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 & 1 /* Any */) {
      return true;
    }
    if (target.flags & (4 /* String */ | 134217728 /* TemplateLiteral */)) {
      return isTypeAssignableTo(source, target);
    }
    if (target.flags & 268435456 /* StringMapping */) {
      const mappingStack = [];
      while (target.flags & 268435456 /* 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 & 2097152 /* Intersection */) {
      return every(target.types, (t) => t === emptyTypeLiteralType || isValidTypeForTemplateLiteralPlaceholder(source, t));
    }
    if (target.flags & 4 /* String */ || isTypeAssignableTo(source, target)) {
      return true;
    }
    if (source.flags & 128 /* StringLiteral */) {
      const value = source.value;
      return !!(target.flags & 8 /* Number */ && isValidNumberString(
        value,
        /*roundTripOnly*/
        false
      ) || target.flags & 64 /* BigInt */ && isValidBigIntString(
        value,
        /*roundTripOnly*/
        false
      ) || target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName || target.flags & 268435456 /* StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target) || target.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source, target));
    }
    if (source.flags & 134217728 /* 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 & 128 /* StringLiteral */ ? inferFromLiteralPartsToTemplateLiteral([source.value], emptyArray, target) : source.flags & 134217728 /* 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 & (1 /* Any */ | 402653316 /* 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 = 0 /* None */, contravariant = false) {
    let bivariant = false;
    let propagationType;
    let inferencePriority = 2048 /* 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 & 3145728 /* UnionOrIntersection */) {
        for (const t of source.types) {
          inferFromTypes(t, t);
        }
        return;
      }
      if (target.flags & 1048576 /* Union */) {
        const [tempSources, tempTargets] = inferFromMatchingTypes(source.flags & 1048576 /* 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, 1 /* NakedTypeVariable */);
          return;
        }
        source = getUnionType(sources);
      } else if (target.flags & 2097152 /* Intersection */ && !every(target.types, isNonGenericObjectType)) {
        if (!(source.flags & 1048576 /* Union */)) {
          const [sources, targets] = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo);
          if (sources.length === 0 || targets.length === 0) {
            return;
          }
          source = getIntersectionType(sources);
          target = getIntersectionType(targets);
        }
      }
      if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
        if (isNoInferType(target)) {
          return;
        }
        target = getActualTypeVariable(target);
      }
      if (target.flags & 8650752 /* TypeVariable */) {
        if (isFromInferenceBlockedSource(source)) {
          return;
        }
        const inference = getInferenceInfoForType(target);
        if (inference) {
          if (getObjectFlags(source) & 262144 /* 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 & 128 /* ReturnType */) && target.flags & 262144 /* 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 & 8388608 /* IndexedAccess */) {
          const indexType = getSimplifiedType(
            target.indexType,
            /*writing*/
            false
          );
          if (indexType.flags & 465829888 /* Instantiable */) {
            const simplified2 = distributeIndexOverObjectType(
              getSimplifiedType(
                target.objectType,
                /*writing*/
                false
              ),
              indexType,
              /*writing*/
              false
            );
            if (simplified2 && simplified2 !== target) {
              inferFromTypes(source, simplified2);
            }
          }
        }
      }
      if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* 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 & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
        inferFromContravariantTypes(source.type, target.type);
      } else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
        const empty = createEmptyObjectTypeFromStringLiteral(source);
        inferFromContravariantTypesWithPriority(empty, target.type, 256 /* LiteralKeyof */);
      } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
        inferFromTypes(source.objectType, target.objectType);
        inferFromTypes(source.indexType, target.indexType);
      } else if (source.flags & 268435456 /* StringMapping */ && target.flags & 268435456 /* StringMapping */) {
        if (source.symbol === target.symbol) {
          inferFromTypes(source.type, target.type);
        }
      } else if (source.flags & 33554432 /* Substitution */) {
        inferFromTypes(source.baseType, target);
        inferWithPriority(getSubstitutionIntersection(source), target, 4 /* SubstituteSource */);
      } else if (target.flags & 16777216 /* Conditional */) {
        invokeOnce(source, target, inferToConditionalType);
      } else if (target.flags & 3145728 /* UnionOrIntersection */) {
        inferToMultipleTypes(source, target.types, target.flags);
      } else if (source.flags & 1048576 /* Union */) {
        const sourceTypes = source.types;
        for (const sourceType of sourceTypes) {
          inferFromTypes(sourceType, target);
        }
      } else if (target.flags & 134217728 /* TemplateLiteral */) {
        inferToTemplateLiteralType(source, target);
      } else {
        source = getReducedType(source);
        if (isGenericMappedType(source) && isGenericMappedType(target)) {
          invokeOnce(source, target, inferFromGenericMappedTypes);
        }
        if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) {
          const apparentSource = getApparentType(source);
          if (apparentSource !== source && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
            return inferFromTypes(apparentSource, target);
          }
          source = apparentSource;
        }
        if (source.flags & (524288 /* Object */ | 2097152 /* 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, -1 /* Circularity */);
      const saveInferencePriority = inferencePriority;
      inferencePriority = 2048 /* MaxValue */;
      const saveExpandingFlags = expandingFlags;
      (sourceStack ?? (sourceStack = [])).push(source);
      (targetStack ?? (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 = -1 /* 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] & 7 /* VarianceMask */) === 2 /* 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 & 1024 /* AlwaysStrict */) {
        inferFromContravariantTypes(source, target);
      } else {
        inferFromTypes(source, target);
      }
    }
    function getInferenceInfoForType(type) {
      if (type.flags & 8650752 /* 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 & 2097152 /* 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 & 1048576 /* Union */) {
        let nakedTypeVariable;
        const sources = source.flags & 1048576 /* 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 = 2048 /* MaxValue */;
              inferFromTypes(sources[i], t);
              if (inferencePriority === priority) matched[i] = true;
              inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
              inferencePriority = Math.min(inferencePriority, saveInferencePriority);
            }
          }
        }
        if (typeVariableCount === 0) {
          const intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
          if (intersectionTypeVariable) {
            inferWithPriority(source, intersectionTypeVariable, 1 /* 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 & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
        for (const t of targets) {
          if (getInferenceInfoForType(t)) {
            inferWithPriority(source, t, 1 /* NakedTypeVariable */);
          }
        }
      }
    }
    function inferToMappedType(source, target, constraintType) {
      if (constraintType.flags & 1048576 /* Union */ || constraintType.flags & 2097152 /* Intersection */) {
        let result = false;
        for (const type of constraintType.types) {
          result = inferToMappedType(source, target, type) || result;
        }
        return result;
      }
      if (constraintType.flags & 4194304 /* 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) & 262144 /* NonInferrableType */ ? 16 /* PartialHomomorphicMappedType */ : 8 /* HomomorphicMappedType */
            );
          }
        }
        return true;
      }
      if (constraintType.flags & 262144 /* TypeParameter */) {
        inferWithPriority(getIndexType(
          source,
          /*indexFlags*/
          !!source.pattern ? 2 /* NoIndexSignatures */ : 0 /* None */
        ), constraintType, 32 /* 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 & 16777216 /* 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 ? 64 /* 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 & 128 /* StringLiteral */ && target2.flags & 8650752 /* TypeVariable */) {
            const inferenceContext = getInferenceInfoForType(target2);
            const constraint = inferenceContext ? getBaseConstraintOfType(inferenceContext.typeParameter) : void 0;
            if (constraint && !isTypeAny(constraint)) {
              const constraintTypes = constraint.flags & 1048576 /* Union */ ? constraint.types : [constraint];
              let allTypeFlags = reduceLeft(constraintTypes, (flags, t) => flags | t.flags, 0);
              if (!(allTypeFlags & 4 /* String */)) {
                const str = source2.value;
                if (allTypeFlags & 296 /* NumberLike */ && !isValidNumberString(
                  str,
                  /*roundTripOnly*/
                  true
                )) {
                  allTypeFlags &= ~296 /* NumberLike */;
                }
                if (allTypeFlags & 2112 /* BigIntLike */ && !isValidBigIntString(
                  str,
                  /*roundTripOnly*/
                  true
                )) {
                  allTypeFlags &= ~2112 /* BigIntLike */;
                }
                const matchingType = reduceLeft(constraintTypes, (left, right) => !(right.flags & allTypeFlags) ? left : left.flags & 4 /* String */ ? left : right.flags & 4 /* String */ ? source2 : left.flags & 134217728 /* TemplateLiteral */ ? left : right.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source2, right) ? source2 : left.flags & 268435456 /* StringMapping */ ? left : right.flags & 268435456 /* StringMapping */ && str === applyStringMapping(right.symbol, str) ? source2 : left.flags & 128 /* StringLiteral */ ? left : right.flags & 128 /* StringLiteral */ && right.value === str ? right : left.flags & 8 /* Number */ ? left : right.flags & 8 /* Number */ ? getNumberLiteralType(+str) : left.flags & 32 /* Enum */ ? left : right.flags & 32 /* Enum */ ? getNumberLiteralType(+str) : left.flags & 256 /* NumberLiteral */ ? left : right.flags & 256 /* NumberLiteral */ && right.value === +str ? right : left.flags & 64 /* BigInt */ ? left : right.flags & 64 /* BigInt */ ? parseBigIntLiteralType(str) : left.flags & 2048 /* BigIntLiteral */ ? left : right.flags & 2048 /* BigIntLiteral */ && pseudoBigIntToString(right.value) === str ? right : left.flags & 16 /* Boolean */ ? left : right.flags & 16 /* Boolean */ ? str === "true" ? trueType : str === "false" ? falseType : booleanType : left.flags & 512 /* BooleanLiteral */ ? left : right.flags & 512 /* BooleanLiteral */ && right.intrinsicName === str ? right : left.flags & 32768 /* Undefined */ ? left : right.flags & 32768 /* Undefined */ && right.intrinsicName === str ? right : left.flags & 65536 /* Null */ ? left : right.flags & 65536 /* Null */ && right.intrinsicName === str ? right : left, neverType);
                if (!(matchingType.flags & 131072 /* 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) {
      var _a, _b;
      if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* 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) & 32 /* 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, 3 /* Fixed */) : 0, target.target.combinedFlags & 12 /* Variable */ ? getEndElementCount(target.target, 3 /* 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] & 4 /* Rest */) {
              const restType = getTypeArguments(source)[startLength];
              for (let i = startLength; i < targetArity - endLength; i++) {
                inferFromTypes(elementFlags[i] & 8 /* Variadic */ ? createArrayType(restType) : restType, elementTypes[i]);
              }
            } else {
              const middleLength = targetArity - startLength - endLength;
              if (middleLength === 2) {
                if (elementFlags[startLength] & elementFlags[startLength + 1] & 8 /* 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] & 8 /* Variadic */ && elementFlags[startLength + 1] & 4 /* Rest */) {
                  const param = (_a = getInferenceInfoForType(elementTypes[startLength])) == null ? void 0 : _a.typeParameter;
                  const constraint = param && getBaseConstraintOfType(param);
                  if (constraint && isTupleType(constraint) && !(constraint.target.combinedFlags & 12 /* 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] & 4 /* Rest */ && elementFlags[startLength + 1] & 8 /* Variadic */) {
                  const param = (_b = getInferenceInfoForType(elementTypes[startLength + 1])) == null ? void 0 : _b.typeParameter;
                  const constraint = param && getBaseConstraintOfType(param);
                  if (constraint && isTupleType(constraint) && !(constraint.target.combinedFlags & 12 /* Variable */)) {
                    const impliedArity = constraint.target.fixedLength;
                    const endIndex = sourceArity - getEndElementCount(target.target, 3 /* 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] & 8 /* Variadic */) {
                const endsInOptional = target.target.elementFlags[targetArity - 1] & 2 /* Optional */;
                const sourceSlice = sliceTupleType(source, startLength, endLength);
                inferWithPriority(sourceSlice, elementTypes[startLength], endsInOptional ? 2 /* SpeculativeTuple */ : 0);
              } else if (middleLength === 1 && elementFlags[startLength] & 4 /* 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, 0 /* Call */);
        inferFromSignatures(source, target, 1 /* 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 & 16777216 /* Optional */)),
            removeMissingType(getTypeOfSymbol(targetProp), !!(targetProp.flags & 16777216 /* 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 & 64 /* IsNonInferrable */)) {
        const saveBivariant = bivariant;
        const kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
        bivariant = bivariant || kind === 174 /* MethodDeclaration */ || kind === 173 /* MethodSignature */ || kind === 176 /* Constructor */;
        applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes);
        bivariant = saveBivariant;
      }
      applyToReturnTypes(source, target, inferFromTypes);
    }
    function inferFromIndexTypes(source, target) {
      const priority2 = getObjectFlags(source) & getObjectFlags(target) & 32 /* Mapped */ ? 8 /* 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, 8576 /* StringOrNumberLiteralOrUnique */), targetInfo.keyType)) {
              const propType = getTypeOfSymbol(prop);
              propTypes.push(prop.flags & 16777216 /* 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 & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
  }
  function isTypeCloselyMatchedBy(s, t) {
    return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* 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 & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 402784252 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
  }
  function isObjectLiteralType2(type) {
    return !!(getObjectFlags(type) & 128 /* ObjectLiteral */);
  }
  function isObjectOrArrayLiteralType(type) {
    return !!(getObjectFlags(type) & (128 /* ObjectLiteral */ | 16384 /* ArrayLiteral */));
  }
  function unionObjectAndArrayLiteralCandidates(candidates) {
    if (candidates.length > 1) {
      const objectLiterals = filter(candidates, isObjectOrArrayLiteralType);
      if (objectLiterals.length) {
        const literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
        return concatenate(filter(candidates, (t) => !isObjectOrArrayLiteralType(t)), [literalsType]);
      }
    }
    return candidates;
  }
  function getContravariantInference(inference) {
    return inference.priority & 416 /* 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 & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* 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 & (131072 /* Never */ | 1 /* 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 & 1 /* 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 & 2 /* 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 === 304 /* 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,
        111551 /* Value */ | 1048576 /* ExportValue */,
        getCannotFindNameDiagnosticForName(node),
        !isWriteOnlyAccess(node),
        /*excludeGlobals*/
        false
      ) || unknownSymbol;
    }
    return links.resolvedSymbol;
  }
  function isInAmbientOrTypeNode(node) {
    return !!(node.flags & 33554432 /* Ambient */ || findAncestor(node, (n) => isInterfaceDeclaration(n) || isTypeAliasDeclaration(n) || isTypeLiteralNode(n)));
  }
  function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
    switch (node.kind) {
      case 80 /* 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 110 /* ThisKeyword */:
        return `0|${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}`;
      case 235 /* NonNullExpression */:
      case 217 /* ParenthesizedExpression */:
        return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
      case 166 /* QualifiedName */:
        const left = getFlowCacheKey(node.left, declaredType, initialType, flowContainer);
        return left && `${left}.${node.right.escapedText}`;
      case 211 /* PropertyAccessExpression */:
      case 212 /* 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 206 /* ObjectBindingPattern */:
      case 207 /* ArrayBindingPattern */:
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 174 /* MethodDeclaration */:
        return `${getNodeId(node)}#${getTypeId(declaredType)}`;
    }
    return void 0;
  }
  function isMatchingReference(source, target) {
    switch (target.kind) {
      case 217 /* ParenthesizedExpression */:
      case 235 /* NonNullExpression */:
        return isMatchingReference(source, target.expression);
      case 226 /* BinaryExpression */:
        return isAssignmentExpression(target) && isMatchingReference(source, target.left) || isBinaryExpression(target) && target.operatorToken.kind === 28 /* CommaToken */ && isMatchingReference(source, target.right);
    }
    switch (source.kind) {
      case 236 /* MetaProperty */:
        return target.kind === 236 /* MetaProperty */ && source.keywordToken === target.keywordToken && source.name.escapedText === target.name.escapedText;
      case 80 /* Identifier */:
      case 81 /* PrivateIdentifier */:
        return isThisInTypeQuery(source) ? target.kind === 110 /* ThisKeyword */ : target.kind === 80 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || (isVariableDeclaration(target) || isBindingElement(target)) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfDeclaration(target);
      case 110 /* ThisKeyword */:
        return target.kind === 110 /* ThisKeyword */;
      case 108 /* SuperKeyword */:
        return target.kind === 108 /* SuperKeyword */;
      case 235 /* NonNullExpression */:
      case 217 /* ParenthesizedExpression */:
        return isMatchingReference(source.expression, target);
      case 211 /* PropertyAccessExpression */:
      case 212 /* 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 166 /* QualifiedName */:
        return isAccessExpression(target) && source.right.escapedText === getAccessedPropertyName(target) && isMatchingReference(source.left, target.expression);
      case 226 /* BinaryExpression */:
        return isBinaryExpression(source) && source.operatorToken.kind === 28 /* 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 & 8192 /* UniqueESSymbol */ ? type.escapedName : type.flags & 384 /* 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,
      111551 /* Value */,
      /*ignoreErrors*/
      true
    );
    if (!symbol || !(isConstantVariable(symbol) || symbol.flags & 8 /* 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 & 1048576 /* Union */) {
      const prop = getUnionOrIntersectionProperty(type, name);
      if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) {
        if (prop.links.isDiscriminantProperty === void 0) {
          prop.links.isDiscriminantProperty = (prop.links.checkFlags & 192 /* Discriminant */) === 192 /* 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 & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* 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) & 32768 /* PrimitiveUnion */ || countWhere(types, (t) => !!(t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */))) < 10) {
      return void 0;
    }
    if (unionType.keyPropertyName === void 0) {
      const keyPropertyName = forEach(types, (t) => t.flags & (524288 /* Object */ | 58982400 /* 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) {
    var _a;
    const result = (_a = unionType.constituentMap) == null ? void 0 : _a.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 === 303 /* 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 === 211 /* 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 & 1048576 /* 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 & 131072 /* 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 & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType;
    return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType;
  }
  function isFunctionObjectType(type) {
    if (getObjectFlags(type) & 256 /* EvolvingArray */) {
      return false;
    }
    const resolved = resolveStructuredTypeMembers(type);
    return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
  }
  function getTypeFacts(type, mask2) {
    return getTypeFactsWorker(type, mask2) & mask2;
  }
  function hasTypeFacts(type, mask2) {
    return getTypeFacts(type, mask2) !== 0;
  }
  function getTypeFactsWorker(type, callerOnlyNeeds) {
    if (type.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */)) {
      type = getBaseConstraintOfType(type) || unknownType;
    }
    const flags = type.flags;
    if (flags & (4 /* String */ | 268435456 /* StringMapping */)) {
      return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
    }
    if (flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */)) {
      const isEmpty = flags & 128 /* StringLiteral */ && type.value === "";
      return strictNullChecks ? isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
    }
    if (flags & (8 /* Number */ | 32 /* Enum */)) {
      return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
    }
    if (flags & 256 /* NumberLiteral */) {
      const isZero = type.value === 0;
      return strictNullChecks ? isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
    }
    if (flags & 64 /* BigInt */) {
      return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
    }
    if (flags & 2048 /* BigIntLiteral */) {
      const isZero = isZeroBigInt(type);
      return strictNullChecks ? isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
    }
    if (flags & 16 /* Boolean */) {
      return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
    }
    if (flags & 528 /* BooleanLike */) {
      return strictNullChecks ? type === falseType || type === regularFalseType ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : type === falseType || type === regularFalseType ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
    }
    if (flags & 524288 /* 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) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 83427327 /* EmptyObjectStrictFacts */ : 83886079 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728e3 /* FunctionFacts */ : strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
    }
    if (flags & 16384 /* Void */) {
      return 9830144 /* VoidFacts */;
    }
    if (flags & 32768 /* Undefined */) {
      return 26607360 /* UndefinedFacts */;
    }
    if (flags & 65536 /* Null */) {
      return 42917664 /* NullFacts */;
    }
    if (flags & 12288 /* ESSymbolLike */) {
      return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
    }
    if (flags & 67108864 /* NonPrimitive */) {
      return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
    }
    if (flags & 131072 /* Never */) {
      return 0 /* None */;
    }
    if (flags & 1048576 /* Union */) {
      return reduceLeft(type.types, (facts, t) => facts | getTypeFactsWorker(t, callerOnlyNeeds), 0 /* None */);
    }
    if (flags & 2097152 /* Intersection */) {
      return getIntersectionTypeFacts(type, callerOnlyNeeds);
    }
    return 83886079 /* UnknownFacts */;
  }
  function getIntersectionTypeFacts(type, callerOnlyNeeds) {
    const ignoreObjects = maybeTypeOfKind(type, 402784252 /* Primitive */);
    let oredFacts = 0 /* None */;
    let andedFacts = 134217727 /* All */;
    for (const t of type.types) {
      if (!(ignoreObjects && t.flags & 524288 /* 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 & 2 /* 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) {
    var _a;
    const nameType = getLiteralTypeFromPropertyName(name);
    if (!isTypeUsableAsPropertyName(nameType)) return errorType;
    const text = getPropertyNameFromType(nameType);
    return getTypeOfPropertyOfType(type, text) || includeUndefinedInIndexSignature((_a = getApplicableIndexInfoForName(type, text)) == null ? void 0 : _a.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 === 209 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || node.parent.kind === 303 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
    return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right);
  }
  function isDestructuringAssignmentTarget(parent2) {
    return parent2.parent.kind === 226 /* BinaryExpression */ && parent2.parent.left === parent2 || parent2.parent.kind === 250 /* ForOfStatement */ && parent2.parent.initializer === parent2;
  }
  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: parent2 } = node;
    switch (parent2.kind) {
      case 249 /* ForInStatement */:
        return stringType;
      case 250 /* ForOfStatement */:
        return checkRightHandSideOfForOf(parent2) || errorType;
      case 226 /* BinaryExpression */:
        return getAssignedTypeOfBinaryExpression(parent2);
      case 220 /* DeleteExpression */:
        return undefinedType;
      case 209 /* ArrayLiteralExpression */:
        return getAssignedTypeOfArrayLiteralElement(parent2, node);
      case 230 /* SpreadElement */:
        return getAssignedTypeOfSpreadExpression(parent2);
      case 303 /* PropertyAssignment */:
        return getAssignedTypeOfPropertyAssignment(parent2);
      case 304 /* ShorthandPropertyAssignment */:
        return getAssignedTypeOfShorthandPropertyAssignment(parent2);
    }
    return errorType;
  }
  function getInitialTypeOfBindingElement(node) {
    const pattern = node.parent;
    const parentType = getInitialType(pattern.parent);
    const type = pattern.kind === 206 /* 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 === 249 /* ForInStatement */) {
      return stringType;
    }
    if (node.parent.parent.kind === 250 /* ForOfStatement */) {
      return checkRightHandSideOfForOf(node.parent.parent) || errorType;
    }
    return errorType;
  }
  function getInitialType(node) {
    return node.kind === 260 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node);
  }
  function isEmptyArrayAssignment(node) {
    return node.kind === 260 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral2(node.initializer) || node.kind !== 208 /* BindingElement */ && node.parent.kind === 226 /* BinaryExpression */ && isEmptyArrayLiteral2(node.parent.right);
  }
  function getReferenceCandidate(node) {
    switch (node.kind) {
      case 217 /* ParenthesizedExpression */:
        return getReferenceCandidate(node.expression);
      case 226 /* BinaryExpression */:
        switch (node.operatorToken.kind) {
          case 64 /* EqualsToken */:
          case 76 /* BarBarEqualsToken */:
          case 77 /* AmpersandAmpersandEqualsToken */:
          case 78 /* QuestionQuestionEqualsToken */:
            return getReferenceCandidate(node.left);
          case 28 /* CommaToken */:
            return getReferenceCandidate(node.right);
        }
    }
    return node;
  }
  function getReferenceRoot(node) {
    const { parent: parent2 } = node;
    return parent2.kind === 217 /* ParenthesizedExpression */ || parent2.kind === 226 /* BinaryExpression */ && parent2.operatorToken.kind === 64 /* EqualsToken */ && parent2.left === node || parent2.kind === 226 /* BinaryExpression */ && parent2.operatorToken.kind === 28 /* CommaToken */ && parent2.right === node ? getReferenceRoot(parent2) : node;
  }
  function getTypeOfSwitchClause(clause) {
    if (clause.kind === 296 /* 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 === 296 /* CaseClause */ && !isStringLiteralLike(clause.expression))) {
      return void 0;
    }
    const witnesses = [];
    for (const clause of switchStatement.caseBlock.clauses) {
      const text = clause.kind === 296 /* CaseClause */ ? clause.expression.text : void 0;
      witnesses.push(text && !contains(witnesses, text) ? text : void 0);
    }
    return witnesses;
  }
  function eachTypeContainedIn(source, types) {
    return source.flags & 1048576 /* Union */ ? !forEach(source.types, (t) => !contains(types, t)) : contains(types, source);
  }
  function isTypeSubsetOf(source, target) {
    return !!(source === target || source.flags & 131072 /* Never */ || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target));
  }
  function isTypeSubsetOfUnion(source, target) {
    if (source.flags & 1048576 /* Union */) {
      for (const t of source.types) {
        if (!containsType(target.types, t)) {
          return false;
        }
      }
      return true;
    }
    if (source.flags & 1056 /* EnumLike */ && getBaseTypeOfEnumLikeType(source) === target) {
      return true;
    }
    return containsType(target.types, source);
  }
  function forEachType(type, f) {
    return type.flags & 1048576 /* Union */ ? forEach(type.types, f) : f(type);
  }
  function someType(type, f) {
    return type.flags & 1048576 /* Union */ ? some(type.types, f) : f(type);
  }
  function everyType(type, f) {
    return type.flags & 1048576 /* Union */ ? every(type.types, f) : f(type);
  }
  function everyContainedType(type, f) {
    return type.flags & 3145728 /* UnionOrIntersection */ ? every(type.types, f) : f(type);
  }
  function filterType(type, f) {
    if (type.flags & 1048576 /* 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 & 1048576 /* Union */) {
        const originTypes = origin.types;
        const originFiltered = filter(originTypes, (t) => !!(t.flags & 1048576 /* Union */) || f(t));
        if (originTypes.length - originFiltered.length === types.length - filtered.length) {
          if (originFiltered.length === 1) {
            return originFiltered[0];
          }
          newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered);
        }
      }
      return getUnionTypeFromSortedList(
        filtered,
        type.objectFlags & (32768 /* PrimitiveUnion */ | 16777216 /* ContainsIntersections */),
        /*aliasSymbol*/
        void 0,
        /*aliasTypeArguments*/
        void 0,
        newOrigin
      );
    }
    return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
  }
  function removeType(type, targetType) {
    return filterType(type, (t) => t !== targetType);
  }
  function countTypes(type) {
    return type.flags & 1048576 /* Union */ ? type.types.length : 1;
  }
  function mapType(type, mapper, noReductions) {
    if (type.flags & 131072 /* Never */) {
      return type;
    }
    if (!(type.flags & 1048576 /* Union */)) {
      return mapper(type);
    }
    const origin = type.origin;
    const types = origin && origin.flags & 1048576 /* Union */ ? origin.types : type.types;
    let mappedTypes;
    let changed = false;
    for (const t of types) {
      const mapped = t.flags & 1048576 /* Union */ ? mapType(t, mapper, noReductions) : mapper(t);
      changed || (changed = t !== mapped);
      if (mapped) {
        if (!mappedTypes) {
          mappedTypes = [mapped];
        } else {
          mappedTypes.push(mapped);
        }
      }
    }
    return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : type;
  }
  function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) {
    return type.flags & 1048576 /* Union */ && aliasSymbol ? getUnionType(map(type.types, mapper), 1 /* 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, 4 /* String */ | 134217728 /* TemplateLiteral */ | 8 /* Number */ | 64 /* BigInt */) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 256 /* NumberLiteral */ | 2048 /* BigIntLiteral */)) {
      return mapType(typeWithPrimitives, (t) => t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) : isPatternLiteralType(t) && !maybeTypeOfKind(typeWithLiterals, 4 /* String */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? extractTypesOfKind(typeWithLiterals, 128 /* StringLiteral */) : t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* 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 & 131072 /* Never */ ? silentNeverType : type } : type;
  }
  function createEvolvingArrayType(elementType) {
    const result = createObjectType(256 /* 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 & 131072 /* Never */ ? autoArrayType : createArrayType(
      elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType
    );
  }
  function getFinalArrayType(evolvingArrayType) {
    return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
  }
  function finalizeEvolvingArrayType(type) {
    return getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
  }
  function getElementTypeOfEvolvingArrayType(type) {
    return getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
  }
  function isEvolvingArrayTypeList(types) {
    let hasEvolvingArrayType = false;
    for (const t of types) {
      if (!(t.flags & 131072 /* Never */)) {
        if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) {
          return false;
        }
        hasEvolvingArrayType = true;
      }
    }
    return hasEvolvingArrayType;
  }
  function isEvolvingArrayOperationTarget(node) {
    const root = getReferenceRoot(node);
    const parent2 = root.parent;
    const isLengthPushOrUnshift = isPropertyAccessExpression(parent2) && (parent2.name.escapedText === "length" || parent2.parent.kind === 213 /* CallExpression */ && isIdentifier(parent2.name) && isPushOrUnshiftIdentifier(parent2.name));
    const isElementAssignment = parent2.kind === 212 /* ElementAccessExpression */ && parent2.expression === root && parent2.parent.kind === 226 /* BinaryExpression */ && parent2.parent.operatorToken.kind === 64 /* EqualsToken */ && parent2.parent.left === parent2 && !isAssignmentTarget(parent2.parent) && isTypeAssignableToKind(getTypeOfExpression(parent2.argumentExpression), 296 /* 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 & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
      return getTypeOfSymbol(symbol);
    }
    if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
      if (getCheckFlags(symbol) & 262144 /* 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 === 250 /* 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 & 67108864 /* InWithStatement */)) {
      switch (node.kind) {
        case 80 /* Identifier */:
          const symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
          return getExplicitTypeOfSymbol(symbol, diagnostic);
        case 110 /* ThisKeyword */:
          return getExplicitThisType(node);
        case 108 /* SuperKeyword */:
          return checkSuperExpression(node);
        case 211 /* 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 217 /* 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 === 244 /* ExpressionStatement */) {
        funcType = getTypeOfDottedName(
          node.expression,
          /*diagnostic*/
          void 0
        );
      } else if (node.expression.kind !== 108 /* 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, 0 /* 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 & 131072 /* Never */);
  }
  function getTypePredicateArgument(predicate, callExpression) {
    if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* 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 === 97 /* FalseKeyword */ || node.kind === 226 /* BinaryExpression */ && (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 57 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
  }
  function isReachableFlowNodeWorker(flow, noCacheCheck) {
    while (true) {
      if (flow === lastFlowNode) {
        return lastFlowNodeReachable;
      }
      const flags = flow.flags;
      if (flags & 4096 /* 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 & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
        flow = flow.antecedent;
      } else if (flags & 512 /* Call */) {
        const signature = getEffectsSignature(flow.node);
        if (signature) {
          const predicate = getTypePredicateOfSignature(signature);
          if (predicate && predicate.kind === 3 /* AssertsIdentifier */ && !predicate.type) {
            const predicateArgument = flow.node.arguments[predicate.parameterIndex];
            if (predicateArgument && isFalseExpression(predicateArgument)) {
              return false;
            }
          }
          if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
            return false;
          }
        }
        flow = flow.antecedent;
      } else if (flags & 4 /* BranchLabel */) {
        return some(flow.antecedent, (f) => isReachableFlowNodeWorker(
          f,
          /*noCacheCheck*/
          false
        ));
      } else if (flags & 8 /* LoopLabel */) {
        const antecedents = flow.antecedent;
        if (antecedents === void 0 || antecedents.length === 0) {
          return false;
        }
        flow = antecedents[0];
      } else if (flags & 128 /* SwitchClause */) {
        const data = flow.node;
        if (data.clauseStart === data.clauseEnd && isExhaustiveSwitchStatement(data.switchStatement)) {
          return false;
        }
        flow = flow.antecedent;
      } else if (flags & 1024 /* 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 & 1 /* Unreachable */);
      }
    }
  }
  function isPostSuperFlowNode(flow, noCacheCheck) {
    while (true) {
      const flags = flow.flags;
      if (flags & 4096 /* 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 & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */ | 128 /* SwitchClause */)) {
        flow = flow.antecedent;
      } else if (flags & 512 /* Call */) {
        if (flow.node.expression.kind === 108 /* SuperKeyword */) {
          return true;
        }
        flow = flow.antecedent;
      } else if (flags & 4 /* BranchLabel */) {
        return every(flow.antecedent, (f) => isPostSuperFlowNode(
          f,
          /*noCacheCheck*/
          false
        ));
      } else if (flags & 8 /* LoopLabel */) {
        flow = flow.antecedent[0];
      } else if (flags & 1024 /* 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 & 1 /* Unreachable */);
      }
    }
  }
  function isConstantReference(node) {
    switch (node.kind) {
      case 110 /* ThisKeyword */:
        return true;
      case 80 /* Identifier */:
        if (!isThisInTypeQuery(node)) {
          const symbol = getResolvedSymbol(node);
          return isConstantVariable(symbol) || isParameterOrMutableLocalVariable(symbol) && !isSymbolAssigned(symbol) || !!symbol.valueDeclaration && isFunctionExpression(symbol.valueDeclaration);
        }
        break;
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        return isConstantReference(node.expression) && isReadonlySymbol(getNodeLinks(node).resolvedSymbol || unknownSymbol);
      case 206 /* ObjectBindingPattern */:
      case 207 /* ArrayBindingPattern */:
        const rootDeclaration = getRootDeclaration(node.parent);
        return isParameter(rootDeclaration) || isCatchClauseVariableDeclaration(rootDeclaration) ? !isSomeSymbolAssigned(rootDeclaration) : isVariableDeclaration(rootDeclaration) && isVarConstLike2(rootDeclaration);
    }
    return false;
  }
  function getFlowTypeOfReference(reference, declaredType, initialType = declaredType, flowContainer, flowNode = ((_a) => (_a = tryCast(reference, canHaveFlowNode)) == null ? void 0 : _a.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) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
    if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 235 /* NonNullExpression */ && !(resultType.flags & 131072 /* Never */) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
      return declaredType;
    }
    return resultType;
    function getOrSetCacheKey() {
      if (isKeySet) {
        return key;
      }
      isKeySet = true;
      return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
    }
    function getTypeAtFlowNode(flow) {
      var _a2;
      if (flowDepth === 2e3) {
        (_a2 = tracing) == null ? void 0 : _a2.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 & 4096 /* Shared */) {
          for (let i = sharedFlowStart; i < sharedFlowCount; i++) {
            if (sharedFlowNodes[i] === flow) {
              flowDepth--;
              return sharedFlowTypes[i];
            }
          }
          sharedFlow = flow;
        }
        let type;
        if (flags & 16 /* Assignment */) {
          type = getTypeAtFlowAssignment(flow);
          if (!type) {
            flow = flow.antecedent;
            continue;
          }
        } else if (flags & 512 /* Call */) {
          type = getTypeAtFlowCall(flow);
          if (!type) {
            flow = flow.antecedent;
            continue;
          }
        } else if (flags & 96 /* Condition */) {
          type = getTypeAtFlowCondition(flow);
        } else if (flags & 128 /* SwitchClause */) {
          type = getTypeAtSwitchClause(flow);
        } else if (flags & 12 /* Label */) {
          if (flow.antecedent.length === 1) {
            flow = flow.antecedent[0];
            continue;
          }
          type = flags & 4 /* BranchLabel */ ? getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow);
        } else if (flags & 256 /* ArrayMutation */) {
          type = getTypeAtFlowArrayMutation(flow);
          if (!type) {
            flow = flow.antecedent;
            continue;
          }
        } else if (flags & 1024 /* 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 & 2 /* Start */) {
          const container = flow.node;
          if (container && container !== flowContainer && reference.kind !== 211 /* PropertyAccessExpression */ && reference.kind !== 212 /* ElementAccessExpression */ && !(reference.kind === 110 /* ThisKeyword */ && container.kind !== 219 /* 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 === 260 /* VariableDeclaration */ || node.kind === 208 /* 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) === 2 /* 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 & 1048576 /* Union */) {
          return getAssignmentReducedType(t, getInitialOrAssignedType(flow));
        }
        return t;
      }
      if (containsMatchingReference(reference, node)) {
        if (!isReachableFlowNode(flow)) {
          return unreachableNeverType;
        }
        if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConstLike2(node))) {
          const init = getDeclaredExpandoInitializer(node);
          if (init && (init.kind === 218 /* FunctionExpression */ || init.kind === 219 /* ArrowFunction */)) {
            return getTypeAtFlowNode(flow.antecedent);
          }
        }
        return declaredType;
      }
      if (isVariableDeclaration(node) && node.parent.parent.kind === 249 /* 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 === 97 /* FalseKeyword */) {
        return unreachableNeverType;
      }
      if (node.kind === 226 /* BinaryExpression */) {
        if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */) {
          return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
        }
        if (node.operatorToken.kind === 57 /* 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 === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
          const flowType = getTypeAtFlowNode(flow.antecedent);
          const type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
          const narrowedType = predicate.type ? narrowTypeByTypePredicate(
            type,
            predicate,
            flow.node,
            /*assumeTrue*/
            true
          ) : predicate.kind === 3 /* 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 & 131072 /* Never */) {
          return unreachableNeverType;
        }
      }
      return void 0;
    }
    function getTypeAtFlowArrayMutation(flow) {
      if (declaredType === autoType || declaredType === autoArrayType) {
        const node = flow.node;
        const expr = node.kind === 213 /* CallExpression */ ? node.expression.expression : node.left.expression;
        if (isMatchingReference(reference, getReferenceCandidate(expr))) {
          const flowType = getTypeAtFlowNode(flow.antecedent);
          const type = getTypeFromFlowType(flowType);
          if (getObjectFlags(type) & 256 /* EvolvingArray */) {
            let evolvedType2 = type;
            if (node.kind === 213 /* CallExpression */) {
              for (const arg of node.arguments) {
                evolvedType2 = addEvolvingArrayElementType(evolvedType2, arg);
              }
            } else {
              const indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
              if (isTypeAssignableToKind(indexType, 296 /* 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 & 131072 /* Never */) {
        return flowType;
      }
      const assumeTrue = (flow.flags & 32 /* 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 === 221 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
        type = narrowTypeBySwitchOnTypeOf(type, flow.node);
      } else if (expr.kind === 112 /* TrueKeyword */) {
        type = narrowTypeBySwitchOnTrue(type, flow.node);
      } else {
        if (strictNullChecks) {
          if (optionalChainContainsReference(expr, reference)) {
            type = narrowTypeBySwitchOptionalChainContainment(type, flow.node, (t) => !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)));
          } else if (expr.kind === 221 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
            type = narrowTypeBySwitchOptionalChainContainment(type, flow.node, (t) => !(t.flags & 131072 /* Never */ || t.flags & 128 /* 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 & 128 /* 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 & 131072 /* 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 ? 2 /* Subtype */ : 1 /* 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], 1 /* 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 ? 2 /* Subtype */ : 1 /* 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 & 1048576 /* 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 parent2 = declaration.parent.parent;
            if (isVariableDeclaration(parent2) && !parent2.type && parent2.initializer && (isIdentifier(parent2.initializer) || isAccessExpression(parent2.initializer)) && isMatchingReference(reference, parent2.initializer)) {
              return declaration;
            }
          }
        }
      }
      return void 0;
    }
    function getDiscriminantPropertyAccess(expr, computedType) {
      if (declaredType.flags & 1048576 /* Union */ || computedType.flags & 1048576 /* Union */) {
        const access = getCandidateDiscriminantPropertyAccess(expr);
        if (access) {
          const name = getAccessedPropertyName(access);
          if (name) {
            const type = declaredType.flags & 1048576 /* 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, 98304 /* 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 & 131072 /* Never */) && !(narrowedPropType.flags & 131072 /* Never */) && areTypesComparable(narrowedPropType, discriminantType);
      });
    }
    function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) {
      if ((operator === 37 /* EqualsEqualsEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */) && type.flags & 1048576 /* Union */) {
        const keyPropertyName = getKeyPropertyName(type);
        if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) {
          const candidate = getConstituentTypeForKeyType(type, getTypeOfExpression(value));
          if (candidate) {
            return operator === (assumeTrue ? 37 /* EqualsEqualsEqualsToken */ : 38 /* 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 & 1048576 /* 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 & 16777216 /* Optional */ || getCheckFlags(prop) & 48 /* 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 === 112 /* TrueKeyword */) !== (operator !== 38 /* ExclamationEqualsEqualsToken */ && operator !== 36 /* ExclamationEqualsToken */);
      return narrowType(type, expr, assumeTrue);
    }
    function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
      switch (expr.operatorToken.kind) {
        case 64 /* EqualsToken */:
        case 76 /* BarBarEqualsToken */:
        case 77 /* AmpersandAmpersandEqualsToken */:
        case 78 /* QuestionQuestionEqualsToken */:
          return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
        case 35 /* EqualsEqualsToken */:
        case 36 /* ExclamationEqualsToken */:
        case 37 /* EqualsEqualsEqualsToken */:
        case 38 /* ExclamationEqualsEqualsToken */:
          const operator = expr.operatorToken.kind;
          const left = getReferenceCandidate(expr.left);
          const right = getReferenceCandidate(expr.right);
          if (left.kind === 221 /* TypeOfExpression */ && isStringLiteralLike(right)) {
            return narrowTypeByTypeof(type, left, operator, right, assumeTrue);
          }
          if (right.kind === 221 /* 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 104 /* InstanceOfKeyword */:
          return narrowTypeByInstanceof(type, expr, assumeTrue);
        case 103 /* 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 28 /* 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 56 /* 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 57 /* 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 === 35 /* EqualsEqualsToken */ || operator === 37 /* EqualsEqualsEqualsToken */;
      const nullableFlags = operator === 35 /* EqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
      const valueType = getTypeOfExpression(value);
      const removeNullable = equalsOperator !== assumeTrue && everyType(valueType, (t) => !!(t.flags & nullableFlags)) || equalsOperator === assumeTrue && everyType(valueType, (t) => !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)));
      return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
    }
    function narrowTypeByEquality(type, operator, value, assumeTrue) {
      if (type.flags & 1 /* Any */) {
        return type;
      }
      if (operator === 36 /* ExclamationEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */) {
        assumeTrue = !assumeTrue;
      }
      const valueType = getTypeOfExpression(value);
      const doubleEquals = operator === 35 /* EqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */;
      if (valueType.flags & 98304 /* Nullable */) {
        if (!strictNullChecks) {
          return type;
        }
        const facts = doubleEquals ? assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : valueType.flags & 65536 /* Null */ ? assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
        return getAdjustedTypeWithFacts(type, facts);
      }
      if (assumeTrue) {
        if (!doubleEquals && (type.flags & 2 /* Unknown */ || someType(type, isEmptyAnonymousObjectType))) {
          if (valueType.flags & (402784252 /* Primitive */ | 67108864 /* NonPrimitive */) || isEmptyAnonymousObjectType(valueType)) {
            return valueType;
          }
          if (valueType.flags & 524288 /* 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 === 36 /* ExclamationEqualsToken */ || operator === 38 /* 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 & 2 /* Unknown */ && !hasDefaultClause) {
        let groundClauseTypes;
        for (let i = 0; i < clauseTypes.length; i += 1) {
          const t = clauseTypes[i];
          if (t.flags & (402784252 /* Primitive */ | 67108864 /* NonPrimitive */)) {
            if (groundClauseTypes !== void 0) {
              groundClauseTypes.push(t);
            }
          } else if (t.flags & 524288 /* 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 & 131072 /* 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 & 32768 /* Undefined */ ? undefinedType : getRegularTypeOfLiteralType(extractUnitType(t)))));
      return caseType.flags & 131072 /* 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 & 1 /* Any */ ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, 32 /* TypeofEQObject */), narrowTypeByTypeFacts(type, nullType, 131072 /* EQNull */)]);
        case "function":
          return type.flags & 1 /* 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 === 297 /* 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 === 297 /* 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 === 296 /* 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 === 296 /* 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 === 296 /* 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 !== 35 /* EqualsEqualsToken */ && operator !== 37 /* EqualsEqualsEqualsToken */ : operator !== 36 /* ExclamationEqualsToken */ && operator !== 38 /* 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 & 524288 /* Object */ && getObjectFlags(source) & 1 /* Class */ || target.flags & 524288 /* Object */ && getObjectFlags(target) & 1 /* 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 === 1 /* 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 & 524288 /* 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, 1 /* Construct */);
      if (constructSignatures.length) {
        return getUnionType(map(constructSignatures, (signature) => getReturnTypeOfSignature(getErasedSignature(signature))));
      }
      return emptyObjectType;
    }
    function getNarrowedType(type, candidate, assumeTrue, checkDerived) {
      const key2 = type.flags & 1048576 /* 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 & 3 /* AnyOrUnknown */) {
        return candidate;
      }
      if (type === candidate) {
        return candidate;
      }
      const isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf;
      const keyPropertyName = type.flags & 1048576 /* 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 & 131072 /* Never */ ? mapType(type, (t) => maybeTypeOfKind(t, 465829888 /* Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType) : directlyRelated;
      });
      return !(narrowedType.flags & 131072 /* 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 === 0 /* This */ || predicate.kind === 1 /* 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 === 61 /* QuestionQuestionToken */ || expr.parent.operatorToken.kind === 78 /* QuestionQuestionEqualsToken */) && expr.parent.left === expr) {
        return narrowTypeByOptionality(type, expr, assumeTrue);
      }
      switch (expr.kind) {
        case 80 /* 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 110 /* ThisKeyword */:
        case 108 /* SuperKeyword */:
        case 211 /* PropertyAccessExpression */:
        case 212 /* ElementAccessExpression */:
          return narrowTypeByTruthiness(type, expr, assumeTrue);
        case 213 /* CallExpression */:
          return narrowTypeByCallExpression(type, expr, assumeTrue);
        case 217 /* ParenthesizedExpression */:
        case 235 /* NonNullExpression */:
          return narrowType(type, expr.expression, assumeTrue);
        case 226 /* BinaryExpression */:
          return narrowTypeByBinaryExpression(type, expr, assumeTrue);
        case 224 /* PrefixUnaryExpression */:
          if (expr.operator === 54 /* 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 === 80 /* Identifier */ || location.kind === 81 /* PrivateIdentifier */) {
      if (isRightSideOfQualifiedNameOrPropertyAccess(location)) {
        location = location.parent;
      }
      if (isExpressionNode(location) && (!isAssignmentTarget(location) || isWriteAccess(location))) {
        const type = removeOptionalTypeMarker(
          isWriteAccess(location) && location.kind === 211 /* 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 === 268 /* ModuleBlock */ || node2.kind === 307 /* SourceFile */ || node2.kind === 172 /* PropertyDeclaration */);
  }
  function isSymbolAssignedDefinitely(symbol) {
    if (symbol.lastAssignmentPos !== void 0) {
      return symbol.lastAssignmentPos < 0;
    }
    return isSymbolAssigned(symbol) && symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0;
  }
  function isSymbolAssigned(symbol) {
    return !isPastLastAssignment(
      symbol,
      /*location*/
      void 0
    );
  }
  function isPastLastAssignment(symbol, location) {
    const parent2 = findAncestor(symbol.valueDeclaration, isFunctionOrSourceFile);
    if (!parent2) {
      return false;
    }
    const links = getNodeLinks(parent2);
    if (!(links.flags & 131072 /* AssignmentsMarked */)) {
      links.flags |= 131072 /* AssignmentsMarked */;
      if (!hasParentWithAssignmentsMarked(parent2)) {
        markNodeAssignments(parent2);
      }
    }
    return !symbol.lastAssignmentPos || location && Math.abs(symbol.lastAssignmentPos) < location.pos;
  }
  function isSomeSymbolAssigned(rootDeclaration) {
    Debug.assert(isVariableDeclaration(rootDeclaration) || isParameter(rootDeclaration));
    return isSomeSymbolAssignedWorker(rootDeclaration.name);
  }
  function isSomeSymbolAssignedWorker(node) {
    if (node.kind === 80 /* Identifier */) {
      return isSymbolAssigned(getSymbolOfDeclaration(node.parent));
    }
    return some(node.elements, (e) => e.kind !== 232 /* OmittedExpression */ && isSomeSymbolAssignedWorker(e.name));
  }
  function hasParentWithAssignmentsMarked(node) {
    return !!findAncestor(node.parent, (node2) => isFunctionOrSourceFile(node2) && !!(getNodeLinks(node2).flags & 131072 /* AssignmentsMarked */));
  }
  function isFunctionOrSourceFile(node) {
    return isFunctionLikeDeclaration(node) || isSourceFile(node);
  }
  function markNodeAssignments(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        const assigmentTarget = getAssignmentTargetKind(node);
        if (assigmentTarget !== 0 /* None */) {
          const symbol = getResolvedSymbol(node);
          const hasDefiniteAssignment = assigmentTarget === 1 /* Definite */ || symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0;
          if (isParameterOrMutableLocalVariable(symbol)) {
            if (symbol.lastAssignmentPos === void 0 || Math.abs(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;
            }
            if (hasDefiniteAssignment && symbol.lastAssignmentPos > 0) {
              symbol.lastAssignmentPos *= -1;
            }
          }
        }
        return;
      case 281 /* ExportSpecifier */:
        const exportDeclaration = node.parent.parent;
        const name = node.propertyName || node.name;
        if (!node.isTypeOnly && !exportDeclaration.isTypeOnly && !exportDeclaration.moduleSpecifier && name.kind !== 11 /* StringLiteral */) {
          const symbol = resolveEntityName(
            name,
            111551 /* Value */,
            /*ignoreErrors*/
            true,
            /*dontResolveAlias*/
            true
          );
          if (symbol && isParameterOrMutableLocalVariable(symbol)) {
            const sign = symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0 ? -1 : 1;
            symbol.lastAssignmentPos = sign * Number.MAX_VALUE;
          }
        }
        return;
      case 264 /* InterfaceDeclaration */:
      case 265 /* TypeAliasDeclaration */:
      case 266 /* 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 243 /* VariableStatement */:
        case 244 /* ExpressionStatement */:
        case 245 /* IfStatement */:
        case 246 /* DoStatement */:
        case 247 /* WhileStatement */:
        case 248 /* ForStatement */:
        case 249 /* ForInStatement */:
        case 250 /* ForOfStatement */:
        case 254 /* WithStatement */:
        case 255 /* SwitchStatement */:
        case 258 /* TryStatement */:
        case 263 /* ClassDeclaration */:
          pos = node.end;
      }
      node = node.parent;
    }
    return pos;
  }
  function isConstantVariable(symbol) {
    return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 6 /* 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 & 1 /* Let */) && !(getCombinedModifierFlags(declaration) & 32 /* Export */ || declaration.parent.parent.kind === 243 /* 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 ?? (links.parameterInitializerContainsUndefined = containsUndefined);
    }
    return links.parameterInitializerContainsUndefined;
  }
  function removeOptionalityFromDeclaredType(declaredType, declaration) {
    const removeUndefined = strictNullChecks && declaration.kind === 169 /* Parameter */ && declaration.initializer && hasTypeFacts(declaredType, 16777216 /* IsUndefined */) && !parameterInitializerContainsUndefined(declaration);
    return removeUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
  }
  function isConstraintPosition(type, node) {
    const parent2 = node.parent;
    return parent2.kind === 211 /* PropertyAccessExpression */ || parent2.kind === 166 /* QualifiedName */ || parent2.kind === 213 /* CallExpression */ && parent2.expression === node || parent2.kind === 214 /* NewExpression */ && parent2.expression === node || parent2.kind === 212 /* ElementAccessExpression */ && parent2.expression === node && !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent2.argumentExpression)));
  }
  function isGenericTypeWithUnionConstraint(type) {
    return type.flags & 2097152 /* Intersection */ ? some(type.types, isGenericTypeWithUnionConstraint) : !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */));
  }
  function isGenericTypeWithoutNullableConstraint(type) {
    return type.flags & 2097152 /* Intersection */ ? some(type.types, isGenericTypeWithoutNullableConstraint) : !!(type.flags & 465829888 /* Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* 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 */ ? getContextualType2(node, 8 /* SkipBindingPatterns */) : getContextualType2(
      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 parent2 = n.parent;
      if (parent2 === void 0) {
        return "quit";
      }
      if (isExportAssignment(parent2)) {
        return parent2.expression === n && isEntityNameExpression(n);
      }
      if (isExportSpecifier(parent2)) {
        return parent2.name === n || parent2.propertyName === n;
      }
      return false;
    });
  }
  function markLinkedReferences(location, hint, propSymbol, parentType) {
    if (!canCollectSymbolAliasAccessabilityData) {
      return;
    }
    if (location.flags & 33554432 /* 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 !== 0 /* 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 & 8 /* EnumMember */ && location.parent.kind === 306 /* EnumMember */))) {
      markAliasReferenced(parentSymbol, location);
    }
    return;
  }
  function markExportAssignmentAliasReferenced(location) {
    if (isIdentifier(location.expression)) {
      const id = location.expression;
      const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName(
        id,
        -1 /* All */,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true,
        location
      ));
      if (sym) {
        markAliasReferenced(sym, id);
      }
    }
  }
  function markJsxAliasReferenced(node) {
    if (!getJsxNamespaceContainerForImplicitImport(node)) {
      const jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? Diagnostics.This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found : void 0;
      const jsxFactoryNamespace = getJsxNamespace(node);
      const jsxFactoryLocation = isJsxOpeningLikeElement(node) ? node.tagName : node;
      const shouldFactoryRefErr = compilerOptions.jsx !== 1 /* Preserve */ && compilerOptions.jsx !== 3 /* ReactNative */;
      let jsxFactorySym;
      if (!(isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) {
        jsxFactorySym = resolveName(
          jsxFactoryLocation,
          jsxFactoryNamespace,
          shouldFactoryRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */,
          jsxFactoryRefErr,
          /*isUse*/
          true
        );
      }
      if (jsxFactorySym) {
        jsxFactorySym.isReferenced = -1 /* All */;
        if (canCollectSymbolAliasAccessabilityData && jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) {
          markAliasSymbolAsReferenced(jsxFactorySym);
        }
      }
      if (isJsxOpeningFragment(node)) {
        const file = getSourceFileOfNode(node);
        const localJsxNamespace = getLocalJsxNamespace(file);
        if (localJsxNamespace) {
          resolveName(
            jsxFactoryLocation,
            localJsxNamespace,
            shouldFactoryRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */,
            jsxFactoryRefErr,
            /*isUse*/
            true
          );
        }
      }
    }
    return;
  }
  function markAsyncFunctionAliasReferenced(location) {
    if (languageVersion < 2 /* ES2015 */) {
      if (getFunctionFlags(location) & 2 /* Async */) {
        const returnTypeNode = getEffectiveReturnTypeNode(location);
        markTypeNodeAsReferenced(returnTypeNode);
      }
    }
  }
  function markImportEqualsAliasReferenced(location) {
    if (hasSyntacticModifier(location, 32 /* 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 === 11 /* StringLiteral */) {
        return;
      }
      const symbol = resolveName(
        exportedName,
        exportedName.escapedText,
        111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* 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 & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
        if (!target || getSymbolFlags(target) & 111551 /* Value */) {
          markExportAsReferenced(location);
          markIdentifierAliasReferenced(exportedName);
        }
      }
      return;
    }
  }
  function markDecoratorAliasReferenced(node) {
    if (compilerOptions.emitDecoratorMetadata) {
      const firstDecorator = find(node.modifiers, isDecorator);
      if (!firstDecorator) {
        return;
      }
      checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
      switch (node.kind) {
        case 263 /* ClassDeclaration */:
          const constructor = getFirstConstructorWithBody(node);
          if (constructor) {
            for (const parameter of constructor.parameters) {
              markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
            }
          }
          break;
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
          const otherKind = node.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */;
          const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(node), otherKind);
          markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
          break;
        case 174 /* MethodDeclaration */:
          for (const parameter of node.parameters) {
            markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
          }
          markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(node));
          break;
        case 172 /* PropertyDeclaration */:
          markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveTypeAnnotationNode(node));
          break;
        case 169 /* 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*/
      111551 /* Value */
    ) && !isInTypeQuery(location)) {
      const target = resolveAlias(symbol);
      if (getSymbolFlags(
        symbol,
        /*excludeTypeOnlyMeanings*/
        true
      ) & (111551 /* Value */ | 1048576 /* 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)) & 111551 /* 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
      ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target);
      if (markAlias) {
        markAliasSymbolAsReferenced(symbol);
      }
    }
  }
  function markEntityNameOrEntityExpressionAsReference(typeName, forDecoratorMetadata) {
    if (!typeName) return;
    const rootName = getFirstIdentifier(typeName);
    const meaning = (typeName.kind === 80 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
    const rootSymbol = resolveName(
      rootName,
      rootName.escapedText,
      meaning,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
    if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */) {
      if (canCollectSymbolAliasAccessabilityData && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) && !getTypeOnlyAliasDeclaration(rootSymbol)) {
        markAliasSymbolAsReferenced(rootSymbol);
      } else if (forDecoratorMetadata && getIsolatedModules(compilerOptions) && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */ && !symbolIsValue(rootSymbol) && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) {
        const diag2 = error2(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(diag2, 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) {
    var _a;
    const type = getTypeOfSymbol(symbol);
    const declaration = symbol.valueDeclaration;
    if (declaration) {
      if (isBindingElement(declaration) && !declaration.initializer && !declaration.dotDotDotToken && declaration.parent.elements.length >= 2) {
        const parent2 = declaration.parent.parent;
        const rootDeclaration = getRootDeclaration(parent2);
        if (rootDeclaration.kind === 260 /* VariableDeclaration */ && getCombinedNodeFlagsCached(rootDeclaration) & 6 /* Constant */ || rootDeclaration.kind === 169 /* Parameter */) {
          const links = getNodeLinks(parent2);
          if (!(links.flags & 4194304 /* InCheckIdentifier */)) {
            links.flags |= 4194304 /* InCheckIdentifier */;
            const parentType = getTypeForBindingElementParent(parent2, 0 /* Normal */);
            const parentTypeConstraint = parentType && mapType(parentType, getBaseConstraintOrType);
            links.flags &= ~4194304 /* InCheckIdentifier */;
            if (parentTypeConstraint && parentTypeConstraint.flags & 1048576 /* Union */ && !(rootDeclaration.kind === 169 /* Parameter */ && isSomeSymbolAssigned(rootDeclaration))) {
              const pattern = declaration.parent;
              const narrowedType = getFlowTypeOfReference(
                pattern,
                parentTypeConstraint,
                parentTypeConstraint,
                /*flowContainer*/
                void 0,
                location.flowNode
              );
              if (narrowedType.flags & 131072 /* 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]), (_a = getInferenceContext(func)) == null ? void 0 : _a.nonFixingMapper));
            if (restType.flags & 1048576 /* 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)) {
        error2(node, Diagnostics.arguments_cannot_be_referenced_in_property_initializers);
        return;
      }
      let container = getContainingFunction(node);
      if (container) {
        if (languageVersion < 2 /* ES2015 */) {
          if (container.kind === 219 /* ArrowFunction */) {
            error2(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_function_expression);
          } else if (hasSyntacticModifier(container, 1024 /* Async */)) {
            error2(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 |= 512 /* CaptureArguments */;
        while (container && isArrowFunction(container)) {
          container = getContainingFunction(container);
          if (container) {
            getNodeLinks(container).flags |= 512 /* 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 & 32 /* Class */) {
      if (isClassLike(declaration) && declaration.name !== node) {
        let container = getThisContainer(
          node,
          /*includeArrowFunctions*/
          false,
          /*includeClassComputedPropertyName*/
          false
        );
        while (container.kind !== 307 /* SourceFile */ && container.parent !== declaration) {
          container = getThisContainer(
            container,
            /*includeArrowFunctions*/
            false,
            /*includeClassComputedPropertyName*/
            false
          );
        }
        if (container.kind !== 307 /* SourceFile */) {
          getNodeLinks(declaration).flags |= 262144 /* ContainsConstructorReference */;
          getNodeLinks(container).flags |= 262144 /* ContainsConstructorReference */;
          getNodeLinks(node).flags |= 536870912 /* 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;
    const immediateDeclaration = declaration;
    if (declaration && declaration.kind === 208 /* BindingElement */ && contains(contextualBindingPatterns, declaration.parent) && findAncestor(node, (parent2) => parent2 === declaration.parent)) {
      return nonInferrableAnyType;
    }
    let type = getNarrowedTypeOfSymbol(localOrExportSymbol, node);
    const assignmentKind = getAssignmentTargetKind(node);
    if (assignmentKind) {
      if (!(localOrExportSymbol.flags & 3 /* Variable */) && !(isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
        const assignmentError = localOrExportSymbol.flags & 384 /* Enum */ ? Diagnostics.Cannot_assign_to_0_because_it_is_an_enum : localOrExportSymbol.flags & 32 /* Class */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_class : localOrExportSymbol.flags & 1536 /* Module */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace : localOrExportSymbol.flags & 16 /* Function */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_function : localOrExportSymbol.flags & 2097152 /* Alias */ ? Diagnostics.Cannot_assign_to_0_because_it_is_an_import : Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable;
        error2(node, assignmentError, symbolToString(symbol));
        return errorType;
      }
      if (isReadonlySymbol(localOrExportSymbol)) {
        if (localOrExportSymbol.flags & 3 /* Variable */) {
          error2(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
        } else {
          error2(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
        }
        return errorType;
      }
    }
    const isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
    if (localOrExportSymbol.flags & 3 /* Variable */) {
      if (assignmentKind === 1 /* 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 === 169 /* 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 & 134217728 /* ModuleExports */;
    const typeIsAutomatic = type === autoType || type === autoArrayType;
    const isAutomaticTypeInNonNull = typeIsAutomatic && node.parent.kind === 235 /* NonNullExpression */;
    while (flowContainer !== declarationContainer && (flowContainer.kind === 218 /* FunctionExpression */ || flowContainer.kind === 219 /* ArrowFunction */ || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstantVariable(localOrExportSymbol) && type !== autoArrayType || isParameterOrMutableLocalVariable(localOrExportSymbol) && isPastLastAssignment(localOrExportSymbol, node))) {
      flowContainer = getControlFlowContainer(flowContainer);
    }
    const isNeverInitialized = immediateDeclaration && isVariableDeclaration(immediateDeclaration) && !immediateDeclaration.initializer && !immediateDeclaration.exclamationToken && isMutableLocalVariableDeclaration(immediateDeclaration) && !isSymbolAssignedDefinitely(symbol);
    const assumeInitialized = isParameter2 || isAlias || isOuterVariable && !isNeverInitialized || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 281 /* ExportSpecifier */) || node.parent.kind === 235 /* NonNullExpression */ || declaration.kind === 260 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 33554432 /* 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) {
          error2(getNameOfDeclaration(declaration), Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType));
          error2(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
        }
        return convertAutoToAny(flowType);
      }
    } else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) {
      error2(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) {
    var _a;
    const parent2 = node.parent;
    if (parent2) {
      if (isPropertyAccessExpression(parent2) && parent2.expression === node) {
        return false;
      }
      if (isExportSpecifier(parent2) && parent2.isTypeOnly) {
        return false;
      }
      const greatGrandparent = (_a = parent2.parent) == null ? void 0 : _a.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 >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || !symbol.valueDeclaration || isSourceFile(symbol.valueDeclaration) || symbol.valueDeclaration.parent.kind === 299 /* 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, 261 /* VariableDeclarationList */);
          if (varDeclList && varDeclList.parent === container) {
            const part = getPartOfForStatementContainingNode(node.parent, container);
            if (part) {
              const links = getNodeLinks(part);
              links.flags |= 8192 /* ContainsCapturedBlockScopeBinding */;
              const capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
              pushIfUnique(capturedBindings, symbol);
              if (part === container.initializer) {
                capturesBlockScopeBindingInLoopBody = false;
              }
            }
          }
        }
        if (capturesBlockScopeBindingInLoopBody) {
          getNodeLinks(enclosingIterationStatement).flags |= 4096 /* LoopWithCapturedBlockScopedBinding */;
        }
      }
      if (isForStatement(container)) {
        const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */);
        if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
          getNodeLinks(symbol.valueDeclaration).flags |= 65536 /* NeedsLoopOutParameter */;
        }
      }
      getNodeLinks(symbol.valueDeclaration).flags |= 32768 /* BlockScopedBindingInLoop */;
    }
    if (isCaptured) {
      getNodeLinks(symbol.valueDeclaration).flags |= 16384 /* 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 === 217 /* ParenthesizedExpression */) {
      current = current.parent;
    }
    let isAssigned = false;
    if (isAssignmentTarget(current)) {
      isAssigned = true;
    } else if (current.parent.kind === 224 /* PrefixUnaryExpression */ || current.parent.kind === 225 /* PostfixUnaryExpression */) {
      const expr = current.parent;
      isAssigned = expr.operator === 46 /* PlusPlusToken */ || expr.operator === 47 /* MinusMinusToken */;
    }
    if (!isAssigned) {
      return false;
    }
    return !!findAncestor(current, (n) => n === container ? "quit" : n === container.statement);
  }
  function captureLexicalThis(node, container) {
    getNodeLinks(node).flags |= 2 /* LexicalThis */;
    if (container.kind === 172 /* PropertyDeclaration */ || container.kind === 176 /* Constructor */) {
      const classNode = container.parent;
      getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
    } else {
      getNodeLinks(container).flags |= 4 /* 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
      )) {
        error2(node, diagnosticMessage);
      }
    }
  }
  function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) {
    if (isPropertyDeclaration(container) && hasStaticModifier(container) && legacyDecorators && container.initializer && textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && hasDecorators(container.parent)) {
      error2(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 === 176 /* Constructor */) {
      checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
    }
    while (true) {
      if (container.kind === 219 /* ArrowFunction */) {
        container = getThisContainer(
          container,
          /*includeArrowFunctions*/
          false,
          !thisInComputedPropertyName
        );
        capturedByArrowFunction = true;
      }
      if (container.kind === 167 /* ComputedPropertyName */) {
        container = getThisContainer(
          container,
          !capturedByArrowFunction,
          /*includeClassComputedPropertyName*/
          false
        );
        thisInComputedPropertyName = true;
        continue;
      }
      break;
    }
    checkThisInStaticClassFieldInitializerInDecoratedClass(node, container);
    if (thisInComputedPropertyName) {
      error2(node, Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
    } else {
      switch (container.kind) {
        case 267 /* ModuleDeclaration */:
          error2(node, Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
          break;
        case 266 /* EnumDeclaration */:
          error2(node, Diagnostics.this_cannot_be_referenced_in_current_location);
          break;
      }
    }
    if (!isNodeInTypeQuery && capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
      captureLexicalThis(node, container);
    }
    const type = tryGetThisTypeAt(
      node,
      /*includeGlobalThis*/
      true,
      container
    );
    if (noImplicitThis) {
      const globalThisType2 = getTypeOfSymbol(globalThisSymbol);
      if (type === globalThisType2 && capturedByArrowFunction) {
        error2(node, Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
      } else if (!type) {
        const diag2 = error2(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(diag2, 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 & 16 /* Function */) {
            thisType = getDeclaredTypeOfSymbol(classSymbol).thisType;
          }
        } else if (isJSConstructor(container)) {
          thisType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
        }
        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 === 218 /* FunctionExpression */ && isBinaryExpression(container.parent) && getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
      return container.parent.left.expression.expression;
    } else if (container.kind === 174 /* MethodDeclaration */ && container.parent.kind === 210 /* ObjectLiteralExpression */ && isBinaryExpression(container.parent.parent) && getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
      return container.parent.parent.left.expression;
    } else if (container.kind === 218 /* FunctionExpression */ && container.parent.kind === 303 /* PropertyAssignment */ && container.parent.parent.kind === 210 /* ObjectLiteralExpression */ && isBinaryExpression(container.parent.parent.parent) && getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
      return container.parent.parent.parent.left.expression;
    } else if (container.kind === 218 /* 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) === 9 /* 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) === 9 /* 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 === 169 /* Parameter */ && n.parent === constructorDecl);
  }
  function checkSuperExpression(node) {
    const isCallExpression2 = node.parent.kind === 213 /* 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 === 219 /* ArrowFunction */) {
        if (hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true;
        container = getSuperContainer(
          container,
          /*stopOnFunctions*/
          true
        );
        needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
      }
      if (container && hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true;
    }
    let nodeCheckFlag = 0;
    if (!container || !isLegalUsageOfSuperExpression(container)) {
      const current = findAncestor(node, (n) => n === container ? "quit" : n.kind === 167 /* ComputedPropertyName */);
      if (current && current.kind === 167 /* ComputedPropertyName */) {
        error2(node, Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
      } else if (isCallExpression2) {
        error2(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 === 210 /* ObjectLiteralExpression */)) {
        error2(node, Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
      } else {
        error2(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 === 176 /* 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 = 32 /* SuperStatic */;
      if (!isCallExpression2 && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container))) {
        forEachEnclosingBlockScopeContainer(node.parent, (current) => {
          if (!isSourceFile(current) || isExternalOrCommonJsModule(current)) {
            getNodeLinks(current).flags |= 2097152 /* ContainsSuperPropertyInStaticInitializer */;
          }
        });
      }
    } else {
      nodeCheckFlag = 16 /* SuperInstance */;
    }
    getNodeLinks(node).flags |= nodeCheckFlag;
    if (container.kind === 174 /* MethodDeclaration */ && inAsyncFunction) {
      if (isSuperProperty(node.parent) && isAssignmentTarget(node.parent)) {
        getNodeLinks(container).flags |= 256 /* MethodWithSuperPropertyAssignmentInAsync */;
      } else {
        getNodeLinks(container).flags |= 128 /* MethodWithSuperPropertyAccessInAsync */;
      }
    }
    if (needToCaptureLexicalThis) {
      captureLexicalThis(node.parent, container);
    }
    if (container.parent.kind === 210 /* ObjectLiteralExpression */) {
      if (languageVersion < 2 /* ES2015 */) {
        error2(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)) {
      error2(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 === 176 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
      error2(node, Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
      return errorType;
    }
    return nodeCheckFlag === 32 /* SuperStatic */ ? getBaseConstructorTypeOfClass(classType) : getTypeWithThisArgument(baseClassType, classType.thisType);
    function isLegalUsageOfSuperExpression(container2) {
      if (isCallExpression2) {
        return container2.kind === 176 /* Constructor */;
      } else {
        if (isClassLike(container2.parent) || container2.parent.kind === 210 /* ObjectLiteralExpression */) {
          if (isStatic(container2)) {
            return container2.kind === 174 /* MethodDeclaration */ || container2.kind === 173 /* MethodSignature */ || container2.kind === 177 /* GetAccessor */ || container2.kind === 178 /* SetAccessor */ || container2.kind === 172 /* PropertyDeclaration */ || container2.kind === 175 /* ClassStaticBlockDeclaration */;
          } else {
            return container2.kind === 174 /* MethodDeclaration */ || container2.kind === 173 /* MethodSignature */ || container2.kind === 177 /* GetAccessor */ || container2.kind === 178 /* SetAccessor */ || container2.kind === 172 /* PropertyDeclaration */ || container2.kind === 171 /* PropertySignature */ || container2.kind === 176 /* Constructor */;
          }
        }
      }
      return false;
    }
  }
  function getContainingObjectLiteral(func) {
    return (func.kind === 174 /* MethodDeclaration */ || func.kind === 177 /* GetAccessor */ || func.kind === 178 /* SetAccessor */) && func.parent.kind === 210 /* ObjectLiteralExpression */ ? func.parent : func.kind === 218 /* FunctionExpression */ && func.parent.kind === 303 /* PropertyAssignment */ ? func.parent.parent : void 0;
  }
  function getThisTypeArgument(type) {
    return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : void 0;
  }
  function getThisTypeFromContextualType(type) {
    return mapType(type, (t) => {
      return t.flags & 2097152 /* 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 !== 303 /* PropertyAssignment */) {
        break;
      }
      literal = literal.parent.parent;
      type = getApparentTypeOfContextualType(
        literal,
        /*contextFlags*/
        void 0
      );
    }
  }
  function getContextualThisParameterType(func) {
    if (func.kind === 219 /* 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 parent2 = walkUpParenthesizedExpressions(func.parent);
      if (isAssignmentExpression(parent2)) {
        const target = parent2.left;
        if (isAccessExpression(target)) {
          const { expression } = target;
          if (inJs && isIdentifier(expression)) {
            const sourceFile = getSourceFileOfNode(parent2);
            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 169 /* Parameter */:
        return getContextuallyTypedParameterType(declaration);
      case 208 /* BindingElement */:
        return getContextualTypeForBindingElement(declaration, contextFlags);
      case 172 /* PropertyDeclaration */:
        if (isStatic(declaration)) {
          return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags);
        }
    }
  }
  function getContextualTypeForBindingElement(declaration, contextFlags) {
    const parent2 = declaration.parent.parent;
    const name = declaration.propertyName || declaration.name;
    const parentType = getContextualTypeForVariableLikeDeclaration(parent2, contextFlags) || parent2.kind !== 208 /* BindingElement */ && parent2.initializer && checkDeclarationInitializer(parent2, declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */);
    if (!parentType || isBindingPattern(name) || isComputedNonLiteralName(name)) return void 0;
    if (parent2.name.kind === 207 /* 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) && getContextualType2(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 & 8 /* 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 & 1 /* Generator */) {
          const isAsyncGenerator = (functionFlags & 2 /* Async */) !== 0;
          if (contextualReturnType.flags & 1048576 /* Union */) {
            contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator));
          }
          const iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
          if (!iterationReturnType) {
            return void 0;
          }
          contextualReturnType = iterationReturnType;
        }
        if (functionFlags & 2 /* Async */) {
          const contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeNoAlias);
          return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
        }
        return contextualReturnType;
      }
    }
    return void 0;
  }
  function getContextualTypeForAwaitOperand(node, contextFlags) {
    const contextualType = getContextualType2(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 & 2 /* Async */) !== 0;
        if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* Union */) {
          contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator));
        }
        if (node.asteriskToken) {
          const iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(contextualReturnType, isAsyncGenerator);
          const yieldType = (iterationTypes == null ? void 0 : iterationTypes.yieldType) ?? silentNeverType;
          const returnType = getContextualType2(node, contextFlags) ?? silentNeverType;
          const nextType = (iterationTypes == null ? void 0 : 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) & 2 /* 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 & 1 /* Generator */) {
        return filterType(returnType2, (t) => {
          return !!(t.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 58982400 /* InstantiableNonPrimitive */)) || checkGeneratorInstantiationAssignabilityToReturnType(
            t,
            functionFlags,
            /*errorNode*/
            void 0
          );
        });
      }
      if (functionFlags & 2 /* Async */) {
        return filterType(returnType2, (t) => {
          return !!(t.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 58982400 /* InstantiableNonPrimitive */)) || !!getAwaitedTypeOfPromise(t);
        });
      }
      return returnType2;
    }
    const iife = getImmediatelyInvokedFunctionExpression(functionDecl);
    if (iife) {
      return getContextualType2(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), 256 /* 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 === 215 /* 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 64 /* EqualsToken */:
      case 77 /* AmpersandAmpersandEqualsToken */:
      case 76 /* BarBarEqualsToken */:
      case 78 /* QuestionQuestionEqualsToken */:
        return node === right ? getContextualTypeForAssignmentDeclaration(binaryExpression) : void 0;
      case 57 /* BarBarToken */:
      case 61 /* QuestionQuestionToken */:
        const type = getContextualType2(binaryExpression, contextFlags);
        return node === right && (type && type.pattern || !type && !isDefaultedExpandoInitializer(binaryExpression)) ? getTypeOfExpression(left) : type;
      case 56 /* AmpersandAmpersandToken */:
      case 28 /* CommaToken */:
        return node === right ? getContextualType2(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) {
    var _a, _b;
    const kind = getAssignmentDeclarationKind(binaryExpression);
    switch (kind) {
      case 0 /* None */:
      case 4 /* 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 === 0 /* None */) {
          return getTypeOfExpression(binaryExpression.left);
        }
        return getContextualTypeForThisPropertyAssignment(binaryExpression);
      case 5 /* 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,
              111551 /* 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 1 /* ExportsProperty */:
      case 6 /* Prototype */:
      case 3 /* PrototypeProperty */:
      case 2 /* ModuleExports */:
        let valueDeclaration;
        if (kind !== 2 /* ModuleExports */) {
          valueDeclaration = canHaveSymbol(binaryExpression.left) ? (_a = binaryExpression.left.symbol) == null ? void 0 : _a.valueDeclaration : void 0;
        }
        valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) == null ? void 0 : _b.valueDeclaration);
        const annotated = valueDeclaration && getEffectiveTypeAnnotationNode(valueDeclaration);
        return annotated ? getTypeFromTypeNode(annotated) : void 0;
      case 7 /* ObjectDefinePropertyValue */:
      case 8 /* ObjectDefinePropertyExports */:
      case 9 /* ObjectDefinePrototypeProperty */:
        return Debug.fail("Does not apply");
      default:
        return Debug.assertNever(kind);
    }
  }
  function isPossiblyAliasedThisProperty(declaration, kind = getAssignmentDeclarationKind(declaration)) {
    if (kind === 4 /* ThisProperty */) {
      return true;
    }
    if (!isInJSFile(declaration) || kind !== 5 /* Property */ || !isIdentifier(declaration.left.expression)) {
      return false;
    }
    const name = declaration.left.expression.escapedText;
    const symbol = resolveName(
      declaration.left,
      name,
      111551 /* Value */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true,
      /*excludeGlobals*/
      true
    );
    return isThisInitializedDeclaration(symbol == null ? void 0 : 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) & 262144 /* Mapped */ && !symbol.links.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
  }
  function isExcludedMappedPropertyName(constraint, propertyNameType) {
    if (constraint.flags & 16777216 /* Conditional */) {
      const type = constraint;
      return !!(getReducedType(getTrueTypeFromConditionalType(type)).flags & 131072 /* Never */) && getActualTypeVariable(getFalseTypeFromConditionalType(type)) === getActualTypeVariable(type.checkType) && isTypeAssignableTo(propertyNameType, type.extendsType);
    }
    if (constraint.flags & 2097152 /* Intersection */) {
      return some(constraint.types, (t) => isExcludedMappedPropertyName(t, propertyNameType));
    }
    return false;
  }
  function getTypeOfPropertyOfContextualType(type, name, nameType) {
    return mapType(
      type,
      (t) => {
        if (t.flags & 2097152 /* Intersection */) {
          let types;
          let indexInfoCandidates;
          let ignoreIndexInfos = false;
          for (const constituentType of t.types) {
            if (!(constituentType.flags & 524288 /* Object */)) {
              continue;
            }
            if (isGenericMappedType(constituentType) && getMappedTypeNameTypeKind(constituentType) !== 2 /* Remapping */) {
              const substitutedType = getIndexedMappedTypeSubstitutedTypeOfContextualType(constituentType, name, nameType);
              types = appendContextualPropertyTypeConstituent(types, substitutedType);
              continue;
            }
            const propertyType = getTypeOfConcretePropertyOfContextualType(constituentType, name);
            if (!propertyType) {
              if (!ignoreIndexInfos) {
                indexInfoCandidates = append(indexInfoCandidates, constituentType);
              }
              continue;
            }
            ignoreIndexInfos = true;
            indexInfoCandidates = void 0;
            types = appendContextualPropertyTypeConstituent(types, propertyType);
          }
          if (indexInfoCandidates) {
            for (const candidate of indexInfoCandidates) {
              const indexInfoType = getTypeFromIndexInfosOfContextualType(candidate, name, nameType);
              types = appendContextualPropertyTypeConstituent(types, indexInfoType);
            }
          }
          if (!types) {
            return;
          }
          if (types.length === 1) {
            return types[0];
          }
          return getIntersectionType(types);
        }
        if (!(t.flags & 524288 /* Object */)) {
          return;
        }
        return isGenericMappedType(t) && getMappedTypeNameTypeKind(t) !== 2 /* Remapping */ ? getIndexedMappedTypeSubstitutedTypeOfContextualType(t, name, nameType) : getTypeOfConcretePropertyOfContextualType(t, name) ?? getTypeFromIndexInfosOfContextualType(t, name, nameType);
      },
      /*noReductions*/
      true
    );
  }
  function appendContextualPropertyTypeConstituent(types, type) {
    return type ? append(types, type.flags & 1 /* Any */ ? unknownType : type) : types;
  }
  function getIndexedMappedTypeSubstitutedTypeOfContextualType(type, name, nameType) {
    const propertyNameType = nameType || getStringLiteralType(unescapeLeadingUnderscores(name));
    const constraint = getConstraintTypeFromMappedType(type);
    if (type.nameType && isExcludedMappedPropertyName(type.nameType, propertyNameType) || isExcludedMappedPropertyName(constraint, propertyNameType)) {
      return;
    }
    const constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
    if (!isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
      return;
    }
    return substituteIndexedMappedType(type, propertyNameType);
  }
  function getTypeOfConcretePropertyOfContextualType(type, name) {
    const prop = getPropertyOfType(type, name);
    if (!prop || isCircularMappedProperty(prop)) {
      return;
    }
    return removeMissingType(getTypeOfSymbol(prop), !!(prop.flags & 16777216 /* Optional */));
  }
  function getTypeFromIndexInfosOfContextualType(type, name, nameType) {
    var _a;
    if (isTupleType(type) && isNumericLiteralName(name) && +name >= 0) {
      const restType = getElementTypeOfSliceOfTupleType(
        type,
        type.target.fixedLength,
        /*endSkipCount*/
        0,
        /*writing*/
        false,
        /*noReductions*/
        true
      );
      if (restType) {
        return restType;
      }
    }
    return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(type), nameType || getStringLiteralType(unescapeLeadingUnderscores(name)))) == null ? void 0 : _a.type;
  }
  function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
    Debug.assert(isObjectLiteralMethod(node));
    if (node.flags & 67108864 /* 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) => {
            var _a;
            return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType)) == null ? void 0 : _a.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 ?? (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] && 2 /* Optional */));
          }
          const offset = length2 !== void 0 && (lastSpreadIndex === void 0 || index > lastSpreadIndex) ? length2 - index : 0;
          const fixedEndLength = offset > 0 && t.target.combinedFlags & 12 /* Variable */ ? getEndElementCount(t.target, 3 /* 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 ? getContextualType2(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) ? getContextualType2(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 getContextualType2(attribute.parent, contextFlags);
    }
  }
  function isPossiblyDiscriminantValue(node) {
    switch (node.kind) {
      case 11 /* StringLiteral */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 228 /* TemplateExpression */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 106 /* NullKeyword */:
      case 80 /* Identifier */:
      case 157 /* UndefinedKeyword */:
        return true;
      case 211 /* PropertyAccessExpression */:
      case 217 /* ParenthesizedExpression */:
        return isPossiblyDiscriminantValue(node.expression);
      case 294 /* 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 === 303 /* PropertyAssignment */) {
                return isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName);
              }
              if (p.kind === 304 /* ShorthandPropertyAssignment */) {
                return isDiscriminantProperty(contextualType, p.symbol.escapedName);
              }
              return false;
            }),
            (prop) => [() => getContextFreeTypeOfExpression(prop.kind === 303 /* PropertyAssignment */ ? prop.initializer : prop.name), prop.symbol.escapedName]
          ),
          map(
            filter(getPropertiesOfType(contextualType), (s) => {
              var _a;
              return !!(s.flags & 16777216 /* Optional */) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.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 === 291 /* 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) => {
              var _a;
              if (!(s.flags & 16777216 /* Optional */) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.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) : getContextualType2(node, contextFlags);
    const instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
    if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* 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) & 32 /* Mapped */ ? t : getApparentType(t),
        /*noReductions*/
        true
      );
      return apparentType.flags & 1048576 /* Union */ && isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : apparentType.flags & 1048576 /* Union */ && isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : apparentType;
    }
  }
  function instantiateContextualType(contextualType, node, contextFlags) {
    if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* Instantiable */)) {
      const inferenceContext = getInferenceContext(node);
      if (inferenceContext && contextFlags & 1 /* Signature */ && some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) {
        return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
      }
      if (inferenceContext == null ? void 0 : inferenceContext.returnMapper) {
        const type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
        return type.flags & 1048576 /* 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 & 465829888 /* Instantiable */) {
      return instantiateType(type, mapper);
    }
    if (type.flags & 1048576 /* Union */) {
      return getUnionType(map(type.types, (t) => instantiateInstantiableTypes(t, mapper)), 0 /* None */);
    }
    if (type.flags & 2097152 /* Intersection */) {
      return getIntersectionType(map(type.types, (t) => instantiateInstantiableTypes(t, mapper)));
    }
    return type;
  }
  function getContextualType2(node, contextFlags) {
    var _a;
    if (node.flags & 67108864 /* InWithStatement */) {
      return void 0;
    }
    const index = findContextualNode(
      node,
      /*includeCaches*/
      !contextFlags
    );
    if (index >= 0) {
      return contextualTypes[index];
    }
    const { parent: parent2 } = node;
    switch (parent2.kind) {
      case 260 /* VariableDeclaration */:
      case 169 /* Parameter */:
      case 172 /* PropertyDeclaration */:
      case 171 /* PropertySignature */:
      case 208 /* BindingElement */:
        return getContextualTypeForInitializerExpression(node, contextFlags);
      case 219 /* ArrowFunction */:
      case 253 /* ReturnStatement */:
        return getContextualTypeForReturnExpression(node, contextFlags);
      case 229 /* YieldExpression */:
        return getContextualTypeForYieldOperand(parent2, contextFlags);
      case 223 /* AwaitExpression */:
        return getContextualTypeForAwaitOperand(parent2, contextFlags);
      case 213 /* CallExpression */:
      case 214 /* NewExpression */:
        return getContextualTypeForArgument(parent2, node);
      case 170 /* Decorator */:
        return getContextualTypeForDecorator(parent2);
      case 216 /* TypeAssertionExpression */:
      case 234 /* AsExpression */:
        return isConstTypeReference(parent2.type) ? getContextualType2(parent2, contextFlags) : getTypeFromTypeNode(parent2.type);
      case 226 /* BinaryExpression */:
        return getContextualTypeForBinaryOperand(node, contextFlags);
      case 303 /* PropertyAssignment */:
      case 304 /* ShorthandPropertyAssignment */:
        return getContextualTypeForObjectLiteralElement(parent2, contextFlags);
      case 305 /* SpreadAssignment */:
        return getContextualType2(parent2.parent, contextFlags);
      case 209 /* ArrayLiteralExpression */: {
        const arrayLiteral = parent2;
        const type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
        const elementIndex = indexOfNode(arrayLiteral.elements, node);
        const spreadIndices = (_a = getNodeLinks(arrayLiteral)).spreadIndices ?? (_a.spreadIndices = getSpreadIndices(arrayLiteral.elements));
        return getContextualTypeForElementExpression(type, elementIndex, arrayLiteral.elements.length, spreadIndices.first, spreadIndices.last);
      }
      case 227 /* ConditionalExpression */:
        return getContextualTypeForConditionalOperand(node, contextFlags);
      case 239 /* TemplateSpan */:
        Debug.assert(parent2.parent.kind === 228 /* TemplateExpression */);
        return getContextualTypeForSubstitutionExpression(parent2.parent, node);
      case 217 /* ParenthesizedExpression */: {
        if (isInJSFile(parent2)) {
          if (isJSDocSatisfiesExpression(parent2)) {
            return getTypeFromTypeNode(getJSDocSatisfiesExpressionType(parent2));
          }
          const typeTag = getJSDocTypeTag(parent2);
          if (typeTag && !isConstTypeReference(typeTag.typeExpression.type)) {
            return getTypeFromTypeNode(typeTag.typeExpression.type);
          }
        }
        return getContextualType2(parent2, contextFlags);
      }
      case 235 /* NonNullExpression */:
        return getContextualType2(parent2, contextFlags);
      case 238 /* SatisfiesExpression */:
        return getTypeFromTypeNode(parent2.type);
      case 277 /* ExportAssignment */:
        return tryGetTypeFromEffectiveTypeNode(parent2);
      case 294 /* JsxExpression */:
        return getContextualTypeForJsxExpression(parent2, contextFlags);
      case 291 /* JsxAttribute */:
      case 293 /* JsxSpreadAttribute */:
        return getContextualTypeForJsxAttribute(parent2, contextFlags);
      case 286 /* JsxOpeningElement */:
      case 285 /* JsxSelfClosingElement */:
        return getContextualJsxElementAttributesType(parent2, contextFlags);
      case 301 /* ImportAttribute */:
        return getContextualImportAttributeType(parent2);
    }
    return void 0;
  }
  function pushCachedContextualType(node) {
    pushContextualType(
      node,
      getContextualType2(
        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 !== 4 /* Completions */) {
      const index = findContextualNode(
        node.parent,
        /*includeCaches*/
        !contextFlags
      );
      if (index >= 0) {
        return contextualTypes[index];
      }
    }
    return getContextualTypeForArgumentAtIndex(node, 0);
  }
  function getEffectiveFirstArgumentForJsxSignature(signature, node) {
    return isJsxOpeningFragment(node) || getJsxReferenceKind(node) !== 0 /* 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 (isJsxOpeningFragment(context)) return getJSXFragmentType(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 & 128 /* 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)) {
        error2(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(
        1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0),
        paramName || `arg${i}`,
        isRestParam ? 32768 /* RestParameter */ : isOptional ? 16384 /* OptionalParameter */ : 0
      );
      paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
      params[i] = paramSymbol;
    }
    if (needsExtraRestElement) {
      const restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args", 32768 /* 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 combineSignaturesOfIntersectionMembers(left, right) {
    const typeParams = left.typeParameters || right.typeParameters;
    let paramMapper;
    if (left.typeParameters && right.typeParameters) {
      paramMapper = createTypeMapper(right.typeParameters, left.typeParameters);
    }
    let flags = (left.flags | right.flags) & (167 /* PropagatingFlags */ & ~1 /* HasRestParameter */);
    const declaration = left.declaration;
    const params = combineIntersectionParameters(left, right, paramMapper);
    const lastParam = lastOrUndefined(params);
    if (lastParam && getCheckFlags(lastParam) & 32768 /* RestParameter */) {
      flags |= 1 /* HasRestParameter */;
    }
    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,
      flags
    );
    result.compositeKind = 2097152 /* Intersection */;
    result.compositeSignatures = concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]);
    if (paramMapper) {
      result.mapper = left.compositeKind === 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper;
    }
    return result;
  }
  function getContextualCallSignature(type, node) {
    const signatures = getSignaturesOfType(type, 0 /* 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 !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node));
    const typeTagSignature = getSignatureOfTypeTag(node);
    if (typeTagSignature) {
      return typeTagSignature;
    }
    const type = getApparentTypeOfContextualType(node, 1 /* Signature */);
    if (!type) {
      return void 0;
    }
    if (!(type.flags & 1048576 /* 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;
      scanner2 ?? (scanner2 = createScanner(
        99 /* ESNext */,
        /*skipTrivia*/
        true
      ));
      scanner2.setScriptTarget(sourceFile.languageVersion);
      scanner2.setLanguageVariant(sourceFile.languageVariant);
      scanner2.setOnError((message, length2, arg0) => {
        const start = scanner2.getTokenEnd();
        if (message.category === 3 /* Message */ && lastError && start === lastError.start && length2 === lastError.length) {
          const error3 = createDetachedDiagnostic(sourceFile.fileName, sourceFile.text, start, length2, message, arg0);
          addRelatedInfo(lastError, error3);
        } else if (!lastError || start !== lastError.start) {
          lastError = createFileDiagnostic(sourceFile, start, length2, message, arg0);
          diagnostics.add(lastError);
        }
      });
      scanner2.setText(sourceFile.text, node.pos, node.end - node.pos);
      try {
        scanner2.scan();
        Debug.assert(scanner2.reScanSlashToken(
          /*reportErrors*/
          true
        ) === 14 /* RegularExpressionLiteral */, "Expected scanner to rescan RegularExpressionLiteral");
        return !!lastError;
      } finally {
        scanner2.setText("");
        scanner2.setOnError(
          /*onError*/
          void 0
        );
      }
    }
    return false;
  }
  function checkRegularExpressionLiteral(node) {
    const nodeLinks2 = getNodeLinks(node);
    if (!(nodeLinks2.flags & 1 /* TypeChecked */)) {
      nodeLinks2.flags |= 1 /* TypeChecked */;
      addLazyDiagnostic(() => checkGrammarRegularExpressionLiteral(node));
    }
    return globalRegExpType;
  }
  function checkSpreadExpression(node, checkMode) {
    if (languageVersion < LanguageFeatureMinimumTarget.SpreadElements) {
      checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* 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 === 208 /* BindingElement */ && !!node.initializer || node.kind === 303 /* PropertyAssignment */ && hasDefaultValue(node.initializer) || node.kind === 304 /* ShorthandPropertyAssignment */ && !!node.objectAssignmentInitializer || node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */;
  }
  function isSpreadIntoCallOrNew(node) {
    const parent2 = walkUpParenthesizedExpressions(node.parent);
    return isSpreadElement(parent2) && isCallOrNewExpression(parent2.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 === 230 /* SpreadElement */) {
        if (languageVersion < LanguageFeatureMinimumTarget.SpreadElements) {
          checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */);
        }
        const spreadType = checkExpression(e.expression, checkMode, forceTuple);
        if (isArrayLikeType(spreadType)) {
          elementTypes.push(spreadType);
          elementFlags.push(8 /* 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(4 /* Rest */);
        } else {
          elementTypes.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, e.expression));
          elementFlags.push(4 /* Rest */);
        }
      } else if (exactOptionalPropertyTypes && e.kind === 232 /* OmittedExpression */) {
        hasOmittedExpression = true;
        elementTypes.push(undefinedOrMissingType);
        elementFlags.push(2 /* Optional */);
      } else {
        const type = checkExpressionForMutableLocation(e, checkMode, forceTuple);
        elementTypes.push(addOptionality(
          type,
          /*isProperty*/
          true,
          hasOmittedExpression
        ));
        elementFlags.push(hasOmittedExpression ? 2 /* Optional */ : 1 /* 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] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t), 2 /* Subtype */) : strictNullChecks ? implicitNeverType : undefinedWideningType,
      inConstContext
    ));
  }
  function createArrayLiteralType(type) {
    if (!(getObjectFlags(type) & 4 /* Reference */)) {
      return type;
    }
    let literalType = type.literalType;
    if (!literalType) {
      literalType = type.literalType = cloneTypeReference(type);
      literalType.objectFlags |= 16384 /* ArrayLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */;
    }
    return literalType;
  }
  function isNumericName(name) {
    switch (name.kind) {
      case 167 /* ComputedPropertyName */:
        return isNumericComputedName(name);
      case 80 /* Identifier */:
        return isNumericLiteralName(name.escapedText);
      case 9 /* NumericLiteral */:
      case 11 /* StringLiteral */:
        return isNumericLiteralName(name.text);
      default:
        return false;
    }
  }
  function isNumericComputedName(name) {
    return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* 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 === 103 /* InKeyword */ && node.parent.kind !== 177 /* GetAccessor */ && node.parent.kind !== 178 /* 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 |= 4096 /* LoopWithCapturedBlockScopedBinding */;
          getNodeLinks(node).flags |= 32768 /* BlockScopedBindingInLoop */;
          getNodeLinks(node.parent.parent).flags |= 32768 /* BlockScopedBindingInLoop */;
        }
      }
      if (links.resolvedType.flags & 98304 /* Nullable */ || !isTypeAssignableToKind(links.resolvedType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
        error2(node, Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
      }
    }
    return links.resolvedType;
  }
  function isSymbolWithNumericName(symbol) {
    var _a;
    const firstDecl = (_a = symbol.declarations) == null ? void 0 : _a[0];
    return isNumericLiteralName(symbol.escapedName) || firstDecl && isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name);
  }
  function isSymbolWithSymbolName(symbol) {
    var _a;
    const firstDecl = (_a = symbol.declarations) == null ? void 0 : _a[0];
    return isKnownSymbol(symbol) || firstDecl && isNamedDeclaration(firstDecl) && isComputedPropertyName(firstDecl.name) && isTypeAssignableToKind(checkComputedPropertyName(firstDecl.name), 4096 /* ESSymbol */);
  }
  function getObjectLiteralIndexInfo(isReadonly, 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, 2 /* Subtype */) : undefinedType;
    return createIndexInfo(keyType, unionType, isReadonly);
  }
  function getImmediateAliasedSymbol(symbol) {
    Debug.assert((symbol.flags & 2097152 /* 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 === 206 /* ObjectBindingPattern */ || contextualType.pattern.kind === 210 /* ObjectLiteralExpression */);
    const inConstContext = isConstContext(node);
    const checkFlags = inConstContext ? 8 /* Readonly */ : 0;
    const isInJavascript = isInJSFile(node) && !isInJsonFile(node);
    const enumTag = isInJavascript ? getJSDocEnumTag(node) : void 0;
    const isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
    let objectFlags = 8192 /* 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 === 167 /* ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : void 0;
      if (memberDecl.kind === 303 /* PropertyAssignment */ || memberDecl.kind === 304 /* ShorthandPropertyAssignment */ || isObjectLiteralMethod(memberDecl)) {
        let type = memberDecl.kind === 303 /* 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 === 304 /* 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) & 458752 /* PropagatingFlags */;
        const nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : void 0;
        const prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
        if (nameType) {
          prop.links.nameType = nameType;
        }
        if (inDestructuringPattern && hasDefaultValue(memberDecl)) {
          prop.flags |= 16777216 /* Optional */;
        } else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
          const impliedProp = getPropertyOfType(contextualType, member.escapedName);
          if (impliedProp) {
            prop.flags |= impliedProp.flags & 16777216 /* Optional */;
          } else if (!getIndexInfoOfType(contextualType, stringType)) {
            error2(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 == null ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
        if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === 303 /* PropertyAssignment */ || memberDecl.kind === 174 /* MethodDeclaration */) && isContextSensitive(memberDecl)) {
          const inferenceContext = getInferenceContext(node);
          Debug.assert(inferenceContext);
          const inferenceNode = memberDecl.kind === 303 /* PropertyAssignment */ ? memberDecl.initializer : memberDecl;
          addIntraExpressionInferenceSite(inferenceContext, inferenceNode, type);
        }
      } else if (memberDecl.kind === 305 /* SpreadAssignment */) {
        if (languageVersion < LanguageFeatureMinimumTarget.ObjectAssign) {
          checkExternalEmitHelpers(memberDecl, 2 /* 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 {
          error2(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types);
          spread = errorType;
        }
        continue;
      } else {
        Debug.assert(memberDecl.kind === 177 /* GetAccessor */ || memberDecl.kind === 178 /* SetAccessor */);
        checkNodeDeferred(memberDecl);
      }
      if (computedNameType && !(computedNameType.flags & 8576 /* 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 = [];
      const isReadonly = isConstContext(node);
      if (hasComputedStringProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, stringType));
      if (hasComputedNumberProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, numberType));
      if (hasComputedSymbolProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, esSymbolType));
      const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, indexInfos);
      result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */;
      if (isJSObjectLiteral) {
        result.objectFlags |= 4096 /* JSLiteral */;
      }
      if (patternWithComputedProperties) {
        result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
      }
      if (inDestructuringPattern) {
        result.pattern = node;
      }
      return result;
    }
  }
  function isValidSpreadType(type) {
    const t = removeDefinitelyFalsyTypes(mapType(type, getBaseConstraintOrType));
    return !!(t.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || t.flags & 3145728 /* 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")) {
      error2(
        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);
    const jsxElementType = getJsxElementTypeAt(node);
    return isErrorType(jsxElementType) ? anyType : jsxElementType;
  }
  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 allAttributesTable = strictNullChecks ? createSymbolTable() : void 0;
    let attributesTable = createSymbolTable();
    let spread = emptyJsxObjectType;
    let hasSpreadAnyType = false;
    let typeToIntersect;
    let explicitlySpecifyChildrenAttribute = false;
    let objectFlags = 2048 /* JsxAttributes */;
    const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
    const isJsxOpenFragment = isJsxOpeningFragment(openingLikeElement);
    let attributesSymbol;
    let attributeParent = openingLikeElement;
    if (!isJsxOpenFragment) {
      const attributes = openingLikeElement.attributes;
      attributesSymbol = attributes.symbol;
      attributeParent = attributes;
      const contextualType = getContextualType2(attributes, 0 /* None */);
      for (const attributeDecl of attributes.properties) {
        const member = attributeDecl.symbol;
        if (isJsxAttribute(attributeDecl)) {
          const exprType = checkJsxAttribute(attributeDecl, checkMode);
          objectFlags |= getObjectFlags(exprType) & 458752 /* PropagatingFlags */;
          const attributeSymbol = createSymbol(4 /* 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 == null ? void 0 : 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 === 293 /* JsxSpreadAttribute */);
          if (attributesTable.size > 0) {
            spread = getSpreadType(
              spread,
              createJsxAttributesTypeHelper(),
              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 {
            error2(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,
            createJsxAttributesTypeHelper(),
            attributes.symbol,
            objectFlags,
            /*readonly*/
            false
          );
        }
      }
    }
    const parent2 = openingLikeElement.parent;
    if ((isJsxElement(parent2) && parent2.openingElement === openingLikeElement || isJsxFragment(parent2) && parent2.openingFragment === openingLikeElement) && getSemanticJsxChildren(parent2.children).length > 0) {
      const childrenTypes = checkJsxChildren(parent2, checkMode);
      if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
        if (explicitlySpecifyChildrenAttribute) {
          error2(attributeParent, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName));
        }
        const contextualType = isJsxOpeningElement(openingLikeElement) ? getApparentTypeOfContextualType(
          openingLikeElement.attributes,
          /*contextFlags*/
          void 0
        ) : void 0;
        const childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
        const childrenPropSymbol = createSymbol(4 /* 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, attributeParent);
        childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
        const childPropMap = createSymbolTable();
        childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
        spread = getSpreadType(
          spread,
          createAnonymousType(attributesSymbol, childPropMap, emptyArray, emptyArray, emptyArray),
          attributesSymbol,
          objectFlags,
          /*readonly*/
          false
        );
      }
    }
    if (hasSpreadAnyType) {
      return anyType;
    }
    if (typeToIntersect && spread !== emptyJsxObjectType) {
      return getIntersectionType([typeToIntersect, spread]);
    }
    return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesTypeHelper() : spread);
    function createJsxAttributesTypeHelper() {
      objectFlags |= 8192 /* FreshLiteral */;
      return createJsxAttributesType(objectFlags, attributesSymbol, attributesTable);
    }
  }
  function createJsxAttributesType(objectFlags, attributesSymbol, attributesTable) {
    const result = createAnonymousType(attributesSymbol, attributesTable, emptyArray, emptyArray, emptyArray);
    result.objectFlags |= objectFlags | 8192 /* FreshLiteral */ | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */;
    return result;
  }
  function checkJsxChildren(node, checkMode) {
    const childrenTypes = [];
    for (const child of node.children) {
      if (child.kind === 12 /* JsxText */) {
        if (!child.containsOnlyTriviaWhiteSpaces) {
          childrenTypes.push(stringType);
        }
      } else if (child.kind === 294 /* 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 & 16777216 /* Optional */)) {
        const left = props.get(right.escapedName);
        if (left) {
          const diagnostic = error2(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 exports2 = namespace && getExportsOfSymbol(namespace);
    const typeSymbol = exports2 && getSymbol2(exports2, name, 788968 /* 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 |= 1 /* IntrinsicNamedElement */;
          return links.resolvedSymbol = intrinsicProp;
        }
        const indexSymbol = getApplicableIndexSymbol(intrinsicElementsType, getStringLiteralType(unescapeLeadingUnderscores(propName)));
        if (indexSymbol) {
          links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
          return links.resolvedSymbol = indexSymbol;
        }
        if (getTypeOfPropertyOrIndexSignatureOfType(intrinsicElementsType, propName)) {
          links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
          return links.resolvedSymbol = intrinsicElementsType.symbol;
        }
        error2(node, Diagnostics.Property_0_does_not_exist_on_type_1, intrinsicTagNameToString(node.tagName), "JSX." + JsxNames.IntrinsicElements);
        return links.resolvedSymbol = unknownSymbol;
      } else {
        if (noImplicitAny) {
          error2(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) === 1 /* 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.This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_for_the_appropriate_package_installed;
    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,
          1920 /* Namespace */,
          /*nameNotFoundMessage*/
          void 0,
          /*isUse*/
          false
        );
      }
      if (resolvedNamespace) {
        const candidate = resolveSymbol(getSymbol2(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
        if (candidate && candidate !== unknownSymbol) {
          if (links) {
            links.jsxNamespace = candidate;
          }
          return candidate;
        }
      }
      if (links) {
        links.jsxNamespace = false;
      }
    }
    const s = resolveSymbol(getGlobalSymbol(
      JsxNames.JSX,
      1920 /* Namespace */,
      /*diagnostic*/
      void 0
    ));
    if (s === unknownSymbol) {
      return void 0;
    }
    return s;
  }
  function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
    const jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol2(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* 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) {
        error2(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 && getSymbol2(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
  }
  function getJsxElementTypeSymbol(jsxNamespace) {
    return jsxNamespace && getSymbol2(jsxNamespace.exports, JsxNames.ElementType, 788968 /* Type */);
  }
  function getJsxElementPropertiesName(jsxNamespace) {
    return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
  }
  function getJsxElementChildrenPropertyName(jsxNamespace) {
    return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
  }
  function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
    if (elementType.flags & 4 /* String */) {
      return [anySignature];
    } else if (elementType.flags & 128 /* StringLiteral */) {
      const intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
      if (!intrinsicType) {
        error2(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, 1 /* Construct */);
    if (signatures.length === 0) {
      signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
    }
    if (signatures.length === 0 && apparentElemType.flags & 1048576 /* 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 === 1 /* 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 === 0 /* 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) {
    var _a;
    Debug.assert(isJsxIntrinsicTagName(node.tagName));
    const links = getNodeLinks(node);
    if (!links.resolvedJsxElementAttributesType) {
      const symbol = getIntrinsicTagSymbol(node);
      if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
        return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType;
      } else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
        const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText;
        return links.resolvedJsxElementAttributesType = ((_a = getApplicableIndexInfoForName(getJsxType(JsxNames.IntrinsicElements, node), propName)) == null ? void 0 : _a.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 & 524288 /* 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 || 0 /* None */) === 0 /* None */) {
      error2(errorNode, Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
    }
    if (getJsxElementTypeAt(errorNode) === void 0) {
      if (noImplicitAny) {
        error2(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);
    const sig = getResolvedSignature(node);
    checkDeprecatedSignature(sig, node);
    if (isNodeOpeningLikeElement) {
      const jsxOpeningLikeNode = 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 & 524288 /* Object */) {
      if (getPropertyOfObjectType(targetType, name) || getApplicableIndexInfoForName(targetType, name) || isLateBoundName(name) && getIndexInfoOfType(targetType, stringType) || isComparingJsxAttributes && isHyphenatedJsxName(name)) {
        return true;
      }
    }
    if (targetType.flags & 33554432 /* Substitution */) {
      return isKnownProperty(targetType.baseType, name, isComparingJsxAttributes);
    }
    if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
      for (const t of targetType.types) {
        if (isKnownProperty(t, name, isComparingJsxAttributes)) {
          return true;
        }
      }
    }
    return false;
  }
  function isExcessPropertyCheckTarget(type) {
    return !!(type.flags & 524288 /* Object */ && !(getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) || type.flags & 67108864 /* NonPrimitive */ || type.flags & 33554432 /* Substitution */ && isExcessPropertyCheckTarget(type.baseType) || type.flags & 1048576 /* Union */ && some(type.types, isExcessPropertyCheckTarget) || type.flags & 2097152 /* 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)) {
        error2(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 & 8192 /* Method */ || getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
      return true;
    }
    if (isInJSFile(symbol.valueDeclaration)) {
      const parent2 = symbol.valueDeclaration.parent;
      return parent2 && isBinaryExpression(parent2) && getAssignmentDeclarationKind(parent2) === 3 /* PrototypeProperty */;
    }
  }
  function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError = true) {
    const errorNode = !reportError ? void 0 : node.kind === 166 /* QualifiedName */ ? node.right : node.kind === 205 /* ImportType */ ? node : node.kind === 208 /* BindingElement */ && node.propertyName ? node.propertyName : node.name;
    return checkPropertyAccessibilityAtLocation(node, isSuper, writing, type, prop, errorNode);
  }
  function checkPropertyAccessibilityAtLocation(location, isSuper, writing, containingType, prop, errorNode) {
    var _a;
    const flags = getDeclarationModifierFlagsFromSymbol(prop, writing);
    if (isSuper) {
      if (languageVersion < 2 /* ES2015 */) {
        if (symbolHasNonMethodDeclaration(prop)) {
          if (errorNode) {
            error2(errorNode, Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
          }
          return false;
        }
      }
      if (flags & 64 /* Abstract */) {
        if (errorNode) {
          error2(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
        }
        return false;
      }
      if (!(flags & 256 /* Static */) && ((_a = prop.declarations) == null ? void 0 : _a.some(isClassInstanceProperty))) {
        if (errorNode) {
          error2(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 & 64 /* 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) {
          error2(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name));
        }
        return false;
      }
    }
    if (!(flags & 6 /* NonPublicAccessibilityModifier */)) {
      return true;
    }
    if (flags & 2 /* Private */) {
      const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
      if (!isNodeWithinClass(location, declaringClassDeclaration)) {
        if (errorNode) {
          error2(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 & 256 /* Static */ || !enclosingClass) {
        if (errorNode) {
          error2(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 & 256 /* Static */) {
      return true;
    }
    if (containingType.flags & 262144 /* TypeParameter */) {
      containingType = containingType.isThisType ? getConstraintOfTypeParameter(containingType) : getBaseConstraintOfType(containingType);
    }
    if (!containingType || !hasBaseType(containingType, enclosingClass)) {
      if (errorNode) {
        error2(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 == null ? void 0 : thisParameter.type) && getTypeFromTypeNode(thisParameter.type);
    if (thisType) {
      if (thisType.flags & 262144 /* TypeParameter */) {
        thisType = getConstraintOfTypeParameter(thisType);
      }
    } else {
      const thisContainer = getThisContainer(
        node,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      );
      if (isFunctionLike(thisContainer)) {
        thisType = getContextualThisParameterType(thisContainer);
      }
    }
    if (thisType && getObjectFlags(thisType) & (3 /* ClassOrInterface */ | 4 /* 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 !!forEachProperty2(symbol, (prop) => !(prop.flags & 8192 /* 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 nodeText2 = isEntityNameExpression(node) ? entityNameToString(node) : void 0;
    if (node.kind === 106 /* NullKeyword */) {
      error2(node, Diagnostics.The_value_0_cannot_be_used_here, "null");
      return;
    }
    if (nodeText2 !== void 0 && nodeText2.length < 100) {
      if (isIdentifier(node) && nodeText2 === "undefined") {
        error2(node, Diagnostics.The_value_0_cannot_be_used_here, "undefined");
        return;
      }
      error2(
        node,
        facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics._0_is_possibly_null_or_undefined : Diagnostics._0_is_possibly_undefined : Diagnostics._0_is_possibly_null,
        nodeText2
      );
    } else {
      error2(
        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) {
    error2(
      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 & 2 /* Unknown */) {
      if (isEntityNameExpression(node)) {
        const nodeText2 = entityNameToString(node);
        if (nodeText2.length < 100) {
          error2(node, Diagnostics._0_is_of_type_unknown, nodeText2);
          return errorType;
        }
      }
      error2(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 & (98304 /* Nullable */ | 131072 /* 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 & 16384 /* Void */) {
      if (isEntityNameExpression(node)) {
        const nodeText2 = entityNameToString(node);
        if (isIdentifier(node) && nodeText2 === "undefined") {
          error2(node, Diagnostics.The_value_0_cannot_be_used_here, nodeText2);
          return nonNullType;
        }
        if (nodeText2.length < 100) {
          error2(node, Diagnostics._0_is_possibly_undefined, nodeText2);
          return nonNullType;
        }
      }
      error2(node, Diagnostics.Object_is_possibly_undefined);
    }
    return nonNullType;
  }
  function checkPropertyAccessExpression(node, checkMode, writeOnly) {
    return node.flags & 64 /* 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 === 217 /* 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 === 103 /* 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 == null ? void 0 : lexicallyScopedIdentifier.valueDeclaration) {
        const lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
        const lexicalClass = getContainingClass(lexicalValueDecl);
        Debug.assert(!!lexicalClass);
        if (findAncestor(lexicalClass, (n) => typeClass === n)) {
          const diagnostic = error2(
            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;
        }
      }
      error2(
        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 !== 0 /* 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 !== 0 /* None */) {
          checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldSet */);
        }
        if (assignmentKind !== 1 /* Definite */) {
          checkExternalEmitHelpers(node, 524288 /* 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 & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
        if (isSetonlyAccessor && assignmentKind !== 1 /* Definite */) {
          error2(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 === 166 /* QualifiedName */
      );
    }
    markLinkedReferences(node, 2 /* Property */, prop, leftType);
    let propType;
    if (!prop) {
      const indexInfo = !isPrivateIdentifier(right) && (assignmentKind === 0 /* 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 & 418 /* BlockScoped */) {
            error2(right, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
          } else if (noImplicitAny) {
            error2(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))) {
        error2(node, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
      }
      propType = indexInfo.type;
      if (compilerOptions.noUncheckedIndexedAccess && getAssignmentTargetKind(node) !== 1 /* Definite */) {
        propType = getUnionType([propType, missingType]);
      }
      if (compilerOptions.noPropertyAccessFromIndexSignature && isPropertyAccessExpression(node)) {
        error2(right, Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, unescapeLeadingUnderscores(right.escapedText));
      }
      if (indexInfo.declaration && isDeprecatedDeclaration2(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 === 108 /* SuperKeyword */, isWriteAccess(node), apparentType, prop);
      if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
        error2(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) {
    var _a;
    const file = getSourceFileOfNode(node);
    if (file) {
      if (compilerOptions.checkJs === void 0 && file.checkJsDirective === void 0 && (file.scriptKind === 1 /* JS */ || file.scriptKind === 2 /* JSX */)) {
        const declarationFile = forEach(suggestion == null ? void 0 : suggestion.declarations, getSourceFileOfNode);
        const suggestionHasNoExtendsOrDecorators = !(suggestion == null ? void 0 : suggestion.valueDeclaration) || !isClassLike(suggestion.valueDeclaration) || ((_a = suggestion.valueDeclaration.heritageClauses) == null ? void 0 : _a.length) || classOrConstructorParameterIsDecorated(
          /*useLegacyDecorators*/
          false,
          suggestion.valueDeclaration
        );
        return !(file !== declarationFile && !!declarationFile && isGlobalSourceFile(declarationFile)) && !(excludeClasses && suggestion && suggestion.flags & 32 /* Class */ && suggestionHasNoExtendsOrDecorators) && !(!!node && excludeClasses && isPropertyAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && suggestionHasNoExtendsOrDecorators);
      }
    }
    return false;
  }
  function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) {
    const assignmentKind = getAssignmentTargetKind(node);
    if (assignmentKind === 1 /* Definite */) {
      return removeMissingType(propType, !!(prop && prop.flags & 16777216 /* Optional */));
    }
    if (prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* 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 === 110 /* ThisKeyword */) {
      const declaration = prop && prop.valueDeclaration;
      if (declaration && isPropertyWithoutInitializer(declaration)) {
        if (!isStatic(declaration)) {
          const flowContainer = getControlFlowContainer(node);
          if (flowContainer.kind === 176 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 33554432 /* 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)) {
      error2(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) & 256 /* Static */) && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) {
      diagnosticMessage = error2(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
    } else if (valueDeclaration.kind === 263 /* ClassDeclaration */ && node.parent.kind !== 183 /* TypeReference */ && !(valueDeclaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
      diagnosticMessage = error2(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 172 /* PropertyDeclaration */:
          return true;
        case 303 /* PropertyAssignment */:
        case 174 /* MethodDeclaration */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
        case 305 /* SpreadAssignment */:
        case 167 /* ComputedPropertyName */:
        case 239 /* TemplateSpan */:
        case 294 /* JsxExpression */:
        case 291 /* JsxAttribute */:
        case 292 /* JsxAttributes */:
        case 293 /* JsxSpreadAttribute */:
        case 286 /* JsxOpeningElement */:
        case 233 /* ExpressionWithTypeArguments */:
        case 298 /* HeritageClause */:
          return false;
        case 219 /* ArrowFunction */:
        case 244 /* ExpressionStatement */:
          return isBlock(node2.parent) && isClassStaticBlockDeclaration(node2.parent.parent) ? true : "quit";
        default:
          return isExpressionNode(node2) ? false : "quit";
      }
    });
  }
  function isPropertyDeclaredInAncestorClass(prop) {
    if (!(prop.parent.flags & 32 /* 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) {
    const links = getNodeLinks(propNode);
    const cache = links.nonExistentPropCheckCache || (links.nonExistentPropCheckCache = /* @__PURE__ */ new Set());
    const key = `${getTypeId(containingType)}|${isUncheckedJS}`;
    if (cache.has(key)) {
      return;
    }
    cache.add(key);
    let errorInfo;
    let relatedInfo;
    if (!isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 402784252 /* 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), 106500 /* ClassMember */);
  }
  function getSuggestedSymbolForNonexistentProperty(name, containingType) {
    let props = getPropertiesOfType(containingType);
    if (typeof name !== "string") {
      const parent2 = name.parent;
      if (isPropertyAccessExpression(parent2)) {
        props = filter(props, (prop) => isValidPropertyAccessForCompletions(parent2, containingType, prop));
      }
      name = idText(name);
    }
    return getSpellingSuggestionForName(name, props, 111551 /* 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, 111551 /* Value */);
  }
  function getSuggestionForNonexistentProperty(name, containingType) {
    const suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
    return suggestion && symbolName(suggestion);
  }
  function getSuggestionForSymbolNameLookup(symbols, name, meaning) {
    const symbol = getSymbol2(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(524288 /* 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), 2623475 /* 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 & 128 /* 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 & 2097152 /* 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 & 106500 /* ClassMember */ && prop.valueDeclaration;
    if (!valueDeclaration) {
      return;
    }
    const hasPrivateModifier = hasEffectiveModifier(valueDeclaration, 2 /* Private */);
    const hasPrivateIdentifier = prop.valueDeclaration && isNamedDeclaration(prop.valueDeclaration) && isPrivateIdentifier(prop.valueDeclaration.name);
    if (!hasPrivateModifier && !hasPrivateIdentifier) {
      return;
    }
    if (nodeForCheckWriteOnly && isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
      return;
    }
    if (isSelfTypeAccess2) {
      const containingMethod = findAncestor(nodeForCheckWriteOnly, isFunctionLikeDeclaration);
      if (containingMethod && containingMethod.symbol === prop) {
        return;
      }
    }
    (getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = -1 /* All */;
  }
  function isSelfTypeAccess(name, parent2) {
    return name.kind === 110 /* ThisKeyword */ || !!parent2 && isEntityNameExpression(name) && parent2 === getResolvedSymbol(getFirstIdentifier(name));
  }
  function isValidPropertyAccess(node, propertyName) {
    switch (node.kind) {
      case 211 /* PropertyAccessExpression */:
        return isValidPropertyAccessWithType(node, node.expression.kind === 108 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
      case 166 /* QualifiedName */:
        return isValidPropertyAccessWithType(
          node,
          /*isSuper*/
          false,
          propertyName,
          getWidenedType(checkExpression(node.left))
        );
      case 205 /* ImportType */:
        return isValidPropertyAccessWithType(
          node,
          /*isSuper*/
          false,
          propertyName,
          getTypeFromTypeNode(node)
        );
    }
  }
  function isValidPropertyAccessForCompletions(node, type, property) {
    return isPropertyAccessible(
      node,
      node.kind === 211 /* PropertyAccessExpression */ && node.expression.kind === 108 /* 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, (parent2) => parent2 === declClass);
    }
    return checkPropertyAccessibilityAtLocation(node, isSuper, isWrite, containingType, property);
  }
  function getForInVariableSymbol(node) {
    const initializer = node.initializer;
    if (initializer.kind === 261 /* VariableDeclarationList */) {
      const variable = initializer.declarations[0];
      if (variable && !isBindingPattern(variable.name)) {
        return getSymbolOfDeclaration(variable);
      }
    } else if (initializer.kind === 80 /* 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 === 80 /* Identifier */) {
      const symbol = getResolvedSymbol(e);
      if (symbol.flags & 3 /* Variable */) {
        let child = expr;
        let node = expr.parent;
        while (node) {
          if (node.kind === 249 /* 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 & 64 /* 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) !== 0 /* 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)) {
      error2(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 === 0 /* None */) {
      accessFlags = 32 /* ExpressionPosition */;
    } else {
      accessFlags = 4 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 2 /* NoIndexSignatures */ : 0);
      if (assignmentTargetKind === 2 /* Compound */) {
        accessFlags |= 32 /* 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 === 215 /* 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 parent2 = signature.declaration && signature.declaration.parent;
      if (!lastSymbol || symbol === lastSymbol) {
        if (lastParent && parent2 === lastParent) {
          index = index + 1;
        } else {
          lastParent = parent2;
          index = cutoffIndex;
        }
      } else {
        index = cutoffIndex = result.length;
        lastParent = parent2;
      }
      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 === 230 /* SpreadElement */ || arg.kind === 237 /* SyntheticExpression */ && arg.isSpread);
  }
  function getSpreadArgumentIndex(args) {
    return findIndex(args, isSpreadArgument);
  }
  function acceptsVoid(t) {
    return !!(t.flags & 16384 /* Void */);
  }
  function acceptsVoidUndefinedUnknownOrAny(t) {
    return !!(t.flags & (16384 /* Void */ | 32768 /* Undefined */ | 2 /* Unknown */ | 1 /* Any */));
  }
  function hasCorrectArity(node, args, signature, signatureHelpTrailingComma = false) {
    if (isJsxOpeningFragment(node)) return true;
    let argCount;
    let callIsIncomplete = false;
    let effectiveParameterCount = getParameterCount(signature);
    let effectiveMinimumArguments = getMinArgumentCount(signature);
    if (node.kind === 215 /* TaggedTemplateExpression */) {
      argCount = args.length;
      if (node.template.kind === 228 /* TemplateExpression */) {
        const lastSpan = last(node.template.templateSpans);
        callIsIncomplete = nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
      } else {
        const templateLiteral = node.template;
        Debug.assert(templateLiteral.kind === 15 /* NoSubstitutionTemplateLiteral */);
        callIsIncomplete = !!templateLiteral.isUnterminated;
      }
    } else if (node.kind === 170 /* Decorator */) {
      argCount = getDecoratorArgumentCount(node, signature);
    } else if (node.kind === 226 /* 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 === 214 /* 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 & 131072 /* 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,
      0 /* Call */,
      /*allowMembers*/
      false
    );
  }
  function getSingleCallOrConstructSignature(type) {
    return getSingleSignature(
      type,
      0 /* Call */,
      /*allowMembers*/
      false
    ) || getSingleSignature(
      type,
      1 /* Construct */,
      /*allowMembers*/
      false
    );
  }
  function getSingleSignature(type, kind, allowMembers) {
    if (type.flags & 524288 /* Object */) {
      const resolved = resolveStructuredTypeMembers(type);
      if (allowMembers || resolved.properties.length === 0 && resolved.indexInfos.length === 0) {
        if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
          return resolved.callSignatures[0];
        }
        if (kind === 1 /* 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, 0 /* None */, compareTypes);
    const restType = getEffectiveRestType(contextualSignature);
    const mapper = inferenceContext && (restType && restType.flags & 262144 /* 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, 128 /* 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 !== 170 /* Decorator */ && node.kind !== 226 /* BinaryExpression */) {
      const skipBindingPatterns = every(signature.typeParameters, (p) => !!getDefaultFromTypeParameter(p));
      const contextualType = getContextualType2(node, skipBindingPatterns ? 8 /* SkipBindingPatterns */ : 0 /* None */);
      if (contextualType) {
        const inferenceTargetType = getReturnTypeOfSignature(signature);
        if (couldContainTypeVariables(inferenceTargetType)) {
          const outerContext = getInferenceContext(node);
          const isFromBindingPattern = !skipBindingPatterns && getContextualType2(node, 8 /* SkipBindingPatterns */) !== contextualType;
          if (!isFromBindingPattern) {
            const outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* 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, 128 /* 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 & 262144 /* 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 !== 232 /* 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 & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) : type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType(
      getElementTypes(type),
      type.target.elementFlags,
      /*readonly*/
      false,
      type.target.labeledElementDeclarations
    ) : createTupleType([type], [8 /* 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 === 237 /* SyntheticExpression */ ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode);
        if (isArrayLikeType(spreadType)) {
          return getMutableArrayOrTupleType(spreadType);
        }
        return createArrayType(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 230 /* 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 === 237 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression);
        if (isArrayLikeType(spreadType)) {
          types.push(spreadType);
          flags.push(8 /* Variadic */);
        } else {
          types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 230 /* SpreadElement */ ? arg.expression : arg));
          flags.push(4 /* Rest */);
        }
      } else {
        const contextualType = isTupleType(restType) ? getContextualTypeForElementExpression(restType, i - index, argCount - index) || unknownType : getIndexedAccessType(restType, getNumberLiteralType(i - index), 256 /* Contextual */);
        const argType = checkExpressionWithContextualType(arg, contextualType, context, checkMode);
        const hasPrimitiveContextualType = inConstContext || maybeTypeOfKind(contextualType, 402784252 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
        types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
        flags.push(1 /* Required */);
      }
      if (arg.kind === 237 /* 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, reportErrors2, 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 = reportErrors2 && 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),
          reportErrors2 ? typeArgumentNodes[i] : void 0,
          typeArgumentHeadMessage,
          errorInfo
        )) {
          return void 0;
        }
      }
    }
    return typeArgumentTypes;
  }
  function getJsxReferenceKind(node) {
    if (isJsxIntrinsicTagName(node.tagName)) {
      return 2 /* Mixed */;
    }
    const tagType = getApparentType(checkExpression(node.tagName));
    if (length(getSignaturesOfType(tagType, 1 /* Construct */))) {
      return 0 /* Component */;
    }
    if (length(getSignaturesOfType(tagType, 0 /* Call */))) {
      return 1 /* Function */;
    }
    return 2 /* Mixed */;
  }
  function checkApplicableSignatureForJsxCallLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer) {
    const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
    const attributesType = isJsxOpeningFragment(node) ? createJsxAttributesTypeFromAttributesProperty(node) : checkExpressionWithContextualType(
      node.attributes,
      paramType,
      /*inferenceContext*/
      void 0,
      checkMode
    );
    const checkAttributesType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(attributesType) : attributesType;
    return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(
      checkAttributesType,
      paramType,
      relation,
      reportErrors2 ? isJsxOpeningFragment(node) ? node : node.tagName : void 0,
      isJsxOpeningFragment(node) ? void 0 : node.attributes,
      /*headMessage*/
      void 0,
      containingMessageChain,
      errorOutputContainer
    );
    function checkTagNameDoesNotExpectTooManyArguments() {
      var _a;
      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, 0 /* Call */);
      if (!length(tagCallSignatures)) {
        return true;
      }
      const factory2 = getJsxFactoryEntity(node);
      if (!factory2) {
        return true;
      }
      const factorySymbol = resolveEntityName(
        factory2,
        111551 /* Value */,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        false,
        node
      );
      if (!factorySymbol) {
        return true;
      }
      const factoryType = getTypeOfSymbol(factorySymbol);
      const callSignatures = getSignaturesOfType(factoryType, 0 /* 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, 0 /* 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 (reportErrors2) {
        const tagName = node.tagName;
        const diag2 = createDiagnosticForNode(tagName, Diagnostics.Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3, entityNameToString(tagName), absoluteMinArgCount, entityNameToString(factory2), maxParamCount);
        const tagNameDeclaration = (_a = getSymbolAtLocation(tagName)) == null ? void 0 : _a.valueDeclaration;
        if (tagNameDeclaration) {
          addRelatedInfo(diag2, createDiagnosticForNode(tagNameDeclaration, Diagnostics._0_is_declared_here, entityNameToString(tagName)));
        }
        if (errorOutputContainer && errorOutputContainer.skipLogging) {
          (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2);
        }
        if (!errorOutputContainer.skipLogging) {
          diagnostics.add(diag2);
        }
      }
      return false;
    }
  }
  function getEffectiveCheckNode(argument) {
    argument = skipParentheses(argument);
    return isSatisfiesExpression(argument) ? skipParentheses(argument.expression) : argument;
  }
  function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors2, containingMessageChain, inferenceContext) {
    const errorOutputContainer = { errors: void 0, skipLogging: true };
    if (isJsxCallLike(node)) {
      if (!checkApplicableSignatureForJsxCallLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer)) {
        Debug.assert(!reportErrors2 || !!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 = reportErrors2 ? 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(!reportErrors2 || !!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 !== 232 /* 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, reportErrors2 ? effectiveCheckArgumentNode : void 0, effectiveCheckArgumentNode, headMessage, containingMessageChain, errorOutputContainer)) {
          Debug.assert(!reportErrors2 || !!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 = !reportErrors2 ? 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(!reportErrors2 || !!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 && reportErrors2 && 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 === 226 /* BinaryExpression */) {
      return node.right;
    }
    const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : node.kind === 170 /* Decorator */ && !legacyDecorators ? node.expression : void 0;
    if (expression) {
      const callee = skipOuterExpressions(expression);
      if (isAccessExpression(callee)) {
        return callee.expression;
      }
    }
  }
  function createSyntheticExpression(parent2, type, isSpread, tupleNameSource) {
    const result = parseNodeFactory.createSyntheticExpression(type, isSpread, tupleNameSource);
    setTextRange(result, parent2);
    setParent(result, parent2);
    return result;
  }
  function getEffectiveCallArguments(node) {
    if (isJsxOpeningFragment(node)) {
      return [createSyntheticExpression(node, emptyFreshJsxObjectType)];
    }
    if (node.kind === 215 /* TaggedTemplateExpression */) {
      const template = node.template;
      const args2 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
      if (template.kind === 228 /* TemplateExpression */) {
        forEach(template.templateSpans, (span) => {
          args2.push(span.expression);
        });
      }
      return args2;
    }
    if (node.kind === 170 /* Decorator */) {
      return getEffectiveDecoratorArguments(node);
    }
    if (node.kind === 226 /* 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 === 230 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression));
        if (spreadType && isTupleType(spreadType)) {
          forEach(getElementTypes(spreadType), (t, i2) => {
            var _a;
            const flags = spreadType.target.elementFlags[i2];
            const syntheticArg = createSyntheticExpression(arg, flags & 4 /* Rest */ ? createArrayType(t) : t, !!(flags & 12 /* Variable */), (_a = spreadType.target.labeledElementDeclarations) == null ? void 0 : _a[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 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
        return 1;
      case 172 /* PropertyDeclaration */:
        return hasAccessorModifier(node.parent) ? 3 : 2;
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        return signature.parameters.length <= 2 ? 2 : 3;
      case 169 /* 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,
      111551 /* Value */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false
    );
    const decl = symbol == null ? void 0 : 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) {
    var _a;
    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 min2 = 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 < min2) {
        min2 = 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 ? min2 : min2 < max ? min2 + "-" + max : min2;
    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 error3 = 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 (min2 < 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 < min2) {
      let diagnostic;
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          error3,
          parameterRange,
          args.length
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        diagnostic = getDiagnosticForCallNode(node, chain);
      } else {
        diagnostic = getDiagnosticForCallNode(node, error3, parameterRange, args.length);
      }
      const parameter = (_a = closestSignature == null ? void 0 : closestSignature.declaration) == null ? void 0 : _a.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,
          error3,
          parameterRange,
          args.length
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), errorSpan, chain);
      }
      return createDiagnosticForNodeArray(getSourceFileOfNode(node), errorSpan, error3, parameterRange, args.length);
    }
  }
  function getTypeArgumentArityError(node, signatures, typeArguments, headMessage) {
    const argCount = typeArguments.length;
    if (signatures.length === 1) {
      const sig = signatures[0];
      const min2 = getMinTypeArgumentCount(sig.typeParameters);
      const max = length(sig.typeParameters);
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.Expected_0_type_arguments_but_got_1,
          min2 < max ? min2 + "-" + max : min2,
          argCount
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain);
      }
      return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, min2 < max ? min2 + "-" + max : min2, argCount);
    }
    let belowArgCount = -Infinity;
    let aboveArgCount = Infinity;
    for (const sig of signatures) {
      const min2 = getMinTypeArgumentCount(sig.typeParameters);
      const max = length(sig.typeParameters);
      if (min2 > argCount) {
        aboveArgCount = Math.min(aboveArgCount, min2);
      } 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 === 215 /* TaggedTemplateExpression */;
    const isDecorator2 = node.kind === 170 /* Decorator */;
    const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node);
    const isJsxOpenFragment = isJsxOpeningFragment(node);
    const isInstanceof = node.kind === 226 /* BinaryExpression */;
    const reportErrors2 = !isInferencePartiallyBlocked && !candidatesOutArray;
    let candidatesForArgumentError;
    let candidateForArgumentArityError;
    let candidateForTypeArgumentError;
    let result;
    let argCheckMode = 0 /* Normal */;
    let candidates = [];
    let typeArguments;
    if (!isDecorator2 && !isInstanceof && !isSuperCall(node) && !isJsxOpenFragment) {
      typeArguments = node.typeArguments;
      if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 108 /* SuperKeyword */) {
        forEach(typeArguments, checkSourceElement);
      }
    }
    candidates = candidatesOutArray || [];
    reorderCandidates(signatures, candidates, callChainFlags);
    if (!isJsxOpenFragment) {
      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;
    if (!isDecorator2 && !isSingleNonGenericCandidate && some(args, isContextSensitive)) {
      argCheckMode = 4 /* SkipContextSensitive */;
    }
    const signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 213 /* 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 (reportErrors2) {
      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 min2 = 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 <= min2) {
                min2 = 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 diag2;
          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];
            diag2 = { file, start, length: length2, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related };
          } else {
            diag2 = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node), getErrorNodeForCallNode(node), chain, related);
          }
          addImplementationSuccessElaboration(candidatesForArgumentError[0], diag2);
          diagnostics.add(diag2);
        }
      } else if (candidateForArgumentArityError) {
        diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args, headMessage));
      } else if (candidateForTypeArgumentError) {
        checkTypeArguments(
          candidateForTypeArgumentError,
          node.typeArguments,
          /*reportErrors*/
          true,
          headMessage
        );
      } else if (!isJsxOpenFragment) {
        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(failed2, diagnostic) {
      var _a, _b;
      const oldCandidatesForArgumentError = candidatesForArgumentError;
      const oldCandidateForArgumentArityError = candidateForArgumentArityError;
      const oldCandidateForTypeArgumentError = candidateForTypeArgumentError;
      const failedSignatureDeclarations = ((_b = (_a = failed2.declaration) == null ? void 0 : _a.symbol) == null ? void 0 : _b.declarations) || emptyArray;
      const isOverload2 = failedSignatureDeclarations.length > 1;
      const implDecl = isOverload2 ? 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) {
      var _a, _b;
      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 = (_b = (_a = candidate.typeParameters[0].symbol.declarations) == null ? void 0 : _a[0]) == null ? void 0 : _b.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) ? 2 /* AnyDefault */ : 0 /* None */
            );
            typeArgumentTypes = instantiateTypes(inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext), inferenceContext.nonFixingMapper);
            argCheckMode |= inferenceContext.flags & 4 /* 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 = 128 /* IsSignatureCandidateForOverloadFailure */;
    if (restParameterSymbols.length !== 0) {
      const type = createArrayType(getUnionType(mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
      parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
      flags |= 1 /* HasRestParameter */;
    }
    if (candidates.some(signatureHasLiteralTypes)) {
      flags |= 2 /* 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, 2 /* 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) ? 2 /* AnyDefault */ : 0 /* 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 === 108 /* 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, 0 /* None */);
        }
      }
      return resolveUntypedCall(node);
    }
    let callChainFlags;
    let funcType = checkExpression(node.expression);
    if (isCallChain(node)) {
      const nonOptionalType = getOptionalExpressionType(funcType, node.expression);
      callChainFlags = nonOptionalType === funcType ? 0 /* None */ : isOutermostOptionalChain(node) ? 16 /* IsOuterCallChain */ : 8 /* IsInnerCallChain */;
      funcType = nonOptionalType;
    } else {
      callChainFlags = 0 /* 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, 0 /* Call */);
    const numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
    if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
      if (!isErrorType(funcType) && node.typeArguments) {
        error2(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
      }
      return resolveUntypedCall(node);
    }
    if (!callSignatures.length) {
      if (numConstructSignatures) {
        error2(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, 0 /* 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))) {
      error2(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 & 262144 /* TypeParameter */) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & 1048576 /* Union */) && !(getReducedType(apparentFuncType).flags & 131072 /* 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) {
        error2(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
      }
      return resolveUntypedCall(node);
    }
    const constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
    if (constructSignatures.length) {
      if (!isConstructorAccessible(node, constructSignatures[0])) {
        return resolveErrorCall(node);
      }
      if (someSignature(constructSignatures, (signature) => !!(signature.flags & 4 /* Abstract */))) {
        error2(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
        return resolveErrorCall(node);
      }
      const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol);
      if (valueDecl && hasSyntacticModifier(valueDecl, 64 /* Abstract */)) {
        error2(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
        return resolveErrorCall(node);
      }
      return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
    }
    const callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
    if (callSignatures.length) {
      const signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
      if (!noImplicitAny) {
        if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
          error2(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
        }
        if (getThisTypeOfSignature(signature) === voidType) {
          error2(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, 1 /* Construct */);
    return resolveErrorCall(node);
  }
  function someSignature(signatures, f) {
    if (isArray(signatures)) {
      return some(signatures, (signature) => someSignature(signature, f));
    }
    return signatures.compositeKind === 1048576 /* 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 & 2097152 /* Intersection */) {
      const types = firstBase.types;
      const mixinFlags = findMixins(types);
      let i = 0;
      for (const intersectionMember of firstBase.types) {
        if (!mixinFlags[i]) {
          if (getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* 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, 6 /* NonPublicAccessibilityModifier */);
    if (!modifiers || declaration.kind !== 176 /* 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 & 4 /* Protected */) {
        const containingType = getTypeOfNode(containingClass);
        if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
          return true;
        }
      }
      if (modifiers & 2 /* Private */) {
        error2(node, Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
      }
      if (modifiers & 4 /* Protected */) {
        error2(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 === 0 /* Call */;
    const awaitedType = getAwaitedType(apparentType);
    const maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
    if (apparentType.flags & 1048576 /* 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 & 32768 /* 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, 0 /* Call */);
    const numConstructSignatures = getSignaturesOfType(apparentType, 1 /* 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, 0 /* Call */);
      return resolveErrorCall(node);
    }
    return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
  }
  function getDiagnosticHeadMessageForDecoratorResolution(node) {
    switch (node.parent.kind) {
      case 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
        return Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
      case 169 /* Parameter */:
        return Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
      case 172 /* PropertyDeclaration */:
        return Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
      case 178 /* 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, 0 /* Call */);
    const numConstructSignatures = getSignaturesOfType(apparentType, 1 /* 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
      );
      error2(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, 0 /* Call */);
      const messageChain = chainDiagnosticMessages(errorDetails.messageChain, headMessage);
      const diag2 = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node.expression), node.expression, messageChain);
      if (errorDetails.relatedMessage) {
        addRelatedInfo(diag2, createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
      }
      diagnostics.add(diag2);
      invocationErrorRecovery(apparentType, 0 /* Call */, diag2);
      return resolveErrorCall(node);
    }
    return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
  }
  function createSignatureForJSXIntrinsic(node, result) {
    const namespace = getJsxNamespaceAt(node);
    const exports2 = namespace && getExportsOfSymbol(namespace);
    const typeSymbol = exports2 && getSymbol2(exports2, JsxNames.Element, 788968 /* Type */);
    const returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* 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(133 /* AnyKeyword */)
    );
    const parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
    parameterSymbol.links.type = result;
    return createSignature(
      declaration,
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      [parameterSymbol],
      typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType,
      /*resolvedTypePredicate*/
      void 0,
      1,
      0 /* None */
    );
  }
  function getJSXFragmentType(node) {
    const sourceFileLinks = getNodeLinks(getSourceFileOfNode(node));
    if (sourceFileLinks.jsxFragmentType !== void 0) return sourceFileLinks.jsxFragmentType;
    const jsxFragmentFactoryName = getJsxNamespace(node);
    const shouldResolveFactoryReference = (compilerOptions.jsx === 2 /* React */ || compilerOptions.jsxFragmentFactory !== void 0) && jsxFragmentFactoryName !== "null";
    if (!shouldResolveFactoryReference) return sourceFileLinks.jsxFragmentType = anyType;
    const shouldModuleRefErr = compilerOptions.jsx !== 1 /* Preserve */ && compilerOptions.jsx !== 3 /* ReactNative */;
    const jsxFactoryRefErr = diagnostics ? Diagnostics.Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found : void 0;
    const jsxFactorySymbol = getJsxNamespaceContainerForImplicitImport(node) ?? resolveName(
      node,
      jsxFragmentFactoryName,
      shouldModuleRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */,
      /*nameNotFoundMessage*/
      jsxFactoryRefErr,
      /*isUse*/
      true
    );
    if (jsxFactorySymbol === void 0) return sourceFileLinks.jsxFragmentType = errorType;
    if (jsxFactorySymbol.escapedName === ReactNames.Fragment) return sourceFileLinks.jsxFragmentType = getTypeOfSymbol(jsxFactorySymbol);
    const resolvedAlias = (jsxFactorySymbol.flags & 2097152 /* Alias */) === 0 ? jsxFactorySymbol : resolveAlias(jsxFactorySymbol);
    const reactExports = jsxFactorySymbol && getExportsOfSymbol(resolvedAlias);
    const typeSymbol = reactExports && getSymbol2(reactExports, ReactNames.Fragment, 2 /* BlockScopedVariable */);
    const type = typeSymbol && getTypeOfSymbol(typeSymbol);
    return sourceFileLinks.jsxFragmentType = type === void 0 ? errorType : type;
  }
  function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
    const isJsxOpenFragment = isJsxOpeningFragment(node);
    let exprTypes;
    if (!isJsxOpenFragment) {
      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;
      }
      exprTypes = checkExpression(node.tagName);
    } else {
      exprTypes = getJSXFragmentType(node);
    }
    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) {
      if (isJsxOpenFragment) {
        error2(node, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node));
      } else {
        error2(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, 0 /* 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, 0 /* Call */);
        const constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */);
        if (isUntypedFunctionCall(hasInstanceMethodType, apparentType, callSignatures.length, constructSignatures.length)) {
          return resolveUntypedCall(node);
        }
        if (callSignatures.length) {
          return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
        }
      } else if (!(typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
        error2(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 213 /* CallExpression */:
        return resolveCallExpression(node, candidatesOutArray, checkMode);
      case 214 /* NewExpression */:
        return resolveNewExpression(node, candidatesOutArray, checkMode);
      case 215 /* TaggedTemplateExpression */:
        return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
      case 170 /* Decorator */:
        return resolveDecorator(node, candidatesOutArray, checkMode);
      case 289 /* JsxOpeningFragment */:
      case 286 /* JsxOpeningElement */:
      case 285 /* JsxSelfClosingElement */:
        return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
      case 226 /* 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) {
    var _a;
    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 !!((_a = symbol == null ? void 0 : symbol.members) == null ? void 0 : _a.size);
    }
    return false;
  }
  function mergeJSSymbols(target, source) {
    var _a, _b;
    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 & 32 /* Class */;
        if ((_a = source.exports) == null ? void 0 : _a.size) {
          mergeSymbolTable(inferred.exports, source.exports);
        }
        if ((_b = source.members) == null ? void 0 : _b.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) {
    var _a;
    const assignmentSymbol = decl && getSymbolOfExpando(
      decl,
      /*allowDeclaration*/
      true
    );
    const prototype = (_a = assignmentSymbol == null ? void 0 : assignmentSymbol.exports) == null ? void 0 : _a.get("prototype");
    const init = (prototype == null ? void 0 : 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) && !(isVarConstLike2(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 === 64 /* EqualsToken */ && (allowDeclaration || parentNode.right === node)) {
        name = parentNode.left;
        decl = name;
      } else if (parentNodeOperator === 57 /* BarBarToken */ || parentNodeOperator === 61 /* 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 === 64 /* 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 parent2 = node.parent;
    while (parent2 && parent2.kind === 211 /* PropertyAccessExpression */) {
      parent2 = parent2.parent;
    }
    if (parent2 && isBinaryExpression(parent2) && isPrototypeAccess(parent2.left) && parent2.operatorToken.kind === 64 /* EqualsToken */) {
      const right = getInitializerOfBinaryExpression(parent2);
      return isObjectLiteralExpression(right) && right;
    }
  }
  function checkCallExpression(node, checkMode) {
    var _a, _b, _c;
    checkGrammarTypeArguments(node, node.typeArguments);
    const signature = getResolvedSignature(
      node,
      /*candidatesOutArray*/
      void 0,
      checkMode
    );
    if (signature === resolvingSignature) {
      return silentNeverType;
    }
    checkDeprecatedSignature(signature, node);
    if (node.expression.kind === 108 /* SuperKeyword */) {
      return voidType;
    }
    if (node.kind === 214 /* NewExpression */) {
      const declaration = signature.declaration;
      if (declaration && declaration.kind !== 176 /* Constructor */ && declaration.kind !== 180 /* ConstructSignature */ && declaration.kind !== 185 /* ConstructorType */ && !(isJSDocSignature(declaration) && ((_b = (_a = getJSDocRoot(declaration)) == null ? void 0 : _a.parent) == null ? void 0 : _b.kind) === 176 /* Constructor */) && !isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) {
        if (noImplicitAny) {
          error2(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 & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
      return getESSymbolLikeTypeForNode(walkUpParenthesizedExpressions(node.parent));
    }
    if (node.kind === 213 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 244 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
      if (!isDottedName(node.expression)) {
        error2(node.expression, Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
      } else if (!getEffectsSignature(node)) {
        const diagnostic = error2(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 ((_c = jsSymbol == null ? void 0 : jsSymbol.exports) == null ? void 0 : _c.size) {
        const jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, emptyArray, emptyArray, emptyArray);
        jsAssignmentType.objectFlags |= 4096 /* JSLiteral */;
        return getIntersectionType([returnType, jsAssignmentType]);
      }
    }
    return returnType;
  }
  function checkDeprecatedSignature(signature, node) {
    if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */) return;
    if (signature.declaration && signature.declaration.flags & 536870912 /* 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 213 /* CallExpression */:
      case 170 /* Decorator */:
      case 214 /* NewExpression */:
        return getDeprecatedSuggestionNode(node.expression);
      case 215 /* TaggedTemplateExpression */:
        return getDeprecatedSuggestionNode(node.tag);
      case 286 /* JsxOpeningElement */:
      case 285 /* JsxSelfClosingElement */:
        return getDeprecatedSuggestionNode(node.tagName);
      case 212 /* ElementAccessExpression */:
        return node.argumentExpression;
      case 211 /* PropertyAccessExpression */:
        return node.name;
      case 183 /* 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",
      111551 /* 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 & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
      error2(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, 32768 /* 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(2097152 /* Alias */, "default" /* Default */);
    newSymbol.parent = originalSymbol;
    newSymbol.links.nameType = getStringLiteralType("default");
    newSymbol.links.aliasTarget = resolveSymbol(symbol);
    memberTable.set("default" /* 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) {
    var _a;
    if (allowSyntheticDefaultImports && type && !isErrorType(type)) {
      const synthType = type;
      if (!synthType.syntheticType) {
        const file = (_a = originalSymbol.declarations) == null ? void 0 : _a.find(isSourceFile);
        const hasSyntheticDefault = canHaveSyntheticDefault(
          file,
          originalSymbol,
          /*dontResolveAlias*/
          false,
          moduleSpecifier
        );
        if (hasSyntheticDefault) {
          const anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* 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,
      111551 /* Value */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
    if (resolvedRequire === requireSymbol) {
      return true;
    }
    if (resolvedRequire.flags & 2097152 /* Alias */) {
      return false;
    }
    const targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ ? 262 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ ? 260 /* VariableDeclaration */ : 0 /* Unknown */;
    if (targetDeclarationKind !== 0 /* Unknown */) {
      const decl = getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
      return !!decl && !!(decl.flags & 33554432 /* Ambient */);
    }
    return false;
  }
  function checkTaggedTemplateExpression(node) {
    if (!checkGrammarTaggedTemplateChain(node)) checkGrammarTypeArguments(node, node.typeArguments);
    if (languageVersion < LanguageFeatureMinimumTarget.TaggedTemplates) {
      checkExternalEmitHelpers(node, 262144 /* MakeTemplateObject */);
    }
    const signature = getResolvedSignature(node);
    checkDeprecatedSignature(signature, node);
    return getReturnTypeOfSignature(signature);
  }
  function checkAssertion(node, checkMode) {
    if (node.kind === 216 /* TypeAssertionExpression */) {
      const file = getSourceFileOfNode(node);
      if (file && fileExtensionIsOneOf(file.fileName, [".cts" /* Cts */, ".mts" /* 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 11 /* StringLiteral */:
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 209 /* ArrayLiteralExpression */:
      case 210 /* ObjectLiteralExpression */:
      case 228 /* TemplateExpression */:
        return true;
      case 217 /* ParenthesizedExpression */:
        return isValidConstAssertionArgument(node.expression);
      case 224 /* PrefixUnaryExpression */:
        const op = node.operator;
        const arg = node.operand;
        return op === 41 /* MinusToken */ && (arg.kind === 9 /* NumericLiteral */ || arg.kind === 10 /* BigIntLiteral */) || op === 40 /* PlusToken */ && arg.kind === 9 /* NumericLiteral */;
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        const expr = skipParentheses(node.expression);
        const symbol = isEntityNameExpression(expr) ? resolveEntityName(
          expr,
          111551 /* Value */,
          /*ignoreErrors*/
          true
        ) : void 0;
        return !!(symbol && symbol.flags & 384 /* Enum */);
    }
    return false;
  }
  function checkAssertionWorker(node, checkMode) {
    const { type, expression } = getAssertionTypeAndExpression(node);
    const exprType = checkExpression(expression, checkMode);
    if (isConstTypeReference(type)) {
      if (!isValidConstAssertionArgument(expression)) {
        error2(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 234 /* AsExpression */:
      case 216 /* TypeAssertionExpression */:
        type = node.type;
        expression = node.expression;
        break;
      case 217 /* 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 & 64 /* OptionalChain */ ? checkNonNullChain(node) : getNonNullableType(checkExpression(node.expression));
  }
  function checkExpressionWithTypeArguments(node) {
    checkGrammarExpressionWithTypeArguments(node);
    forEach(node.typeArguments, checkSourceElement);
    if (node.kind === 233 /* ExpressionWithTypeArguments */) {
      const parent2 = walkUpParenthesizedExpressions(node.parent);
      if (parent2.kind === 226 /* BinaryExpression */ && parent2.operatorToken.kind === 104 /* InstanceOfKeyword */ && isNodeDescendantOf(node, parent2.right)) {
        error2(node, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression);
      }
    }
    const exprType = node.kind === 233 /* 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;
    }
    const links = getNodeLinks(node);
    if (!links.instantiationExpressionTypes) {
      links.instantiationExpressionTypes = /* @__PURE__ */ new Map();
    }
    if (links.instantiationExpressionTypes.has(exprType.id)) {
      return links.instantiationExpressionTypes.get(exprType.id);
    }
    let hasSomeApplicableSignature = false;
    let nonApplicableType;
    const result = getInstantiatedType(exprType);
    links.instantiationExpressionTypes.set(exprType.id, result);
    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 || (hasSomeApplicableSignature = hasApplicableSignature);
      if (hasSignatures && !hasApplicableSignature) {
        nonApplicableType ?? (nonApplicableType = type);
      }
      return result2;
      function getInstantiatedTypePart(type2) {
        if (type2.flags & 524288 /* Object */) {
          const resolved = resolveStructuredTypeMembers(type2);
          const callSignatures = getInstantiatedSignatures(resolved.callSignatures);
          const constructSignatures = getInstantiatedSignatures(resolved.constructSignatures);
          hasSignatures || (hasSignatures = resolved.callSignatures.length !== 0 || resolved.constructSignatures.length !== 0);
          hasApplicableSignature || (hasApplicableSignature = callSignatures.length !== 0 || constructSignatures.length !== 0);
          if (callSignatures !== resolved.callSignatures || constructSignatures !== resolved.constructSignatures) {
            const result3 = createAnonymousType(createSymbol(0 /* None */, "__instantiationExpression" /* InstantiationExpression */), resolved.members, callSignatures, constructSignatures, resolved.indexInfos);
            result3.objectFlags |= 8388608 /* InstantiationExpressionType */;
            result3.node = node;
            return result3;
          }
        } else if (type2.flags & 58982400 /* InstantiableNonPrimitive */) {
          const constraint = getBaseConstraintOfType(type2);
          if (constraint) {
            const instantiated = getInstantiatedTypePart(constraint);
            if (instantiated !== constraint) {
              return instantiated;
            }
          }
        } else if (type2.flags & 1048576 /* Union */) {
          return mapType(type2, getInstantiatedType);
        } else if (type2.flags & 2097152 /* 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 === 238 /* SatisfiesExpression */ || n.kind === 350 /* 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 === 105 /* NewKeyword */) {
      return checkNewTargetMetaProperty(node);
    }
    if (node.keywordToken === 102 /* ImportKeyword */) {
      return checkImportMetaProperty(node);
    }
    return Debug.assertNever(node.keywordToken);
  }
  function checkMetaPropertyKeyword(node) {
    switch (node.keywordToken) {
      case 102 /* ImportKeyword */:
        return getGlobalImportMetaExpressionType();
      case 105 /* 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) {
      error2(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 === 176 /* Constructor */) {
      const symbol = getSymbolOfDeclaration(container.parent);
      return getTypeOfSymbol(symbol);
    } else {
      const symbol = getSymbolOfDeclaration(container);
      return getTypeOfSymbol(symbol);
    }
  }
  function checkImportMetaProperty(node) {
    if (moduleKind === 100 /* Node16 */ || moduleKind === 199 /* NodeNext */) {
      if (getSourceFileOfNode(node).impliedNodeFormat !== 99 /* ESNext */) {
        error2(node, Diagnostics.The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output);
      }
    } else if (moduleKind < 6 /* ES2020 */ && moduleKind !== 4 /* System */) {
      error2(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 & 8388608 /* 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 80 /* Identifier */: {
        const name = node.name.escapedText;
        if (node.dotDotDotToken) {
          return elementFlags & 12 /* Variable */ ? name : `${name}_${index}`;
        } else {
          return elementFlags & 3 /* Fixed */ ? name : `${name}_n`;
        }
      }
      case 207 /* ArrayBindingPattern */: {
        if (node.dotDotDotToken) {
          const elements = node.name.elements;
          const lastElement = tryCast(lastOrUndefined(elements), isBindingElement);
          const elementCount = elements.length - ((lastElement == null ? void 0 : lastElement.dotDotDotToken) ? 1 : 0);
          if (index < elementCount) {
            const element = elements[index];
            if (isBindingElement(element)) {
              return getTupleElementLabelFromBindingElement(element, index, elementFlags);
            }
          } else if (lastElement == null ? void 0 : lastElement.dotDotDotToken) {
            return getTupleElementLabelFromBindingElement(lastElement, index - elementCount, elementFlags);
          }
        }
        break;
      }
    }
    return `arg_${index}`;
  }
  function getTupleElementLabel(d, index = 0, elementFlags = 3 /* Fixed */, restSymbol) {
    if (!d) {
      const restParameter = tryCast(restSymbol == null ? void 0 : restSymbol.valueDeclaration, isParameter);
      return restParameter ? getTupleElementLabelFromBindingElement(restParameter, index, elementFlags) : `${(restSymbol == null ? void 0 : restSymbol.escapedName) ?? "arg"}_${index}`;
    }
    Debug.assert(isIdentifier(d.name));
    return d.name.escapedText;
  }
  function getParameterNameAtPosition(signature, pos, overrideRestType) {
    var _a;
    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 = (_a = tupleType.labeledElementDeclarations) == null ? void 0 : _a[index];
      const elementFlags = tupleType.elementFlags[index];
      return getTupleElementLabel(associatedName, index, elementFlags, restParameter);
    }
    return restParameter.escapedName;
  }
  function getParameterIdentifierInfoAtPosition(signature, pos) {
    var _a;
    if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 317 /* 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 == null ? void 0 : associatedNames[index];
      const isRestTupleElement = !!(associatedName == null ? void 0 : 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 === 202 /* 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 & 12 /* 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 ? 1 /* Required */ : 2 /* Optional */);
      } else {
        types.push(restType);
        flags.push(8 /* 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 & 12 /* 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 & 1 /* 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 & 32 /* 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 & 131072 /* 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 & 12 /* 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 & 12 /* 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) & 65536 /* 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 !== 80 /* 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 === 80 /* 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 = createParameter2("this", thisType);
    const valueParam = createParameter2("value", valueType);
    return createFunctionType(
      /*typeParameters*/
      void 0,
      thisParam,
      [valueParam],
      valueType,
      /*typePredicate*/
      void 0,
      1
    );
  }
  function createESDecoratorCallSignature(targetType, contextType, nonOptionalReturnType) {
    const targetParam = createParameter2("target", targetType);
    const contextParam = createParameter2("context", contextType);
    const returnType = getUnionType([nonOptionalReturnType, voidType]);
    return createCallSignature(
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      [targetParam, contextParam],
      returnType
    );
  }
  function getESDecoratorCallSignature(decorator) {
    const { parent: parent2 } = decorator;
    const links = getNodeLinks(parent2);
    if (!links.decoratorSignature) {
      links.decoratorSignature = anySignature;
      switch (parent2.kind) {
        case 263 /* ClassDeclaration */:
        case 231 /* ClassExpression */: {
          const node = parent2;
          const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node));
          const contextType = createClassDecoratorContextType(targetType);
          links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, targetType);
          break;
        }
        case 174 /* MethodDeclaration */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */: {
          const node = parent2;
          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 172 /* PropertyDeclaration */: {
          const node = parent2;
          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: parent2 } = decorator;
    const links = getNodeLinks(parent2);
    if (!links.decoratorSignature) {
      links.decoratorSignature = anySignature;
      switch (parent2.kind) {
        case 263 /* ClassDeclaration */:
        case 231 /* ClassExpression */: {
          const node = parent2;
          const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node));
          const targetParam = createParameter2("target", targetType);
          links.decoratorSignature = createCallSignature(
            /*typeParameters*/
            void 0,
            /*thisParameter*/
            void 0,
            [targetParam],
            getUnionType([targetType, voidType])
          );
          break;
        }
        case 169 /* Parameter */: {
          const node = parent2;
          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 = createParameter2("target", targetType);
          const keyParam = createParameter2("propertyKey", keyType);
          const indexParam = createParameter2("parameterIndex", indexType);
          links.decoratorSignature = createCallSignature(
            /*typeParameters*/
            void 0,
            /*thisParameter*/
            void 0,
            [targetParam, keyParam, indexParam],
            voidType
          );
          break;
        }
        case 174 /* MethodDeclaration */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
        case 172 /* PropertyDeclaration */: {
          const node = parent2;
          if (!isClassLike(node.parent)) break;
          const targetType = getParentTypeOfClassElement(node);
          const targetParam = createParameter2("target", targetType);
          const keyType = getClassElementPropertyKeyType(node);
          const keyParam = createParameter2("propertyKey", keyType);
          const returnType = isPropertyDeclaration(node) ? voidType : createTypedPropertyDescriptorType(getTypeOfNode(node));
          const hasPropDesc = !isPropertyDeclaration(parent2) || hasAccessorModifier(parent2);
          if (hasPropDesc) {
            const descriptorType = createTypedPropertyDescriptorType(getTypeOfNode(node));
            const descriptorParam = createParameter2("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) {
      error2(
        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
    )) {
      error2(
        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(0 /* None */, "NewTargetExpression");
    const targetPropertySymbol = createSymbol(4 /* Property */, "target", 8 /* 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 & 2 /* Async */) !== 0;
    const isGenerator = (functionFlags & 1 /* Generator */) !== 0;
    let returnType;
    let yieldType;
    let nextType;
    let fallbackReturnType = voidType;
    if (func.body.kind !== 241 /* 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, 2 /* Subtype */);
      }
      const { yieldTypes, nextTypes } = checkAndAggregateYieldOperandTypes(func, checkMode);
      yieldType = some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : void 0;
      nextType = some(nextTypes) ? getIntersectionType(nextTypes) : void 0;
    } else {
      const types = checkAndAggregateReturnExpressionTypes(func, checkMode);
      if (!types) {
        return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, neverType) : neverType;
      }
      if (types.length === 0) {
        const contextualReturnType = getContextualReturnType(
          func,
          /*contextFlags*/
          void 0
        );
        const returnType2 = contextualReturnType && (unwrapReturnType(contextualReturnType, functionFlags) || voidType).flags & 32768 /* Undefined */ ? undefinedType : voidType;
        return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, returnType2) : (
          // Async function
          returnType2
        );
      }
      returnType = getUnionType(types, 2 /* 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) & 2 /* 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 = getContextualType2(
          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 === 221 /* 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 & 3 /* 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 & 2 /* Async */ && expr.kind === 223 /* AwaitExpression */) {
          expr = skipParentheses(
            expr.expression,
            /*excludeJSDocTypeAssertions*/
            true
          );
        }
        if (expr.kind === 213 /* CallExpression */ && expr.expression.kind === 80 /* 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 & 2 /* 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 & 131072 /* 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 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
        return true;
      case 174 /* MethodDeclaration */:
        return func.parent.kind === 210 /* ObjectLiteralExpression */;
      default:
        return false;
    }
  }
  function getTypePredicateFromBody(func) {
    switch (func.kind) {
      case 176 /* Constructor */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        return void 0;
    }
    const functionFlags = getFunctionFlags(func);
    if (functionFlags !== 0 /* Normal */) return void 0;
    let singleReturn;
    if (func.body && func.body.kind !== 241 /* 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 & 16 /* Boolean */)) return void 0;
    return forEach(func.parameters, (param, i) => {
      const initType = getTypeOfSymbol(param.symbol);
      if (!initType || initType.flags & 16 /* Boolean */ || !isIdentifier(param.name) || isSymbolAssigned(param.symbol) || isRestParameter(param)) {
        return;
      }
      const trueType2 = checkIfExpressionRefinesParameter(func, expr, param, initType);
      if (trueType2) {
        return createTypePredicate(1 /* Identifier */, unescapeLeadingUnderscores(param.name.escapedText), i, trueType2);
      }
    });
  }
  function checkIfExpressionRefinesParameter(func, expr, param, initType) {
    const antecedent = canHaveFlowNode(expr) && expr.flowNode || expr.parent.kind === 253 /* ReturnStatement */ && expr.parent.flowNode || createFlowNode(
      2 /* Start */,
      /*node*/
      void 0,
      /*antecedent*/
      void 0
    );
    const trueCondition = createFlowNode(32 /* TrueCondition */, expr, antecedent);
    const trueType2 = getFlowTypeOfReference(param.name, initType, initType, func, trueCondition);
    if (trueType2 === initType) return void 0;
    const falseCondition = createFlowNode(64 /* FalseCondition */, expr, antecedent);
    const falseSubtype = getFlowTypeOfReference(param.name, initType, trueType2, func, falseCondition);
    return falseSubtype.flags & 131072 /* 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, 16384 /* Void */) || type.flags & (1 /* Any */ | 32768 /* Undefined */))) {
        return;
      }
      if (func.kind === 173 /* MethodSignature */ || nodeIsMissing(func.body) || func.body.kind !== 241 /* Block */ || !functionHasImplicitReturn(func)) {
        return;
      }
      const hasExplicitReturn = func.flags & 1024 /* HasExplicitReturn */;
      const errorNode = getEffectiveReturnTypeNode(func) || func;
      if (type && type.flags & 131072 /* Never */) {
        error2(errorNode, Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
      } else if (type && !hasExplicitReturn) {
        error2(errorNode, Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value);
      } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
        error2(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;
          }
        }
        error2(errorNode, Diagnostics.Not_all_code_paths_return_a_value);
      }
    }
  }
  function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
    Debug.assert(node.kind !== 174 /* 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,
            64 /* IsNonInferrable */
          );
          const returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], emptyArray, emptyArray);
          returnOnlyType.objectFlags |= 262144 /* NonInferrableType */;
          return links.contextFreeType = returnOnlyType;
        }
      }
      return anyFunctionType;
    }
    const hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
    if (!hasGrammarError && node.kind === 218 /* FunctionExpression */) {
      checkGrammarForGenerator(node);
    }
    contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
    return getTypeOfSymbol(getSymbolOfDeclaration(node));
  }
  function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
    const links = getNodeLinks(node);
    if (!(links.flags & 64 /* ContextChecked */)) {
      const contextualSignature = getContextualSignature(node);
      if (!(links.flags & 64 /* ContextChecked */)) {
        links.flags |= 64 /* ContextChecked */;
        const signature = firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfDeclaration(node)), 0 /* 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 & 262144 /* TypeParameter */) {
                instantiatedContextualSignature = instantiateSignature(contextualSignature, inferenceContext.nonFixingMapper);
              }
            }
            instantiatedContextualSignature || (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 !== 174 /* 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 === 241 /* 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 & 3 /* AsyncGenerator */) === 2 /* 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) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 8 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 6 /* Constant */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || symbol.flags & 8 /* EnumMember */ || some(symbol.declarations, isReadonlyAssignmentDeclaration));
  }
  function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
    var _a, _b;
    if (assignmentKind === 0 /* None */) {
      return false;
    }
    if (isReadonlySymbol(symbol)) {
      if (symbol.flags & 4 /* Property */ && isAccessExpression(expr) && expr.expression.kind === 110 /* ThisKeyword */) {
        const ctor = getContainingFunction(expr);
        if (!(ctor && (ctor.kind === 176 /* 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 && ((_a = symbol.parent) == null ? void 0 : _a.valueDeclaration) === ctor.parent;
          const isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration2 && ((_b = symbol.parent) == null ? void 0 : _b.valueDeclaration) === ctor;
          const isWriteableSymbol = isLocalPropertyDeclaration || isLocalParameterProperty || isLocalThisPropertyAssignment || isLocalThisPropertyAssignmentConstructorFunction;
          return !isWriteableSymbol;
        }
      }
      return true;
    }
    if (isAccessExpression(expr)) {
      const node = skipParentheses(expr.expression);
      if (node.kind === 80 /* Identifier */) {
        const symbol2 = getNodeLinks(node).resolvedSymbol;
        if (symbol2.flags & 2097152 /* Alias */) {
          const declaration = getDeclarationOfAliasSymbol(symbol2);
          return !!declaration && declaration.kind === 274 /* NamespaceImport */;
        }
      }
    }
    return false;
  }
  function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
    const node = skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
    if (node.kind !== 80 /* Identifier */ && !isAccessExpression(node)) {
      error2(expr, invalidReferenceMessage);
      return false;
    }
    if (node.flags & 64 /* OptionalChain */) {
      error2(expr, invalidOptionalChainMessage);
      return false;
    }
    return true;
  }
  function checkDeleteExpression(node) {
    checkExpression(node.expression);
    const expr = skipParentheses(node.expression);
    if (!isAccessExpression(expr)) {
      error2(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
      return booleanType;
    }
    if (isPropertyAccessExpression(expr) && isPrivateIdentifier(expr.name)) {
      error2(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)) {
        error2(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 & (3 /* AnyOrUnknown */ | 131072 /* Never */)) && !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* Optional */ : hasTypeFacts(type, 16777216 /* IsUndefined */))) {
      error2(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;
      error2(node, message);
      hasError = true;
    } else if (!(node.flags & 65536 /* AwaitContext */)) {
      if (isInTopLevelContext(node)) {
        const sourceFile = getSourceFileOfNode(node);
        if (!hasParseDiagnostics(sourceFile)) {
          let span;
          if (!isEffectiveExternalModule(sourceFile, compilerOptions)) {
            span ?? (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 100 /* Node16 */:
            case 199 /* NodeNext */:
              if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) {
                span ?? (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 7 /* ES2022 */:
            case 99 /* ESNext */:
            case 200 /* Preserve */:
            case 4 /* System */:
              if (languageVersion >= 4 /* ES2017 */) {
                break;
              }
            // fallthrough
            default:
              span ?? (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 !== 176 /* Constructor */ && (getFunctionFlags(container) & 2 /* 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)) {
      error2(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 & 3 /* 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 9 /* NumericLiteral */:
        switch (node.operator) {
          case 41 /* MinusToken */:
            return getFreshTypeOfLiteralType(getNumberLiteralType(-node.operand.text));
          case 40 /* PlusToken */:
            return getFreshTypeOfLiteralType(getNumberLiteralType(+node.operand.text));
        }
        break;
      case 10 /* BigIntLiteral */:
        if (node.operator === 41 /* MinusToken */) {
          return getFreshTypeOfLiteralType(getBigIntLiteralType({
            negative: true,
            base10Value: parsePseudoBigInt(node.operand.text)
          }));
        }
    }
    switch (node.operator) {
      case 40 /* PlusToken */:
      case 41 /* MinusToken */:
      case 55 /* TildeToken */:
        checkNonNullType(operandType, node.operand);
        if (maybeTypeOfKindConsideringBaseConstraint(operandType, 12288 /* ESSymbolLike */)) {
          error2(node.operand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(node.operator));
        }
        if (node.operator === 40 /* PlusToken */) {
          if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112 /* BigIntLike */)) {
            error2(node.operand, Diagnostics.Operator_0_cannot_be_applied_to_type_1, tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
          }
          return numberType;
        }
        return getUnaryResultType(operandType);
      case 54 /* ExclamationToken */:
        checkTruthinessOfType(operandType, node.operand);
        const facts = getTypeFacts(operandType, 4194304 /* Truthy */ | 8388608 /* Falsy */);
        return facts === 4194304 /* Truthy */ ? falseType : facts === 8388608 /* Falsy */ ? trueType : booleanType;
      case 46 /* PlusPlusToken */:
      case 47 /* 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, 2112 /* BigIntLike */)) {
      return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* 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 & 3145728 /* 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 & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
      return false;
    }
    return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || !!(kind & 402653316 /* StringLike */) && isTypeAssignableTo(source, stringType) || !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
  }
  function allTypesAssignableToKind(source, kind, strict) {
    return source.flags & 1048576 /* Union */ ? every(source.types, (subType) => allTypesAssignableToKind(subType, kind, strict)) : isTypeAssignableToKind(source, kind, strict);
  }
  function isConstEnumObjectType(type) {
    return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
  }
  function isConstEnumSymbol(symbol) {
    return (symbol.flags & 128 /* ConstEnum */) !== 0;
  }
  function getSymbolHasInstanceMethodOfObjectType(type) {
    const hasInstancePropertyName = getPropertyNameForKnownSymbolName("hasInstance");
    if (allTypesAssignableToKind(type, 67108864 /* NonPrimitive */)) {
      const hasInstanceProperty = getPropertyOfType(type, hasInstancePropertyName);
      if (hasInstanceProperty) {
        const hasInstancePropertyType = getTypeOfSymbol(hasInstanceProperty);
        if (hasInstancePropertyType && getSignaturesOfType(hasInstancePropertyType, 0 /* Call */).length !== 0) {
          return hasInstancePropertyType;
        }
      }
    }
  }
  function checkInstanceOfExpression(left, right, leftType, rightType, checkMode) {
    if (leftType === silentNeverType || rightType === silentNeverType) {
      return silentNeverType;
    }
    if (!isTypeAny(leftType) && allTypesAssignableToKind(leftType, 402784252 /* Primitive */)) {
      error2(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 & 2097152 /* 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, 2097152 /* 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)) {
        error2(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 === 303 /* PropertyAssignment */ || property.kind === 304 /* 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, 32 /* ExpressionPosition */ | (hasDefaultValue(property) ? 16 /* AllowMissing */ : 0), name);
      const type = getFlowTypeOfDestructuring(property, elementType);
      return checkDestructuringAssignment(property.kind === 304 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
    } else if (property.kind === 305 /* SpreadAssignment */) {
      if (propertyIndex < properties.length - 1) {
        error2(property, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
      } else {
        if (languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest) {
          checkExternalEmitHelpers(property, 4 /* 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 {
      error2(property, Diagnostics.Property_assignment_expected);
    }
  }
  function checkArrayLiteralAssignment(node, sourceType, checkMode) {
    const elements = node.elements;
    if (languageVersion < LanguageFeatureMinimumTarget.DestructuringAssignment && compilerOptions.downlevelIteration) {
      checkExternalEmitHelpers(node, 512 /* 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 === 230 /* 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 !== 232 /* OmittedExpression */) {
      if (element.kind !== 230 /* SpreadElement */) {
        const indexType = getNumberLiteralType(elementIndex);
        if (isArrayLikeType(sourceType)) {
          const accessFlags = 32 /* ExpressionPosition */ | (hasDefaultValue(element) ? 16 /* 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) {
        error2(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
      } else {
        const restExpression = element.expression;
        if (restExpression.kind === 226 /* BinaryExpression */ && restExpression.operatorToken.kind === 64 /* EqualsToken */) {
          error2(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 === 304 /* 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 === 226 /* BinaryExpression */ && target.operatorToken.kind === 64 /* EqualsToken */) {
      checkBinaryExpression(target, checkMode);
      target = target.left;
      if (strictNullChecks) {
        sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
      }
    }
    if (target.kind === 210 /* ObjectLiteralExpression */) {
      return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
    }
    if (target.kind === 209 /* ArrayLiteralExpression */) {
      return checkArrayLiteralAssignment(target, sourceType, checkMode);
    }
    return checkReferenceAssignment(target, sourceType, checkMode);
  }
  function checkReferenceAssignment(target, sourceType, checkMode) {
    const targetType = checkExpression(target, checkMode);
    const error3 = target.parent.kind === 305 /* 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 === 305 /* 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, error3, optionalError)) {
      checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
    }
    if (isPrivateIdentifierPropertyAccessExpression(target)) {
      checkExternalEmitHelpers(target.parent, 1048576 /* ClassPrivateFieldSet */);
    }
    return sourceType;
  }
  function isSideEffectFree(node) {
    node = skipParentheses(node);
    switch (node.kind) {
      case 80 /* Identifier */:
      case 11 /* StringLiteral */:
      case 14 /* RegularExpressionLiteral */:
      case 215 /* TaggedTemplateExpression */:
      case 228 /* TemplateExpression */:
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 106 /* NullKeyword */:
      case 157 /* UndefinedKeyword */:
      case 218 /* FunctionExpression */:
      case 231 /* ClassExpression */:
      case 219 /* ArrowFunction */:
      case 209 /* ArrayLiteralExpression */:
      case 210 /* ObjectLiteralExpression */:
      case 221 /* TypeOfExpression */:
      case 235 /* NonNullExpression */:
      case 285 /* JsxSelfClosingElement */:
      case 284 /* JsxElement */:
        return true;
      case 227 /* ConditionalExpression */:
        return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse);
      case 226 /* BinaryExpression */:
        if (isAssignmentOperator(node.operatorToken.kind)) {
          return false;
        }
        return isSideEffectFree(node.left) && isSideEffectFree(node.right);
      case 224 /* PrefixUnaryExpression */:
      case 225 /* PostfixUnaryExpression */:
        switch (node.operator) {
          case 54 /* ExclamationToken */:
          case 40 /* PlusToken */:
          case 41 /* MinusToken */:
          case 55 /* TildeToken */:
            return true;
        }
        return false;
      // Some forms listed here for clarity
      case 222 /* VoidExpression */:
      // Explicit opt-out
      case 216 /* TypeAssertionExpression */:
      // Not SEF, but can produce useful type warnings
      case 234 /* AsExpression */:
      // Not SEF, but can produce useful type warnings
      default:
        return false;
    }
  }
  function isTypeEqualityComparableTo(source, target) {
    return (target.flags & 98304 /* 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 === 64 /* EqualsToken */ && (node.left.kind === 210 /* ObjectLiteralExpression */ || node.left.kind === 209 /* ArrayLiteralExpression */)) {
        state.skip = true;
        setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 110 /* 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 parent2 = node.parent;
          while (parent2.kind === 217 /* ParenthesizedExpression */ || isLogicalOrCoalescingBinaryExpression(parent2)) {
            parent2 = parent2.parent;
          }
          if (operator === 56 /* AmpersandAmpersandToken */ || isIfStatement(parent2)) {
            checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.left, leftType, isIfStatement(parent2) ? parent2.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 === 61 /* QuestionQuestionToken */) {
      if (isBinaryExpression(left) && (left.operatorToken.kind === 57 /* BarBarToken */ || left.operatorToken.kind === 56 /* 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 === 57 /* BarBarToken */ || right.operatorToken.kind === 56 /* AmpersandAmpersandToken */)) {
        grammarErrorOnNode(right, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(right.operatorToken.kind), tokenToString(operatorToken.kind));
      }
      const leftTarget = skipOuterExpressions(left, 31 /* All */);
      const nullishSemantics = getSyntacticNullishnessSemantics(leftTarget);
      if (nullishSemantics !== 3 /* Sometimes */) {
        if (node.parent.kind === 226 /* BinaryExpression */) {
          error2(leftTarget, Diagnostics.This_binary_expression_is_never_nullish_Are_you_missing_parentheses);
        } else {
          if (nullishSemantics === 1 /* Always */) {
            error2(leftTarget, Diagnostics.This_expression_is_always_nullish);
          } else {
            error2(leftTarget, Diagnostics.Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish);
          }
        }
      }
    }
  }
  function getSyntacticNullishnessSemantics(node) {
    node = skipOuterExpressions(node);
    switch (node.kind) {
      case 223 /* AwaitExpression */:
      case 213 /* CallExpression */:
      case 215 /* TaggedTemplateExpression */:
      case 212 /* ElementAccessExpression */:
      case 236 /* MetaProperty */:
      case 214 /* NewExpression */:
      case 211 /* PropertyAccessExpression */:
      case 229 /* YieldExpression */:
      case 110 /* ThisKeyword */:
        return 3 /* Sometimes */;
      case 226 /* BinaryExpression */:
        switch (node.operatorToken.kind) {
          case 64 /* EqualsToken */:
          case 61 /* QuestionQuestionToken */:
          case 78 /* QuestionQuestionEqualsToken */:
          case 57 /* BarBarToken */:
          case 76 /* BarBarEqualsToken */:
          case 56 /* AmpersandAmpersandToken */:
          case 77 /* AmpersandAmpersandEqualsToken */:
            return 3 /* Sometimes */;
          case 28 /* CommaToken */:
            return getSyntacticNullishnessSemantics(node.right);
        }
        return 2 /* Never */;
      case 227 /* ConditionalExpression */:
        return getSyntacticNullishnessSemantics(node.whenTrue) | getSyntacticNullishnessSemantics(node.whenFalse);
      case 106 /* NullKeyword */:
        return 1 /* Always */;
      case 80 /* Identifier */:
        if (getResolvedSymbol(node) === undefinedSymbol) {
          return 1 /* Always */;
        }
        return 3 /* Sometimes */;
    }
    return 2 /* Never */;
  }
  function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
    const operator = operatorToken.kind;
    if (operator === 64 /* EqualsToken */ && (left.kind === 210 /* ObjectLiteralExpression */ || left.kind === 209 /* ArrayLiteralExpression */)) {
      return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 110 /* 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 42 /* AsteriskToken */:
      case 43 /* AsteriskAsteriskToken */:
      case 67 /* AsteriskEqualsToken */:
      case 68 /* AsteriskAsteriskEqualsToken */:
      case 44 /* SlashToken */:
      case 69 /* SlashEqualsToken */:
      case 45 /* PercentToken */:
      case 70 /* PercentEqualsToken */:
      case 41 /* MinusToken */:
      case 66 /* MinusEqualsToken */:
      case 48 /* LessThanLessThanToken */:
      case 71 /* LessThanLessThanEqualsToken */:
      case 49 /* GreaterThanGreaterThanToken */:
      case 72 /* GreaterThanGreaterThanEqualsToken */:
      case 50 /* GreaterThanGreaterThanGreaterThanToken */:
      case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
      case 52 /* BarToken */:
      case 75 /* BarEqualsToken */:
      case 53 /* CaretToken */:
      case 79 /* CaretEqualsToken */:
      case 51 /* AmpersandToken */:
      case 74 /* AmpersandEqualsToken */:
        if (leftType === silentNeverType || rightType === silentNeverType) {
          return silentNeverType;
        }
        leftType = checkNonNullType(leftType, left);
        rightType = checkNonNullType(rightType, right);
        let suggestedOperator;
        if (leftType.flags & 528 /* BooleanLike */ && rightType.flags & 528 /* BooleanLike */ && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== void 0) {
          error2(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, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */) || // Or, if neither could be bigint, implicit coercion results in a number result
          !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
            resultType2 = numberType;
          } else if (bothAreBigIntLike(leftType, rightType)) {
            switch (operator) {
              case 50 /* GreaterThanGreaterThanGreaterThanToken */:
              case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
                reportOperatorError();
                break;
              case 43 /* AsteriskAsteriskToken */:
              case 68 /* AsteriskAsteriskEqualsToken */:
                if (languageVersion < 3 /* ES2016 */) {
                  error2(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 48 /* LessThanLessThanToken */:
              case 71 /* LessThanLessThanEqualsToken */:
              case 49 /* GreaterThanGreaterThanToken */:
              case 72 /* GreaterThanGreaterThanEqualsToken */:
              case 50 /* GreaterThanGreaterThanGreaterThanToken */:
              case 73 /* 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 40 /* PlusToken */:
      case 65 /* PlusEqualsToken */:
        if (leftType === silentNeverType || rightType === silentNeverType) {
          return silentNeverType;
        }
        if (!isTypeAssignableToKind(leftType, 402653316 /* StringLike */) && !isTypeAssignableToKind(rightType, 402653316 /* StringLike */)) {
          leftType = checkNonNullType(leftType, left);
          rightType = checkNonNullType(rightType, right);
        }
        let resultType;
        if (isTypeAssignableToKind(
          leftType,
          296 /* NumberLike */,
          /*strict*/
          true
        ) && isTypeAssignableToKind(
          rightType,
          296 /* NumberLike */,
          /*strict*/
          true
        )) {
          resultType = numberType;
        } else if (isTypeAssignableToKind(
          leftType,
          2112 /* BigIntLike */,
          /*strict*/
          true
        ) && isTypeAssignableToKind(
          rightType,
          2112 /* BigIntLike */,
          /*strict*/
          true
        )) {
          resultType = bigintType;
        } else if (isTypeAssignableToKind(
          leftType,
          402653316 /* StringLike */,
          /*strict*/
          true
        ) || isTypeAssignableToKind(
          rightType,
          402653316 /* 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 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 3 /* AnyOrUnknown */;
          reportOperatorError(
            (left2, right2) => isTypeAssignableToKind(left2, closeEnoughKind) && isTypeAssignableToKind(right2, closeEnoughKind)
          );
          return anyType;
        }
        if (operator === 65 /* PlusEqualsToken */) {
          checkAssignmentOperator(resultType);
        }
        return resultType;
      case 30 /* LessThanToken */:
      case 32 /* GreaterThanToken */:
      case 33 /* LessThanEqualsToken */:
      case 34 /* 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 35 /* EqualsEqualsToken */:
      case 36 /* ExclamationEqualsToken */:
      case 37 /* EqualsEqualsEqualsToken */:
      case 38 /* ExclamationEqualsEqualsToken */:
        if (!(checkMode && checkMode & 64 /* TypeOnly */)) {
          if ((isLiteralExpressionOfObject(left) || isLiteralExpressionOfObject(right)) && // only report for === and !== in JS, not == or !=
          (!isInJSFile(left) || (operator === 37 /* EqualsEqualsEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */))) {
            const eqType = operator === 35 /* EqualsEqualsToken */ || operator === 37 /* EqualsEqualsEqualsToken */;
            error2(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 104 /* InstanceOfKeyword */:
        return checkInstanceOfExpression(left, right, leftType, rightType, checkMode);
      case 103 /* InKeyword */:
        return checkInExpression(left, right, leftType, rightType);
      case 56 /* AmpersandAmpersandToken */:
      case 77 /* AmpersandAmpersandEqualsToken */: {
        const resultType2 = hasTypeFacts(leftType, 4194304 /* Truthy */) ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType;
        if (operator === 77 /* AmpersandAmpersandEqualsToken */) {
          checkAssignmentOperator(rightType);
        }
        return resultType2;
      }
      case 57 /* BarBarToken */:
      case 76 /* BarBarEqualsToken */: {
        const resultType2 = hasTypeFacts(leftType, 8388608 /* Falsy */) ? getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* Subtype */) : leftType;
        if (operator === 76 /* BarBarEqualsToken */) {
          checkAssignmentOperator(rightType);
        }
        return resultType2;
      }
      case 61 /* QuestionQuestionToken */:
      case 78 /* QuestionQuestionEqualsToken */: {
        const resultType2 = hasTypeFacts(leftType, 262144 /* EQUndefinedOrNull */) ? getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) : leftType;
        if (operator === 78 /* QuestionQuestionEqualsToken */) {
          checkAssignmentOperator(rightType);
        }
        return resultType2;
      }
      case 64 /* EqualsToken */:
        const declKind = isBinaryExpression(left.parent) ? getAssignmentDeclarationKind(left.parent) : 0 /* None */;
        checkAssignmentDeclaration(declKind, rightType);
        if (isAssignmentDeclaration2(declKind)) {
          if (!(rightType.flags & 524288 /* Object */) || declKind !== 2 /* ModuleExports */ && declKind !== 6 /* Prototype */ && !isEmptyObjectType(rightType) && !isFunctionObjectType(rightType) && !(getObjectFlags(rightType) & 1 /* Class */)) {
            checkAssignmentOperator(rightType);
          }
          return leftType;
        } else {
          checkAssignmentOperator(rightType);
          return rightType;
        }
      case 28 /* 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((diag2) => {
            if (diag2.code !== Diagnostics.JSX_expressions_must_have_one_parent_element.code) return false;
            return textSpanContainsPosition(diag2, start);
          });
          if (!isInDiag2657) error2(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, 2112 /* BigIntLike */) && isTypeAssignableToKind(right2, 2112 /* BigIntLike */);
    }
    function checkAssignmentDeclaration(kind, rightType2) {
      if (kind === 2 /* ModuleExports */) {
        for (const prop of getPropertiesOfObjectType(rightType2)) {
          const propType = getTypeOfSymbol(prop);
          if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
            const name = prop.escapedName;
            const symbol = resolveName(
              prop.valueDeclaration,
              name,
              788968 /* Type */,
              /*nameNotFoundMessage*/
              void 0,
              /*isUse*/
              false
            );
            if ((symbol == null ? void 0 : 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 === 217 /* ParenthesizedExpression */ && isNumericLiteral(node.left) && node.left.text === "0" && (isCallExpression(node.parent.parent) && node.parent.parent.expression === node.parent || node.parent.parent.kind === 215 /* 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, 12288 /* ESSymbolLike */) ? left : maybeTypeOfKindConsideringBaseConstraint(rightType, 12288 /* ESSymbolLike */) ? right : void 0;
      if (offendingSymbolOperand) {
        error2(offendingSymbolOperand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(operator2));
        return false;
      }
      return true;
    }
    function getSuggestedBooleanOperator(operator2) {
      switch (operator2) {
        case 52 /* BarToken */:
        case 75 /* BarEqualsToken */:
          return 57 /* BarBarToken */;
        case 53 /* CaretToken */:
        case 79 /* CaretEqualsToken */:
          return 38 /* ExclamationEqualsEqualsToken */;
        case 51 /* AmpersandToken */:
        case 74 /* AmpersandEqualsToken */:
          return 56 /* AmpersandAmpersandToken */;
        default:
          return void 0;
      }
    }
    function checkAssignmentOperator(valueType) {
      if (isAssignmentOperator(operator)) {
        addLazyDiagnostic(checkAssignmentOperatorWorker);
      }
      function checkAssignmentOperatorWorker() {
        let assigneeType = leftType;
        if (isCompoundAssignment(operatorToken.kind) && left.kind === 211 /* 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, 32768 /* 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) {
      var _a;
      switch (kind) {
        case 2 /* ModuleExports */:
          return true;
        case 1 /* ExportsProperty */:
        case 5 /* Property */:
        case 6 /* Prototype */:
        case 3 /* PrototypeProperty */:
        case 4 /* ThisProperty */:
          const symbol = getSymbolOfNode(left);
          const init = getAssignedExpandoInitializer(right);
          return !!init && isObjectLiteralExpression(init) && !!((_a = symbol == null ? void 0 : symbol.exports) == null ? void 0 : _a.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 37 /* EqualsEqualsEqualsToken */:
        case 35 /* EqualsEqualsToken */:
        case 38 /* ExclamationEqualsEqualsToken */:
        case 36 /* 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 = error2(errorNode2, Diagnostics.This_condition_will_always_return_0, tokenToString(operator2 === 37 /* EqualsEqualsEqualsToken */ || operator2 === 35 /* EqualsEqualsToken */ ? 97 /* FalseKeyword */ : 112 /* TrueKeyword */));
        if (isLeftNaN && isRightNaN) return;
        const operatorString = operator2 === 38 /* ExclamationEqualsEqualsToken */ || operator2 === 36 /* ExclamationEqualsToken */ ? tokenToString(54 /* 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 & 1 /* Generator */)) {
      return anyType;
    }
    const isAsync = (functionFlags & 2 /* Async */) !== 0;
    if (node.asteriskToken) {
      if (isAsync && languageVersion < LanguageFeatureMinimumTarget.AsyncGenerators) {
        checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
      }
      if (!isAsync && languageVersion < LanguageFeatureMinimumTarget.Generators && compilerOptions.downlevelIteration) {
        checkExternalEmitHelpers(node, 256 /* Values */);
      }
    }
    let returnType = getReturnTypeFromAnnotation(func);
    if (returnType && returnType.flags & 1048576 /* 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 = getContextualType2(
            node,
            /*contextFlags*/
            void 0
          );
          if (!contextualType || isTypeAny(contextualType)) {
            error2(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 & 16384 /* YieldContext */)) {
        grammarErrorOnFirstToken(node, Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
      }
      if (isInParameterInitializerBeforeContainingFunction(node)) {
        error2(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], 2 /* Subtype */);
  }
  function isTemplateLiteralContext(node) {
    const parent2 = node.parent;
    return isParenthesizedExpression(parent2) && isTemplateLiteralContext(parent2) || isElementAccessExpression(parent2) && parent2.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, 12288 /* ESSymbolLike */)) {
        error2(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 !== 215 /* TaggedTemplateExpression */ && evaluate(node).value;
    if (evaluated) {
      return getFreshTypeOfLiteralType(getStringLiteralType(evaluated));
    }
    if (isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType2(
      node,
      /*contextFlags*/
      void 0
    ) || unknownType, isTemplateLiteralContextualType)) {
      return getTemplateLiteralType(texts, types);
    }
    return stringType;
  }
  function isTemplateLiteralContextualType(type) {
    return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) || type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */));
  }
  function getContextNode2(node) {
    if (isJsxAttributes(node) && !isJsxSelfClosingElement(node.parent)) {
      return node.parent.parent;
    }
    return node;
  }
  function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
    const contextNode = getContextNode2(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, 2944 /* 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 === 216 /* TypeAssertionExpression */ || node.kind === 234 /* 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 === 206 /* ObjectBindingPattern */ && isObjectLiteralType2(type)) {
        return padObjectLiteralType(type, declaration.name);
      }
      if (declaration.name.kind === 207 /* 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(4 /* Property */ | 16777216 /* 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 & 12 /* 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 === 208 /* BindingElement */ && e.dotDotDotToken)) {
        elementTypes.push(!isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(
          e,
          /*includePatternInType*/
          false,
          /*reportErrors*/
          false
        ) : anyType);
        elementFlags.push(2 /* Optional */);
        if (!isOmittedExpression(e) && !hasDefaultValue(e)) {
          reportImplicitAny(e, anyType);
        }
      }
    }
    return createTupleType(elementTypes, elementFlags, type.target.readonly);
  }
  function widenTypeInferredFromInitializer(declaration, type) {
    const widened = getWidenedLiteralTypeForInitializer(declaration, type);
    if (isInJSFile(declaration)) {
      if (isEmptyLiteralType(widened)) {
        reportImplicitAny(declaration, anyType);
        return anyType;
      } else if (isEmptyArrayLiteralType(widened)) {
        reportImplicitAny(declaration, anyArrayType);
        return anyArrayType;
      }
    }
    return widened;
  }
  function getWidenedLiteralTypeForInitializer(declaration, type) {
    return getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
  }
  function isLiteralOfContextualType(candidateType, contextualType) {
    if (contextualType) {
      if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
        const types = contextualType.types;
        return some(types, (t) => isLiteralOfContextualType(candidateType, t));
      }
      if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
        const constraint = getBaseConstraintOfType(contextualType) || unknownType;
        return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint);
      }
      return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
    }
    return false;
  }
  function isConstContext(node) {
    const parent2 = node.parent;
    return isAssertionExpression(parent2) && isConstTypeReference(parent2.type) || isJSDocTypeAssertion(parent2) && isConstTypeReference(getJSDocTypeAssertionType(parent2)) || isValidConstAssertionArgument(node) && isConstTypeVariable(getContextualType2(node, 0 /* None */)) || (isParenthesizedExpression(parent2) || isArrayLiteralExpression(parent2) || isSpreadElement(parent2)) && isConstContext(parent2) || (isPropertyAssignment(parent2) || isShorthandPropertyAssignment(parent2) || isTemplateSpan(parent2)) && isConstContext(parent2.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(
      getContextualType2(
        node,
        /*contextFlags*/
        void 0
      ),
      node,
      /*contextFlags*/
      void 0
    ));
  }
  function checkPropertyAssignment(node, checkMode) {
    if (node.name.kind === 167 /* ComputedPropertyName */) {
      checkComputedPropertyName(node.name);
    }
    return checkExpressionForMutableLocation(node.initializer, checkMode);
  }
  function checkObjectLiteralMethod(node, checkMode) {
    checkGrammarMethod(node);
    if (node.name.kind === 167 /* 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,
        0 /* Call */,
        /*allowMembers*/
        true
      );
      const constructSignature = getSingleSignature(
        type,
        1 /* Construct */,
        /*allowMembers*/
        true
      );
      const signature = callSignature || constructSignature;
      if (signature && signature.typeParameters) {
        const contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
        if (contextualType) {
          const contextualSignature = getSingleSignature(
            getNonNullableType(contextualType),
            callSignature ? 0 /* Call */ : 1 /* 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 |= 4 /* 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(262144 /* 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) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _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 & 268435456 /* 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 | 268435456 /* 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 !== 108 /* 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) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.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;
    (_b = tracing) == null ? void 0 : _b.pop();
    return type;
  }
  function checkConstEnumAccess(node, type) {
    const ok = node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.expression === node || node.parent.kind === 212 /* ElementAccessExpression */ && node.parent.expression === node || ((node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || node.parent.kind === 186 /* TypeQuery */ && node.parent.exprName === node) || node.parent.kind === 281 /* ExportSpecifier */;
    if (!ok) {
      error2(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),
      2097152 /* Alias */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false,
      /*excludeGlobals*/
      true
    )) {
      Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
      const constEnumDeclaration = type.symbol.valueDeclaration;
      const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(getSourceFileOfNode(constEnumDeclaration).resolvedPath);
      if (constEnumDeclaration.flags & 33554432 /* Ambient */ && !isValidTypeOnlyAliasUseSite(node) && (!redirect || !shouldPreserveConstEnums(redirect.commandLine.options))) {
        error2(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 231 /* ClassExpression */:
        case 218 /* FunctionExpression */:
        case 219 /* ArrowFunction */:
          cancellationToken.throwIfCancellationRequested();
      }
    }
    switch (kind) {
      case 80 /* Identifier */:
        return checkIdentifier(node, checkMode);
      case 81 /* PrivateIdentifier */:
        return checkPrivateIdentifierExpression(node);
      case 110 /* ThisKeyword */:
        return checkThisExpression(node);
      case 108 /* SuperKeyword */:
        return checkSuperExpression(node);
      case 106 /* NullKeyword */:
        return nullWideningType;
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 11 /* StringLiteral */:
        return hasSkipDirectInferenceFlag(node) ? blockedStringType : getFreshTypeOfLiteralType(getStringLiteralType(node.text));
      case 9 /* NumericLiteral */:
        checkGrammarNumericLiteral(node);
        return getFreshTypeOfLiteralType(getNumberLiteralType(+node.text));
      case 10 /* BigIntLiteral */:
        checkGrammarBigIntLiteral(node);
        return getFreshTypeOfLiteralType(getBigIntLiteralType({
          negative: false,
          base10Value: parsePseudoBigInt(node.text)
        }));
      case 112 /* TrueKeyword */:
        return trueType;
      case 97 /* FalseKeyword */:
        return falseType;
      case 228 /* TemplateExpression */:
        return checkTemplateExpression(node);
      case 14 /* RegularExpressionLiteral */:
        return checkRegularExpressionLiteral(node);
      case 209 /* ArrayLiteralExpression */:
        return checkArrayLiteral(node, checkMode, forceTuple);
      case 210 /* ObjectLiteralExpression */:
        return checkObjectLiteral(node, checkMode);
      case 211 /* PropertyAccessExpression */:
        return checkPropertyAccessExpression(node, checkMode);
      case 166 /* QualifiedName */:
        return checkQualifiedName(node, checkMode);
      case 212 /* ElementAccessExpression */:
        return checkIndexedAccess(node, checkMode);
      case 213 /* CallExpression */:
        if (node.expression.kind === 102 /* ImportKeyword */) {
          return checkImportCallExpression(node);
        }
      // falls through
      case 214 /* NewExpression */:
        return checkCallExpression(node, checkMode);
      case 215 /* TaggedTemplateExpression */:
        return checkTaggedTemplateExpression(node);
      case 217 /* ParenthesizedExpression */:
        return checkParenthesizedExpression(node, checkMode);
      case 231 /* ClassExpression */:
        return checkClassExpression(node);
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
        return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
      case 221 /* TypeOfExpression */:
        return checkTypeOfExpression(node);
      case 216 /* TypeAssertionExpression */:
      case 234 /* AsExpression */:
        return checkAssertion(node, checkMode);
      case 235 /* NonNullExpression */:
        return checkNonNullAssertion(node);
      case 233 /* ExpressionWithTypeArguments */:
        return checkExpressionWithTypeArguments(node);
      case 238 /* SatisfiesExpression */:
        return checkSatisfiesExpression(node);
      case 236 /* MetaProperty */:
        return checkMetaProperty(node);
      case 220 /* DeleteExpression */:
        return checkDeleteExpression(node);
      case 222 /* VoidExpression */:
        return checkVoidExpression(node);
      case 223 /* AwaitExpression */:
        return checkAwaitExpression(node);
      case 224 /* PrefixUnaryExpression */:
        return checkPrefixUnaryExpression(node);
      case 225 /* PostfixUnaryExpression */:
        return checkPostfixUnaryExpression(node);
      case 226 /* BinaryExpression */:
        return checkBinaryExpression(node, checkMode);
      case 227 /* ConditionalExpression */:
        return checkConditionalExpression(node, checkMode);
      case 230 /* SpreadElement */:
        return checkSpreadExpression(node, checkMode);
      case 232 /* OmittedExpression */:
        return undefinedWideningType;
      case 229 /* YieldExpression */:
        return checkYieldExpression(node);
      case 237 /* SyntheticExpression */:
        return checkSyntheticExpression(node);
      case 294 /* JsxExpression */:
        return checkJsxExpression(node, checkMode);
      case 284 /* JsxElement */:
        return checkJsxElement(node, checkMode);
      case 285 /* JsxSelfClosingElement */:
        return checkJsxSelfClosingElement(node, checkMode);
      case 288 /* JsxFragment */:
        return checkJsxFragment(node);
      case 292 /* JsxAttributes */:
        return checkJsxAttributes(node, checkMode);
      case 286 /* 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)) {
      error2(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) {
    var _a, _b;
    if (isInterfaceDeclaration(node.parent) || isClassLike(node.parent) || isTypeAliasDeclaration(node.parent)) {
      const typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node));
      const modifiers = getTypeParameterModifiers(typeParameter) & (8192 /* In */ | 16384 /* Out */);
      if (modifiers) {
        const symbol = getSymbolOfDeclaration(node.parent);
        if (isTypeAliasDeclaration(node.parent) && !(getObjectFlags(getDeclaredTypeOfSymbol(symbol)) & (16 /* Anonymous */ | 32 /* Mapped */))) {
          error2(node, Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types);
        } else if (modifiers === 8192 /* In */ || modifiers === 16384 /* Out */) {
          (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) });
          const source = createMarkerType(symbol, typeParameter, modifiers === 16384 /* Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck);
          const target = createMarkerType(symbol, typeParameter, modifiers === 16384 /* 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;
          (_b = tracing) == null ? void 0 : _b.pop();
        }
      }
    }
  }
  function checkParameter(node) {
    checkGrammarModifiers(node);
    checkVariableLikeDeclaration(node);
    const func = getContainingFunction(node);
    if (hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */)) {
      if (!(func.kind === 176 /* Constructor */ && nodeIsPresent(func.body))) {
        error2(node, Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
      }
      if (func.kind === 176 /* Constructor */ && isIdentifier(node.name) && node.name.escapedText === "constructor") {
        error2(node.name, Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
      }
    }
    if (!node.initializer && isOptionalDeclaration(node) && isBindingPattern(node.name) && func.body) {
      error2(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) {
        error2(node, Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
      }
      if (func.kind === 176 /* Constructor */ || func.kind === 180 /* ConstructSignature */ || func.kind === 185 /* ConstructorType */) {
        error2(node, Diagnostics.A_constructor_cannot_have_a_this_parameter);
      }
      if (func.kind === 219 /* ArrowFunction */) {
        error2(node, Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
      }
      if (func.kind === 177 /* GetAccessor */ || func.kind === 178 /* SetAccessor */) {
        error2(node, Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
      }
    }
    if (node.dotDotDotToken && !isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
      error2(node, Diagnostics.A_rest_parameter_must_be_of_an_array_type);
    }
  }
  function checkTypePredicate(node) {
    const parent2 = getTypePredicateParent(node);
    if (!parent2) {
      error2(node, Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
      return;
    }
    const signature = getSignatureFromDeclaration(parent2);
    const typePredicate = getTypePredicateOfSignature(signature);
    if (!typePredicate) {
      return;
    }
    checkSourceElement(node.type);
    const { parameterName } = node;
    if (typePredicate.kind !== 0 /* This */ && typePredicate.kind !== 2 /* AssertsThis */) {
      if (typePredicate.parameterIndex >= 0) {
        if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
          error2(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 parent2.parameters) {
          if (isBindingPattern(name) && checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
            hasReportedError = true;
            break;
          }
        }
        if (!hasReportedError) {
          error2(node.parameterName, Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
        }
      }
    }
  }
  function getTypePredicateParent(node) {
    switch (node.parent.kind) {
      case 219 /* ArrowFunction */:
      case 179 /* CallSignature */:
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
      case 184 /* FunctionType */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        const parent2 = node.parent;
        if (node === parent2.type) {
          return parent2;
        }
    }
  }
  function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
    for (const element of pattern.elements) {
      if (isOmittedExpression(element)) {
        continue;
      }
      const name = element.name;
      if (name.kind === 80 /* Identifier */ && name.escapedText === predicateVariableName) {
        error2(predicateVariableNode, Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
        return true;
      } else if (name.kind === 207 /* ArrayBindingPattern */ || name.kind === 206 /* ObjectBindingPattern */) {
        if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(
          name,
          predicateVariableNode,
          predicateVariableName
        )) {
          return true;
        }
      }
    }
  }
  function checkSignatureDeclaration(node) {
    if (node.kind === 181 /* IndexSignature */) {
      checkGrammarIndexSignature(node);
    } else if (node.kind === 184 /* FunctionType */ || node.kind === 262 /* FunctionDeclaration */ || node.kind === 185 /* ConstructorType */ || node.kind === 179 /* CallSignature */ || node.kind === 176 /* Constructor */ || node.kind === 180 /* ConstructSignature */) {
      checkGrammarFunctionLikeDeclaration(node);
    }
    const functionFlags = getFunctionFlags(node);
    if (!(functionFlags & 4 /* Invalid */)) {
      if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < LanguageFeatureMinimumTarget.AsyncGenerators) {
        checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
      }
      if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < LanguageFeatureMinimumTarget.AsyncFunctions) {
        checkExternalEmitHelpers(node, 64 /* Awaiter */);
      }
      if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < LanguageFeatureMinimumTarget.Generators) {
        checkExternalEmitHelpers(node, 128 /* 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 180 /* ConstructSignature */:
            error2(node, Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
            break;
          case 179 /* CallSignature */:
            error2(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 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
          const returnType = getTypeFromTypeNode(returnTypeNode);
          if (returnType === voidType) {
            error2(returnTypeErrorLocation, Diagnostics.A_generator_cannot_have_a_void_type_annotation);
          } else {
            checkGeneratorInstantiationAssignabilityToReturnType(returnType, functionFlags2, returnTypeErrorLocation);
          }
        } else if ((functionFlags2 & 3 /* AsyncGenerator */) === 2 /* Async */) {
          checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation);
        }
      }
      if (node.kind !== 181 /* IndexSignature */ && node.kind !== 317 /* JSDocFunctionType */) {
        registerForUnusedIdentifiersCheck(node);
      }
    }
  }
  function checkGeneratorInstantiationAssignabilityToReturnType(returnType, functionFlags, errorNode) {
    const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags & 2 /* Async */) !== 0) || anyType;
    const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags & 2 /* Async */) !== 0) || generatorYieldType;
    const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags & 2 /* Async */) !== 0) || unknownType;
    const generatorInstantiation = createGeneratorType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags & 2 /* 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 === 176 /* 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 177 /* GetAccessor */:
              addName(names, name, memberName, 1 /* GetAccessor */ | privateStaticFlags);
              break;
            case 178 /* SetAccessor */:
              addName(names, name, memberName, 2 /* SetAccessor */ | privateStaticFlags);
              break;
            case 172 /* PropertyDeclaration */:
              addName(names, name, memberName, 3 /* GetOrSetAccessor */ | privateStaticFlags);
              break;
            case 174 /* 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 */)) {
          error2(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) {
              error2(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location));
            }
          } else if (prev & meaning & ~16 /* PrivateStatic */) {
            error2(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));
            error2(memberNameNode, message, memberName, className);
            break;
        }
      }
    }
  }
  function checkObjectTypeForDuplicateDeclarations(node) {
    const names = /* @__PURE__ */ new Map();
    for (const member of node.members) {
      if (member.kind === 171 /* PropertySignature */) {
        let memberName;
        const name = member.name;
        switch (name.kind) {
          case 11 /* StringLiteral */:
          case 9 /* NumericLiteral */:
            memberName = name.text;
            break;
          case 80 /* Identifier */:
            memberName = idText(name);
            break;
          default:
            continue;
        }
        if (names.get(memberName)) {
          error2(getNameOfDeclaration(member.symbol.valueDeclaration), Diagnostics.Duplicate_identifier_0, memberName);
          error2(member.name, Diagnostics.Duplicate_identifier_0, memberName);
        } else {
          names.set(memberName, true);
        }
      }
    }
  }
  function checkTypeForDuplicateIndexSignatures(node) {
    if (node.kind === 264 /* InterfaceDeclaration */) {
      const nodeSymbol = getSymbolOfDeclaration(node);
      if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
        return;
      }
    }
    const indexSymbol = getIndexSymbol(getSymbolOfDeclaration(node));
    if (indexSymbol == null ? void 0 : indexSymbol.declarations) {
      const indexSignatureMap = /* @__PURE__ */ new Map();
      for (const declaration of indexSymbol.declarations) {
        if (isIndexSignatureDeclaration(declaration)) {
          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) {
            error2(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, 64 /* Abstract */) && node.kind === 172 /* PropertyDeclaration */ && node.initializer) {
      error2(node, Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, declarationNameToString(node.name));
    }
  }
  function checkPropertySignature(node) {
    if (isPrivateIdentifier(node.name)) {
      error2(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") {
      error2(node.name, Diagnostics.Class_constructor_may_not_be_a_generator);
    }
    checkFunctionOrMethodDeclaration(node);
    if (hasSyntacticModifier(node, 64 /* Abstract */) && node.kind === 174 /* MethodDeclaration */ && node.body) {
      error2(node, Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, declarationNameToString(node.name));
    }
    if (isPrivateIdentifier(node.name) && !getContainingClass(node)) {
      error2(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 |= 1048576 /* ContainsClassWithPrivateIdentifiers */;
        }
        if (isClassExpression(node.parent)) {
          const enclosingIterationStatement = getEnclosingIterationStatement(node.parent);
          if (enclosingIterationStatement) {
            getNodeLinks(node.name).flags |= 32768 /* BlockScopedBindingInLoop */;
            getNodeLinks(enclosingIterationStatement).flags |= 4096 /* 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 === 172 /* 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) {
            error2(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, 31 /* ParameterPropertyModifier */)));
          if (superCallShouldBeRootLevel) {
            if (!superCallIsRootLevelInConstructor(superCall, node.body)) {
              error2(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) {
                error2(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) {
          error2(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 === 108 /* SuperKeyword */ || node.kind === 110 /* 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)) {
      error2(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 === 177 /* GetAccessor */) {
        if (!(node.flags & 33554432 /* Ambient */) && nodeIsPresent(node.body) && node.flags & 512 /* HasImplicitReturn */) {
          if (!(node.flags & 1024 /* HasExplicitReturn */)) {
            error2(node.name, Diagnostics.A_get_accessor_must_return_a_value);
          }
        }
      }
      if (node.name.kind === 167 /* ComputedPropertyName */) {
        checkComputedPropertyName(node.name);
      }
      if (hasBindableName(node)) {
        const symbol = getSymbolOfDeclaration(node);
        const getter = getDeclarationOfKind(symbol, 177 /* GetAccessor */);
        const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */);
        if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) {
          getNodeLinks(getter).flags |= 1 /* TypeChecked */;
          const getterFlags = getEffectiveModifierFlags(getter);
          const setterFlags = getEffectiveModifierFlags(setter);
          if ((getterFlags & 64 /* Abstract */) !== (setterFlags & 64 /* Abstract */)) {
            error2(getter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
            error2(setter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
          }
          if (getterFlags & 4 /* Protected */ && !(setterFlags & (4 /* Protected */ | 2 /* Private */)) || getterFlags & 2 /* Private */ && !(setterFlags & 2 /* Private */)) {
            error2(getter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter);
            error2(setter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter);
          }
        }
      }
      const returnType = getTypeOfAccessors(getSymbolOfDeclaration(node));
      if (node.kind === 177 /* 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 getEffectiveTypeArguments2(node, typeParameters)[index];
  }
  function getEffectiveTypeArguments2(node, typeParameters) {
    return fillMissingTypeArguments(map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(node));
