ion(node);
      case 264 /* InterfaceDeclaration */:
        return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
      case 265 /* TypeAliasDeclaration */:
        return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
      case 266 /* EnumDeclaration */:
        return bindEnumDeclaration(node);
      case 267 /* ModuleDeclaration */:
        return bindModuleDeclaration(node);
      // Jsx-attributes
      case 292 /* JsxAttributes */:
        return bindJsxAttributes(node);
      case 291 /* JsxAttribute */:
        return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
      // Imports and exports
      case 271 /* ImportEqualsDeclaration */:
      case 274 /* NamespaceImport */:
      case 276 /* ImportSpecifier */:
      case 281 /* ExportSpecifier */:
        return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
      case 270 /* NamespaceExportDeclaration */:
        return bindNamespaceExportDeclaration(node);
      case 273 /* ImportClause */:
        return bindImportClause(node);
      case 278 /* ExportDeclaration */:
        return bindExportDeclaration(node);
      case 277 /* ExportAssignment */:
        return bindExportAssignment(node);
      case 307 /* SourceFile */:
        updateStrictModeStatementList(node.statements);
        return bindSourceFileIfExternalModule();
      case 241 /* Block */:
        if (!isFunctionLikeOrClassStaticBlockDeclaration(node.parent)) {
          return;
        }
      // falls through
      case 268 /* ModuleBlock */:
        return updateStrictModeStatementList(node.statements);
      case 341 /* JSDocParameterTag */:
        if (node.parent.kind === 323 /* JSDocSignature */) {
          return bindParameter(node);
        }
        if (node.parent.kind !== 322 /* JSDocTypeLiteral */) {
          break;
        }
      // falls through
      case 348 /* JSDocPropertyTag */:
        const propTag = node;
        const flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 316 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */;
        return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
      case 346 /* JSDocTypedefTag */:
      case 338 /* JSDocCallbackTag */:
      case 340 /* JSDocEnumTag */:
        return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
      case 339 /* JSDocOverloadTag */:
        return bind(node.typeExpression);
      case 351 /* JSDocImportTag */:
        return (jsDocImports || (jsDocImports = [])).push(node);
    }
  }
  function bindPropertyWorker(node) {
    const isAutoAccessor = isAutoAccessorPropertyDeclaration(node);
    const includes = isAutoAccessor ? 98304 /* Accessor */ : 4 /* Property */;
    const excludes = isAutoAccessor ? 13247 /* AccessorExcludes */ : 0 /* PropertyExcludes */;
    return bindPropertyOrMethodOrAccessor(node, includes | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), excludes);
  }
  function bindAnonymousTypeWorker(node) {
    return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
  }
  function bindSourceFileIfExternalModule() {
    setExportContextFlag(file);
    if (isExternalModule(file)) {
      bindSourceFileAsExternalModule();
    } else if (isJsonSourceFile(file)) {
      bindSourceFileAsExternalModule();
      const originalSymbol = file.symbol;
      declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, -1 /* All */);
      file.symbol = originalSymbol;
    }
  }
  function bindSourceFileAsExternalModule() {
    bindAnonymousDeclaration(file, 512 /* ValueModule */, `"${removeFileExtension(file.fileName)}"`);
  }
  function bindExportAssignment(node) {
    if (!container.symbol || !container.symbol.exports) {
      bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node));
    } else {
      const flags = exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */;
      const symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, -1 /* All */);
      if (node.isExportEquals) {
        setValueDeclaration(symbol, node);
      }
    }
  }
  function bindNamespaceExportDeclaration(node) {
    if (some(node.modifiers)) {
      file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Modifiers_cannot_appear_here));
    }
    const diag2 = !isSourceFile(node.parent) ? Diagnostics.Global_module_exports_may_only_appear_at_top_level : !isExternalModule(node.parent) ? Diagnostics.Global_module_exports_may_only_appear_in_module_files : !node.parent.isDeclarationFile ? Diagnostics.Global_module_exports_may_only_appear_in_declaration_files : void 0;
    if (diag2) {
      file.bindDiagnostics.push(createDiagnosticForNode2(node, diag2));
    } else {
      file.symbol.globalExports = file.symbol.globalExports || createSymbolTable();
      declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
    }
  }
  function bindExportDeclaration(node) {
    if (!container.symbol || !container.symbol.exports) {
      bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
    } else if (!node.exportClause) {
      declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
    } else if (isNamespaceExport(node.exportClause)) {
      setParent(node.exportClause, node);
      declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
    }
  }
  function bindImportClause(node) {
    if (node.name) {
      declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
    }
  }
  function setCommonJsModuleIndicator(node) {
    if (file.externalModuleIndicator && file.externalModuleIndicator !== true) {
      return false;
    }
    if (!file.commonJsModuleIndicator) {
      file.commonJsModuleIndicator = node;
      if (!file.externalModuleIndicator) {
        bindSourceFileAsExternalModule();
      }
    }
    return true;
  }
  function bindObjectDefinePropertyExport(node) {
    if (!setCommonJsModuleIndicator(node)) {
      return;
    }
    const symbol = forEachIdentifierInEntityName(
      node.arguments[0],
      /*parent*/
      void 0,
      (id, symbol2) => {
        if (symbol2) {
          addDeclarationToSymbol(symbol2, id, 1536 /* Module */ | 67108864 /* Assignment */);
        }
        return symbol2;
      }
    );
    if (symbol) {
      const flags = 4 /* Property */ | 1048576 /* ExportValue */;
      declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
    }
  }
  function bindExportsPropertyAssignment(node) {
    if (!setCommonJsModuleIndicator(node)) {
      return;
    }
    const symbol = forEachIdentifierInEntityName(
      node.left.expression,
      /*parent*/
      void 0,
      (id, symbol2) => {
        if (symbol2) {
          addDeclarationToSymbol(symbol2, id, 1536 /* Module */ | 67108864 /* Assignment */);
        }
        return symbol2;
      }
    );
    if (symbol) {
      const isAlias = isAliasableExpression(node.right) && (isExportsIdentifier(node.left.expression) || isModuleExportsAccessExpression(node.left.expression));
      const flags = isAlias ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */;
      setParent(node.left, node);
      declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
    }
  }
  function bindModuleExportsAssignment(node) {
    if (!setCommonJsModuleIndicator(node)) {
      return;
    }
    const assignedExpression = getRightMostAssignedExpression(node.right);
    if (isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
      return;
    }
    if (isObjectLiteralExpression(assignedExpression) && every(assignedExpression.properties, isShorthandPropertyAssignment)) {
      forEach(assignedExpression.properties, bindExportAssignedObjectMemberAlias);
      return;
    }
    const flags = exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
    const symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
    setValueDeclaration(symbol, node);
  }
  function bindExportAssignedObjectMemberAlias(node) {
    declareSymbol(file.symbol.exports, file.symbol, node, 2097152 /* Alias */ | 67108864 /* Assignment */, 0 /* None */);
  }
  function bindThisPropertyAssignment(node) {
    Debug.assert(isInJSFile(node));
    const hasPrivateIdentifier = isBinaryExpression(node) && isPropertyAccessExpression(node.left) && isPrivateIdentifier(node.left.name) || isPropertyAccessExpression(node) && isPrivateIdentifier(node.name);
    if (hasPrivateIdentifier) {
      return;
    }
    const thisContainer = getThisContainer(
      node,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    switch (thisContainer.kind) {
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
        let constructorSymbol = thisContainer.symbol;
        if (isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 64 /* EqualsToken */) {
          const l = thisContainer.parent.left;
          if (isBindableStaticAccessExpression(l) && isPrototypeAccess(l.expression)) {
            constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
          }
        }
        if (constructorSymbol && constructorSymbol.valueDeclaration) {
          constructorSymbol.members = constructorSymbol.members || createSymbolTable();
          if (hasDynamicName(node)) {
            bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol, constructorSymbol.members);
          } else {
            declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
          }
          addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
        }
        break;
      case 176 /* Constructor */:
      case 172 /* PropertyDeclaration */:
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 175 /* ClassStaticBlockDeclaration */:
        const containingClass = thisContainer.parent;
        const symbolTable = isStatic(thisContainer) ? containingClass.symbol.exports : containingClass.symbol.members;
        if (hasDynamicName(node)) {
          bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol, symbolTable);
        } else {
          declareSymbol(
            symbolTable,
            containingClass.symbol,
            node,
            4 /* Property */ | 67108864 /* Assignment */,
            0 /* None */,
            /*isReplaceableByMethod*/
            true
          );
        }
        break;
      case 307 /* SourceFile */:
        if (hasDynamicName(node)) {
          break;
        } else if (thisContainer.commonJsModuleIndicator) {
          declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
        } else {
          declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
        }
        break;
      // Namespaces are not allowed in javascript files, so do nothing here
      case 267 /* ModuleDeclaration */:
        break;
      default:
        Debug.failBadSyntaxKind(thisContainer);
    }
  }
  function bindDynamicallyNamedThisPropertyAssignment(node, symbol, symbolTable) {
    declareSymbol(
      symbolTable,
      symbol,
      node,
      4 /* Property */,
      0 /* None */,
      /*isReplaceableByMethod*/
      true,
      /*isComputedName*/
      true
    );
    addLateBoundAssignmentDeclarationToSymbol(node, symbol);
  }
  function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
    if (symbol) {
      (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = /* @__PURE__ */ new Map())).set(getNodeId(node), node);
    }
  }
  function bindSpecialPropertyDeclaration(node) {
    if (node.expression.kind === 110 /* ThisKeyword */) {
      bindThisPropertyAssignment(node);
    } else if (isBindableStaticAccessExpression(node) && node.parent.parent.kind === 307 /* SourceFile */) {
      if (isPrototypeAccess(node.expression)) {
        bindPrototypePropertyAssignment(node, node.parent);
      } else {
        bindStaticPropertyAssignment(node);
      }
    }
  }
  function bindPrototypeAssignment(node) {
    setParent(node.left, node);
    setParent(node.right, node);
    bindPropertyAssignment(
      node.left.expression,
      node.left,
      /*isPrototypeProperty*/
      false,
      /*containerIsClass*/
      true
    );
  }
  function bindObjectDefinePrototypeProperty(node) {
    const namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
    if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
      addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
    }
    bindPotentiallyNewExpandoMemberToNamespace(
      node,
      namespaceSymbol,
      /*isPrototypeProperty*/
      true
    );
  }
  function bindPrototypePropertyAssignment(lhs, parent2) {
    const classPrototype = lhs.expression;
    const constructorFunction = classPrototype.expression;
    setParent(constructorFunction, classPrototype);
    setParent(classPrototype, lhs);
    setParent(lhs, parent2);
    bindPropertyAssignment(
      constructorFunction,
      lhs,
      /*isPrototypeProperty*/
      true,
      /*containerIsClass*/
      true
    );
  }
  function bindObjectDefinePropertyAssignment(node) {
    let namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
    const isToplevel = node.parent.parent.kind === 307 /* SourceFile */;
    namespaceSymbol = bindPotentiallyMissingNamespaces(
      namespaceSymbol,
      node.arguments[0],
      isToplevel,
      /*isPrototypeProperty*/
      false,
      /*containerIsClass*/
      false
    );
    bindPotentiallyNewExpandoMemberToNamespace(
      node,
      namespaceSymbol,
      /*isPrototypeProperty*/
      false
    );
  }
  function bindSpecialPropertyAssignment(node) {
    var _a;
    const parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer) || lookupSymbolForPropertyAccess(node.left.expression, container);
    if (!isInJSFile(node) && !isFunctionSymbol(parentSymbol)) {
      return;
    }
    const rootExpr = getLeftmostAccessExpression(node.left);
    if (isIdentifier(rootExpr) && ((_a = lookupSymbolForName(container, rootExpr.escapedText)) == null ? void 0 : _a.flags) & 2097152 /* Alias */) {
      return;
    }
    setParent(node.left, node);
    setParent(node.right, node);
    if (isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
      bindExportsPropertyAssignment(node);
    } else if (hasDynamicName(node)) {
      bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
      const sym = bindPotentiallyMissingNamespaces(
        parentSymbol,
        node.left.expression,
        isTopLevelNamespaceAssignment(node.left),
        /*isPrototypeProperty*/
        false,
        /*containerIsClass*/
        false
      );
      addLateBoundAssignmentDeclarationToSymbol(node, sym);
    } else {
      bindStaticPropertyAssignment(cast(node.left, isBindableStaticNameExpression));
    }
  }
  function bindStaticPropertyAssignment(node) {
    Debug.assert(!isIdentifier(node));
    setParent(node.expression, node);
    bindPropertyAssignment(
      node.expression,
      node,
      /*isPrototypeProperty*/
      false,
      /*containerIsClass*/
      false
    );
  }
  function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
    if ((namespaceSymbol == null ? void 0 : namespaceSymbol.flags) & 2097152 /* Alias */) {
      return namespaceSymbol;
    }
    if (isToplevel && !isPrototypeProperty) {
      const flags = 1536 /* Module */ | 67108864 /* Assignment */;
      const excludeFlags = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
      namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, (id, symbol, parent2) => {
        if (symbol) {
          addDeclarationToSymbol(symbol, id, flags);
          return symbol;
        } else {
          const table = parent2 ? parent2.exports : file.jsGlobalAugmentations || (file.jsGlobalAugmentations = createSymbolTable());
          return declareSymbol(table, parent2, id, flags, excludeFlags);
        }
      });
    }
    if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
      addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
    }
    return namespaceSymbol;
  }
  function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
    if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
      return;
    }
    const symbolTable = isPrototypeProperty ? namespaceSymbol.members || (namespaceSymbol.members = createSymbolTable()) : namespaceSymbol.exports || (namespaceSymbol.exports = createSymbolTable());
    let includes = 0 /* None */;
    let excludes = 0 /* None */;
    if (isFunctionLikeDeclaration(getAssignedExpandoInitializer(declaration))) {
      includes = 8192 /* Method */;
      excludes = 103359 /* MethodExcludes */;
    } else if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) {
      if (some(declaration.arguments[2].properties, (p) => {
        const id = getNameOfDeclaration(p);
        return !!id && isIdentifier(id) && idText(id) === "set";
      })) {
        includes |= 65536 /* SetAccessor */ | 4 /* Property */;
        excludes |= 78783 /* SetAccessorExcludes */;
      }
      if (some(declaration.arguments[2].properties, (p) => {
        const id = getNameOfDeclaration(p);
        return !!id && isIdentifier(id) && idText(id) === "get";
      })) {
        includes |= 32768 /* GetAccessor */ | 4 /* Property */;
        excludes |= 46015 /* GetAccessorExcludes */;
      }
    }
    if (includes === 0 /* None */) {
      includes = 4 /* Property */;
      excludes = 0 /* PropertyExcludes */;
    }
    declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
  }
  function isTopLevelNamespaceAssignment(propertyAccess) {
    return isBinaryExpression(propertyAccess.parent) ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 307 /* SourceFile */ : propertyAccess.parent.parent.kind === 307 /* SourceFile */;
  }
  function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
    let namespaceSymbol = lookupSymbolForPropertyAccess(name, blockScopeContainer) || lookupSymbolForPropertyAccess(name, container);
    const isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
    namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
    bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
  }
  function isExpandoSymbol(symbol) {
    if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
      return true;
    }
    const node = symbol.valueDeclaration;
    if (node && isCallExpression(node)) {
      return !!getAssignedExpandoInitializer(node);
    }
    let init = !node ? void 0 : isVariableDeclaration(node) ? node.initializer : isBinaryExpression(node) ? node.right : isPropertyAccessExpression(node) && isBinaryExpression(node.parent) ? node.parent.right : void 0;
    init = init && getRightMostAssignedExpression(init);
    if (init) {
      const isPrototypeAssignment = isPrototypeAccess(isVariableDeclaration(node) ? node.name : isBinaryExpression(node) ? node.left : node);
      return !!getExpandoInitializer(isBinaryExpression(init) && (init.operatorToken.kind === 57 /* BarBarToken */ || init.operatorToken.kind === 61 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
    }
    return false;
  }
  function getParentOfBinaryExpression(expr) {
    while (isBinaryExpression(expr.parent)) {
      expr = expr.parent;
    }
    return expr.parent;
  }
  function lookupSymbolForPropertyAccess(node, lookupContainer = container) {
    if (isIdentifier(node)) {
      return lookupSymbolForName(lookupContainer, node.escapedText);
    } else {
      const symbol = lookupSymbolForPropertyAccess(node.expression);
      return symbol && symbol.exports && symbol.exports.get(getElementOrPropertyAccessName(node));
    }
  }
  function forEachIdentifierInEntityName(e, parent2, action) {
    if (isExportsOrModuleExportsOrAlias(file, e)) {
      return file.symbol;
    } else if (isIdentifier(e)) {
      return action(e, lookupSymbolForPropertyAccess(e), parent2);
    } else {
      const s = forEachIdentifierInEntityName(e.expression, parent2, action);
      const name = getNameOrArgument(e);
      if (isPrivateIdentifier(name)) {
        Debug.fail("unexpected PrivateIdentifier");
      }
      return action(name, s && s.exports && s.exports.get(getElementOrPropertyAccessName(e)), s);
    }
  }
  function bindCallExpression(node) {
    if (!file.commonJsModuleIndicator && isRequireCall(
      node,
      /*requireStringLiteralLikeArgument*/
      false
    )) {
      setCommonJsModuleIndicator(node);
    }
  }
  function bindClassLikeDeclaration(node) {
    if (node.kind === 263 /* ClassDeclaration */) {
      bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
    } else {
      const bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
      bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
      if (node.name) {
        classifiableNames.add(node.name.escapedText);
      }
    }
    const { symbol } = node;
    const prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
    const symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
    if (symbolExport) {
      if (node.name) {
        setParent(node.name, node);
      }
      file.bindDiagnostics.push(createDiagnosticForNode2(symbolExport.declarations[0], Diagnostics.Duplicate_identifier_0, symbolName(prototypeSymbol)));
    }
    symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
    prototypeSymbol.parent = symbol;
  }
  function bindEnumDeclaration(node) {
    return isEnumConst(node) ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
  }
  function bindVariableDeclarationOrBindingElement(node) {
    if (inStrictMode) {
      checkStrictModeEvalOrArguments(node, node.name);
    }
    if (!isBindingPattern(node.name)) {
      const possibleVariableDecl = node.kind === 260 /* VariableDeclaration */ ? node : node.parent.parent;
      if (isInJSFile(node) && isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && !getJSDocTypeTag(node) && !(getCombinedModifierFlags(node) & 32 /* Export */)) {
        declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
      } else if (isBlockOrCatchScoped(node)) {
        bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
      } else if (isPartOfParameterDeclaration(node)) {
        declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
      } else {
        declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
      }
    }
  }
  function bindParameter(node) {
    if (node.kind === 341 /* JSDocParameterTag */ && container.kind !== 323 /* JSDocSignature */) {
      return;
    }
    if (inStrictMode && !(node.flags & 33554432 /* Ambient */)) {
      checkStrictModeEvalOrArguments(node, node.name);
    }
    if (isBindingPattern(node.name)) {
      bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
    } else {
      declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
    }
    if (isParameterPropertyDeclaration(node, node.parent)) {
      const classDeclaration = node.parent.parent;
      declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
    }
  }
  function bindFunctionDeclaration(node) {
    if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */)) {
      if (isAsyncFunction(node)) {
        emitFlags |= 4096 /* HasAsyncFunctions */;
      }
    }
    checkStrictModeFunctionName(node);
    if (inStrictMode) {
      checkStrictModeFunctionDeclaration(node);
      bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
    } else {
      declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
    }
  }
  function bindFunctionExpression(node) {
    if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */)) {
      if (isAsyncFunction(node)) {
        emitFlags |= 4096 /* HasAsyncFunctions */;
      }
    }
    if (currentFlow) {
      node.flowNode = currentFlow;
    }
    checkStrictModeFunctionName(node);
    const bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
    return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
  }
  function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
    if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */) && isAsyncFunction(node)) {
      emitFlags |= 4096 /* HasAsyncFunctions */;
    }
    if (currentFlow && isObjectLiteralOrClassExpressionMethodOrAccessor(node)) {
      node.flowNode = currentFlow;
    }
    return hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
  }
  function getInferTypeContainer(node) {
    const extendsType = findAncestor(node, (n) => n.parent && isConditionalTypeNode(n.parent) && n.parent.extendsType === n);
    return extendsType && extendsType.parent;
  }
  function bindTypeParameter(node) {
    if (isJSDocTemplateTag(node.parent)) {
      const container2 = getEffectiveContainerForJSDocTemplateTag(node.parent);
      if (container2) {
        Debug.assertNode(container2, canHaveLocals);
        container2.locals ?? (container2.locals = createSymbolTable());
        declareSymbol(
          container2.locals,
          /*parent*/
          void 0,
          node,
          262144 /* TypeParameter */,
          526824 /* TypeParameterExcludes */
        );
      } else {
        declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
      }
    } else if (node.parent.kind === 195 /* InferType */) {
      const container2 = getInferTypeContainer(node.parent);
      if (container2) {
        Debug.assertNode(container2, canHaveLocals);
        container2.locals ?? (container2.locals = createSymbolTable());
        declareSymbol(
          container2.locals,
          /*parent*/
          void 0,
          node,
          262144 /* TypeParameter */,
          526824 /* TypeParameterExcludes */
        );
      } else {
        bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node));
      }
    } else {
      declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
    }
  }
  function shouldReportErrorOnModuleDeclaration(node) {
    const instanceState = getModuleInstanceState(node);
    return instanceState === 1 /* Instantiated */ || instanceState === 2 /* ConstEnumOnly */ && shouldPreserveConstEnums(options);
  }
  function checkUnreachable(node) {
    if (!(currentFlow.flags & 1 /* Unreachable */)) {
      return false;
    }
    if (currentFlow === unreachableFlow) {
      const reportError = (
        // report error on all statements except empty ones
        isStatementButNotDeclaration(node) && node.kind !== 242 /* EmptyStatement */ || // report error on class declarations
        node.kind === 263 /* ClassDeclaration */ || // report errors on enums with preserved emit
        isEnumDeclarationWithPreservedEmit(node, options) || // report error on instantiated modules
        node.kind === 267 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)
      );
      if (reportError) {
        currentFlow = reportedUnreachableFlow;
        if (!options.allowUnreachableCode) {
          const isError = unreachableCodeIsError(options) && !(node.flags & 33554432 /* Ambient */) && (!isVariableStatement(node) || !!(getCombinedNodeFlags(node.declarationList) & 7 /* BlockScoped */) || node.declarationList.declarations.some((d) => !!d.initializer));
          eachUnreachableRange(node, options, (start, end) => errorOrSuggestionOnRange(isError, start, end, Diagnostics.Unreachable_code_detected));
        }
      }
    }
    return true;
  }
}
function isEnumDeclarationWithPreservedEmit(node, options) {
  return node.kind === 266 /* EnumDeclaration */ && (!isEnumConst(node) || shouldPreserveConstEnums(options));
}
function eachUnreachableRange(node, options, cb) {
  if (isStatement(node) && isExecutableStatement(node) && isBlock(node.parent)) {
    const { statements } = node.parent;
    const slice = sliceAfter(statements, node);
    getRangesWhere(slice, isExecutableStatement, (start, afterEnd) => cb(slice[start], slice[afterEnd - 1]));
  } else {
    cb(node, node);
  }
  function isExecutableStatement(s) {
    return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && // `var x;` may declare a variable used above
    !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & 7 /* BlockScoped */) && s.declarationList.declarations.some((d) => !d.initializer));
  }
  function isPurelyTypeDeclaration(s) {
    switch (s.kind) {
      case 264 /* InterfaceDeclaration */:
      case 265 /* TypeAliasDeclaration */:
        return true;
      case 267 /* ModuleDeclaration */:
        return getModuleInstanceState(s) !== 1 /* Instantiated */;
      case 266 /* EnumDeclaration */:
        return !isEnumDeclarationWithPreservedEmit(s, options);
      default:
        return false;
    }
  }
}
function isExportsOrModuleExportsOrAlias(sourceFile, node) {
  let i = 0;
  const q = createQueue();
  q.enqueue(node);
  while (!q.isEmpty() && i < 100) {
    i++;
    node = q.dequeue();
    if (isExportsIdentifier(node) || isModuleExportsAccessExpression(node)) {
      return true;
    } else if (isIdentifier(node)) {
      const symbol = lookupSymbolForName(sourceFile, node.escapedText);
      if (!!symbol && !!symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
        const init = symbol.valueDeclaration.initializer;
        q.enqueue(init);
        if (isAssignmentExpression(
          init,
          /*excludeCompoundAssignment*/
          true
        )) {
          q.enqueue(init.left);
          q.enqueue(init.right);
        }
      }
    }
  }
  return false;
}
function getContainerFlags(node) {
  switch (node.kind) {
    case 231 /* ClassExpression */:
    case 263 /* ClassDeclaration */:
    case 266 /* EnumDeclaration */:
    case 210 /* ObjectLiteralExpression */:
    case 187 /* TypeLiteral */:
    case 322 /* JSDocTypeLiteral */:
    case 292 /* JsxAttributes */:
      return 1 /* IsContainer */;
    case 264 /* InterfaceDeclaration */:
      return 1 /* IsContainer */ | 64 /* IsInterface */;
    case 267 /* ModuleDeclaration */:
    case 265 /* TypeAliasDeclaration */:
    case 200 /* MappedType */:
    case 181 /* IndexSignature */:
      return 1 /* IsContainer */ | 32 /* HasLocals */;
    case 307 /* SourceFile */:
      return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
    case 174 /* MethodDeclaration */:
      if (isObjectLiteralOrClassExpressionMethodOrAccessor(node)) {
        return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */;
      }
    // falls through
    case 176 /* Constructor */:
    case 262 /* FunctionDeclaration */:
    case 173 /* MethodSignature */:
    case 179 /* CallSignature */:
    case 323 /* JSDocSignature */:
    case 317 /* JSDocFunctionType */:
    case 184 /* FunctionType */:
    case 180 /* ConstructSignature */:
    case 185 /* ConstructorType */:
    case 175 /* ClassStaticBlockDeclaration */:
      return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
      return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
    case 268 /* ModuleBlock */:
      return 4 /* IsControlFlowContainer */;
    case 172 /* PropertyDeclaration */:
      return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
    case 299 /* CatchClause */:
    case 248 /* ForStatement */:
    case 249 /* ForInStatement */:
    case 250 /* ForOfStatement */:
    case 269 /* CaseBlock */:
      return 2 /* IsBlockScopedContainer */ | 32 /* HasLocals */;
    case 241 /* Block */:
      return isFunctionLike(node.parent) || isClassStaticBlockDeclaration(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */ | 32 /* HasLocals */;
  }
  return 0 /* None */;
}
function lookupSymbolForName(container, name) {
  var _a, _b, _c, _d;
  const local = (_b = (_a = tryCast(container, canHaveLocals)) == null ? void 0 : _a.locals) == null ? void 0 : _b.get(name);
  if (local) {
    return local.exportSymbol ?? local;
  }
  if (isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
    return container.jsGlobalAugmentations.get(name);
  }
  if (canHaveSymbol(container)) {
    return (_d = (_c = container.symbol) == null ? void 0 : _c.exports) == null ? void 0 : _d.get(name);
  }
}

// src/compiler/symbolWalker.ts
function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getConstraintOfTypeParameter, getFirstIdentifier2, getTypeArguments) {
  return getSymbolWalker;
  function getSymbolWalker(accept = () => true) {
    const visitedTypes = [];
    const visitedSymbols = [];
    return {
      walkType: (type) => {
        try {
          visitType(type);
          return { visitedTypes: getOwnValues(visitedTypes), visitedSymbols: getOwnValues(visitedSymbols) };
        } finally {
          clear(visitedTypes);
          clear(visitedSymbols);
        }
      },
      walkSymbol: (symbol) => {
        try {
          visitSymbol(symbol);
          return { visitedTypes: getOwnValues(visitedTypes), visitedSymbols: getOwnValues(visitedSymbols) };
        } finally {
          clear(visitedTypes);
          clear(visitedSymbols);
        }
      }
    };
    function visitType(type) {
      if (!type) {
        return;
      }
      if (visitedTypes[type.id]) {
        return;
      }
      visitedTypes[type.id] = type;
      const shouldBail = visitSymbol(type.symbol);
      if (shouldBail) return;
      if (type.flags & 524288 /* Object */) {
        const objectType = type;
        const objectFlags = objectType.objectFlags;
        if (objectFlags & 4 /* Reference */) {
          visitTypeReference(type);
        }
        if (objectFlags & 32 /* Mapped */) {
          visitMappedType(type);
        }
        if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
          visitInterfaceType(type);
        }
        if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
          visitObjectType(objectType);
        }
      }
      if (type.flags & 262144 /* TypeParameter */) {
        visitTypeParameter(type);
      }
      if (type.flags & 3145728 /* UnionOrIntersection */) {
        visitUnionOrIntersectionType(type);
      }
      if (type.flags & 4194304 /* Index */) {
        visitIndexType(type);
      }
      if (type.flags & 8388608 /* IndexedAccess */) {
        visitIndexedAccessType(type);
      }
    }
    function visitTypeReference(type) {
      visitType(type.target);
      forEach(getTypeArguments(type), visitType);
    }
    function visitTypeParameter(type) {
      visitType(getConstraintOfTypeParameter(type));
    }
    function visitUnionOrIntersectionType(type) {
      forEach(type.types, visitType);
    }
    function visitIndexType(type) {
      visitType(type.type);
    }
    function visitIndexedAccessType(type) {
      visitType(type.objectType);
      visitType(type.indexType);
      visitType(type.constraint);
    }
    function visitMappedType(type) {
      visitType(type.typeParameter);
      visitType(type.constraintType);
      visitType(type.templateType);
      visitType(type.modifiersType);
    }
    function visitSignature(signature) {
      const typePredicate = getTypePredicateOfSignature(signature);
      if (typePredicate) {
        visitType(typePredicate.type);
      }
      forEach(signature.typeParameters, visitType);
      for (const parameter of signature.parameters) {
        visitSymbol(parameter);
      }
      visitType(getRestTypeOfSignature(signature));
      visitType(getReturnTypeOfSignature(signature));
    }
    function visitInterfaceType(interfaceT) {
      visitObjectType(interfaceT);
      forEach(interfaceT.typeParameters, visitType);
      forEach(getBaseTypes(interfaceT), visitType);
      visitType(interfaceT.thisType);
    }
    function visitObjectType(type) {
      const resolved = resolveStructuredTypeMembers(type);
      for (const info of resolved.indexInfos) {
        visitType(info.keyType);
        visitType(info.type);
      }
      for (const signature of resolved.callSignatures) {
        visitSignature(signature);
      }
      for (const signature of resolved.constructSignatures) {
        visitSignature(signature);
      }
      for (const p of resolved.properties) {
        visitSymbol(p);
      }
    }
    function visitSymbol(symbol) {
      if (!symbol) {
        return false;
      }
      const symbolId = getSymbolId(symbol);
      if (visitedSymbols[symbolId]) {
        return false;
      }
      visitedSymbols[symbolId] = symbol;
      if (!accept(symbol)) {
        return true;
      }
      const t = getTypeOfSymbol(symbol);
      visitType(t);
      if (symbol.exports) {
        symbol.exports.forEach(visitSymbol);
      }
      forEach(symbol.declarations, (d) => {
        if (d.type && d.type.kind === 186 /* TypeQuery */) {
          const query = d.type;
          const entity = getResolvedSymbol(getFirstIdentifier2(query.exprName));
          visitSymbol(entity);
        }
      });
      return false;
    }
  }
}

// src/compiler/moduleSpecifiers.ts
var stringToRegex = memoizeOne((pattern) => {
  try {
    let slash = pattern.indexOf("/");
    if (slash !== 0) {
      return new RegExp(pattern);
    }
    const lastSlash = pattern.lastIndexOf("/");
    if (slash === lastSlash) {
      return new RegExp(pattern);
    }
    while ((slash = pattern.indexOf("/", slash + 1)) !== lastSlash) {
      if (pattern[slash - 1] !== "\\") {
        return new RegExp(pattern);
      }
    }
    const flags = pattern.substring(lastSlash + 1).replace(/[^iu]/g, "");
    pattern = pattern.substring(1, lastSlash);
    return new RegExp(pattern, flags);
  } catch {
    return void 0;
  }
});
function getModuleSpecifierPreferences({ importModuleSpecifierPreference, importModuleSpecifierEnding, autoImportSpecifierExcludeRegexes }, host, compilerOptions, importingSourceFile, oldImportSpecifier) {
  const filePreferredEnding = getPreferredEnding();
  return {
    excludeRegexes: autoImportSpecifierExcludeRegexes,
    relativePreference: oldImportSpecifier !== void 0 ? isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */ : importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : importModuleSpecifierPreference === "project-relative" ? 3 /* ExternalNonRelative */ : 2 /* Shortest */,
    getAllowedEndingsInPreferredOrder: (syntaxImpliedNodeFormat) => {
      const impliedNodeFormat = getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions);
      const preferredEnding = syntaxImpliedNodeFormat !== impliedNodeFormat ? getPreferredEnding(syntaxImpliedNodeFormat) : filePreferredEnding;
      const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
      if ((syntaxImpliedNodeFormat ?? impliedNodeFormat) === 99 /* ESNext */ && 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */) {
        if (shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName)) {
          return [3 /* TsExtension */, 2 /* JsExtension */];
        }
        return [2 /* JsExtension */];
      }
      if (getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */) {
        return preferredEnding === 2 /* JsExtension */ ? [2 /* JsExtension */, 1 /* Index */] : [1 /* Index */, 2 /* JsExtension */];
      }
      const allowImportingTsExtension = shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName);
      switch (preferredEnding) {
        case 2 /* JsExtension */:
          return allowImportingTsExtension ? [2 /* JsExtension */, 3 /* TsExtension */, 0 /* Minimal */, 1 /* Index */] : [2 /* JsExtension */, 0 /* Minimal */, 1 /* Index */];
        case 3 /* TsExtension */:
          return [3 /* TsExtension */, 0 /* Minimal */, 2 /* JsExtension */, 1 /* Index */];
        case 1 /* Index */:
          return allowImportingTsExtension ? [1 /* Index */, 0 /* Minimal */, 3 /* TsExtension */, 2 /* JsExtension */] : [1 /* Index */, 0 /* Minimal */, 2 /* JsExtension */];
        case 0 /* Minimal */:
          return allowImportingTsExtension ? [0 /* Minimal */, 1 /* Index */, 3 /* TsExtension */, 2 /* JsExtension */] : [0 /* Minimal */, 1 /* Index */, 2 /* JsExtension */];
        default:
          Debug.assertNever(preferredEnding);
      }
    }
  };
  function getPreferredEnding(resolutionMode) {
    if (oldImportSpecifier !== void 0) {
      if (hasJSFileExtension(oldImportSpecifier)) return 2 /* JsExtension */;
      if (endsWith(oldImportSpecifier, "/index")) return 1 /* Index */;
    }
    return getModuleSpecifierEndingPreference(
      importModuleSpecifierEnding,
      resolutionMode ?? getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions),
      compilerOptions,
      isFullSourceFile(importingSourceFile) ? importingSourceFile : void 0
    );
  }
}
function tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences, options = {}) {
  var _a;
  const moduleSourceFile = getSourceFileOfModule(moduleSymbol);
  if (!moduleSourceFile) {
    return emptyArray;
  }
  const cache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host);
  const cached = cache == null ? void 0 : cache.get(importingSourceFile.path, moduleSourceFile.path, userPreferences, options);
  return [cached == null ? void 0 : cached.kind, cached == null ? void 0 : cached.moduleSpecifiers, moduleSourceFile, cached == null ? void 0 : cached.modulePaths, cache];
}
function getModuleSpecifiers(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}) {
  return getModuleSpecifiersWithCacheInfo(
    moduleSymbol,
    checker,
    compilerOptions,
    importingSourceFile,
    host,
    userPreferences,
    options,
    /*forAutoImport*/
    false
  ).moduleSpecifiers;
}
function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) {
  let computedWithoutCache = false;
  const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker);
  if (ambient) {
    return {
      kind: "ambient",
      moduleSpecifiers: !(forAutoImport && isExcludedByRegex(ambient, userPreferences.autoImportSpecifierExcludeRegexes)) ? [ambient] : emptyArray,
      computedWithoutCache
    };
  }
  let [kind, specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker(
    moduleSymbol,
    importingSourceFile,
    host,
    userPreferences,
    options
  );
  if (specifiers) return { kind, moduleSpecifiers: specifiers, computedWithoutCache };
  if (!moduleSourceFile) return { kind: void 0, moduleSpecifiers: emptyArray, computedWithoutCache };
  computedWithoutCache = true;
  modulePaths || (modulePaths = getAllModulePathsWorker(getInfo(importingSourceFile.fileName, host), moduleSourceFile.originalFileName, host, compilerOptions, options));
  const result = computeModuleSpecifiers(
    modulePaths,
    compilerOptions,
    importingSourceFile,
    host,
    userPreferences,
    options,
    forAutoImport
  );
  cache == null ? void 0 : cache.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, result.kind, modulePaths, result.moduleSpecifiers);
  return result;
}
function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) {
  const info = getInfo(importingSourceFile.fileName, host);
  const preferences = getModuleSpecifierPreferences(userPreferences, host, compilerOptions, importingSourceFile);
  const existingSpecifier = isFullSourceFile(importingSourceFile) && forEach(modulePaths, (modulePath) => forEach(
    host.getFileIncludeReasons().get(toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)),
    (reason) => {
      if (reason.kind !== 3 /* Import */ || reason.file !== importingSourceFile.path) return void 0;
      const existingMode = host.getModeForResolutionAtIndex(importingSourceFile, reason.index);
      const targetMode = options.overrideImportMode ?? host.getDefaultResolutionModeForFile(importingSourceFile);
      if (existingMode !== targetMode && existingMode !== void 0 && targetMode !== void 0) {
        return void 0;
      }
      const specifier = getModuleNameStringLiteralAt(importingSourceFile, reason.index).text;
      return preferences.relativePreference !== 1 /* NonRelative */ || !pathIsRelative(specifier) ? specifier : void 0;
    }
  ));
  if (existingSpecifier) {
    return { kind: void 0, moduleSpecifiers: [existingSpecifier], computedWithoutCache: true };
  }
  const importedFileIsInNodeModules = some(modulePaths, (p) => p.isInNodeModules);
  let nodeModulesSpecifiers;
  let pathsSpecifiers;
  let redirectPathsSpecifiers;
  let relativeSpecifiers;
  for (const modulePath of modulePaths) {
    const specifier = modulePath.isInNodeModules ? tryGetModuleNameAsNodeModule(
      modulePath,
      info,
      importingSourceFile,
      host,
      compilerOptions,
      userPreferences,
      /*packageNameOnly*/
      void 0,
      options.overrideImportMode
    ) : void 0;
    if (specifier && !(forAutoImport && isExcludedByRegex(specifier, preferences.excludeRegexes))) {
      nodeModulesSpecifiers = append(nodeModulesSpecifiers, specifier);
      if (modulePath.isRedirect) {
        return { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true };
      }
    }
    const local = getLocalModuleSpecifier(
      modulePath.path,
      info,
      compilerOptions,
      host,
      options.overrideImportMode || importingSourceFile.impliedNodeFormat,
      preferences,
      /*pathsOnly*/
      modulePath.isRedirect || !!specifier
    );
    if (!local || forAutoImport && isExcludedByRegex(local, preferences.excludeRegexes)) {
      continue;
    }
    if (modulePath.isRedirect) {
      redirectPathsSpecifiers = append(redirectPathsSpecifiers, local);
    } else if (pathIsBareSpecifier(local)) {
      if (pathContainsNodeModules(local)) {
        relativeSpecifiers = append(relativeSpecifiers, local);
      } else {
        pathsSpecifiers = append(pathsSpecifiers, local);
      }
    } else if (forAutoImport || !importedFileIsInNodeModules || modulePath.isInNodeModules) {
      relativeSpecifiers = append(relativeSpecifiers, local);
    }
  }
  return (pathsSpecifiers == null ? void 0 : pathsSpecifiers.length) ? { kind: "paths", moduleSpecifiers: pathsSpecifiers, computedWithoutCache: true } : (redirectPathsSpecifiers == null ? void 0 : redirectPathsSpecifiers.length) ? { kind: "redirect", moduleSpecifiers: redirectPathsSpecifiers, computedWithoutCache: true } : (nodeModulesSpecifiers == null ? void 0 : nodeModulesSpecifiers.length) ? { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true } : { kind: "relative", moduleSpecifiers: relativeSpecifiers ?? emptyArray, computedWithoutCache: true };
}
function isExcludedByRegex(moduleSpecifier, excludeRegexes) {
  return some(excludeRegexes, (pattern) => {
    var _a;
    return !!((_a = stringToRegex(pattern)) == null ? void 0 : _a.test(moduleSpecifier));
  });
}
function getInfo(importingSourceFileName, host) {
  importingSourceFileName = getNormalizedAbsolutePath(importingSourceFileName, host.getCurrentDirectory());
  const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
  const sourceDirectory = getDirectoryPath(importingSourceFileName);
  return {
    getCanonicalFileName,
    importingSourceFileName,
    sourceDirectory,
    canonicalSourceDirectory: getCanonicalFileName(sourceDirectory)
  };
}
function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, { getAllowedEndingsInPreferredOrder: getAllowedEndingsInPrefererredOrder, relativePreference, excludeRegexes }, pathsOnly) {
  const { baseUrl, paths, rootDirs } = compilerOptions;
  if (pathsOnly && !paths) {
    return void 0;
  }
  const { sourceDirectory, canonicalSourceDirectory, getCanonicalFileName } = info;
  const allowedEndings = getAllowedEndingsInPrefererredOrder(importMode);
  const relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, allowedEndings, compilerOptions) || processEnding(ensurePathIsNonModuleName(getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), allowedEndings, compilerOptions);
  if (!baseUrl && !paths && !getResolvePackageJsonImports(compilerOptions) || relativePreference === 0 /* Relative */) {
    return pathsOnly ? void 0 : relativePath;
  }
  const baseDirectory = getNormalizedAbsolutePath(getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory());
  const relativeToBaseUrl = getRelativePathIfInSameVolume(moduleFileName, baseDirectory, getCanonicalFileName);
  if (!relativeToBaseUrl) {
    return pathsOnly ? void 0 : relativePath;
  }
  const fromPackageJsonImports = pathsOnly ? void 0 : tryGetModuleNameFromPackageJsonImports(
    moduleFileName,
    sourceDirectory,
    compilerOptions,
    host,
    importMode,
    prefersTsExtension(allowedEndings)
  );
  const fromPaths = pathsOnly || fromPackageJsonImports === void 0 ? paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, baseDirectory, getCanonicalFileName, host, compilerOptions) : void 0;
  if (pathsOnly) {
    return fromPaths;
  }
  const maybeNonRelative = fromPackageJsonImports ?? (fromPaths === void 0 && baseUrl !== void 0 ? processEnding(relativeToBaseUrl, allowedEndings, compilerOptions) : fromPaths);
  if (!maybeNonRelative) {
    return relativePath;
  }
  const relativeIsExcluded = isExcludedByRegex(relativePath, excludeRegexes);
  const nonRelativeIsExcluded = isExcludedByRegex(maybeNonRelative, excludeRegexes);
  if (!relativeIsExcluded && nonRelativeIsExcluded) {
    return relativePath;
  }
  if (relativeIsExcluded && !nonRelativeIsExcluded) {
    return maybeNonRelative;
  }
  if (relativePreference === 1 /* NonRelative */ && !pathIsRelative(maybeNonRelative)) {
    return maybeNonRelative;
  }
  if (relativePreference === 3 /* ExternalNonRelative */ && !pathIsRelative(maybeNonRelative)) {
    const projectDirectory = compilerOptions.configFilePath ? toPath(getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : info.getCanonicalFileName(host.getCurrentDirectory());
    const modulePath = toPath(moduleFileName, projectDirectory, getCanonicalFileName);
    const sourceIsInternal = startsWith(canonicalSourceDirectory, projectDirectory);
    const targetIsInternal = startsWith(modulePath, projectDirectory);
    if (sourceIsInternal && !targetIsInternal || !sourceIsInternal && targetIsInternal) {
      return maybeNonRelative;
    }
    const nearestTargetPackageJson = getNearestAncestorDirectoryWithPackageJson(host, getDirectoryPath(modulePath));
    const nearestSourcePackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory);
    const ignoreCase = !hostUsesCaseSensitiveFileNames(host);
    if (!packageJsonPathsAreEqual(nearestTargetPackageJson, nearestSourcePackageJson, ignoreCase)) {
      return maybeNonRelative;
    }
    return relativePath;
  }
  return isPathRelativeToParent(maybeNonRelative) || countPathComponents(relativePath) < countPathComponents(maybeNonRelative) ? relativePath : maybeNonRelative;
}
function packageJsonPathsAreEqual(a, b, ignoreCase) {
  if (a === b) return true;
  if (a === void 0 || b === void 0) return false;
  return comparePaths(a, b, ignoreCase) === 0 /* EqualTo */;
}
function countPathComponents(path) {
  let count = 0;
  for (let i = startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
    if (path.charCodeAt(i) === 47 /* slash */) count++;
  }
  return count;
}
function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) {
  return compareBooleans(b.isRedirect, a.isRedirect) || compareNumberOfDirectorySeparators(a.path, b.path);
}
function getNearestAncestorDirectoryWithPackageJson(host, fileName) {
  if (host.getNearestAncestorDirectoryWithPackageJson) {
    return host.getNearestAncestorDirectoryWithPackageJson(fileName);
  }
  return forEachAncestorDirectoryStoppingAtGlobalCache(
    host,
    fileName,
    (directory) => host.fileExists(combinePaths(directory, "package.json")) ? directory : void 0
  );
}
function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
  var _a;
  const getCanonicalFileName = hostGetCanonicalFileName(host);
  const cwd = host.getCurrentDirectory();
  const referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : void 0;
  const importedPath = toPath(importedFileName, cwd, getCanonicalFileName);
  const redirects = host.redirectTargetsMap.get(importedPath) || emptyArray;
  const importedFileNames = [...referenceRedirect ? [referenceRedirect] : emptyArray, importedFileName, ...redirects];
  const targets = importedFileNames.map((f) => getNormalizedAbsolutePath(f, cwd));
  let shouldFilterIgnoredPaths = !every(targets, containsIgnoredPath);
  if (!preferSymlinks) {
    const result2 = forEach(targets, (p) => !(shouldFilterIgnoredPaths && containsIgnoredPath(p)) && cb(p, referenceRedirect === p));
    if (result2) return result2;
  }
  const symlinkedDirectories = (_a = host.getSymlinkCache) == null ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath();
  const fullImportedFileName = getNormalizedAbsolutePath(importedFileName, cwd);
  const result = symlinkedDirectories && forEachAncestorDirectoryStoppingAtGlobalCache(
    host,
    getDirectoryPath(fullImportedFileName),
    (realPathDirectory) => {
      const symlinkDirectories = symlinkedDirectories.get(ensureTrailingDirectorySeparator(toPath(realPathDirectory, cwd, getCanonicalFileName)));
      if (!symlinkDirectories) return void 0;
      if (startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) {
        return false;
      }
      return forEach(targets, (target) => {
        if (!startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) {
          return;
        }
        const relative = getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName);
        for (const symlinkDirectory of symlinkDirectories) {
          const option = resolvePath(symlinkDirectory, relative);
          const result2 = cb(option, target === referenceRedirect);
          shouldFilterIgnoredPaths = true;
          if (result2) return result2;
        }
      });
    }
  );
  return result || (preferSymlinks ? forEach(targets, (p) => shouldFilterIgnoredPaths && containsIgnoredPath(p) ? void 0 : cb(p, p === referenceRedirect)) : void 0);
}
var runtimeDependencyFields = ["dependencies", "peerDependencies", "optionalDependencies"];
function getAllRuntimeDependencies(packageJson) {
  let result;
  for (const field of runtimeDependencyFields) {
    const deps = packageJson[field];
    if (deps && typeof deps === "object") {
      result = concatenate(result, getOwnKeys(deps));
    }
  }
  return result;
}
function getAllModulePathsWorker(info, importedFileName, host, compilerOptions, options) {
  var _a, _b;
  const cache = (_a = host.getModuleResolutionCache) == null ? void 0 : _a.call(host);
  const links = (_b = host.getSymlinkCache) == null ? void 0 : _b.call(host);
  if (cache && links && host.readFile && !pathContainsNodeModules(info.importingSourceFileName)) {
    Debug.type(host);
    const state = getTemporaryModuleResolutionState(cache.getPackageJsonInfoCache(), host, {});
    const packageJson = getPackageScopeForPath(getDirectoryPath(info.importingSourceFileName), state);
    if (packageJson) {
      const toResolve = getAllRuntimeDependencies(packageJson.contents.packageJsonContent);
      for (const depName of toResolve || emptyArray) {
        const resolved = resolveModuleName(
          depName,
          combinePaths(packageJson.packageDirectory, "package.json"),
          compilerOptions,
          host,
          cache,
          /*redirectedReference*/
          void 0,
          options.overrideImportMode
        );
        links.setSymlinksFromResolution(resolved.resolvedModule);
      }
    }
  }
  const allFileNames = /* @__PURE__ */ new Map();
  let importedFileFromNodeModules = false;
  forEachFileNameOfModule(
    info.importingSourceFileName,
    importedFileName,
    host,
    /*preferSymlinks*/
    true,
    (path, isRedirect) => {
      const isInNodeModules = pathContainsNodeModules(path);
      allFileNames.set(path, { path: info.getCanonicalFileName(path), isRedirect, isInNodeModules });
      importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules;
    }
  );
  const sortedPaths = [];
  for (let directory = info.canonicalSourceDirectory; allFileNames.size !== 0; ) {
    const directoryStart = ensureTrailingDirectorySeparator(directory);
    let pathsInDirectory;
    allFileNames.forEach(({ path, isRedirect, isInNodeModules }, fileName) => {
      if (startsWith(path, directoryStart)) {
        (pathsInDirectory || (pathsInDirectory = [])).push({ path: fileName, isRedirect, isInNodeModules });
        allFileNames.delete(fileName);
      }
    });
    if (pathsInDirectory) {
      if (pathsInDirectory.length > 1) {
        pathsInDirectory.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
      }
      sortedPaths.push(...pathsInDirectory);
    }
    const newDirectory = getDirectoryPath(directory);
    if (newDirectory === directory) break;
    directory = newDirectory;
  }
  if (allFileNames.size) {
    const remainingPaths = arrayFrom(
      allFileNames.entries(),
      ([fileName, { isRedirect, isInNodeModules }]) => ({ path: fileName, isRedirect, isInNodeModules })
    );
    if (remainingPaths.length > 1) remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
    sortedPaths.push(...remainingPaths);
  }
  return sortedPaths;
}
function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) {
  var _a;
  const decl = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(
    (d) => isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name)))
  );
  if (decl) {
    return decl.name.text;
  }
  const ambientModuleDeclareCandidates = mapDefined(moduleSymbol.declarations, (d) => {
    var _a2, _b, _c, _d;
    if (!isModuleDeclaration(d)) return;
    const topNamespace = getTopNamespace(d);
    if (!(((_a2 = topNamespace == null ? void 0 : topNamespace.parent) == null ? void 0 : _a2.parent) && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) return;
    const exportAssignment = (_d = (_c = (_b = topNamespace.parent.parent.symbol.exports) == null ? void 0 : _b.get("export=")) == null ? void 0 : _c.valueDeclaration) == null ? void 0 : _d.expression;
    if (!exportAssignment) return;
    const exportSymbol = checker.getSymbolAtLocation(exportAssignment);
    if (!exportSymbol) return;
    const originalExportSymbol = (exportSymbol == null ? void 0 : exportSymbol.flags) & 2097152 /* Alias */ ? checker.getAliasedSymbol(exportSymbol) : exportSymbol;
    if (originalExportSymbol === d.symbol) return topNamespace.parent.parent;
    function getTopNamespace(namespaceDeclaration) {
      while (namespaceDeclaration.flags & 8 /* NestedNamespace */) {
        namespaceDeclaration = namespaceDeclaration.parent;
      }
      return namespaceDeclaration;
    }
  });
  const ambientModuleDeclare = ambientModuleDeclareCandidates[0];
  if (ambientModuleDeclare) {
    return ambientModuleDeclare.name.text;
  }
}
function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, baseDirectory, getCanonicalFileName, host, compilerOptions) {
  for (const key in paths) {
    for (const patternText2 of paths[key]) {
      const normalized = normalizePath(patternText2);
      const pattern = getRelativePathIfInSameVolume(normalized, baseDirectory, getCanonicalFileName) ?? normalized;
      const indexOfStar = pattern.indexOf("*");
      const candidates = allowedEndings.map((ending) => ({
        ending,
        value: processEnding(relativeToBaseUrl, [ending], compilerOptions)
      }));
      if (tryGetExtensionFromPath2(pattern)) {
        candidates.push({ ending: void 0, value: relativeToBaseUrl });
      }
      if (indexOfStar !== -1) {
        const prefix = pattern.substring(0, indexOfStar);
        const suffix = pattern.substring(indexOfStar + 1);
        for (const { ending, value } of candidates) {
          if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) {
            const matchedStar = value.substring(prefix.length, value.length - suffix.length);
            if (!pathIsRelative(matchedStar)) {
              return replaceFirstStar(key, matchedStar);
            }
          }
        }
      } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) {
        return key;
      }
    }
  }
  function validateEnding({ ending, value }) {
    return ending !== 0 /* Minimal */ || value === processEnding(relativeToBaseUrl, [ending], compilerOptions, host);
  }
}
function tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, exports2, conditions, mode, isImports, preferTsExtension) {
  if (typeof exports2 === "string") {
    const ignoreCase = !hostUsesCaseSensitiveFileNames(host);
    const getCommonSourceDirectory2 = () => host.getCommonSourceDirectory();
    const outputFile = isImports && getOutputJSFileNameWorker(targetFilePath, options, ignoreCase, getCommonSourceDirectory2);
    const declarationFile = isImports && getOutputDeclarationFileNameWorker(targetFilePath, options, ignoreCase, getCommonSourceDirectory2);
    const pathOrPattern = getNormalizedAbsolutePath(
      combinePaths(packageDirectory, exports2),
      /*currentDirectory*/
      void 0
    );
    const extensionSwappedTarget = hasTSFileExtension(targetFilePath) ? removeFileExtension(targetFilePath) + tryGetJSExtensionForFile(targetFilePath, options) : void 0;
    const canTryTsExtension = preferTsExtension && hasImplementationTSFileExtension(targetFilePath);
    switch (mode) {
      case 0 /* Exact */:
        if (extensionSwappedTarget && comparePaths(extensionSwappedTarget, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || comparePaths(targetFilePath, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || outputFile && comparePaths(outputFile, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || declarationFile && comparePaths(declarationFile, pathOrPattern, ignoreCase) === 0 /* EqualTo */) {
          return { moduleFileToTry: packageName };
        }
        break;
      case 1 /* Directory */:
        if (canTryTsExtension && containsPath(targetFilePath, pathOrPattern, ignoreCase)) {
          const fragment = getRelativePathFromDirectory(
            pathOrPattern,
            targetFilePath,
            /*ignoreCase*/
            false
          );
          return { moduleFileToTry: getNormalizedAbsolutePath(
            combinePaths(combinePaths(packageName, exports2), fragment),
            /*currentDirectory*/
            void 0
          ) };
        }
        if (extensionSwappedTarget && containsPath(pathOrPattern, extensionSwappedTarget, ignoreCase)) {
          const fragment = getRelativePathFromDirectory(
            pathOrPattern,
            extensionSwappedTarget,
            /*ignoreCase*/
            false
          );
          return { moduleFileToTry: getNormalizedAbsolutePath(
            combinePaths(combinePaths(packageName, exports2), fragment),
            /*currentDirectory*/
            void 0
          ) };
        }
        if (!canTryTsExtension && containsPath(pathOrPattern, targetFilePath, ignoreCase)) {
          const fragment = getRelativePathFromDirectory(
            pathOrPattern,
            targetFilePath,
            /*ignoreCase*/
            false
          );
          return { moduleFileToTry: getNormalizedAbsolutePath(
            combinePaths(combinePaths(packageName, exports2), fragment),
            /*currentDirectory*/
            void 0
          ) };
        }
        if (outputFile && containsPath(pathOrPattern, outputFile, ignoreCase)) {
          const fragment = getRelativePathFromDirectory(
            pathOrPattern,
            outputFile,
            /*ignoreCase*/
            false
          );
          return { moduleFileToTry: combinePaths(packageName, fragment) };
        }
        if (declarationFile && containsPath(pathOrPattern, declarationFile, ignoreCase)) {
          const fragment = changeFullExtension(getRelativePathFromDirectory(
            pathOrPattern,
            declarationFile,
            /*ignoreCase*/
            false
          ), getJSExtensionForFile(declarationFile, options));
          return { moduleFileToTry: combinePaths(packageName, fragment) };
        }
        break;
      case 2 /* Pattern */:
        const starPos = pathOrPattern.indexOf("*");
        const leadingSlice = pathOrPattern.slice(0, starPos);
        const trailingSlice = pathOrPattern.slice(starPos + 1);
        if (canTryTsExtension && startsWith(targetFilePath, leadingSlice, ignoreCase) && endsWith(targetFilePath, trailingSlice, ignoreCase)) {
          const starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length);
          return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) };
        }
        if (extensionSwappedTarget && startsWith(extensionSwappedTarget, leadingSlice, ignoreCase) && endsWith(extensionSwappedTarget, trailingSlice, ignoreCase)) {
          const starReplacement = extensionSwappedTarget.slice(leadingSlice.length, extensionSwappedTarget.length - trailingSlice.length);
          return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) };
        }
        if (!canTryTsExtension && startsWith(targetFilePath, leadingSlice, ignoreCase) && endsWith(targetFilePath, trailingSlice, ignoreCase)) {
          const starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length);
          return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) };
        }
        if (outputFile && startsWith(outputFile, leadingSlice, ignoreCase) && endsWith(outputFile, trailingSlice, ignoreCase)) {
          const starReplacement = outputFile.slice(leadingSlice.length, outputFile.length - trailingSlice.length);
          return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) };
        }
        if (declarationFile && startsWith(declarationFile, leadingSlice, ignoreCase) && endsWith(declarationFile, trailingSlice, ignoreCase)) {
          const starReplacement = declarationFile.slice(leadingSlice.length, declarationFile.length - trailingSlice.length);
          const substituted = replaceFirstStar(packageName, starReplacement);
          const jsExtension = tryGetJSExtensionForFile(declarationFile, options);
          return jsExtension ? { moduleFileToTry: changeFullExtension(substituted, jsExtension) } : void 0;
        }
        break;
    }
  } else if (Array.isArray(exports2)) {
    return forEach(exports2, (e) => tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, e, conditions, mode, isImports, preferTsExtension));
  } else if (typeof exports2 === "object" && exports2 !== null) {
    for (const key of getOwnKeys(exports2)) {
      if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) {
        const subTarget = exports2[key];
        const result = tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode, isImports, preferTsExtension);
        if (result) {
          return result;
        }
      }
    }
  }
  return void 0;
}
function tryGetModuleNameFromExports(options, host, targetFilePath, packageDirectory, packageName, exports2, conditions) {
  if (typeof exports2 === "object" && exports2 !== null && !Array.isArray(exports2) && allKeysStartWithDot(exports2)) {
    return forEach(getOwnKeys(exports2), (k) => {
      const subPackageName = getNormalizedAbsolutePath(
        combinePaths(packageName, k),
        /*currentDirectory*/
        void 0
      );
      const mode = endsWith(k, "/") ? 1 /* Directory */ : k.includes("*") ? 2 /* Pattern */ : 0 /* Exact */;
      return tryGetModuleNameFromExportsOrImports(
        options,
        host,
        targetFilePath,
        packageDirectory,
        subPackageName,
        exports2[k],
        conditions,
        mode,
        /*isImports*/
        false,
        /*preferTsExtension*/
        false
      );
    });
  }
  return tryGetModuleNameFromExportsOrImports(
    options,
    host,
    targetFilePath,
    packageDirectory,
    packageName,
    exports2,
    conditions,
    0 /* Exact */,
    /*isImports*/
    false,
    /*preferTsExtension*/
    false
  );
}
function tryGetModuleNameFromPackageJsonImports(moduleFileName, sourceDirectory, options, host, importMode, preferTsExtension) {
  var _a, _b, _c;
  if (!host.readFile || !getResolvePackageJsonImports(options)) {
    return void 0;
  }
  const ancestorDirectoryWithPackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory);
  if (!ancestorDirectoryWithPackageJson) {
    return void 0;
  }
  const packageJsonPath = combinePaths(ancestorDirectoryWithPackageJson, "package.json");
  const cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
  if (isMissingPackageJsonInfo(cachedPackageJson) || !host.fileExists(packageJsonPath)) {
    return void 0;
  }
  const packageJsonContent = (cachedPackageJson == null ? void 0 : cachedPackageJson.contents.packageJsonContent) || tryParseJson(host.readFile(packageJsonPath));
  const imports = packageJsonContent == null ? void 0 : packageJsonContent.imports;
  if (!imports) {
    return void 0;
  }
  const conditions = getConditions(options, importMode);
  return (_c = forEach(getOwnKeys(imports), (k) => {
    if (!startsWith(k, "#") || k === "#" || startsWith(k, "#/")) return void 0;
    const mode = endsWith(k, "/") ? 1 /* Directory */ : k.includes("*") ? 2 /* Pattern */ : 0 /* Exact */;
    return tryGetModuleNameFromExportsOrImports(
      options,
      host,
      moduleFileName,
      ancestorDirectoryWithPackageJson,
      k,
      imports[k],
      conditions,
      mode,
      /*isImports*/
      true,
      preferTsExtension
    );
  })) == null ? void 0 : _c.moduleFileToTry;
}
function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, allowedEndings, compilerOptions) {
  const normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
  if (normalizedTargetPaths === void 0) {
    return void 0;
  }
  const normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
  const relativePaths = flatMap(normalizedSourcePaths, (sourcePath) => {
    return map(normalizedTargetPaths, (targetPath) => ensurePathIsNonModuleName(getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName)));
  });
  const shortest = min(relativePaths, compareNumberOfDirectorySeparators);
  if (!shortest) {
    return void 0;
  }
  return processEnding(shortest, allowedEndings, compilerOptions);
}
function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileName, canonicalSourceDirectory }, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) {
  if (!host.fileExists || !host.readFile) {
    return void 0;
  }
  const parts = getNodeModulePathParts(path);
  if (!parts) {
    return void 0;
  }
  const preferences = getModuleSpecifierPreferences(userPreferences, host, options, importingSourceFile);
  const allowedEndings = preferences.getAllowedEndingsInPreferredOrder();
  let moduleSpecifier = path;
  let isPackageRootPath = false;
  if (!packageNameOnly) {
    let packageRootIndex = parts.packageRootIndex;
    let moduleFileName;
    while (true) {
      const { moduleFileToTry, packageRootPath, blockedByExports, verbatimFromExports } = tryDirectoryWithPackageJson(packageRootIndex);
      if (getEmitModuleResolutionKind(options) !== 1 /* Classic */) {
        if (blockedByExports) {
          return void 0;
        }
        if (verbatimFromExports) {
          return moduleFileToTry;
        }
      }
      if (packageRootPath) {
        moduleSpecifier = packageRootPath;
        isPackageRootPath = true;
        break;
      }
      if (!moduleFileName) moduleFileName = moduleFileToTry;
      packageRootIndex = path.indexOf(directorySeparator, packageRootIndex + 1);
      if (packageRootIndex === -1) {
        moduleSpecifier = processEnding(moduleFileName, allowedEndings, options, host);
        break;
      }
    }
  }
  if (isRedirect && !isPackageRootPath) {
    return void 0;
  }
  const globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
  const pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
  if (!(startsWith(canonicalSourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
    return void 0;
  }
  const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
  const packageName = getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
  return getEmitModuleResolutionKind(options) === 1 /* Classic */ && packageName === nodeModulesDirectoryName ? void 0 : packageName;
  function tryDirectoryWithPackageJson(packageRootIndex) {
    var _a, _b;
    const packageRootPath = path.substring(0, packageRootIndex);
    const packageJsonPath = combinePaths(packageRootPath, "package.json");
    let moduleFileToTry = path;
    let maybeBlockedByTypesVersions = false;
    const cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
    if (isPackageJsonInfo(cachedPackageJson) || cachedPackageJson === void 0 && host.fileExists(packageJsonPath)) {
      const packageJsonContent = (cachedPackageJson == null ? void 0 : cachedPackageJson.contents.packageJsonContent) || tryParseJson(host.readFile(packageJsonPath));
      const importMode = overrideMode || getDefaultResolutionModeForFile(importingSourceFile, host, options);
      if (getResolvePackageJsonExports(options)) {
        const nodeModulesDirectoryName2 = packageRootPath.substring(parts.topLevelPackageNameIndex + 1);
        const packageName2 = getPackageNameFromTypesPackageName(nodeModulesDirectoryName2);
        const conditions = getConditions(options, importMode);
        const fromExports = (packageJsonContent == null ? void 0 : packageJsonContent.exports) ? tryGetModuleNameFromExports(
          options,
          host,
          path,
          packageRootPath,
          packageName2,
          packageJsonContent.exports,
          conditions
        ) : void 0;
        if (fromExports) {
          return { ...fromExports, verbatimFromExports: true };
        }
        if (packageJsonContent == null ? void 0 : packageJsonContent.exports) {
          return { moduleFileToTry: path, blockedByExports: true };
        }
      }
      const versionPaths = (packageJsonContent == null ? void 0 : packageJsonContent.typesVersions) ? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) : void 0;
      if (versionPaths) {
        const subModuleName = path.slice(packageRootPath.length + 1);
        const fromPaths = tryGetModuleNameFromPaths(
          subModuleName,
          versionPaths.paths,
          allowedEndings,
          packageRootPath,
          getCanonicalFileName,
          host,
          options
        );
        if (fromPaths === void 0) {
          maybeBlockedByTypesVersions = true;
        } else {
          moduleFileToTry = combinePaths(packageRootPath, fromPaths);
        }
      }
      const mainFileRelative = (packageJsonContent == null ? void 0 : packageJsonContent.typings) || (packageJsonContent == null ? void 0 : packageJsonContent.types) || (packageJsonContent == null ? void 0 : packageJsonContent.main) || "index.js";
      if (isString(mainFileRelative) && !(maybeBlockedByTypesVersions && matchPatternOrExact(tryParsePatterns(versionPaths.paths), mainFileRelative))) {
        const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
        const canonicalModuleFileToTry = getCanonicalFileName(moduleFileToTry);
        if (removeFileExtension(mainExportFile) === removeFileExtension(canonicalModuleFileToTry)) {
          return { packageRootPath, moduleFileToTry };
        } else if ((packageJsonContent == null ? void 0 : packageJsonContent.type) !== "module" && !fileExtensionIsOneOf(canonicalModuleFileToTry, extensionsNotSupportingExtensionlessResolution) && startsWith(canonicalModuleFileToTry, mainExportFile) && getDirectoryPath(canonicalModuleFileToTry) === removeTrailingDirectorySeparator(mainExportFile) && removeFileExtension(getBaseFileName(canonicalModuleFileToTry)) === "index") {
          return { packageRootPath, moduleFileToTry };
        }
      }
    } else {
      const fileName = getCanonicalFileName(moduleFileToTry.substring(parts.packageRootIndex + 1));
      if (fileName === "index.d.ts" || fileName === "index.js" || fileName === "index.ts" || fileName === "index.tsx") {
        return { moduleFileToTry, packageRootPath };
      }
    }
    return { moduleFileToTry };
  }
}
function tryGetAnyFileFromPath(host, path) {
  if (!host.fileExists) return;
  const extensions = flatten(getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]));
  for (const e of extensions) {
    const fullPath = path + e;
    if (host.fileExists(fullPath)) {
      return fullPath;
    }
  }
}
function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
  return mapDefined(rootDirs, (rootDir) => {
    const relativePath = getRelativePathIfInSameVolume(path, rootDir, getCanonicalFileName);
    return relativePath !== void 0 && isPathRelativeToParent(relativePath) ? void 0 : relativePath;
  });
}
function processEnding(fileName, allowedEndings, options, host) {
  if (fileExtensionIsOneOf(fileName, [".json" /* Json */, ".mjs" /* Mjs */, ".cjs" /* Cjs */])) {
    return fileName;
  }
  const noExtension = removeFileExtension(fileName);
  if (fileName === noExtension) {
    return fileName;
  }
  const jsPriority = allowedEndings.indexOf(2 /* JsExtension */);
  const tsPriority = allowedEndings.indexOf(3 /* TsExtension */);
  if (fileExtensionIsOneOf(fileName, [".mts" /* Mts */, ".cts" /* Cts */]) && tsPriority !== -1 && tsPriority < jsPriority) {
    return fileName;
  } else if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) {
    return noExtension + getJSExtensionForFile(fileName, options);
  } else if (!fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */]) && fileExtensionIsOneOf(fileName, [".ts" /* Ts */]) && fileName.includes(".d.")) {
    return tryGetRealFileNameForNonJsDeclarationFileName(fileName);
  }
  switch (allowedEndings[0]) {
    case 0 /* Minimal */:
      const withoutIndex = removeSuffix(noExtension, "/index");
      if (host && withoutIndex !== noExtension && tryGetAnyFileFromPath(host, withoutIndex)) {
        return noExtension;
      }
      return withoutIndex;
    case 1 /* Index */:
      return noExtension;
    case 2 /* JsExtension */:
      return noExtension + getJSExtensionForFile(fileName, options);
    case 3 /* TsExtension */:
      if (isDeclarationFileName(fileName)) {
        const extensionlessPriority = allowedEndings.findIndex((e) => e === 0 /* Minimal */ || e === 1 /* Index */);
        return extensionlessPriority !== -1 && extensionlessPriority < jsPriority ? noExtension : noExtension + getJSExtensionForFile(fileName, options);
      }
      return fileName;
    default:
      return Debug.assertNever(allowedEndings[0]);
  }
}
function tryGetRealFileNameForNonJsDeclarationFileName(fileName) {
  const baseName = getBaseFileName(fileName);
  if (!endsWith(fileName, ".ts" /* Ts */) || !baseName.includes(".d.") || fileExtensionIsOneOf(baseName, [".d.ts" /* Dts */])) return void 0;
  const noExtension = removeExtension(fileName, ".ts" /* Ts */);
  const ext = noExtension.substring(noExtension.lastIndexOf("."));
  return noExtension.substring(0, noExtension.indexOf(".d.")) + ext;
}
function getJSExtensionForFile(fileName, options) {
  return tryGetJSExtensionForFile(fileName, options) ?? Debug.fail(`Extension ${extensionFromPath(fileName)} is unsupported:: FileName:: ${fileName}`);
}
function tryGetJSExtensionForFile(fileName, options) {
  const ext = tryGetExtensionFromPath2(fileName);
  switch (ext) {
    case ".ts" /* Ts */:
    case ".d.ts" /* Dts */:
      return ".js" /* Js */;
    case ".tsx" /* Tsx */:
      return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
    case ".js" /* Js */:
    case ".jsx" /* Jsx */:
    case ".json" /* Json */:
      return ext;
    case ".d.mts" /* Dmts */:
    case ".mts" /* Mts */:
    case ".mjs" /* Mjs */:
      return ".mjs" /* Mjs */;
    case ".d.cts" /* Dcts */:
    case ".cts" /* Cts */:
    case ".cjs" /* Cjs */:
      return ".cjs" /* Cjs */;
    default:
      return void 0;
  }
}
function getRelativePathIfInSameVolume(path, directoryPath, getCanonicalFileName) {
  const relativePath = getRelativePathToDirectoryOrUrl(
    directoryPath,
    path,
    directoryPath,
    getCanonicalFileName,
    /*isAbsolutePathAnUrl*/
    false
  );
  return isRootedDiskPath(relativePath) ? void 0 : relativePath;
}
function isPathRelativeToParent(path) {
  return startsWith(path, "..");
}
function getDefaultResolutionModeForFile(file, host, compilerOptions) {
  return isFullSourceFile(file) ? host.getDefaultResolutionModeForFile(file) : getDefaultResolutionModeForFileWorker(file, compilerOptions);
}
function prefersTsExtension(allowedEndings) {
  const tsPriority = allowedEndings.indexOf(3 /* TsExtension */);
  return tsPriority > -1 && tsPriority < allowedEndings.indexOf(2 /* JsExtension */);
}

// src/compiler/checker.ts
var ambientModuleSymbolRegex = /^".+"$/;
var anon = "(anonymous)";
var nextSymbolId = 1;
var nextNodeId = 1;
var nextMergeId = 1;
var nextFlowId = 1;
var TypeFacts = /* @__PURE__ */ ((TypeFacts3) => {
  TypeFacts3[TypeFacts3["None"] = 0] = "None";
  TypeFacts3[TypeFacts3["TypeofEQString"] = 1] = "TypeofEQString";
  TypeFacts3[TypeFacts3["TypeofEQNumber"] = 2] = "TypeofEQNumber";
  TypeFacts3[TypeFacts3["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
  TypeFacts3[TypeFacts3["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
  TypeFacts3[TypeFacts3["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
  TypeFacts3[TypeFacts3["TypeofEQObject"] = 32] = "TypeofEQObject";
  TypeFacts3[TypeFacts3["TypeofEQFunction"] = 64] = "TypeofEQFunction";
  TypeFacts3[TypeFacts3["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
  TypeFacts3[TypeFacts3["TypeofNEString"] = 256] = "TypeofNEString";
  TypeFacts3[TypeFacts3["TypeofNENumber"] = 512] = "TypeofNENumber";
  TypeFacts3[TypeFacts3["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
  TypeFacts3[TypeFacts3["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
  TypeFacts3[TypeFacts3["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
  TypeFacts3[TypeFacts3["TypeofNEObject"] = 8192] = "TypeofNEObject";
  TypeFacts3[TypeFacts3["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
  TypeFacts3[TypeFacts3["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
  TypeFacts3[TypeFacts3["EQUndefined"] = 65536] = "EQUndefined";
  TypeFacts3[TypeFacts3["EQNull"] = 131072] = "EQNull";
  TypeFacts3[TypeFacts3["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
  TypeFacts3[TypeFacts3["NEUndefined"] = 524288] = "NEUndefined";
  TypeFacts3[TypeFacts3["NENull"] = 1048576] = "NENull";
  TypeFacts3[TypeFacts3["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
  TypeFacts3[TypeFacts3["Truthy"] = 4194304] = "Truthy";
  TypeFacts3[TypeFacts3["Falsy"] = 8388608] = "Falsy";
  TypeFacts3[TypeFacts3["IsUndefined"] = 16777216] = "IsUndefined";
  TypeFacts3[TypeFacts3["IsNull"] = 33554432] = "IsNull";
  TypeFacts3[TypeFacts3["IsUndefinedOrNull"] = 50331648] = "IsUndefinedOrNull";
  TypeFacts3[TypeFacts3["All"] = 134217727] = "All";
  TypeFacts3[TypeFacts3["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
  TypeFacts3[TypeFacts3["BaseStringFacts"] = 12582401] = "BaseStringFacts";
  TypeFacts3[TypeFacts3["StringStrictFacts"] = 16317953] = "StringStrictFacts";
  TypeFacts3[TypeFacts3["StringFacts"] = 16776705] = "StringFacts";
  TypeFacts3[TypeFacts3["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
  TypeFacts3[TypeFacts3["EmptyStringFacts"] = 12582401 /* BaseStringFacts */] = "EmptyStringFacts";
  TypeFacts3[TypeFacts3["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
  TypeFacts3[TypeFacts3["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
  TypeFacts3[TypeFacts3["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
  TypeFacts3[TypeFacts3["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
  TypeFacts3[TypeFacts3["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
  TypeFacts3[TypeFacts3["NumberFacts"] = 16776450] = "NumberFacts";
  TypeFacts3[TypeFacts3["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
  TypeFacts3[TypeFacts3["ZeroNumberFacts"] = 12582146 /* BaseNumberFacts */] = "ZeroNumberFacts";
  TypeFacts3[TypeFacts3["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
  TypeFacts3[TypeFacts3["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
  TypeFacts3[TypeFacts3["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
  TypeFacts3[TypeFacts3["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
  TypeFacts3[TypeFacts3["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
  TypeFacts3[TypeFacts3["BigIntFacts"] = 16775940] = "BigIntFacts";
  TypeFacts3[TypeFacts3["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
  TypeFacts3[TypeFacts3["ZeroBigIntFacts"] = 12581636 /* BaseBigIntFacts */] = "ZeroBigIntFacts";
  TypeFacts3[TypeFacts3["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
  TypeFacts3[TypeFacts3["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
  TypeFacts3[TypeFacts3["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
  TypeFacts3[TypeFacts3["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
  TypeFacts3[TypeFacts3["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
  TypeFacts3[TypeFacts3["BooleanFacts"] = 16774920] = "BooleanFacts";
  TypeFacts3[TypeFacts3["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
  TypeFacts3[TypeFacts3["FalseFacts"] = 12580616 /* BaseBooleanFacts */] = "FalseFacts";
  TypeFacts3[TypeFacts3["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
  TypeFacts3[TypeFacts3["TrueFacts"] = 16774920] = "TrueFacts";
  TypeFacts3[TypeFacts3["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
  TypeFacts3[TypeFacts3["SymbolFacts"] = 16772880] = "SymbolFacts";
  TypeFacts3[TypeFacts3["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
  TypeFacts3[TypeFacts3["ObjectFacts"] = 16736160] = "ObjectFacts";
  TypeFacts3[TypeFacts3["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
  TypeFacts3[TypeFacts3["FunctionFacts"] = 16728e3] = "FunctionFacts";
  TypeFacts3[TypeFacts3["VoidFacts"] = 9830144] = "VoidFacts";
  TypeFacts3[TypeFacts3["UndefinedFacts"] = 26607360] = "UndefinedFacts";
  TypeFacts3[TypeFacts3["NullFacts"] = 42917664] = "NullFacts";
  TypeFacts3[TypeFacts3["EmptyObjectStrictFacts"] = 83427327] = "EmptyObjectStrictFacts";
  TypeFacts3[TypeFacts3["EmptyObjectFacts"] = 83886079] = "EmptyObjectFacts";
  TypeFacts3[TypeFacts3["UnknownFacts"] = 83886079] = "UnknownFacts";
  TypeFacts3[TypeFacts3["AllTypeofNE"] = 556800] = "AllTypeofNE";
  TypeFacts3[TypeFacts3["OrFactsMask"] = 8256] = "OrFactsMask";
  TypeFacts3[TypeFacts3["AndFactsMask"] = 134209471] = "AndFactsMask";
  return TypeFacts3;
})(TypeFacts || {});
var typeofNEFacts = new Map(Object.entries({
  string: 256 /* TypeofNEString */,
  number: 512 /* TypeofNENumber */,
  bigint: 1024 /* TypeofNEBigInt */,
  boolean: 2048 /* TypeofNEBoolean */,
  symbol: 4096 /* TypeofNESymbol */,
  undefined: 524288 /* NEUndefined */,
  object: 8192 /* TypeofNEObject */,
  function: 16384 /* TypeofNEFunction */
}));
var CheckMode = /* @__PURE__ */ ((CheckMode3) => {
  CheckMode3[CheckMode3["Normal"] = 0] = "Normal";
  CheckMode3[CheckMode3["Contextual"] = 1] = "Contextual";
  CheckMode3[CheckMode3["Inferential"] = 2] = "Inferential";
  CheckMode3[CheckMode3["SkipContextSensitive"] = 4] = "SkipContextSensitive";
  CheckMode3[CheckMode3["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
  CheckMode3[CheckMode3["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
  CheckMode3[CheckMode3["RestBindingElement"] = 32] = "RestBindingElement";
  CheckMode3[CheckMode3["TypeOnly"] = 64] = "TypeOnly";
  return CheckMode3;
})(CheckMode || {});
var SignatureCheckMode = /* @__PURE__ */ ((SignatureCheckMode3) => {
  SignatureCheckMode3[SignatureCheckMode3["None"] = 0] = "None";
  SignatureCheckMode3[SignatureCheckMode3["BivariantCallback"] = 1] = "BivariantCallback";
  SignatureCheckMode3[SignatureCheckMode3["StrictCallback"] = 2] = "StrictCallback";
  SignatureCheckMode3[SignatureCheckMode3["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
  SignatureCheckMode3[SignatureCheckMode3["StrictArity"] = 8] = "StrictArity";
  SignatureCheckMode3[SignatureCheckMode3["StrictTopSignature"] = 16] = "StrictTopSignature";
  SignatureCheckMode3[SignatureCheckMode3["Callback"] = 3] = "Callback";
  return SignatureCheckMode3;
})(SignatureCheckMode || {});
var isNotOverloadAndNotAccessor = and(isNotOverload, isNotAccessor);
var intrinsicTypeKinds = new Map(Object.entries({
  Uppercase: 0 /* Uppercase */,
  Lowercase: 1 /* Lowercase */,
  Capitalize: 2 /* Capitalize */,
  Uncapitalize: 3 /* Uncapitalize */,
  NoInfer: 4 /* NoInfer */
}));
var SymbolLinks = class {
};
function NodeLinks() {
  this.flags = 0 /* None */;
}
function getNodeId(node) {
  if (!node.id) {
    node.id = nextNodeId;
    nextNodeId++;
  }
  return node.id;
}
function getSymbolId(symbol) {
  if (!symbol.id) {
    symbol.id = nextSymbolId;
    nextSymbolId++;
  }
  return symbol.id;
}
function isInstantiatedModule(node, preserveConstEnums) {
  const moduleState = getModuleInstanceState(node);
  return moduleState === 1 /* Instantiated */ || preserveConstEnums && moduleState === 2 /* ConstEnumOnly */;
}
function createTypeChecker(host) {
  var deferredDiagnosticsCallbacks = [];
  var addLazyDiagnostic = (arg) => {
    deferredDiagnosticsCallbacks.push(arg);
  };
  var cancellationToken;
  var scanner;
  var Symbol13 = objectAllocator.getSymbolConstructor();
  var Type7 = objectAllocator.getTypeConstructor();
  var Signature5 = objectAllocator.getSignatureConstructor();
  var typeCount = 0;
  var symbolCount = 0;
  var totalInstantiationCount = 0;
  var instantiationCount = 0;
  var instantiationDepth = 0;
  var inlineLevel = 0;
  var currentNode;
  var varianceTypeParameter;
  var isInferencePartiallyBlocked = false;
  var emptySymbols = createSymbolTable();
  var arrayVariances = [1 /* Covariant */];
  var compilerOptions = host.getCompilerOptions();
  var languageVersion = getEmitScriptTarget(compilerOptions);
  var moduleKind = getEmitModuleKind(compilerOptions);
  var legacyDecorators = !!compilerOptions.experimentalDecorators;
  var useDefineForClassFields = getUseDefineForClassFields(compilerOptions);
  var emitStandardClassFields = getEmitStandardClassFields(compilerOptions);
  var allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions);
  var strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks");
  var strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes");
  var strictBindCallApply = getStrictOptionValue(compilerOptions, "strictBindCallApply");
  var strictPropertyInitialization = getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
  var strictBuiltinIteratorReturn = getStrictOptionValue(compilerOptions, "strictBuiltinIteratorReturn");
  var noImplicitAny = getStrictOptionValue(compilerOptions, "noImplicitAny");
  var noImplicitThis = getStrictOptionValue(compilerOptions, "noImplicitThis");
  var useUnknownInCatchVariables = getStrictOptionValue(compilerOptions, "useUnknownInCatchVariables");
  var exactOptionalPropertyTypes = compilerOptions.exactOptionalPropertyTypes;
  var noUncheckedSideEffectImports = !!compilerOptions.noUncheckedSideEffectImports;
  var checkBinaryExpression = createCheckBinaryExpression();
  var emitResolver = createResolver();
  var nodeBuilder = createNodeBuilder();
  var syntacticNodeBuilder = createSyntacticTypeNodeBuilder(compilerOptions, nodeBuilder.syntacticBuilderResolver);
  var evaluate = createEvaluator({
    evaluateElementAccessExpression,
    evaluateEntityNameExpression
  });
  var globals = createSymbolTable();
  var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
  undefinedSymbol.declarations = [];
  var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
  globalThisSymbol.exports = globals;
  globalThisSymbol.declarations = [];
  globals.set(globalThisSymbol.escapedName, globalThisSymbol);
  var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
  var requireSymbol = createSymbol(4 /* Property */, "require");
  var isolatedModulesLikeFlagName = compilerOptions.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules";
  var canCollectSymbolAliasAccessabilityData = !compilerOptions.verbatimModuleSyntax;
  var apparentArgumentCount;
  var lastGetCombinedNodeFlagsNode;
  var lastGetCombinedNodeFlagsResult = 0 /* None */;
  var lastGetCombinedModifierFlagsNode;
  var lastGetCombinedModifierFlagsResult = 0 /* None */;
  var resolveName = createNameResolver({
    compilerOptions,
    requireSymbol,
    argumentsSymbol,
    globals,
    getSymbolOfDeclaration,
    error,
    getRequiresScopeChangeCache,
    setRequiresScopeChangeCache,
    lookup: getSymbol,
    onPropertyWithInvalidInitializer: checkAndReportErrorForInvalidInitializer,
    onFailedToResolveSymbol,
    onSuccessfullyResolvedSymbol
  });
  var resolveNameForSymbolSuggestion = createNameResolver({
    compilerOptions,
    requireSymbol,
    argumentsSymbol,
    globals,
    getSymbolOfDeclaration,
    error,
    getRequiresScopeChangeCache,
    setRequiresScopeChangeCache,
    lookup: getSuggestionForSymbolNameLookup
  });
  const checker = {
    getNodeCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.nodeCount, 0),
    getIdentifierCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.identifierCount, 0),
    getSymbolCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.symbolCount, symbolCount),
    getTypeCount: () => typeCount,
    getInstantiationCount: () => totalInstantiationCount,
    getRelationCacheSizes: () => ({
      assignable: assignableRelation.size,
      identity: identityRelation.size,
      subtype: subtypeRelation.size,
      strictSubtype: strictSubtypeRelation.size
    }),
    isUndefinedSymbol: (symbol) => symbol === undefinedSymbol,
    isArgumentsSymbol: (symbol) => symbol === argumentsSymbol,
    isUnknownSymbol: (symbol) => symbol === unknownSymbol,
    getMergedSymbol,
    symbolIsValue,
    getDiagnostics,
    getGlobalDiagnostics,
    getRecursionIdentity,
    getUnmatchedProperties,
    getTypeOfSymbolAtLocation: (symbol, locationIn) => {
      const location = getParseTreeNode(locationIn);
      return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
    },
    getTypeOfSymbol,
    getSymbolsOfParameterPropertyDeclaration: (parameterIn, parameterName) => {
      const parameter = getParseTreeNode(parameterIn, isParameter);
      if (parameter === void 0) return Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
      Debug.assert(isParameterPropertyDeclaration(parameter, parameter.parent));
      return getSymbolsOfParameterPropertyDeclaration(parameter, escapeLeadingUnderscores(parameterName));
    },
    getDeclaredTypeOfSymbol,
    getPropertiesOfType,
    getPropertyOfType: (type, name) => getPropertyOfType(type, escapeLeadingUnderscores(name)),
    getPrivateIdentifierPropertyOfType: (leftType, name, location) => {
      const node = getParseTreeNode(location);
      if (!node) {
        return void 0;
      }
      const propName = escapeLeadingUnderscores(name);
      const lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
      return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : void 0;
    },
    getTypeOfPropertyOfType: (type, name) => getTypeOfPropertyOfType(type, escapeLeadingUnderscores(name)),
    getIndexInfoOfType: (type, kind) => getIndexInfoOfType(type, kind === 0 /* String */ ? stringType : numberType),
    getIndexInfosOfType,
    getIndexInfosOfIndexSymbol,
    getSignaturesOfType,
    getIndexTypeOfType: (type, kind) => getIndexTypeOfType(type, kind === 0 /* String */ ? stringType : numberType),
    getIndexType: (type) => getIndexType(type),
    getBaseTypes,
    getBaseTypeOfLiteralType,
    getWidenedType,
    getWidenedLiteralType,
    fillMissingTypeArguments,
    getTypeFromTypeNode: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isTypeNode);
      return node ? getTypeFromTypeNode(node) : errorType;
    },
    getParameterType: getTypeAtPosition,
    getParameterIdentifierInfoAtPosition,
    getPromisedTypeOfPromise,
    getAwaitedType: (type) => getAwaitedType(type),
    getReturnTypeOfSignature,
    isNullableType,
    getNullableType,
    getNonNullableType,
    getNonOptionalType: removeOptionalTypeMarker,
    getTypeArguments,
    typeToTypeNode: nodeBuilder.typeToTypeNode,
    typePredicateToTypePredicateNode: nodeBuilder.typePredicateToTypePredicateNode,
    indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
    signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
    symbolToEntityName: nodeBuilder.symbolToEntityName,
    symbolToExpression: nodeBuilder.symbolToExpression,
    symbolToNode: nodeBuilder.symbolToNode,
    symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
    symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
    typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
    getSymbolsInScope: (locationIn, meaning) => {
      const location = getParseTreeNode(locationIn);
      return location ? getSymbolsInScope(location, meaning) : [];
    },
    getSymbolAtLocation: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getSymbolAtLocation(
        node,
        /*ignoreErrors*/
        true
      ) : void 0;
    },
    getIndexInfosAtLocation: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getIndexInfosAtLocation(node) : void 0;
    },
    getShorthandAssignmentValueSymbol: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getShorthandAssignmentValueSymbol(node) : void 0;
    },
    getExportSpecifierLocalTargetSymbol: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isExportSpecifier);
      return node ? getExportSpecifierLocalTargetSymbol(node) : void 0;
    },
    getExportSymbolOfSymbol(symbol) {
      return getMergedSymbol(symbol.exportSymbol || symbol);
    },
    getTypeAtLocation: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getTypeOfNode(node) : errorType;
    },
    getTypeOfAssignmentPattern: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isAssignmentPattern);
      return node && getTypeOfAssignmentPattern(node) || errorType;
    },
    getPropertySymbolOfDestructuringAssignment: (locationIn) => {
      const location = getParseTreeNode(locationIn, isIdentifier);
      return location ? getPropertySymbolOfDestructuringAssignment(location) : void 0;
    },
    signatureToString: (signature, enclosingDeclaration, flags, kind) => {
      return signatureToString(signature, getParseTreeNode(enclosingDeclaration), flags, kind);
    },
    typeToString: (type, enclosingDeclaration, flags) => {
      return typeToString(type, getParseTreeNode(enclosingDeclaration), flags);
    },
    symbolToString: (symbol, enclosingDeclaration, meaning, flags) => {
      return symbolToString(symbol, getParseTreeNode(enclosingDeclaration), meaning, flags);
    },
    typePredicateToString: (predicate, enclosingDeclaration, flags) => {
      return typePredicateToString(predicate, getParseTreeNode(enclosingDeclaration), flags);
    },
    writeSignature: (signature, enclosingDeclaration, flags, kind, writer) => {
      return signatureToString(signature, getParseTreeNode(enclosingDeclaration), flags, kind, writer);
    },
    writeType: (type, enclosingDeclaration, flags, writer) => {
      return typeToString(type, getParseTreeNode(enclosingDeclaration), flags, writer);
    },
    writeSymbol: (symbol, enclosingDeclaration, meaning, flags, writer) => {
      return symbolToString(symbol, getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
    },
    writeTypePredicate: (predicate, enclosingDeclaration, flags, writer) => {
      return typePredicateToString(predicate, getParseTreeNode(enclosingDeclaration), flags, writer);
    },
    getAugmentedPropertiesOfType,
    getRootSymbols,
    getSymbolOfExpando,
    getContextualType: (nodeIn, contextFlags) => {
      const node = getParseTreeNode(nodeIn, isExpression);
      if (!node) {
        return void 0;
      }
      if (contextFlags & 4 /* Completions */) {
        return runWithInferenceBlockedFromSourceNode(node, () => getContextualType(node, contextFlags));
      }
      return getContextualType(node, contextFlags);
    },
    getContextualTypeForObjectLiteralElement: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isObjectLiteralElementLike);
      return node ? getContextualTypeForObjectLiteralElement(
        node,
        /*contextFlags*/
        void 0
      ) : void 0;
    },
    getContextualTypeForArgumentAtIndex: (nodeIn, argIndex) => {
      const node = getParseTreeNode(nodeIn, isCallLikeExpression);
      return node && getContextualTypeForArgumentAtIndex(node, argIndex);
    },
    getContextualTypeForJsxAttribute: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isJsxAttributeLike);
      return node && getContextualTypeForJsxAttribute(
        node,
        /*contextFlags*/
        void 0
      );
    },
    isContextSensitive,
    getTypeOfPropertyOfContextualType,
    getFullyQualifiedName,
    getResolvedSignature: (node, candidatesOutArray, argumentCount) => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */),
    getCandidateSignaturesForStringLiteralCompletions,
    getResolvedSignatureForSignatureHelp: (node, candidatesOutArray, argumentCount) => runWithoutResolvedSignatureCaching(node, () => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */)),
    getExpandedParameters,
    hasEffectiveRestParameter,
    containsArgumentsReference,
    getConstantValue: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, canHaveConstantValue);
      return node ? getConstantValue2(node) : void 0;
    },
    isValidPropertyAccess: (nodeIn, propertyName) => {
      const node = getParseTreeNode(nodeIn, isPropertyAccessOrQualifiedNameOrImportTypeNode);
      return !!node && isValidPropertyAccess(node, escapeLeadingUnderscores(propertyName));
    },
    isValidPropertyAccessForCompletions: (nodeIn, type, property) => {
      const node = getParseTreeNode(nodeIn, isPropertyAccessExpression);
      return !!node && isValidPropertyAccessForCompletions(node, type, property);
    },
    getSignatureFromDeclaration: (declarationIn) => {
      const declaration = getParseTreeNode(declarationIn, isFunctionLike);
      return declaration ? getSignatureFromDeclaration(declaration) : void 0;
    },
    isImplementationOfOverload: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isFunctionLike);
      return node ? isImplementationOfOverload(node) : void 0;
    },
    getImmediateAliasedSymbol,
    getAliasedSymbol: resolveAlias,
    getEmitResolver,
    requiresAddingImplicitUndefined,
    getExportsOfModule: getExportsOfModuleAsArray,
    getExportsAndPropertiesOfModule,
    forEachExportAndPropertyOfModule,
    getSymbolWalker: createGetSymbolWalker(
      getRestTypeOfSignature,
      getTypePredicateOfSignature,
      getReturnTypeOfSignature,
      getBaseTypes,
      resolveStructuredTypeMembers,
      getTypeOfSymbol,
      getResolvedSymbol,
      getConstraintOfTypeParameter,
      getFirstIdentifier,
      getTypeArguments
    ),
    getAmbientModules,
    getJsxIntrinsicTagNamesAt,
    isOptionalParameter: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isParameter);
      return node ? isOptionalParameter(node) : false;
    },
    tryGetMemberInModuleExports: (name, symbol) => tryGetMemberInModuleExports(escapeLeadingUnderscores(name), symbol),
    tryGetMemberInModuleExportsAndProperties: (name, symbol) => tryGetMemberInModuleExportsAndProperties(escapeLeadingUnderscores(name), symbol),
    tryFindAmbientModule: (moduleName) => tryFindAmbientModule(
      moduleName,
      /*withAugmentations*/
      true
    ),
    getApparentType,
    getUnionType,
    isTypeAssignableTo,
    createAnonymousType,
    createSignature,
    createSymbol,
    createIndexInfo,
    getAnyType: () => anyType,
    getStringType: () => stringType,
    getStringLiteralType,
    getNumberType: () => numberType,
    getNumberLiteralType,
    getBigIntType: () => bigintType,
    getBigIntLiteralType,
    createPromiseType,
    createArrayType,
    getElementTypeOfArrayType,
    getBooleanType: () => booleanType,
    getFalseType: (fresh) => fresh ? falseType : regularFalseType,
    getTrueType: (fresh) => fresh ? trueType : regularTrueType,
    getVoidType: () => voidType,
    getUndefinedType: () => undefinedType,
    getNullType: () => nullType,
    getESSymbolType: () => esSymbolType,
    getNeverType: () => neverType,
    getOptionalType: () => optionalType,
    getPromiseType: () => getGlobalPromiseType(
      /*reportErrors*/
      false
    ),
    getPromiseLikeType: () => getGlobalPromiseLikeType(
      /*reportErrors*/
      false
    ),
    getAnyAsyncIterableType: () => {
      const type = getGlobalAsyncIterableType(
        /*reportErrors*/
        false
      );
      if (type === emptyGenericType) return void 0;
      return createTypeReference(type, [anyType, anyType, anyType]);
    },
    isSymbolAccessible,
    isArrayType,
    isTupleType,
    isArrayLikeType,
    isEmptyAnonymousObjectType,
    isTypeInvalidDueToUnionDiscriminant,
    getExactOptionalProperties,
    getAllPossiblePropertiesOfTypes,
    getSuggestedSymbolForNonexistentProperty,
    getSuggestedSymbolForNonexistentJSXAttribute,
    getSuggestedSymbolForNonexistentSymbol: (location, name, meaning) => getSuggestedSymbolForNonexistentSymbol(location, escapeLeadingUnderscores(name), meaning),
    getSuggestedSymbolForNonexistentModule,
    getSuggestedSymbolForNonexistentClassMember,
    getBaseConstraintOfType,
    getDefaultFromTypeParameter: (type) => type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : void 0,
    resolveName(name, location, meaning, excludeGlobals) {
      return resolveName(
        location,
        escapeLeadingUnderscores(name),
        meaning,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false,
        excludeGlobals
      );
    },
    getJsxNamespace: (n) => unescapeLeadingUnderscores(getJsxNamespace(n)),
    getJsxFragmentFactory: (n) => {
      const jsxFragmentFactory = getJsxFragmentFactoryEntity(n);
      return jsxFragmentFactory && unescapeLeadingUnderscores(getFirstIdentifier(jsxFragmentFactory).escapedText);
    },
    getAccessibleSymbolChain,
    getTypePredicateOfSignature,
    resolveExternalModuleName: (moduleSpecifierIn) => {
      const moduleSpecifier = getParseTreeNode(moduleSpecifierIn, isExpression);
      return moduleSpecifier && resolveExternalModuleName(
        moduleSpecifier,
        moduleSpecifier,
        /*ignoreErrors*/
        true
      );
    },
    resolveExternalModuleSymbol,
    tryGetThisTypeAt: (nodeIn, includeGlobalThis, container) => {
      const node = getParseTreeNode(nodeIn);
      return node && tryGetThisTypeAt(node, includeGlobalThis, container);
    },
    getTypeArgumentConstraint: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isTypeNode);
      return node && getTypeArgumentConstraint(node);
    },
    getSuggestionDiagnostics: (fileIn, ct) => {
      const file = getParseTreeNode(fileIn, isSourceFile) || Debug.fail("Could not determine parsed source file.");
      if (skipTypeChecking(file, compilerOptions, host)) {
        return emptyArray;
      }
      let diagnostics2;
      try {
        cancellationToken = ct;
        checkSourceFileWithEagerDiagnostics(file);
        Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
        diagnostics2 = addRange(diagnostics2, suggestionDiagnostics.getDiagnostics(file.fileName));
        checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), (containingNode, kind, diag2) => {
          if (!containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 33554432 /* Ambient */))) {
            (diagnostics2 || (diagnostics2 = [])).push({ ...diag2, category: 2 /* Suggestion */ });
          }
        });
        return diagnostics2 || emptyArray;
      } finally {
        cancellationToken = void 0;
      }
    },
    runWithCancellationToken: (token, callback) => {
      try {
        cancellationToken = token;
        return callback(checker);
      } finally {
        cancellationToken = void 0;
      }
    },
    getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
    isDeclarationVisible,
    isPropertyAccessible,
    getTypeOnlyAliasDeclaration,
    getMemberOverrideModifierStatus,
    isTypeParameterPossiblyReferenced,
    typeHasCallOrConstructSignatures,
    getSymbolFlags
  };
  function getCandidateSignaturesForStringLiteralCompletions(call, editingArgument) {
    const candidatesSet = /* @__PURE__ */ new Set();
    const candidates = [];
    runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignatureWorker(
      call,
      candidates,
      /*argumentCount*/
      void 0,
      0 /* Normal */
    ));
    for (const candidate of candidates) {
      candidatesSet.add(candidate);
    }
    candidates.length = 0;
    runWithoutResolvedSignatureCaching(editingArgument, () => getResolvedSignatureWorker(
      call,
      candidates,
      /*argumentCount*/
      void 0,
      0 /* Normal */
    ));
    for (const candidate of candidates) {
      candidatesSet.add(candidate);
    }
    return arrayFrom(candidatesSet);
  }
  function runWithoutResolvedSignatureCaching(node, fn) {
    node = findAncestor(node, isCallLikeOrFunctionLikeExpression);
    if (node) {
      const cachedResolvedSignatures = [];
      const cachedTypes2 = [];
      while (node) {
        const nodeLinks2 = getNodeLinks(node);
        cachedResolvedSignatures.push([nodeLinks2, nodeLinks2.resolvedSignature]);
        nodeLinks2.resolvedSignature = void 0;
        if (isFunctionExpressionOrArrowFunction(node)) {
          const symbolLinks2 = getSymbolLinks(getSymbolOfDeclaration(node));
          const type = symbolLinks2.type;
          cachedTypes2.push([symbolLinks2, type]);
          symbolLinks2.type = void 0;
        }
        node = findAncestor(node.parent, isCallLikeOrFunctionLikeExpression);
      }
      const result = fn();
      for (const [nodeLinks2, resolvedSignature] of cachedResolvedSignatures) {
        nodeLinks2.resolvedSignature = resolvedSignature;
      }
      for (const [symbolLinks2, type] of cachedTypes2) {
        symbolLinks2.type = type;
      }
      return result;
    }
    return fn();
  }
  function runWithInferenceBlockedFromSourceNode(node, fn) {
    const containingCall = findAncestor(node, isCallLikeExpression);
    if (containingCall) {
      let toMarkSkip = node;
      do {
        getNodeLinks(toMarkSkip).skipDirectInference = true;
        toMarkSkip = toMarkSkip.parent;
      } while (toMarkSkip && toMarkSkip !== containingCall);
    }
    isInferencePartiallyBlocked = true;
    const result = runWithoutResolvedSignatureCaching(node, fn);
    isInferencePartiallyBlocked = false;
    if (containingCall) {
      let toMarkSkip = node;
      do {
        getNodeLinks(toMarkSkip).skipDirectInference = void 0;
        toMarkSkip = toMarkSkip.parent;
      } while (toMarkSkip && toMarkSkip !== containingCall);
    }
    return result;
  }
  function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
    const node = getParseTreeNode(nodeIn, isCallLikeExpression);
    apparentArgumentCount = argumentCount;
    const res = !node ? void 0 : getResolvedSignature(node, candidatesOutArray, checkMode);
    apparentArgumentCount = void 0;
    return res;
  }
  var tupleTypes = /* @__PURE__ */ new Map();
  var unionTypes = /* @__PURE__ */ new Map();
  var unionOfUnionTypes = /* @__PURE__ */ new Map();
  var intersectionTypes = /* @__PURE__ */ new Map();
  var stringLiteralTypes = /* @__PURE__ */ new Map();
  var numberLiteralTypes = /* @__PURE__ */ new Map();
  var bigIntLiteralTypes = /* @__PURE__ */ new Map();
  var enumLiteralTypes = /* @__PURE__ */ new Map();
  var indexedAccessTypes = /* @__PURE__ */ new Map();
  var templateLiteralTypes = /* @__PURE__ */ new Map();
  var stringMappingTypes = /* @__PURE__ */ new Map();
  var substitutionTypes = /* @__PURE__ */ new Map();
  var subtypeReductionCache = /* @__PURE__ */ new Map();
  var decoratorContextOverrideTypeCache = /* @__PURE__ */ new Map();
  var cachedTypes = /* @__PURE__ */ new Map();
  var evolvingArrayTypes = [];
  var undefinedProperties = /* @__PURE__ */ new Map();
  var markerTypes = /* @__PURE__ */ new Set();
  var unknownSymbol = createSymbol(4 /* Property */, "unknown");
  var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
  var unresolvedSymbols = /* @__PURE__ */ new Map();
  var errorTypes = /* @__PURE__ */ new Map();
  var seenIntrinsicNames = /* @__PURE__ */ new Set();
  var anyType = createIntrinsicType(1 /* Any */, "any");
  var autoType = createIntrinsicType(1 /* Any */, "any", 262144 /* NonInferrableType */, "auto");
  var wildcardType = createIntrinsicType(
    1 /* Any */,
    "any",
    /*objectFlags*/
    void 0,
    "wildcard"
  );
  var blockedStringType = createIntrinsicType(
    1 /* Any */,
    "any",
    /*objectFlags*/
    void 0,
    "blocked string"
  );
  var errorType = createIntrinsicType(1 /* Any */, "error");
  var unresolvedType = createIntrinsicType(1 /* Any */, "unresolved");
  var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 65536 /* ContainsWideningType */, "non-inferrable");
  var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic");
  var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
  var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
  var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 65536 /* ContainsWideningType */, "widening");
  var missingType = createIntrinsicType(
    32768 /* Undefined */,
    "undefined",
    /*objectFlags*/
    void 0,
    "missing"
  );
  var undefinedOrMissingType = exactOptionalPropertyTypes ? missingType : undefinedType;
  var optionalType = createIntrinsicType(
    32768 /* Undefined */,
    "undefined",
    /*objectFlags*/
    void 0,
    "optional"
  );
  var nullType = createIntrinsicType(65536 /* Null */, "null");
  var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 65536 /* ContainsWideningType */, "widening");
  var stringType = createIntrinsicType(4 /* String */, "string");
  var numberType = createIntrinsicType(8 /* Number */, "number");
  var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
  var falseType = createIntrinsicType(
    512 /* BooleanLiteral */,
    "false",
    /*objectFlags*/
    void 0,
    "fresh"
  );
  var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
  var trueType = createIntrinsicType(
    512 /* BooleanLiteral */,
    "true",
    /*objectFlags*/
    void 0,
    "fresh"
  );
  var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
  trueType.regularType = regularTrueType;
  trueType.freshType = trueType;
  regularTrueType.regularType = regularTrueType;
  regularTrueType.freshType = trueType;
  falseType.regularType = regularFalseType;
  falseType.freshType = falseType;
  regularFalseType.regularType = regularFalseType;
  regularFalseType.freshType = falseType;
  var booleanType = getUnionType([regularFalseType, regularTrueType]);
  var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
  var voidType = createIntrinsicType(16384 /* Void */, "void");
  var neverType = createIntrinsicType(131072 /* Never */, "never");
  var silentNeverType = createIntrinsicType(131072 /* Never */, "never", 262144 /* NonInferrableType */, "silent");
  var implicitNeverType = createIntrinsicType(
    131072 /* Never */,
    "never",
    /*objectFlags*/
    void 0,
    "implicit"
  );
  var unreachableNeverType = createIntrinsicType(
    131072 /* Never */,
    "never",
    /*objectFlags*/
    void 0,
    "unreachable"
  );
  var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
  var stringOrNumberType = getUnionType([stringType, numberType]);
  var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
  var numberOrBigIntType = getUnionType([numberType, bigintType]);
  var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]);
  var numericStringType = getTemplateLiteralType(["", ""], [numberType]);
  var restrictiveMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t, () => "(restrictive mapper)");
  var permissiveMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? wildcardType : t, () => "(permissive mapper)");
  var uniqueLiteralType = createIntrinsicType(
    131072 /* Never */,
    "never",
    /*objectFlags*/
    void 0,
    "unique literal"
  );
  var uniqueLiteralMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? uniqueLiteralType : t, () => "(unique literal mapper)");
  var outofbandVarianceMarkerHandler;
  var reportUnreliableMapper = makeFunctionTypeMapper((t) => {
    if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) {
      outofbandVarianceMarkerHandler(
        /*onlyUnreliable*/
        true
      );
    }
    return t;
  }, () => "(unmeasurable reporter)");
  var reportUnmeasurableMapper = makeFunctionTypeMapper((t) => {
    if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) {
      outofbandVarianceMarkerHandler(
        /*onlyUnreliable*/
        false
      );
    }
    return t;
  }, () => "(unreliable reporter)");
  var emptyObjectType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var emptyJsxObjectType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */;
  var emptyFreshJsxObjectType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  emptyFreshJsxObjectType.objectFlags |= 2048 /* JsxAttributes */ | 8192 /* FreshLiteral */ | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */;
  var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
  emptyTypeLiteralSymbol.members = createSymbolTable();
  var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, emptyArray);
  var unknownEmptyObjectType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, unknownEmptyObjectType]) : unknownType;
  var emptyGenericType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  emptyGenericType.instantiations = /* @__PURE__ */ new Map();
  var anyFunctionType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  anyFunctionType.objectFlags |= 262144 /* NonInferrableType */;
  var noConstraintType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var circularConstraintType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var resolvingDefaultType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var markerSuperType = createTypeParameter();
  var markerSubType = createTypeParameter();
  markerSubType.constraint = markerSuperType;
  var markerOtherType = createTypeParameter();
  var markerSuperTypeForCheck = createTypeParameter();
  var markerSubTypeForCheck = createTypeParameter();
  markerSubTypeForCheck.constraint = markerSuperTypeForCheck;
  var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
  var anySignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    anyType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    0 /* None */
  );
  var unknownSignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    errorType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    0 /* None */
  );
  var resolvingSignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    anyType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    0 /* None */
  );
  var silentNeverSignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    silentNeverType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    0 /* None */
  );
  var enumNumberIndexInfo = createIndexInfo(
    numberType,
    stringType,
    /*isReadonly*/
    true
  );
  var anyBaseTypeIndexInfo = createIndexInfo(
    stringType,
    anyType,
    /*isReadonly*/
    false
  );
  var iterationTypesCache = /* @__PURE__ */ new Map();
  var noIterationTypes = {
    get yieldType() {
      return Debug.fail("Not supported");
    },
    get returnType() {
      return Debug.fail("Not supported");
    },
    get nextType() {
      return Debug.fail("Not supported");
    }
  };
  var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
  var asyncIterationTypesResolver = {
    iterableCacheKey: "iterationTypesOfAsyncIterable",
    iteratorCacheKey: "iterationTypesOfAsyncIterator",
    iteratorSymbolName: "asyncIterator",
    getGlobalIteratorType: getGlobalAsyncIteratorType,
    getGlobalIterableType: getGlobalAsyncIterableType,
    getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
    getGlobalIteratorObjectType: getGlobalAsyncIteratorObjectType,
    getGlobalGeneratorType: getGlobalAsyncGeneratorType,
    getGlobalBuiltinIteratorTypes: getGlobalBuiltinAsyncIteratorTypes,
    resolveIterationType: (type, errorNode) => getAwaitedType(type, errorNode, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member),
    mustHaveANextMethodDiagnostic: Diagnostics.An_async_iterator_must_have_a_next_method,
    mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
    mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property
  };
  var syncIterationTypesResolver = {
    iterableCacheKey: "iterationTypesOfIterable",
    iteratorCacheKey: "iterationTypesOfIterator",
    iteratorSymbolName: "iterator",
    getGlobalIteratorType,
    getGlobalIterableType,
    getGlobalIterableIteratorType,
    getGlobalIteratorObjectType,
    getGlobalGeneratorType,
    getGlobalBuiltinIteratorTypes,
    resolveIterationType: (type, _errorNode) => type,
    mustHaveANextMethodDiagnostic: Diagnostics.An_iterator_must_have_a_next_method,
    mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
    mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property
  };
  var amalgamatedDuplicates;
  var reverseMappedCache = /* @__PURE__ */ new Map();
  var reverseHomomorphicMappedCache = /* @__PURE__ */ new Map();
  var ambientModulesCache;
  var patternAmbientModules;
  var patternAmbientModuleAugmentations;
  var globalObjectType;
  var globalFunctionType;
  var globalCallableFunctionType;
  var globalNewableFunctionType;
  var globalArrayType;
  var globalReadonlyArrayType;
  var globalStringType;
  var globalNumberType;
  var globalBooleanType;
  var globalRegExpType;
  var globalThisType;
  var anyArrayType;
  var autoArrayType;
  var anyReadonlyArrayType;
  var deferredGlobalNonNullableTypeAlias;
  var deferredGlobalESSymbolConstructorSymbol;
  var deferredGlobalESSymbolConstructorTypeSymbol;
  var deferredGlobalESSymbolType;
  var deferredGlobalTypedPropertyDescriptorType;
  var deferredGlobalPromiseType;
  var deferredGlobalPromiseLikeType;
  var deferredGlobalPromiseConstructorSymbol;
  var deferredGlobalPromiseConstructorLikeType;
  var deferredGlobalIterableType;
  var deferredGlobalIteratorType;
  var deferredGlobalIterableIteratorType;
  var deferredGlobalIteratorObjectType;
  var deferredGlobalGeneratorType;
  var deferredGlobalIteratorYieldResultType;
  var deferredGlobalIteratorReturnResultType;
  var deferredGlobalAsyncIterableType;
  var deferredGlobalAsyncIteratorType;
  var deferredGlobalAsyncIterableIteratorType;
  var deferredGlobalBuiltinIteratorTypes;
  var deferredGlobalBuiltinAsyncIteratorTypes;
  var deferredGlobalAsyncIteratorObjectType;
  var deferredGlobalAsyncGeneratorType;
  var deferredGlobalTemplateStringsArrayType;
  var deferredGlobalImportMetaType;
  var deferredGlobalImportMetaExpressionType;
  var deferredGlobalImportCallOptionsType;
  var deferredGlobalImportAttributesType;
  var deferredGlobalDisposableType;
  var deferredGlobalAsyncDisposableType;
  var deferredGlobalExtractSymbol;
  var deferredGlobalOmitSymbol;
  var deferredGlobalAwaitedSymbol;
  var deferredGlobalBigIntType;
  var deferredGlobalNaNSymbol;
  var deferredGlobalRecordSymbol;
  var deferredGlobalClassDecoratorContextType;
  var deferredGlobalClassMethodDecoratorContextType;
  var deferredGlobalClassGetterDecoratorContextType;
  var deferredGlobalClassSetterDecoratorContextType;
  var deferredGlobalClassAccessorDecoratorContextType;
  var deferredGlobalClassAccessorDecoratorTargetType;
  var deferredGlobalClassAccessorDecoratorResultType;
  var deferredGlobalClassFieldDecoratorContextType;
  var allPotentiallyUnusedIdentifiers = /* @__PURE__ */ new Map();
  var flowLoopStart = 0;
  var flowLoopCount = 0;
  var sharedFlowCount = 0;
  var flowAnalysisDisabled = false;
  var flowInvocationCount = 0;
  var lastFlowNode;
  var lastFlowNodeReachable;
  var flowTypeCache;
  var contextualTypeNodes = [];
  var contextualTypes = [];
  var contextualIsCache = [];
  var contextualTypeCount = 0;
  var contextualBindingPatterns = [];
  var inferenceContextNodes = [];
  var inferenceContexts = [];
  var inferenceContextCount = 0;
  var emptyStringType = getStringLiteralType("");
  var zeroType = getNumberLiteralType(0);
  var zeroBigIntType = getBigIntLiteralType({ negative: false, base10Value: "0" });
  var resolutionTargets = [];
  var resolutionResults = [];
  var resolutionPropertyNames = [];
  var resolutionStart = 0;
  var inVarianceComputation = false;
  var suggestionCount = 0;
  var maximumSuggestionCount = 10;
  var mergedSymbols = [];
  var symbolLinks = [];
  var nodeLinks = [];
  var flowLoopCaches = [];
  var flowLoopNodes = [];
  var flowLoopKeys = [];
  var flowLoopTypes = [];
  var sharedFlowNodes = [];
  var sharedFlowTypes = [];
  var flowNodeReachable = [];
  var flowNodePostSuper = [];
  var potentialThisCollisions = [];
  var potentialNewTargetCollisions = [];
  var potentialWeakMapSetCollisions = [];
  var potentialReflectCollisions = [];
  var potentialUnusedRenamedBindingElementsInTypes = [];
  var awaitedTypeStack = [];
  var reverseMappedSourceStack = [];
  var reverseMappedTargetStack = [];
  var reverseExpandingFlags = 0 /* None */;
  var diagnostics = createDiagnosticCollection();
  var suggestionDiagnostics = createDiagnosticCollection();
  var typeofType = createTypeofType();
  var _jsxNamespace;
  var _jsxFactoryEntity;
  var subtypeRelation = /* @__PURE__ */ new Map();
  var strictSubtypeRelation = /* @__PURE__ */ new Map();
  var assignableRelation = /* @__PURE__ */ new Map();
  var comparableRelation = /* @__PURE__ */ new Map();
  var identityRelation = /* @__PURE__ */ new Map();
  var enumRelation = /* @__PURE__ */ new Map();
  var suggestedExtensions = [
    [".mts", ".mjs"],
    [".ts", ".js"],
    [".cts", ".cjs"],
    [".mjs", ".mjs"],
    [".js", ".js"],
    [".cjs", ".cjs"],
    [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"],
    [".jsx", ".jsx"],
    [".json", ".json"]
  ];
  initializeTypeChecker();
  return checker;
  function isDefinitelyReferenceToGlobalSymbolObject(node) {
    if (!isPropertyAccessExpression(node)) return false;
    if (!isIdentifier(node.name)) return false;
    if (!isPropertyAccessExpression(node.expression) && !isIdentifier(node.expression)) return false;
    if (isIdentifier(node.expression)) {
      return idText(node.expression) === "Symbol" && getResolvedSymbol(node.expression) === (getGlobalSymbol(
        "Symbol",
        111551 /* Value */ | 1048576 /* ExportValue */,
        /*diagnostic*/
        void 0
      ) || unknownSymbol);
    }
    if (!isIdentifier(node.expression.expression)) return false;
    return idText(node.expression.name) === "Symbol" && idText(node.expression.expression) === "globalThis" && getResolvedSymbol(node.expression.expression) === globalThisSymbol;
  }
  function getCachedType(key) {
    return key ? cachedTypes.get(key) : void 0;
  }
  function setCachedType(key, type) {
    if (key) cachedTypes.set(key, type);
    return type;
  }
  function getJsxNamespace(location) {
    if (location) {
      const file = getSourceFileOfNode(location);
      if (file) {
        if (isJsxOpeningFragment(location)) {
          if (file.localJsxFragmentNamespace) {
            return file.localJsxFragmentNamespace;
          }
          const jsxFragmentPragma = file.pragmas.get("jsxfrag");
          if (jsxFragmentPragma) {
            const chosenPragma = isArray(jsxFragmentPragma) ? jsxFragmentPragma[0] : jsxFragmentPragma;
            file.localJsxFragmentFactory = parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
            visitNode(file.localJsxFragmentFactory, markAsSynthetic, isEntityName);
            if (file.localJsxFragmentFactory) {
              return file.localJsxFragmentNamespace = getFirstIdentifier(file.localJsxFragmentFactory).escapedText;
            }
          }
          const entity = getJsxFragmentFactoryEntity(location);
          if (entity) {
            file.localJsxFragmentFactory = entity;
            return file.localJsxFragmentNamespace = getFirstIdentifier(entity).escapedText;
          }
        } else {
          const localJsxNamespace = getLocalJsxNamespace(file);
          if (localJsxNamespace) {
            return file.localJsxNamespace = localJsxNamespace;
          }
        }
      }
    }
    if (!_jsxNamespace) {
      _jsxNamespace = "React";
      if (compilerOptions.jsxFactory) {
        _jsxFactoryEntity = parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
        visitNode(_jsxFactoryEntity, markAsSynthetic);
        if (_jsxFactoryEntity) {
          _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText;
        }
      } else if (compilerOptions.reactNamespace) {
        _jsxNamespace = escapeLeadingUnderscores(compilerOptions.reactNamespace);
      }
    }
    if (!_jsxFactoryEntity) {
      _jsxFactoryEntity = factory.createQualifiedName(factory.createIdentifier(unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
    }
    return _jsxNamespace;
  }
  function getLocalJsxNamespace(file) {
    if (file.localJsxNamespace) {
      return file.localJsxNamespace;
    }
    const jsxPragma = file.pragmas.get("jsx");
    if (jsxPragma) {
      const chosenPragma = isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
      file.localJsxFactory = parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
      visitNode(file.localJsxFactory, markAsSynthetic, isEntityName);
      if (file.localJsxFactory) {
        return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
      }
    }
  }
  function markAsSynthetic(node) {
    setTextRangePosEnd(node, -1, -1);
    return visitEachChild(
      node,
      markAsSynthetic,
      /*context*/
      void 0
    );
  }
  function getEmitResolver(sourceFile, cancellationToken2, skipDiagnostics) {
    if (!skipDiagnostics) getDiagnostics(sourceFile, cancellationToken2);
    return emitResolver;
  }
  function lookupOrIssueError(location, message, ...args) {
    const diagnostic = location ? createDiagnosticForNode(location, message, ...args) : createCompilerDiagnostic(message, ...args);
    const existing = diagnostics.lookup(diagnostic);
    if (existing) {
      return existing;
    } else {
      diagnostics.add(diagnostic);
      return diagnostic;
    }
  }
  function errorSkippedOn(key, location, message, ...args) {
    const diagnostic = error(location, message, ...args);
    diagnostic.skippedOn = key;
    return diagnostic;
  }
  function createError(location, message, ...args) {
    return location ? createDiagnosticForNode(location, message, ...args) : createCompilerDiagnostic(message, ...args);
  }
  function error(location, message, ...args) {
    const diagnostic = createError(location, message, ...args);
    diagnostics.add(diagnostic);
    return diagnostic;
  }
  function addErrorOrSuggestion(isError, diagnostic) {
    if (isError) {
      diagnostics.add(diagnostic);
    } else {
      suggestionDiagnostics.add({ ...diagnostic, category: 2 /* Suggestion */ });
    }
  }
  function errorOrSuggestion(isError, location, message, ...args) {
    if (location.pos < 0 || location.end < 0) {
      if (!isError) {
        return;
      }
      const file = getSourceFileOfNode(location);
      addErrorOrSuggestion(isError, "message" in message ? createFileDiagnostic(file, 0, 0, message, ...args) : createDiagnosticForFileFromMessageChain(file, message));
      return;
    }
    addErrorOrSuggestion(isError, "message" in message ? createDiagnosticForNode(location, message, ...args) : createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(location), location, message));
  }
  function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, ...args) {
    const diagnostic = error(location, message, ...args);
    if (maybeMissingAwait) {
      const related = createDiagnosticForNode(location, Diagnostics.Did_you_forget_to_use_await);
      addRelatedInfo(diagnostic, related);
    }
    return diagnostic;
  }
  function addDeprecatedSuggestionWorker(declarations, diagnostic) {
    const deprecatedTag = Array.isArray(declarations) ? forEach(declarations, getJSDocDeprecatedTag) : getJSDocDeprecatedTag(declarations);
    if (deprecatedTag) {
      addRelatedInfo(
        diagnostic,
        createDiagnosticForNode(deprecatedTag, Diagnostics.The_declaration_was_marked_as_deprecated_here)
      );
    }
    suggestionDiagnostics.add(diagnostic);
    return diagnostic;
  }
  function isDeprecatedSymbol(symbol) {
    const parentSymbol = getParentOfSymbol(symbol);
    if (parentSymbol && length(symbol.declarations) > 1) {
      return parentSymbol.flags & 64 /* Interface */ ? some(symbol.declarations, isDeprecatedDeclaration) : every(symbol.declarations, isDeprecatedDeclaration);
    }
    return !!symbol.valueDeclaration && isDeprecatedDeclaration(symbol.valueDeclaration) || length(symbol.declarations) && every(symbol.declarations, isDeprecatedDeclaration);
  }
  function isDeprecatedDeclaration(declaration) {
    return !!(getCombinedNodeFlagsCached(declaration) & 536870912 /* Deprecated */);
  }
  function addDeprecatedSuggestion(location, declarations, deprecatedEntity) {
    const diagnostic = createDiagnosticForNode(location, Diagnostics._0_is_deprecated, deprecatedEntity);
    return addDeprecatedSuggestionWorker(declarations, diagnostic);
  }
  function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) {
    const diagnostic = deprecatedEntity ? createDiagnosticForNode(location, Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) : createDiagnosticForNode(location, Diagnostics._0_is_deprecated, signatureString);
    return addDeprecatedSuggestionWorker(declaration, diagnostic);
  }
  function createSymbol(flags, name, checkFlags) {
    symbolCount++;
    const symbol = new Symbol13(flags | 33554432 /* Transient */, name);
    symbol.links = new SymbolLinks();
    symbol.links.checkFlags = checkFlags || 0 /* None */;
    return symbol;
  }
  function createParameter(name, type) {
    const symbol = createSymbol(1 /* FunctionScopedVariable */, name);
    symbol.links.type = type;
    return symbol;
  }
  function createProperty(name, type) {
    const symbol = createSymbol(4 /* Property */, name);
    symbol.links.type = type;
    return symbol;
  }
  function getExcludedSymbolFlags(flags) {
    let result = 0;
    if (flags & 2 /* BlockScopedVariable */) result |= 111551 /* BlockScopedVariableExcludes */;
    if (flags & 1 /* FunctionScopedVariable */) result |= 111550 /* FunctionScopedVariableExcludes */;
    if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */;
    if (flags & 8 /* EnumMember */) result |= 900095 /* EnumMemberExcludes */;
    if (flags & 16 /* Function */) result |= 110991 /* FunctionExcludes */;
    if (flags & 32 /* Class */) result |= 899503 /* ClassExcludes */;
    if (flags & 64 /* Interface */) result |= 788872 /* InterfaceExcludes */;
    if (flags & 256 /* RegularEnum */) result |= 899327 /* RegularEnumExcludes */;
    if (flags & 128 /* ConstEnum */) result |= 899967 /* ConstEnumExcludes */;
    if (flags & 512 /* ValueModule */) result |= 110735 /* ValueModuleExcludes */;
    if (flags & 8192 /* Method */) result |= 103359 /* MethodExcludes */;
    if (flags & 32768 /* GetAccessor */) result |= 46015 /* GetAccessorExcludes */;
    if (flags & 65536 /* SetAccessor */) result |= 78783 /* SetAccessorExcludes */;
    if (flags & 262144 /* TypeParameter */) result |= 526824 /* TypeParameterExcludes */;
    if (flags & 524288 /* TypeAlias */) result |= 788968 /* TypeAliasExcludes */;
    if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */;
    return result;
  }
  function recordMergedSymbol(target, source) {
    if (!source.mergeId) {
      source.mergeId = nextMergeId;
      nextMergeId++;
    }
    mergedSymbols[source.mergeId] = target;
  }
  function cloneSymbol(symbol) {
    const result = createSymbol(symbol.flags, symbol.escapedName);
    result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
    result.parent = symbol.parent;
    if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration;
    if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true;
    if (symbol.members) result.members = new Map(symbol.members);
    if (symbol.exports) result.exports = new Map(symbol.exports);
    recordMergedSymbol(result, symbol);
    return result;
  }
  function mergeSymbol(target, source, unidirectional = false) {
    if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864 /* Assignment */) {
      if (source === target) {
        return target;
      }
      if (!(target.flags & 33554432 /* Transient */)) {
        const resolvedTarget = resolveSymbol(target);
        if (resolvedTarget === unknownSymbol) {
          return source;
        }
        if (!(resolvedTarget.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | resolvedTarget.flags) & 67108864 /* Assignment */) {
          target = cloneSymbol(resolvedTarget);
        } else {
          reportMergeSymbolError(target, source);
          return source;
        }
      }
      if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
        target.constEnumOnlyModule = false;
      }
      target.flags |= source.flags;
      if (source.valueDeclaration) {
        setValueDeclaration(target, source.valueDeclaration);
      }
      addRange(target.declarations, source.declarations);
      if (source.members) {
        if (!target.members) target.members = createSymbolTable();
        mergeSymbolTable(target.members, source.members, unidirectional);
      }
      if (source.exports) {
        if (!target.exports) target.exports = createSymbolTable();
        mergeSymbolTable(target.exports, source.exports, unidirectional, target);
      }
      if (!unidirectional) {
        recordMergedSymbol(target, source);
      }
    } else if (target.flags & 1024 /* NamespaceModule */) {
      if (target !== globalThisSymbol) {
        error(
          source.declarations && getNameOfDeclaration(source.declarations[0]),
          Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity,
          symbolToString(target)
        );
      }
    } else {
      reportMergeSymbolError(target, source);
    }
    return target;
    function reportMergeSymbolError(target2, source2) {
      const isEitherEnum = !!(target2.flags & 384 /* Enum */ || source2.flags & 384 /* Enum */);
      const isEitherBlockScoped = !!(target2.flags & 2 /* BlockScopedVariable */ || source2.flags & 2 /* BlockScopedVariable */);
      const message = isEitherEnum ? Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations : isEitherBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0;
      const sourceSymbolFile = source2.declarations && getSourceFileOfNode(source2.declarations[0]);
      const targetSymbolFile = target2.declarations && getSourceFileOfNode(target2.declarations[0]);
      const isSourcePlainJs = isPlainJsFile(sourceSymbolFile, compilerOptions.checkJs);
      const isTargetPlainJs = isPlainJsFile(targetSymbolFile, compilerOptions.checkJs);
      const symbolName2 = symbolToString(source2);
      if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
        const firstFile = comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
        const secondFile = firstFile === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
        const filesDuplicates = getOrUpdate(amalgamatedDuplicates, `${firstFile.path}|${secondFile.path}`, () => ({ firstFile, secondFile, conflictingSymbols: /* @__PURE__ */ new Map() }));
        const conflictingSymbolInfo = getOrUpdate(filesDuplicates.conflictingSymbols, symbolName2, () => ({ isBlockScoped: isEitherBlockScoped, firstFileLocations: [], secondFileLocations: [] }));
        if (!isSourcePlainJs) addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source2);
        if (!isTargetPlainJs) addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target2);
      } else {
        if (!isSourcePlainJs) addDuplicateDeclarationErrorsForSymbols(source2, message, symbolName2, target2);
        if (!isTargetPlainJs) addDuplicateDeclarationErrorsForSymbols(target2, message, symbolName2, source2);
      }
    }
    function addDuplicateLocations(locs, symbol) {
      if (symbol.declarations) {
        for (const decl of symbol.declarations) {
          pushIfUnique(locs, decl);
        }
      }
    }
  }
  function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName2, source) {
    forEach(target.declarations, (node) => {
      addDuplicateDeclarationError(node, message, symbolName2, source.declarations);
    });
  }
  function addDuplicateDeclarationError(node, message, symbolName2, relatedNodes) {
    const errorNode = (getExpandoInitializer(
      node,
      /*isPrototypeAssignment*/
      false
    ) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node;
    const err = lookupOrIssueError(errorNode, message, symbolName2);
    for (const relatedNode of relatedNodes || emptyArray) {
      const adjustedNode = (getExpandoInitializer(
        relatedNode,
        /*isPrototypeAssignment*/
        false
      ) ? getNameOfExpando(relatedNode) : getNameOfDeclaration(relatedNode)) || relatedNode;
      if (adjustedNode === errorNode) continue;
      err.relatedInformation = err.relatedInformation || [];
      const leadingMessage = createDiagnosticForNode(adjustedNode, Diagnostics._0_was_also_declared_here, symbolName2);
      const followOnMessage = createDiagnosticForNode(adjustedNode, Diagnostics.and_here);
      if (length(err.relatedInformation) >= 5 || some(err.relatedInformation, (r) => compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */)) continue;
      addRelatedInfo(err, !length(err.relatedInformation) ? leadingMessage : followOnMessage);
    }
  }
  function combineSymbolTables(first2, second) {
    if (!(first2 == null ? void 0 : first2.size)) return second;
    if (!(second == null ? void 0 : second.size)) return first2;
    const combined = createSymbolTable();
    mergeSymbolTable(combined, first2);
    mergeSymbolTable(combined, second);
    return combined;
  }
  function mergeSymbolTable(target, source, unidirectional = false, mergedParent) {
    source.forEach((sourceSymbol, id) => {
      const targetSymbol = target.get(id);
      const merged = targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : getMergedSymbol(sourceSymbol);
      if (mergedParent && targetSymbol) {
        merged.parent = mergedParent;
      }
      target.set(id, merged);
    });
  }
  function mergeModuleAugmentation(moduleName) {
    var _a, _b, _c;
    const moduleAugmentation = moduleName.parent;
    if (((_a = moduleAugmentation.symbol.declarations) == null ? void 0 : _a[0]) !== moduleAugmentation) {
      Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
      return;
    }
    if (isGlobalScopeAugmentation(moduleAugmentation)) {
      mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
    } else {
      const moduleNotFoundError = !(moduleName.parent.parent.flags & 33554432 /* Ambient */) ? Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : void 0;
      let mainModule = resolveExternalModuleNameWorker(
        moduleName,
        moduleName,
        moduleNotFoundError,
        /*ignoreErrors*/
        false,
        /*isForAugmentation*/
        true
      );
      if (!mainModule) {
        return;
      }
      mainModule = resolveExternalModuleSymbol(mainModule);
      if (mainModule.flags & 1920 /* Namespace */) {
        if (some(patternAmbientModules, (module2) => mainModule === module2.symbol)) {
          const merged = mergeSymbol(
            moduleAugmentation.symbol,
            mainModule,
            /*unidirectional*/
            true
          );
          if (!patternAmbientModuleAugmentations) {
            patternAmbientModuleAugmentations = /* @__PURE__ */ new Map();
          }
          patternAmbientModuleAugmentations.set(moduleName.text, merged);
        } else {
          if (((_b = mainModule.exports) == null ? void 0 : _b.get("__export" /* ExportStar */)) && ((_c = moduleAugmentation.symbol.exports) == null ? void 0 : _c.size)) {
            const resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule, "resolvedExports" /* resolvedExports */);
            for (const [key, value] of arrayFrom(moduleAugmentation.symbol.exports.entries())) {
              if (resolvedExports.has(key) && !mainModule.exports.has(key)) {
                mergeSymbol(resolvedExports.get(key), value);
              }
            }
          }
          mergeSymbol(mainModule, moduleAugmentation.symbol);
        }
      } else {
        error(moduleName, Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
      }
    }
  }
  function addUndefinedToGlobalsOrErrorOnRedeclaration() {
    const name = undefinedSymbol.escapedName;
    const targetSymbol = globals.get(name);
    if (targetSymbol) {
      forEach(targetSymbol.declarations, (declaration) => {
        if (!isTypeDeclaration(declaration)) {
          diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, unescapeLeadingUnderscores(name)));
        }
      });
    } else {
      globals.set(name, undefinedSymbol);
    }
  }
  function getSymbolLinks(symbol) {
    if (symbol.flags & 33554432 /* Transient */) return symbol.links;
    const id = getSymbolId(symbol);
    return symbolLinks[id] ?? (symbolLinks[id] = new SymbolLinks());
  }
  function getNodeLinks(node) {
    const nodeId = getNodeId(node);
    return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
  }
  function getSymbol(symbols, name, meaning) {
    if (meaning) {
      const symbol = getMergedSymbol(symbols.get(name));
      if (symbol) {
        if (symbol.flags & meaning) {
          return symbol;
        }
        if (symbol.flags & 2097152 /* Alias */) {
          const targetFlags = getSymbolFlags(symbol);
          if (targetFlags & meaning) {
            return symbol;
          }
        }
      }
    }
  }
  function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
    const constructorDeclaration = parameter.parent;
    const classDeclaration = parameter.parent.parent;
    const parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
    const propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
    if (parameterSymbol && propertySymbol) {
      return [parameterSymbol, propertySymbol];
    }
    return Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
  }
  function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
    const declarationFile = getSourceFileOfNode(declaration);
    const useFile = getSourceFileOfNode(usage);
    const declContainer = getEnclosingBlockScopeContainer(declaration);
    if (declarationFile !== useFile) {
      if (moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator) || !compilerOptions.outFile || isInTypeQuery(usage) || declaration.flags & 33554432 /* Ambient */) {
        return true;
      }
      if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
        return true;
      }
      const sourceFiles = host.getSourceFiles();
      return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
    }
    if (!!(usage.flags & 16777216 /* JSDoc */) || isInTypeQuery(usage) || isInAmbientOrTypeNode(usage)) {
      return true;
    }
    if (declaration.pos <= usage.pos && !(isPropertyDeclaration(declaration) && isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) {
      if (declaration.kind === 208 /* BindingElement */) {
        const errorBindingElement = getAncestor(usage, 208 /* BindingElement */);
        if (errorBindingElement) {
          return findAncestor(errorBindingElement, isBindingElement) !== findAncestor(declaration, isBindingElement) || declaration.pos < errorBindingElement.pos;
        }
        return isBlockScopedNameDeclaredBeforeUse(getAncestor(declaration, 260 /* VariableDeclaration */), usage);
      } else if (declaration.kind === 260 /* VariableDeclaration */) {
        return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
      } else if (isClassLike(declaration)) {
        const container = findAncestor(usage, (n) => n === declaration ? "quit" : isComputedPropertyName(n) ? n.parent.parent === declaration : !legacyDecorators && isDecorator(n) && (n.parent === declaration || isMethodDeclaration(n.parent) && n.parent.parent === declaration || isGetOrSetAccessorDeclaration(n.parent) && n.parent.parent === declaration || isPropertyDeclaration(n.parent) && n.parent.parent === declaration || isParameter(n.parent) && n.parent.parent.parent === declaration));
        if (!container) {
          return true;
        }
        if (!legacyDecorators && isDecorator(container)) {
          return !!findAncestor(usage, (n) => n === container ? "quit" : isFunctionLike(n) && !getImmediatelyInvokedFunctionExpression(n));
        }
        return false;
      } else if (isPropertyDeclaration(declaration)) {
        return !isPropertyImmediatelyReferencedWithinDeclaration(
          declaration,
          usage,
          /*stopAtAnyPropertyDeclaration*/
          false
        );
      } else if (isParameterPropertyDeclaration(declaration, declaration.parent)) {
        return !(emitStandardClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration));
      }
      return true;
    }
    if (usage.parent.kind === 281 /* ExportSpecifier */ || usage.parent.kind === 277 /* ExportAssignment */ && usage.parent.isExportEquals) {
      return true;
    }
    if (usage.kind === 277 /* ExportAssignment */ && usage.isExportEquals) {
      return true;
    }
    if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
      if (emitStandardClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) {
        return !isPropertyImmediatelyReferencedWithinDeclaration(
          declaration,
          usage,
          /*stopAtAnyPropertyDeclaration*/
          true
        );
      } else {
        return true;
      }
    }
    return false;
    function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration2, usage2) {
      switch (declaration2.parent.parent.kind) {
        case 243 /* VariableStatement */:
        case 248 /* ForStatement */:
        case 250 /* ForOfStatement */:
          if (isSameScopeDescendentOf(usage2, declaration2, declContainer)) {
            return true;
          }
          break;
      }
      const grandparent = declaration2.parent.parent;
      return isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage2, grandparent.expression, declContainer);
    }
    function isUsedInFunctionOrInstanceProperty(usage2, declaration2) {
      return !!findAncestor(usage2, (current) => {
        if (current === declContainer) {
          return "quit";
        }
        if (isFunctionLike(current)) {
          return true;
        }
        if (isClassStaticBlockDeclaration(current)) {
          return declaration2.pos < usage2.pos;
        }
        const propertyDeclaration = tryCast(current.parent, isPropertyDeclaration);
        if (propertyDeclaration) {
          const initializerOfProperty = propertyDeclaration.initializer === current;
          if (initializerOfProperty) {
            if (isStatic(current.parent)) {
              if (declaration2.kind === 174 /* MethodDeclaration */) {
                return true;
              }
              if (isPropertyDeclaration(declaration2) && getContainingClass(usage2) === getContainingClass(declaration2)) {
                const propName = declaration2.name;
                if (isIdentifier(propName) || isPrivateIdentifier(propName)) {
                  const type = getTypeOfSymbol(getSymbolOfDeclaration(declaration2));
                  const staticBlocks = filter(declaration2.parent.members, isClassStaticBlockDeclaration);
                  if (isPropertyInitializedInStaticBlocks(propName, type, staticBlocks, declaration2.parent.pos, current.pos)) {
                    return true;
                  }
                }
              }
            } else {
              const isDeclarationInstanceProperty = declaration2.kind === 172 /* PropertyDeclaration */ && !isStatic(declaration2);
              if (!isDeclarationInstanceProperty || getContainingClass(usage2) !== getContainingClass(declaration2)) {
                return true;
              }
            }
          }
        }
        return false;
      });
    }
    function isPropertyImmediatelyReferencedWithinDeclaration(declaration2, usage2, stopAtAnyPropertyDeclaration) {
      if (usage2.end > declaration2.end) {
        return false;
      }
      const ancestorChangingReferenceScope = findAncestor(usage2, (node) => {
        if (node === declaration2) {
          return "quit";
        }
        switch (node.kind) {
          case 219 /* ArrowFunction */:
            return true;
          case 172 /* PropertyDeclaration */:
            return stopAtAnyPropertyDeclaration && (isPropertyDeclaration(declaration2) && node.parent === declaration2.parent || isParameterPropertyDeclaration(declaration2, declaration2.parent) && node.parent === declaration2.parent.parent) ? "quit" : true;
          case 241 /* Block */:
            switch (node.parent.kind) {
              case 177 /* GetAccessor */:
              case 174 /* MethodDeclaration */:
              case 178 /* SetAccessor */:
                return true;
              default:
                return false;
            }
          default:
            return false;
        }
      });
      return ancestorChangingReferenceScope === void 0;
    }
  }
  function getRequiresScopeChangeCache(node) {
    return getNodeLinks(node).declarationRequiresScopeChange;
  }
  function setRequiresScopeChangeCache(node, value) {
    getNodeLinks(node).declarationRequiresScopeChange = value;
  }
  function checkAndReportErrorForInvalidInitializer(errorLocation, name, propertyWithInvalidInitializer, result) {
    if (!emitStandardClassFields) {
      if (errorLocation && !result && checkAndReportErrorForMissingPrefix(errorLocation, name, name)) {
        return true;
      }
      error(
        errorLocation,
        errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor,
        declarationNameToString(propertyWithInvalidInitializer.name),
        diagnosticName(name)
      );
      return true;
    }
    return false;
  }
  function onFailedToResolveSymbol(errorLocation, nameArg, meaning, nameNotFoundMessage) {
    const name = isString(nameArg) ? nameArg : nameArg.escapedText;
    addLazyDiagnostic(() => {
      if (!errorLocation || errorLocation.parent.kind !== 324 /* JSDocLink */ && !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
        let suggestion;
        let suggestedLib;
        if (nameArg) {
          suggestedLib = getSuggestedLibForNonExistentName(nameArg);
          if (suggestedLib) {
            error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib);
          }
        }
        if (!suggestedLib && suggestionCount < maximumSuggestionCount) {
          suggestion = getSuggestedSymbolForNonexistentSymbol(errorLocation, name, meaning);
          const isGlobalScopeAugmentationDeclaration = (suggestion == null ? void 0 : suggestion.valueDeclaration) && isAmbientModule(suggestion.valueDeclaration) && isGlobalScopeAugmentation(suggestion.valueDeclaration);
          if (isGlobalScopeAugmentationDeclaration) {
            suggestion = void 0;
          }
          if (suggestion) {
            const suggestionName = symbolToString(suggestion);
            const isUncheckedJS = isUncheckedJSSuggestion(
              errorLocation,
              suggestion,
              /*excludeClasses*/
              false
            );
            const message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && nodeIsSynthesized(nameArg) ? Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 : isUncheckedJS ? Diagnostics.Could_not_find_name_0_Did_you_mean_1 : Diagnostics.Cannot_find_name_0_Did_you_mean_1;
            const diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName);
            diagnostic.canonicalHead = getCanonicalDiagnostic(nameNotFoundMessage, diagnosticName(nameArg));
            addErrorOrSuggestion(!isUncheckedJS, diagnostic);
            if (suggestion.valueDeclaration) {
              addRelatedInfo(
                diagnostic,
                createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName)
              );
            }
          }
        }
        if (!suggestion && !suggestedLib && nameArg) {
          error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
        }
        suggestionCount++;
      }
    });
  }
  function onSuccessfullyResolvedSymbol(errorLocation, result, meaning, lastLocation, associatedDeclarationForContainingInitializerOrBindingName, withinDeferredContext) {
    addLazyDiagnostic(() => {
      var _a;
      const name = result.escapedName;
      const isInExternalModule = lastLocation && isSourceFile(lastLocation) && isExternalOrCommonJsModule(lastLocation);
      if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || (meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */)) {
        const exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
        if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
          checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
        }
      }
      if (isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(errorLocation.flags & 16777216 /* JSDoc */)) {
        const merged = getMergedSymbol(result);
        if (length(merged.declarations) && every(merged.declarations, (d) => isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) {
          errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name));
        }
      }
      if (associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
        const candidate = getMergedSymbol(getLateBoundSymbol(result));
        const root = getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
        if (candidate === getSymbolOfDeclaration(associatedDeclarationForContainingInitializerOrBindingName)) {
          error(errorLocation, Diagnostics.Parameter_0_cannot_reference_itself, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
        } else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && getSymbol(root.parent.locals, candidate.escapedName, meaning) === candidate) {
          error(errorLocation, Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), declarationNameToString(errorLocation));
        }
      }
      if (errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */ && !(result.flags & 111551 /* Value */) && !isValidTypeOnlyAliasUseSite(errorLocation)) {
        const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, 111551 /* Value */);
        if (typeOnlyDeclaration) {
          const message = typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 280 /* NamespaceExport */ ? Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type : Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
          const unescapedName = unescapeLeadingUnderscores(name);
          addTypeOnlyDeclarationRelatedInfo(
            error(errorLocation, message, unescapedName),
            typeOnlyDeclaration,
            unescapedName
          );
        }
      }
      if (compilerOptions.isolatedModules && result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */) {
        const isGlobal = getSymbol(globals, name, meaning) === result;
        const nonValueSymbol = isGlobal && isSourceFile(lastLocation) && lastLocation.locals && getSymbol(lastLocation.locals, name, ~111551 /* Value */);
        if (nonValueSymbol) {
          const importDecl = (_a = nonValueSymbol.declarations) == null ? void 0 : _a.find((d) => d.kind === 276 /* ImportSpecifier */ || d.kind === 273 /* ImportClause */ || d.kind === 274 /* NamespaceImport */ || d.kind === 271 /* ImportEqualsDeclaration */);
          if (importDecl && !isTypeOnlyImportDeclaration(importDecl)) {
            error(importDecl, Diagnostics.Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_when_isolatedModules_is_enabled, unescapeLeadingUnderscores(name));
          }
        }
      }
    });
  }
  function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) {
    if (!typeOnlyDeclaration) return diagnostic;
    return addRelatedInfo(
      diagnostic,
      createDiagnosticForNode(
        typeOnlyDeclaration,
        typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 280 /* NamespaceExport */ ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here,
        unescapedName
      )
    );
  }
  function diagnosticName(nameArg) {
    return isString(nameArg) ? unescapeLeadingUnderscores(nameArg) : declarationNameToString(nameArg);
  }
  function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
    if (!isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
      return false;
    }
    const container = getThisContainer(
      errorLocation,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    let location = container;
    while (location) {
      if (isClassLike(location.parent)) {
        const classSymbol = getSymbolOfDeclaration(location.parent);
        if (!classSymbol) {
          break;
        }
        const constructorType = getTypeOfSymbol(classSymbol);
        if (getPropertyOfType(constructorType, name)) {
          error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
          return true;
        }
        if (location === container && !isStatic(location)) {
          const instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType;
          if (getPropertyOfType(instanceType, name)) {
            error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
            return true;
          }
        }
      }
      location = location.parent;
    }
    return false;
  }
  function checkAndReportErrorForExtendingInterface(errorLocation) {
    const expression = getEntityNameForExtendingInterface(errorLocation);
    if (expression && resolveEntityName(
      expression,
      64 /* Interface */,
      /*ignoreErrors*/
      true
    )) {
      error(errorLocation, Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, getTextOfNode(expression));
      return true;
    }
    return false;
  }
  function getEntityNameForExtendingInterface(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
      case 211 /* PropertyAccessExpression */:
        return node.parent ? getEntityNameForExtendingInterface(node.parent) : void 0;
      case 233 /* ExpressionWithTypeArguments */:
        if (isEntityNameExpression(node.expression)) {
          return node.expression;
        }
      // falls through
      default:
        return void 0;
    }
  }
  function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
    const namespaceMeaning = 1920 /* Namespace */ | (isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
    if (meaning === namespaceMeaning) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        788968 /* Type */ & ~namespaceMeaning,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      const parent = errorLocation.parent;
      if (symbol) {
        if (isQualifiedName(parent)) {
          Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
          const propName = parent.right.escapedText;
          const propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
          if (propType) {
            error(
              parent,
              Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1,
              unescapeLeadingUnderscores(name),
              unescapeLeadingUnderscores(propName)
            );
            return true;
          }
        }
        error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, unescapeLeadingUnderscores(name));
        return true;
      }
    }
    return false;
  }
  function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
    if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        ~788968 /* Type */ & 111551 /* Value */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
        error(errorLocation, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, unescapeLeadingUnderscores(name));
        return true;
      }
    }
    return false;
  }
  function isPrimitiveTypeName(name) {
    return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
  }
  function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
    if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 281 /* ExportSpecifier */) {
      error(errorLocation, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
      return true;
    }
    return false;
  }
  function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
    if (meaning & 111551 /* Value */) {
      if (isPrimitiveTypeName(name)) {
        const grandparent = errorLocation.parent.parent;
        if (grandparent && grandparent.parent && isHeritageClause(grandparent)) {
          const heritageKind = grandparent.token;
          const containerKind = grandparent.parent.kind;
          if (containerKind === 264 /* InterfaceDeclaration */ && heritageKind === 96 /* ExtendsKeyword */) {
            error(errorLocation, Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types, unescapeLeadingUnderscores(name));
          } else if (containerKind === 263 /* ClassDeclaration */ && heritageKind === 96 /* ExtendsKeyword */) {
            error(errorLocation, Diagnostics.A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values, unescapeLeadingUnderscores(name));
          } else if (containerKind === 263 /* ClassDeclaration */ && heritageKind === 119 /* ImplementsKeyword */) {
            error(errorLocation, Diagnostics.A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types, unescapeLeadingUnderscores(name));
          }
        } else {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, unescapeLeadingUnderscores(name));
        }
        return true;
      }
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        788968 /* Type */ & ~111551 /* Value */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      const allFlags = symbol && getSymbolFlags(symbol);
      if (symbol && allFlags !== void 0 && !(allFlags & 111551 /* Value */)) {
        const rawName = unescapeLeadingUnderscores(name);
        if (isES2015OrLaterConstructorName(name)) {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName);
        } else if (maybeMappedType(errorLocation, symbol)) {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0, rawName, rawName === "K" ? "P" : "K");
        } else {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, rawName);
        }
        return true;
      }
    }
    return false;
  }
  function maybeMappedType(node, symbol) {
    const container = findAncestor(node.parent, (n) => isComputedPropertyName(n) || isPropertySignature(n) ? false : isTypeLiteralNode(n) || "quit");
    if (container && container.members.length === 1) {
      const type = getDeclaredTypeOfSymbol(symbol);
      return !!(type.flags & 1048576 /* Union */) && allTypesAssignableToKind(
        type,
        384 /* StringOrNumberLiteral */,
        /*strict*/
        true
      );
    }
    return false;
  }
  function isES2015OrLaterConstructorName(n) {
    switch (n) {
      case "Promise":
      case "Symbol":
      case "Map":
      case "WeakMap":
      case "Set":
      case "WeakSet":
        return true;
    }
    return false;
  }
  function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) {
    if (meaning & (111551 /* Value */ & ~788968 /* Type */)) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        1024 /* NamespaceModule */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      if (symbol) {
        error(
          errorLocation,
          Diagnostics.Cannot_use_namespace_0_as_a_value,
          unescapeLeadingUnderscores(name)
        );
        return true;
      }
    } else if (meaning & (788968 /* Type */ & ~111551 /* Value */)) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        1536 /* Module */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      if (symbol) {
        error(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_type, unescapeLeadingUnderscores(name));
        return true;
      }
    }
    return false;
  }
  function checkResolvedBlockScopedVariable(result, errorLocation) {
    var _a;
    Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
    if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
      return;
    }
    const declaration = (_a = result.declarations) == null ? void 0 : _a.find(
      (d) => isBlockOrCatchScoped(d) || isClassLike(d) || d.kind === 266 /* EnumDeclaration */
    );
    if (declaration === void 0) return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
    if (!(declaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
      let diagnosticMessage;
      const declarationName = declarationNameToString(getNameOfDeclaration(declaration));
      if (result.flags & 2 /* BlockScopedVariable */) {
        diagnosticMessage = error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
      } else if (result.flags & 32 /* Class */) {
        diagnosticMessage = error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationName);
      } else if (result.flags & 256 /* RegularEnum */) {
        diagnosticMessage = error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName);
      } else {
        Debug.assert(!!(result.flags & 128 /* ConstEnum */));
        if (getIsolatedModules(compilerOptions)) {
          diagnosticMessage = error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName);
        }
      }
      if (diagnosticMessage) {
        addRelatedInfo(diagnosticMessage, createDiagnosticForNode(declaration, Diagnostics._0_is_declared_here, declarationName));
      }
    }
  }
  function isSameScopeDescendentOf(initial, parent, stopAt) {
    return !!parent && !!findAncestor(initial, (n) => n === parent || (n === stopAt || isFunctionLike(n) && (!getImmediatelyInvokedFunctionExpression(n) || getFunctionFlags(n) & 3 /* AsyncGenerator */) ? "quit" : false));
  }
  function getAnyImportSyntax(node) {
    switch (node.kind) {
      case 271 /* ImportEqualsDeclaration */:
        return node;
      case 273 /* ImportClause */:
        return node.parent;
      case 274 /* NamespaceImport */:
        return node.parent.parent;
      case 276 /* ImportSpecifier */:
        return node.parent.parent.parent;
      default:
        return void 0;
    }
  }
  function getDeclarationOfAliasSymbol(symbol) {
    return symbol.declarations && findLast(symbol.declarations, isAliasSymbolDeclaration);
  }
  function isAliasSymbolDeclaration(node) {
    return node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 270 /* NamespaceExportDeclaration */ || node.kind === 273 /* ImportClause */ && !!node.name || node.kind === 274 /* NamespaceImport */ || node.kind === 280 /* NamespaceExport */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 281 /* ExportSpecifier */ || node.kind === 277 /* ExportAssignment */ && exportAssignmentIsAlias(node) || isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || isAccessExpression(node) && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */ && isAliasableOrJsExpression(node.parent.right) || node.kind === 304 /* ShorthandPropertyAssignment */ || node.kind === 303 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) || node.kind === 260 /* VariableDeclaration */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node) || node.kind === 208 /* BindingElement */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent);
  }
  function isAliasableOrJsExpression(e) {
    return isAliasableExpression(e) || isFunctionExpression(e) && isJSConstructor(e);
  }
  function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
    const commonJSPropertyAccess = getCommonJSPropertyAccess(node);
    if (commonJSPropertyAccess) {
      const name = getLeftmostAccessExpression(commonJSPropertyAccess.expression).arguments[0];
      return isIdentifier(commonJSPropertyAccess.name) ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : void 0;
    }
    if (isVariableDeclaration(node) || node.moduleReference.kind === 283 /* ExternalModuleReference */) {
      const immediate = resolveExternalModuleName(
        node,
        getExternalModuleRequireArgument(node) || getExternalModuleImportEqualsDeclarationExpression(node)
      );
      const resolved2 = resolveExternalModuleSymbol(immediate);
      markSymbolOfAliasDeclarationIfTypeOnly(
        node,
        immediate,
        resolved2,
        /*overwriteEmpty*/
        false
      );
      return resolved2;
    }
    const resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
    checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
    return resolved;
  }
  function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
    if (markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    ) && !node.isTypeOnly) {
      const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfDeclaration(node));
      const isExport = typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */;
      const message = isExport ? Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type : Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
      const relatedMessage = isExport ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here;
      const name = typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? "*" : moduleExportNameTextUnescaped(typeOnlyDeclaration.name);
      addRelatedInfo(error(node.moduleReference, message), createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
    }
  }
  function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
    const exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
    const exportSymbol = exportValue ? getPropertyOfType(
      getTypeOfSymbol(exportValue),
      name,
      /*skipObjectFunctionPropertyAugment*/
      true
    ) : moduleSymbol.exports.get(name);
    const resolved = resolveSymbol(exportSymbol, dontResolveAlias);
    markSymbolOfAliasDeclarationIfTypeOnly(
      sourceNode,
      exportSymbol,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function isSyntacticDefault(node) {
    return isExportAssignment(node) && !node.isExportEquals || hasSyntacticModifier(node, 2048 /* Default */) || isExportSpecifier(node) || isNamespaceExport(node);
  }
  function getEmitSyntaxForModuleSpecifierExpression(usage) {
    return isStringLiteralLike(usage) ? host.getEmitSyntaxForUsageLocation(getSourceFileOfNode(usage), usage) : void 0;
  }
  function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) {
    return usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */;
  }
  function isOnlyImportableAsDefault(usage, resolvedModule) {
    if (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) {
      const usageMode = getEmitSyntaxForModuleSpecifierExpression(usage);
      if (usageMode === 99 /* ESNext */) {
        resolvedModule ?? (resolvedModule = resolveExternalModuleName(
          usage,
          usage,
          /*ignoreErrors*/
          true
        ));
        const targetFile = resolvedModule && getSourceFileOfModule(resolvedModule);
        return targetFile && (isJsonSourceFile(targetFile) || getDeclarationFileExtension(targetFile.fileName) === ".d.json.ts");
      }
    }
    return false;
  }
  function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) {
    const usageMode = file && getEmitSyntaxForModuleSpecifierExpression(usage);
    if (file && usageMode !== void 0) {
      const targetMode = host.getImpliedNodeFormatForEmit(file);
      if (usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */ && 100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) {
        return true;
      }
      if (usageMode === 99 /* ESNext */ && targetMode === 99 /* ESNext */) {
        return false;
      }
    }
    if (!allowSyntheticDefaultImports) {
      return false;
    }
    if (!file || file.isDeclarationFile) {
      const defaultExportSymbol = resolveExportByName(
        moduleSymbol,
        "default" /* Default */,
        /*sourceNode*/
        void 0,
        /*dontResolveAlias*/
        true
      );
      if (defaultExportSymbol && some(defaultExportSymbol.declarations, isSyntacticDefault)) {
        return false;
      }
      if (resolveExportByName(
        moduleSymbol,
        escapeLeadingUnderscores("__esModule"),
        /*sourceNode*/
        void 0,
        dontResolveAlias
      )) {
        return false;
      }
      return true;
    }
    if (!isSourceFileJS(file)) {
      return hasExportAssignmentSymbol(moduleSymbol);
    }
    return typeof file.externalModuleIndicator !== "object" && !resolveExportByName(
      moduleSymbol,
      escapeLeadingUnderscores("__esModule"),
      /*sourceNode*/
      void 0,
      dontResolveAlias
    );
  }
  function getTargetOfImportClause(node, dontResolveAlias) {
    const moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
    if (moduleSymbol) {
      return getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias);
    }
  }
  function getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias) {
    var _a;
    let exportDefaultSymbol;
    if (isShorthandAmbientModuleSymbol(moduleSymbol)) {
      exportDefaultSymbol = moduleSymbol;
    } else {
      exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
    }
    const file = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile);
    const specifier = getModuleSpecifierForImportOrExport(node);
    if (!specifier) {
      return exportDefaultSymbol;
    }
    const hasDefaultOnly = isOnlyImportableAsDefault(specifier, moduleSymbol);
    const hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, specifier);
    if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) {
      if (hasExportAssignmentSymbol(moduleSymbol) && !allowSyntheticDefaultImports) {
        const compilerOptionName = moduleKind >= 5 /* ES2015 */ ? "allowSyntheticDefaultImports" : "esModuleInterop";
        const exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
        const exportAssignment = exportEqualsSymbol.valueDeclaration;
        const err = error(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
        if (exportAssignment) {
          addRelatedInfo(
            err,
            createDiagnosticForNode(
              exportAssignment,
              Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag,
              compilerOptionName
            )
          );
        }
      } else if (isImportClause(node)) {
        reportNonDefaultExport(moduleSymbol, node);
      } else {
        errorNoModuleMemberSymbol(moduleSymbol, moduleSymbol, node, isImportOrExportSpecifier(node) && node.propertyName || node.name);
      }
    } else if (hasSyntheticDefault || hasDefaultOnly) {
      const resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
      markSymbolOfAliasDeclarationIfTypeOnly(
        node,
        moduleSymbol,
        resolved,
        /*overwriteEmpty*/
        false
      );
      return resolved;
    }
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      exportDefaultSymbol,
      /*finalTarget*/
      void 0,
      /*overwriteEmpty*/
      false
    );
    return exportDefaultSymbol;
  }
  function getModuleSpecifierForImportOrExport(node) {
    switch (node.kind) {
      case 273 /* ImportClause */:
        return node.parent.moduleSpecifier;
      case 271 /* ImportEqualsDeclaration */:
        return isExternalModuleReference(node.moduleReference) ? node.moduleReference.expression : void 0;
      case 274 /* NamespaceImport */:
        return node.parent.parent.moduleSpecifier;
      case 276 /* ImportSpecifier */:
        return node.parent.parent.parent.moduleSpecifier;
      case 281 /* ExportSpecifier */:
        return node.parent.parent.moduleSpecifier;
      default:
        return Debug.assertNever(node);
    }
  }
  function reportNonDefaultExport(moduleSymbol, node) {
    var _a, _b, _c;
    if ((_a = moduleSymbol.exports) == null ? void 0 : _a.has(node.symbol.escapedName)) {
      error(
        node.name,
        Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead,
        symbolToString(moduleSymbol),
        symbolToString(node.symbol)
      );
    } else {
      const diagnostic = error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
      const exportStar = (_b = moduleSymbol.exports) == null ? void 0 : _b.get("__export" /* ExportStar */);
      if (exportStar) {
        const defaultExport = (_c = exportStar.declarations) == null ? void 0 : _c.find(
          (decl) => {
            var _a2, _b2;
            return !!(isExportDeclaration(decl) && decl.moduleSpecifier && ((_b2 = (_a2 = resolveExternalModuleName(decl, decl.moduleSpecifier)) == null ? void 0 : _a2.exports) == null ? void 0 : _b2.has("default" /* Default */)));
          }
        );
        if (defaultExport) {
          addRelatedInfo(diagnostic, createDiagnosticForNode(defaultExport, Diagnostics.export_Asterisk_does_not_re_export_a_default));
        }
      }
    }
  }
  function getTargetOfNamespaceImport(node, dontResolveAlias) {
    const moduleSpecifier = node.parent.parent.moduleSpecifier;
    const immediate = resolveExternalModuleName(node, moduleSpecifier);
    const resolved = resolveESModuleSymbol(
      immediate,
      moduleSpecifier,
      dontResolveAlias,
      /*suppressInteropError*/
      false
    );
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      immediate,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getTargetOfNamespaceExport(node, dontResolveAlias) {
    const moduleSpecifier = node.parent.moduleSpecifier;
    const immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
    const resolved = moduleSpecifier && resolveESModuleSymbol(
      immediate,
      moduleSpecifier,
      dontResolveAlias,
      /*suppressInteropError*/
      false
    );
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      immediate,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
    if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
      return unknownSymbol;
    }
    if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
      return valueSymbol;
    }
    const result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
    Debug.assert(valueSymbol.declarations || typeSymbol.declarations);
    result.declarations = deduplicate(concatenate(valueSymbol.declarations, typeSymbol.declarations), equateValues);
    result.parent = valueSymbol.parent || typeSymbol.parent;
    if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration;
    if (typeSymbol.members) result.members = new Map(typeSymbol.members);
    if (valueSymbol.exports) result.exports = new Map(valueSymbol.exports);
    return result;
  }
  function getExportOfModule(symbol, nameText, specifier, dontResolveAlias) {
    var _a;
    if (symbol.flags & 1536 /* Module */) {
      const exportSymbol = getExportsOfSymbol(symbol).get(nameText);
      const resolved = resolveSymbol(exportSymbol, dontResolveAlias);
      const exportStarDeclaration = (_a = getSymbolLinks(symbol).typeOnlyExportStarMap) == null ? void 0 : _a.get(nameText);
      markSymbolOfAliasDeclarationIfTypeOnly(
        specifier,
        exportSymbol,
        resolved,
        /*overwriteEmpty*/
        false,
        exportStarDeclaration,
        nameText
      );
      return resolved;
    }
  }
  function getPropertyOfVariable(symbol, name) {
    if (symbol.flags & 3 /* Variable */) {
      const typeAnnotation = symbol.valueDeclaration.type;
      if (typeAnnotation) {
        return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
      }
    }
  }
  function getExternalModuleMember(node, specifier, dontResolveAlias = false) {
    var _a;
    const moduleSpecifier = getExternalModuleRequireArgument(node) || node.moduleSpecifier;
    const moduleSymbol = resolveExternalModuleName(node, moduleSpecifier);
    const name = !isPropertyAccessExpression(specifier) && specifier.propertyName || specifier.name;
    if (!isIdentifier(name) && name.kind !== 11 /* StringLiteral */) {
      return void 0;
    }
    const nameText = moduleExportNameTextEscaped(name);
    const suppressInteropError = nameText === "default" /* Default */ && allowSyntheticDefaultImports;
    const targetSymbol = resolveESModuleSymbol(
      moduleSymbol,
      moduleSpecifier,
      /*dontResolveAlias*/
      false,
      suppressInteropError
    );
    if (targetSymbol) {
      if (nameText || name.kind === 11 /* StringLiteral */) {
        if (isShorthandAmbientModuleSymbol(moduleSymbol)) {
          return moduleSymbol;
        }
        let symbolFromVariable;
        if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
          symbolFromVariable = getPropertyOfType(
            getTypeOfSymbol(targetSymbol),
            nameText,
            /*skipObjectFunctionPropertyAugment*/
            true
          );
        } else {
          symbolFromVariable = getPropertyOfVariable(targetSymbol, nameText);
        }
        symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
        let symbolFromModule = getExportOfModule(targetSymbol, nameText, specifier, dontResolveAlias);
        if (symbolFromModule === void 0 && nameText === "default" /* Default */) {
          const file = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile);
          if (isOnlyImportableAsDefault(moduleSpecifier, moduleSymbol) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) {
            symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
          }
        }
        const symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable;
        if (isImportOrExportSpecifier(specifier) && isOnlyImportableAsDefault(moduleSpecifier, moduleSymbol) && nameText !== "default" /* Default */) {
          error(name, Diagnostics.Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0, ModuleKind[moduleKind]);
        } else if (!symbol) {
          errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name);
        }
        return symbol;
      }
    }
  }
  function errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name) {
    var _a;
    const moduleName = getFullyQualifiedName(moduleSymbol, node);
    const declarationName = declarationNameToString(name);
    const suggestion = isIdentifier(name) ? getSuggestedSymbolForNonexistentModule(name, targetSymbol) : void 0;
    if (suggestion !== void 0) {
      const suggestionName = symbolToString(suggestion);
      const diagnostic = error(name, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
      if (suggestion.valueDeclaration) {
        addRelatedInfo(diagnostic, createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName));
      }
    } else {
      if ((_a = moduleSymbol.exports) == null ? void 0 : _a.has("default" /* Default */)) {
        error(
          name,
          Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead,
          moduleName,
          declarationName
        );
      } else {
        reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
      }
    }
  }
  function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
    var _a, _b;
    const localSymbol = (_b = (_a = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _a.locals) == null ? void 0 : _b.get(moduleExportNameTextEscaped(name));
    const exports2 = moduleSymbol.exports;
    if (localSymbol) {
      const exportedEqualsSymbol = exports2 == null ? void 0 : exports2.get("export=" /* ExportEquals */);
      if (exportedEqualsSymbol) {
        getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
      } else {
        const exportedSymbol = exports2 ? find(symbolsToArray(exports2), (symbol) => !!getSymbolIfSameReference(symbol, localSymbol)) : void 0;
        const diagnostic = exportedSymbol ? error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
        if (localSymbol.declarations) {
          addRelatedInfo(diagnostic, ...map(localSymbol.declarations, (decl, index) => createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName)));
        }
      }
    } else {
      error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
    }
  }
  function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
    if (moduleKind >= 5 /* ES2015 */) {
      const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_a_default_import : Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
      error(name, message, declarationName);
    } else {
      if (isInJSFile(node)) {
        const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
        error(name, message, declarationName);
      } else {
        const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
        error(name, message, declarationName, declarationName, moduleName);
      }
    }
  }
  function getTargetOfImportSpecifier(node, dontResolveAlias) {
    if (isImportSpecifier(node) && moduleExportNameIsDefault(node.propertyName || node.name)) {
      const specifier = getModuleSpecifierForImportOrExport(node);
      const moduleSymbol = specifier && resolveExternalModuleName(node, specifier);
      if (moduleSymbol) {
        return getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias);
      }
    }
    const root = isBindingElement(node) ? getRootDeclaration(node) : node.parent.parent.parent;
    const commonJSPropertyAccess = getCommonJSPropertyAccess(root);
    const resolved = getExternalModuleMember(root, commonJSPropertyAccess || node, dontResolveAlias);
    const name = node.propertyName || node.name;
    if (commonJSPropertyAccess && resolved && isIdentifier(name)) {
      return resolveSymbol(getPropertyOfType(getTypeOfSymbol(resolved), name.escapedText), dontResolveAlias);
    }
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getCommonJSPropertyAccess(node) {
    if (isVariableDeclaration(node) && node.initializer && isPropertyAccessExpression(node.initializer)) {
      return node.initializer;
    }
  }
  function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
    if (canHaveSymbol(node.parent)) {
      const resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
      markSymbolOfAliasDeclarationIfTypeOnly(
        node,
        /*immediateTarget*/
        void 0,
        resolved,
        /*overwriteEmpty*/
        false
      );
      return resolved;
    }
  }
  function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
    const name = node.propertyName || node.name;
    if (moduleExportNameIsDefault(name)) {
      const specifier = getModuleSpecifierForImportOrExport(node);
      const moduleSymbol = specifier && resolveExternalModuleName(node, specifier);
      if (moduleSymbol) {
        return getTargetofModuleDefault(moduleSymbol, node, !!dontResolveAlias);
      }
    }
    const resolved = node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : name.kind === 11 /* StringLiteral */ ? void 0 : (
      // Skip for invalid syntax like this: export { "x" }
      resolveEntityName(
        name,
        meaning,
        /*ignoreErrors*/
        false,
        dontResolveAlias
      )
    );
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getTargetOfExportAssignment(node, dontResolveAlias) {
    const expression = isExportAssignment(node) ? node.expression : node.right;
    const resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
    if (isClassExpression(expression)) {
      return checkExpressionCached(expression).symbol;
    }
    if (!isEntityName(expression) && !isEntityNameExpression(expression)) {
      return void 0;
    }
    const aliasLike = resolveEntityName(
      expression,
      111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */,
      /*ignoreErrors*/
      true,
      dontResolveAlias
    );
    if (aliasLike) {
      return aliasLike;
    }
    checkExpressionCached(expression);
    return getNodeLinks(expression).resolvedSymbol;
  }
  function getTargetOfAccessExpression(node, dontRecursivelyResolve) {
    if (!(isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */)) {
      return void 0;
    }
    return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
  }
  function getTargetOfAliasDeclaration(node, dontRecursivelyResolve = false) {
    switch (node.kind) {
      case 271 /* ImportEqualsDeclaration */:
      case 260 /* VariableDeclaration */:
        return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
      case 273 /* ImportClause */:
        return getTargetOfImportClause(node, dontRecursivelyResolve);
      case 274 /* NamespaceImport */:
        return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
      case 280 /* NamespaceExport */:
        return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
      case 276 /* ImportSpecifier */:
      case 208 /* BindingElement */:
        return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
      case 281 /* ExportSpecifier */:
        return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
      case 277 /* ExportAssignment */:
      case 226 /* BinaryExpression */:
        return getTargetOfExportAssignment(node, dontRecursivelyResolve);
      case 270 /* NamespaceExportDeclaration */:
        return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
      case 304 /* ShorthandPropertyAssignment */:
        return resolveEntityName(
          node.name,
          111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */,
          /*ignoreErrors*/
          true,
          dontRecursivelyResolve
        );
      case 303 /* PropertyAssignment */:
        return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve);
      case 212 /* ElementAccessExpression */:
      case 211 /* PropertyAccessExpression */:
        return getTargetOfAccessExpression(node, dontRecursivelyResolve);
      default:
        return Debug.fail();
    }
  }
  function isNonLocalAlias(symbol, excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */) {
    if (!symbol) return false;
    return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
  }
  function resolveSymbol(symbol, dontResolveAlias) {
    return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
  }
  function resolveAlias(symbol) {
    Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
    const links = getSymbolLinks(symbol);
    if (!links.aliasTarget) {
      links.aliasTarget = resolvingSymbol;
      const node = getDeclarationOfAliasSymbol(symbol);
      if (!node) return Debug.fail();
      const target = getTargetOfAliasDeclaration(node);
      if (links.aliasTarget === resolvingSymbol) {
        links.aliasTarget = target || unknownSymbol;
      } else {
        error(node, Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
      }
    } else if (links.aliasTarget === resolvingSymbol) {
      links.aliasTarget = unknownSymbol;
    }
    return links.aliasTarget;
  }
  function tryResolveAlias(symbol) {
    const links = getSymbolLinks(symbol);
    if (links.aliasTarget !== resolvingSymbol) {
      return resolveAlias(symbol);
    }
    return void 0;
  }
  function getSymbolFlags(symbol, excludeTypeOnlyMeanings, excludeLocalMeanings) {
    const typeOnlyDeclaration = excludeTypeOnlyMeanings && getTypeOnlyAliasDeclaration(symbol);
    const typeOnlyDeclarationIsExportStar = typeOnlyDeclaration && isExportDeclaration(typeOnlyDeclaration);
    const typeOnlyResolution = typeOnlyDeclaration && (typeOnlyDeclarationIsExportStar ? resolveExternalModuleName(
      typeOnlyDeclaration.moduleSpecifier,
      typeOnlyDeclaration.moduleSpecifier,
      /*ignoreErrors*/
      true
    ) : resolveAlias(typeOnlyDeclaration.symbol));
    const typeOnlyExportStarTargets = typeOnlyDeclarationIsExportStar && typeOnlyResolution ? getExportsOfModule(typeOnlyResolution) : void 0;
    let flags = excludeLocalMeanings ? 0 /* None */ : symbol.flags;
    let seenSymbols;
    while (symbol.flags & 2097152 /* Alias */) {
      const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol));
      if (!typeOnlyDeclarationIsExportStar && target === typeOnlyResolution || (typeOnlyExportStarTargets == null ? void 0 : typeOnlyExportStarTargets.get(target.escapedName)) === target) {
        break;
      }
      if (target === unknownSymbol) {
        return -1 /* All */;
      }
      if (target === symbol || (seenSymbols == null ? void 0 : seenSymbols.has(target))) {
        break;
      }
      if (target.flags & 2097152 /* Alias */) {
        if (seenSymbols) {
          seenSymbols.add(target);
        } else {
          seenSymbols = /* @__PURE__ */ new Set([symbol, target]);
        }
      }
      flags |= target.flags;
      symbol = target;
    }
    return flags;
  }
  function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty, exportStarDeclaration, exportStarName) {
    if (!aliasDeclaration || isPropertyAccessExpression(aliasDeclaration)) return false;
    const sourceSymbol = getSymbolOfDeclaration(aliasDeclaration);
    if (isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
      const links2 = getSymbolLinks(sourceSymbol);
      links2.typeOnlyDeclaration = aliasDeclaration;
      return true;
    }
    if (exportStarDeclaration) {
      const links2 = getSymbolLinks(sourceSymbol);
      links2.typeOnlyDeclaration = exportStarDeclaration;
      if (sourceSymbol.escapedName !== exportStarName) {
        links2.typeOnlyExportStarName = exportStarName;
      }
      return true;
    }
    const links = getSymbolLinks(sourceSymbol);
    return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty) || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
  }
  function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
    var _a;
    if (target && (aliasDeclarationLinks.typeOnlyDeclaration === void 0 || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
      const exportSymbol = ((_a = target.exports) == null ? void 0 : _a.get("export=" /* ExportEquals */)) ?? target;
      const typeOnly = exportSymbol.declarations && find(exportSymbol.declarations, isTypeOnlyImportOrExportDeclaration);
      aliasDeclarationLinks.typeOnlyDeclaration = typeOnly ?? getSymbolLinks(exportSymbol).typeOnlyDeclaration ?? false;
    }
    return !!aliasDeclarationLinks.typeOnlyDeclaration;
  }
  function getTypeOnlyAliasDeclaration(symbol, include) {
    var _a;
    if (!(symbol.flags & 2097152 /* Alias */)) {
      return void 0;
    }
    const links = getSymbolLinks(symbol);
    if (links.typeOnlyDeclaration === void 0) {
      links.typeOnlyDeclaration = false;
      const resolved = resolveSymbol(symbol);
      markSymbolOfAliasDeclarationIfTypeOnly(
        (_a = symbol.declarations) == null ? void 0 : _a[0],
        getDeclarationOfAliasSymbol(symbol) && getImmediateAliasedSymbol(symbol),
        resolved,
        /*overwriteEmpty*/
        true
      );
    }
    if (include === void 0) {
      return links.typeOnlyDeclaration || void 0;
    }
    if (links.typeOnlyDeclaration) {
      const resolved = links.typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? resolveSymbol(getExportsOfModule(links.typeOnlyDeclaration.symbol.parent).get(links.typeOnlyExportStarName || symbol.escapedName)) : resolveAlias(links.typeOnlyDeclaration.symbol);
      return getSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0;
    }
    return void 0;
  }
  function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
    if (entityName.kind === 80 /* Identifier */ && isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
      entityName = entityName.parent;
    }
    if (entityName.kind === 80 /* Identifier */ || entityName.parent.kind === 166 /* QualifiedName */) {
      return resolveEntityName(
        entityName,
        1920 /* Namespace */,
        /*ignoreErrors*/
        false,
        dontResolveAlias
      );
    } else {
      Debug.assert(entityName.parent.kind === 271 /* ImportEqualsDeclaration */);
      return resolveEntityName(
        entityName,
        111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */,
        /*ignoreErrors*/
        false,
        dontResolveAlias
      );
    }
  }
  function getFullyQualifiedName(symbol, containingLocation) {
    return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(
      symbol,
      containingLocation,
      /*meaning*/
      void 0,
      32 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */
    );
  }
  function getContainingQualifiedNameNode(node) {
    while (isQualifiedName(node.parent)) {
      node = node.parent;
    }
    return node;
  }
  function tryGetQualifiedNameAsValue(node) {
    let left = getFirstIdentifier(node);
    let symbol = resolveName(
      left,
      left,
      111551 /* Value */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
    if (!symbol) {
      return void 0;
    }
    while (isQualifiedName(left.parent)) {
      const type = getTypeOfSymbol(symbol);
      symbol = getPropertyOfType(type, left.parent.right.escapedText);
      if (!symbol) {
        return void 0;
      }
      left = left.parent;
    }
    return symbol;
  }
  function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
    if (nodeIsMissing(name)) {
      return void 0;
    }
    const namespaceMeaning = 1920 /* Namespace */ | (isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
    let symbol;
    if (name.kind === 80 /* Identifier */) {
      const message = meaning === namespaceMeaning || nodeIsSynthesized(name) ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name));
      const symbolFromJSPrototype = isInJSFile(name) && !nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : void 0;
      symbol = getMergedSymbol(resolveName(
        location || name,
        name,
        meaning,
        ignoreErrors || symbolFromJSPrototype ? void 0 : message,
        /*isUse*/
        true,
        /*excludeGlobals*/
        false
      ));
      if (!symbol) {
        return getMergedSymbol(symbolFromJSPrototype);
      }
    } else if (name.kind === 166 /* QualifiedName */ || name.kind === 211 /* PropertyAccessExpression */) {
      const left = name.kind === 166 /* QualifiedName */ ? name.left : name.expression;
      const right = name.kind === 166 /* QualifiedName */ ? name.right : name.name;
      let namespace = resolveEntityName(
        left,
        namespaceMeaning,
        ignoreErrors,
        /*dontResolveAlias*/
        false,
        location
      );
      if (!namespace || nodeIsMissing(right)) {
        return void 0;
      } else if (namespace === unknownSymbol) {
        return namespace;
      }
      if (namespace.valueDeclaration && isInJSFile(namespace.valueDeclaration) && getEmitModuleResolutionKind(compilerOptions) !== 100 /* Bundler */ && isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && isCommonJsRequire(namespace.valueDeclaration.initializer)) {
        const moduleName = namespace.valueDeclaration.initializer.arguments[0];
        const moduleSym = resolveExternalModuleName(moduleName, moduleName);
        if (moduleSym) {
          const resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
          if (resolvedModuleSymbol) {
            namespace = resolvedModuleSymbol;
          }
        }
      }
      symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
      if (!symbol && namespace.flags & 2097152 /* Alias */) {
        symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(resolveAlias(namespace)), right.escapedText, meaning));
      }
      if (!symbol) {
        if (!ignoreErrors) {
          const namespaceName = getFullyQualifiedName(namespace);
          const declarationName = declarationNameToString(right);
          const suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace);
          if (suggestionForNonexistentModule) {
            error(right, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule));
            return void 0;
          }
          const containingQualifiedName = isQualifiedName(name) && getContainingQualifiedNameNode(name);
          const canSuggestTypeof = globalObjectType && meaning & 788968 /* Type */ && containingQualifiedName && !isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName);
          if (canSuggestTypeof) {
            error(
              containingQualifiedName,
              Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0,
              entityNameToString(containingQualifiedName)
            );
            return void 0;
          }
          if (meaning & 1920 /* Namespace */ && isQualifiedName(name.parent)) {
            const exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */));
            if (exportedTypeSymbol) {
              error(
                name.parent.right,
                Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1,
                symbolToString(exportedTypeSymbol),
                unescapeLeadingUnderscores(name.parent.right.escapedText)
              );
              return void 0;
            }
          }
          error(right, Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName);
        }
        return void 0;
      }
    } else {
      Debug.assertNever(name, "Unknown entity name kind.");
    }
    if (!nodeIsSynthesized(name) && isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 277 /* ExportAssignment */)) {
      markSymbolOfAliasDeclarationIfTypeOnly(
        getAliasDeclarationFromName(name),
        symbol,
        /*finalTarget*/
        void 0,
        /*overwriteEmpty*/
        true
      );
    }
    return symbol.flags & meaning || dontResolveAlias ? symbol : resolveAlias(symbol);
  }
  function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
    if (isJSDocTypeReference(name.parent)) {
      const secondaryLocation = getAssignmentDeclarationLocation(name.parent);
      if (secondaryLocation) {
        return resolveName(
          secondaryLocation,
          name,
          meaning,
          /*nameNotFoundMessage*/
          void 0,
          /*isUse*/
          true
        );
      }
    }
  }
  function getAssignmentDeclarationLocation(node) {
    const typeAlias = findAncestor(node, (node2) => !(isJSDocNode(node2) || node2.flags & 16777216 /* JSDoc */) ? "quit" : isJSDocTypeAlias(node2));
    if (typeAlias) {
      return;
    }
    const host2 = getJSDocHost(node);
    if (host2 && isExpressionStatement(host2) && isPrototypePropertyAssignment(host2.expression)) {
      const symbol = getSymbolOfDeclaration(host2.expression.left);
      if (symbol) {
        return getDeclarationOfJSPrototypeContainer(symbol);
      }
    }
    if (host2 && isFunctionExpression(host2) && isPrototypePropertyAssignment(host2.parent) && isExpressionStatement(host2.parent.parent)) {
      const symbol = getSymbolOfDeclaration(host2.parent.left);
      if (symbol) {
        return getDeclarationOfJSPrototypeContainer(symbol);
      }
    }
    if (host2 && (isObjectLiteralMethod(host2) || isPropertyAssignment(host2)) && isBinaryExpression(host2.parent.parent) && getAssignmentDeclarationKind(host2.parent.parent) === 6 /* Prototype */) {
      const symbol = getSymbolOfDeclaration(host2.parent.parent.left);
      if (symbol) {
        return getDeclarationOfJSPrototypeContainer(symbol);
      }
    }
    const sig = getEffectiveJSDocHost(node);
    if (sig && isFunctionLike(sig)) {
      const symbol = getSymbolOfDeclaration(sig);
      return symbol && symbol.valueDeclaration;
    }
  }
  function getDeclarationOfJSPrototypeContainer(symbol) {
    const decl = symbol.parent.valueDeclaration;
    if (!decl) {
      return void 0;
    }
    const initializer = isAssignmentDeclaration(decl) ? getAssignedExpandoInitializer(decl) : hasOnlyExpressionInitializer(decl) ? getDeclaredExpandoInitializer(decl) : void 0;
    return initializer || decl;
  }
  function getExpandoSymbol(symbol) {
    const decl = symbol.valueDeclaration;
    if (!decl || !isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || getExpandoInitializer(
      decl,
      /*isPrototypeAssignment*/
      false
    )) {
      return void 0;
    }
    const init = isVariableDeclaration(decl) ? getDeclaredExpandoInitializer(decl) : getAssignedExpandoInitializer(decl);
    if (init) {
      const initSymbol = getSymbolOfNode(init);
      if (initSymbol) {
        return mergeJSSymbols(initSymbol, symbol);
      }
    }
  }
  function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
    const isClassic = getEmitModuleResolutionKind(compilerOptions) === 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.Cannot_find_module_0_or_its_corresponding_type_declarations;
    return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? void 0 : errorMessage, ignoreErrors);
  }
  function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, ignoreErrors = false, isForAugmentation = false) {
    return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, !ignoreErrors ? moduleReferenceExpression : void 0, isForAugmentation) : void 0;
  }
  function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
    if (errorNode && startsWith(moduleReference, "@types/")) {
      const diag2 = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
      const withoutAtTypePrefix = removePrefix(moduleReference, "@types/");
      error(errorNode, diag2, withoutAtTypePrefix, moduleReference);
    }
    const ambientModule = tryFindAmbientModule(
      moduleReference,
      /*withAugmentations*/
      true
    );
    if (ambientModule) {
      return ambientModule;
    }
    const currentSourceFile = getSourceFileOfNode(location);
    const contextSpecifier = isStringLiteralLike(location) ? location : ((_a = isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : void 0) == null ? void 0 : _a.name) || ((_b = isLiteralImportTypeNode(location) ? location : void 0) == null ? void 0 : _b.argument.literal) || (isVariableDeclaration(location) && location.initializer && isRequireCall(
      location.initializer,
      /*requireStringLiteralLikeArgument*/
      true
    ) ? location.initializer.arguments[0] : void 0) || ((_c = findAncestor(location, isImportCall)) == null ? void 0 : _c.arguments[0]) || ((_d = findAncestor(location, or(isImportDeclaration, isJSDocImportTag, isExportDeclaration))) == null ? void 0 : _d.moduleSpecifier) || ((_e = findAncestor(location, isExternalModuleImportEqualsDeclaration)) == null ? void 0 : _e.moduleReference.expression);
    const mode = contextSpecifier && isStringLiteralLike(contextSpecifier) ? host.getModeForUsageLocation(currentSourceFile, contextSpecifier) : host.getDefaultResolutionModeForFile(currentSourceFile);
    const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions);
    const resolvedModule = (_f = host.getResolvedModule(currentSourceFile, moduleReference, mode)) == null ? void 0 : _f.resolvedModule;
    const resolutionDiagnostic = errorNode && resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule, currentSourceFile);
    const sourceFile = resolvedModule && (!resolutionDiagnostic || resolutionDiagnostic === Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set) && host.getSourceFile(resolvedModule.resolvedFileName);
    if (sourceFile) {
      if (resolutionDiagnostic) {
        error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
      }
      if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) {
        const importOrExport = ((_g = findAncestor(location, isImportDeclaration)) == null ? void 0 : _g.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration));
        if (errorNode && importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) {
          error(
            errorNode,
            Diagnostics.A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead,
            getSuggestedImportSource(Debug.checkDefined(tryExtractTSExtension(moduleReference)))
          );
        }
      } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) {
        const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration));
        if (errorNode && !((importOrExport == null ? void 0 : importOrExport.isTypeOnly) || findAncestor(location, isImportTypeNode))) {
          const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference));
          error(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension);
        }
      } else if (compilerOptions.rewriteRelativeImportExtensions && !(location.flags & 33554432 /* Ambient */) && !isDeclarationFileName(moduleReference) && !isLiteralImportTypeNode(location) && !isPartOfTypeOnlyImportOrExportDeclaration(location)) {
        const shouldRewrite = shouldRewriteModuleSpecifier(moduleReference, compilerOptions);
        if (!resolvedModule.resolvedUsingTsExtension && shouldRewrite) {
          error(
            errorNode,
            Diagnostics.This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolves_to_0,
            getRelativePathFromFile(getNormalizedAbsolutePath(currentSourceFile.fileName, host.getCurrentDirectory()), resolvedModule.resolvedFileName, hostGetCanonicalFileName(host))
          );
        } else if (resolvedModule.resolvedUsingTsExtension && !shouldRewrite && sourceFileMayBeEmitted(sourceFile, host)) {
          error(
            errorNode,
            Diagnostics.This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_during_emit_because_it_is_not_a_relative_path,
            getAnyExtensionFromPath(moduleReference)
          );
        } else if (resolvedModule.resolvedUsingTsExtension && shouldRewrite) {
          const redirect = host.getResolvedProjectReferenceToRedirect(sourceFile.path);
          if (redirect) {
            const ignoreCase = !host.useCaseSensitiveFileNames();
            const ownRootDir = host.getCommonSourceDirectory();
            const otherRootDir = getCommonSourceDirectoryOfConfig(redirect.commandLine, ignoreCase);
            const rootDirPath = getRelativePathFromDirectory(ownRootDir, otherRootDir, ignoreCase);
            const outDirPath = getRelativePathFromDirectory(compilerOptions.outDir || ownRootDir, redirect.commandLine.options.outDir || otherRootDir, ignoreCase);
            if (rootDirPath !== outDirPath) {
              error(
                errorNode,
                Diagnostics.This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_between_the_projects_output_files_is_not_the_same_as_the_relative_path_between_its_input_files
              );
            }
          }
        }
      }
      if (sourceFile.symbol) {
        if (errorNode && resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
          errorOnImplicitAnyModule(
            /*isError*/
            false,
            errorNode,
            currentSourceFile,
            mode,
            resolvedModule,
            moduleReference
          );
        }
        if (errorNode && (moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */)) {
          const isSyncImport = currentSourceFile.impliedNodeFormat === 1 /* CommonJS */ && !findAncestor(location, isImportCall) || !!findAncestor(location, isImportEqualsDeclaration);
          const overrideHost = findAncestor(location, (l) => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l) || isJSDocImportTag(l));
          if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !hasResolutionModeOverride(overrideHost)) {
            if (findAncestor(location, isImportEqualsDeclaration)) {
              error(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference);
            } else {
              let diagnosticDetails;
              const ext = tryGetExtensionFromPath2(currentSourceFile.fileName);
              if (ext === ".ts" /* Ts */ || ext === ".js" /* Js */ || ext === ".tsx" /* Tsx */ || ext === ".jsx" /* Jsx */) {
                diagnosticDetails = createModeMismatchDetails(currentSourceFile);
              }
              const message = (overrideHost == null ? void 0 : overrideHost.kind) === 272 /* ImportDeclaration */ && ((_i = overrideHost.importClause) == null ? void 0 : _i.isTypeOnly) ? Diagnostics.Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute : (overrideHost == null ? void 0 : overrideHost.kind) === 205 /* ImportType */ ? Diagnostics.Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute : Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead;
              diagnostics.add(createDiagnosticForNodeFromMessageChain(
                getSourceFileOfNode(errorNode),
                errorNode,
                chainDiagnosticMessages(diagnosticDetails, message, moduleReference)
              ));
            }
          }
        }
        return getMergedSymbol(sourceFile.symbol);
      }
      if (errorNode && moduleNotFoundError && !isSideEffectImport(errorNode)) {
        error(errorNode, Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
      }
      return void 0;
    }
    if (patternAmbientModules) {
      const pattern = findBestPatternMatch(patternAmbientModules, (_) => _.pattern, moduleReference);
      if (pattern) {
        const augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
        if (augmentation) {
          return getMergedSymbol(augmentation);
        }
        return getMergedSymbol(pattern.symbol);
      }
    }
    if (!errorNode) {
      return void 0;
    }
    if (resolvedModule && !resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === void 0 || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
      if (isForAugmentation) {
        const diag2 = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
        error(errorNode, diag2, moduleReference, resolvedModule.resolvedFileName);
      } else {
        errorOnImplicitAnyModule(
          /*isError*/
          noImplicitAny && !!moduleNotFoundError,
          errorNode,
          currentSourceFile,
          mode,
          resolvedModule,
          moduleReference
        );
      }
      return void 0;
    }
    if (moduleNotFoundError) {
      if (resolvedModule) {
        const redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
        if (redirect) {
          error(errorNode, Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
          return void 0;
        }
      }
      if (resolutionDiagnostic) {
        error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
      } else {
        const isExtensionlessRelativePathImport = pathIsRelative(moduleReference) && !hasExtension(moduleReference);
        const resolutionIsNode16OrNext = moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */;
        if (!getResolveJsonModule(compilerOptions) && fileExtensionIs(moduleReference, ".json" /* Json */) && moduleResolutionKind !== 1 /* Classic */ && hasJsonModuleEmitEnabled(compilerOptions)) {
          error(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
        } else if (mode === 99 /* ESNext */ && resolutionIsNode16OrNext && isExtensionlessRelativePathImport) {
          const absoluteRef = getNormalizedAbsolutePath(moduleReference, getDirectoryPath(currentSourceFile.path));
          const suggestedExt = (_j = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _j[1];
          if (suggestedExt) {
            error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt);
          } else {
            error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path);
          }
        } else {
          if ((_k = host.getResolvedModule(currentSourceFile, moduleReference, mode)) == null ? void 0 : _k.alternateResult) {
            const errorInfo = createModuleNotFoundChain(currentSourceFile, host, moduleReference, mode, moduleReference);
            errorOrSuggestion(
              /*isError*/
              true,
              errorNode,
              chainDiagnosticMessages(errorInfo, moduleNotFoundError, moduleReference)
            );
          } else {
            error(errorNode, moduleNotFoundError, moduleReference);
          }
        }
      }
    }
    return void 0;
    function getSuggestedImportSource(tsExtension) {
      const importSourceWithoutExtension = removeExtension(moduleReference, tsExtension);
      if (emitModuleKindIsNonNodeESM(moduleKind) || mode === 99 /* ESNext */) {
        const preferTs = isDeclarationFileName(moduleReference) && shouldAllowImportingTsExtension(compilerOptions);
        const ext = tsExtension === ".mts" /* Mts */ || tsExtension === ".d.mts" /* Dmts */ ? preferTs ? ".mts" : ".mjs" : tsExtension === ".cts" /* Cts */ || tsExtension === ".d.mts" /* Dmts */ ? preferTs ? ".cts" : ".cjs" : preferTs ? ".ts" : ".js";
        return importSourceWithoutExtension + ext;
      }
      return importSourceWithoutExtension;
    }
  }
  function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId, resolvedFileName }, moduleReference) {
    if (isSideEffectImport(errorNode)) {
      return;
    }
    let errorInfo;
    if (!isExternalModuleNameRelative(moduleReference) && packageId) {
      errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name);
    }
    errorOrSuggestion(
      isError,
      errorNode,
      chainDiagnosticMessages(
        errorInfo,
        Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type,
        moduleReference,
        resolvedFileName
      )
    );
  }
  function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
    if (moduleSymbol == null ? void 0 : moduleSymbol.exports) {
      const exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
      const exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
      return getMergedSymbol(exported) || moduleSymbol;
    }
    return void 0;
  }
  function getCommonJsExportEquals(exported, moduleSymbol) {
    if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
      return exported;
    }
    const links = getSymbolLinks(exported);
    if (links.cjsExportMerged) {
      return links.cjsExportMerged;
    }
    const merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
    merged.flags = merged.flags | 512 /* ValueModule */;
    if (merged.exports === void 0) {
      merged.exports = createSymbolTable();
    }
    moduleSymbol.exports.forEach((s, name) => {
      if (name === "export=" /* ExportEquals */) return;
      merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
    });
    if (merged === exported) {
      getSymbolLinks(merged).resolvedExports = void 0;
      getSymbolLinks(merged).resolvedMembers = void 0;
    }
    getSymbolLinks(merged).cjsExportMerged = merged;
    return links.cjsExportMerged = merged;
  }
  function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
    var _a;
    const symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
    if (!dontResolveAlias && symbol) {
      if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !getDeclarationOfKind(symbol, 307 /* SourceFile */)) {
        const compilerOptionName = moduleKind >= 5 /* ES2015 */ ? "allowSyntheticDefaultImports" : "esModuleInterop";
        error(referencingLocation, Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName);
        return symbol;
      }
      const referenceParent = referencingLocation.parent;
      if (isImportDeclaration(referenceParent) && getNamespaceDeclarationNode(referenceParent) || isImportCall(referenceParent)) {
        const reference = isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier;
        const type = getTypeOfSymbol(symbol);
        const defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference);
        if (defaultOnlyType) {
          return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent);
        }
        const targetFile = (_a = moduleSymbol == null ? void 0 : moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile);
        const isEsmCjsRef = targetFile && isESMFormatImportImportingCommonjsFormatFile(getEmitSyntaxForModuleSpecifierExpression(reference), host.getImpliedNodeFormatForEmit(targetFile));
        if (getESModuleInterop(compilerOptions) || isEsmCjsRef) {
          let sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
          if (!sigs || !sigs.length) {
            sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
          }
          if (sigs && sigs.length || getPropertyOfType(
            type,
            "default" /* Default */,
            /*skipObjectFunctionPropertyAugment*/
            true
          ) || isEsmCjsRef) {
            const moduleType = type.flags & 3670016 /* StructuredType */ ? getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference) : createDefaultPropertyWrapperForModule(symbol, symbol.parent);
            return cloneTypeAsModuleType(symbol, moduleType, referenceParent);
          }
        }
      }
    }
    return symbol;
  }
  function cloneTypeAsModuleType(symbol, moduleType, referenceParent) {
    const result = createSymbol(symbol.flags, symbol.escapedName);
    result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
    result.parent = symbol.parent;
    result.links.target = symbol;
    result.links.originatingImport = referenceParent;
    if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration;
    if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true;
    if (symbol.members) result.members = new Map(symbol.members);
    if (symbol.exports) result.exports = new Map(symbol.exports);
    const resolvedModuleType = resolveStructuredTypeMembers(moduleType);
    result.links.type = createAnonymousType(result, resolvedModuleType.members, emptyArray, emptyArray, resolvedModuleType.indexInfos);
    return result;
  }
  function hasExportAssignmentSymbol(moduleSymbol) {
    return moduleSymbol.exports.get("export=" /* ExportEquals */) !== void 0;
  }
  function getExportsOfModuleAsArray(moduleSymbol) {
    return symbolsToArray(getExportsOfModule(moduleSymbol));
  }
  function getExportsAndPropertiesOfModule(moduleSymbol) {
    const exports2 = getExportsOfModuleAsArray(moduleSymbol);
    const exportEquals = resolveExternalModuleSymbol(moduleSymbol);
    if (exportEquals !== moduleSymbol) {
      const type = getTypeOfSymbol(exportEquals);
      if (shouldTreatPropertiesOfExternalModuleAsExports(type)) {
        addRange(exports2, getPropertiesOfType(type));
      }
    }
    return exports2;
  }
  function forEachExportAndPropertyOfModule(moduleSymbol, cb) {
    const exports2 = getExportsOfModule(moduleSymbol);
    exports2.forEach((symbol, key) => {
      if (!isReservedMemberName(key)) {
        cb(symbol, key);
      }
    });
    const exportEquals = resolveExternalModuleSymbol(moduleSymbol);
    if (exportEquals !== moduleSymbol) {
      const type = getTypeOfSymbol(exportEquals);
      if (shouldTreatPropertiesOfExternalModuleAsExports(type)) {
        forEachPropertyOfType(type, (symbol, escapedName) => {
          cb(symbol, escapedName);
        });
      }
    }
  }
  function tryGetMemberInModuleExports(memberName, moduleSymbol) {
    const symbolTable = getExportsOfModule(moduleSymbol);
    if (symbolTable) {
      return symbolTable.get(memberName);
    }
  }
  function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
    const symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
    if (symbol) {
      return symbol;
    }
    const exportEquals = resolveExternalModuleSymbol(moduleSymbol);
    if (exportEquals === moduleSymbol) {
      return void 0;
    }
    const type = getTypeOfSymbol(exportEquals);
    return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : void 0;
  }
  function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) {
    return !(resolvedExternalModuleType.flags & 402784252 /* Primitive */ || getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path
    isArrayType(resolvedExternalModuleType) || isTupleType(resolvedExternalModuleType));
  }
  function getExportsOfSymbol(symbol) {
    return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols;
  }
  function getExportsOfModule(moduleSymbol) {
    const links = getSymbolLinks(moduleSymbol);
    if (!links.resolvedExports) {
      const { exports: exports2, typeOnlyExportStarMap } = getExportsOfModuleWorker(moduleSymbol);
      links.resolvedExports = exports2;
      links.typeOnlyExportStarMap = typeOnlyExportStarMap;
    }
    return links.resolvedExports;
  }
  function extendExportSymbols(target, source, lookupTable, exportNode) {
    if (!source) return;
    source.forEach((sourceSymbol, id) => {
      if (id === "default" /* Default */) return;
      const targetSymbol = target.get(id);
      if (!targetSymbol) {
        target.set(id, sourceSymbol);
        if (lookupTable && exportNode) {
          lookupTable.set(id, {
            specifierText: getTextOfNode(exportNode.moduleSpecifier)
          });
        }
      } else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
        const collisionTracker = lookupTable.get(id);
        if (!collisionTracker.exportsWithDuplicate) {
          collisionTracker.exportsWithDuplicate = [exportNode];
        } else {
          collisionTracker.exportsWithDuplicate.push(exportNode);
        }
      }
    });
  }
  function getExportsOfModuleWorker(moduleSymbol) {
    const visitedSymbols = [];
    let typeOnlyExportStarMap;
    const nonTypeOnlyNames = /* @__PURE__ */ new Set();
    moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
    const exports2 = visit(moduleSymbol) || emptySymbols;
    if (typeOnlyExportStarMap) {
      nonTypeOnlyNames.forEach((name) => typeOnlyExportStarMap.delete(name));
    }
    return {
      exports: exports2,
      typeOnlyExportStarMap
    };
    function visit(symbol, exportStar, isTypeOnly) {
      if (!isTypeOnly && (symbol == null ? void 0 : symbol.exports)) {
        symbol.exports.forEach((_, name) => nonTypeOnlyNames.add(name));
      }
      if (!(symbol && symbol.exports && pushIfUnique(visitedSymbols, symbol))) {
        return;
      }
      const symbols = new Map(symbol.exports);
      const exportStars = symbol.exports.get("__export" /* ExportStar */);
      if (exportStars) {
        const nestedSymbols = createSymbolTable();
        const lookupTable = /* @__PURE__ */ new Map();
        if (exportStars.declarations) {
          for (const node of exportStars.declarations) {
            const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
            const exportedSymbols = visit(resolvedModule, node, isTypeOnly || node.isTypeOnly);
            extendExportSymbols(
              nestedSymbols,
              exportedSymbols,
              lookupTable,
              node
            );
          }
        }
        lookupTable.forEach(({ exportsWithDuplicate }, id) => {
          if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
            return;
          }
          for (const node of exportsWithDuplicate) {
            diagnostics.add(createDiagnosticForNode(
              node,
              Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity,
              lookupTable.get(id).specifierText,
              unescapeLeadingUnderscores(id)
            ));
          }
        });
        extendExportSymbols(symbols, nestedSymbols);
      }
      if (exportStar == null ? void 0 : exportStar.isTypeOnly) {
        typeOnlyExportStarMap ?? (typeOnlyExportStarMap = /* @__PURE__ */ new Map());
        symbols.forEach(
          (_, escapedName) => typeOnlyExportStarMap.set(
            escapedName,
            exportStar
          )
        );
      }
      return symbols;
    }
  }
  function getMergedSymbol(symbol) {
    let merged;
    return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
  }
  function getSymbolOfDeclaration(node) {
    return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
  }
  function getSymbolOfNode(node) {
    return canHaveSymbol(node) ? getSymbolOfDeclaration(node) : void 0;
  }
  function getParentOfSymbol(symbol) {
    return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
  }
  function getFunctionExpressionParentSymbolOrSymbol(symbol) {
    var _a, _b;
    return ((_a = symbol.valueDeclaration) == null ? void 0 : _a.kind) === 219 /* ArrowFunction */ || ((_b = symbol.valueDeclaration) == null ? void 0 : _b.kind) === 218 /* FunctionExpression */ ? getSymbolOfNode(symbol.valueDeclaration.parent) || symbol : symbol;
  }
  function getAlternativeContainingModules(symbol, enclosingDeclaration) {
    const containingFile = getSourceFileOfNode(enclosingDeclaration);
    const id = getNodeId(containingFile);
    const links = getSymbolLinks(symbol);
    let results;
    if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
      return results;
    }
    if (containingFile && containingFile.imports) {
      for (const importRef of containingFile.imports) {
        if (nodeIsSynthesized(importRef)) continue;
        const resolvedModule = resolveExternalModuleName(
          enclosingDeclaration,
          importRef,
          /*ignoreErrors*/
          true
        );
        if (!resolvedModule) continue;
        const ref = getAliasForSymbolInContainer(resolvedModule, symbol);
        if (!ref) continue;
        results = append(results, resolvedModule);
      }
      if (length(results)) {
        (links.extendedContainersByFile || (links.extendedContainersByFile = /* @__PURE__ */ new Map())).set(id, results);
        return results;
      }
    }
    if (links.extendedContainers) {
      return links.extendedContainers;
    }
    const otherFiles = host.getSourceFiles();
    for (const file of otherFiles) {
      if (!isExternalModule(file)) continue;
      const sym = getSymbolOfDeclaration(file);
      const ref = getAliasForSymbolInContainer(sym, symbol);
      if (!ref) continue;
      results = append(results, sym);
    }
    return links.extendedContainers = results || emptyArray;
  }
  function getContainersOfSymbol(symbol, enclosingDeclaration, meaning) {
    const container = getParentOfSymbol(symbol);
    if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
      return getWithAlternativeContainers(container);
    }
    const candidates = mapDefined(symbol.declarations, (d) => {
      if (!isAmbientModule(d) && d.parent) {
        if (hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
          return getSymbolOfDeclaration(d.parent);
        }
        if (isModuleBlock(d.parent) && d.parent.parent && resolveExternalModuleSymbol(getSymbolOfDeclaration(d.parent.parent)) === symbol) {
          return getSymbolOfDeclaration(d.parent.parent);
        }
      }
      if (isClassExpression(d) && isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 64 /* EqualsToken */ && isAccessExpression(d.parent.left) && isEntityNameExpression(d.parent.left.expression)) {
        if (isModuleExportsAccessExpression(d.parent.left) || isExportsIdentifier(d.parent.left.expression)) {
          return getSymbolOfDeclaration(getSourceFileOfNode(d));
        }
        checkExpressionCached(d.parent.left.expression);
        return getNodeLinks(d.parent.left.expression).resolvedSymbol;
      }
    });
    if (!length(candidates)) {
      return void 0;
    }
    const containers = mapDefined(candidates, (candidate) => getAliasForSymbolInContainer(candidate, symbol) ? candidate : void 0);
    let bestContainers = [];
    let alternativeContainers = [];
    for (const container2 of containers) {
      const [bestMatch, ...rest] = getWithAlternativeContainers(container2);
      bestContainers = append(bestContainers, bestMatch);
      alternativeContainers = addRange(alternativeContainers, rest);
    }
    return concatenate(bestContainers, alternativeContainers);
    function getWithAlternativeContainers(container2) {
      const additionalContainers = mapDefined(container2.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
      const reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
      const objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container2, meaning);
      if (enclosingDeclaration && container2.flags & getQualifiedLeftMeaning(meaning) && getAccessibleSymbolChain(
        container2,
        enclosingDeclaration,
        1920 /* Namespace */,
        /*useOnlyExternalAliasing*/
        false
      )) {
        return append(concatenate(concatenate([container2], additionalContainers), reexportContainers), objectLiteralContainer);
      }
      const firstVariableMatch = !(container2.flags & getQualifiedLeftMeaning(meaning)) && container2.flags & 788968 /* Type */ && getDeclaredTypeOfSymbol(container2).flags & 524288 /* Object */ && meaning === 111551 /* Value */ ? forEachSymbolTableInScope(enclosingDeclaration, (t) => {
        return forEachEntry(t, (s) => {
          if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container2)) {
            return s;
          }
        });
      }) : void 0;
      let res = firstVariableMatch ? [firstVariableMatch, ...additionalContainers, container2] : [...additionalContainers, container2];
      res = append(res, objectLiteralContainer);
      res = addRange(res, reexportContainers);
      return res;
    }
    function fileSymbolIfFileSymbolExportEqualsContainer(d) {
      return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
    }
  }
  function getVariableDeclarationOfObjectLiteral(symbol, meaning) {
    const firstDecl = !!length(symbol.declarations) && first(symbol.declarations);
    if (meaning & 111551 /* Value */ && firstDecl && firstDecl.parent && isVariableDeclaration(firstDecl.parent)) {
      if (isObjectLiteralExpression(firstDecl) && firstDecl === firstDecl.parent.initializer || isTypeLiteralNode(firstDecl) && firstDecl === firstDecl.parent.type) {
        return getSymbolOfDeclaration(firstDecl.parent);
      }
    }
  }
  function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
    const fileSymbol = getExternalModuleContainer(d);
    const exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
    return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : void 0;
  }
  function getAliasForSymbolInContainer(container, symbol) {
    if (container === getParentOfSymbol(symbol)) {
      return symbol;
    }
    const exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
    if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
      return container;
    }
    const exports2 = getExportsOfSymbol(container);
    const quick = exports2.get(symbol.escapedName);
    if (quick && getSymbolIfSameReference(quick, symbol)) {
      return quick;
    }
    return forEachEntry(exports2, (exported) => {
      if (getSymbolIfSameReference(exported, symbol)) {
        return exported;
      }
    });
  }
  function getSymbolIfSameReference(s1, s2) {
    if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
      return s1;
    }
  }
  function getExportSymbolOfValueSymbolIfExported(symbol) {
    return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 && symbol.exportSymbol || symbol);
  }
  function symbolIsValue(symbol, includeTypeOnlyMembers) {
    return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getSymbolFlags(symbol, !includeTypeOnlyMembers) & 111551 /* Value */);
  }
  function createType(flags) {
    var _a;
    const result = new Type7(checker, flags);
    typeCount++;
    result.id = typeCount;
    (_a = tracing) == null ? void 0 : _a.recordType(result);
    return result;
  }
  function createTypeWithSymbol(flags, symbol) {
    const result = createType(flags);
    result.symbol = symbol;
    return result;
  }
  function createOriginType(flags) {
    return new Type7(checker, flags);
  }
  function createIntrinsicType(kind, intrinsicName, objectFlags = 0 /* None */, debugIntrinsicName) {
    checkIntrinsicName(intrinsicName, debugIntrinsicName);
    const type = createType(kind);
    type.intrinsicName = intrinsicName;
    type.debugIntrinsicName = debugIntrinsicName;
    type.objectFlags = objectFlags | 524288 /* CouldContainTypeVariablesComputed */ | 2097152 /* IsGenericTypeComputed */ | 33554432 /* IsUnknownLikeUnionComputed */ | 16777216 /* IsNeverIntersectionComputed */;
    return type;
  }
  function checkIntrinsicName(name, debug) {
    const key = `${name},${debug ?? ""}`;
    if (seenIntrinsicNames.has(key)) {
      Debug.fail(`Duplicate intrinsic type name ${name}${debug ? ` (${debug})` : ""}; you may need to pass a name to createIntrinsicType.`);
    }
    seenIntrinsicNames.add(key);
  }
  function createObjectType(objectFlags, symbol) {
    const type = createTypeWithSymbol(524288 /* Object */, symbol);
    type.objectFlags = objectFlags;
    type.members = void 0;
    type.properties = void 0;
    type.callSignatures = void 0;
    type.constructSignatures = void 0;
    type.indexInfos = void 0;
    return type;
  }
  function createTypeofType() {
    return getUnionType(arrayFrom(typeofNEFacts.keys(), getStringLiteralType));
  }
  function createTypeParameter(symbol) {
    return createTypeWithSymbol(262144 /* TypeParameter */, symbol);
  }
  function isReservedMemberName(name) {
    return name.charCodeAt(0) === 95 /* _ */ && name.charCodeAt(1) === 95 /* _ */ && name.charCodeAt(2) !== 95 /* _ */ && name.charCodeAt(2) !== 64 /* at */ && name.charCodeAt(2) !== 35 /* hash */;
  }
  function getNamedMembers(members) {
    let result;
    members.forEach((symbol, id) => {
      if (isNamedMember(symbol, id)) {
        (result || (result = [])).push(symbol);
      }
    });
    return result || emptyArray;
  }
  function isNamedMember(member, escapedName) {
    return !isReservedMemberName(escapedName) && symbolIsValue(member);
  }
  function getNamedOrIndexSignatureMembers(members) {
    const result = getNamedMembers(members);
    const index = getIndexSymbolFromSymbolTable(members);
    return index ? concatenate(result, [index]) : result;
  }
  function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos) {
    const resolved = type;
    resolved.members = members;
    resolved.properties = emptyArray;
    resolved.callSignatures = callSignatures;
    resolved.constructSignatures = constructSignatures;
    resolved.indexInfos = indexInfos;
    if (members !== emptySymbols) resolved.properties = getNamedMembers(members);
    return resolved;
  }
  function createAnonymousType(symbol, members, callSignatures, constructSignatures, indexInfos) {
    return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, indexInfos);
  }
  function getResolvedTypeWithoutAbstractConstructSignatures(type) {
    if (type.constructSignatures.length === 0) return type;
    if (type.objectTypeWithoutAbstractConstructSignatures) return type.objectTypeWithoutAbstractConstructSignatures;
    const constructSignatures = filter(type.constructSignatures, (signature) => !(signature.flags & 4 /* Abstract */));
    if (type.constructSignatures === constructSignatures) return type;
    const typeCopy = createAnonymousType(
      type.symbol,
      type.members,
      type.callSignatures,
      some(constructSignatures) ? constructSignatures : emptyArray,
      type.indexInfos
    );
    type.objectTypeWithoutAbstractConstructSignatures = typeCopy;
    typeCopy.objectTypeWithoutAbstractConstructSignatures = typeCopy;
    return typeCopy;
  }
  function forEachSymbolTableInScope(enclosingDeclaration, callback) {
    let result;
    for (let location = enclosingDeclaration; location; location = location.parent) {
      if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) {
        if (result = callback(
          location.locals,
          /*ignoreQualification*/
          void 0,
          /*isLocalNameLookup*/
          true,
          location
        )) {
          return result;
        }
      }
      switch (location.kind) {
        case 307 /* SourceFile */:
          if (!isExternalOrCommonJsModule(location)) {
            break;
          }
        // falls through
        case 267 /* ModuleDeclaration */:
          const sym = getSymbolOfDeclaration(location);
          if (result = callback(
            (sym == null ? void 0 : sym.exports) || emptySymbols,
            /*ignoreQualification*/
            void 0,
            /*isLocalNameLookup*/
            true,
            location
          )) {
            return result;
          }
          break;
        case 263 /* ClassDeclaration */:
        case 231 /* ClassExpression */:
        case 264 /* InterfaceDeclaration */:
          let table;
          (getSymbolOfDeclaration(location).members || emptySymbols).forEach((memberSymbol, key) => {
            if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
              (table || (table = createSymbolTable())).set(key, memberSymbol);
            }
          });
          if (table && (result = callback(
            table,
            /*ignoreQualification*/
            void 0,
            /*isLocalNameLookup*/
            false,
            location
          ))) {
            return result;
          }
          break;
      }
    }
    return callback(
      globals,
      /*ignoreQualification*/
      void 0,
      /*isLocalNameLookup*/
      true
    );
  }
  function getQualifiedLeftMeaning(rightMeaning) {
    return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
  }
  function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap = /* @__PURE__ */ new Map()) {
    if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
      return void 0;
    }
    const links = getSymbolLinks(symbol);
    const cache = links.accessibleChainCache || (links.accessibleChainCache = /* @__PURE__ */ new Map());
    const firstRelevantLocation = forEachSymbolTableInScope(enclosingDeclaration, (_, __, ___, node) => node);
    const key = `${useOnlyExternalAliasing ? 0 : 1}|${firstRelevantLocation ? getNodeId(firstRelevantLocation) : 0}|${meaning}`;
    if (cache.has(key)) {
      return cache.get(key);
    }
    const id = getSymbolId(symbol);
    let visitedSymbolTables = visitedSymbolTablesMap.get(id);
    if (!visitedSymbolTables) {
      visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
    }
    const result = forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
    cache.set(key, result);
    return result;
    function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) {
      if (!pushIfUnique(visitedSymbolTables, symbols)) {
        return void 0;
      }
      const result2 = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup);
      visitedSymbolTables.pop();
      return result2;
    }
    function canQualifySymbol(symbolFromSymbolTable, meaning2) {
      return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning2) || // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
      !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning2), useOnlyExternalAliasing, visitedSymbolTablesMap);
    }
    function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
      return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) && // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
      // and if symbolFromSymbolTable or alias resolution matches the symbol,
      // check the symbol can be qualified, it is only then this symbol is accessible
      !some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
    }
    function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) {
      if (isAccessible(
        symbols.get(symbol.escapedName),
        /*resolvedAliasSymbol*/
        void 0,
        ignoreQualification
      )) {
        return [symbol];
      }
      const result2 = forEachEntry(symbols, (symbolFromSymbolTable) => {
        if (symbolFromSymbolTable.flags & 2097152 /* Alias */ && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && isExternalModule(getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || some(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) && (isLocalNameLookup ? !some(symbolFromSymbolTable.declarations, isNamespaceReexportDeclaration) : true) && (ignoreQualification || !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */))) {
          const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
          const candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
          if (candidate) {
            return candidate;
          }
        }
        if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
          if (isAccessible(
            getMergedSymbol(symbolFromSymbolTable.exportSymbol),
            /*resolvedAliasSymbol*/
            void 0,
            ignoreQualification
          )) {
            return [symbol];
          }
        }
      });
      return result2 || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : void 0);
    }
    function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
      if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
        return [symbolFromSymbolTable];
      }
      const candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
      const accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(
        candidateTable,
        /*ignoreQualification*/
        true
      );
      if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
        return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
      }
    }
  }
  function needsQualification(symbol, enclosingDeclaration, meaning) {
    let qualify = false;
    forEachSymbolTableInScope(enclosingDeclaration, (symbolTable) => {
      let symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
      if (!symbolFromSymbolTable) {
        return false;
      }
      if (symbolFromSymbolTable === symbol) {
        return true;
      }
      const shouldResolveAlias = symbolFromSymbolTable.flags & 2097152 /* Alias */ && !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */);
      symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
      const flags = shouldResolveAlias ? getSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags;
      if (flags & meaning) {
        qualify = true;
        return true;
      }
      return false;
    });
    return qualify;
  }
  function isPropertyOrMethodDeclarationSymbol(symbol) {
    if (symbol.declarations && symbol.declarations.length) {
      for (const declaration of symbol.declarations) {
        switch (declaration.kind) {
          case 172 /* PropertyDeclaration */:
          case 174 /* MethodDeclaration */:
          case 177 /* GetAccessor */:
          case 178 /* SetAccessor */:
            continue;
          default:
            return false;
        }
      }
      return true;
    }
    return false;
  }
  function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
    const access = isSymbolAccessibleWorker(
      typeSymbol,
      enclosingDeclaration,
      788968 /* Type */,
      /*shouldComputeAliasesToMakeVisible*/
      false,
      /*allowModules*/
      true
    );
    return access.accessibility === 0 /* Accessible */;
  }
  function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
    const access = isSymbolAccessibleWorker(
      typeSymbol,
      enclosingDeclaration,
      111551 /* Value */,
      /*shouldComputeAliasesToMakeVisible*/
      false,
      /*allowModules*/
      true
    );
    return access.accessibility === 0 /* Accessible */;
  }
  function isSymbolAccessibleByFlags(typeSymbol, enclosingDeclaration, flags) {
    const access = isSymbolAccessibleWorker(
      typeSymbol,
      enclosingDeclaration,
      flags,
      /*shouldComputeAliasesToMakeVisible*/
      false,
      /*allowModules*/
      false
    );
    return access.accessibility === 0 /* Accessible */;
  }
  function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
    if (!length(symbols)) return;
    let hadAccessibleChain;
    let earlyModuleBail = false;
    for (const symbol of symbols) {
      const accessibleSymbolChain = getAccessibleSymbolChain(
        symbol,
        enclosingDeclaration,
        meaning,
        /*useOnlyExternalAliasing*/
        false
      );
      if (accessibleSymbolChain) {
        hadAccessibleChain = symbol;
        const hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
        if (hasAccessibleDeclarations) {
          return hasAccessibleDeclarations;
        }
      }
      if (allowModules) {
        if (some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
          if (shouldComputeAliasesToMakeVisible) {
            earlyModuleBail = true;
            continue;
          }
          return {
            accessibility: 0 /* Accessible */
          };
        }
      }
      const containers = getContainersOfSymbol(symbol, enclosingDeclaration, meaning);
      const parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible, allowModules);
      if (parentResult) {
        return parentResult;
      }
    }
    if (earlyModuleBail) {
      return {
        accessibility: 0 /* Accessible */
      };
    }
    if (hadAccessibleChain) {
      return {
        accessibility: 1 /* NotAccessible */,
        errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
        errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : void 0
      };
    }
  }
  function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
    return isSymbolAccessibleWorker(
      symbol,
      enclosingDeclaration,
      meaning,
      shouldComputeAliasesToMakeVisible,
      /*allowModules*/
      true
    );
  }
  function isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
    if (symbol && enclosingDeclaration) {
      const result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible, allowModules);
      if (result) {
        return result;
      }
      const symbolExternalModule = forEach(symbol.declarations, getExternalModuleContainer);
      if (symbolExternalModule) {
        const enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
        if (symbolExternalModule !== enclosingExternalModule) {
          return {
            accessibility: 2 /* CannotBeNamed */,
            errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
            errorModuleName: symbolToString(symbolExternalModule),
            errorNode: isInJSFile(enclosingDeclaration) ? enclosingDeclaration : void 0
          };
        }
      }
      return {
        accessibility: 1 /* NotAccessible */,
        errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning)
      };
    }
    return { accessibility: 0 /* Accessible */ };
  }
  function getExternalModuleContainer(declaration) {
    const node = findAncestor(declaration, hasExternalModuleSymbol);
    return node && getSymbolOfDeclaration(node);
  }
  function hasExternalModuleSymbol(declaration) {
    return isAmbientModule(declaration) || declaration.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(declaration);
  }
  function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
    return isModuleWithStringLiteralName(declaration) || declaration.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(declaration);
  }
  function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
    let aliasesToMakeVisible;
    if (!every(filter(symbol.declarations, (d) => d.kind !== 80 /* Identifier */), getIsDeclarationVisible)) {
      return void 0;
    }
    return { accessibility: 0 /* Accessible */, aliasesToMakeVisible };
    function getIsDeclarationVisible(declaration) {
      var _a, _b;
      if (!isDeclarationVisible(declaration)) {
        const anyImportSyntax = getAnyImportSyntax(declaration);
        if (anyImportSyntax && !hasSyntacticModifier(anyImportSyntax, 32 /* Export */) && // import clause without export
        isDeclarationVisible(anyImportSyntax.parent)) {
          return addVisibleAlias(declaration, anyImportSyntax);
        } else if (isVariableDeclaration(declaration) && isVariableStatement(declaration.parent.parent) && !hasSyntacticModifier(declaration.parent.parent, 32 /* Export */) && // unexported variable statement
        isDeclarationVisible(declaration.parent.parent.parent)) {
          return addVisibleAlias(declaration, declaration.parent.parent);
        } else if (isLateVisibilityPaintedStatement(declaration) && !hasSyntacticModifier(declaration, 32 /* Export */) && isDeclarationVisible(declaration.parent)) {
          return addVisibleAlias(declaration, declaration);
        } else if (isBindingElement(declaration)) {
          if (symbol.flags & 2097152 /* Alias */ && isInJSFile(declaration) && ((_a = declaration.parent) == null ? void 0 : _a.parent) && isVariableDeclaration(declaration.parent.parent) && ((_b = declaration.parent.parent.parent) == null ? void 0 : _b.parent) && isVariableStatement(declaration.parent.parent.parent.parent) && !hasSyntacticModifier(declaration.parent.parent.parent.parent, 32 /* Export */) && declaration.parent.parent.parent.parent.parent && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) {
            return addVisibleAlias(declaration, declaration.parent.parent.parent.parent);
          } else if (symbol.flags & 2 /* BlockScopedVariable */) {
            const variableStatement = findAncestor(declaration, isVariableStatement);
            if (hasSyntacticModifier(variableStatement, 32 /* Export */)) {
              return true;
            }
            if (!isDeclarationVisible(variableStatement.parent)) {
              return false;
            }
            return addVisibleAlias(declaration, variableStatement);
          }
        }
        return false;
      }
      return true;
    }
    function addVisibleAlias(declaration, aliasingStatement) {
      if (shouldComputeAliasToMakeVisible) {
        getNodeLinks(declaration).isVisible = true;
        aliasesToMakeVisible = appendIfUnique(aliasesToMakeVisible, aliasingStatement);
      }
      return true;
    }
  }
  function getMeaningOfEntityNameReference(entityName) {
    let meaning;
    if (entityName.parent.kind === 186 /* TypeQuery */ || entityName.parent.kind === 233 /* ExpressionWithTypeArguments */ && !isPartOfTypeNode(entityName.parent) || entityName.parent.kind === 167 /* ComputedPropertyName */ || entityName.parent.kind === 182 /* TypePredicate */ && entityName.parent.parameterName === entityName) {
      meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
    } else if (entityName.kind === 166 /* QualifiedName */ || entityName.kind === 211 /* PropertyAccessExpression */ || entityName.parent.kind === 271 /* ImportEqualsDeclaration */ || entityName.parent.kind === 166 /* QualifiedName */ && entityName.parent.left === entityName || entityName.parent.kind === 211 /* PropertyAccessExpression */ && entityName.parent.expression === entityName || entityName.parent.kind === 212 /* ElementAccessExpression */ && entityName.parent.expression === entityName) {
      meaning = 1920 /* Namespace */;
    } else {
      meaning = 788968 /* Type */;
    }
    return meaning;
  }
  function isEntityNameVisible(entityName, enclosingDeclaration, shouldComputeAliasToMakeVisible = true) {
    const meaning = getMeaningOfEntityNameReference(entityName);
    const firstIdentifier = getFirstIdentifier(entityName);
    const symbol = resolveName(
      enclosingDeclaration,
      firstIdentifier.escapedText,
      meaning,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false
    );
    if (symbol && symbol.flags & 262144 /* TypeParameter */ && meaning & 788968 /* Type */) {
      return { accessibility: 0 /* Accessible */ };
    }
    if (!symbol && isThisIdentifier(firstIdentifier) && isSymbolAccessible(
      getSymbolOfDeclaration(getThisContainer(
        firstIdentifier,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      )),
      firstIdentifier,
      meaning,
      /*shouldComputeAliasesToMakeVisible*/
      false
    ).accessibility === 0 /* Accessible */) {
      return { accessibility: 0 /* Accessible */ };
    }
    if (!symbol) {
      return {
        accessibility: 3 /* NotResolved */,
        errorSymbolName: getTextOfNode(firstIdentifier),
        errorNode: firstIdentifier
      };
    }
    return hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) || {
      accessibility: 1 /* NotAccessible */,
      errorSymbolName: getTextOfNode(firstIdentifier),
      errorNode: firstIdentifier
    };
  }
  function symbolToString(symbol, enclosingDeclaration, meaning, flags = 4 /* AllowAnyNodeKind */, writer) {
    let nodeFlags = 70221824 /* IgnoreErrors */;
    let internalNodeFlags = 0 /* None */;
    if (flags & 2 /* UseOnlyExternalAliasing */) {
      nodeFlags |= 128 /* UseOnlyExternalAliasing */;
    }
    if (flags & 1 /* WriteTypeParametersOrArguments */) {
      nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
    }
    if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
      nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
    }
    if (flags & 32 /* DoNotIncludeSymbolChain */) {
      internalNodeFlags |= 4 /* DoNotIncludeSymbolChain */;
    }
    if (flags & 16 /* WriteComputedProps */) {
      internalNodeFlags |= 1 /* WriteComputedProps */;
    }
    const builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToNode : nodeBuilder.symbolToEntityName;
    return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker);
    function symbolToStringWorker(writer2) {
      const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags, internalNodeFlags);
      const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 307 /* SourceFile */ ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments();
      const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
      printer.writeNode(
        4 /* Unspecified */,
        entity,
        /*sourceFile*/
        sourceFile,
        writer2
      );
      return writer2;
    }
  }
  function signatureToString(signature, enclosingDeclaration, flags = 0 /* None */, kind, writer) {
    return writer ? signatureToStringWorker(writer).getText() : usingSingleLineStringWriter(signatureToStringWorker);
    function signatureToStringWorker(writer2) {
      let sigOutput;
      if (flags & 262144 /* WriteArrowStyleSignature */) {
        sigOutput = kind === 1 /* Construct */ ? 185 /* ConstructorType */ : 184 /* FunctionType */;
      } else {
        sigOutput = kind === 1 /* Construct */ ? 180 /* ConstructSignature */ : 179 /* CallSignature */;
      }
      const sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
      const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon();
      const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
      printer.writeNode(
        4 /* Unspecified */,
        sig,
        /*sourceFile*/
        sourceFile,
        getTrailingSemicolonDeferringWriter(writer2)
      );
      return writer2;
    }
  }
  function typeToString(type, enclosingDeclaration, flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer = createTextWriter("")) {
    const noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
    const typeNode = nodeBuilder.typeToTypeNode(
      type,
      enclosingDeclaration,
      toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0 /* None */),
      /*internalFlags*/
      void 0
    );
    if (typeNode === void 0) return Debug.fail("should always get typenode");
    const printer = type !== unresolvedType ? createPrinterWithRemoveComments() : createPrinterWithDefaults();
    const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
    printer.writeNode(
      4 /* Unspecified */,
      typeNode,
      /*sourceFile*/
      sourceFile,
      writer
    );
    const result = writer.getText();
    const maxLength = noTruncation ? noTruncationMaximumTruncationLength * 2 : defaultMaximumTruncationLength * 2;
    if (maxLength && result && result.length >= maxLength) {
      return result.substr(0, maxLength - "...".length) + "...";
    }
    return result;
  }
  function getTypeNamesForErrorDisplay(left, right) {
    let leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
    let rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
    if (leftStr === rightStr) {
      leftStr = getTypeNameForErrorDisplay(left);
      rightStr = getTypeNameForErrorDisplay(right);
    }
    return [leftStr, rightStr];
  }
  function getTypeNameForErrorDisplay(type) {
    return typeToString(
      type,
      /*enclosingDeclaration*/
      void 0,
      64 /* UseFullyQualifiedType */
    );
  }
  function symbolValueDeclarationIsContextSensitive(symbol) {
    return symbol && !!symbol.valueDeclaration && isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
  }
  function toNodeBuilderFlags(flags = 0 /* None */) {
    return flags & 848330095 /* NodeBuilderFlagsMask */;
  }
  function isClassInstanceSide(type) {
    return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(type.flags & 524288 /* Object */) && !!(getObjectFlags(type) & 16777216 /* IsClassInstanceClone */));
  }
  function getTypeFromTypeNodeWithoutContext(node) {
    return getTypeFromTypeNode(node);
  }
  function createNodeBuilder() {
    const syntacticBuilderResolver = {
      evaluateEntityNameExpression,
      isExpandoFunctionDeclaration,
      hasLateBindableName,
      shouldRemoveDeclaration(context, node) {
        return !(context.internalFlags & 8 /* AllowUnresolvedNames */ && isEntityNameExpression(node.name.expression) && checkComputedPropertyName(node.name).flags & 1 /* Any */);
      },
      createRecoveryBoundary(context) {
        return createRecoveryBoundary(context);
      },
      isDefinitelyReferenceToGlobalSymbolObject,
      getAllAccessorDeclarations: getAllAccessorDeclarationsForDeclaration,
      requiresAddingImplicitUndefined(declaration, symbol, enclosingDeclaration) {
        var _a;
        switch (declaration.kind) {
          case 172 /* PropertyDeclaration */:
          case 171 /* PropertySignature */:
          case 348 /* JSDocPropertyTag */:
            symbol ?? (symbol = getSymbolOfDeclaration(declaration));
            const type = getTypeOfSymbol(symbol);
            return !!(symbol.flags & 4 /* Property */ && symbol.flags & 16777216 /* Optional */ && isOptionalDeclaration(declaration) && ((_a = symbol.links) == null ? void 0 : _a.mappedType) && containsNonMissingUndefinedType(type));
          case 169 /* Parameter */:
          case 341 /* JSDocParameterTag */:
            return requiresAddingImplicitUndefined(declaration, enclosingDeclaration);
          default:
            Debug.assertNever(declaration);
        }
      },
      isOptionalParameter,
      isUndefinedIdentifierExpression(node) {
        Debug.assert(isExpressionNode(node));
        return getSymbolAtLocation(node) === undefinedSymbol;
      },
      isEntityNameVisible(context, entityName, shouldComputeAliasToMakeVisible) {
        return isEntityNameVisible(entityName, context.enclosingDeclaration, shouldComputeAliasToMakeVisible);
      },
      serializeExistingTypeNode(context, typeNode, addUndefined) {
        return serializeExistingTypeNode(context, typeNode, !!addUndefined);
      },
      serializeReturnTypeForSignature(syntacticContext, signatureDeclaration) {
        const context = syntacticContext;
        const signature = getSignatureFromDeclaration(signatureDeclaration);
        const returnType = context.enclosingSymbolTypes.get(getSymbolId(getSymbolOfDeclaration(signatureDeclaration))) ?? instantiateType(getReturnTypeOfSignature(signature), context.mapper);
        return serializeInferredReturnTypeForSignature(context, signature, returnType);
      },
      serializeTypeOfExpression(syntacticContext, expr) {
        const context = syntacticContext;
        const type = instantiateType(getWidenedType(getRegularTypeOfExpression(expr)), context.mapper);
        return typeToTypeNodeHelper(type, context);
      },
      serializeTypeOfDeclaration(syntacticContext, declaration, symbol) {
        var _a;
        const context = syntacticContext;
        symbol ?? (symbol = getSymbolOfDeclaration(declaration));
        let type = (_a = context.enclosingSymbolTypes) == null ? void 0 : _a.get(getSymbolId(symbol));
        if (type === void 0) {
          type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? instantiateType(getWidenedLiteralType(getTypeOfSymbol(symbol)), context.mapper) : errorType;
        }
        const addUndefinedForParameter = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration, context.enclosingDeclaration);
        if (addUndefinedForParameter) {
          type = getOptionalType(type);
        }
        return serializeInferredTypeForDeclaration(symbol, context, type);
      },
      serializeNameOfParameter(context, parameter) {
        return parameterToParameterDeclarationName(getSymbolOfDeclaration(parameter), parameter, context);
      },
      serializeEntityName(syntacticContext, node) {
        const context = syntacticContext;
        const symbol = getSymbolAtLocation(
          node,
          /*ignoreErrors*/
          true
        );
        if (!symbol) return void 0;
        if (!isValueSymbolAccessible(symbol, context.enclosingDeclaration)) return void 0;
        return symbolToExpression(symbol, context, 111551 /* Value */ | 1048576 /* ExportValue */);
      },
      serializeTypeName(context, node, isTypeOf, typeArguments) {
        return serializeTypeName(context, node, isTypeOf, typeArguments);
      },
      getJsDocPropertyOverride(syntacticContext, jsDocTypeLiteral, jsDocProperty) {
        const context = syntacticContext;
        const name = isIdentifier(jsDocProperty.name) ? jsDocProperty.name : jsDocProperty.name.right;
        const typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode2(context, jsDocTypeLiteral), name.escapedText);
        const overrideTypeNode = typeViaParent && jsDocProperty.typeExpression && getTypeFromTypeNode2(context, jsDocProperty.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : void 0;
        return overrideTypeNode;
      },
      enterNewScope(context, node) {
        if (isFunctionLike(node) || isJSDocSignature(node)) {
          const signature = getSignatureFromDeclaration(node);
          const expandedParams = getExpandedParameters(
            signature,
            /*skipUnionExpanding*/
            true
          )[0];
          return enterNewScope(context, node, expandedParams, signature.typeParameters);
        } else {
          const typeParameters = isConditionalTypeNode(node) ? getInferTypeParameters(node) : [getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))];
          return enterNewScope(
            context,
            node,
            /*expandedParams*/
            void 0,
            typeParameters
          );
        }
      },
      markNodeReuse(context, range, location) {
        return setTextRange2(context, range, location);
      },
      trackExistingEntityName(context, node) {
        return trackExistingEntityName(node, context);
      },
      trackComputedName(context, accessExpression) {
        trackComputedName(accessExpression, context.enclosingDeclaration, context);
      },
      getModuleSpecifierOverride(syntacticContext, parent, lit) {
        const context = syntacticContext;
        if (context.bundled || context.enclosingFile !== getSourceFileOfNode(lit)) {
          let name = lit.text;
          const nodeSymbol = getNodeLinks(parent).resolvedSymbol;
          const meaning = parent.isTypeOf ? 111551 /* Value */ : 788968 /* Type */;
          const parentSymbol = nodeSymbol && isSymbolAccessible(
            nodeSymbol,
            context.enclosingDeclaration,
            meaning,
            /*shouldComputeAliasesToMakeVisible*/
            false
          ).accessibility === 0 /* Accessible */ && lookupSymbolChain(
            nodeSymbol,
            context,
            meaning,
            /*yieldModuleSymbol*/
            true
          )[0];
          if (parentSymbol && isExternalModuleSymbol(parentSymbol)) {
            name = getSpecifierForModuleSymbol(parentSymbol, context);
          } else {
            const targetFile = getExternalModuleFileFromDeclaration(parent);
            if (targetFile) {
              name = getSpecifierForModuleSymbol(targetFile.symbol, context);
            }
          }
          if (name.includes("/node_modules/")) {
            context.encounteredError = true;
            if (context.tracker.reportLikelyUnsafeImportRequiredError) {
              context.tracker.reportLikelyUnsafeImportRequiredError(name);
            }
          }
          return name;
        }
      },
      canReuseTypeNode(context, typeNode) {
        return canReuseTypeNode(context, typeNode);
      },
      canReuseTypeNodeAnnotation(syntacticContext, node, existing, symbol, requiresAddingUndefined) {
        var _a;
        const context = syntacticContext;
        if (context.enclosingDeclaration === void 0) return false;
        symbol ?? (symbol = getSymbolOfDeclaration(node));
        let type = (_a = context.enclosingSymbolTypes) == null ? void 0 : _a.get(getSymbolId(symbol));
        if (type === void 0) {
          if (symbol.flags & 98304 /* Accessor */) {
            type = node.kind === 178 /* SetAccessor */ ? getWriteTypeOfSymbol(symbol) : getTypeOfAccessors(symbol);
          } else if (isValueSignatureDeclaration(node)) {
            type = getReturnTypeOfSignature(getSignatureFromDeclaration(node));
          } else {
            type = getTypeOfSymbol(symbol);
          }
        }
        let annotationType = getTypeFromTypeNodeWithoutContext(existing);
        if (isErrorType(annotationType)) {
          return true;
        }
        if (requiresAddingUndefined && annotationType) {
          annotationType = addOptionality(annotationType, !isParameter(node));
        }
        return !!annotationType && typeNodeIsEquivalentToType(node, type, annotationType) && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type);
      }
    };
    return {
      syntacticBuilderResolver,
      typeToTypeNode: (type, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeToTypeNodeHelper(type, context)),
      typePredicateToTypePredicateNode: (typePredicate, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typePredicateToTypePredicateNodeHelper(typePredicate, context)),
      serializeTypeForExpression: (expr, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeTypeOfExpression(expr, context)),
      serializeTypeForDeclaration: (declaration, symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeTypeOfDeclaration(declaration, symbol, context)),
      serializeReturnTypeForSignature: (signature, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeReturnTypeForSignature(signature, getSymbolOfDeclaration(signature), context)),
      indexInfoToIndexSignatureDeclaration: (indexInfo, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => indexInfoToIndexSignatureDeclarationHelper(
        indexInfo,
        context,
        /*typeNode*/
        void 0
      )),
      signatureToSignatureDeclaration: (signature, kind, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => signatureToSignatureDeclarationHelper(signature, kind, context)),
      symbolToEntityName: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToName(
        symbol,
        context,
        meaning,
        /*expectsIdentifier*/
        false
      )),
      symbolToExpression: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToExpression(symbol, context, meaning)),
      symbolToTypeParameterDeclarations: (symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeParametersToTypeParameterDeclarations(symbol, context)),
      symbolToParameterDeclaration: (symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToParameterDeclaration(symbol, context)),
      typeParameterToDeclaration: (parameter, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeParameterToDeclaration(parameter, context)),
      symbolTableToDeclarationStatements: (symbolTable, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolTableToDeclarationStatements(symbolTable, context)),
      symbolToNode: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToNode(symbol, context, meaning))
    };
    function getTypeFromTypeNode2(context, node, noMappedTypes) {
      const type = getTypeFromTypeNodeWithoutContext(node);
      if (!context.mapper) return type;
      const mappedType = instantiateType(type, context.mapper);
      return noMappedTypes && mappedType !== type ? void 0 : mappedType;
    }
    function setTextRange2(context, range, location) {
      if (!nodeIsSynthesized(range) || !(range.flags & 16 /* Synthesized */) || !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(getOriginalNode(range))) {
        range = factory.cloneNode(range);
      }
      if (range === location) return range;
      if (!location) {
        return range;
      }
      let original = range.original;
      while (original && original !== location) {
        original = original.original;
      }
      if (!original) {
        setOriginalNode(range, location);
      }
      if (context.enclosingFile && context.enclosingFile === getSourceFileOfNode(getOriginalNode(location))) {
        return setTextRange(range, location);
      }
      return range;
    }
    function symbolToNode(symbol, context, meaning) {
      if (context.internalFlags & 1 /* WriteComputedProps */) {
        if (symbol.valueDeclaration) {
          const name = getNameOfDeclaration(symbol.valueDeclaration);
          if (name && isComputedPropertyName(name)) return name;
        }
        const nameType = getSymbolLinks(symbol).nameType;
        if (nameType && nameType.flags & (1024 /* EnumLiteral */ | 8192 /* UniqueESSymbol */)) {
          context.enclosingDeclaration = nameType.symbol.valueDeclaration;
          return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, meaning));
        }
      }
      return symbolToExpression(symbol, context, meaning);
    }
    function withContext(enclosingDeclaration, flags, internalFlags, tracker, cb) {
      const moduleResolverHost = (tracker == null ? void 0 : tracker.trackSymbol) ? tracker.moduleResolverHost : (internalFlags || 0 /* None */) & 4 /* DoNotIncludeSymbolChain */ ? createBasicNodeBuilderModuleSpecifierResolutionHost(host) : void 0;
      const context = {
        enclosingDeclaration,
        enclosingFile: enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration),
        flags: flags || 0 /* None */,
        internalFlags: internalFlags || 0 /* None */,
        tracker: void 0,
        encounteredError: false,
        suppressReportInferenceFallback: false,
        reportedDiagnostic: false,
        visitedTypes: void 0,
        symbolDepth: void 0,
        inferTypeParameters: void 0,
        approximateLength: 0,
        trackedSymbols: void 0,
        bundled: !!compilerOptions.outFile && !!enclosingDeclaration && isExternalOrCommonJsModule(getSourceFileOfNode(enclosingDeclaration)),
        truncating: false,
        usedSymbolNames: void 0,
        remappedSymbolNames: void 0,
        remappedSymbolReferences: void 0,
        reverseMappedStack: void 0,
        mustCreateTypeParameterSymbolList: true,
        typeParameterSymbolList: void 0,
        mustCreateTypeParametersNamesLookups: true,
        typeParameterNames: void 0,
        typeParameterNamesByText: void 0,
        typeParameterNamesByTextNextNameCount: void 0,
        enclosingSymbolTypes: /* @__PURE__ */ new Map(),
        mapper: void 0
      };
      context.tracker = new SymbolTrackerImpl(context, tracker, moduleResolverHost);
      const resultingNode = cb(context);
      if (context.truncating && context.flags & 1 /* NoTruncation */) {
        context.tracker.reportTruncationError();
      }
      return context.encounteredError ? void 0 : resultingNode;
    }
    function addSymbolTypeToContext(context, symbol, type) {
      const id = getSymbolId(symbol);
      const oldType = context.enclosingSymbolTypes.get(id);
      context.enclosingSymbolTypes.set(id, type);
      return restore;
      function restore() {
        if (oldType) {
          context.enclosingSymbolTypes.set(id, oldType);
        } else {
          context.enclosingSymbolTypes.delete(id);
        }
      }
    }
    function saveRestoreFlags(context) {
      const flags = context.flags;
      const internalFlags = context.internalFlags;
      return restore;
      function restore() {
        context.flags = flags;
        context.internalFlags = internalFlags;
      }
    }
    function checkTruncationLength(context) {
      if (context.truncating) return context.truncating;
      return context.truncating = context.approximateLength > (context.flags & 1 /* NoTruncation */ ? noTruncationMaximumTruncationLength : defaultMaximumTruncationLength);
    }
    function typeToTypeNodeHelper(type, context) {
      const restoreFlags = saveRestoreFlags(context);
      const typeNode = typeToTypeNodeWorker(type, context);
      restoreFlags();
      return typeNode;
    }
    function typeToTypeNodeWorker(type, context) {
      var _a, _b;
      if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
        cancellationToken.throwIfCancellationRequested();
      }
      const inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
      context.flags &= ~8388608 /* InTypeAlias */;
      if (!type) {
        if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
          context.encounteredError = true;
          return void 0;
        }
        context.approximateLength += 3;
        return factory.createKeywordTypeNode(133 /* AnyKeyword */);
      }
      if (!(context.flags & 536870912 /* NoTypeReduction */)) {
        type = getReducedType(type);
      }
      if (type.flags & 1 /* Any */) {
        if (type.aliasSymbol) {
          return factory.createTypeReferenceNode(symbolToEntityNameNode(type.aliasSymbol), mapToTypeNodes(type.aliasTypeArguments, context));
        }
        if (type === unresolvedType) {
          return addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "unresolved");
        }
        context.approximateLength += 3;
        return factory.createKeywordTypeNode(type === intrinsicMarkerType ? 141 /* IntrinsicKeyword */ : 133 /* AnyKeyword */);
      }
      if (type.flags & 2 /* Unknown */) {
        return factory.createKeywordTypeNode(159 /* UnknownKeyword */);
      }
      if (type.flags & 4 /* String */) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(154 /* StringKeyword */);
      }
      if (type.flags & 8 /* Number */) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(150 /* NumberKeyword */);
      }
      if (type.flags & 64 /* BigInt */) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(163 /* BigIntKeyword */);
      }
      if (type.flags & 16 /* Boolean */ && !type.aliasSymbol) {
        context.approximateLength += 7;
        return factory.createKeywordTypeNode(136 /* BooleanKeyword */);
      }
      if (type.flags & 1056 /* EnumLike */) {
        if (type.symbol.flags & 8 /* EnumMember */) {
          const parentSymbol = getParentOfSymbol(type.symbol);
          const parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
          if (getDeclaredTypeOfSymbol(parentSymbol) === type) {
            return parentName;
          }
          const memberName = symbolName(type.symbol);
          if (isIdentifierText(memberName, 1 /* ES5 */)) {
            return appendReferenceToType(
              parentName,
              factory.createTypeReferenceNode(
                memberName,
                /*typeArguments*/
                void 0
              )
            );
          }
          if (isImportTypeNode(parentName)) {
            parentName.isTypeOf = true;
            return factory.createIndexedAccessTypeNode(parentName, factory.createLiteralTypeNode(factory.createStringLiteral(memberName)));
          } else if (isTypeReferenceNode(parentName)) {
            return factory.createIndexedAccessTypeNode(factory.createTypeQueryNode(parentName.typeName), factory.createLiteralTypeNode(factory.createStringLiteral(memberName)));
          } else {
            return Debug.fail("Unhandled type node kind returned from `symbolToTypeNode`.");
          }
        }
        return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
      }
      if (type.flags & 128 /* StringLiteral */) {
        context.approximateLength += type.value.length + 2;
        return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
      }
      if (type.flags & 256 /* NumberLiteral */) {
        const value = type.value;
        context.approximateLength += ("" + value).length;
        return factory.createLiteralTypeNode(value < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-value)) : factory.createNumericLiteral(value));
      }
      if (type.flags & 2048 /* BigIntLiteral */) {
        context.approximateLength += pseudoBigIntToString(type.value).length + 1;
        return factory.createLiteralTypeNode(factory.createBigIntLiteral(type.value));
      }
      if (type.flags & 512 /* BooleanLiteral */) {
        context.approximateLength += type.intrinsicName.length;
        return factory.createLiteralTypeNode(type.intrinsicName === "true" ? factory.createTrue() : factory.createFalse());
      }
      if (type.flags & 8192 /* UniqueESSymbol */) {
        if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
          if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
            context.approximateLength += 6;
            return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
          }
          if (context.tracker.reportInaccessibleUniqueSymbolError) {
            context.tracker.reportInaccessibleUniqueSymbolError();
          }
        }
        context.approximateLength += 13;
        return factory.createTypeOperatorNode(158 /* UniqueKeyword */, factory.createKeywordTypeNode(155 /* SymbolKeyword */));
      }
      if (type.flags & 16384 /* Void */) {
        context.approximateLength += 4;
        return factory.createKeywordTypeNode(116 /* VoidKeyword */);
      }
      if (type.flags & 32768 /* Undefined */) {
        context.approximateLength += 9;
        return factory.createKeywordTypeNode(157 /* UndefinedKeyword */);
      }
      if (type.flags & 65536 /* Null */) {
        context.approximateLength += 4;
        return factory.createLiteralTypeNode(factory.createNull());
      }
      if (type.flags & 131072 /* Never */) {
        context.approximateLength += 5;
        return factory.createKeywordTypeNode(146 /* NeverKeyword */);
      }
      if (type.flags & 4096 /* ESSymbol */) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(155 /* SymbolKeyword */);
      }
      if (type.flags & 67108864 /* NonPrimitive */) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(151 /* ObjectKeyword */);
      }
      if (isThisTypeParameter(type)) {
        if (context.flags & 4194304 /* InObjectTypeLiteral */) {
          if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
            context.encounteredError = true;
          }
          (_b = (_a = context.tracker).reportInaccessibleThisError) == null ? void 0 : _b.call(_a);
        }
        context.approximateLength += 4;
        return factory.createThisTypeNode();
      }
      if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
        const typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
        if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return factory.createTypeReferenceNode(factory.createIdentifier(""), typeArgumentNodes);
        if (length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) {
          return factory.createArrayTypeNode(typeArgumentNodes[0]);
        }
        return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
      }
      const objectFlags = getObjectFlags(type);
      if (objectFlags & 4 /* Reference */) {
        Debug.assert(!!(type.flags & 524288 /* Object */));
        return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
      }
      if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
        if (type.flags & 262144 /* TypeParameter */ && contains(context.inferTypeParameters, type)) {
          context.approximateLength += symbolName(type.symbol).length + 6;
          let constraintNode;
          const constraint = getConstraintOfTypeParameter(type);
          if (constraint) {
            const inferredConstraint = getInferredTypeParameterConstraint(
              type,
              /*omitTypeReferences*/
              true
            );
            if (!(inferredConstraint && isTypeIdenticalTo(constraint, inferredConstraint))) {
              context.approximateLength += 9;
              constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
            }
          }
          return factory.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, constraintNode));
        }
        if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && type.flags & 262144 /* TypeParameter */) {
          const name2 = typeParameterToName(type, context);
          context.approximateLength += idText(name2).length;
          return factory.createTypeReferenceNode(
            factory.createIdentifier(idText(name2)),
            /*typeArguments*/
            void 0
          );
        }
        if (type.symbol) {
          return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
        }
        const name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? (type === markerSubTypeForCheck ? "sub-" : "super-") + symbolName(varianceTypeParameter.symbol) : "?";
        return factory.createTypeReferenceNode(
          factory.createIdentifier(name),
          /*typeArguments*/
          void 0
        );
      }
      if (type.flags & 1048576 /* Union */ && type.origin) {
        type = type.origin;
      }
      if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
        const types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
        if (length(types) === 1) {
          return typeToTypeNodeHelper(types[0], context);
        }
        const typeNodes = mapToTypeNodes(
          types,
          context,
          /*isBareList*/
          true
        );
        if (typeNodes && typeNodes.length > 0) {
          return type.flags & 1048576 /* Union */ ? factory.createUnionTypeNode(typeNodes) : factory.createIntersectionTypeNode(typeNodes);
        } else {
          if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
            context.encounteredError = true;
          }
          return void 0;
        }
      }
      if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
        Debug.assert(!!(type.flags & 524288 /* Object */));
        return createAnonymousTypeNode(type);
      }
      if (type.flags & 4194304 /* Index */) {
        const indexedType = type.type;
        context.approximateLength += 6;
        const indexTypeNode = typeToTypeNodeHelper(indexedType, context);
        return factory.createTypeOperatorNode(143 /* KeyOfKeyword */, indexTypeNode);
      }
      if (type.flags & 134217728 /* TemplateLiteral */) {
        const texts = type.texts;
        const types = type.types;
        const templateHead = factory.createTemplateHead(texts[0]);
        const templateSpans = factory.createNodeArray(
          map(types, (t, i) => factory.createTemplateLiteralTypeSpan(
            typeToTypeNodeHelper(t, context),
            (i < types.length - 1 ? factory.createTemplateMiddle : factory.createTemplateTail)(texts[i + 1])
          ))
        );
        context.approximateLength += 2;
        return factory.createTemplateLiteralType(templateHead, templateSpans);
      }
      if (type.flags & 268435456 /* StringMapping */) {
        const typeNode = typeToTypeNodeHelper(type.type, context);
        return symbolToTypeNode(type.symbol, context, 788968 /* Type */, [typeNode]);
      }
      if (type.flags & 8388608 /* IndexedAccess */) {
        const objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
        const indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
        context.approximateLength += 2;
        return factory.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
      }
      if (type.flags & 16777216 /* Conditional */) {
        return visitAndTransformType(type, (type2) => conditionalTypeToTypeNode(type2));
      }
      if (type.flags & 33554432 /* Substitution */) {
        const typeNode = typeToTypeNodeHelper(type.baseType, context);
        const noInferSymbol = isNoInferType(type) && getGlobalTypeSymbol(
          "NoInfer",
          /*reportErrors*/
          false
        );
        return noInferSymbol ? symbolToTypeNode(noInferSymbol, context, 788968 /* Type */, [typeNode]) : typeNode;
      }
      return Debug.fail("Should be unreachable.");
      function conditionalTypeToTypeNode(type2) {
        const checkTypeNode = typeToTypeNodeHelper(type2.checkType, context);
        context.approximateLength += 15;
        if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && type2.root.isDistributive && !(type2.checkType.flags & 262144 /* TypeParameter */)) {
          const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T"));
          const name = typeParameterToName(newParam, context);
          const newTypeVariable = factory.createTypeReferenceNode(name);
          context.approximateLength += 37;
          const newMapper = prependTypeMapping(type2.root.checkType, newParam, type2.mapper);
          const saveInferTypeParameters2 = context.inferTypeParameters;
          context.inferTypeParameters = type2.root.inferTypeParameters;
          const extendsTypeNode2 = typeToTypeNodeHelper(instantiateType(type2.root.extendsType, newMapper), context);
          context.inferTypeParameters = saveInferTypeParameters2;
          const trueTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.trueType), newMapper));
          const falseTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.falseType), newMapper));
          return factory.createConditionalTypeNode(
            checkTypeNode,
            factory.createInferTypeNode(factory.createTypeParameterDeclaration(
              /*modifiers*/
              void 0,
              factory.cloneNode(newTypeVariable.typeName)
            )),
            factory.createConditionalTypeNode(
              factory.createTypeReferenceNode(factory.cloneNode(name)),
              typeToTypeNodeHelper(type2.checkType, context),
              factory.createConditionalTypeNode(newTypeVariable, extendsTypeNode2, trueTypeNode2, falseTypeNode2),
              factory.createKeywordTypeNode(146 /* NeverKeyword */)
            ),
            factory.createKeywordTypeNode(146 /* NeverKeyword */)
          );
        }
        const saveInferTypeParameters = context.inferTypeParameters;
        context.inferTypeParameters = type2.root.inferTypeParameters;
        const extendsTypeNode = typeToTypeNodeHelper(type2.extendsType, context);
        context.inferTypeParameters = saveInferTypeParameters;
        const trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type2));
        const falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type2));
        return factory.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
      }
      function typeToTypeNodeOrCircularityElision(type2) {
        var _a2, _b2, _c;
        if (type2.flags & 1048576 /* Union */) {
          if ((_a2 = context.visitedTypes) == null ? void 0 : _a2.has(getTypeId(type2))) {
            if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
              context.encounteredError = true;
              (_c = (_b2 = context.tracker) == null ? void 0 : _b2.reportCyclicStructureError) == null ? void 0 : _c.call(_b2);
            }
            return createElidedInformationPlaceholder(context);
          }
          return visitAndTransformType(type2, (type3) => typeToTypeNodeHelper(type3, context));
        }
        return typeToTypeNodeHelper(type2, context);
      }
      function isMappedTypeHomomorphic(type2) {
        return !!getHomomorphicTypeVariable(type2);
      }
      function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) {
        return !!type2.target && isMappedTypeHomomorphic(type2.target) && !isMappedTypeHomomorphic(type2);
      }
      function createMappedTypeNodeFromType(type2) {
        var _a2;
        Debug.assert(!!(type2.flags & 524288 /* Object */));
        const readonlyToken = type2.declaration.readonlyToken ? factory.createToken(type2.declaration.readonlyToken.kind) : void 0;
        const questionToken = type2.declaration.questionToken ? factory.createToken(type2.declaration.questionToken.kind) : void 0;
        let appropriateConstraintTypeNode;
        let newTypeVariable;
        const needsModifierPreservingWrapper = !isMappedTypeWithKeyofConstraintDeclaration(type2) && !(getModifiersTypeFromMappedType(type2).flags & 2 /* Unknown */) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && !(getConstraintTypeFromMappedType(type2).flags & 262144 /* TypeParameter */ && ((_a2 = getConstraintOfTypeParameter(getConstraintTypeFromMappedType(type2))) == null ? void 0 : _a2.flags) & 4194304 /* Index */);
        if (isMappedTypeWithKeyofConstraintDeclaration(type2)) {
          if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
            const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T"));
            const name = typeParameterToName(newParam, context);
            newTypeVariable = factory.createTypeReferenceNode(name);
          }
          appropriateConstraintTypeNode = factory.createTypeOperatorNode(143 /* KeyOfKeyword */, newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context));
        } else if (needsModifierPreservingWrapper) {
          const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T"));
          const name = typeParameterToName(newParam, context);
          newTypeVariable = factory.createTypeReferenceNode(name);
          appropriateConstraintTypeNode = newTypeVariable;
        } else {
          appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context);
        }
        const typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type2), context, appropriateConstraintTypeNode);
        const nameTypeNode = type2.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type2), context) : void 0;
        const templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type2), !!(getMappedTypeModifiers(type2) & 4 /* IncludeOptional */)), context);
        const mappedTypeNode = factory.createMappedTypeNode(
          readonlyToken,
          typeParameterNode,
          nameTypeNode,
          questionToken,
          templateTypeNode,
          /*members*/
          void 0
        );
        context.approximateLength += 10;
        const result = setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
        if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
          const originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode2(context, type2.declaration.typeParameter.constraint.type)) || unknownType, type2.mapper);
          return factory.createConditionalTypeNode(
            typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context),
            factory.createInferTypeNode(factory.createTypeParameterDeclaration(
              /*modifiers*/
              void 0,
              factory.cloneNode(newTypeVariable.typeName),
              originalConstraint.flags & 2 /* Unknown */ ? void 0 : typeToTypeNodeHelper(originalConstraint, context)
            )),
            result,
            factory.createKeywordTypeNode(146 /* NeverKeyword */)
          );
        } else if (needsModifierPreservingWrapper) {
          return factory.createConditionalTypeNode(
            typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context),
            factory.createInferTypeNode(factory.createTypeParameterDeclaration(
              /*modifiers*/
              void 0,
              factory.cloneNode(newTypeVariable.typeName),
              factory.createTypeOperatorNode(143 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context))
            )),
            result,
            factory.createKeywordTypeNode(146 /* NeverKeyword */)
          );
        }
        return result;
      }
      function createAnonymousTypeNode(type2) {
        var _a2, _b2;
        const typeId = type2.id;
        const symbol = type2.symbol;
        if (symbol) {
          const isInstantiationExpressionType = !!(getObjectFlags(type2) & 8388608 /* InstantiationExpressionType */);
          if (isInstantiationExpressionType) {
            const instantiationExpressionType = type2;
            const existing = instantiationExpressionType.node;
            if (isTypeQueryNode(existing) && getTypeFromTypeNode2(context, existing) === type2) {
              const typeNode = syntacticNodeBuilder.tryReuseExistingTypeNode(context, existing);
              if (typeNode) {
                return typeNode;
              }
            }
            if ((_a2 = context.visitedTypes) == null ? void 0 : _a2.has(typeId)) {
              return createElidedInformationPlaceholder(context);
            }
            return visitAndTransformType(type2, createTypeNodeFromObjectType);
          }
          const isInstanceType = isClassInstanceSide(type2) ? 788968 /* Type */ : 111551 /* Value */;
          if (isJSConstructor(symbol.valueDeclaration)) {
            return symbolToTypeNode(symbol, context, isInstanceType);
          } else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration && isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && (!isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(
            symbol,
            context.enclosingDeclaration,
            isInstanceType,
            /*shouldComputeAliasesToMakeVisible*/
            false
          ).accessibility !== 0 /* Accessible */)) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) {
            return symbolToTypeNode(symbol, context, isInstanceType);
          } else if ((_b2 = context.visitedTypes) == null ? void 0 : _b2.has(typeId)) {
            const typeAlias = getTypeAliasForTypeLiteral(type2);
            if (typeAlias) {
              return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
            } else {
              return createElidedInformationPlaceholder(context);
            }
          } else {
            return visitAndTransformType(type2, createTypeNodeFromObjectType);
          }
        } else {
          return createTypeNodeFromObjectType(type2);
        }
        function shouldWriteTypeOfFunctionSymbol() {
          var _a3;
          const isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
          some(symbol.declarations, (declaration) => isStatic(declaration));
          const isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol
          forEach(symbol.declarations, (declaration) => declaration.parent.kind === 307 /* SourceFile */ || declaration.parent.kind === 268 /* ModuleBlock */));
          if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
            return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ((_a3 = context.visitedTypes) == null ? void 0 : _a3.has(typeId))) && // it is type of the symbol uses itself recursively
            (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration));
          }
        }
      }
      function visitAndTransformType(type2, transform) {
        var _a2, _b2, _c;
        const typeId = type2.id;
        const isConstructorObject = getObjectFlags(type2) & 16 /* Anonymous */ && type2.symbol && type2.symbol.flags & 32 /* Class */;
        const id = getObjectFlags(type2) & 4 /* Reference */ && type2.node ? "N" + getNodeId(type2.node) : type2.flags & 16777216 /* Conditional */ ? "N" + getNodeId(type2.root.node) : type2.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type2.symbol) : void 0;
        if (!context.visitedTypes) {
          context.visitedTypes = /* @__PURE__ */ new Set();
        }
        if (id && !context.symbolDepth) {
          context.symbolDepth = /* @__PURE__ */ new Map();
        }
        const links = context.enclosingDeclaration && getNodeLinks(context.enclosingDeclaration);
        const key = `${getTypeId(type2)}|${context.flags}|${context.internalFlags}`;
        if (links) {
          links.serializedTypes || (links.serializedTypes = /* @__PURE__ */ new Map());
        }
        const cachedResult = (_a2 = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _a2.get(key);
        if (cachedResult) {
          (_b2 = cachedResult.trackedSymbols) == null ? void 0 : _b2.forEach(
            ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol(
              symbol,
              enclosingDeclaration,
              meaning
            )
          );
          if (cachedResult.truncating) {
            context.truncating = true;
          }
          context.approximateLength += cachedResult.addedLength;
          return deepCloneOrReuseNode(cachedResult.node);
        }
        let depth;
        if (id) {
          depth = context.symbolDepth.get(id) || 0;
          if (depth > 10) {
            return createElidedInformationPlaceholder(context);
          }
          context.symbolDepth.set(id, depth + 1);
        }
        context.visitedTypes.add(typeId);
        const prevTrackedSymbols = context.trackedSymbols;
        context.trackedSymbols = void 0;
        const startLength = context.approximateLength;
        const result = transform(type2);
        const addedLength = context.approximateLength - startLength;
        if (!context.reportedDiagnostic && !context.encounteredError) {
          (_c = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _c.set(key, {
            node: result,
            truncating: context.truncating,
            addedLength,
            trackedSymbols: context.trackedSymbols
          });
        }
        context.visitedTypes.delete(typeId);
        if (id) {
          context.symbolDepth.set(id, depth);
        }
        context.trackedSymbols = prevTrackedSymbols;
        return result;
        function deepCloneOrReuseNode(node) {
          if (!nodeIsSynthesized(node) && getParseTreeNode(node) === node) {
            return node;
          }
          return setTextRange2(context, factory.cloneNode(visitEachChild(
            node,
            deepCloneOrReuseNode,
            /*context*/
            void 0,
            deepCloneOrReuseNodes,
            deepCloneOrReuseNode
          )), node);
        }
        function deepCloneOrReuseNodes(nodes, visitor, test, start, count) {
          if (nodes && nodes.length === 0) {
            return setTextRange(factory.createNodeArray(
              /*elements*/
              void 0,
              nodes.hasTrailingComma
            ), nodes);
          }
          return visitNodes2(nodes, visitor, test, start, count);
        }
      }
      function createTypeNodeFromObjectType(type2) {
        if (isGenericMappedType(type2) || type2.containsError) {
          return createMappedTypeNodeFromType(type2);
        }
        const resolved = resolveStructuredTypeMembers(type2);
        if (!resolved.properties.length && !resolved.indexInfos.length) {
          if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
            context.approximateLength += 2;
            return setEmitFlags(factory.createTypeLiteralNode(
              /*members*/
              void 0
            ), 1 /* SingleLine */);
          }
          if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
            const signature = resolved.callSignatures[0];
            const signatureNode = signatureToSignatureDeclarationHelper(signature, 184 /* FunctionType */, context);
            return signatureNode;
          }
          if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
            const signature = resolved.constructSignatures[0];
            const signatureNode = signatureToSignatureDeclarationHelper(signature, 185 /* ConstructorType */, context);
            return signatureNode;
          }
        }
        const abstractSignatures = filter(resolved.constructSignatures, (signature) => !!(signature.flags & 4 /* Abstract */));
        if (some(abstractSignatures)) {
          const types = map(abstractSignatures, (s) => getOrCreateTypeFromSignature(s));
          const typeElementCount = resolved.callSignatures.length + (resolved.constructSignatures.length - abstractSignatures.length) + resolved.indexInfos.length + // exclude `prototype` when writing a class expression as a type literal, as per
          // the logic in `createTypeNodesFromResolvedType`.
          (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ ? countWhere(resolved.properties, (p) => !(p.flags & 4194304 /* Prototype */)) : length(resolved.properties));
          if (typeElementCount) {
            types.push(getResolvedTypeWithoutAbstractConstructSignatures(resolved));
          }
          return typeToTypeNodeHelper(getIntersectionType(types), context);
        }
        const restoreFlags = saveRestoreFlags(context);
        context.flags |= 4194304 /* InObjectTypeLiteral */;
        const members = createTypeNodesFromResolvedType(resolved);
        restoreFlags();
        const typeLiteralNode = factory.createTypeLiteralNode(members);
        context.approximateLength += 2;
        setEmitFlags(typeLiteralNode, context.flags & 1024 /* MultilineObjectLiterals */ ? 0 : 1 /* SingleLine */);
        return typeLiteralNode;
      }
      function typeReferenceToTypeNode(type2) {
        let typeArguments = getTypeArguments(type2);
        if (type2.target === globalArrayType || type2.target === globalReadonlyArrayType) {
          if (context.flags & 2 /* WriteArrayAsGenericType */) {
            const typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
            return factory.createTypeReferenceNode(type2.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
          }
          const elementType = typeToTypeNodeHelper(typeArguments[0], context);
          const arrayType = factory.createArrayTypeNode(elementType);
          return type2.target === globalArrayType ? arrayType : factory.createTypeOperatorNode(148 /* ReadonlyKeyword */, arrayType);
        } else if (type2.target.objectFlags & 8 /* Tuple */) {
          typeArguments = sameMap(typeArguments, (t, i) => removeMissingType(t, !!(type2.target.elementFlags[i] & 2 /* Optional */)));
          if (typeArguments.length > 0) {
            const arity = getTypeReferenceArity(type2);
            const tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
            if (tupleConstituentNodes) {
              const { labeledElementDeclarations } = type2.target;
              for (let i = 0; i < tupleConstituentNodes.length; i++) {
                const flags = type2.target.elementFlags[i];
                const labeledElementDeclaration = labeledElementDeclarations == null ? void 0 : labeledElementDeclarations[i];
                if (labeledElementDeclaration) {
                  tupleConstituentNodes[i] = factory.createNamedTupleMember(
                    flags & 12 /* Variable */ ? factory.createToken(26 /* DotDotDotToken */) : void 0,
                    factory.createIdentifier(unescapeLeadingUnderscores(getTupleElementLabel(labeledElementDeclaration))),
                    flags & 2 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0,
                    flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]
                  );
                } else {
                  tupleConstituentNodes[i] = flags & 12 /* Variable */ ? factory.createRestTypeNode(flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) : flags & 2 /* Optional */ ? factory.createOptionalTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i];
                }
              }
              const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode(tupleConstituentNodes), 1 /* SingleLine */);
              return type2.target.readonly ? factory.createTypeOperatorNode(148 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
            }
          }
          if (context.encounteredError || context.flags & 524288 /* AllowEmptyTuple */) {
            const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode([]), 1 /* SingleLine */);
            return type2.target.readonly ? factory.createTypeOperatorNode(148 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
          }
          context.encounteredError = true;
          return void 0;
        } else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type2.symbol.valueDeclaration && isClassLike(type2.symbol.valueDeclaration) && !isValueSymbolAccessible(type2.symbol, context.enclosingDeclaration)) {
          return createAnonymousTypeNode(type2);
        } else {
          const outerTypeParameters = type2.target.outerTypeParameters;
          let i = 0;
          let resultType;
          if (outerTypeParameters) {
            const length2 = outerTypeParameters.length;
            while (i < length2) {
              const start = i;
              const parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
              do {
                i++;
              } while (i < length2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
              if (!rangeEquals(outerTypeParameters, typeArguments, start, i)) {
                const typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
                const restoreFlags2 = saveRestoreFlags(context);
                context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
                const ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
                restoreFlags2();
                resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
              }
            }
          }
          let typeArgumentNodes;
          if (typeArguments.length > 0) {
            let typeParameterCount = 0;
            if (type2.target.typeParameters) {
              typeParameterCount = Math.min(type2.target.typeParameters.length, typeArguments.length);
              if (isReferenceToType(type2, getGlobalIterableType(
                /*reportErrors*/
                false
              )) || isReferenceToType(type2, getGlobalIterableIteratorType(
                /*reportErrors*/
                false
              )) || isReferenceToType(type2, getGlobalAsyncIterableType(
                /*reportErrors*/
                false
              )) || isReferenceToType(type2, getGlobalAsyncIterableIteratorType(
                /*reportErrors*/
                false
              ))) {
                if (!type2.node || !isTypeReferenceNode(type2.node) || !type2.node.typeArguments || type2.node.typeArguments.length < typeParameterCount) {
                  while (typeParameterCount > 0) {
                    const typeArgument = typeArguments[typeParameterCount - 1];
                    const typeParameter = type2.target.typeParameters[typeParameterCount - 1];
                    const defaultType = getDefaultFromTypeParameter(typeParameter);
                    if (!defaultType || !isTypeIdenticalTo(typeArgument, defaultType)) {
                      break;
                    }
                    typeParameterCount--;
                  }
                }
              }
            }
            typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
          }
          const restoreFlags = saveRestoreFlags(context);
          context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
          const finalRef = symbolToTypeNode(type2.symbol, context, 788968 /* Type */, typeArgumentNodes);
          restoreFlags();
          return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
        }
      }
      function appendReferenceToType(root, ref) {
        if (isImportTypeNode(root)) {
          let typeArguments = root.typeArguments;
          let qualifier = root.qualifier;
          if (qualifier) {
            if (isIdentifier(qualifier)) {
              if (typeArguments !== getIdentifierTypeArguments(qualifier)) {
                qualifier = setIdentifierTypeArguments(factory.cloneNode(qualifier), typeArguments);
              }
            } else {
              if (typeArguments !== getIdentifierTypeArguments(qualifier.right)) {
                qualifier = factory.updateQualifiedName(qualifier, qualifier.left, setIdentifierTypeArguments(factory.cloneNode(qualifier.right), typeArguments));
              }
            }
          }
          typeArguments = ref.typeArguments;
          const ids = getAccessStack(ref);
          for (const id of ids) {
            qualifier = qualifier ? factory.createQualifiedName(qualifier, id) : id;
          }
          return factory.updateImportTypeNode(
            root,
            root.argument,
            root.attributes,
            qualifier,
            typeArguments,
            root.isTypeOf
          );
        } else {
          let typeArguments = root.typeArguments;
          let typeName = root.typeName;
          if (isIdentifier(typeName)) {
            if (typeArguments !== getIdentifierTypeArguments(typeName)) {
              typeName = setIdentifierTypeArguments(factory.cloneNode(typeName), typeArguments);
            }
          } else {
            if (typeArguments !== getIdentifierTypeArguments(typeName.right)) {
              typeName = factory.updateQualifiedName(typeName, typeName.left, setIdentifierTypeArguments(factory.cloneNode(typeName.right), typeArguments));
            }
          }
          typeArguments = ref.typeArguments;
          const ids = getAccessStack(ref);
          for (const id of ids) {
            typeName = factory.createQualifiedName(typeName, id);
          }
          return factory.updateTypeReferenceNode(
            root,
            typeName,
            typeArguments
          );
        }
      }
      function getAccessStack(ref) {
        let state = ref.typeName;
        const ids = [];
        while (!isIdentifier(state)) {
          ids.unshift(state.right);
          state = state.left;
        }
        ids.unshift(state);
        return ids;
      }
      function createTypeNodesFromResolvedType(resolvedType) {
        if (checkTruncationLength(context)) {
          if (context.flags & 1 /* NoTruncation */) {
            return [addSyntheticTrailingComment(factory.createNotEmittedTypeElement(), 3 /* MultiLineCommentTrivia */, "elided")];
          }
          return [factory.createPropertySignature(
            /*modifiers*/
            void 0,
            "...",
            /*questionToken*/
            void 0,
            /*type*/
            void 0
          )];
        }
        const typeElements = [];
        for (const signature of resolvedType.callSignatures) {
          typeElements.push(signatureToSignatureDeclarationHelper(signature, 179 /* CallSignature */, context));
        }
        for (const signature of resolvedType.constructSignatures) {
          if (signature.flags & 4 /* Abstract */) continue;
          typeElements.push(signatureToSignatureDeclarationHelper(signature, 180 /* ConstructSignature */, context));
        }
        for (const info of resolvedType.indexInfos) {
          typeElements.push(indexInfoToIndexSignatureDeclarationHelper(info, context, resolvedType.objectFlags & 1024 /* ReverseMapped */ ? createElidedInformationPlaceholder(context) : void 0));
        }
        const properties = resolvedType.properties;
        if (!properties) {
          return typeElements;
        }
        let i = 0;
        for (const propertySymbol of properties) {
          i++;
          if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
            if (propertySymbol.flags & 4194304 /* Prototype */) {
              continue;
            }
            if (getDeclarationModifierFlagsFromSymbol(propertySymbol) & (2 /* Private */ | 4 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
              context.tracker.reportPrivateInBaseOfClassExpression(unescapeLeadingUnderscores(propertySymbol.escapedName));
            }
          }
          if (checkTruncationLength(context) && i + 2 < properties.length - 1) {
            if (context.flags & 1 /* NoTruncation */) {
              const typeElement = typeElements.pop();
              typeElements.push(addSyntheticTrailingComment(typeElement, 3 /* MultiLineCommentTrivia */, `... ${properties.length - i} more elided ...`));
            } else {
              typeElements.push(factory.createPropertySignature(
                /*modifiers*/
                void 0,
                `... ${properties.length - i} more ...`,
                /*questionToken*/
                void 0,
                /*type*/
                void 0
              ));
            }
            addPropertyToElementList(properties[properties.length - 1], context, typeElements);
            break;
          }
          addPropertyToElementList(propertySymbol, context, typeElements);
        }
        return typeElements.length ? typeElements : void 0;
      }
    }
    function createElidedInformationPlaceholder(context) {
      context.approximateLength += 3;
      if (!(context.flags & 1 /* NoTruncation */)) {
        return factory.createTypeReferenceNode(
          factory.createIdentifier("..."),
          /*typeArguments*/
          void 0
        );
      }
      return addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "elided");
    }
    function shouldUsePlaceholderForProperty(propertySymbol, context) {
      var _a;
      const depth = 3;
      return !!(getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) && (contains(context.reverseMappedStack, propertySymbol) || ((_a = context.reverseMappedStack) == null ? void 0 : _a[0]) && !(getObjectFlags(last(context.reverseMappedStack).links.propertyType) & 16 /* Anonymous */) || isDeeplyNestedReverseMappedTypeProperty());
      function isDeeplyNestedReverseMappedTypeProperty() {
        var _a2;
        if ((((_a2 = context.reverseMappedStack) == null ? void 0 : _a2.length) ?? 0) < depth) {
          return false;
        }
        for (let i = 0; i < depth; i++) {
          const prop = context.reverseMappedStack[context.reverseMappedStack.length - 1 - i];
          if (prop.links.mappedType.symbol !== propertySymbol.links.mappedType.symbol) {
            return false;
          }
        }
        return true;
      }
    }
    function addPropertyToElementList(propertySymbol, context, typeElements) {
      var _a;
      const propertyIsReverseMapped = !!(getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
      const propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getNonMissingTypeOfSymbol(propertySymbol);
      const saveEnclosingDeclaration = context.enclosingDeclaration;
      context.enclosingDeclaration = void 0;
      if (context.tracker.canTrackSymbol && isLateBoundName(propertySymbol.escapedName)) {
        if (propertySymbol.declarations) {
          const decl = first(propertySymbol.declarations);
          if (hasLateBindableName(decl)) {
            if (isBinaryExpression(decl)) {
              const name = getNameOfDeclaration(decl);
              if (name && isElementAccessExpression(name) && isPropertyAccessEntityNameExpression(name.argumentExpression)) {
                trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
              }
            } else {
              trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
            }
          }
        } else {
          context.tracker.reportNonSerializableProperty(symbolToString(propertySymbol));
        }
      }
      context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_a = propertySymbol.declarations) == null ? void 0 : _a[0]) || saveEnclosingDeclaration;
      const propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
      context.enclosingDeclaration = saveEnclosingDeclaration;
      context.approximateLength += symbolName(propertySymbol).length + 1;
      if (propertySymbol.flags & 98304 /* Accessor */) {
        const writeType = getWriteTypeOfSymbol(propertySymbol);
        if (propertyType !== writeType && !isErrorType(propertyType) && !isErrorType(writeType)) {
          const getterDeclaration = getDeclarationOfKind(propertySymbol, 177 /* GetAccessor */);
          const getterSignature = getSignatureFromDeclaration(getterDeclaration);
          typeElements.push(
            setCommentRange2(
              context,
              signatureToSignatureDeclarationHelper(getterSignature, 177 /* GetAccessor */, context, { name: propertyName }),
              getterDeclaration
            )
          );
          const setterDeclaration = getDeclarationOfKind(propertySymbol, 178 /* SetAccessor */);
          const setterSignature = getSignatureFromDeclaration(setterDeclaration);
          typeElements.push(
            setCommentRange2(
              context,
              signatureToSignatureDeclarationHelper(setterSignature, 178 /* SetAccessor */, context, { name: propertyName }),
              setterDeclaration
            )
          );
          return;
        }
      }
      const optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0;
      if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
        const signatures = getSignaturesOfType(filterType(propertyType, (t) => !(t.flags & 32768 /* Undefined */)), 0 /* Call */);
        for (const signature of signatures) {
          const methodDeclaration = signatureToSignatureDeclarationHelper(signature, 173 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken });
          typeElements.push(preserveCommentsOn(methodDeclaration, signature.declaration || propertySymbol.valueDeclaration));
        }
        if (signatures.length || !optionalToken) {
          return;
        }
      }
      let propertyTypeNode;
      if (shouldUsePlaceholderForProperty(propertySymbol, context)) {
        propertyTypeNode = createElidedInformationPlaceholder(context);
      } else {
        if (propertyIsReverseMapped) {
          context.reverseMappedStack || (context.reverseMappedStack = []);
          context.reverseMappedStack.push(propertySymbol);
        }
        propertyTypeNode = propertyType ? serializeTypeForDeclaration(
          context,
          /*declaration*/
          void 0,
          propertyType,
          propertySymbol
        ) : factory.createKeywordTypeNode(133 /* AnyKeyword */);
        if (propertyIsReverseMapped) {
          context.reverseMappedStack.pop();
        }
      }
      const modifiers = isReadonlySymbol(propertySymbol) ? [factory.createToken(148 /* ReadonlyKeyword */)] : void 0;
      if (modifiers) {
        context.approximateLength += 9;
      }
      const propertySignature = factory.createPropertySignature(
        modifiers,
        propertyName,
        optionalToken,
        propertyTypeNode
      );
      typeElements.push(preserveCommentsOn(propertySignature, propertySymbol.valueDeclaration));
      function preserveCommentsOn(node, range) {
        var _a2;
        const jsdocPropertyTag = (_a2 = propertySymbol.declarations) == null ? void 0 : _a2.find((d) => d.kind === 348 /* JSDocPropertyTag */);
        if (jsdocPropertyTag) {
          const commentText = getTextOfJSDocComment(jsdocPropertyTag.comment);
          if (commentText) {
            setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
          }
        } else if (range) {
          setCommentRange2(context, node, range);
        }
        return node;
      }
    }
    function setCommentRange2(context, node, range) {
      if (context.enclosingFile && context.enclosingFile === getSourceFileOfNode(range)) {
        return setCommentRange(node, range);
      }
      return node;
    }
    function mapToTypeNodes(types, context, isBareList) {
      if (some(types)) {
        if (checkTruncationLength(context)) {
          if (!isBareList) {
            return [
              context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "elided") : factory.createTypeReferenceNode(
                "...",
                /*typeArguments*/
                void 0
              )
            ];
          } else if (types.length > 2) {
            return [
              typeToTypeNodeHelper(types[0], context),
              context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, `... ${types.length - 2} more elided ...`) : factory.createTypeReferenceNode(
                `... ${types.length - 2} more ...`,
                /*typeArguments*/
                void 0
              ),
              typeToTypeNodeHelper(types[types.length - 1], context)
            ];
          }
        }
        const mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
        const seenNames = mayHaveNameCollisions ? createMultiMap() : void 0;
        const result = [];
        let i = 0;
        for (const type of types) {
          i++;
          if (checkTruncationLength(context) && i + 2 < types.length - 1) {
            result.push(
              context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, `... ${types.length - i} more elided ...`) : factory.createTypeReferenceNode(
                `... ${types.length - i} more ...`,
                /*typeArguments*/
                void 0
              )
            );
            const typeNode2 = typeToTypeNodeHelper(types[types.length - 1], context);
            if (typeNode2) {
              result.push(typeNode2);
            }
            break;
          }
          context.approximateLength += 2;
          const typeNode = typeToTypeNodeHelper(type, context);
          if (typeNode) {
            result.push(typeNode);
            if (seenNames && isIdentifierTypeReference(typeNode)) {
              seenNames.add(typeNode.typeName.escapedText, [type, result.length - 1]);
            }
          }
        }
        if (seenNames) {
          const restoreFlags = saveRestoreFlags(context);
          context.flags |= 64 /* UseFullyQualifiedType */;
          seenNames.forEach((types2) => {
            if (!arrayIsHomogeneous(types2, ([a], [b]) => typesAreSameReference(a, b))) {
              for (const [type, resultIndex] of types2) {
                result[resultIndex] = typeToTypeNodeHelper(type, context);
              }
            }
          });
          restoreFlags();
        }
        return result;
      }
    }
    function typesAreSameReference(a, b) {
      return a === b || !!a.symbol && a.symbol === b.symbol || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
    }
    function indexInfoToIndexSignatureDeclarationHelper(indexInfo, context, typeNode) {
      const name = getNameFromIndexInfo(indexInfo) || "x";
      const indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context);
      const indexingParameter = factory.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        name,
        /*questionToken*/
        void 0,
        indexerTypeNode,
        /*initializer*/
        void 0
      );
      if (!typeNode) {
        typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
      }
      if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
        context.encounteredError = true;
      }
      context.approximateLength += name.length + 4;
      return factory.createIndexSignature(
        indexInfo.isReadonly ? [factory.createToken(148 /* ReadonlyKeyword */)] : void 0,
        [indexingParameter],
        typeNode
      );
    }
    function signatureToSignatureDeclarationHelper(signature, kind, context, options) {
      var _a;
      let typeParameters;
      let typeArguments;
      const expandedParams = getExpandedParameters(
        signature,
        /*skipUnionExpanding*/
        true
      )[0];
      const cleanup = enterNewScope(context, signature.declaration, expandedParams, signature.typeParameters, signature.parameters, signature.mapper);
      context.approximateLength += 3;
      if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
        typeArguments = signature.target.typeParameters.map((parameter) => typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context));
      } else {
        typeParameters = signature.typeParameters && signature.typeParameters.map((parameter) => typeParameterToDeclaration(parameter, context));
      }
      const restoreFlags = saveRestoreFlags(context);
      context.flags &= ~256 /* SuppressAnyReturnType */;
      const parameters = (some(expandedParams, (p) => p !== expandedParams[expandedParams.length - 1] && !!(getCheckFlags(p) & 32768 /* RestParameter */)) ? signature.parameters : expandedParams).map((parameter) => symbolToParameterDeclaration(parameter, context, kind === 176 /* Constructor */));
      const thisParameter = context.flags & 33554432 /* OmitThisParameter */ ? void 0 : tryGetThisParameterDeclaration(signature, context);
      if (thisParameter) {
        parameters.unshift(thisParameter);
      }
      restoreFlags();
      const returnTypeNode = serializeReturnTypeForSignature(context, signature);
      let modifiers = options == null ? void 0 : options.modifiers;
      if (kind === 185 /* ConstructorType */ && signature.flags & 4 /* Abstract */) {
        const flags = modifiersToFlags(modifiers);
        modifiers = factory.createModifiersFromModifierFlags(flags | 64 /* Abstract */);
      }
      const node = kind === 179 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 180 /* ConstructSignature */ ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 173 /* MethodSignature */ ? factory.createMethodSignature(modifiers, (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), options == null ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : kind === 174 /* MethodDeclaration */ ? factory.createMethodDeclaration(
        modifiers,
        /*asteriskToken*/
        void 0,
        (options == null ? void 0 : options.name) ?? factory.createIdentifier(""),
        /*questionToken*/
        void 0,
        typeParameters,
        parameters,
        returnTypeNode,
        /*body*/
        void 0
      ) : kind === 176 /* Constructor */ ? factory.createConstructorDeclaration(
        modifiers,
        parameters,
        /*body*/
        void 0
      ) : kind === 177 /* GetAccessor */ ? factory.createGetAccessorDeclaration(
        modifiers,
        (options == null ? void 0 : options.name) ?? factory.createIdentifier(""),
        parameters,
        returnTypeNode,
        /*body*/
        void 0
      ) : kind === 178 /* SetAccessor */ ? factory.createSetAccessorDeclaration(
        modifiers,
        (options == null ? void 0 : options.name) ?? factory.createIdentifier(""),
        parameters,
        /*body*/
        void 0
      ) : kind === 181 /* IndexSignature */ ? factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 317 /* JSDocFunctionType */ ? factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 184 /* FunctionType */ ? factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 185 /* ConstructorType */ ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 262 /* FunctionDeclaration */ ? factory.createFunctionDeclaration(
        modifiers,
        /*asteriskToken*/
        void 0,
        (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""),
        typeParameters,
        parameters,
        returnTypeNode,
        /*body*/
        void 0
      ) : kind === 218 /* FunctionExpression */ ? factory.createFunctionExpression(
        modifiers,
        /*asteriskToken*/
        void 0,
        (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""),
        typeParameters,
        parameters,
        returnTypeNode,
        factory.createBlock([])
      ) : kind === 219 /* ArrowFunction */ ? factory.createArrowFunction(
        modifiers,
        typeParameters,
        parameters,
        returnTypeNode,
        /*equalsGreaterThanToken*/
        void 0,
        factory.createBlock([])
      ) : Debug.assertNever(kind);
      if (typeArguments) {
        node.typeArguments = factory.createNodeArray(typeArguments);
      }
      if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 323 /* JSDocSignature */ && signature.declaration.parent.kind === 339 /* JSDocOverloadTag */) {
        const comment = getTextOfNode(
          signature.declaration.parent.parent,
          /*includeTrivia*/
          true
        ).slice(2, -2).split(/\r\n|\n|\r/).map((line) => line.replace(/^\s+/, " ")).join("\n");
        addSyntheticLeadingComment(
          node,
          3 /* MultiLineCommentTrivia */,
          comment,
          /*hasTrailingNewLine*/
          true
        );
      }
      cleanup == null ? void 0 : cleanup();
      return node;
    }
    function createRecoveryBoundary(context) {
      if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
        cancellationToken.throwIfCancellationRequested();
      }
      let trackedSymbols;
      let unreportedErrors;
      let hadError = false;
      const oldTracker = context.tracker;
      const oldTrackedSymbols = context.trackedSymbols;
      context.trackedSymbols = void 0;
      const oldEncounteredError = context.encounteredError;
      context.tracker = new SymbolTrackerImpl(context, {
        ...oldTracker.inner,
        reportCyclicStructureError() {
          markError(() => oldTracker.reportCyclicStructureError());
        },
        reportInaccessibleThisError() {
          markError(() => oldTracker.reportInaccessibleThisError());
        },
        reportInaccessibleUniqueSymbolError() {
          markError(() => oldTracker.reportInaccessibleUniqueSymbolError());
        },
        reportLikelyUnsafeImportRequiredError(specifier) {
          markError(() => oldTracker.reportLikelyUnsafeImportRequiredError(specifier));
        },
        reportNonSerializableProperty(name) {
          markError(() => oldTracker.reportNonSerializableProperty(name));
        },
        reportPrivateInBaseOfClassExpression(propertyName) {
          markError(() => oldTracker.reportPrivateInBaseOfClassExpression(propertyName));
        },
        trackSymbol(sym, decl, meaning) {
          (trackedSymbols ?? (trackedSymbols = [])).push([sym, decl, meaning]);
          return false;
        },
        moduleResolverHost: context.tracker.moduleResolverHost
      }, context.tracker.moduleResolverHost);
      return {
        startRecoveryScope,
        finalizeBoundary,
        markError,
        hadError: () => hadError
      };
      function markError(unreportedError) {
        hadError = true;
        if (unreportedError) {
          (unreportedErrors ?? (unreportedErrors = [])).push(unreportedError);
        }
      }
      function startRecoveryScope() {
        const trackedSymbolsTop = (trackedSymbols == null ? void 0 : trackedSymbols.length) ?? 0;
        const unreportedErrorsTop = (unreportedErrors == null ? void 0 : unreportedErrors.length) ?? 0;
        return () => {
          hadError = false;
          if (trackedSymbols) {
            trackedSymbols.length = trackedSymbolsTop;
          }
          if (unreportedErrors) {
            unreportedErrors.length = unreportedErrorsTop;
          }
        };
      }
      function finalizeBoundary() {
        context.tracker = oldTracker;
        context.trackedSymbols = oldTrackedSymbols;
        context.encounteredError = oldEncounteredError;
        unreportedErrors == null ? void 0 : unreportedErrors.forEach((fn) => fn());
        if (hadError) {
          return false;
        }
        trackedSymbols == null ? void 0 : trackedSymbols.forEach(
          ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol(
            symbol,
            enclosingDeclaration,
            meaning
          )
        );
        return true;
      }
    }
    function enterNewScope(context, declaration, expandedParams, typeParameters, originalParameters, mapper) {
      const cleanupContext = cloneNodeBuilderContext(context);
      let cleanupParams;
      let cleanupTypeParams;
      const oldEnclosingDecl = context.enclosingDeclaration;
      const oldMapper = context.mapper;
      if (mapper) {
        context.mapper = mapper;
      }
      if (context.enclosingDeclaration && declaration) {
        let pushFakeScope2 = function(kind, addAll) {
          Debug.assert(context.enclosingDeclaration);
          let existingFakeScope;
          if (getNodeLinks(context.enclosingDeclaration).fakeScopeForSignatureDeclaration === kind) {
            existingFakeScope = context.enclosingDeclaration;
          } else if (context.enclosingDeclaration.parent && getNodeLinks(context.enclosingDeclaration.parent).fakeScopeForSignatureDeclaration === kind) {
            existingFakeScope = context.enclosingDeclaration.parent;
          }
          Debug.assertOptionalNode(existingFakeScope, isBlock);
          const locals = (existingFakeScope == null ? void 0 : existingFakeScope.locals) ?? createSymbolTable();
          let newLocals;
          let oldLocals;
          addAll((name, symbol) => {
            if (existingFakeScope) {
              const oldSymbol = locals.get(name);
              if (!oldSymbol) {
                newLocals = append(newLocals, name);
              } else {
                oldLocals = append(oldLocals, { name, oldSymbol });
              }
            }
            locals.set(name, symbol);
          });
          if (!existingFakeScope) {
            const fakeScope = factory.createBlock(emptyArray);
            getNodeLinks(fakeScope).fakeScopeForSignatureDeclaration = kind;
            fakeScope.locals = locals;
            setParent(fakeScope, context.enclosingDeclaration);
            context.enclosingDeclaration = fakeScope;
          } else {
            return function undo() {
              forEach(newLocals, (s) => locals.delete(s));
              forEach(oldLocals, (s) => locals.set(s.name, s.oldSymbol));
            };
          }
        };
        var pushFakeScope = pushFakeScope2;
        cleanupParams = !some(expandedParams) ? void 0 : pushFakeScope2(
          "params",
          (add) => {
            if (!expandedParams) return;
            for (let pIndex = 0; pIndex < expandedParams.length; pIndex++) {
              const param = expandedParams[pIndex];
              const originalParam = originalParameters == null ? void 0 : originalParameters[pIndex];
              if (originalParameters && originalParam !== param) {
                add(param.escapedName, unknownSymbol);
                if (originalParam) {
                  add(originalParam.escapedName, unknownSymbol);
                }
              } else if (!forEach(param.declarations, (d) => {
                if (isParameter(d) && isBindingPattern(d.name)) {
                  bindPattern(d.name);
                  return true;
                }
                return void 0;
                function bindPattern(p) {
                  forEach(p.elements, (e) => {
                    switch (e.kind) {
                      case 232 /* OmittedExpression */:
                        return;
                      case 208 /* BindingElement */:
                        return bindElement(e);
                      default:
                        return Debug.assertNever(e);
                    }
                  });
                }
                function bindElement(e) {
                  if (isBindingPattern(e.name)) {
                    return bindPattern(e.name);
                  }
                  const symbol = getSymbolOfDeclaration(e);
                  add(symbol.escapedName, symbol);
                }
              })) {
                add(param.escapedName, param);
              }
            }
          }
        );
        if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && some(typeParameters)) {
          cleanupTypeParams = pushFakeScope2(
            "typeParams",
            (add) => {
              for (const typeParam of typeParameters ?? emptyArray) {
                const typeParamName = typeParameterToName(typeParam, context).escapedText;
                add(typeParamName, typeParam.symbol);
              }
            }
          );
        }
      }
      return () => {
        cleanupParams == null ? void 0 : cleanupParams();
        cleanupTypeParams == null ? void 0 : cleanupTypeParams();
        cleanupContext();
        context.enclosingDeclaration = oldEnclosingDecl;
        context.mapper = oldMapper;
      };
    }
    function tryGetThisParameterDeclaration(signature, context) {
      if (signature.thisParameter) {
        return symbolToParameterDeclaration(signature.thisParameter, context);
      }
      if (signature.declaration && isInJSFile(signature.declaration)) {
        const thisTag = getJSDocThisTag(signature.declaration);
        if (thisTag && thisTag.typeExpression) {
          return factory.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            "this",
            /*questionToken*/
            void 0,
            typeToTypeNodeHelper(getTypeFromTypeNode2(context, thisTag.typeExpression), context)
          );
        }
      }
    }
    function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
      const restoreFlags = saveRestoreFlags(context);
      context.flags &= ~512 /* WriteTypeParametersInQualifiedName */;
      const modifiers = factory.createModifiersFromModifierFlags(getTypeParameterModifiers(type));
      const name = typeParameterToName(type, context);
      const defaultParameter = getDefaultFromTypeParameter(type);
      const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
      restoreFlags();
      return factory.createTypeParameterDeclaration(modifiers, name, constraintNode, defaultParameterNode);
    }
    function typeToTypeNodeHelperWithPossibleReusableTypeNode(type, typeNode, context) {
      return typeNode && getTypeFromTypeNode2(context, typeNode) === type && syntacticNodeBuilder.tryReuseExistingTypeNode(context, typeNode) || typeToTypeNodeHelper(type, context);
    }
    function typeParameterToDeclaration(type, context, constraint = getConstraintOfTypeParameter(type)) {
      const constraintNode = constraint && typeToTypeNodeHelperWithPossibleReusableTypeNode(constraint, getConstraintDeclaration(type), context);
      return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
    }
    function typePredicateToTypePredicateNodeHelper(typePredicate, context) {
      const assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(131 /* AssertsKeyword */) : void 0;
      const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : factory.createThisTypeNode();
      const typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
      return factory.createTypePredicateNode(assertsModifier, parameterName, typeNode);
    }
    function getEffectiveParameterDeclaration(parameterSymbol) {
      const parameterDeclaration = getDeclarationOfKind(parameterSymbol, 169 /* Parameter */);
      if (parameterDeclaration) {
        return parameterDeclaration;
      }
      if (!isTransientSymbol(parameterSymbol)) {
        return getDeclarationOfKind(parameterSymbol, 341 /* JSDocParameterTag */);
      }
    }
    function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
      const parameterDeclaration = getEffectiveParameterDeclaration(parameterSymbol);
      const parameterType = getTypeOfSymbol(parameterSymbol);
      const parameterTypeNode = serializeTypeForDeclaration(context, parameterDeclaration, parameterType, parameterSymbol);
      const modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && canHaveModifiers(parameterDeclaration) ? map(getModifiers(parameterDeclaration), factory.cloneNode) : void 0;
      const isRest = parameterDeclaration && isRestParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
      const dotDotDotToken = isRest ? factory.createToken(26 /* DotDotDotToken */) : void 0;
      const name = parameterToParameterDeclarationName(parameterSymbol, parameterDeclaration, context);
      const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
      const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0;
      const parameterNode = factory.createParameterDeclaration(
        modifiers,
        dotDotDotToken,
        name,
        questionToken,
        parameterTypeNode,
        /*initializer*/
        void 0
      );
      context.approximateLength += symbolName(parameterSymbol).length + 3;
      return parameterNode;
    }
    function parameterToParameterDeclarationName(parameterSymbol, parameterDeclaration, context) {
      return parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 166 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol);
      function cloneBindingName(node) {
        return elideInitializerAndSetEmitFlags(node);
        function elideInitializerAndSetEmitFlags(node2) {
          if (context.tracker.canTrackSymbol && isComputedPropertyName(node2) && isLateBindableName(node2)) {
            trackComputedName(node2.expression, context.enclosingDeclaration, context);
          }
          let visited = visitEachChild(
            node2,
            elideInitializerAndSetEmitFlags,
            /*context*/
            void 0,
            /*nodesVisitor*/
            void 0,
            elideInitializerAndSetEmitFlags
          );
          if (isBindingElement(visited)) {
            visited = factory.updateBindingElement(
              visited,
              visited.dotDotDotToken,
              visited.propertyName,
              visited.name,
              /*initializer*/
              void 0
            );
          }
          if (!nodeIsSynthesized(visited)) {
            visited = factory.cloneNode(visited);
          }
          return setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
        }
      }
    }
    function trackComputedName(accessExpression, enclosingDeclaration, context) {
      if (!context.tracker.canTrackSymbol) return;
      const firstIdentifier = getFirstIdentifier(accessExpression);
      const name = resolveName(
        firstIdentifier,
        firstIdentifier.escapedText,
        111551 /* Value */ | 1048576 /* ExportValue */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        true
      );
      if (name) {
        context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
      }
    }
    function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
      context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning);
      return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
    }
    function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
      let chain;
      const isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
      if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.internalFlags & 4 /* DoNotIncludeSymbolChain */)) {
        chain = Debug.checkDefined(getSymbolChain(
          symbol,
          meaning,
          /*endOfChain*/
          true
        ));
        Debug.assert(chain && chain.length > 0);
      } else {
        chain = [symbol];
      }
      return chain;
      function getSymbolChain(symbol2, meaning2, endOfChain) {
        let accessibleSymbolChain = getAccessibleSymbolChain(symbol2, context.enclosingDeclaration, meaning2, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
        let parentSpecifiers;
        if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning2 : getQualifiedLeftMeaning(meaning2))) {
          const parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol2, context.enclosingDeclaration, meaning2);
          if (length(parents)) {
            parentSpecifiers = parents.map(
              (symbol3) => some(symbol3.declarations, hasNonGlobalAugmentationExternalModuleSymbol) ? getSpecifierForModuleSymbol(symbol3, context) : void 0
            );
            const indices = parents.map((_, i) => i);
            indices.sort(sortByBestName);
            const sortedParents = indices.map((i) => parents[i]);
            for (const parent of sortedParents) {
              const parentChain = getSymbolChain(
                parent,
                getQualifiedLeftMeaning(meaning2),
                /*endOfChain*/
                false
              );
              if (parentChain) {
                if (parent.exports && parent.exports.get("export=" /* ExportEquals */) && getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol2)) {
                  accessibleSymbolChain = parentChain;
                  break;
                }
                accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol2) || symbol2]);
                break;
              }
            }
          }
        }
        if (accessibleSymbolChain) {
          return accessibleSymbolChain;
        }
        if (
          // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
          endOfChain || // If a parent symbol is an anonymous type, don't write it.
          !(symbol2.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))
        ) {
          if (!endOfChain && !yieldModuleSymbol && !!forEach(symbol2.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
            return;
          }
          return [symbol2];
        }
        function sortByBestName(a, b) {
          const specifierA = parentSpecifiers[a];
          const specifierB = parentSpecifiers[b];
          if (specifierA && specifierB) {
            const isBRelative = pathIsRelative(specifierB);
            if (pathIsRelative(specifierA) === isBRelative) {
              return countPathComponents(specifierA) - countPathComponents(specifierB);
            }
            if (isBRelative) {
              return -1;
            }
            return 1;
          }
          return 0;
        }
      }
    }
    function typeParametersToTypeParameterDeclarations(symbol, context) {
      let typeParameterNodes;
      const targetSymbol = getTargetSymbol(symbol);
      if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
        typeParameterNodes = factory.createNodeArray(map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), (tp) => typeParameterToDeclaration(tp, context)));
      }
      return typeParameterNodes;
    }
    function lookupTypeParameterNodes(chain, index, context) {
      var _a;
      Debug.assert(chain && 0 <= index && index < chain.length);
      const symbol = chain[index];
      const symbolId = getSymbolId(symbol);
      if ((_a = context.typeParameterSymbolList) == null ? void 0 : _a.has(symbolId)) {
        return void 0;
      }
      if (context.mustCreateTypeParameterSymbolList) {
        context.mustCreateTypeParameterSymbolList = false;
        context.typeParameterSymbolList = new Set(context.typeParameterSymbolList);
      }
      context.typeParameterSymbolList.add(symbolId);
      let typeParameterNodes;
      if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < chain.length - 1) {
        const parentSymbol = symbol;
        const nextSymbol = chain[index + 1];
        if (getCheckFlags(nextSymbol) & 1 /* Instantiated */) {
          const params = getTypeParametersOfClassOrInterface(
            parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol
          );
          typeParameterNodes = mapToTypeNodes(map(params, (t) => getMappedType(t, nextSymbol.links.mapper)), context);
        } else {
          typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
        }
      }
      return typeParameterNodes;
    }
    function getTopmostIndexedAccessType(top) {
      if (isIndexedAccessTypeNode(top.objectType)) {
        return getTopmostIndexedAccessType(top.objectType);
      }
      return top;
    }
    function getSpecifierForModuleSymbol(symbol, context, overrideImportMode) {
      let file = getDeclarationOfKind(symbol, 307 /* SourceFile */);
      if (!file) {
        const equivalentFileSymbol = firstDefined(symbol.declarations, (d) => getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol));
        if (equivalentFileSymbol) {
          file = getDeclarationOfKind(equivalentFileSymbol, 307 /* SourceFile */);
        }
      }
      if (file && file.moduleName !== void 0) {
        return file.moduleName;
      }
      if (!file) {
        if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
          return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
        }
      }
      if (!context.enclosingFile || !context.tracker.moduleResolverHost) {
        if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
          return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
        }
        return getSourceFileOfNode(getNonAugmentationDeclaration(symbol)).fileName;
      }
      const enclosingDeclaration = getOriginalNode(context.enclosingDeclaration);
      const originalModuleSpecifier = canHaveModuleSpecifier(enclosingDeclaration) ? tryGetModuleSpecifierFromDeclaration(enclosingDeclaration) : void 0;
      const contextFile = context.enclosingFile;
      const resolutionMode = overrideImportMode || originalModuleSpecifier && host.getModeForUsageLocation(contextFile, originalModuleSpecifier) || contextFile && host.getDefaultResolutionModeForFile(contextFile);
      const cacheKey = createModeAwareCacheKey(contextFile.path, resolutionMode);
      const links = getSymbolLinks(symbol);
      let specifier = links.specifierCache && links.specifierCache.get(cacheKey);
      if (!specifier) {
        const isBundle2 = !!compilerOptions.outFile;
        const { moduleResolverHost } = context.tracker;
        const specifierCompilerOptions = isBundle2 ? { ...compilerOptions, baseUrl: moduleResolverHost.getCommonSourceDirectory() } : compilerOptions;
        specifier = first(getModuleSpecifiers(
          symbol,
          checker,
          specifierCompilerOptions,
          contextFile,
          moduleResolverHost,
          {
            importModuleSpecifierPreference: isBundle2 ? "non-relative" : "project-relative",
            importModuleSpecifierEnding: isBundle2 ? "minimal" : resolutionMode === 99 /* ESNext */ ? "js" : void 0
          },
          { overrideImportMode }
        ));
        links.specifierCache ?? (links.specifierCache = /* @__PURE__ */ new Map());
        links.specifierCache.set(cacheKey, specifier);
      }
      return specifier;
    }
    function symbolToEntityNameNode(symbol) {
      const identifier = factory.createIdentifier(unescapeLeadingUnderscores(symbol.escapedName));
      return symbol.parent ? factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier;
    }
    function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
      const chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */));
      const isTypeOf = meaning === 111551 /* Value */;
      if (some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
        const nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : void 0;
        const typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
        const contextFile = getSourceFileOfNode(getOriginalNode(context.enclosingDeclaration));
        const targetFile = getSourceFileOfModule(chain[0]);
        let specifier;
        let attributes;
        if (getEmitModuleResolutionKind(compilerOptions) === 3 /* Node16 */ || getEmitModuleResolutionKind(compilerOptions) === 99 /* NodeNext */) {
          if ((targetFile == null ? void 0 : targetFile.impliedNodeFormat) === 99 /* ESNext */ && targetFile.impliedNodeFormat !== (contextFile == null ? void 0 : contextFile.impliedNodeFormat)) {
            specifier = getSpecifierForModuleSymbol(chain[0], context, 99 /* ESNext */);
            attributes = factory.createImportAttributes(
              factory.createNodeArray([
                factory.createImportAttribute(
                  factory.createStringLiteral("resolution-mode"),
                  factory.createStringLiteral("import")
                )
              ])
            );
          }
        }
        if (!specifier) {
          specifier = getSpecifierForModuleSymbol(chain[0], context);
        }
        if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && getEmitModuleResolutionKind(compilerOptions) !== 1 /* Classic */ && specifier.includes("/node_modules/")) {
          const oldSpecifier = specifier;
          if (getEmitModuleResolutionKind(compilerOptions) === 3 /* Node16 */ || getEmitModuleResolutionKind(compilerOptions) === 99 /* NodeNext */) {
            const swappedMode = (contextFile == null ? void 0 : contextFile.impliedNodeFormat) === 99 /* ESNext */ ? 1 /* CommonJS */ : 99 /* ESNext */;
            specifier = getSpecifierForModuleSymbol(chain[0], context, swappedMode);
            if (specifier.includes("/node_modules/")) {
              specifier = oldSpecifier;
            } else {
              attributes = factory.createImportAttributes(
                factory.createNodeArray([
                  factory.createImportAttribute(
                    factory.createStringLiteral("resolution-mode"),
                    factory.createStringLiteral(swappedMode === 99 /* ESNext */ ? "import" : "require")
                  )
                ])
              );
            }
          }
          if (!attributes) {
            context.encounteredError = true;
            if (context.tracker.reportLikelyUnsafeImportRequiredError) {
              context.tracker.reportLikelyUnsafeImportRequiredError(oldSpecifier);
            }
          }
        }
        const lit = factory.createLiteralTypeNode(factory.createStringLiteral(specifier));
        context.approximateLength += specifier.length + 10;
        if (!nonRootParts || isEntityName(nonRootParts)) {
          if (nonRootParts) {
            const lastId = isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
            setIdentifierTypeArguments(
              lastId,
              /*typeArguments*/
              void 0
            );
          }
          return factory.createImportTypeNode(lit, attributes, nonRootParts, typeParameterNodes, isTypeOf);
        } else {
          const splitNode = getTopmostIndexedAccessType(nonRootParts);
          const qualifier = splitNode.objectType.typeName;
          return factory.createIndexedAccessTypeNode(factory.createImportTypeNode(lit, attributes, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
        }
      }
      const entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
      if (isIndexedAccessTypeNode(entityName)) {
        return entityName;
      }
      if (isTypeOf) {
        return factory.createTypeQueryNode(entityName);
      } else {
        const lastId = isIdentifier(entityName) ? entityName : entityName.right;
        const lastTypeArgs = getIdentifierTypeArguments(lastId);
        setIdentifierTypeArguments(
          lastId,
          /*typeArguments*/
          void 0
        );
        return factory.createTypeReferenceNode(entityName, lastTypeArgs);
      }
      function createAccessFromSymbolChain(chain2, index, stopper) {
        const typeParameterNodes = index === chain2.length - 1 ? overrideTypeArguments : lookupTypeParameterNodes(chain2, index, context);
        const symbol2 = chain2[index];
        const parent = chain2[index - 1];
        let symbolName2;
        if (index === 0) {
          context.flags |= 16777216 /* InInitialEntityName */;
          symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
          context.approximateLength += (symbolName2 ? symbolName2.length : 0) + 1;
          context.flags ^= 16777216 /* InInitialEntityName */;
        } else {
          if (parent && getExportsOfSymbol(parent)) {
            const exports2 = getExportsOfSymbol(parent);
            forEachEntry(exports2, (ex, name) => {
              if (getSymbolIfSameReference(ex, symbol2) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
                symbolName2 = unescapeLeadingUnderscores(name);
                return true;
              }
            });
          }
        }
        if (symbolName2 === void 0) {
          const name = firstDefined(symbol2.declarations, getNameOfDeclaration);
          if (name && isComputedPropertyName(name) && isEntityName(name.expression)) {
            const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper);
            if (isEntityName(LHS)) {
              return factory.createIndexedAccessTypeNode(factory.createParenthesizedType(factory.createTypeQueryNode(LHS)), factory.createTypeQueryNode(name.expression));
            }
            return LHS;
          }
          symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
        }
        context.approximateLength += symbolName2.length + 1;
        if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol2.escapedName) && getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol2.escapedName), symbol2)) {
          const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper);
          if (isIndexedAccessTypeNode(LHS)) {
            return factory.createIndexedAccessTypeNode(LHS, factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2)));
          } else {
            return factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(LHS, typeParameterNodes), factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2)));
          }
        }
        const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */);
        if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
        identifier.symbol = symbol2;
        if (index > stopper) {
          const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper);
          if (!isEntityName(LHS)) {
            return Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
          }
          return factory.createQualifiedName(LHS, identifier);
        }
        return identifier;
      }
    }
    function typeParameterShadowsOtherTypeParameterInScope(escapedName, context, type) {
      const result = resolveName(
        context.enclosingDeclaration,
        escapedName,
        788968 /* Type */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      );
      if (result && result.flags & 262144 /* TypeParameter */) {
        return result !== type.symbol;
      }
      return false;
    }
    function typeParameterToName(type, context) {
      var _a, _b, _c, _d;
      if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
        const cached = context.typeParameterNames.get(getTypeId(type));
        if (cached) {
          return cached;
        }
      }
      let result = symbolToName(
        type.symbol,
        context,
        788968 /* Type */,
        /*expectsIdentifier*/
        true
      );
      if (!(result.kind & 80 /* Identifier */)) {
        return factory.createIdentifier("(Missing type parameter)");
      }
      const decl = (_b = (_a = type.symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b[0];
      if (decl && isTypeParameterDeclaration(decl)) {
        result = setTextRange2(context, result, decl.name);
      }
      if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
        const rawtext = result.escapedText;
        let i = ((_c = context.typeParameterNamesByTextNextNameCount) == null ? void 0 : _c.get(rawtext)) || 0;
        let text = rawtext;
        while (((_d = context.typeParameterNamesByText) == null ? void 0 : _d.has(text)) || typeParameterShadowsOtherTypeParameterInScope(text, context, type)) {
          i++;
          text = `${rawtext}_${i}`;
        }
        if (text !== rawtext) {
          const typeArguments = getIdentifierTypeArguments(result);
          result = factory.createIdentifier(text);
          setIdentifierTypeArguments(result, typeArguments);
        }
        if (context.mustCreateTypeParametersNamesLookups) {
          context.mustCreateTypeParametersNamesLookups = false;
          context.typeParameterNames = new Map(context.typeParameterNames);
          context.typeParameterNamesByTextNextNameCount = new Map(context.typeParameterNamesByTextNextNameCount);
          context.typeParameterNamesByText = new Set(context.typeParameterNamesByText);
        }
        context.typeParameterNamesByTextNextNameCount.set(rawtext, i);
        context.typeParameterNames.set(getTypeId(type), result);
        context.typeParameterNamesByText.add(text);
      }
      return result;
    }
    function symbolToName(symbol, context, meaning, expectsIdentifier) {
      const chain = lookupSymbolChain(symbol, context, meaning);
      if (expectsIdentifier && chain.length !== 1 && !context.encounteredError && !(context.flags & 65536 /* AllowQualifiedNameInPlaceOfIdentifier */)) {
        context.encounteredError = true;
      }
      return createEntityNameFromSymbolChain(chain, chain.length - 1);
      function createEntityNameFromSymbolChain(chain2, index) {
        const typeParameterNodes = lookupTypeParameterNodes(chain2, index, context);
        const symbol2 = chain2[index];
        if (index === 0) {
          context.flags |= 16777216 /* InInitialEntityName */;
        }
        const symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
        if (index === 0) {
          context.flags ^= 16777216 /* InInitialEntityName */;
        }
        const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */);
        if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
        identifier.symbol = symbol2;
        return index > 0 ? factory.createQualifiedName(createEntityNameFromSymbolChain(chain2, index - 1), identifier) : identifier;
      }
    }
    function symbolToExpression(symbol, context, meaning) {
      const chain = lookupSymbolChain(symbol, context, meaning);
      return createExpressionFromSymbolChain(chain, chain.length - 1);
      function createExpressionFromSymbolChain(chain2, index) {
        const typeParameterNodes = lookupTypeParameterNodes(chain2, index, context);
        const symbol2 = chain2[index];
        if (index === 0) {
          context.flags |= 16777216 /* InInitialEntityName */;
        }
        let symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
        if (index === 0) {
          context.flags ^= 16777216 /* InInitialEntityName */;
        }
        let firstChar = symbolName2.charCodeAt(0);
        if (isSingleOrDoubleQuote(firstChar) && some(symbol2.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
          return factory.createStringLiteral(getSpecifierForModuleSymbol(symbol2, context));
        }
        if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) {
          const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */);
          if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
          identifier.symbol = symbol2;
          return index > 0 ? factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain2, index - 1), identifier) : identifier;
        } else {
          if (firstChar === 91 /* openBracket */) {
            symbolName2 = symbolName2.substring(1, symbolName2.length - 1);
            firstChar = symbolName2.charCodeAt(0);
          }
          let expression;
          if (isSingleOrDoubleQuote(firstChar) && !(symbol2.flags & 8 /* EnumMember */)) {
            expression = factory.createStringLiteral(stripQuotes(symbolName2).replace(/\\./g, (s) => s.substring(1)), firstChar === 39 /* singleQuote */);
          } else if ("" + +symbolName2 === symbolName2) {
            expression = factory.createNumericLiteral(+symbolName2);
          }
          if (!expression) {
            const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */);
            if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
            identifier.symbol = symbol2;
            expression = identifier;
          }
          return factory.createElementAccessExpression(createExpressionFromSymbolChain(chain2, index - 1), expression);
        }
      }
    }
    function isStringNamed(d) {
      const name = getNameOfDeclaration(d);
      if (!name) {
        return false;
      }
      if (isComputedPropertyName(name)) {
        const type = checkExpression(name.expression);
        return !!(type.flags & 402653316 /* StringLike */);
      }
      if (isElementAccessExpression(name)) {
        const type = checkExpression(name.argumentExpression);
        return !!(type.flags & 402653316 /* StringLike */);
      }
      return isStringLiteral(name);
    }
    function isSingleQuotedStringNamed(d) {
      const name = getNameOfDeclaration(d);
      return !!(name && isStringLiteral(name) && (name.singleQuote || !nodeIsSynthesized(name) && startsWith(getTextOfNode(
        name,
        /*includeTrivia*/
        false
      ), "'")));
    }
    function getPropertyNameNodeForSymbol(symbol, context) {
      const stringNamed = !!length(symbol.declarations) && every(symbol.declarations, isStringNamed);
      const singleQuote = !!length(symbol.declarations) && every(symbol.declarations, isSingleQuotedStringNamed);
      const isMethod = !!(symbol.flags & 8192 /* Method */);
      const fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed, isMethod);
      if (fromNameType) {
        return fromNameType;
      }
      const rawName = unescapeLeadingUnderscores(symbol.escapedName);
      return createPropertyNameNodeForIdentifierOrLiteral(rawName, getEmitScriptTarget(compilerOptions), singleQuote, stringNamed, isMethod);
    }
    function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed, isMethod) {
      const nameType = getSymbolLinks(symbol).nameType;
      if (nameType) {
        if (nameType.flags & 384 /* StringOrNumberLiteral */) {
          const name = "" + nameType.value;
          if (!isIdentifierText(name, getEmitScriptTarget(compilerOptions)) && (stringNamed || !isNumericLiteralName(name))) {
            return factory.createStringLiteral(name, !!singleQuote);
          }
          if (isNumericLiteralName(name) && startsWith(name, "-")) {
            return factory.createComputedPropertyName(factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-name)));
          }
          return createPropertyNameNodeForIdentifierOrLiteral(name, getEmitScriptTarget(compilerOptions), singleQuote, stringNamed, isMethod);
        }
        if (nameType.flags & 8192 /* UniqueESSymbol */) {
          return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
        }
      }
    }
    function cloneNodeBuilderContext(context) {
      const oldMustCreateTypeParameterSymbolList = context.mustCreateTypeParameterSymbolList;
      const oldMustCreateTypeParametersNamesLookups = context.mustCreateTypeParametersNamesLookups;
      context.mustCreateTypeParameterSymbolList = true;
      context.mustCreateTypeParametersNamesLookups = true;
      const oldTypeParameterNames = context.typeParameterNames;
      const oldTypeParameterNamesByText = context.typeParameterNamesByText;
      const oldTypeParameterNamesByTextNextNameCount = context.typeParameterNamesByTextNextNameCount;
      const oldTypeParameterSymbolList = context.typeParameterSymbolList;
      return () => {
        context.typeParameterNames = oldTypeParameterNames;
        context.typeParameterNamesByText = oldTypeParameterNamesByText;
        context.typeParameterNamesByTextNextNameCount = oldTypeParameterNamesByTextNextNameCount;
        context.typeParameterSymbolList = oldTypeParameterSymbolList;
        context.mustCreateTypeParameterSymbolList = oldMustCreateTypeParameterSymbolList;
        context.mustCreateTypeParametersNamesLookups = oldMustCreateTypeParametersNamesLookups;
      };
    }
    function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
      return symbol.declarations && find(symbol.declarations, (s) => !!getNonlocalEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!findAncestor(s, (n) => n === enclosingDeclaration)));
    }
    function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
      if (!(getObjectFlags(type) & 4 /* Reference */)) return true;
      if (!isTypeReferenceNode(existing)) return true;
      void getTypeFromTypeReference(existing);
      const symbol = getNodeLinks(existing).resolvedSymbol;
      const existingTarget = symbol && getDeclaredTypeOfSymbol(symbol);
      if (!existingTarget || existingTarget !== type.target) return true;
      return length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
    }
    function getEnclosingDeclarationIgnoringFakeScope(enclosingDeclaration) {
      while (getNodeLinks(enclosingDeclaration).fakeScopeForSignatureDeclaration) {
        enclosingDeclaration = enclosingDeclaration.parent;
      }
      return enclosingDeclaration;
    }
    function serializeInferredTypeForDeclaration(symbol, context, type) {
      if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, (d) => getSourceFileOfNode(d) === context.enclosingFile))) {
        context.flags |= 1048576 /* AllowUniqueESSymbolType */;
      }
      const result = typeToTypeNodeHelper(type, context);
      return result;
    }
    function serializeTypeForDeclaration(context, declaration, type, symbol) {
      var _a;
      let result;
      const addUndefinedForParameter = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration, context.enclosingDeclaration);
      const decl = declaration ?? symbol.valueDeclaration ?? getDeclarationWithTypeAnnotation(symbol) ?? ((_a = symbol.declarations) == null ? void 0 : _a[0]);
      if (decl) {
        if (isAccessor(decl)) {
          result = syntacticNodeBuilder.serializeTypeOfAccessor(decl, symbol, context);
        } else if (hasInferredType(decl) && !nodeIsSynthesized(decl) && !(getObjectFlags(type) & 196608 /* RequiresWidening */)) {
          const restore = addSymbolTypeToContext(context, symbol, type);
          result = syntacticNodeBuilder.serializeTypeOfDeclaration(decl, symbol, context);
          restore();
        }
      }
      if (!result) {
        if (addUndefinedForParameter) {
          type = getOptionalType(type);
        }
        result = serializeInferredTypeForDeclaration(symbol, context, type);
      }
      return result ?? factory.createKeywordTypeNode(133 /* AnyKeyword */);
    }
    function typeNodeIsEquivalentToType(annotatedDeclaration, type, typeFromTypeNode) {
      if (typeFromTypeNode === type) {
        return true;
      }
      if (!annotatedDeclaration) {
        return false;
      }
      if ((isPropertySignature(annotatedDeclaration) || isPropertyDeclaration(annotatedDeclaration)) && annotatedDeclaration.questionToken) {
        return getTypeWithFacts(type, 524288 /* NEUndefined */) === typeFromTypeNode;
      }
      if (isParameter(annotatedDeclaration) && hasEffectiveQuestionToken(annotatedDeclaration)) {
        return getTypeWithFacts(type, 524288 /* NEUndefined */) === typeFromTypeNode;
      }
      return false;
    }
    function serializeReturnTypeForSignature(context, signature) {
      const suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
      const restoreFlags = saveRestoreFlags(context);
      if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */;
      let returnTypeNode;
      const returnType = getReturnTypeOfSignature(signature);
      if (!(suppressAny && isTypeAny(returnType))) {
        if (signature.declaration && !nodeIsSynthesized(signature.declaration)) {
          const declarationSymbol = getSymbolOfDeclaration(signature.declaration);
          const restore = addSymbolTypeToContext(context, declarationSymbol, returnType);
          returnTypeNode = syntacticNodeBuilder.serializeReturnTypeForSignature(signature.declaration, declarationSymbol, context);
          restore();
        }
        if (!returnTypeNode) {
          returnTypeNode = serializeInferredReturnTypeForSignature(context, signature, returnType);
        }
      }
      if (!returnTypeNode && !suppressAny) {
        returnTypeNode = factory.createKeywordTypeNode(133 /* AnyKeyword */);
      }
      restoreFlags();
      return returnTypeNode;
    }
    function serializeInferredReturnTypeForSignature(context, signature, returnType) {
      const oldSuppressReportInferenceFallback = context.suppressReportInferenceFallback;
      context.suppressReportInferenceFallback = true;
      const typePredicate = getTypePredicateOfSignature(signature);
      const returnTypeNode = typePredicate ? typePredicateToTypePredicateNodeHelper(context.mapper ? instantiateTypePredicate(typePredicate, context.mapper) : typePredicate, context) : typeToTypeNodeHelper(returnType, context);
      context.suppressReportInferenceFallback = oldSuppressReportInferenceFallback;
      return returnTypeNode;
    }
    function trackExistingEntityName(node, context, enclosingDeclaration = context.enclosingDeclaration) {
      let introducesError = false;
      const leftmost = getFirstIdentifier(node);
      if (isInJSFile(node) && (isExportsIdentifier(leftmost) || isModuleExportsAccessExpression(leftmost.parent) || isQualifiedName(leftmost.parent) && isModuleIdentifier(leftmost.parent.left) && isExportsIdentifier(leftmost.parent.right))) {
        introducesError = true;
        return { introducesError, node };
      }
      const meaning = getMeaningOfEntityNameReference(node);
      let sym;
      if (isThisIdentifier(leftmost)) {
        sym = getSymbolOfDeclaration(getThisContainer(
          leftmost,
          /*includeArrowFunctions*/
          false,
          /*includeClassComputedPropertyName*/
          false
        ));
        if (isSymbolAccessible(
          sym,
          leftmost,
          meaning,
          /*shouldComputeAliasesToMakeVisible*/
          false
        ).accessibility !== 0 /* Accessible */) {
          introducesError = true;
          context.tracker.reportInaccessibleThisError();
        }
        return { introducesError, node: attachSymbolToLeftmostIdentifier(node) };
      }
      sym = resolveEntityName(
        leftmost,
        meaning,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true
      );
      if (context.enclosingDeclaration && !(sym && sym.flags & 262144 /* TypeParameter */)) {
        sym = getExportSymbolOfValueSymbolIfExported(sym);
        const symAtLocation = resolveEntityName(
          leftmost,
          meaning,
          /*ignoreErrors*/
          true,
          /*dontResolveAlias*/
          true,
          context.enclosingDeclaration
        );
        if (
          // Check for unusable parameters symbols
          symAtLocation === unknownSymbol || // If the symbol is not found, but was not found in the original scope either we probably have an error, don't reuse the node
          symAtLocation === void 0 && sym !== void 0 || // If the symbol is found both in declaration scope and in current scope then it should point to the same reference
          symAtLocation && sym && !getSymbolIfSameReference(getExportSymbolOfValueSymbolIfExported(symAtLocation), sym)
        ) {
          if (symAtLocation !== unknownSymbol) {
            context.tracker.reportInferenceFallback(node);
          }
          introducesError = true;
          return { introducesError, node, sym };
        } else {
          sym = symAtLocation;
        }
      }
      if (sym) {
        if (sym.flags & 1 /* FunctionScopedVariable */ && sym.valueDeclaration) {
          if (isPartOfParameterDeclaration(sym.valueDeclaration) || isJSDocParameterTag(sym.valueDeclaration)) {
            return { introducesError, node: attachSymbolToLeftmostIdentifier(node) };
          }
        }
        if (!(sym.flags & 262144 /* TypeParameter */) && // Type parameters are visible in the current context if they are are resolvable
        !isDeclarationName(node) && isSymbolAccessible(
          sym,
          enclosingDeclaration,
          meaning,
          /*shouldComputeAliasesToMakeVisible*/
          false
        ).accessibility !== 0 /* Accessible */) {
          context.tracker.reportInferenceFallback(node);
          introducesError = true;
        } else {
          context.tracker.trackSymbol(sym, enclosingDeclaration, meaning);
        }
        return { introducesError, node: attachSymbolToLeftmostIdentifier(node) };
      }
      return { introducesError, node };
      function attachSymbolToLeftmostIdentifier(node2) {
        if (node2 === leftmost) {
          const type = getDeclaredTypeOfSymbol(sym);
          const name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(type, context) : factory.cloneNode(node2);
          name.symbol = sym;
          return setTextRange2(context, setEmitFlags(name, 16777216 /* NoAsciiEscaping */), node2);
        }
        const updated = visitEachChild(
          node2,
          (c) => attachSymbolToLeftmostIdentifier(c),
          /*context*/
          void 0
        );
        if (updated !== node2) {
          setTextRange2(context, updated, node2);
        }
        return updated;
      }
    }
    function serializeTypeName(context, node, isTypeOf, typeArguments) {
      const meaning = isTypeOf ? 111551 /* Value */ : 788968 /* Type */;
      const symbol = resolveEntityName(
        node,
        meaning,
        /*ignoreErrors*/
        true
      );
      if (!symbol) return void 0;
      const resolvedSymbol = symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol;
      if (isSymbolAccessible(
        symbol,
        context.enclosingDeclaration,
        meaning,
        /*shouldComputeAliasesToMakeVisible*/
        false
      ).accessibility !== 0 /* Accessible */) return void 0;
      return symbolToTypeNode(resolvedSymbol, context, meaning, typeArguments);
    }
    function canReuseTypeNode(context, existing) {
      const type = getTypeFromTypeNode2(
        context,
        existing,
        /*noMappedTypes*/
        true
      );
      if (!type) {
        return false;
      }
      if (isInJSFile(existing)) {
        if (isLiteralImportTypeNode(existing)) {
          void getTypeFromImportTypeNode(existing);
          const nodeSymbol = getNodeLinks(existing).resolvedSymbol;
          return !nodeSymbol || !// The import type resolved using jsdoc fallback logic
          (!existing.isTypeOf && !(nodeSymbol.flags & 788968 /* Type */) || // The import type had type arguments autofilled by js fallback logic
          !(length(existing.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))));
        }
      }
      if (isTypeReferenceNode(existing)) {
        if (isConstTypeReference(existing)) return false;
        const symbol = getNodeLinks(existing).resolvedSymbol;
        if (!symbol) return false;
        if (symbol.flags & 262144 /* TypeParameter */) {
          const declaredType = getDeclaredTypeOfSymbol(symbol);
          return !(context.mapper && getMappedType(declaredType, context.mapper) !== declaredType);
        }
        if (isInJSDoc(existing)) {
          return existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) && !getIntendedTypeFromJSDocTypeReference(existing) && !!(symbol.flags & 788968 /* Type */);
        }
      }
      if (isTypeOperatorNode(existing) && existing.operator === 158 /* UniqueKeyword */ && existing.type.kind === 155 /* SymbolKeyword */) {
        const effectiveEnclosingContext = context.enclosingDeclaration && getEnclosingDeclarationIgnoringFakeScope(context.enclosingDeclaration);
        return !!findAncestor(existing, (n) => n === effectiveEnclosingContext);
      }
      return true;
    }
    function serializeExistingTypeNode(context, typeNode, addUndefined) {
      const type = getTypeFromTypeNode2(context, typeNode);
      if (addUndefined && !someType(type, (t) => !!(t.flags & 32768 /* Undefined */)) && canReuseTypeNode(context, typeNode)) {
        const clone = syntacticNodeBuilder.tryReuseExistingTypeNode(context, typeNode);
        if (clone) {
          return factory.createUnionTypeNode([clone, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]);
        }
      }
      return typeToTypeNodeHelper(type, context);
    }
    function symbolTableToDeclarationStatements(symbolTable, context) {
      var _a;
      const serializePropertySymbolForClass = makeSerializePropertySymbol(
        factory.createPropertyDeclaration,
        174 /* MethodDeclaration */,
        /*useAccessors*/
        true
      );
      const serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(
        (mods, name, question, type) => factory.createPropertySignature(mods, name, question, type),
        173 /* MethodSignature */,
        /*useAccessors*/
        false
      );
      const enclosingDeclaration = context.enclosingDeclaration;
      let results = [];
      const visitedSymbols = /* @__PURE__ */ new Set();
      const deferredPrivatesStack = [];
      const oldcontext = context;
      context = {
        ...oldcontext,
        usedSymbolNames: new Set(oldcontext.usedSymbolNames),
        remappedSymbolNames: /* @__PURE__ */ new Map(),
        remappedSymbolReferences: new Map((_a = oldcontext.remappedSymbolReferences) == null ? void 0 : _a.entries()),
        tracker: void 0
      };
      const tracker = {
        ...oldcontext.tracker.inner,
        trackSymbol: (sym, decl, meaning) => {
          var _a2, _b;
          if ((_a2 = context.remappedSymbolNames) == null ? void 0 : _a2.has(getSymbolId(sym))) return false;
          const accessibleResult = isSymbolAccessible(
            sym,
            decl,
            meaning,
            /*shouldComputeAliasesToMakeVisible*/
            false
          );
          if (accessibleResult.accessibility === 0 /* Accessible */) {
            const chain = lookupSymbolChainWorker(sym, context, meaning);
            if (!(sym.flags & 4 /* Property */)) {
              const root = chain[0];
              const contextFile = getSourceFileOfNode(oldcontext.enclosingDeclaration);
              if (some(root.declarations, (d) => getSourceFileOfNode(d) === contextFile)) {
                includePrivateSymbol(root);
              }
            }
          } else if ((_b = oldcontext.tracker.inner) == null ? void 0 : _b.trackSymbol) {
            return oldcontext.tracker.inner.trackSymbol(sym, decl, meaning);
          }
          return false;
        }
      };
      context.tracker = new SymbolTrackerImpl(context, tracker, oldcontext.tracker.moduleResolverHost);
      forEachEntry(symbolTable, (symbol, name) => {
        const baseName = unescapeLeadingUnderscores(name);
        void getInternalSymbolName(symbol, baseName);
      });
      let addingDeclare = !context.bundled;
      const exportEquals = symbolTable.get("export=" /* ExportEquals */);
      if (exportEquals && symbolTable.size > 1 && exportEquals.flags & (2097152 /* Alias */ | 1536 /* Module */)) {
        symbolTable = createSymbolTable();
        symbolTable.set("export=" /* ExportEquals */, exportEquals);
      }
      visitSymbolTable(symbolTable);
      return mergeRedundantStatements(results);
      function isIdentifierAndNotUndefined(node) {
        return !!node && node.kind === 80 /* Identifier */;
      }
      function getNamesOfDeclaration(statement) {
        if (isVariableStatement(statement)) {
          return filter(map(statement.declarationList.declarations, getNameOfDeclaration), isIdentifierAndNotUndefined);
        }
        return filter([getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
      }
      function flattenExportAssignedNamespace(statements) {
        const exportAssignment = find(statements, isExportAssignment);
        const nsIndex = findIndex(statements, isModuleDeclaration);
        let ns = nsIndex !== -1 ? statements[nsIndex] : void 0;
        if (ns && exportAssignment && exportAssignment.isExportEquals && isIdentifier(exportAssignment.expression) && isIdentifier(ns.name) && idText(ns.name) === idText(exportAssignment.expression) && ns.body && isModuleBlock(ns.body)) {
          const excessExports = filter(statements, (s) => !!(getEffectiveModifierFlags(s) & 32 /* Export */));
          const name = ns.name;
          let body = ns.body;
          if (length(excessExports)) {
            ns = factory.updateModuleDeclaration(
              ns,
              ns.modifiers,
              ns.name,
              body = factory.updateModuleBlock(
                body,
                factory.createNodeArray([
                  ...ns.body.statements,
                  factory.createExportDeclaration(
                    /*modifiers*/
                    void 0,
                    /*isTypeOnly*/
                    false,
                    factory.createNamedExports(map(flatMap(excessExports, (e) => getNamesOfDeclaration(e)), (id) => factory.createExportSpecifier(
                      /*isTypeOnly*/
                      false,
                      /*propertyName*/
                      void 0,
                      id
                    ))),
                    /*moduleSpecifier*/
                    void 0
                  )
                ])
              )
            );
            statements = [...statements.slice(0, nsIndex), ns, ...statements.slice(nsIndex + 1)];
          }
          if (!find(statements, (s) => s !== ns && nodeHasName(s, name))) {
            results = [];
            const mixinExportFlag = !some(body.statements, (s) => hasSyntacticModifier(s, 32 /* Export */) || isExportAssignment(s) || isExportDeclaration(s));
            forEach(body.statements, (s) => {
              addResult(s, mixinExportFlag ? 32 /* Export */ : 0 /* None */);
            });
            statements = [...filter(statements, (s) => s !== ns && s !== exportAssignment), ...results];
          }
        }
        return statements;
      }
      function mergeExportDeclarations(statements) {
        const exports2 = filter(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause));
        if (length(exports2) > 1) {
          const nonExports = filter(statements, (d) => !isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause);
          statements = [
            ...nonExports,
            factory.createExportDeclaration(
              /*modifiers*/
              void 0,
              /*isTypeOnly*/
              false,
              factory.createNamedExports(flatMap(exports2, (e) => cast(e.exportClause, isNamedExports).elements)),
              /*moduleSpecifier*/
              void 0
            )
          ];
        }
        const reexports = filter(statements, (d) => isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause));
        if (length(reexports) > 1) {
          const groups = group(reexports, (decl) => isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">");
          if (groups.length !== reexports.length) {
            for (const group2 of groups) {
              if (group2.length > 1) {
                statements = [
                  ...filter(statements, (s) => !group2.includes(s)),
                  factory.createExportDeclaration(
                    /*modifiers*/
                    void 0,
                    /*isTypeOnly*/
                    false,
                    factory.createNamedExports(flatMap(group2, (e) => cast(e.exportClause, isNamedExports).elements)),
                    group2[0].moduleSpecifier
                  )
                ];
              }
            }
          }
        }
        return statements;
      }
      function inlineExportModifiers(statements) {
        const index = findIndex(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !d.attributes && !!d.exportClause && isNamedExports(d.exportClause));
        if (index >= 0) {
          const exportDecl = statements[index];
          const replacements = mapDefined(exportDecl.exportClause.elements, (e) => {
            if (!e.propertyName && e.name.kind !== 11 /* StringLiteral */) {
              const name = e.name;
              const indices = indicesOf(statements);
              const associatedIndices = filter(indices, (i) => nodeHasName(statements[i], name));
              if (length(associatedIndices) && every(associatedIndices, (i) => canHaveExportModifier(statements[i]))) {
                for (const index2 of associatedIndices) {
                  statements[index2] = addExportModifier(statements[index2]);
                }
                return void 0;
              }
            }
            return e;
          });
          if (!length(replacements)) {
            orderedRemoveItemAt(statements, index);
          } else {
            statements[index] = factory.updateExportDeclaration(
              exportDecl,
              exportDecl.modifiers,
              exportDecl.isTypeOnly,
              factory.updateNamedExports(
                exportDecl.exportClause,
                replacements
              ),
              exportDecl.moduleSpecifier,
              exportDecl.attributes
            );
          }
        }
        return statements;
      }
      function mergeRedundantStatements(statements) {
        statements = flattenExportAssignedNamespace(statements);
        statements = mergeExportDeclarations(statements);
        statements = inlineExportModifiers(statements);
        if (enclosingDeclaration && (isSourceFile(enclosingDeclaration) && isExternalOrCommonJsModule(enclosingDeclaration) || isModuleDeclaration(enclosingDeclaration)) && (!some(statements, isExternalModuleIndicator) || !hasScopeMarker(statements) && some(statements, needsScopeMarker))) {
          statements.push(createEmptyExports(factory));
        }
        return statements;
      }
      function addExportModifier(node) {
        const flags = (getEffectiveModifierFlags(node) | 32 /* Export */) & ~128 /* Ambient */;
        return factory.replaceModifiers(node, flags);
      }
      function removeExportModifier(node) {
        const flags = getEffectiveModifierFlags(node) & ~32 /* Export */;
        return factory.replaceModifiers(node, flags);
      }
      function visitSymbolTable(symbolTable2, suppressNewPrivateContext, propertyAsAlias) {
        if (!suppressNewPrivateContext) {
          deferredPrivatesStack.push(/* @__PURE__ */ new Map());
        }
        symbolTable2.forEach((symbol) => {
          serializeSymbol(
            symbol,
            /*isPrivate*/
            false,
            !!propertyAsAlias
          );
        });
        if (!suppressNewPrivateContext) {
          deferredPrivatesStack[deferredPrivatesStack.length - 1].forEach((symbol) => {
            serializeSymbol(
              symbol,
              /*isPrivate*/
              true,
              !!propertyAsAlias
            );
          });
          deferredPrivatesStack.pop();
        }
      }
      function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
        void getPropertiesOfType(getTypeOfSymbol(symbol));
        const visitedSym = getMergedSymbol(symbol);
        if (visitedSymbols.has(getSymbolId(visitedSym))) {
          return;
        }
        visitedSymbols.add(getSymbolId(visitedSym));
        const skipMembershipCheck = !isPrivate;
        if (skipMembershipCheck || !!length(symbol.declarations) && some(symbol.declarations, (d) => !!findAncestor(d, (n) => n === enclosingDeclaration))) {
          const scopeCleanup = cloneNodeBuilderContext(context);
          context.tracker.pushErrorFallbackNode(find(symbol.declarations, (d) => getSourceFileOfNode(d) === context.enclosingFile));
          serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
          context.tracker.popErrorFallbackNode();
          scopeCleanup();
        }
      }
      function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias, escapedSymbolName = symbol.escapedName) {
        var _a2, _b, _c, _d, _e, _f;
        const symbolName2 = unescapeLeadingUnderscores(escapedSymbolName);
        const isDefault = escapedSymbolName === "default" /* Default */;
        if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && isStringANonContextualKeyword(symbolName2) && !isDefault) {
          context.encounteredError = true;
          return;
        }
        let needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */ || symbol.flags & 16 /* Function */ && length(getPropertiesOfType(getTypeOfSymbol(symbol)))) && !(symbol.flags & 2097152 /* Alias */);
        let needsExportDeclaration = !needsPostExportDefault && !isPrivate && isStringANonContextualKeyword(symbolName2) && !isDefault;
        if (needsPostExportDefault || needsExportDeclaration) {
          isPrivate = true;
        }
        const modifierFlags = (!isPrivate ? 32 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 2048 /* Default */ : 0);
        const isConstMergedWithNS = symbol.flags & 1536 /* Module */ && symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && escapedSymbolName !== "export=" /* ExportEquals */;
        const isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
        if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
          serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
        }
        if (symbol.flags & 524288 /* TypeAlias */) {
          serializeTypeAlias(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */ | 98304 /* Accessor */) && escapedSymbolName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) {
          if (propertyAsAlias) {
            const createdExport = serializeMaybeAliasAssignment(symbol);
            if (createdExport) {
              needsExportDeclaration = false;
              needsPostExportDefault = false;
            }
          } else {
            const type = getTypeOfSymbol(symbol);
            const localName = getInternalSymbolName(symbol, symbolName2);
            if (type.symbol && type.symbol !== symbol && type.symbol.flags & 16 /* Function */ && some(type.symbol.declarations, isFunctionExpressionOrArrowFunction) && (((_a2 = type.symbol.members) == null ? void 0 : _a2.size) || ((_b = type.symbol.exports) == null ? void 0 : _b.size))) {
              if (!context.remappedSymbolReferences) {
                context.remappedSymbolReferences = /* @__PURE__ */ new Map();
              }
              context.remappedSymbolReferences.set(getSymbolId(type.symbol), symbol);
              serializeSymbolWorker(type.symbol, isPrivate, propertyAsAlias, escapedSymbolName);
              context.remappedSymbolReferences.delete(getSymbolId(type.symbol));
            } else if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
              serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
            } else {
              const flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? ((_c = symbol.parent) == null ? void 0 : _c.valueDeclaration) && isSourceFile((_d = symbol.parent) == null ? void 0 : _d.valueDeclaration) ? 2 /* Const */ : void 0 : isConstantVariable(symbol) ? 2 /* Const */ : 1 /* Let */;
              const name = needsPostExportDefault || !(symbol.flags & 4 /* Property */) ? localName : getUnusedName(localName, symbol);
              let textRange = symbol.declarations && find(symbol.declarations, (d) => isVariableDeclaration(d));
              if (textRange && isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
                textRange = textRange.parent.parent;
              }
              const propertyAccessRequire = (_e = symbol.declarations) == null ? void 0 : _e.find(isPropertyAccessExpression);
              if (propertyAccessRequire && isBinaryExpression(propertyAccessRequire.parent) && isIdentifier(propertyAccessRequire.parent.right) && ((_f = type.symbol) == null ? void 0 : _f.valueDeclaration) && isSourceFile(type.symbol.valueDeclaration)) {
                const alias = localName === propertyAccessRequire.parent.right.escapedText ? void 0 : propertyAccessRequire.parent.right;
                addResult(
                  factory.createExportDeclaration(
                    /*modifiers*/
                    void 0,
                    /*isTypeOnly*/
                    false,
                    factory.createNamedExports([factory.createExportSpecifier(
                      /*isTypeOnly*/
                      false,
                      alias,
                      localName
                    )])
                  ),
                  0 /* None */
                );
                context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* Value */);
              } else {
                const statement = setTextRange2(
                  context,
                  factory.createVariableStatement(
                    /*modifiers*/
                    void 0,
                    factory.createVariableDeclarationList([
                      factory.createVariableDeclaration(
                        name,
                        /*exclamationToken*/
                        void 0,
                        serializeTypeForDeclaration(
                          context,
                          /*declaration*/
                          void 0,
                          type,
                          symbol
                        )
                      )
                    ], flags)
                  ),
                  textRange
                );
                addResult(statement, name !== localName ? modifierFlags & ~32 /* Export */ : modifierFlags);
                if (name !== localName && !isPrivate) {
                  addResult(
                    factory.createExportDeclaration(
                      /*modifiers*/
                      void 0,
                      /*isTypeOnly*/
                      false,
                      factory.createNamedExports([factory.createExportSpecifier(
                        /*isTypeOnly*/
                        false,
                        name,
                        localName
                      )])
                    ),
                    0 /* None */
                  );
                  needsExportDeclaration = false;
                  needsPostExportDefault = false;
                }
              }
            }
          }
        }
        if (symbol.flags & 384 /* Enum */) {
          serializeEnum(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & 32 /* Class */) {
          if (symbol.flags & 4 /* Property */ && symbol.valueDeclaration && isBinaryExpression(symbol.valueDeclaration.parent) && isClassExpression(symbol.valueDeclaration.parent.right)) {
            serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
          } else {
            serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
          }
        }
        if (symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol)) || isConstMergedWithNSPrintableAsSignatureMerge) {
          serializeModule(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & 64 /* Interface */ && !(symbol.flags & 32 /* Class */)) {
          serializeInterface(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & 2097152 /* Alias */) {
          serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
        }
        if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
          serializeMaybeAliasAssignment(symbol);
        }
        if (symbol.flags & 8388608 /* ExportStar */) {
          if (symbol.declarations) {
            for (const node of symbol.declarations) {
              const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
              if (!resolvedModule) continue;
              addResult(factory.createExportDeclaration(
                /*modifiers*/
                void 0,
                /*isTypeOnly*/
                node.isTypeOnly,
                /*exportClause*/
                void 0,
                factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))
              ), 0 /* None */);
            }
          }
        }
        if (needsPostExportDefault) {
          addResult(factory.createExportAssignment(
            /*modifiers*/
            void 0,
            /*isExportEquals*/
            false,
            factory.createIdentifier(getInternalSymbolName(symbol, symbolName2))
          ), 0 /* None */);
        } else if (needsExportDeclaration) {
          addResult(
            factory.createExportDeclaration(
              /*modifiers*/
              void 0,
              /*isTypeOnly*/
              false,
              factory.createNamedExports([factory.createExportSpecifier(
                /*isTypeOnly*/
                false,
                getInternalSymbolName(symbol, symbolName2),
                symbolName2
              )])
            ),
            0 /* None */
          );
        }
      }
      function includePrivateSymbol(symbol) {
        if (some(symbol.declarations, isPartOfParameterDeclaration)) return;
        Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]);
        getUnusedName(unescapeLeadingUnderscores(symbol.escapedName), symbol);
        const isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !some(symbol.declarations, (d) => !!findAncestor(d, isExportDeclaration) || isNamespaceExport(d) || isImportEqualsDeclaration(d) && !isExternalModuleReference(d.moduleReference));
        deferredPrivatesStack[isExternalImportAlias ? 0 : deferredPrivatesStack.length - 1].set(getSymbolId(symbol), symbol);
      }
      function isExportingScope(enclosingDeclaration2) {
        return isSourceFile(enclosingDeclaration2) && (isExternalOrCommonJsModule(enclosingDeclaration2) || isJsonSourceFile(enclosingDeclaration2)) || isAmbientModule(enclosingDeclaration2) && !isGlobalScopeAugmentation(enclosingDeclaration2);
      }
      function addResult(node, additionalModifierFlags) {
        if (canHaveModifiers(node)) {
          let newModifierFlags = 0 /* None */;
          const enclosingDeclaration2 = context.enclosingDeclaration && (isJSDocTypeAlias(context.enclosingDeclaration) ? getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration);
          if (additionalModifierFlags & 32 /* Export */ && enclosingDeclaration2 && (isExportingScope(enclosingDeclaration2) || isModuleDeclaration(enclosingDeclaration2)) && canHaveExportModifier(node)) {
            newModifierFlags |= 32 /* Export */;
          }
          if (addingDeclare && !(newModifierFlags & 32 /* Export */) && (!enclosingDeclaration2 || !(enclosingDeclaration2.flags & 33554432 /* Ambient */)) && (isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isModuleDeclaration(node))) {
            newModifierFlags |= 128 /* Ambient */;
          }
          if (additionalModifierFlags & 2048 /* Default */ && (isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionDeclaration(node))) {
            newModifierFlags |= 2048 /* Default */;
          }
          if (newModifierFlags) {
            node = factory.replaceModifiers(node, newModifierFlags | getEffectiveModifierFlags(node));
          }
        }
        results.push(node);
      }
      function serializeTypeAlias(symbol, symbolName2, modifierFlags) {
        var _a2;
        const aliasType = getDeclaredTypeOfTypeAlias(symbol);
        const typeParams = getSymbolLinks(symbol).typeParameters;
        const typeParamDecls = map(typeParams, (p) => typeParameterToDeclaration(p, context));
        const jsdocAliasDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isJSDocTypeAlias);
        const commentText = getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : void 0);
        const restoreFlags = saveRestoreFlags(context);
        context.flags |= 8388608 /* InTypeAlias */;
        const oldEnclosingDecl = context.enclosingDeclaration;
        context.enclosingDeclaration = jsdocAliasDecl;
        const typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && syntacticNodeBuilder.tryReuseExistingTypeNode(context, jsdocAliasDecl.typeExpression.type) || typeToTypeNodeHelper(aliasType, context);
        addResult(
          setSyntheticLeadingComments(
            factory.createTypeAliasDeclaration(
              /*modifiers*/
              void 0,
              getInternalSymbolName(symbol, symbolName2),
              typeParamDecls,
              typeNode
            ),
            !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]
          ),
          modifierFlags
        );
        restoreFlags();
        context.enclosingDeclaration = oldEnclosingDecl;
      }
      function serializeInterface(symbol, symbolName2, modifierFlags) {
        const interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
        const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
        const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context));
        const baseTypes = getBaseTypes(interfaceType);
        const baseType = length(baseTypes) ? getIntersectionType(baseTypes) : void 0;
        const members = flatMap(getPropertiesOfType(interfaceType), (p) => serializePropertySymbolForInterface(p, baseType));
        const callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 179 /* CallSignature */);
        const constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 180 /* ConstructSignature */);
        const indexSignatures = serializeIndexSignatures(interfaceType, baseType);
        const heritageClauses = !length(baseTypes) ? void 0 : [factory.createHeritageClause(96 /* ExtendsKeyword */, mapDefined(baseTypes, (b) => trySerializeAsTypeReference(b, 111551 /* Value */)))];
        addResult(
          factory.createInterfaceDeclaration(
            /*modifiers*/
            void 0,
            getInternalSymbolName(symbol, symbolName2),
            typeParamDecls,
            heritageClauses,
            [...indexSignatures, ...constructSignatures, ...callSignatures, ...members]
          ),
          modifierFlags
        );
      }
      function getNamespaceMembersForSerialization(symbol) {
        let exports2 = arrayFrom(getExportsOfSymbol(symbol).values());
        const merged = getMergedSymbol(symbol);
        if (merged !== symbol) {
          const membersSet = new Set(exports2);
          for (const exported of getExportsOfSymbol(merged).values()) {
            if (!(getSymbolFlags(resolveSymbol(exported)) & 111551 /* Value */)) {
              membersSet.add(exported);
            }
          }
          exports2 = arrayFrom(membersSet);
        }
        return filter(exports2, (m) => isNamespaceMember(m) && isIdentifierText(m.escapedName, 99 /* ESNext */));
      }
      function isTypeOnlyNamespace(symbol) {
        return every(getNamespaceMembersForSerialization(symbol), (m) => !(getSymbolFlags(resolveSymbol(m)) & 111551 /* Value */));
      }
      function serializeModule(symbol, symbolName2, modifierFlags) {
        const members = getNamespaceMembersForSerialization(symbol);
        const locationMap = arrayToMultiMap(members, (m) => m.parent && m.parent === symbol ? "real" : "merged");
        const realMembers = locationMap.get("real") || emptyArray;
        const mergedMembers = locationMap.get("merged") || emptyArray;
        if (length(realMembers)) {
          const localName = getInternalSymbolName(symbol, symbolName2);
          serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
        }
        if (length(mergedMembers)) {
          const containingFile = getSourceFileOfNode(context.enclosingDeclaration);
          const localName = getInternalSymbolName(symbol, symbolName2);
          const nsBody = factory.createModuleBlock([factory.createExportDeclaration(
            /*modifiers*/
            void 0,
            /*isTypeOnly*/
            false,
            factory.createNamedExports(mapDefined(filter(mergedMembers, (n) => n.escapedName !== "export=" /* ExportEquals */), (s) => {
              var _a2, _b;
              const name = unescapeLeadingUnderscores(s.escapedName);
              const localName2 = getInternalSymbolName(s, name);
              const aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
              if (containingFile && (aliasDecl ? containingFile !== getSourceFileOfNode(aliasDecl) : !some(s.declarations, (d) => getSourceFileOfNode(d) === containingFile))) {
                (_b = (_a2 = context.tracker) == null ? void 0 : _a2.reportNonlocalAugmentation) == null ? void 0 : _b.call(_a2, containingFile, symbol, s);
                return void 0;
              }
              const target = aliasDecl && getTargetOfAliasDeclaration(
                aliasDecl,
                /*dontRecursivelyResolve*/
                true
              );
              includePrivateSymbol(target || s);
              const targetName = target ? getInternalSymbolName(target, unescapeLeadingUnderscores(target.escapedName)) : localName2;
              return factory.createExportSpecifier(
                /*isTypeOnly*/
                false,
                name === targetName ? void 0 : targetName,
                name
              );
            }))
          )]);
          addResult(
            factory.createModuleDeclaration(
              /*modifiers*/
              void 0,
              factory.createIdentifier(localName),
              nsBody,
              32 /* Namespace */
            ),
            0 /* None */
          );
        }
      }
      function serializeEnum(symbol, symbolName2, modifierFlags) {
        addResult(
          factory.createEnumDeclaration(
            factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 4096 /* Const */ : 0),
            getInternalSymbolName(symbol, symbolName2),
            map(filter(getPropertiesOfType(getTypeOfSymbol(symbol)), (p) => !!(p.flags & 8 /* EnumMember */)), (p) => {
              const initializedValue = p.declarations && p.declarations[0] && isEnumMember(p.declarations[0]) ? getConstantValue2(p.declarations[0]) : void 0;
              return factory.createEnumMember(
                unescapeLeadingUnderscores(p.escapedName),
                initializedValue === void 0 ? void 0 : typeof initializedValue === "string" ? factory.createStringLiteral(initializedValue) : factory.createNumericLiteral(initializedValue)
              );
            })
          ),
          modifierFlags
        );
      }
      function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
        const signatures = getSignaturesOfType(type, 0 /* Call */);
        for (const sig of signatures) {
          const decl = signatureToSignatureDeclarationHelper(sig, 262 /* FunctionDeclaration */, context, { name: factory.createIdentifier(localName) });
          addResult(setTextRange2(context, decl, getSignatureTextRangeLocation(sig)), modifierFlags);
        }
        if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
          const props = filter(getPropertiesOfType(type), isNamespaceMember);
          serializeAsNamespaceDeclaration(
            props,
            localName,
            modifierFlags,
            /*suppressNewPrivateContext*/
            true
          );
        }
      }
      function getSignatureTextRangeLocation(signature) {
        if (signature.declaration && signature.declaration.parent) {
          if (isBinaryExpression(signature.declaration.parent) && getAssignmentDeclarationKind(signature.declaration.parent) === 5 /* Property */) {
            return signature.declaration.parent;
          }
          if (isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) {
            return signature.declaration.parent.parent;
          }
        }
        return signature.declaration;
      }
      function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
        if (length(props)) {
          const localVsRemoteMap = arrayToMultiMap(props, (p) => !length(p.declarations) || some(p.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)) ? "local" : "remote");
          const localProps = localVsRemoteMap.get("local") || emptyArray;
          let fakespace = parseNodeFactory.createModuleDeclaration(
            /*modifiers*/
            void 0,
            factory.createIdentifier(localName),
            factory.createModuleBlock([]),
            32 /* Namespace */
          );
          setParent(fakespace, enclosingDeclaration);
          fakespace.locals = createSymbolTable(props);
          fakespace.symbol = props[0].parent;
          const oldResults = results;
          results = [];
          const oldAddingDeclare = addingDeclare;
          addingDeclare = false;
          const subcontext = { ...context, enclosingDeclaration: fakespace };
          const oldContext = context;
          context = subcontext;
          visitSymbolTable(
            createSymbolTable(localProps),
            suppressNewPrivateContext,
            /*propertyAsAlias*/
            true
          );
          context = oldContext;
          addingDeclare = oldAddingDeclare;
          const declarations = results;
          results = oldResults;
          const defaultReplaced = map(declarations, (d) => isExportAssignment(d) && !d.isExportEquals && isIdentifier(d.expression) ? factory.createExportDeclaration(
            /*modifiers*/
            void 0,
            /*isTypeOnly*/
            false,
            factory.createNamedExports([factory.createExportSpecifier(
              /*isTypeOnly*/
              false,
              d.expression,
              factory.createIdentifier("default" /* Default */)
            )])
          ) : d);
          const exportModifierStripped = every(defaultReplaced, (d) => hasSyntacticModifier(d, 32 /* Export */)) ? map(defaultReplaced, removeExportModifier) : defaultReplaced;
          fakespace = factory.updateModuleDeclaration(
            fakespace,
            fakespace.modifiers,
            fakespace.name,
            factory.createModuleBlock(exportModifierStripped)
          );
          addResult(fakespace, modifierFlags);
        }
      }
      function isNamespaceMember(p) {
        return !!(p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) || !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && isStatic(p.valueDeclaration) && isClassLike(p.valueDeclaration.parent));
      }
      function sanitizeJSDocImplements(clauses) {
        const result = mapDefined(clauses, (e) => {
          const oldEnclosing = context.enclosingDeclaration;
          context.enclosingDeclaration = e;
          let expr = e.expression;
          if (isEntityNameExpression(expr)) {
            if (isIdentifier(expr) && idText(expr) === "") {
              return cleanup(
                /*result*/
                void 0
              );
            }
            let introducesError;
            ({ introducesError, node: expr } = trackExistingEntityName(expr, context));
            if (introducesError) {
              return cleanup(
                /*result*/
                void 0
              );
            }
          }
          return cleanup(factory.createExpressionWithTypeArguments(
            expr,
            map(e.typeArguments, (a) => syntacticNodeBuilder.tryReuseExistingTypeNode(context, a) || typeToTypeNodeHelper(getTypeFromTypeNode2(context, a), context))
          ));
          function cleanup(result2) {
            context.enclosingDeclaration = oldEnclosing;
            return result2;
          }
        });
        if (result.length === clauses.length) {
          return result;
        }
        return void 0;
      }
      function serializeAsClass(symbol, localName, modifierFlags) {
        var _a2, _b;
        const originalDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isClassLike);
        const oldEnclosing = context.enclosingDeclaration;
        context.enclosingDeclaration = originalDecl || oldEnclosing;
        const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
        const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context));
        const classType = getTypeWithThisArgument(getDeclaredTypeOfClassOrInterface(symbol));
        const baseTypes = getBaseTypes(classType);
        const originalImplements = originalDecl && getEffectiveImplementsTypeNodes(originalDecl);
        const implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || mapDefined(getImplementsTypes(classType), serializeImplementedType);
        const staticType = getTypeOfSymbol(symbol);
        const isClass = !!((_b = staticType.symbol) == null ? void 0 : _b.valueDeclaration) && isClassLike(staticType.symbol.valueDeclaration);
        const staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType;
        const heritageClauses = [
          ...!length(baseTypes) ? [] : [factory.createHeritageClause(96 /* ExtendsKeyword */, map(baseTypes, (b) => serializeBaseType(b, staticBaseType, localName)))],
          ...!length(implementsExpressions) ? [] : [factory.createHeritageClause(119 /* ImplementsKeyword */, implementsExpressions)]
        ];
        const symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType));
        const publicSymbolProps = filter(symbolProps, (s) => {
          const valueDecl = s.valueDeclaration;
          return !!valueDecl && !(isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name));
        });
        const hasPrivateIdentifier = some(symbolProps, (s) => {
          const valueDecl = s.valueDeclaration;
          return !!valueDecl && isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name);
        });
        const privateProperties = hasPrivateIdentifier ? [factory.createPropertyDeclaration(
          /*modifiers*/
          void 0,
          factory.createPrivateIdentifier("#private"),
          /*questionOrExclamationToken*/
          void 0,
          /*type*/
          void 0,
          /*initializer*/
          void 0
        )] : emptyArray;
        const publicProperties = flatMap(publicSymbolProps, (p) => serializePropertySymbolForClass(
          p,
          /*isStatic*/
          false,
          baseTypes[0]
        ));
        const staticMembers = flatMap(
          filter(getPropertiesOfType(staticType), (p) => !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p)),
          (p) => serializePropertySymbolForClass(
            p,
            /*isStatic*/
            true,
            staticBaseType
          )
        );
        const isNonConstructableClassLikeInJsFile = !isClass && !!symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && !some(getSignaturesOfType(staticType, 1 /* Construct */));
        const constructors = isNonConstructableClassLikeInJsFile ? [factory.createConstructorDeclaration(
          factory.createModifiersFromModifierFlags(2 /* Private */),
          [],
          /*body*/
          void 0
        )] : serializeSignatures(1 /* Construct */, staticType, staticBaseType, 176 /* Constructor */);
        const indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
        context.enclosingDeclaration = oldEnclosing;
        addResult(
          setTextRange2(
            context,
            factory.createClassDeclaration(
              /*modifiers*/
              void 0,
              localName,
              typeParamDecls,
              heritageClauses,
              [...indexSignatures, ...staticMembers, ...constructors, ...publicProperties, ...privateProperties]
            ),
            symbol.declarations && filter(symbol.declarations, (d) => isClassDeclaration(d) || isClassExpression(d))[0]
          ),
          modifierFlags
        );
      }
      function getSomeTargetNameFromDeclarations(declarations) {
        return firstDefined(declarations, (d) => {
          if (isImportSpecifier(d) || isExportSpecifier(d)) {
            return moduleExportNameTextUnescaped(d.propertyName || d.name);
          }
          if (isBinaryExpression(d) || isExportAssignment(d)) {
            const expression = isExportAssignment(d) ? d.expression : d.right;
            if (isPropertyAccessExpression(expression)) {
              return idText(expression.name);
            }
          }
          if (isAliasSymbolDeclaration(d)) {
            const name = getNameOfDeclaration(d);
            if (name && isIdentifier(name)) {
              return idText(name);
            }
          }
          return void 0;
        });
      }
      function serializeAsAlias(symbol, localName, modifierFlags) {
        var _a2, _b, _c, _d, _e;
        const node = getDeclarationOfAliasSymbol(symbol);
        if (!node) return Debug.fail();
        const target = getMergedSymbol(getTargetOfAliasDeclaration(
          node,
          /*dontRecursivelyResolve*/
          true
        ));
        if (!target) {
          return;
        }
        let verbatimTargetName = isShorthandAmbientModuleSymbol(target) && getSomeTargetNameFromDeclarations(symbol.declarations) || unescapeLeadingUnderscores(target.escapedName);
        if (verbatimTargetName === "export=" /* ExportEquals */ && allowSyntheticDefaultImports) {
          verbatimTargetName = "default" /* Default */;
        }
        const targetName = getInternalSymbolName(target, verbatimTargetName);
        includePrivateSymbol(target);
        switch (node.kind) {
          case 208 /* BindingElement */:
            if (((_b = (_a2 = node.parent) == null ? void 0 : _a2.parent) == null ? void 0 : _b.kind) === 260 /* VariableDeclaration */) {
              const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context);
              const { propertyName } = node;
              addResult(
                factory.createImportDeclaration(
                  /*modifiers*/
                  void 0,
                  factory.createImportClause(
                    /*isTypeOnly*/
                    false,
                    /*name*/
                    void 0,
                    factory.createNamedImports([factory.createImportSpecifier(
                      /*isTypeOnly*/
                      false,
                      propertyName && isIdentifier(propertyName) ? factory.createIdentifier(idText(propertyName)) : void 0,
                      factory.createIdentifier(localName)
                    )])
                  ),
                  factory.createStringLiteral(specifier2),
                  /*attributes*/
                  void 0
                ),
                0 /* None */
              );
              break;
            }
            Debug.failBadSyntaxKind(((_c = node.parent) == null ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization");
            break;
          case 304 /* ShorthandPropertyAssignment */:
            if (((_e = (_d = node.parent) == null ? void 0 : _d.parent) == null ? void 0 : _e.kind) === 226 /* BinaryExpression */) {
              serializeExportSpecifier(
                unescapeLeadingUnderscores(symbol.escapedName),
                targetName
              );
            }
            break;
          case 260 /* VariableDeclaration */:
            if (isPropertyAccessExpression(node.initializer)) {
              const initializer = node.initializer;
              const uniqueName = factory.createUniqueName(localName);
              const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context);
              addResult(
                factory.createImportEqualsDeclaration(
                  /*modifiers*/
                  void 0,
                  /*isTypeOnly*/
                  false,
                  uniqueName,
                  factory.createExternalModuleReference(factory.createStringLiteral(specifier2))
                ),
                0 /* None */
              );
              addResult(
                factory.createImportEqualsDeclaration(
                  /*modifiers*/
                  void 0,
                  /*isTypeOnly*/
                  false,
                  factory.createIdentifier(localName),
                  factory.createQualifiedName(uniqueName, initializer.name)
                ),
                modifierFlags
              );
              break;
            }
          // else fall through and treat commonjs require just like import=
          case 271 /* ImportEqualsDeclaration */:
            if (target.escapedName === "export=" /* ExportEquals */ && some(target.declarations, (d) => isSourceFile(d) && isJsonSourceFile(d))) {
              serializeMaybeAliasAssignment(symbol);
              break;
            }
            const isLocalImport = !(target.flags & 512 /* ValueModule */) && !isVariableDeclaration(node);
            addResult(
              factory.createImportEqualsDeclaration(
                /*modifiers*/
                void 0,
                /*isTypeOnly*/
                false,
                factory.createIdentifier(localName),
                isLocalImport ? symbolToName(
                  target,
                  context,
                  -1 /* All */,
                  /*expectsIdentifier*/
                  false
                ) : factory.createExternalModuleReference(factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))
              ),
              isLocalImport ? modifierFlags : 0 /* None */
            );
            break;
          case 270 /* NamespaceExportDeclaration */:
            addResult(factory.createNamespaceExportDeclaration(idText(node.name)), 0 /* None */);
            break;
          case 273 /* ImportClause */: {
            const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context);
            const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.moduleSpecifier;
            const attributes = isImportDeclaration(node.parent) ? node.parent.attributes : void 0;
            const isTypeOnly = isJSDocImportTag(node.parent);
            addResult(
              factory.createImportDeclaration(
                /*modifiers*/
                void 0,
                factory.createImportClause(
                  isTypeOnly,
                  factory.createIdentifier(localName),
                  /*namedBindings*/
                  void 0
                ),
                specifier2,
                attributes
              ),
              0 /* None */
            );
            break;
          }
          case 274 /* NamespaceImport */: {
            const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context);
            const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.moduleSpecifier;
            const isTypeOnly = isJSDocImportTag(node.parent.parent);
            addResult(
              factory.createImportDeclaration(
                /*modifiers*/
                void 0,
                factory.createImportClause(
                  isTypeOnly,
                  /*name*/
                  void 0,
                  factory.createNamespaceImport(factory.createIdentifier(localName))
                ),
                specifier2,
                node.parent.attributes
              ),
              0 /* None */
            );
            break;
          }
          case 280 /* NamespaceExport */:
            addResult(
              factory.createExportDeclaration(
                /*modifiers*/
                void 0,
                /*isTypeOnly*/
                false,
                factory.createNamespaceExport(factory.createIdentifier(localName)),
                factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))
              ),
              0 /* None */
            );
            break;
          case 276 /* ImportSpecifier */: {
            const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context);
            const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.parent.moduleSpecifier;
            const isTypeOnly = isJSDocImportTag(node.parent.parent.parent);
            addResult(
              factory.createImportDeclaration(
                /*modifiers*/
                void 0,
                factory.createImportClause(
                  isTypeOnly,
                  /*name*/
                  void 0,
                  factory.createNamedImports([
                    factory.createImportSpecifier(
                      /*isTypeOnly*/
                      false,
                      localName !== verbatimTargetName ? factory.createIdentifier(verbatimTargetName) : void 0,
                      factory.createIdentifier(localName)
                    )
                  ])
                ),
                specifier2,
                node.parent.parent.parent.attributes
              ),
              0 /* None */
            );
            break;
          }
          case 281 /* ExportSpecifier */:
            const specifier = node.parent.parent.moduleSpecifier;
            if (specifier) {
              const propertyName = node.propertyName;
              if (propertyName && moduleExportNameIsDefault(propertyName)) {
                verbatimTargetName = "default" /* Default */;
              }
            }
            serializeExportSpecifier(
              unescapeLeadingUnderscores(symbol.escapedName),
              specifier ? verbatimTargetName : targetName,
              specifier && isStringLiteralLike(specifier) ? factory.createStringLiteral(specifier.text) : void 0
            );
            break;
          case 277 /* ExportAssignment */:
            serializeMaybeAliasAssignment(symbol);
            break;
          case 226 /* BinaryExpression */:
          case 211 /* PropertyAccessExpression */:
          case 212 /* ElementAccessExpression */:
            if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
              serializeMaybeAliasAssignment(symbol);
            } else {
              serializeExportSpecifier(localName, targetName);
            }
            break;
          default:
            return Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
        }
      }
      function serializeExportSpecifier(localName, targetName, specifier) {
        addResult(
          factory.createExportDeclaration(
            /*modifiers*/
            void 0,
            /*isTypeOnly*/
            false,
            factory.createNamedExports([factory.createExportSpecifier(
              /*isTypeOnly*/
              false,
              localName !== targetName ? targetName : void 0,
              localName
            )]),
            specifier
          ),
          0 /* None */
        );
      }
      function serializeMaybeAliasAssignment(symbol) {
        var _a2;
        if (symbol.flags & 4194304 /* Prototype */) {
          return false;
        }
        const name = unescapeLeadingUnderscores(symbol.escapedName);
        const isExportEquals = name === "export=" /* ExportEquals */;
        const isDefault = name === "default" /* Default */;
        const isExportAssignmentCompatibleSymbolName = isExportEquals || isDefault;
        const aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
        const target = aliasDecl && getTargetOfAliasDeclaration(
          aliasDecl,
          /*dontRecursivelyResolve*/
          true
        );
        if (target && length(target.declarations) && some(target.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(enclosingDeclaration))) {
          const expr = aliasDecl && (isExportAssignment(aliasDecl) || isBinaryExpression(aliasDecl) ? getExportAssignmentExpression(aliasDecl) : getPropertyAssignmentAliasLikeExpression(aliasDecl));
          const first2 = expr && isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : void 0;
          const referenced = first2 && resolveEntityName(
            first2,
            -1 /* All */,
            /*ignoreErrors*/
            true,
            /*dontResolveAlias*/
            true,
            enclosingDeclaration
          );
          if (referenced || target) {
            includePrivateSymbol(referenced || target);
          }
          const prevDisableTrackSymbol = context.tracker.disableTrackSymbol;
          context.tracker.disableTrackSymbol = true;
          if (isExportAssignmentCompatibleSymbolName) {
            results.push(factory.createExportAssignment(
              /*modifiers*/
              void 0,
              isExportEquals,
              symbolToExpression(target, context, -1 /* All */)
            ));
          } else {
            if (first2 === expr && first2) {
              serializeExportSpecifier(name, idText(first2));
            } else if (expr && isClassExpression(expr)) {
              serializeExportSpecifier(name, getInternalSymbolName(target, symbolName(target)));
            } else {
              const varName = getUnusedName(name, symbol);
              addResult(
                factory.createImportEqualsDeclaration(
                  /*modifiers*/
                  void 0,
                  /*isTypeOnly*/
                  false,
                  factory.createIdentifier(varName),
                  symbolToName(
                    target,
                    context,
                    -1 /* All */,
                    /*expectsIdentifier*/
                    false
                  )
                ),
                0 /* None */
              );
              serializeExportSpecifier(name, varName);
            }
          }
          context.tracker.disableTrackSymbol = prevDisableTrackSymbol;
          return true;
        } else {
          const varName = getUnusedName(name, symbol);
          const typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
          if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
            serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? 0 /* None */ : 32 /* Export */);
          } else {
            const flags = ((_a2 = context.enclosingDeclaration) == null ? void 0 : _a2.kind) === 267 /* ModuleDeclaration */ && (!(symbol.flags & 98304 /* Accessor */) || symbol.flags & 65536 /* SetAccessor */) ? 1 /* Let */ : 2 /* Const */;
            const statement = factory.createVariableStatement(
              /*modifiers*/
              void 0,
              factory.createVariableDeclarationList([
                factory.createVariableDeclaration(
                  varName,
                  /*exclamationToken*/
                  void 0,
                  serializeTypeForDeclaration(
                    context,
                    /*declaration*/
                    void 0,
                    typeToSerialize,
                    symbol
                  )
                )
              ], flags)
            );
            addResult(
              statement,
              target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 128 /* Ambient */ : name === varName ? 32 /* Export */ : 0 /* None */
            );
          }
          if (isExportAssignmentCompatibleSymbolName) {
            results.push(factory.createExportAssignment(
              /*modifiers*/
              void 0,
              isExportEquals,
              factory.createIdentifier(varName)
            ));
            return true;
          } else if (name !== varName) {
            serializeExportSpecifier(name, varName);
            return true;
          }
          return false;
        }
      }
      function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
        var _a2;
        const ctxSrc = getSourceFileOfNode(context.enclosingDeclaration);
        return getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) && !some((_a2 = typeToSerialize.symbol) == null ? void 0 : _a2.declarations, isTypeNode) && // If the type comes straight from a type node, we shouldn't try to break it up
        !length(getIndexInfosOfType(typeToSerialize)) && !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class
        !!(length(filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
        !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && !some(getPropertiesOfType(typeToSerialize), (p) => isLateBoundName(p.escapedName)) && !some(getPropertiesOfType(typeToSerialize), (p) => some(p.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && every(getPropertiesOfType(typeToSerialize), (p) => {
          if (!isIdentifierText(symbolName(p), languageVersion)) {
            return false;
          }
          if (!(p.flags & 98304 /* Accessor */)) {
            return true;
          }
          return getNonMissingTypeOfSymbol(p) === getWriteTypeOfSymbol(p);
        });
      }
      function makeSerializePropertySymbol(createProperty2, methodKind, useAccessors) {
        return function serializePropertySymbol(p, isStatic2, baseType) {
          var _a2, _b, _c, _d, _e, _f;
          const modifierFlags = getDeclarationModifierFlagsFromSymbol(p);
          const isPrivate = !!(modifierFlags & 2 /* Private */);
          if (isStatic2 && p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) {
            return [];
          }
          if (p.flags & 4194304 /* Prototype */ || p.escapedName === "constructor" || baseType && getPropertyOfType(baseType, p.escapedName) && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName))) {
            return [];
          }
          const flag = modifierFlags & ~1024 /* Async */ | (isStatic2 ? 256 /* Static */ : 0);
          const name = getPropertyNameNodeForSymbol(p, context);
          const firstPropertyLikeDecl = (_a2 = p.declarations) == null ? void 0 : _a2.find(or(isPropertyDeclaration, isAccessor, isVariableDeclaration, isPropertySignature, isBinaryExpression, isPropertyAccessExpression));
          if (p.flags & 98304 /* Accessor */ && useAccessors) {
            const result = [];
            if (p.flags & 65536 /* SetAccessor */) {
              const setter = p.declarations && forEach(p.declarations, (d) => {
                if (d.kind === 178 /* SetAccessor */) {
                  return d;
                }
                if (isCallExpression(d) && isBindableObjectDefinePropertyCall(d)) {
                  return forEach(d.arguments[2].properties, (propDecl) => {
                    const id = getNameOfDeclaration(propDecl);
                    if (!!id && isIdentifier(id) && idText(id) === "set") {
                      return propDecl;
                    }
                  });
                }
              });
              Debug.assert(!!setter);
              const paramSymbol = isFunctionLikeDeclaration(setter) ? getSignatureFromDeclaration(setter).parameters[0] : void 0;
              const setterDeclaration = (_b = p.declarations) == null ? void 0 : _b.find(isSetAccessor);
              result.push(setTextRange2(
                context,
                factory.createSetAccessorDeclaration(
                  factory.createModifiersFromModifierFlags(flag),
                  name,
                  [factory.createParameterDeclaration(
                    /*modifiers*/
                    void 0,
                    /*dotDotDotToken*/
                    void 0,
                    paramSymbol ? parameterToParameterDeclarationName(paramSymbol, getEffectiveParameterDeclaration(paramSymbol), context) : "value",
                    /*questionToken*/
                    void 0,
                    isPrivate ? void 0 : serializeTypeForDeclaration(context, setterDeclaration, getWriteTypeOfSymbol(p), p)
                  )],
                  /*body*/
                  void 0
                ),
                setterDeclaration ?? firstPropertyLikeDecl
              ));
            }
            if (p.flags & 32768 /* GetAccessor */) {
              const isPrivate2 = modifierFlags & 2 /* Private */;
              const getterDeclaration = (_c = p.declarations) == null ? void 0 : _c.find(isGetAccessor);
              result.push(setTextRange2(
                context,
                factory.createGetAccessorDeclaration(
                  factory.createModifiersFromModifierFlags(flag),
                  name,
                  [],
                  isPrivate2 ? void 0 : serializeTypeForDeclaration(context, getterDeclaration, getTypeOfSymbol(p), p),
                  /*body*/
                  void 0
                ),
                getterDeclaration ?? firstPropertyLikeDecl
              ));
            }
            return result;
          } else if (p.flags & (4 /* Property */ | 3 /* Variable */ | 98304 /* Accessor */)) {
            return setTextRange2(
              context,
              createProperty2(
                factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag),
                name,
                p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0,
                isPrivate ? void 0 : serializeTypeForDeclaration(context, (_d = p.declarations) == null ? void 0 : _d.find(isSetAccessorDeclaration), getWriteTypeOfSymbol(p), p),
                // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
                // interface members can't have initializers, however class members _can_
                /*initializer*/
                void 0
              ),
              ((_e = p.declarations) == null ? void 0 : _e.find(or(isPropertyDeclaration, isVariableDeclaration))) || firstPropertyLikeDecl
            );
          }
          if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
            const type = getTypeOfSymbol(p);
            const signatures = getSignaturesOfType(type, 0 /* Call */);
            if (flag & 2 /* Private */) {
              return setTextRange2(
                context,
                createProperty2(
                  factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag),
                  name,
                  p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0,
                  /*type*/
                  void 0,
                  /*initializer*/
                  void 0
                ),
                ((_f = p.declarations) == null ? void 0 : _f.find(isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]
              );
            }
            const results2 = [];
            for (const sig of signatures) {
              const decl = signatureToSignatureDeclarationHelper(
                sig,
                methodKind,
                context,
                {
                  name,
                  questionToken: p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0,
                  modifiers: flag ? factory.createModifiersFromModifierFlags(flag) : void 0
                }
              );
              const location = sig.declaration && isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration;
              results2.push(setTextRange2(context, decl, location));
            }
            return results2;
          }
          return Debug.fail(`Unhandled class member kind! ${p.__debugFlags || p.flags}`);
        };
      }
      function serializePropertySymbolForInterface(p, baseType) {
        return serializePropertySymbolForInterfaceWorker(
          p,
          /*isStatic*/
          false,
          baseType
        );
      }
      function serializeSignatures(kind, input, baseType, outputKind) {
        const signatures = getSignaturesOfType(input, kind);
        if (kind === 1 /* Construct */) {
          if (!baseType && every(signatures, (s) => length(s.parameters) === 0)) {
            return [];
          }
          if (baseType) {
            const baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
            if (!length(baseSigs) && every(signatures, (s) => length(s.parameters) === 0)) {
              return [];
            }
            if (baseSigs.length === signatures.length) {
              let failed2 = false;
              for (let i = 0; i < baseSigs.length; i++) {
                if (!compareSignaturesIdentical(
                  signatures[i],
                  baseSigs[i],
                  /*partialMatch*/
                  false,
                  /*ignoreThisTypes*/
                  false,
                  /*ignoreReturnTypes*/
                  true,
                  compareTypesIdentical
                )) {
                  failed2 = true;
                  break;
                }
              }
              if (!failed2) {
                return [];
              }
            }
          }
          let privateProtected = 0;
          for (const s of signatures) {
            if (s.declaration) {
              privateProtected |= getSelectedEffectiveModifierFlags(s.declaration, 2 /* Private */ | 4 /* Protected */);
            }
          }
          if (privateProtected) {
            return [setTextRange2(
              context,
              factory.createConstructorDeclaration(
                factory.createModifiersFromModifierFlags(privateProtected),
                /*parameters*/
                [],
                /*body*/
                void 0
              ),
              signatures[0].declaration
            )];
          }
        }
        const results2 = [];
        for (const sig of signatures) {
          const decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
          results2.push(setTextRange2(context, decl, sig.declaration));
        }
        return results2;
      }
      function serializeIndexSignatures(input, baseType) {
        const results2 = [];
        for (const info of getIndexInfosOfType(input)) {
          if (baseType) {
            const baseInfo = getIndexInfoOfType(baseType, info.keyType);
            if (baseInfo) {
              if (isTypeIdenticalTo(info.type, baseInfo.type)) {
                continue;
              }
            }
          }
          results2.push(indexInfoToIndexSignatureDeclarationHelper(
            info,
            context,
            /*typeNode*/
            void 0
          ));
        }
        return results2;
      }
      function serializeBaseType(t, staticType, rootName) {
        const ref = trySerializeAsTypeReference(t, 111551 /* Value */);
        if (ref) {
          return ref;
        }
        const tempName = getUnusedName(`${rootName}_base`);
        const statement = factory.createVariableStatement(
          /*modifiers*/
          void 0,
          factory.createVariableDeclarationList([
            factory.createVariableDeclaration(
              tempName,
              /*exclamationToken*/
              void 0,
              typeToTypeNodeHelper(staticType, context)
            )
          ], 2 /* Const */)
        );
        addResult(statement, 0 /* None */);
        return factory.createExpressionWithTypeArguments(
          factory.createIdentifier(tempName),
          /*typeArguments*/
          void 0
        );
      }
      function trySerializeAsTypeReference(t, flags) {
        let typeArgs;
        let reference;
        if (t.target && isSymbolAccessibleByFlags(t.target.symbol, enclosingDeclaration, flags)) {
          typeArgs = map(getTypeArguments(t), (t2) => typeToTypeNodeHelper(t2, context));
          reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
        } else if (t.symbol && isSymbolAccessibleByFlags(t.symbol, enclosingDeclaration, flags)) {
          reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
        }
        if (reference) {
          return factory.createExpressionWithTypeArguments(reference, typeArgs);
        }
      }
      function serializeImplementedType(t) {
        const ref = trySerializeAsTypeReference(t, 788968 /* Type */);
        if (ref) {
          return ref;
        }
        if (t.symbol) {
          return factory.createExpressionWithTypeArguments(
            symbolToExpression(t.symbol, context, 788968 /* Type */),
            /*typeArguments*/
            void 0
          );
        }
      }
      function getUnusedName(input, symbol) {
        var _a2, _b;
        const id = symbol ? getSymbolId(symbol) : void 0;
        if (id) {
          if (context.remappedSymbolNames.has(id)) {
            return context.remappedSymbolNames.get(id);
          }
        }
        if (symbol) {
          input = getNameCandidateWorker(symbol, input);
        }
        let i = 0;
        const original = input;
        while ((_a2 = context.usedSymbolNames) == null ? void 0 : _a2.has(input)) {
          i++;
          input = `${original}_${i}`;
        }
        (_b = context.usedSymbolNames) == null ? void 0 : _b.add(input);
        if (id) {
          context.remappedSymbolNames.set(id, input);
        }
        return input;
      }
      function getNameCandidateWorker(symbol, localName) {
        if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
          const restoreFlags = saveRestoreFlags(context);
          context.flags |= 16777216 /* InInitialEntityName */;
          const nameCandidate = getNameOfSymbolAsWritten(symbol, context);
          restoreFlags();
          localName = nameCandidate.length > 0 && isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? stripQuotes(nameCandidate) : nameCandidate;
        }
        if (localName === "default" /* Default */) {
          localName = "_default";
        } else if (localName === "export=" /* ExportEquals */) {
          localName = "_exports";
        }
        localName = isIdentifierText(localName, languageVersion) && !isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-z0-9]/gi, "_");
        return localName;
      }
      function getInternalSymbolName(symbol, localName) {
        const id = getSymbolId(symbol);
        if (context.remappedSymbolNames.has(id)) {
          return context.remappedSymbolNames.get(id);
        }
        localName = getNameCandidateWorker(symbol, localName);
        context.remappedSymbolNames.set(id, localName);
        return localName;
      }
    }
  }
  function typePredicateToString(typePredicate, enclosingDeclaration, flags = 16384 /* UseAliasDefinedOutsideCurrentScope */, writer) {
    return writer ? typePredicateToStringWorker(writer).getText() : usingSingleLineStringWriter(typePredicateToStringWorker);
    function typePredicateToStringWorker(writer2) {
      const nodeBuilderFlags = toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */;
      const predicate = nodeBuilder.typePredicateToTypePredicateNode(typePredicate, enclosingDeclaration, nodeBuilderFlags);
      const printer = createPrinterWithRemoveComments();
      const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
      printer.writeNode(
        4 /* Unspecified */,
        predicate,
        /*sourceFile*/
        sourceFile,
        writer2
      );
      return writer2;
    }
  }
  function formatUnionTypes(types) {
    const result = [];
    let flags = 0;
    for (let i = 0; i < types.length; i++) {
      const t = types[i];
      flags |= t.flags;
      if (!(t.flags & 98304 /* Nullable */)) {
        if (t.flags & (512 /* BooleanLiteral */ | 1056 /* EnumLike */)) {
          const baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLikeType(t);
          if (baseType.flags & 1048576 /* Union */) {
            const count = baseType.types.length;
            if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
              result.push(baseType);
              i += count - 1;
              continue;
            }
          }
        }
        result.push(t);
      }
    }
    if (flags & 65536 /* Null */) result.push(nullType);
    if (flags & 32768 /* Undefined */) result.push(undefinedType);
    return result || types;
  }
  function visibilityToString(flags) {
    if (flags === 2 /* Private */) {
      return "private";
    }
    if (flags === 4 /* Protected */) {
      return "protected";
    }
    return "public";
  }
  function getTypeAliasForTypeLiteral(type) {
    if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && type.symbol.declarations) {
      const node = walkUpParenthesizedTypes(type.symbol.declarations[0].parent);
      if (isTypeAliasDeclaration(node)) {
        return getSymbolOfDeclaration(node);
      }
    }
    return void 0;
  }
  function isTopLevelInExternalModuleAugmentation(node) {
    return node && node.parent && node.parent.kind === 268 /* ModuleBlock */ && isExternalModuleAugmentation(node.parent.parent);
  }
  function isDefaultBindingContext(location) {
    return location.kind === 307 /* SourceFile */ || isAmbientModule(location);
  }
  function getNameOfSymbolFromNameType(symbol, context) {
    const nameType = getSymbolLinks(symbol).nameType;
    if (nameType) {
      if (nameType.flags & 384 /* StringOrNumberLiteral */) {
        const name = "" + nameType.value;
        if (!isIdentifierText(name, getEmitScriptTarget(compilerOptions)) && !isNumericLiteralName(name)) {
          return `"${escapeString(name, 34 /* doubleQuote */)}"`;
        }
        if (isNumericLiteralName(name) && startsWith(name, "-")) {
          return `[${name}]`;
        }
        return name;
      }
      if (nameType.flags & 8192 /* UniqueESSymbol */) {
        return `[${getNameOfSymbolAsWritten(nameType.symbol, context)}]`;
      }
    }
  }
  function getNameOfSymbolAsWritten(symbol, context) {
    var _a;
    if ((_a = context == null ? void 0 : context.remappedSymbolReferences) == null ? void 0 : _a.has(getSymbolId(symbol))) {
      symbol = context.remappedSymbolReferences.get(getSymbolId(symbol));
    }
    if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && // If it's not the first part of an entity name, it must print as `default`
    (!(context.flags & 16777216 /* InInitialEntityName */) || // if the symbol is synthesized, it will only be referenced externally it must print as `default`
    !symbol.declarations || // if not in the same binding context (source file, module declaration), it must print as `default`
    context.enclosingDeclaration && findAncestor(symbol.declarations[0], isDefaultBindingContext) !== findAncestor(context.enclosingDeclaration, isDefaultBindingContext))) {
      return "default";
    }
    if (symbol.declarations && symbol.declarations.length) {
      let declaration = firstDefined(symbol.declarations, (d) => getNameOfDeclaration(d) ? d : void 0);
      const name2 = declaration && getNameOfDeclaration(declaration);
      if (declaration && name2) {
        if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) {
          return symbolName(symbol);
        }
        if (isComputedPropertyName(name2) && !(getCheckFlags(symbol) & 4096 /* Late */)) {
          const nameType = getSymbolLinks(symbol).nameType;
          if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
            const result = getNameOfSymbolFromNameType(symbol, context);
            if (result !== void 0) {
              return result;
            }
          }
        }
        return declarationNameToString(name2);
      }
      if (!declaration) {
        declaration = symbol.declarations[0];
      }
      if (declaration.parent && declaration.parent.kind === 260 /* VariableDeclaration */) {
        return declarationNameToString(declaration.parent.name);
      }
      switch (declaration.kind) {
        case 231 /* ClassExpression */:
        case 218 /* FunctionExpression */:
        case 219 /* ArrowFunction */:
          if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
            context.encounteredError = true;
          }
          return declaration.kind === 231 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
      }
    }
    const name = getNameOfSymbolFromNameType(symbol, context);
    return name !== void 0 ? name : symbolName(symbol);
  }
  function isDeclarationVisible(node) {
    if (node) {
      const links = getNodeLinks(node);
      if (links.isVisible === void 0) {
        links.isVisible = !!determineIfDeclarationIsVisible();
      }
      return links.isVisible;
    }
    return false;
    function determineIfDeclarationIsVisible() {
      switch (node.kind) {
        case 338 /* JSDocCallbackTag */:
        case 346 /* JSDocTypedefTag */:
        case 340 /* JSDocEnumTag */:
          return !!(node.parent && node.parent.parent && node.parent.parent.parent && isSourceFile(node.parent.parent.parent));
        case 208 /* BindingElement */:
          return isDeclarationVisible(node.parent.parent);
        case 260 /* VariableDeclaration */:
          if (isBindingPattern(node.name) && !node.name.elements.length) {
            return false;
          }
        // falls through
        case 267 /* ModuleDeclaration */:
        case 263 /* ClassDeclaration */:
        case 264 /* InterfaceDeclaration */:
        case 265 /* TypeAliasDeclaration */:
        case 262 /* FunctionDeclaration */:
        case 266 /* EnumDeclaration */:
        case 271 /* ImportEqualsDeclaration */:
          if (isExternalModuleAugmentation(node)) {
            return true;
          }
          const parent = getDeclarationContainer(node);
          if (!(getCombinedModifierFlagsCached(node) & 32 /* Export */) && !(node.kind !== 271 /* ImportEqualsDeclaration */ && parent.kind !== 307 /* SourceFile */ && parent.flags & 33554432 /* Ambient */)) {
            return isGlobalSourceFile(parent);
          }
          return isDeclarationVisible(parent);
        case 172 /* PropertyDeclaration */:
        case 171 /* PropertySignature */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
        case 174 /* MethodDeclaration */:
        case 173 /* MethodSignature */:
          if (hasEffectiveModifier(node, 2 /* Private */ | 4 /* Protected */)) {
            return false;
          }
        // Public properties/methods are visible if its parents are visible, so:
        // falls through
        case 176 /* Constructor */:
        case 180 /* ConstructSignature */:
        case 179 /* CallSignature */:
        case 181 /* IndexSignature */:
        case 169 /* Parameter */:
        case 268 /* ModuleBlock */:
        case 184 /* FunctionType */:
        case 185 /* ConstructorType */:
        case 187 /* TypeLiteral */:
        case 183 /* TypeReference */:
        case 188 /* ArrayType */:
        case 189 /* TupleType */:
        case 192 /* UnionType */:
        case 193 /* IntersectionType */:
        case 196 /* ParenthesizedType */:
        case 202 /* NamedTupleMember */:
          return isDeclarationVisible(node.parent);
        // Default binding, import specifier and namespace import is visible
        // only on demand so by default it is not visible
        case 273 /* ImportClause */:
        case 274 /* NamespaceImport */:
        case 276 /* ImportSpecifier */:
          return false;
        // Type parameters are always visible
        case 168 /* TypeParameter */:
        // Source file and namespace export are always visible
        // falls through
        case 307 /* SourceFile */:
        case 270 /* NamespaceExportDeclaration */:
          return true;
        // Export assignments do not create name bindings outside the module
        case 277 /* ExportAssignment */:
          return false;
        default:
          return false;
      }
    }
  }
  function collectLinkedAliases(node, setVisibility) {
    let exportSymbol;
    if (node.kind !== 11 /* StringLiteral */ && node.parent && node.parent.kind === 277 /* ExportAssignment */) {
      exportSymbol = resolveName(
        node,
        node,
        111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      );
    } else if (node.parent.kind === 281 /* ExportSpecifier */) {
      exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
    }
    let result;
    let visited;
    if (exportSymbol) {
      visited = /* @__PURE__ */ new Set();
      visited.add(getSymbolId(exportSymbol));
      buildVisibleNodeList(exportSymbol.declarations);
    }
    return result;
    function buildVisibleNodeList(declarations) {
      forEach(declarations, (declaration) => {
        const resultNode = getAnyImportSyntax(declaration) || declaration;
        if (setVisibility) {
          getNodeLinks(declaration).isVisible = true;
        } else {
          result = result || [];
          pushIfUnique(result, resultNode);
        }
        if (isInternalModuleImportEqualsDeclaration(declaration)) {
          const internalModuleReference = declaration.moduleReference;
          const firstIdentifier = getFirstIdentifier(internalModuleReference);
          const importSymbol = resolveName(
            declaration,
            firstIdentifier.escapedText,
            111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */,
            /*nameNotFoundMessage*/
            void 0,
            /*isUse*/
            false
          );
          if (importSymbol && visited) {
            if (tryAddToSet(visited, getSymbolId(importSymbol))) {
              buildVisibleNodeList(importSymbol.declarations);
            }
          }
        }
      });
    }
  }
  function pushTypeResolution(target, propertyName) {
    const resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
    if (resolutionCycleStartIndex >= 0) {
      const { length: length2 } = resolutionTargets;
      for (let i = resolutionCycleStartIndex; i < length2; i++) {
        resolutionResults[i] = false;
      }
      return false;
    }
    resolutionTargets.push(target);
    resolutionResults.push(
      /*items*/
      true
    );
    resolutionPropertyNames.push(propertyName);
    return true;
  }
  function findResolutionCycleStartIndex(target, propertyName) {
    for (let i = resolutionTargets.length - 1; i >= resolutionStart; i--) {
      if (resolutionTargetHasProperty(resolutionTargets[i], resolutionPropertyNames[i])) {
        return -1;
      }
      if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
        return i;
      }
    }
    return -1;
  }
  function resolutionTargetHasProperty(target, propertyName) {
    switch (propertyName) {
      case 0 /* Type */:
        return !!getSymbolLinks(target).type;
      case 2 /* DeclaredType */:
        return !!getSymbolLinks(target).declaredType;
      case 1 /* ResolvedBaseConstructorType */:
        return !!target.resolvedBaseConstructorType;
      case 3 /* ResolvedReturnType */:
        return !!target.resolvedReturnType;
      case 4 /* ImmediateBaseConstraint */:
        return !!target.immediateBaseConstraint;
      case 5 /* ResolvedTypeArguments */:
        return !!target.resolvedTypeArguments;
      case 6 /* ResolvedBaseTypes */:
        return !!target.baseTypesResolved;
      case 7 /* WriteType */:
        return !!getSymbolLinks(target).writeType;
      case 8 /* ParameterInitializerContainsUndefined */:
        return getNodeLinks(target).parameterInitializerContainsUndefined !== void 0;
    }
    return Debug.assertNever(propertyName);
  }
  function popTypeResolution() {
    resolutionTargets.pop();
    resolutionPropertyNames.pop();
    return resolutionResults.pop();
  }
  function getDeclarationContainer(node) {
    return findAncestor(getRootDeclaration(node), (node2) => {
      switch (node2.kind) {
        case 260 /* VariableDeclaration */:
        case 261 /* VariableDeclarationList */:
        case 276 /* ImportSpecifier */:
        case 275 /* NamedImports */:
        case 274 /* NamespaceImport */:
        case 273 /* ImportClause */:
          return false;
        default:
          return true;
      }
    }).parent;
  }
  function getTypeOfPrototypeProperty(prototype) {
    const classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
    return classType.typeParameters ? createTypeReference(classType, map(classType.typeParameters, (_) => anyType)) : classType;
  }
  function getTypeOfPropertyOfType(type, name) {
    const prop = getPropertyOfType(type, name);
    return prop ? getTypeOfSymbol(prop) : void 0;
  }
  function getTypeOfPropertyOrIndexSignatureOfType(type, name) {
    var _a;
    let propType;
    return getTypeOfPropertyOfType(type, name) || (propType = (_a = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a.type) && addOptionality(
      propType,
      /*isProperty*/
      true,
      /*isOptional*/
      true
    );
  }
  function isTypeAny(type) {
    return type && (type.flags & 1 /* Any */) !== 0;
  }
  function isErrorType(type) {
    return type === errorType || !!(type.flags & 1 /* Any */ && type.aliasSymbol);
  }
  function getTypeForBindingElementParent(node, checkMode) {
    if (checkMode !== 0 /* Normal */) {
      return getTypeForVariableLikeDeclaration(
        node,
        /*includeOptionality*/
        false,
        checkMode
      );
    }
    const symbol = getSymbolOfDeclaration(node);
    return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(
      node,
      /*includeOptionality*/
      false,
      checkMode
    );
  }
  function getRestType(source, properties, symbol) {
    source = filterType(source, (t) => !(t.flags & 98304 /* Nullable */));
    if (source.flags & 131072 /* Never */) {
      return emptyObjectType;
    }
    if (source.flags & 1048576 /* Union */) {
      return mapType(source, (t) => getRestType(t, properties, symbol));
    }
    let omitKeyType = getUnionType(map(properties, getLiteralTypeFromPropertyName));
    const spreadableProperties = [];
    const unspreadableToRestKeys = [];
    for (const prop of getPropertiesOfType(source)) {
      const literalTypeFromProperty = getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */);
      if (!isTypeAssignableTo(literalTypeFromProperty, omitKeyType) && !(getDeclarationModifierFlagsFromSymbol(prop) & (2 /* Private */ | 4 /* Protected */)) && isSpreadableProperty(prop)) {
        spreadableProperties.push(prop);
      } else {
        unspreadableToRestKeys.push(literalTypeFromProperty);
      }
    }
    if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
      if (unspreadableToRestKeys.length) {
        omitKeyType = getUnionType([omitKeyType, ...unspreadableToRestKeys]);
      }
      if (omitKeyType.flags & 131072 /* Never */) {
        return source;
      }
      const omitTypeAlias = getGlobalOmitSymbol();
      if (!omitTypeAlias) {
        return errorType;
      }
      return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
    }
    const members = createSymbolTable();
    for (const prop of spreadableProperties) {
      members.set(prop.escapedName, getSpreadSymbol(
        prop,
        /*readonly*/
        false
      ));
    }
    const result = createAnonymousType(symbol, members, emptyArray, emptyArray, getIndexInfosOfType(source));
    result.objectFlags |= 4194304 /* ObjectRestType */;
    return result;
  }
  function isGenericTypeWithUndefinedConstraint(type) {
    return !!(type.flags & 465829888 /* Instantiable */) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 32768 /* Undefined */);
  }
  function getNonUndefinedType(type) {
    const typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, (t) => t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t) : type;
    return getTypeWithFacts(typeOrConstraint, 524288 /* NEUndefined */);
  }
  function getFlowTypeOfDestructuring(node, declaredType) {
    const reference = getSyntheticElementAccess(node);
    return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
  }
  function getSyntheticElementAccess(node) {
    const parentAccess = getParentElementAccess(node);
    if (parentAccess && canHaveFlowNode(parentAccess) && parentAccess.flowNode) {
      const propName = getDestructuringPropertyName(node);
      if (propName) {
        const literal = setTextRange(parseNodeFactory.createStringLiteral(propName), node);
        const lhsExpr = isLeftHandSideExpression(parentAccess) ? parentAccess : parseNodeFactory.createParenthesizedExpression(parentAccess);
        const result = setTextRange(parseNodeFactory.createElementAccessExpression(lhsExpr, literal), node);
        setParent(literal, result);
        setParent(result, node);
        if (lhsExpr !== parentAccess) {
          setParent(lhsExpr, result);
        }
        result.flowNode = parentAccess.flowNode;
        return result;
      }
    }
  }
  function getParentElementAccess(node) {
    const ancestor = node.parent.parent;
    switch (ancestor.kind) {
      case 208 /* BindingElement */:
      case 303 /* PropertyAssignment */:
        return getSyntheticElementAccess(ancestor);
      case 209 /* ArrayLiteralExpression */:
        return getSyntheticElementAccess(node.parent);
      case 260 /* VariableDeclaration */:
        return ancestor.initializer;
      case 226 /* BinaryExpression */:
        return ancestor.right;
    }
  }
  function getDestructuringPropertyName(node) {
    const parent = node.parent;
    if (node.kind === 208 /* BindingElement */ && parent.kind === 206 /* ObjectBindingPattern */) {
      return getLiteralPropertyNameText(node.propertyName || node.name);
    }
    if (node.kind === 303 /* PropertyAssignment */ || node.kind === 304 /* ShorthandPropertyAssignment */) {
      return getLiteralPropertyNameText(node.name);
    }
    return "" + parent.elements.indexOf(node);
  }
  function getLiteralPropertyNameText(name) {
    const type = getLiteralTypeFromPropertyName(name);
    return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : void 0;
  }
  function getTypeForBindingElement(declaration) {
    const checkMode = declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */;
    const parentType = getTypeForBindingElementParent(declaration.parent.parent, checkMode);
    return parentType && getBindingElementTypeFromParentType(
      declaration,
      parentType,
      /*noTupleBoundsCheck*/
      false
    );
  }
  function getBindingElementTypeFromParentType(declaration, parentType, noTupleBoundsCheck) {
    if (isTypeAny(parentType)) {
      return parentType;
    }
    const pattern = declaration.parent;
    if (strictNullChecks && declaration.flags & 33554432 /* Ambient */ && isPartOfParameterDeclaration(declaration)) {
      parentType = getNonNullableType(parentType);
    } else if (strictNullChecks && pattern.parent.initializer && !hasTypeFacts(getTypeOfInitializer(pattern.parent.initializer), 65536 /* EQUndefined */)) {
      parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
    }
    const accessFlags = 32 /* ExpressionPosition */ | (noTupleBoundsCheck || hasDefaultValue(declaration) ? 16 /* AllowMissing */ : 0);
    let type;
    if (pattern.kind === 206 /* ObjectBindingPattern */) {
      if (declaration.dotDotDotToken) {
        parentType = getReducedType(parentType);
        if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
          error(declaration, Diagnostics.Rest_types_may_only_be_created_from_object_types);
          return errorType;
        }
        const literalMembers = [];
        for (const element of pattern.elements) {
          if (!element.dotDotDotToken) {
            literalMembers.push(element.propertyName || element.name);
          }
        }
        type = getRestType(parentType, literalMembers, declaration.symbol);
      } else {
        const name = declaration.propertyName || declaration.name;
        const indexType = getLiteralTypeFromPropertyName(name);
        const declaredType = getIndexedAccessType(parentType, indexType, accessFlags, name);
        type = getFlowTypeOfDestructuring(declaration, declaredType);
      }
    } else {
      const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern);
      const index = pattern.elements.indexOf(declaration);
      if (declaration.dotDotDotToken) {
        const baseConstraint = mapType(parentType, (t) => t.flags & 58982400 /* InstantiableNonPrimitive */ ? getBaseConstraintOrType(t) : t);
        type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t) => sliceTupleType(t, index)) : createArrayType(elementType);
      } else if (isArrayLikeType(parentType)) {
        const indexType = getNumberLiteralType(index);
        const declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, accessFlags, declaration.name) || errorType;
        type = getFlowTypeOfDestructuring(declaration, declaredType);
      } else {
        type = elementType;
      }
    }
    if (!declaration.initializer) {
      return type;
    }
    if (getEffectiveTypeAnnotationNode(walkUpBindingElementsAndPatterns(declaration))) {
      return strictNullChecks && !hasTypeFacts(checkDeclarationInitializer(declaration, 0 /* Normal */), 16777216 /* IsUndefined */) ? getNonUndefinedType(type) : type;
    }
    return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* Normal */)], 2 /* Subtype */));
  }
  function getTypeForDeclarationFromJSDocComment(declaration) {
    const jsdocType = getJSDocType(declaration);
    if (jsdocType) {
      return getTypeFromTypeNode(jsdocType);
    }
    return void 0;
  }
  function isNullOrUndefined2(node) {
    const expr = skipParentheses(
      node,
      /*excludeJSDocTypeAssertions*/
      true
    );
    return expr.kind === 106 /* NullKeyword */ || expr.kind === 80 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
  }
  function isEmptyArrayLiteral2(node) {
    const expr = skipParentheses(
      node,
      /*excludeJSDocTypeAssertions*/
      true
    );
    return expr.kind === 209 /* ArrayLiteralExpression */ && expr.elements.length === 0;
  }
  function addOptionality(type, isProperty = false, isOptional = true) {
    return strictNullChecks && isOptional ? getOptionalType(type, isProperty) : type;
  }
  function getTypeForVariableLikeDeclaration(declaration, includeOptionality, checkMode) {
    if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 249 /* ForInStatement */) {
      const indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(
        declaration.parent.parent.expression,
        /*checkMode*/
        checkMode
      )));
      return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
    }
    if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 250 /* ForOfStatement */) {
      const forOfStatement = declaration.parent.parent;
      return checkRightHandSideOfForOf(forOfStatement) || anyType;
    }
    if (isBindingPattern(declaration.parent)) {
      return getTypeForBindingElement(declaration);
    }
    const isProperty = isPropertyDeclaration(declaration) && !hasAccessorModifier(declaration) || isPropertySignature(declaration) || isJSDocPropertyTag(declaration);
    const isOptional = includeOptionality && isOptionalDeclaration(declaration);
    const declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
    if (isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
      if (declaredType) {
        return isTypeAny(declaredType) || declaredType === unknownType ? declaredType : errorType;
      }
      return useUnknownInCatchVariables ? unknownType : anyType;
    }
    if (declaredType) {
      return addOptionality(declaredType, isProperty, isOptional);
    }
    if ((noImplicitAny || isInJSFile(declaration)) && isVariableDeclaration(declaration) && !isBindingPattern(declaration.name) && !(getCombinedModifierFlagsCached(declaration) & 32 /* Export */) && !(declaration.flags & 33554432 /* Ambient */)) {
      if (!(getCombinedNodeFlagsCached(declaration) & 6 /* Constant */) && (!declaration.initializer || isNullOrUndefined2(declaration.initializer))) {
        return autoType;
      }
      if (declaration.initializer && isEmptyArrayLiteral2(declaration.initializer)) {
        return autoArrayType;
      }
    }
    if (isParameter(declaration)) {
      if (!declaration.symbol) {
        return;
      }
      const func = declaration.parent;
      if (func.kind === 178 /* SetAccessor */ && hasBindableName(func)) {
        const getter = getDeclarationOfKind(getSymbolOfDeclaration(declaration.parent), 177 /* GetAccessor */);
        if (getter) {
          const getterSignature = getSignatureFromDeclaration(getter);
          const thisParameter = getAccessorThisParameter(func);
          if (thisParameter && declaration === thisParameter) {
            Debug.assert(!thisParameter.type);
            return getTypeOfSymbol(getterSignature.thisParameter);
          }
          return getReturnTypeOfSignature(getterSignature);
        }
      }
      const parameterTypeOfTypeTag = getParameterTypeOfTypeTag(func, declaration);
      if (parameterTypeOfTypeTag) return parameterTypeOfTypeTag;
      const type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
      if (type) {
        return addOptionality(
          type,
          /*isProperty*/
          false,
          isOptional
        );
      }
    }
    if (hasOnlyExpressionInitializer(declaration) && !!declaration.initializer) {
      if (isInJSFile(declaration) && !isParameter(declaration)) {
        const containerObjectType = getJSContainerObjectType(declaration, getSymbolOfDeclaration(declaration), getDeclaredExpandoInitializer(declaration));
        if (containerObjectType) {
          return containerObjectType;
        }
      }
      const type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration, checkMode));
      return addOptionality(type, isProperty, isOptional);
    }
    if (isPropertyDeclaration(declaration) && (noImplicitAny || isInJSFile(declaration))) {
      if (!hasStaticModifier(declaration)) {
        const constructor = findConstructorDeclaration(declaration.parent);
        const type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : getEffectiveModifierFlags(declaration) & 128 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0;
        return type && addOptionality(
          type,
          /*isProperty*/
          true,
          isOptional
        );
      } else {
        const staticBlocks = filter(declaration.parent.members, isClassStaticBlockDeclaration);
        const type = staticBlocks.length ? getFlowTypeInStaticBlocks(declaration.symbol, staticBlocks) : getEffectiveModifierFlags(declaration) & 128 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0;
        return type && addOptionality(
          type,
          /*isProperty*/
          true,
          isOptional
        );
      }
    }
    if (isJsxAttribute(declaration)) {
      return trueType;
    }
    if (isBindingPattern(declaration.name)) {
      return getTypeFromBindingPattern(
        declaration.name,
        /*includePatternInType*/
        false,
        /*reportErrors*/
        true
      );
    }
    return void 0;
  }
  function isConstructorDeclaredProperty(symbol) {
    if (symbol.valueDeclaration && isBinaryExpression(symbol.valueDeclaration)) {
      const links = getSymbolLinks(symbol);
      if (links.isConstructorDeclaredProperty === void 0) {
        links.isConstructorDeclaredProperty = false;
        links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && every(symbol.declarations, (declaration) => isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && (declaration.left.kind !== 212 /* ElementAccessExpression */ || isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(
          /*declaredType*/
          void 0,
          declaration,
          symbol,
          declaration
        ));
      }
      return links.isConstructorDeclaredProperty;
    }
    return false;
  }
  function isAutoTypedProperty(symbol) {
    const declaration = symbol.valueDeclaration;
    return declaration && isPropertyDeclaration(declaration) && !getEffectiveTypeAnnotationNode(declaration) && !declaration.initializer && (noImplicitAny || isInJSFile(declaration));
  }
  function getDeclaringConstructor(symbol) {
    if (!symbol.declarations) {
      return;
    }
    for (const declaration of symbol.declarations) {
      const container = getThisContainer(
        declaration,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      );
      if (container && (container.kind === 176 /* Constructor */ || isJSConstructor(container))) {
        return container;
      }
    }
  }
  function getFlowTypeFromCommonJSExport(symbol) {
    const file = getSourceFileOfNode(symbol.declarations[0]);
    const accessName = unescapeLeadingUnderscores(symbol.escapedName);
    const areAllModuleExports = symbol.declarations.every((d) => isInJSFile(d) && isAccessExpression(d) && isModuleExportsAccessExpression(d.expression));
    const reference = areAllModuleExports ? factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(factory.createIdentifier("module"), factory.createIdentifier("exports")), accessName) : factory.createPropertyAccessExpression(factory.createIdentifier("exports"), accessName);
    if (areAllModuleExports) {
      setParent(reference.expression.expression, reference.expression);
    }
    setParent(reference.expression, reference);
    setParent(reference, file);
    reference.flowNode = file.endFlowNode;
    return getFlowTypeOfReference(reference, autoType, undefinedType);
  }
  function getFlowTypeInStaticBlocks(symbol, staticBlocks) {
    const accessName = startsWith(symbol.escapedName, "__#") ? factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) : unescapeLeadingUnderscores(symbol.escapedName);
    for (const staticBlock of staticBlocks) {
      const reference = factory.createPropertyAccessExpression(factory.createThis(), accessName);
      setParent(reference.expression, reference);
      setParent(reference, staticBlock);
      reference.flowNode = staticBlock.returnFlowNode;
      const flowType = getFlowTypeOfProperty(reference, symbol);
      if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
        error(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
      }
      if (everyType(flowType, isNullableType)) {
        continue;
      }
      return convertAutoToAny(flowType);
    }
  }
  function getFlowTypeInConstructor(symbol, constructor) {
    const accessName = startsWith(symbol.escapedName, "__#") ? factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) : unescapeLeadingUnderscores(symbol.escapedName);
    const reference = factory.createPropertyAccessExpression(factory.createThis(), accessName);
    setParent(reference.expression, reference);
    setParent(reference, constructor);
    reference.flowNode = constructor.returnFlowNode;
    const flowType = getFlowTypeOfProperty(reference, symbol);
    if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
      error(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
    }
    return everyType(flowType, isNullableType) ? void 0 : convertAutoToAny(flowType);
  }
  function getFlowTypeOfProperty(reference, prop) {
    const initialType = (prop == null ? void 0 : prop.valueDeclaration) && (!isAutoTypedProperty(prop) || getEffectiveModifierFlags(prop.valueDeclaration) & 128 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType;
    return getFlowTypeOfReference(reference, autoType, initialType);
  }
  function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
    const container = getAssignedExpandoInitializer(symbol.valueDeclaration);
    if (container) {
      const tag = isInJSFile(container) ? getJSDocTypeTag(container) : void 0;
      if (tag && tag.typeExpression) {
        return getTypeFromTypeNode(tag.typeExpression);
      }
      const containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
      return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
    }
    let type;
    let definedInConstructor = false;
    let definedInMethod = false;
    if (isConstructorDeclaredProperty(symbol)) {
      type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol));
    }
    if (!type) {
      let types;
      if (symbol.declarations) {
        let jsdocType;
        for (const declaration of symbol.declarations) {
          const expression = isBinaryExpression(declaration) || isCallExpression(declaration) ? declaration : isAccessExpression(declaration) ? isBinaryExpression(declaration.parent) ? declaration.parent : declaration : void 0;
          if (!expression) {
            continue;
          }
          const kind = isAccessExpression(expression) ? getAssignmentDeclarationPropertyAccessKind(expression) : getAssignmentDeclarationKind(expression);
          if (kind === 4 /* ThisProperty */ || isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) {
            if (isDeclarationInConstructor(expression)) {
              definedInConstructor = true;
            } else {
              definedInMethod = true;
            }
          }
          if (!isCallExpression(expression)) {
            jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
          }
          if (!jsdocType) {
            (types || (types = [])).push(isBinaryExpression(expression) || isCallExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
          }
        }
        type = jsdocType;
      }
      if (!type) {
        if (!length(types)) {
          return errorType;
        }
        let constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : void 0;
        if (definedInMethod) {
          const propType = getTypeOfPropertyInBaseClass(symbol);
          if (propType) {
            (constructorTypes || (constructorTypes = [])).push(propType);
            definedInConstructor = true;
          }
        }
        const sourceTypes = some(constructorTypes, (t) => !!(t.flags & ~98304 /* Nullable */)) ? constructorTypes : types;
        type = getUnionType(sourceTypes);
      }
    }
    const widened = getWidenedType(addOptionality(
      type,
      /*isProperty*/
      false,
      definedInMethod && !definedInConstructor
    ));
    if (symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) {
      reportImplicitAny(symbol.valueDeclaration, anyType);
      return anyType;
    }
    return widened;
  }
  function getJSContainerObjectType(decl, symbol, init) {
    var _a, _b;
    if (!isInJSFile(decl) || !init || !isObjectLiteralExpression(init) || init.properties.length) {
      return void 0;
    }
    const exports2 = createSymbolTable();
    while (isBinaryExpression(decl) || isPropertyAccessExpression(decl)) {
      const s2 = getSymbolOfNode(decl);
      if ((_a = s2 == null ? void 0 : s2.exports) == null ? void 0 : _a.size) {
        mergeSymbolTable(exports2, s2.exports);
      }
      decl = isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
    }
    const s = getSymbolOfNode(decl);
    if ((_b = s == null ? void 0 : s.exports) == null ? void 0 : _b.size) {
      mergeSymbolTable(exports2, s.exports);
    }
    const type = createAnonymousType(symbol, exports2, emptyArray, emptyArray, emptyArray);
    type.objectFlags |= 4096 /* JSLiteral */;
    return type;
  }
  function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
    var _a;
    const typeNode = getEffectiveTypeAnnotationNode(expression.parent);
    if (typeNode) {
      const type = getWidenedType(getTypeFromTypeNode(typeNode));
      if (!declaredType) {
        return type;
      } else if (!isErrorType(declaredType) && !isErrorType(type) && !isTypeIdenticalTo(declaredType, type)) {
        errorNextVariableOrPropertyDeclarationMustHaveSameType(
          /*firstDeclaration*/
          void 0,
          declaredType,
          declaration,
          type
        );
      }
    }
    if ((_a = symbol.parent) == null ? void 0 : _a.valueDeclaration) {
      const possiblyAnnotatedSymbol = getFunctionExpressionParentSymbolOrSymbol(symbol.parent);
      if (possiblyAnnotatedSymbol.valueDeclaration) {
        const typeNode2 = getEffectiveTypeAnnotationNode(possiblyAnnotatedSymbol.valueDeclaration);
        if (typeNode2) {
          const annotationSymbol = getPropertyOfType(getTypeFromTypeNode(typeNode2), symbol.escapedName);
          if (annotationSymbol) {
            return getNonMissingTypeOfSymbol(annotationSymbol);
          }
        }
      }
    }
    return declaredType;
  }
  function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
    if (isCallExpression(expression)) {
      if (resolvedSymbol) {
        return getTypeOfSymbol(resolvedSymbol);
      }
      const objectLitType = checkExpressionCached(expression.arguments[2]);
      const valueType = getTypeOfPropertyOfType(objectLitType, "value");
      if (valueType) {
        return valueType;
      }
      const getFunc = getTypeOfPropertyOfType(objectLitType, "get");
      if (getFunc) {
        const getSig = getSingleCallSignature(getFunc);
        if (getSig) {
          return getReturnTypeOfSignature(getSig);
        }
      }
      const setFunc = getTypeOfPropertyOfType(objectLitType, "set");
      if (setFunc) {
        const setSig = getSingleCallSignature(setFunc);
        if (setSig) {
          return getTypeOfFirstParameterOfSignature(setSig);
        }
      }
      return anyType;
    }
    if (containsSameNamedThisProperty(expression.left, expression.right)) {
      return anyType;
    }
    const isDirectExport = kind === 1 /* ExportsProperty */ && (isPropertyAccessExpression(expression.left) || isElementAccessExpression(expression.left)) && (isModuleExportsAccessExpression(expression.left.expression) || isIdentifier(expression.left.expression) && isExportsIdentifier(expression.left.expression));
    const type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : isDirectExport ? getRegularTypeOfLiteralType(checkExpressionCached(expression.right)) : getWidenedLiteralType(checkExpressionCached(expression.right));
    if (type.flags & 524288 /* Object */ && kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) {
      const exportedType = resolveStructuredTypeMembers(type);
      const members = createSymbolTable();
      copyEntries(exportedType.members, members);
      const initialSize = members.size;
      if (resolvedSymbol && !resolvedSymbol.exports) {
        resolvedSymbol.exports = createSymbolTable();
      }
      (resolvedSymbol || symbol).exports.forEach((s, name) => {
        var _a;
        const exportedMember = members.get(name);
        if (exportedMember && exportedMember !== s && !(s.flags & 2097152 /* Alias */)) {
          if (s.flags & 111551 /* Value */ && exportedMember.flags & 111551 /* Value */) {
            if (s.valueDeclaration && exportedMember.valueDeclaration && getSourceFileOfNode(s.valueDeclaration) !== getSourceFileOfNode(exportedMember.valueDeclaration)) {
              const unescapedName = unescapeLeadingUnderscores(s.escapedName);
              const exportedMemberName = ((_a = tryCast(exportedMember.valueDeclaration, isNamedDeclaration)) == null ? void 0 : _a.name) || exportedMember.valueDeclaration;
              addRelatedInfo(
                error(s.valueDeclaration, Diagnostics.Duplicate_identifier_0, unescapedName),
                createDiagnosticForNode(exportedMemberName, Diagnostics._0_was_also_declared_here, unescapedName)
              );
              addRelatedInfo(
                error(exportedMemberName, Diagnostics.Duplicate_identifier_0, unescapedName),
                createDiagnosticForNode(s.valueDeclaration, Diagnostics._0_was_also_declared_here, unescapedName)
              );
            }
            const union = createSymbol(s.flags | exportedMember.flags, name);
            union.links.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
            union.valueDeclaration = exportedMember.valueDeclaration;
            union.declarations = concatenate(exportedMember.declarations, s.declarations);
            members.set(name, union);
          } else {
            members.set(name, mergeSymbol(s, exportedMember));
          }
        } else {
          members.set(name, s);
        }
      });
      const result = createAnonymousType(
        initialSize !== members.size ? void 0 : exportedType.symbol,
        // Only set the type's symbol if it looks to be the same as the original type
        members,
        exportedType.callSignatures,
        exportedType.constructSignatures,
        exportedType.indexInfos
      );
      if (initialSize === members.size) {
        if (type.aliasSymbol) {
          result.aliasSymbol = type.aliasSymbol;
          result.aliasTypeArguments = type.aliasTypeArguments;
        }
        if (getObjectFlags(type) & 4 /* Reference */) {
          result.aliasSymbol = type.symbol;
          const args = getTypeArguments(type);
          result.aliasTypeArguments = length(args) ? args : void 0;
        }
      }
      result.objectFlags |= getPropagatingFlagsOfTypes([type]) | getObjectFlags(type) & (4096 /* JSLiteral */ | 16384 /* ArrayLiteral */ | 128 /* ObjectLiteral */);
      if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) {
        result.objectFlags |= 16777216 /* IsClassInstanceClone */;
      }
      return result;
    }
    if (isEmptyArrayLiteralType(type)) {
      reportImplicitAny(expression, anyArrayType);
      return anyArrayType;
    }
    return type;
  }
  function containsSameNamedThisProperty(thisProperty, expression) {
    return isPropertyAccessExpression(thisProperty) && thisProperty.expression.kind === 110 /* ThisKeyword */ && forEachChildRecursively(expression, (n) => isMatchingReference(thisProperty, n));
  }
  function isDeclarationInConstructor(expression) {
    const thisContainer = getThisContainer(
      expression,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    return thisContainer.kind === 176 /* Constructor */ || thisContainer.kind === 262 /* FunctionDeclaration */ || thisContainer.kind === 218 /* FunctionExpression */ && !isPrototypePropertyAssignment(thisContainer.parent);
  }
  function getConstructorDefinedThisAssignmentTypes(types, declarations) {
    Debug.assert(types.length === declarations.length);
    return types.filter((_, i) => {
      const declaration = declarations[i];
      const expression = isBinaryExpression(declaration) ? declaration : isBinaryExpression(declaration.parent) ? declaration.parent : void 0;
      return expression && isDeclarationInConstructor(expression);
    });
  }
  function getTypeFromBindingElement(element, includePatternInType, reportErrors2) {
    if (element.initializer) {
      const contextualType = isBindingPattern(element.name) ? getTypeFromBindingPattern(
        element.name,
        /*includePatternInType*/
        true,
        /*reportErrors*/
        false
      ) : unknownType;
      return addOptionality(getWidenedLiteralTypeForInitializer(element, checkDeclarationInitializer(element, 0 /* Normal */, contextualType)));
    }
    if (isBindingPattern(element.name)) {
      return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors2);
    }
    if (reportErrors2 && !declarationBelongsToPrivateAmbientMember(element)) {
      reportImplicitAny(element, anyType);
    }
    return includePatternInType ? nonInferrableAnyType : anyType;
  }
  function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors2) {
    const members = createSymbolTable();
    let stringIndexInfo;
    let objectFlags = 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */;
    forEach(pattern.elements, (e) => {
      const name = e.propertyName || e.name;
      if (e.dotDotDotToken) {
        stringIndexInfo = createIndexInfo(
          stringType,
          anyType,
          /*isReadonly*/
          false
        );
        return;
      }
      const exprType = getLiteralTypeFromPropertyName(name);
      if (!isTypeUsableAsPropertyName(exprType)) {
        objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
        return;
      }
      const text = getPropertyNameFromType(exprType);
      const flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
      const symbol = createSymbol(flags, text);
      symbol.links.type = getTypeFromBindingElement(e, includePatternInType, reportErrors2);
      members.set(symbol.escapedName, symbol);
    });
    const result = createAnonymousType(
      /*symbol*/
      void 0,
      members,
      emptyArray,
      emptyArray,
      stringIndexInfo ? [stringIndexInfo] : emptyArray
    );
    result.objectFlags |= objectFlags;
    if (includePatternInType) {
      result.pattern = pattern;
      result.objectFlags |= 131072 /* ContainsObjectOrArrayLiteral */;
    }
    return result;
  }
  function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2) {
    const elements = pattern.elements;
    const lastElement = lastOrUndefined(elements);
    const restElement = lastElement && lastElement.kind === 208 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : void 0;
    if (elements.length === 0 || elements.length === 1 && restElement) {
      return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
    }
    const elementTypes = map(elements, (e) => isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors2));
    const minLength = findLastIndex(elements, (e) => !(e === restElement || isOmittedExpression(e) || hasDefaultValue(e)), elements.length - 1) + 1;
    const elementFlags = map(elements, (e, i) => e === restElement ? 4 /* Rest */ : i >= minLength ? 2 /* Optional */ : 1 /* Required */);
    let result = createTupleType(elementTypes, elementFlags);
    if (includePatternInType) {
      result = cloneTypeReference(result);
      result.pattern = pattern;
      result.objectFlags |= 131072 /* ContainsObjectOrArrayLiteral */;
    }
    return result;
  }
  function getTypeFromBindingPattern(pattern, includePatternInType = false, reportErrors2 = false) {
    if (includePatternInType) contextualBindingPatterns.push(pattern);
    const result = pattern.kind === 206 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors2) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2);
    if (includePatternInType) contextualBindingPatterns.pop();
    return result;
  }
  function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors2) {
    return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(
      declaration,
      /*includeOptionality*/
      true,
      0 /* Normal */
    ), declaration, reportErrors2);
  }
  function getTypeFromImportAttributes(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const symbol = createSymbol(4096 /* ObjectLiteral */, "__importAttributes" /* ImportAttributes */);
      const members = createSymbolTable();
      forEach(node.elements, (attr) => {
        const member = createSymbol(4 /* Property */, getNameFromImportAttribute(attr));
        member.parent = symbol;
        member.links.type = checkImportAttribute(attr);
        member.links.target = member;
        members.set(member.escapedName, member);
      });
      const type = createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
      type.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* NonInferrableType */;
      links.resolvedType = type;
    }
    return links.resolvedType;
  }
  function isGlobalSymbolConstructor(node) {
    const symbol = getSymbolOfNode(node);
    const globalSymbol = getGlobalESSymbolConstructorTypeSymbol(
      /*reportErrors*/
      false
    );
    return globalSymbol && symbol && symbol === globalSymbol;
  }
  function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors2) {
    if (type) {
      if (type.flags & 4096 /* ESSymbol */ && isGlobalSymbolConstructor(declaration.parent)) {
        type = getESSymbolLikeTypeForNode(declaration);
      }
      if (reportErrors2) {
        reportErrorsFromWidening(declaration, type);
      }
      if (type.flags & 8192 /* UniqueESSymbol */ && (isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfDeclaration(declaration)) {
        type = esSymbolType;
      }
      return getWidenedType(type);
    }
    type = isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
    if (reportErrors2) {
      if (!declarationBelongsToPrivateAmbientMember(declaration)) {
        reportImplicitAny(declaration, type);
      }
    }
    return type;
  }
  function declarationBelongsToPrivateAmbientMember(declaration) {
    const root = getRootDeclaration(declaration);
    const memberDeclaration = root.kind === 169 /* Parameter */ ? root.parent : root;
    return isPrivateWithinAmbient(memberDeclaration);
  }
  function tryGetTypeFromEffectiveTypeNode(node) {
    const typeNode = getEffectiveTypeAnnotationNode(node);
    if (typeNode) {
      return getTypeFromTypeNode(typeNode);
    }
  }
  function isParameterOfContextSensitiveSignature(symbol) {
    let decl = symbol.valueDeclaration;
    if (!decl) {
      return false;
    }
    if (isBindingElement(decl)) {
      decl = walkUpBindingElementsAndPatterns(decl);
    }
    if (isParameter(decl)) {
      return isContextSensitiveFunctionOrObjectLiteralMethod(decl.parent);
    }
    return false;
  }
  function getTypeOfVariableOrParameterOrProperty(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      const type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
      if (!links.type && !isParameterOfContextSensitiveSignature(symbol)) {
        links.type = type;
      }
      return type;
    }
    return links.type;
  }
  function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
    if (symbol.flags & 4194304 /* Prototype */) {
      return getTypeOfPrototypeProperty(symbol);
    }
    if (symbol === requireSymbol) {
      return anyType;
    }
    if (symbol.flags & 134217728 /* ModuleExports */ && symbol.valueDeclaration) {
      const fileSymbol = getSymbolOfDeclaration(getSourceFileOfNode(symbol.valueDeclaration));
      const result = createSymbol(fileSymbol.flags, "exports");
      result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : [];
      result.parent = symbol;
      result.links.target = fileSymbol;
      if (fileSymbol.valueDeclaration) result.valueDeclaration = fileSymbol.valueDeclaration;
      if (fileSymbol.members) result.members = new Map(fileSymbol.members);
      if (fileSymbol.exports) result.exports = new Map(fileSymbol.exports);
      const members = createSymbolTable();
      members.set("exports", result);
      return createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
    }
    Debug.assertIsDefined(symbol.valueDeclaration);
    const declaration = symbol.valueDeclaration;
    if (isSourceFile(declaration) && isJsonSourceFile(declaration)) {
      if (!declaration.statements.length) {
        return emptyObjectType;
      }
      return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
    }
    if (isAccessor(declaration)) {
      return getTypeOfAccessors(symbol);
    }
    if (!pushTypeResolution(symbol, 0 /* Type */)) {
      if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
        return getTypeOfFuncClassEnumModule(symbol);
      }
      return reportCircularityError(symbol);
    }
    let type;
    if (declaration.kind === 277 /* ExportAssignment */) {
      type = widenTypeForVariableLikeDeclaration(tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionCached(declaration.expression), declaration);
    } else if (isBinaryExpression(declaration) || isInJSFile(declaration) && (isCallExpression(declaration) || (isPropertyAccessExpression(declaration) || isBindableStaticElementAccessExpression(declaration)) && isBinaryExpression(declaration.parent))) {
      type = getWidenedTypeForAssignmentDeclaration(symbol);
    } else if (isPropertyAccessExpression(declaration) || isElementAccessExpression(declaration) || isIdentifier(declaration) || isStringLiteralLike(declaration) || isNumericLiteral(declaration) || isClassDeclaration(declaration) || isFunctionDeclaration(declaration) || isMethodDeclaration(declaration) && !isObjectLiteralMethod(declaration) || isMethodSignature(declaration) || isSourceFile(declaration)) {
      if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
        return getTypeOfFuncClassEnumModule(symbol);
      }
      type = isBinaryExpression(declaration.parent) ? getWidenedTypeForAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
    } else if (isPropertyAssignment(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
    } else if (isJsxAttribute(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
    } else if (isShorthandPropertyAssignment(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
    } else if (isObjectLiteralMethod(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
    } else if (isParameter(declaration) || isPropertyDeclaration(declaration) || isPropertySignature(declaration) || isVariableDeclaration(declaration) || isBindingElement(declaration) || isJSDocPropertyLikeTag(declaration)) {
      type = getWidenedTypeForVariableLikeDeclaration(
        declaration,
        /*reportErrors*/
        true
      );
    } else if (isEnumDeclaration(declaration)) {
      type = getTypeOfFuncClassEnumModule(symbol);
    } else if (isEnumMember(declaration)) {
      type = getTypeOfEnumMember(symbol);
    } else {
      return Debug.fail("Unhandled declaration kind! " + Debug.formatSyntaxKind(declaration.kind) + " for " + Debug.formatSymbol(symbol));
    }
    if (!popTypeResolution()) {
      if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
        return getTypeOfFuncClassEnumModule(symbol);
      }
      return reportCircularityError(symbol);
    }
    return type;
  }
  function getAnnotatedAccessorTypeNode(accessor) {
    if (accessor) {
      switch (accessor.kind) {
        case 177 /* GetAccessor */:
          const getterTypeAnnotation = getEffectiveReturnTypeNode(accessor);
          return getterTypeAnnotation;
        case 178 /* SetAccessor */:
          const setterTypeAnnotation = getEffectiveSetAccessorTypeAnnotationNode(accessor);
          return setterTypeAnnotation;
        case 172 /* PropertyDeclaration */:
          Debug.assert(hasAccessorModifier(accessor));
          const accessorTypeAnnotation = getEffectiveTypeAnnotationNode(accessor);
          return accessorTypeAnnotation;
      }
    }
    return void 0;
  }
  function getAnnotatedAccessorType(accessor) {
    const node = getAnnotatedAccessorTypeNode(accessor);
    return node && getTypeFromTypeNode(node);
  }
  function getAnnotatedAccessorThisParameter(accessor) {
    const parameter = getAccessorThisParameter(accessor);
    return parameter && parameter.symbol;
  }
  function getThisTypeOfDeclaration(declaration) {
    return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
  }
  function getTypeOfAccessors(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      if (!pushTypeResolution(symbol, 0 /* Type */)) {
        return errorType;
      }
      const getter = getDeclarationOfKind(symbol, 177 /* GetAccessor */);
      const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */);
      const accessor = tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration);
      let type = getter && isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || getAnnotatedAccessorType(getter) || getAnnotatedAccessorType(setter) || getAnnotatedAccessorType(accessor) || getter && getter.body && getReturnTypeFromBody(getter) || accessor && getWidenedTypeForVariableLikeDeclaration(
        accessor,
        /*reportErrors*/
        true
      );
      if (!type) {
        if (setter && !isPrivateWithinAmbient(setter)) {
          errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
        } else if (getter && !isPrivateWithinAmbient(getter)) {
          errorOrSuggestion(noImplicitAny, getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
        } else if (accessor && !isPrivateWithinAmbient(accessor)) {
          errorOrSuggestion(noImplicitAny, accessor, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), "any");
        }
        type = anyType;
      }
      if (!popTypeResolution()) {
        if (getAnnotatedAccessorTypeNode(getter)) {
          error(getter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        } else if (getAnnotatedAccessorTypeNode(setter)) {
          error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        } else if (getAnnotatedAccessorTypeNode(accessor)) {
          error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        } else if (getter && noImplicitAny) {
          error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol));
        }
        type = anyType;
      }
      links.type ?? (links.type = type);
    }
    return links.type;
  }
  function getWriteTypeOfAccessors(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.writeType) {
      if (!pushTypeResolution(symbol, 7 /* WriteType */)) {
        return errorType;
      }
      const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */) ?? tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration);
      let writeType = getAnnotatedAccessorType(setter);
      if (!popTypeResolution()) {
        if (getAnnotatedAccessorTypeNode(setter)) {
          error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        }
        writeType = anyType;
      }
      links.writeType ?? (links.writeType = writeType || getTypeOfAccessors(symbol));
    }
    return links.writeType;
  }
  function getBaseTypeVariableOfClass(symbol) {
    const baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
    return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : baseConstructorType.flags & 2097152 /* Intersection */ ? find(baseConstructorType.types, (t) => !!(t.flags & 8650752 /* TypeVariable */)) : void 0;
  }
  function getTypeOfFuncClassEnumModule(symbol) {
    let links = getSymbolLinks(symbol);
    const originalLinks = links;
    if (!links.type) {
      const expando = symbol.valueDeclaration && getSymbolOfExpando(
        symbol.valueDeclaration,
        /*allowDeclaration*/
        false
      );
      if (expando) {
        const merged = mergeJSSymbols(symbol, expando);
        if (merged) {
          symbol = merged;
          links = merged.links;
        }
      }
      originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
    }
    return links.type;
  }
  function getTypeOfFuncClassEnumModuleWorker(symbol) {
    const declaration = symbol.valueDeclaration;
    if (symbol.flags & 1536 /* Module */ && isShorthandAmbientModuleSymbol(symbol)) {
      return anyType;
    } else if (declaration && (declaration.kind === 226 /* BinaryExpression */ || isAccessExpression(declaration) && declaration.parent.kind === 226 /* BinaryExpression */)) {
      return getWidenedTypeForAssignmentDeclaration(symbol);
    } else if (symbol.flags & 512 /* ValueModule */ && declaration && isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
      const resolvedModule = resolveExternalModuleSymbol(symbol);
      if (resolvedModule !== symbol) {
        if (!pushTypeResolution(symbol, 0 /* Type */)) {
          return errorType;
        }
        const exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
        const type2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? void 0 : resolvedModule);
        if (!popTypeResolution()) {
          return reportCircularityError(symbol);
        }
        return type2;
      }
    }
    const type = createObjectType(16 /* Anonymous */, symbol);
    if (symbol.flags & 32 /* Class */) {
      const baseTypeVariable = getBaseTypeVariableOfClass(symbol);
      return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
    } else {
      return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(
        type,
        /*isProperty*/
        true
      ) : type;
    }
  }
  function getTypeOfEnumMember(symbol) {
    const links = getSymbolLinks(symbol);
    return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
  }
  function getTypeOfAlias(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      if (!pushTypeResolution(symbol, 0 /* Type */)) {
        return errorType;
      }
      const targetSymbol = resolveAlias(symbol);
      const exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(
        getDeclarationOfAliasSymbol(symbol),
        /*dontRecursivelyResolve*/
        true
      );
      const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, (d) => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0);
      links.type ?? (links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType);
      if (!popTypeResolution()) {
        reportCircularityError(exportSymbol ?? symbol);
        return links.type ?? (links.type = errorType);
      }
    }
    return links.type;
  }
  function getTypeOfInstantiatedSymbol(symbol) {
    const links = getSymbolLinks(symbol);
    return links.type || (links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper));
  }
  function getWriteTypeOfInstantiatedSymbol(symbol) {
    const links = getSymbolLinks(symbol);
    return links.writeType || (links.writeType = instantiateType(getWriteTypeOfSymbol(links.target), links.mapper));
  }
  function reportCircularityError(symbol) {
    const declaration = symbol.valueDeclaration;
    if (declaration) {
      if (getEffectiveTypeAnnotationNode(declaration)) {
        error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        return errorType;
      }
      if (noImplicitAny && (declaration.kind !== 169 /* Parameter */ || declaration.initializer)) {
        error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
      }
    } else if (symbol.flags & 2097152 /* Alias */) {
      const node = getDeclarationOfAliasSymbol(symbol);
      if (node) {
        error(node, Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
      }
    }
    return anyType;
  }
  function getTypeOfSymbolWithDeferredType(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      Debug.assertIsDefined(links.deferralParent);
      Debug.assertIsDefined(links.deferralConstituents);
      links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
    }
    return links.type;
  }
  function getWriteTypeOfSymbolWithDeferredType(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.writeType && links.deferralWriteConstituents) {
      Debug.assertIsDefined(links.deferralParent);
      Debug.assertIsDefined(links.deferralConstituents);
      links.writeType = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralWriteConstituents) : getIntersectionType(links.deferralWriteConstituents);
    }
    return links.writeType;
  }
  function getWriteTypeOfSymbol(symbol) {
    const checkFlags = getCheckFlags(symbol);
    if (symbol.flags & 4 /* Property */) {
      return checkFlags & 2 /* SyntheticProperty */ ? checkFlags & 65536 /* DeferredType */ ? getWriteTypeOfSymbolWithDeferredType(symbol) || getTypeOfSymbolWithDeferredType(symbol) : (
        // NOTE: cast to TransientSymbol should be safe because only TransientSymbols can have CheckFlags.SyntheticProperty
        symbol.links.writeType || symbol.links.type
      ) : removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */));
    }
    if (symbol.flags & 98304 /* Accessor */) {
      return checkFlags & 1 /* Instantiated */ ? getWriteTypeOfInstantiatedSymbol(symbol) : getWriteTypeOfAccessors(symbol);
    }
    return getTypeOfSymbol(symbol);
  }
  function getTypeOfSymbol(symbol) {
    const checkFlags = getCheckFlags(symbol);
    if (checkFlags & 65536 /* DeferredType */) {
      return getTypeOfSymbolWithDeferredType(symbol);
    }
    if (checkFlags & 1 /* Instantiated */) {
      return getTypeOfInstantiatedSymbol(symbol);
    }
    if (checkFlags & 262144 /* Mapped */) {
      return getTypeOfMappedSymbol(symbol);
    }
    if (checkFlags & 8192 /* ReverseMapped */) {
      return getTypeOfReverseMappedSymbol(symbol);
    }
    if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
      return getTypeOfVariableOrParameterOrProperty(symbol);
    }
    if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
      return getTypeOfFuncClassEnumModule(symbol);
    }
    if (symbol.flags & 8 /* EnumMember */) {
      return getTypeOfEnumMember(symbol);
    }
    if (symbol.flags & 98304 /* Accessor */) {
      return getTypeOfAccessors(symbol);
    }
    if (symbol.flags & 2097152 /* Alias */) {
      return getTypeOfAlias(symbol);
    }
    return errorType;
  }
  function getNonMissingTypeOfSymbol(symbol) {
    return removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */));
  }
  function isReferenceToSomeType(type, targets) {
    if (type === void 0 || (getObjectFlags(type) & 4 /* Reference */) === 0) {
      return false;
    }
    for (const target of targets) {
      if (type.target === target) {
        return true;
      }
    }
    return false;
  }
  function isReferenceToType(type, target) {
    return type !== void 0 && target !== void 0 && (getObjectFlags(type) & 4 /* Reference */) !== 0 && type.target === target;
  }
  function getTargetType(type) {
    return getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
  }
  function hasBaseType(type, checkBase) {
    return check(type);
    function check(type2) {
      if (getObjectFlags(type2) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
        const target = getTargetType(type2);
        return target === checkBase || some(getBaseTypes(target), check);
      } else if (type2.flags & 2097152 /* Intersection */) {
        return some(type2.types, check);
      }
      return false;
    }
  }
  function appendTypeParameters(typeParameters, declarations) {
    for (const declaration of declarations) {
      typeParameters = appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(declaration)));
    }
    return typeParameters;
  }
  function getOuterTypeParameters(node, includeThisTypes) {
    while (true) {
      node = node.parent;
      if (node && isBinaryExpression(node)) {
        const assignmentKind = getAssignmentDeclarationKind(node);
        if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
          const symbol = getSymbolOfDeclaration(node.left);
          if (symbol && symbol.parent && !findAncestor(symbol.parent.valueDeclaration, (d) => node === d)) {
            node = symbol.parent.valueDeclaration;
          }
        }
      }
      if (!node) {
        return void 0;
      }
      const kind = node.kind;
      switch (kind) {
        case 263 /* ClassDeclaration */:
        case 231 /* ClassExpression */:
        case 264 /* InterfaceDeclaration */:
        case 179 /* CallSignature */:
        case 180 /* ConstructSignature */:
        case 173 /* MethodSignature */:
        case 184 /* FunctionType */:
        case 185 /* ConstructorType */:
        case 317 /* JSDocFunctionType */:
        case 262 /* FunctionDeclaration */:
        case 174 /* MethodDeclaration */:
        case 218 /* FunctionExpression */:
        case 219 /* ArrowFunction */:
        case 265 /* TypeAliasDeclaration */:
        case 345 /* JSDocTemplateTag */:
        case 346 /* JSDocTypedefTag */:
        case 340 /* JSDocEnumTag */:
        case 338 /* JSDocCallbackTag */:
        case 200 /* MappedType */:
        case 194 /* ConditionalType */: {
          const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
          if ((kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */ || isObjectLiteralMethod(node)) && isContextSensitive(node)) {
            const signature = firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfDeclaration(node)), 0 /* Call */));
            if (signature && signature.typeParameters) {
              return [...outerTypeParameters || emptyArray, ...signature.typeParameters];
            }
          }
          if (kind === 200 /* MappedType */) {
            return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter)));
          } else if (kind === 194 /* ConditionalType */) {
            return concatenate(outerTypeParameters, getInferTypeParameters(node));
          }
          const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node));
          const thisType = includeThisTypes && (kind === 263 /* ClassDeclaration */ || kind === 231 /* ClassExpression */ || kind === 264 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node)).thisType;
          return thisType ? append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
        }
        case 341 /* JSDocParameterTag */:
          const paramSymbol = getParameterSymbolFromJSDoc(node);
          if (paramSymbol) {
            node = paramSymbol.valueDeclaration;
          }
          break;
        case 320 /* JSDoc */: {
          const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
          return node.tags ? appendTypeParameters(outerTypeParameters, flatMap(node.tags, (t) => isJSDocTemplateTag(t) ? t.typeParameters : void 0)) : outerTypeParameters;
        }
      }
    }
  }
  function getOuterTypeParametersOfClassOrInterface(symbol) {
    var _a;
    const declaration = symbol.flags & 32 /* Class */ || symbol.flags & 16 /* Function */ ? symbol.valueDeclaration : (_a = symbol.declarations) == null ? void 0 : _a.find((decl) => {
      if (decl.kind === 264 /* InterfaceDeclaration */) {
        return true;
      }
      if (decl.kind !== 260 /* VariableDeclaration */) {
        return false;
      }
      const initializer = decl.initializer;
      return !!initializer && (initializer.kind === 218 /* FunctionExpression */ || initializer.kind === 219 /* ArrowFunction */);
    });
    Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
    return getOuterTypeParameters(declaration);
  }
  function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
    if (!symbol.declarations) {
      return;
    }
    let result;
    for (const node of symbol.declarations) {
      if (node.kind === 264 /* InterfaceDeclaration */ || node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */ || isJSConstructor(node) || isTypeAlias(node)) {
        const declaration = node;
        result = appendTypeParameters(result, getEffectiveTypeParameterDeclarations(declaration));
      }
    }
    return result;
  }
  function getTypeParametersOfClassOrInterface(symbol) {
    return concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
  }
  function isMixinConstructorType(type) {
    const signatures = getSignaturesOfType(type, 1 /* Construct */);
    if (signatures.length === 1) {
      const s = signatures[0];
      if (!s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s)) {
        const paramType = getTypeOfParameter(s.parameters[0]);
        return isTypeAny(paramType) || getElementTypeOfArrayType(paramType) === anyType;
      }
    }
    return false;
  }
  function isConstructorType(type) {
    if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
      return true;
    }
    if (type.flags & 8650752 /* TypeVariable */) {
      const constraint = getBaseConstraintOfType(type);
      return !!constraint && isMixinConstructorType(constraint);
    }
    return false;
  }
  function getBaseTypeNodeOfClass(type) {
    const decl = getClassLikeDeclarationOfSymbol(type.symbol);
    return decl && getEffectiveBaseTypeNode(decl);
  }
  function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
    const typeArgCount = length(typeArgumentNodes);
    const isJavascript = isInJSFile(location);
    return filter(getSignaturesOfType(type, 1 /* Construct */), (sig) => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters));
  }
  function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
    const signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
    const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode);
    return sameMap(signatures, (sig) => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJSFile(location)) : sig);
  }
  function getBaseConstructorTypeOfClass(type) {
    if (!type.resolvedBaseConstructorType) {
      const decl = getClassLikeDeclarationOfSymbol(type.symbol);
      const extended = decl && getEffectiveBaseTypeNode(decl);
      const baseTypeNode = getBaseTypeNodeOfClass(type);
      if (!baseTypeNode) {
        return type.resolvedBaseConstructorType = undefinedType;
      }
      if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
        return errorType;
      }
      const baseConstructorType = checkExpression(baseTypeNode.expression);
      if (extended && baseTypeNode !== extended) {
        Debug.assert(!extended.typeArguments);
        checkExpression(extended.expression);
      }
      if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
        resolveStructuredTypeMembers(baseConstructorType);
      }
      if (!popTypeResolution()) {
        error(type.symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
        return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType);
      }
      if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
        const err = error(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
        if (baseConstructorType.flags & 262144 /* TypeParameter */) {
          const constraint = getConstraintFromTypeParameter(baseConstructorType);
          let ctorReturn = unknownType;
          if (constraint) {
            const ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
            if (ctorSig[0]) {
              ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
            }
          }
          if (baseConstructorType.symbol.declarations) {
            addRelatedInfo(err, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
          }
        }
        return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType);
      }
      type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = baseConstructorType);
    }
    return type.resolvedBaseConstructorType;
  }
  function getImplementsTypes(type) {
    let resolvedImplementsTypes = emptyArray;
    if (type.symbol.declarations) {
      for (const declaration of type.symbol.declarations) {
        const implementsTypeNodes = getEffectiveImplementsTypeNodes(declaration);
        if (!implementsTypeNodes) continue;
        for (const node of implementsTypeNodes) {
          const implementsType = getTypeFromTypeNode(node);
          if (!isErrorType(implementsType)) {
            if (resolvedImplementsTypes === emptyArray) {
              resolvedImplementsTypes = [implementsType];
            } else {
              resolvedImplementsTypes.push(implementsType);
            }
          }
        }
      }
    }
    return resolvedImplementsTypes;
  }
  function reportCircularBaseType(node, type) {
    error(node, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(
      type,
      /*enclosingDeclaration*/
      void 0,
      2 /* WriteArrayAsGenericType */
    ));
  }
  function getBaseTypes(type) {
    if (!type.baseTypesResolved) {
      if (pushTypeResolution(type, 6 /* ResolvedBaseTypes */)) {
        if (type.objectFlags & 8 /* Tuple */) {
          type.resolvedBaseTypes = [getTupleBaseType(type)];
        } else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
          if (type.symbol.flags & 32 /* Class */) {
            resolveBaseTypesOfClass(type);
          }
          if (type.symbol.flags & 64 /* Interface */) {
            resolveBaseTypesOfInterface(type);
          }
        } else {
          Debug.fail("type must be class or interface");
        }
        if (!popTypeResolution() && type.symbol.declarations) {
          for (const declaration of type.symbol.declarations) {
            if (declaration.kind === 263 /* ClassDeclaration */ || declaration.kind === 264 /* InterfaceDeclaration */) {
              reportCircularBaseType(declaration, type);
            }
          }
        }
      }
      type.baseTypesResolved = true;
    }
    return type.resolvedBaseTypes;
  }
  function getTupleBaseType(type) {
    const elementTypes = sameMap(type.typeParameters, (t, i) => type.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t);
    return createArrayType(getUnionType(elementTypes || emptyArray), type.readonly);
  }
  function resolveBaseTypesOfClass(type) {
    type.resolvedBaseTypes = resolvingEmptyArray;
    const baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
    if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
      return type.resolvedBaseTypes = emptyArray;
    }
    const baseTypeNode = getBaseTypeNodeOfClass(type);
    let baseType;
    const originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : void 0;
    if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) {
      baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
    } else if (baseConstructorType.flags & 1 /* Any */) {
      baseType = baseConstructorType;
    } else {
      const constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
      if (!constructors.length) {
        error(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
        return type.resolvedBaseTypes = emptyArray;
      }
      baseType = getReturnTypeOfSignature(constructors[0]);
    }
    if (isErrorType(baseType)) {
      return type.resolvedBaseTypes = emptyArray;
    }
    const reducedBaseType = getReducedType(baseType);
    if (!isValidBaseType(reducedBaseType)) {
      const elaboration = elaborateNeverIntersection(
        /*errorInfo*/
        void 0,
        baseType
      );
      const diagnostic = chainDiagnosticMessages(elaboration, Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType));
      diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(baseTypeNode.expression), baseTypeNode.expression, diagnostic));
      return type.resolvedBaseTypes = emptyArray;
    }
    if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
      error(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(
        type,
        /*enclosingDeclaration*/
        void 0,
        2 /* WriteArrayAsGenericType */
      ));
      return type.resolvedBaseTypes = emptyArray;
    }
    if (type.resolvedBaseTypes === resolvingEmptyArray) {
      type.members = void 0;
    }
    return type.resolvedBaseTypes = [reducedBaseType];
  }
  function areAllOuterTypeParametersApplied(type) {
    const outerTypeParameters = type.outerTypeParameters;
    if (outerTypeParameters) {
      const last2 = outerTypeParameters.length - 1;
      const typeArguments = getTypeArguments(type);
      return outerTypeParameters[last2].symbol !== typeArguments[last2].symbol;
    }
    return true;
  }
  function isValidBaseType(type) {
    if (type.flags & 262144 /* TypeParameter */) {
      const constraint = getBaseConstraintOfType(type);
      if (constraint) {
        return isValidBaseType(constraint);
      }
    }
    return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || type.flags & 2097152 /* Intersection */ && every(type.types, isValidBaseType));
  }
  function resolveBaseTypesOfInterface(type) {
    type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
    if (type.symbol.declarations) {
      for (const declaration of type.symbol.declarations) {
        if (declaration.kind === 264 /* InterfaceDeclaration */ && getInterfaceBaseTypeNodes(declaration)) {
          for (const node of getInterfaceBaseTypeNodes(declaration)) {
            const baseType = getReducedType(getTypeFromTypeNode(node));
            if (!isErrorType(baseType)) {
              if (isValidBaseType(baseType)) {
                if (type !== baseType && !hasBaseType(baseType, type)) {
                  if (type.resolvedBaseTypes === emptyArray) {
                    type.resolvedBaseTypes = [baseType];
                  } else {
                    type.resolvedBaseTypes.push(baseType);
                  }
                } else {
                  reportCircularBaseType(declaration, type);
                }
              } else {
                error(node, Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
              }
            }
          }
        }
      }
    }
  }
  function isThislessInterface(symbol) {
    if (!symbol.declarations) {
      return true;
    }
    for (const declaration of symbol.declarations) {
      if (declaration.kind === 264 /* InterfaceDeclaration */) {
        if (declaration.flags & 256 /* ContainsThis */) {
          return false;
        }
        const baseTypeNodes = getInterfaceBaseTypeNodes(declaration);
        if (baseTypeNodes) {
          for (const node of baseTypeNodes) {
            if (isEntityNameExpression(node.expression)) {
              const baseSymbol = resolveEntityName(
                node.expression,
                788968 /* Type */,
                /*ignoreErrors*/
                true
              );
              if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
                return false;
              }
            }
          }
        }
      }
    }
    return true;
  }
  function getDeclaredTypeOfClassOrInterface(symbol) {
    let links = getSymbolLinks(symbol);
    const originalLinks = links;
    if (!links.declaredType) {
      const kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
      const merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration));
      if (merged) {
        symbol = merged;
        links = merged.links;
      }
      const type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
      const outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
      const localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
      if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
        type.objectFlags |= 4 /* Reference */;
        type.typeParameters = concatenate(outerTypeParameters, localTypeParameters);
        type.outerTypeParameters = outerTypeParameters;
        type.localTypeParameters = localTypeParameters;
        type.instantiations = /* @__PURE__ */ new Map();
        type.instantiations.set(getTypeListId(type.typeParameters), type);
        type.target = type;
        type.resolvedTypeArguments = type.typeParameters;
        type.thisType = createTypeParameter(symbol);
        type.thisType.isThisType = true;
        type.thisType.constraint = type;
      }
    }
    return links.declaredType;
  }
  function getDeclaredTypeOfTypeAlias(symbol) {
    var _a;
    const links = getSymbolLinks(symbol);
    if (!links.declaredType) {
      if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
        return errorType;
      }
      const declaration = Debug.checkDefined((_a = symbol.declarations) == null ? void 0 : _a.find(isTypeAlias), "Type alias symbol with no valid declaration found");
      const typeNode = isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
      let type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
      if (popTypeResolution()) {
        const typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
        if (typeParameters) {
          links.typeParameters = typeParameters;
          links.instantiations = /* @__PURE__ */ new Map();
          links.instantiations.set(getTypeListId(typeParameters), type);
        }
        if (type === intrinsicMarkerType && symbol.escapedName === "BuiltinIteratorReturn") {
          type = getBuiltinIteratorReturnType();
        }
      } else {
        type = errorType;
        if (declaration.kind === 340 /* JSDocEnumTag */) {
          error(declaration.typeExpression.type, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
        } else {
          error(isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
        }
      }
      links.declaredType ?? (links.declaredType = type);
    }
    return links.declaredType;
  }
  function getBaseTypeOfEnumLikeType(type) {
    return type.flags & 1056 /* EnumLike */ && type.symbol.flags & 8 /* EnumMember */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
  }
  function getDeclaredTypeOfEnum(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.declaredType) {
      const memberTypeList = [];
      if (symbol.declarations) {
        for (const declaration of symbol.declarations) {
          if (declaration.kind === 266 /* EnumDeclaration */) {
            for (const member of declaration.members) {
              if (hasBindableName(member)) {
                const memberSymbol = getSymbolOfDeclaration(member);
                const value = getEnumMemberValue(member).value;
                const memberType = getFreshTypeOfLiteralType(
                  value !== void 0 ? getEnumLiteralType(value, getSymbolId(symbol), memberSymbol) : createComputedEnumType(memberSymbol)
                );
                getSymbolLinks(memberSymbol).declaredType = memberType;
                memberTypeList.push(getRegularTypeOfLiteralType(memberType));
              }
            }
          }
        }
      }
      const enumType = memberTypeList.length ? getUnionType(
        memberTypeList,
        1 /* Literal */,
        symbol,
        /*aliasTypeArguments*/
        void 0
      ) : createComputedEnumType(symbol);
      if (enumType.flags & 1048576 /* Union */) {
        enumType.flags |= 1024 /* EnumLiteral */;
        enumType.symbol = symbol;
      }
      links.declaredType = enumType;
    }
    return links.declaredType;
  }
  function createComputedEnumType(symbol) {
    const regularType = createTypeWithSymbol(32 /* Enum */, symbol);
    const freshType = createTypeWithSymbol(32 /* Enum */, symbol);
    regularType.regularType = regularType;
    regularType.freshType = freshType;
    freshType.regularType = regularType;
    freshType.freshType = freshType;
    return regularType;
  }
  function getDeclaredTypeOfEnumMember(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.declaredType) {
      const enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
      if (!links.declaredType) {
        links.declaredType = enumType;
      }
    }
    return links.declaredType;
  }
  function getDeclaredTypeOfTypeParameter(symbol) {
    const links = getSymbolLinks(symbol);
    return links.declaredType || (links.declaredType = createTypeParameter(symbol));
  }
  function getDeclaredTypeOfAlias(symbol) {
    const links = getSymbolLinks(symbol);
    return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
  }
  function getDeclaredTypeOfSymbol(symbol) {
    return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
  }
  function tryGetDeclaredTypeOfSymbol(symbol) {
    if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
      return getDeclaredTypeOfClassOrInterface(symbol);
    }
    if (symbol.flags & 524288 /* TypeAlias */) {
      return getDeclaredTypeOfTypeAlias(symbol);
    }
    if (symbol.flags & 262144 /* TypeParameter */) {
      return getDeclaredTypeOfTypeParameter(symbol);
    }
    if (symbol.flags & 384 /* Enum */) {
      return getDeclaredTypeOfEnum(symbol);
    }
    if (symbol.flags & 8 /* EnumMember */) {
      return getDeclaredTypeOfEnumMember(symbol);
    }
    if (symbol.flags & 2097152 /* Alias */) {
      return getDeclaredTypeOfAlias(symbol);
    }
    return void 0;
  }
  function isThislessType(node) {
    switch (node.kind) {
      case 133 /* AnyKeyword */:
      case 159 /* UnknownKeyword */:
      case 154 /* StringKeyword */:
      case 150 /* NumberKeyword */:
      case 163 /* BigIntKeyword */:
      case 136 /* BooleanKeyword */:
      case 155 /* SymbolKeyword */:
      case 151 /* ObjectKeyword */:
      case 116 /* VoidKeyword */:
      case 157 /* UndefinedKeyword */:
      case 146 /* NeverKeyword */:
      case 201 /* LiteralType */:
        return true;
      case 188 /* ArrayType */:
        return isThislessType(node.elementType);
      case 183 /* TypeReference */:
        return !node.typeArguments || node.typeArguments.every(isThislessType);
    }
    return false;
  }
  function isThislessTypeParameter(node) {
    const constraint = getEffectiveConstraintOfTypeParameter(node);
    return !constraint || isThislessType(constraint);
  }
  function isThislessVariableLikeDeclaration(node) {
    const typeNode = getEffectiveTypeAnnotationNode(node);
    return typeNode ? isThislessType(typeNode) : !hasInitializer(node);
  }
  function isThislessFunctionLikeDeclaration(node) {
    const returnType = getEffectiveReturnTypeNode(node);
    const typeParameters = getEffectiveTypeParameterDeclarations(node);
    return (node.kind === 176 /* Constructor */ || !!returnType && isThislessType(returnType)) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter);
  }
  function isThisless(symbol) {
    if (symbol.declarations && symbol.declarations.length === 1) {
      const declaration = symbol.declarations[0];
      if (declaration) {
        switch (declaration.kind) {
          case 172 /* PropertyDeclaration */:
          case 171 /* PropertySignature */:
            return isThislessVariableLikeDeclaration(declaration);
          case 174 /* MethodDeclaration */:
          case 173 /* MethodSignature */:
          case 176 /* Constructor */:
          case 177 /* GetAccessor */:
          case 178 /* SetAccessor */:
            return isThislessFunctionLikeDeclaration(declaration);
        }
      }
    }
    return false;
  }
  function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
    const result = createSymbolTable();
    for (const symbol of symbols) {
      result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
    }
    return result;
  }
  function addInheritedMembers(symbols, baseSymbols) {
    for (const base of baseSymbols) {
      if (isStaticPrivateIdentifierProperty(base)) {
        continue;
      }
      const derived = symbols.get(base.escapedName);
      if (!derived || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration) && !isConstructorDeclaredProperty(derived) && !getContainingClassStaticBlock(derived.valueDeclaration)) {
        symbols.set(base.escapedName, base);
        symbols.set(base.escapedName, base);
      }
    }
  }
  function isStaticPrivateIdentifierProperty(s) {
    return !!s.valueDeclaration && isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && isStatic(s.valueDeclaration);
  }
  function resolveDeclaredMembers(type) {
    if (!type.declaredProperties) {
      const symbol = type.symbol;
      const members = getMembersOfSymbol(symbol);
      type.declaredProperties = getNamedMembers(members);
      type.declaredCallSignatures = emptyArray;
      type.declaredConstructSignatures = emptyArray;
      type.declaredIndexInfos = emptyArray;
      type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
      type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
      type.declaredIndexInfos = getIndexInfosOfSymbol(symbol);
    }
    return type;
  }
  function isLateBindableName(node) {
    return isLateBindableAST(node) && isTypeUsableAsPropertyName(isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(node.argumentExpression));
  }
  function isLateBindableIndexSignature(node) {
    return isLateBindableAST(node) && isTypeUsableAsIndexSignature(isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(node.argumentExpression));
  }
  function isLateBindableAST(node) {
    if (!isComputedPropertyName(node) && !isElementAccessExpression(node)) {
      return false;
    }
    const expr = isComputedPropertyName(node) ? node.expression : node.argumentExpression;
    return isEntityNameExpression(expr);
  }
  function isTypeUsableAsIndexSignature(type) {
    return isTypeAssignableTo(type, stringNumberSymbolType);
  }
  function isLateBoundName(name) {
    return name.charCodeAt(0) === 95 /* _ */ && name.charCodeAt(1) === 95 /* _ */ && name.charCodeAt(2) === 64 /* at */;
  }
  function hasLateBindableName(node) {
    const name = getNameOfDeclaration(node);
    return !!name && isLateBindableName(name);
  }
  function hasLateBindableIndexSignature(node) {
    const name = getNameOfDeclaration(node);
    return !!name && isLateBindableIndexSignature(name);
  }
  function hasBindableName(node) {
    return !hasDynamicName(node) || hasLateBindableName(node);
  }
  function isNonBindableDynamicName(node) {
    return isDynamicName(node) && !isLateBindableName(node);
  }
  function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
    Debug.assert(!!(getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
    symbol.flags |= symbolFlags;
    getSymbolLinks(member.symbol).lateSymbol = symbol;
    if (!symbol.declarations) {
      symbol.declarations = [member];
    } else if (!member.symbol.isReplaceableByMethod) {
      symbol.declarations.push(member);
    }
    if (symbolFlags & 111551 /* Value */) {
      if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
        symbol.valueDeclaration = member;
      }
    }
  }
  function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
    Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
    const links = getNodeLinks(decl);
    if (!links.resolvedSymbol) {
      links.resolvedSymbol = decl.symbol;
      const declName = isBinaryExpression(decl) ? decl.left : decl.name;
      const type = isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
      if (isTypeUsableAsPropertyName(type)) {
        const memberName = getPropertyNameFromType(type);
        const symbolFlags = decl.symbol.flags;
        let lateSymbol = lateSymbols.get(memberName);
        if (!lateSymbol) lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
        const earlySymbol = earlySymbols && earlySymbols.get(memberName);
        if (!(parent.flags & 32 /* Class */) && lateSymbol.flags & getExcludedSymbolFlags(symbolFlags)) {
          const declarations = earlySymbol ? concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
          const name = !(type.flags & 8192 /* UniqueESSymbol */) && unescapeLeadingUnderscores(memberName) || declarationNameToString(declName);
          forEach(declarations, (declaration) => error(getNameOfDeclaration(declaration) || declaration, Diagnostics.Property_0_was_also_declared_here, name));
          error(declName || decl, Diagnostics.Duplicate_property_0, name);
          lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
        }
        lateSymbol.links.nameType = type;
        addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
        if (lateSymbol.parent) {
          Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
        } else {
          lateSymbol.parent = parent;
        }
        return links.resolvedSymbol = lateSymbol;
      }
    }
    return links.resolvedSymbol;
  }
  function lateBindIndexSignature(parent, earlySymbols, lateSymbols, decl) {
    let indexSymbol = lateSymbols.get("__index" /* Index */);
    if (!indexSymbol) {
      const early = earlySymbols == null ? void 0 : earlySymbols.get("__index" /* Index */);
      if (!early) {
        indexSymbol = createSymbol(0 /* None */, "__index" /* Index */, 4096 /* Late */);
      } else {
        indexSymbol = cloneSymbol(early);
        indexSymbol.links.checkFlags |= 4096 /* Late */;
      }
      lateSymbols.set("__index" /* Index */, indexSymbol);
    }
    if (!indexSymbol.declarations) {
      indexSymbol.declarations = [decl];
    } else if (!decl.symbol.isReplaceableByMethod) {
      indexSymbol.declarations.push(decl);
    }
  }
  function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
    const links = getSymbolLinks(symbol);
    if (!links[resolutionKind]) {
      const isStatic2 = resolutionKind === "resolvedExports" /* resolvedExports */;
      const earlySymbols = !isStatic2 ? symbol.members : symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol).exports : symbol.exports;
      links[resolutionKind] = earlySymbols || emptySymbols;
      const lateSymbols = createSymbolTable();
      for (const decl of symbol.declarations || emptyArray) {
        const members = getMembersOfDeclaration(decl);
        if (members) {
          for (const member of members) {
            if (isStatic2 === hasStaticModifier(member)) {
              if (hasLateBindableName(member)) {
                lateBindMember(symbol, earlySymbols, lateSymbols, member);
              } else if (hasLateBindableIndexSignature(member)) {
                lateBindIndexSignature(symbol, earlySymbols, lateSymbols, member);
              }
            }
          }
        }
      }
      const assignments = getFunctionExpressionParentSymbolOrSymbol(symbol).assignmentDeclarationMembers;
      if (assignments) {
        const decls = arrayFrom(assignments.values());
        for (const member of decls) {
          const assignmentKind = getAssignmentDeclarationKind(member);
          const isInstanceMember = assignmentKind === 3 /* PrototypeProperty */ || isBinaryExpression(member) && isPossiblyAliasedThisProperty(member, assignmentKind) || assignmentKind === 9 /* ObjectDefinePrototypeProperty */ || assignmentKind === 6 /* Prototype */;
          if (isStatic2 === !isInstanceMember) {
            if (hasLateBindableName(member)) {
              lateBindMember(symbol, earlySymbols, lateSymbols, member);
            }
          }
        }
      }
      let resolved = combineSymbolTables(earlySymbols, lateSymbols);
      if (symbol.flags & 33554432 /* Transient */ && links.cjsExportMerged && symbol.declarations) {
        for (const decl of symbol.declarations) {
          const original = getSymbolLinks(decl.symbol)[resolutionKind];
          if (!resolved) {
            resolved = original;
            continue;
          }
          if (!original) continue;
          original.forEach((s, name) => {
            const existing = resolved.get(name);
            if (!existing) resolved.set(name, s);
            else if (existing === s) return;
            else resolved.set(name, mergeSymbol(existing, s));
          });
        }
      }
      links[resolutionKind] = resolved || emptySymbols;
    }
    return links[resolutionKind];
  }
  function getMembersOfSymbol(symbol) {
    return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) : symbol.members || emptySymbols;
  }
  function getLateBoundSymbol(symbol) {
    if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
      const links = getSymbolLinks(symbol);
      if (!links.lateSymbol && some(symbol.declarations, hasLateBindableName)) {
        const parent = getMergedSymbol(symbol.parent);
        if (some(symbol.declarations, hasStaticModifier)) {
          getExportsOfSymbol(parent);
        } else {
          getMembersOfSymbol(parent);
        }
      }
      return links.lateSymbol || (links.lateSymbol = symbol);
    }
    return symbol;
  }
  function getTypeWithThisArgument(type, thisArgument, needApparentType) {
    if (getObjectFlags(type) & 4 /* Reference */) {
      const target = type.target;
      const typeArguments = getTypeArguments(type);
      return length(target.typeParameters) === length(typeArguments) ? createTypeReference(target, concatenate(typeArguments, [thisArgument || target.thisType])) : type;
    } else if (type.flags & 2097152 /* Intersection */) {
      const types = sameMap(type.types, (t) => getTypeWithThisArgument(t, thisArgument, needApparentType));
      return types !== type.types ? getIntersectionType(types) : type;
    }
    return needApparentType ? getApparentType(type) : type;
  }
  function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
    let mapper;
    let members;
    let callSignatures;
    let constructSignatures;
    let indexInfos;
    if (rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
      members = source.symbol ? getMembersOfSymbol(source.symbol) : createSymbolTable(source.declaredProperties);
      callSignatures = source.declaredCallSignatures;
      constructSignatures = source.declaredConstructSignatures;
      indexInfos = source.declaredIndexInfos;
    } else {
      mapper = createTypeMapper(typeParameters, typeArguments);
      members = createInstantiatedSymbolTable(
        source.declaredProperties,
        mapper,
        /*mappingThisOnly*/
        typeParameters.length === 1
      );
      callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
      constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
      indexInfos = instantiateIndexInfos(source.declaredIndexInfos, mapper);
    }
    const baseTypes = getBaseTypes(source);
    if (baseTypes.length) {
      if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
        const symbolTable = createSymbolTable(source.declaredProperties);
        const sourceIndex = getIndexSymbol(source.symbol);
        if (sourceIndex) {
          symbolTable.set("__index" /* Index */, sourceIndex);
        }
        members = symbolTable;
      }
      setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos);
      const thisArgument = lastOrUndefined(typeArguments);
      for (const baseType of baseTypes) {
        const instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
        addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
        callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
        constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
        const inheritedIndexInfos = instantiatedBaseType !== anyType ? getIndexInfosOfType(instantiatedBaseType) : [anyBaseTypeIndexInfo];
        indexInfos = concatenate(indexInfos, filter(inheritedIndexInfos, (info) => !findIndexInfo(indexInfos, info.keyType)));
      }
    }
    setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos);
  }
  function resolveClassOrInterfaceMembers(type) {
    resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray);
  }
  function resolveTypeReferenceMembers(type) {
    const source = resolveDeclaredMembers(type.target);
    const typeParameters = concatenate(source.typeParameters, [source.thisType]);
    const typeArguments = getTypeArguments(type);
    const paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : concatenate(typeArguments, [type]);
    resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
  }
  function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
    const sig = new Signature5(checker, flags);
    sig.declaration = declaration;
    sig.typeParameters = typeParameters;
    sig.parameters = parameters;
    sig.thisParameter = thisParameter;
    sig.resolvedReturnType = resolvedReturnType;
    sig.resolvedTypePredicate = resolvedTypePredicate;
    sig.minArgumentCount = minArgumentCount;
    sig.resolvedMinArgumentCount = void 0;
    sig.target = void 0;
    sig.mapper = void 0;
    sig.compositeSignatures = void 0;
    sig.compositeKind = void 0;
    return sig;
  }
  function cloneSignature(sig) {
    const result = createSignature(
      sig.declaration,
      sig.typeParameters,
      sig.thisParameter,
      sig.parameters,
      /*resolvedReturnType*/
      void 0,
      /*resolvedTypePredicate*/
      void 0,
      sig.minArgumentCount,
      sig.flags & 167 /* PropagatingFlags */
    );
    result.target = sig.target;
    result.mapper = sig.mapper;
    result.compositeSignatures = sig.compositeSignatures;
    result.compositeKind = sig.compositeKind;
    return result;
  }
  function createUnionSignature(signature, unionSignatures) {
    const result = cloneSignature(signature);
    result.compositeSignatures = unionSignatures;
    result.compositeKind = 1048576 /* Union */;
    result.target = void 0;
    result.mapper = void 0;
    return result;
  }
  function getOptionalCallSignature(signature, callChainFlags) {
    if ((signature.flags & 24 /* CallChainFlags */) === callChainFlags) {
      return signature;
    }
    if (!signature.optionalCallSignatureCache) {
      signature.optionalCallSignatureCache = {};
    }
    const key = callChainFlags === 8 /* IsInnerCallChain */ ? "inner" : "outer";
    return signature.optionalCallSignatureCache[key] || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
  }
  function createOptionalCallSignature(signature, callChainFlags) {
    Debug.assert(callChainFlags === 8 /* IsInnerCallChain */ || callChainFlags === 16 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both.");
    const result = cloneSignature(signature);
    result.flags |= callChainFlags;
    return result;
  }
  function getExpandedParameters(sig, skipUnionExpanding) {
    if (signatureHasRestParameter(sig)) {
      const restIndex = sig.parameters.length - 1;
      const restSymbol = sig.parameters[restIndex];
      const restType = getTypeOfSymbol(restSymbol);
      if (isTupleType(restType)) {
        return [expandSignatureParametersWithTupleMembers(restType, restIndex, restSymbol)];
      } else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && every(restType.types, isTupleType)) {
        return map(restType.types, (t) => expandSignatureParametersWithTupleMembers(t, restIndex, restSymbol));
      }
    }
    return [sig.parameters];
    function expandSignatureParametersWithTupleMembers(restType, restIndex, restSymbol) {
      const elementTypes = getTypeArguments(restType);
      const associatedNames = getUniqAssociatedNamesFromTupleType(restType, restSymbol);
      const restParams = map(elementTypes, (t, i) => {
        const name = associatedNames && associatedNames[i] ? associatedNames[i] : getParameterNameAtPosition(sig, restIndex + i, restType);
        const flags = restType.target.elementFlags[i];
        const checkFlags = flags & 12 /* Variable */ ? 32768 /* RestParameter */ : flags & 2 /* Optional */ ? 16384 /* OptionalParameter */ : 0;
        const symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
        symbol.links.type = flags & 4 /* Rest */ ? createArrayType(t) : t;
        return symbol;
      });
      return concatenate(sig.parameters.slice(0, restIndex), restParams);
    }
    function getUniqAssociatedNamesFromTupleType(type, restSymbol) {
      const names = map(type.target.labeledElementDeclarations, (labeledElement, i) => getTupleElementLabel(labeledElement, i, type.target.elementFlags[i], restSymbol));
      if (names) {
        const duplicates = [];
        const uniqueNames = /* @__PURE__ */ new Set();
        for (let i = 0; i < names.length; i++) {
          const name = names[i];
          if (!tryAddToSet(uniqueNames, name)) {
            duplicates.push(i);
          }
        }
        const counters = /* @__PURE__ */ new Map();
        for (const i of duplicates) {
          let counter = counters.get(names[i]) ?? 1;
          let name;
          while (!tryAddToSet(uniqueNames, name = `${names[i]}_${counter}`)) {
            counter++;
          }
          names[i] = name;
          counters.set(names[i], counter + 1);
        }
      }
      return names;
    }
  }
  function getDefaultConstructSignatures(classType) {
    const baseConstructorType = getBaseConstructorTypeOfClass(classType);
    const baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
    const declaration = getClassLikeDeclarationOfSymbol(classType.symbol);
    const isAbstract = !!declaration && hasSyntacticModifier(declaration, 64 /* Abstract */);
    if (baseSignatures.length === 0) {
      return [createSignature(
        /*declaration*/
        void 0,
        classType.localTypeParameters,
        /*thisParameter*/
        void 0,
        emptyArray,
        classType,
        /*resolvedTypePredicate*/
        void 0,
        0,
        isAbstract ? 4 /* Abstract */ : 0 /* None */
      )];
    }
    const baseTypeNode = getBaseTypeNodeOfClass(classType);
    const isJavaScript = isInJSFile(baseTypeNode);
    const typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
    const typeArgCount = length(typeArguments);
    const result = [];
    for (const baseSig of baseSignatures) {
      const minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
      const typeParamCount = length(baseSig.typeParameters);
      if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
        const sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
        sig.typeParameters = classType.localTypeParameters;
        sig.resolvedReturnType = classType;
        sig.flags = isAbstract ? sig.flags | 4 /* Abstract */ : sig.flags & ~4 /* Abstract */;
        result.push(sig);
      }
    }
    return result;
  }
  function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
    for (const s of signatureList) {
      if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
        return s;
      }
    }
  }
  function findMatchingSignatures(signatureLists, signature, listIndex) {
    if (signature.typeParameters) {
      if (listIndex > 0) {
        return void 0;
      }
      for (let i = 1; i < signatureLists.length; i++) {
        if (!findMatchingSignature(
          signatureLists[i],
          signature,
          /*partialMatch*/
          false,
          /*ignoreThisTypes*/
          false,
          /*ignoreReturnTypes*/
          false
        )) {
          return void 0;
        }
      }
      return [signature];
    }
    let result;
    for (let i = 0; i < signatureLists.length; i++) {
      const match = i === listIndex ? signature : findMatchingSignature(
        signatureLists[i],
        signature,
        /*partialMatch*/
        false,
        /*ignoreThisTypes*/
        false,
        /*ignoreReturnTypes*/
        true
      ) || findMatchingSignature(
        signatureLists[i],
        signature,
        /*partialMatch*/
        true,
        /*ignoreThisTypes*/
        false,
        /*ignoreReturnTypes*/
        true
      );
      if (!match) {
        return void 0;
      }
      result = appendIfUnique(result, match);
    }
    return result;
  }
  function getUnionSignatures(signatureLists) {
    let result;
    let indexWithLengthOverOne;
    for (let i = 0; i < signatureLists.length; i++) {
      if (signatureLists[i].length === 0) return emptyArray;
      if (signatureLists[i].length > 1) {
        indexWithLengthOverOne = indexWithLengthOverOne === void 0 ? i : -1;
      }
      for (const signature of signatureLists[i]) {
        if (!result || !findMatchingSignature(
          result,
          signature,
          /*partialMatch*/
          false,
          /*ignoreThisTypes*/
          false,
          /*ignoreReturnTypes*/
          true
        )) {
          const unionSignatures = findMatchingSignatures(signatureLists, signature, i);
          if (unionSignatures) {
            let s = signature;
            if (unionSignatures.length > 1) {
              let thisParameter = signature.thisParameter;
              const firstThisParameterOfUnionSignatures = forEach(unionSignatures, (sig) => sig.thisParameter);
              if (firstThisParameterOfUnionSignatures) {
                const thisType = getIntersectionType(mapDefined(unionSignatures, (sig) => sig.thisParameter && getTypeOfSymbol(sig.thisParameter)));
                thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
              }
              s = createUnionSignature(signature, unionSignatures);
              s.thisParameter = thisParameter;
            }
            (result || (result = [])).push(s);
          }
        }
      }
    }
    if (!length(result) && indexWithLengthOverOne !== -1) {
      const masterList = signatureLists[indexWithLengthOverOne !== void 0 ? indexWithLengthOverOne : 0];
      let results = masterList.slice();
      for (const signatures of signatureLists) {
        if (signatures !== masterList) {
          const signature = signatures[0];
          Debug.assert(!!signature, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
          results = !!signature.typeParameters && some(results, (s) => !!s.typeParameters && !compareTypeParametersIdentical(signature.typeParameters, s.typeParameters)) ? void 0 : map(results, (sig) => combineSignaturesOfUnionMembers(sig, signature));
          if (!results) {
            break;
          }
        }
      }
      result = results;
    }
    return result || emptyArray;
  }
  function compareTypeParametersIdentical(sourceParams, targetParams) {
    if (length(sourceParams) !== length(targetParams)) {
      return false;
    }
    if (!sourceParams || !targetParams) {
      return true;
    }
    const mapper = createTypeMapper(targetParams, sourceParams);
    for (let i = 0; i < sourceParams.length; i++) {
      const source = sourceParams[i];
      const target = targetParams[i];
      if (source === target) continue;
      if (!isTypeIdenticalTo(getConstraintFromTypeParameter(source) || unknownType, instantiateType(getConstraintFromTypeParameter(target) || unknownType, mapper))) return false;
    }
    return true;
  }
  function combineUnionThisParam(left, right, mapper) {
    if (!left || !right) {
      return left || right;
    }
    const thisType = getIntersectionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]);
    return createSymbolWithType(left, thisType);
  }
  function combineUnionParameters(left, right, mapper) {
    const leftCount = getParameterCount(left);
    const rightCount = getParameterCount(right);
    const longest = leftCount >= rightCount ? left : right;
    const shorter = longest === left ? right : left;
    const longestCount = longest === left ? leftCount : rightCount;
    const eitherHasEffectiveRest = hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right);
    const needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
    const params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
    for (let i = 0; i < longestCount; i++) {
      let longestParamType = tryGetTypeAtPosition(longest, i);
      if (longest === right) {
        longestParamType = instantiateType(longestParamType, mapper);
      }
      let shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
      if (shorter === right) {
        shorterParamType = instantiateType(shorterParamType, mapper);
      }
      const unionParamType = getIntersectionType([longestParamType, shorterParamType]);
      const isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === longestCount - 1;
      const isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
      const leftName = i >= leftCount ? void 0 : getParameterNameAtPosition(left, i);
      const rightName = i >= rightCount ? void 0 : getParameterNameAtPosition(right, i);
      const paramName = leftName === rightName ? leftName : !leftName ? rightName : !rightName ? leftName : void 0;
      const paramSymbol = createSymbol(
        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 combineSignaturesOfUnionMembers(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 = combineUnionParameters(left, right, paramMapper);
    const lastParam = lastOrUndefined(params);
    if (lastParam && getCheckFlags(lastParam) & 32768 /* RestParameter */) {
      flags |= 1 /* HasRestParameter */;
    }
    const thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter, paramMapper);
    const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
    const result = createSignature(
      declaration,
      typeParams,
      thisParam,
      params,
      /*resolvedReturnType*/
      void 0,
      /*resolvedTypePredicate*/
      void 0,
      minArgCount,
      flags
    );
    result.compositeKind = 1048576 /* Union */;
    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;
    } else if (left.compositeKind !== 2097152 /* Intersection */ && left.mapper && left.compositeSignatures) {
      result.mapper = left.mapper;
    }
    return result;
  }
  function getUnionIndexInfos(types) {
    const sourceInfos = getIndexInfosOfType(types[0]);
    if (sourceInfos) {
      const result = [];
      for (const info of sourceInfos) {
        const indexType = info.keyType;
        if (every(types, (t) => !!getIndexInfoOfType(t, indexType))) {
          result.push(createIndexInfo(indexType, getUnionType(map(types, (t) => getIndexTypeOfType(t, indexType))), some(types, (t) => getIndexInfoOfType(t, indexType).isReadonly)));
        }
      }
      return result;
    }
    return emptyArray;
  }
  function resolveUnionTypeMembers(type) {
    const callSignatures = getUnionSignatures(map(type.types, (t) => t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */)));
    const constructSignatures = getUnionSignatures(map(type.types, (t) => getSignaturesOfType(t, 1 /* Construct */)));
    const indexInfos = getUnionIndexInfos(type.types);
    setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, indexInfos);
  }
  function intersectTypes(type1, type2) {
    return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
  }
  function findMixins(types) {
    const constructorTypeCount = countWhere(types, (t) => getSignaturesOfType(t, 1 /* Construct */).length > 0);
    const mixinFlags = map(types, isMixinConstructorType);
    if (constructorTypeCount > 0 && constructorTypeCount === countWhere(mixinFlags, (b) => b)) {
      const firstMixinIndex = mixinFlags.indexOf(
        /*searchElement*/
        true
      );
      mixinFlags[firstMixinIndex] = false;
    }
    return mixinFlags;
  }
  function includeMixinType(type, types, mixinFlags, index) {
    const mixedTypes = [];
    for (let i = 0; i < types.length; i++) {
      if (i === index) {
        mixedTypes.push(type);
      } else if (mixinFlags[i]) {
        mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
      }
    }
    return getIntersectionType(mixedTypes);
  }
  function resolveIntersectionTypeMembers(type) {
    let callSignatures;
    let constructSignatures;
    let indexInfos;
    const types = type.types;
    const mixinFlags = findMixins(types);
    const mixinCount = countWhere(mixinFlags, (b) => b);
    for (let i = 0; i < types.length; i++) {
      const t = type.types[i];
      if (!mixinFlags[i]) {
        let signatures = getSignaturesOfType(t, 1 /* Construct */);
        if (signatures.length && mixinCount > 0) {
          signatures = map(signatures, (s) => {
            const clone = cloneSignature(s);
            clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
            return clone;
          });
        }
        constructSignatures = appendSignatures(constructSignatures, signatures);
      }
      callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
      indexInfos = reduceLeft(getIndexInfosOfType(t), (infos, newInfo) => appendIndexInfo(
        infos,
        newInfo,
        /*union*/
        false
      ), indexInfos);
    }
    setStructuredTypeMembers(type, emptySymbols, callSignatures || emptyArray, constructSignatures || emptyArray, indexInfos || emptyArray);
  }
  function appendSignatures(signatures, newSignatures) {
    for (const sig of newSignatures) {
      if (!signatures || every(signatures, (s) => !compareSignaturesIdentical(
        s,
        sig,
        /*partialMatch*/
        false,
        /*ignoreThisTypes*/
        false,
        /*ignoreReturnTypes*/
        false,
        compareTypesIdentical
      ))) {
        signatures = append(signatures, sig);
      }
    }
    return signatures;
  }
  function appendIndexInfo(indexInfos, newInfo, union) {
    if (indexInfos) {
      for (let i = 0; i < indexInfos.length; i++) {
        const info = indexInfos[i];
        if (info.keyType === newInfo.keyType) {
          indexInfos[i] = createIndexInfo(info.keyType, union ? getUnionType([info.type, newInfo.type]) : getIntersectionType([info.type, newInfo.type]), union ? info.isReadonly || newInfo.isReadonly : info.isReadonly && newInfo.isReadonly);
          return indexInfos;
        }
      }
    }
    return append(indexInfos, newInfo);
  }
  function resolveAnonymousTypeMembers(type) {
    if (type.target) {
      setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray);
      const members2 = createInstantiatedSymbolTable(
        getPropertiesOfObjectType(type.target),
        type.mapper,
        /*mappingThisOnly*/
        false
      );
      const callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
      const constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
      const indexInfos2 = instantiateIndexInfos(getIndexInfosOfType(type.target), type.mapper);
      setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2);
      return;
    }
    const symbol = getMergedSymbol(type.symbol);
    if (symbol.flags & 2048 /* TypeLiteral */) {
      setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray);
      const members2 = getMembersOfSymbol(symbol);
      const callSignatures = getSignaturesOfSymbol(members2.get("__call" /* Call */));
      const constructSignatures = getSignaturesOfSymbol(members2.get("__new" /* New */));
      const indexInfos2 = getIndexInfosOfSymbol(symbol);
      setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2);
      return;
    }
    let members = getExportsOfSymbol(symbol);
    let indexInfos;
    if (symbol === globalThisSymbol) {
      const varsOnly = /* @__PURE__ */ new Map();
      members.forEach((p) => {
        var _a;
        if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) {
          varsOnly.set(p.escapedName, p);
        }
      });
      members = varsOnly;
    }
    let baseConstructorIndexInfo;
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, emptyArray);
    if (symbol.flags & 32 /* Class */) {
      const classType = getDeclaredTypeOfClassOrInterface(symbol);
      const baseConstructorType = getBaseConstructorTypeOfClass(classType);
      if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
        members = createSymbolTable(getNamedOrIndexSignatureMembers(members));
        addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
      } else if (baseConstructorType === anyType) {
        baseConstructorIndexInfo = anyBaseTypeIndexInfo;
      }
    }
    const indexSymbol = getIndexSymbolFromSymbolTable(members);
    if (indexSymbol) {
      indexInfos = getIndexInfosOfIndexSymbol(indexSymbol, arrayFrom(members.values()));
    } else {
      if (baseConstructorIndexInfo) {
        indexInfos = append(indexInfos, baseConstructorIndexInfo);
      }
      if (symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || some(type.properties, (prop) => !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */)))) {
        indexInfos = append(indexInfos, enumNumberIndexInfo);
      }
    }
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos || emptyArray);
    if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
      type.callSignatures = getSignaturesOfSymbol(symbol);
    }
    if (symbol.flags & 32 /* Class */) {
      const classType = getDeclaredTypeOfClassOrInterface(symbol);
      let constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : emptyArray;
      if (symbol.flags & 16 /* Function */) {
        constructSignatures = addRange(
          constructSignatures.slice(),
          mapDefined(
            type.callSignatures,
            (sig) => isJSConstructor(sig.declaration) ? createSignature(
              sig.declaration,
              sig.typeParameters,
              sig.thisParameter,
              sig.parameters,
              classType,
              /*resolvedTypePredicate*/
              void 0,
              sig.minArgumentCount,
              sig.flags & 167 /* PropagatingFlags */
            ) : void 0
          )
        );
      }
      if (!constructSignatures.length) {
        constructSignatures = getDefaultConstructSignatures(classType);
      }
      type.constructSignatures = constructSignatures;
    }
  }
  function replaceIndexedAccess(instantiable, type, replacement) {
    return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getNumberLiteralType(0), createTupleType([replacement])]));
  }
  function getLimitedConstraint(type) {
    const constraint = getConstraintTypeFromMappedType(type.mappedType);
    if (!(constraint.flags & 1048576 /* Union */ || constraint.flags & 2097152 /* Intersection */)) {
      return;
    }
    const origin = constraint.flags & 1048576 /* Union */ ? constraint.origin : constraint;
    if (!origin || !(origin.flags & 2097152 /* Intersection */)) {
      return;
    }
    const limitedConstraint = getIntersectionType(origin.types.filter((t) => t !== type.constraintType));
    return limitedConstraint !== neverType ? limitedConstraint : void 0;
  }
  function resolveReverseMappedTypeMembers(type) {
    const indexInfo = getIndexInfoOfType(type.source, stringType);
    const modifiers = getMappedTypeModifiers(type.mappedType);
    const readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
    const optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
    const indexInfos = indexInfo ? [createIndexInfo(stringType, inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType) || unknownType, readonlyMask && indexInfo.isReadonly)] : emptyArray;
    const members = createSymbolTable();
    const limitedConstraint = getLimitedConstraint(type);
    for (const prop of getPropertiesOfType(type.source)) {
      if (limitedConstraint) {
        const propertyNameType = getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */);
        if (!isTypeAssignableTo(propertyNameType, limitedConstraint)) {
          continue;
        }
      }
      const checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
      const inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
      inferredProp.declarations = prop.declarations;
      inferredProp.links.nameType = getSymbolLinks(prop).nameType;
      inferredProp.links.propertyType = getTypeOfSymbol(prop);
      if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) {
        const newTypeParam = type.constraintType.type.objectType;
        const newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam);
        inferredProp.links.mappedType = newMappedType;
        inferredProp.links.constraintType = getIndexType(newTypeParam);
      } else {
        inferredProp.links.mappedType = type.mappedType;
        inferredProp.links.constraintType = type.constraintType;
      }
      members.set(prop.escapedName, inferredProp);
    }
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos);
  }
  function getLowerBoundOfKeyType(type) {
    if (type.flags & 4194304 /* Index */) {
      const t = getApparentType(type.type);
      return isGenericTupleType(t) ? getKnownKeysOfTupleType(t) : getIndexType(t);
    }
    if (type.flags & 16777216 /* Conditional */) {
      if (type.root.isDistributive) {
        const checkType = type.checkType;
        const constraint = getLowerBoundOfKeyType(checkType);
        if (constraint !== checkType) {
          return getConditionalTypeInstantiation(
            type,
            prependTypeMapping(type.root.checkType, constraint, type.mapper),
            /*forConstraint*/
            false
          );
        }
      }
      return type;
    }
    if (type.flags & 1048576 /* Union */) {
      return mapType(
        type,
        getLowerBoundOfKeyType,
        /*noReductions*/
        true
      );
    }
    if (type.flags & 2097152 /* Intersection */) {
      const types = type.types;
      if (types.length === 2 && !!(types[0].flags & (4 /* String */ | 8 /* Number */ | 64 /* BigInt */)) && types[1] === emptyTypeLiteralType) {
        return type;
      }
      return getIntersectionType(sameMap(type.types, getLowerBoundOfKeyType));
    }
    return type;
  }
  function getIsLateCheckFlag(s) {
    return getCheckFlags(s) & 4096 /* Late */;
  }
  function forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(type, include, stringsOnly, cb) {
    for (const prop of getPropertiesOfType(type)) {
      cb(getLiteralTypeFromProperty(prop, include));
    }
    if (type.flags & 1 /* Any */) {
      cb(stringType);
    } else {
      for (const info of getIndexInfosOfType(type)) {
        if (!stringsOnly || info.keyType.flags & (4 /* String */ | 134217728 /* TemplateLiteral */)) {
          cb(info.keyType);
        }
      }
    }
  }
  function resolveMappedTypeMembers(type) {
    const members = createSymbolTable();
    let indexInfos;
    setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray);
    const typeParameter = getTypeParameterFromMappedType(type);
    const constraintType = getConstraintTypeFromMappedType(type);
    const mappedType = type.target || type;
    const nameType = getNameTypeFromMappedType(mappedType);
    const shouldLinkPropDeclarations = getMappedTypeNameTypeKind(mappedType) !== 2 /* Remapping */;
    const templateType = getTemplateTypeFromMappedType(mappedType);
    const modifiersType = getApparentType(getModifiersTypeFromMappedType(type));
    const templateModifiers = getMappedTypeModifiers(type);
    const include = 8576 /* StringOrNumberLiteralOrUnique */;
    if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
      forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(
        modifiersType,
        include,
        /*stringsOnly*/
        false,
        addMemberForKeyType
      );
    } else {
      forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
    }
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos || emptyArray);
    function addMemberForKeyType(keyType) {
      const propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType;
      forEachType(propNameType, (t) => addMemberForKeyTypeWorker(keyType, t));
    }
    function addMemberForKeyTypeWorker(keyType, propNameType) {
      if (isTypeUsableAsPropertyName(propNameType)) {
        const propName = getPropertyNameFromType(propNameType);
        const existingProp = members.get(propName);
        if (existingProp) {
          existingProp.links.nameType = getUnionType([existingProp.links.nameType, propNameType]);
          existingProp.links.keyType = getUnionType([existingProp.links.keyType, keyType]);
        } else {
          const modifiersProp = isTypeUsableAsPropertyName(keyType) ? getPropertyOfType(modifiersType, getPropertyNameFromType(keyType)) : void 0;
          const isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
          const isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
          const stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
          const lateFlag = modifiersProp ? getIsLateCheckFlag(modifiersProp) : 0;
          const prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, lateFlag | 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
          prop.links.mappedType = type;
          prop.links.nameType = propNameType;
          prop.links.keyType = keyType;
          if (modifiersProp) {
            prop.links.syntheticOrigin = modifiersProp;
            prop.declarations = shouldLinkPropDeclarations ? modifiersProp.declarations : void 0;
          }
          members.set(propName, prop);
        }
      } else if (isValidIndexKeyType(propNameType) || propNameType.flags & (1 /* Any */ | 32 /* Enum */)) {
        const indexKeyType = propNameType.flags & (1 /* Any */ | 4 /* String */) ? stringType : propNameType.flags & (8 /* Number */ | 32 /* Enum */) ? numberType : propNameType;
        const propType = instantiateType(templateType, appendTypeMapping(type.mapper, typeParameter, keyType));
        const modifiersIndexInfo = getApplicableIndexInfo(modifiersType, propNameType);
        const isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && (modifiersIndexInfo == null ? void 0 : modifiersIndexInfo.isReadonly));
        const indexInfo = createIndexInfo(indexKeyType, propType, isReadonly);
        indexInfos = appendIndexInfo(
          indexInfos,
          indexInfo,
          /*union*/
          true
        );
      }
    }
  }
  function getTypeOfMappedSymbol(symbol) {
    var _a;
    if (!symbol.links.type) {
      const mappedType = symbol.links.mappedType;
      if (!pushTypeResolution(symbol, 0 /* Type */)) {
        mappedType.containsError = true;
        return errorType;
      }
      const templateType = getTemplateTypeFromMappedType(mappedType.target || mappedType);
      const mapper = appendTypeMapping(mappedType.mapper, getTypeParameterFromMappedType(mappedType), symbol.links.keyType);
      const propType = instantiateType(templateType, mapper);
      let type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(
        propType,
        /*isProperty*/
        true
      ) : symbol.links.checkFlags & 524288 /* StripOptional */ ? removeMissingOrUndefinedType(propType) : propType;
      if (!popTypeResolution()) {
        error(currentNode, Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType));
        type = errorType;
      }
      (_a = symbol.links).type ?? (_a.type = type);
    }
    return symbol.links.type;
  }
  function getTypeParameterFromMappedType(type) {
    return type.typeParameter || (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(type.declaration.typeParameter)));
  }
  function getConstraintTypeFromMappedType(type) {
    return type.constraintType || (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
  }
  function getNameTypeFromMappedType(type) {
    return type.declaration.nameType ? type.nameType || (type.nameType = instantiateType(getTypeFromTypeNode(type.declaration.nameType), type.mapper)) : void 0;
  }
  function getTemplateTypeFromMappedType(type) {
    return type.templateType || (type.templateType = type.declaration.type ? instantiateType(addOptionality(
      getTypeFromTypeNode(type.declaration.type),
      /*isProperty*/
      true,
      !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)
    ), type.mapper) : errorType);
  }
  function getConstraintDeclarationForMappedType(type) {
    return getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
  }
  function isMappedTypeWithKeyofConstraintDeclaration(type) {
    const constraintDeclaration = getConstraintDeclarationForMappedType(type);
    return constraintDeclaration.kind === 198 /* TypeOperator */ && constraintDeclaration.operator === 143 /* KeyOfKeyword */;
  }
  function getModifiersTypeFromMappedType(type) {
    if (!type.modifiersType) {
      if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
        type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
      } else {
        const declaredType = getTypeFromMappedTypeNode(type.declaration);
        const constraint = getConstraintTypeFromMappedType(declaredType);
        const extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
        type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
      }
    }
    return type.modifiersType;
  }
  function getMappedTypeModifiers(type) {
    const declaration = type.declaration;
    return (declaration.readonlyToken ? declaration.readonlyToken.kind === 41 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | (declaration.questionToken ? declaration.questionToken.kind === 41 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
  }
  function getMappedTypeOptionality(type) {
    const modifiers = getMappedTypeModifiers(type);
    return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
  }
  function getCombinedMappedTypeOptionality(type) {
    if (getObjectFlags(type) & 32 /* Mapped */) {
      return getMappedTypeOptionality(type) || getCombinedMappedTypeOptionality(getModifiersTypeFromMappedType(type));
    }
    if (type.flags & 2097152 /* Intersection */) {
      const optionality = getCombinedMappedTypeOptionality(type.types[0]);
      return every(type.types, (t, i) => i === 0 || getCombinedMappedTypeOptionality(t) === optionality) ? optionality : 0;
    }
    return 0;
  }
  function isPartialMappedType(type) {
    return !!(getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
  }
  function isGenericMappedType(type) {
    if (getObjectFlags(type) & 32 /* Mapped */) {
      const constraint = getConstraintTypeFromMappedType(type);
      if (isGenericIndexType(constraint)) {
        return true;
      }
      const nameType = getNameTypeFromMappedType(type);
      if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type), constraint)))) {
        return true;
      }
    }
    return false;
  }
  function getMappedTypeNameTypeKind(type) {
    const nameType = getNameTypeFromMappedType(type);
    if (!nameType) {
      return 0 /* None */;
    }
    return isTypeAssignableTo(nameType, getTypeParameterFromMappedType(type)) ? 1 /* Filtering */ : 2 /* Remapping */;
  }
  function resolveStructuredTypeMembers(type) {
    if (!type.members) {
      if (type.flags & 524288 /* Object */) {
        if (type.objectFlags & 4 /* Reference */) {
          resolveTypeReferenceMembers(type);
        } else if (type.objectFlags & 3 /* ClassOrInterface */) {
          resolveClassOrInterfaceMembers(type);
        } else if (type.objectFlags & 1024 /* ReverseMapped */) {
          resolveReverseMappedTypeMembers(type);
        } else if (type.objectFlags & 16 /* Anonymous */) {
          resolveAnonymousTypeMembers(type);
        } else if (type.objectFlags & 32 /* Mapped */) {
          resolveMappedTypeMembers(type);
        } else {
          Debug.fail("Unhandled object type " + Debug.formatObjectFlags(type.objectFlags));
        }
      } else if (type.flags & 1048576 /* Union */) {
        resolveUnionTypeMembers(type);
      } else if (type.flags & 2097152 /* Intersection */) {
        resolveIntersectionTypeMembers(type);
      } else {
        Debug.fail("Unhandled type " + Debug.formatTypeFlags(type.flags));
      }
    }
    return type;
  }
  function getPropertiesOfObjectType(type) {
    if (type.flags & 524288 /* Object */) {
      return resolveStructuredTypeMembers(type).properties;
    }
    return emptyArray;
  }
  function getPropertyOfObjectType(type, name) {
    if (type.flags & 524288 /* Object */) {
      const resolved = resolveStructuredTypeMembers(type);
      const symbol = resolved.members.get(name);
      if (symbol && symbolIsValue(symbol)) {
        return symbol;
      }
    }
  }
  function getPropertiesOfUnionOrIntersectionType(type) {
    if (!type.resolvedProperties) {
      const members = createSymbolTable();
      for (const current of type.types) {
        for (const prop of getPropertiesOfType(current)) {
          if (!members.has(prop.escapedName)) {
            const combinedProp = getPropertyOfUnionOrIntersectionType(
              type,
              prop.escapedName,
              /*skipObjectFunctionPropertyAugment*/
              !!(type.flags & 2097152 /* Intersection */)
            );
            if (combinedProp) {
              members.set(prop.escapedName, combinedProp);
            }
          }
        }
        if (type.flags & 1048576 /* Union */ && getIndexInfosOfType(current).length === 0) {
          break;
        }
      }
      type.resolvedProperties = getNamedMembers(members);
    }
    return type.resolvedProperties;
  }
  function getPropertiesOfType(type) {
    type = getReducedApparentType(type);
    return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type);
  }
  function forEachPropertyOfType(type, action) {
    type = getReducedApparentType(type);
    if (type.flags & 3670016 /* StructuredType */) {
      resolveStructuredTypeMembers(type).members.forEach((symbol, escapedName) => {
        if (isNamedMember(symbol, escapedName)) {
          action(symbol, escapedName);
        }
      });
    }
  }
  function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
    const list = obj.properties;
    return list.some((property) => {
      const nameType = property.name && (isJsxNamespacedName(property.name) ? getStringLiteralType(getTextOfJsxAttributeName(property.name)) : getLiteralTypeFromPropertyName(property.name));
      const name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : void 0;
      const expected = name === void 0 ? void 0 : getTypeOfPropertyOfType(contextualType, name);
      return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
    });
  }
  function getAllPossiblePropertiesOfTypes(types) {
    const unionType = getUnionType(types);
    if (!(unionType.flags & 1048576 /* Union */)) {
      return getAugmentedPropertiesOfType(unionType);
    }
    const props = createSymbolTable();
    for (const memberType of types) {
      for (const { escapedName } of getAugmentedPropertiesOfType(memberType)) {
        if (!props.has(escapedName)) {
          const prop = createUnionOrIntersectionProperty(unionType, escapedName);
          if (prop) props.set(escapedName, prop);
        }
      }
    }
    return arrayFrom(props.values());
  }
  function getConstraintOfType(type) {
    return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type);
  }
  function getConstraintOfTypeParameter(typeParameter) {
    return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : void 0;
  }
  function isConstMappedType(type, depth) {
    const typeVariable = getHomomorphicTypeVariable(type);
    return !!typeVariable && isConstTypeVariable(typeVariable, depth);
  }
  function isConstTypeVariable(type, depth = 0) {
    var _a;
    return depth < 5 && !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 4096 /* Const */)) || type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, (t) => isConstTypeVariable(t, depth)) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType, depth + 1) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type), depth + 1) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType, depth) || getObjectFlags(type) & 32 /* Mapped */ && isConstMappedType(type, depth) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t, depth)) >= 0));
  }
  function getConstraintOfIndexedAccess(type) {
    return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : void 0;
  }
  function getSimplifiedTypeOrConstraint(type) {
    const simplified = getSimplifiedType(
      type,
      /*writing*/
      false
    );
    return simplified !== type ? simplified : getConstraintOfType(type);
  }
  function getConstraintFromIndexedAccess(type) {
    if (isMappedTypeGenericIndexedAccess(type)) {
      return substituteIndexedMappedType(type.objectType, type.indexType);
    }
    const indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
    if (indexConstraint && indexConstraint !== type.indexType) {
      const indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.accessFlags);
      if (indexedAccess) {
        return indexedAccess;
      }
    }
    const objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
    if (objectConstraint && objectConstraint !== type.objectType) {
      return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType, type.accessFlags);
    }
    return void 0;
  }
  function getDefaultConstraintOfConditionalType(type) {
    if (!type.resolvedDefaultConstraint) {
      const trueConstraint = getInferredTrueTypeFromConditionalType(type);
      const falseConstraint = getFalseTypeFromConditionalType(type);
      type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
    }
    return type.resolvedDefaultConstraint;
  }
  function getConstraintOfDistributiveConditionalType(type) {
    if (type.resolvedConstraintOfDistributive !== void 0) {
      return type.resolvedConstraintOfDistributive || void 0;
    }
    if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
      const simplified = getSimplifiedType(
        type.checkType,
        /*writing*/
        false
      );
      const constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
      if (constraint && constraint !== type.checkType) {
        const instantiated = getConditionalTypeInstantiation(
          type,
          prependTypeMapping(type.root.checkType, constraint, type.mapper),
          /*forConstraint*/
          true
        );
        if (!(instantiated.flags & 131072 /* Never */)) {
          type.resolvedConstraintOfDistributive = instantiated;
          return instantiated;
        }
      }
    }
    type.resolvedConstraintOfDistributive = false;
    return void 0;
  }
  function getConstraintFromConditionalType(type) {
    return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
  }
  function getConstraintOfConditionalType(type) {
    return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : void 0;
  }
  function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
    let constraints;
    let hasDisjointDomainType = false;
    for (const t of types) {
      if (t.flags & 465829888 /* Instantiable */) {
        let constraint = getConstraintOfType(t);
        while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
          constraint = getConstraintOfType(constraint);
        }
        if (constraint) {
          constraints = append(constraints, constraint);
          if (targetIsUnion) {
            constraints = append(constraints, t);
          }
        }
      } else if (t.flags & 469892092 /* DisjointDomains */ || isEmptyAnonymousObjectType(t)) {
        hasDisjointDomainType = true;
      }
    }
    if (constraints && (targetIsUnion || hasDisjointDomainType)) {
      if (hasDisjointDomainType) {
        for (const t of types) {
          if (t.flags & 469892092 /* DisjointDomains */ || isEmptyAnonymousObjectType(t)) {
            constraints = append(constraints, t);
          }
        }
      }
      return getNormalizedType(
        getIntersectionType(constraints, 2 /* NoConstraintReduction */),
        /*writing*/
        false
      );
    }
    return void 0;
  }
  function getBaseConstraintOfType(type) {
    if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || isGenericTupleType(type)) {
      const constraint = getResolvedBaseConstraint(type);
      return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : void 0;
    }
    return type.flags & 4194304 /* Index */ ? stringNumberSymbolType : void 0;
  }
  function getBaseConstraintOrType(type) {
    return getBaseConstraintOfType(type) || type;
  }
  function hasNonCircularBaseConstraint(type) {
    return getResolvedBaseConstraint(type) !== circularConstraintType;
  }
  function getResolvedBaseConstraint(type) {
    if (type.resolvedBaseConstraint) {
      return type.resolvedBaseConstraint;
    }
    const stack = [];
    return type.resolvedBaseConstraint = getImmediateBaseConstraint(type);
    function getImmediateBaseConstraint(t) {
      if (!t.immediateBaseConstraint) {
        if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
          return circularConstraintType;
        }
        let result;
        const identity2 = getRecursionIdentity(t);
        if (stack.length < 10 || stack.length < 50 && !contains(stack, identity2)) {
          stack.push(identity2);
          result = computeBaseConstraint(getSimplifiedType(
            t,
            /*writing*/
            false
          ));
          stack.pop();
        }
        if (!popTypeResolution()) {
          if (t.flags & 262144 /* TypeParameter */) {
            const errorNode = getConstraintDeclaration(t);
            if (errorNode) {
              const diagnostic = error(errorNode, Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
              if (currentNode && !isNodeDescendantOf(errorNode, currentNode) && !isNodeDescendantOf(currentNode, errorNode)) {
                addRelatedInfo(diagnostic, createDiagnosticForNode(currentNode, Diagnostics.Circularity_originates_in_type_at_this_location));
              }
            }
          }
          result = circularConstraintType;
        }
        t.immediateBaseConstraint ?? (t.immediateBaseConstraint = result || noConstraintType);
      }
      return t.immediateBaseConstraint;
    }
    function getBaseConstraint(t) {
      const c = getImmediateBaseConstraint(t);
      return c !== noConstraintType && c !== circularConstraintType ? c : void 0;
    }
    function computeBaseConstraint(t) {
      if (t.flags & 262144 /* TypeParameter */) {
        const constraint = getConstraintFromTypeParameter(t);
        return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint);
      }
      if (t.flags & 3145728 /* UnionOrIntersection */) {
        const types = t.types;
        const baseTypes = [];
        let different = false;
        for (const type2 of types) {
          const baseType = getBaseConstraint(type2);
          if (baseType) {
            if (baseType !== type2) {
              different = true;
            }
            baseTypes.push(baseType);
          } else {
            different = true;
          }
        }
        if (!different) {
          return t;
        }
        return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : void 0;
      }
      if (t.flags & 4194304 /* Index */) {
        return stringNumberSymbolType;
      }
      if (t.flags & 134217728 /* TemplateLiteral */) {
        const types = t.types;
        const constraints = mapDefined(types, getBaseConstraint);
        return constraints.length === types.length ? getTemplateLiteralType(t.texts, constraints) : stringType;
      }
      if (t.flags & 268435456 /* StringMapping */) {
        const constraint = getBaseConstraint(t.type);
        return constraint && constraint !== t.type ? getStringMappingType(t.symbol, constraint) : stringType;
      }
      if (t.flags & 8388608 /* IndexedAccess */) {
        if (isMappedTypeGenericIndexedAccess(t)) {
          return getBaseConstraint(substituteIndexedMappedType(t.objectType, t.indexType));
        }
        const baseObjectType = getBaseConstraint(t.objectType);
        const baseIndexType = getBaseConstraint(t.indexType);
        const baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, t.accessFlags);
        return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
      }
      if (t.flags & 16777216 /* Conditional */) {
        const constraint = getConstraintFromConditionalType(t);
        return constraint && getBaseConstraint(constraint);
      }
      if (t.flags & 33554432 /* Substitution */) {
        return getBaseConstraint(getSubstitutionIntersection(t));
      }
      if (isGenericTupleType(t)) {
        const newElements = map(getElementTypes(t), (v, i) => {
          const constraint = v.flags & 262144 /* TypeParameter */ && t.target.elementFlags[i] & 8 /* Variadic */ && getBaseConstraint(v) || v;
          return constraint !== v && everyType(constraint, (c) => isArrayOrTupleType(c) && !isGenericTupleType(c)) ? constraint : v;
        });
        return createTupleType(newElements, t.target.elementFlags, t.target.readonly, t.target.labeledElementDeclarations);
      }
      return t;
    }
  }
  function getApparentTypeOfIntersectionType(type, thisArgument) {
    if (type === thisArgument) {
      return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(
        type,
        thisArgument,
        /*needApparentType*/
        true
      ));
    }
    const key = `I${getTypeId(type)},${getTypeId(thisArgument)}`;
    return getCachedType(key) ?? setCachedType(key, getTypeWithThisArgument(
      type,
      thisArgument,
      /*needApparentType*/
      true
    ));
  }
  function getResolvedTypeParameterDefault(typeParameter) {
    if (!typeParameter.default) {
      if (typeParameter.target) {
        const targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
        typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
      } else {
        typeParameter.default = resolvingDefaultType;
        const defaultDeclaration = typeParameter.symbol && forEach(typeParameter.symbol.declarations, (decl) => isTypeParameterDeclaration(decl) && decl.default);
        const defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
        if (typeParameter.default === resolvingDefaultType) {
          typeParameter.default = defaultType;
        }
      }
    } else if (typeParameter.default === resolvingDefaultType) {
      typeParameter.default = circularConstraintType;
    }
    return typeParameter.default;
  }
  function getDefaultFromTypeParameter(typeParameter) {
    const defaultType = getResolvedTypeParameterDefault(typeParameter);
    return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : void 0;
  }
  function hasNonCircularTypeParameterDefault(typeParameter) {
    return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
  }
  function hasTypeParameterDefault(typeParameter) {
    return !!(typeParameter.symbol && forEach(typeParameter.symbol.declarations, (decl) => isTypeParameterDeclaration(decl) && decl.default));
  }
  function getApparentTypeOfMappedType(type) {
    return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
  }
  function getResolvedApparentTypeOfMappedType(type) {
    const target = type.target ?? type;
    const typeVariable = getHomomorphicTypeVariable(target);
    if (typeVariable && !target.declaration.nameType) {
      const modifiersType = getModifiersTypeFromMappedType(type);
      const baseConstraint = isGenericMappedType(modifiersType) ? getApparentTypeOfMappedType(modifiersType) : getBaseConstraintOfType(modifiersType);
      if (baseConstraint && everyType(baseConstraint, (t) => isArrayOrTupleType(t) || isArrayOrTupleOrIntersection(t))) {
        return instantiateType(target, prependTypeMapping(typeVariable, baseConstraint, type.mapper));
      }
    }
    return type;
  }
  function isArrayOrTupleOrIntersection(type) {
    return !!(type.flags & 2097152 /* Intersection */) && every(type.types, isArrayOrTupleType);
  }
  function isMappedTypeGenericIndexedAccess(type) {
    let objectType;
    return !!(type.flags & 8388608 /* IndexedAccess */ && getObjectFlags(objectType = type.objectType) & 32 /* Mapped */ && !isGenericMappedType(objectType) && isGenericIndexType(type.indexType) && !(getMappedTypeModifiers(objectType) & 8 /* ExcludeOptional */) && !objectType.declaration.nameType);
  }
  function getApparentType(type) {
    const t = type.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
    const objectFlags = getObjectFlags(t);
    return objectFlags & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : objectFlags & 4 /* Reference */ && t !== type ? getTypeWithThisArgument(t, type) : t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t, type) : t.flags & 402653316 /* StringLike */ ? globalStringType : t.flags & 296 /* NumberLike */ ? globalNumberType : t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType() : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType() : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : t.flags & 4194304 /* Index */ ? stringNumberSymbolType : t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType : t;
  }
  function getReducedApparentType(type) {
    return getReducedType(getApparentType(getReducedType(type)));
  }
  function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) {
    var _a, _b, _c;
    let singleProp;
    let propSet;
    let indexTypes;
    const isUnion = containingType.flags & 1048576 /* Union */;
    let optionalFlag;
    let syntheticFlag = 4 /* SyntheticMethod */;
    let checkFlags = isUnion ? 0 : 8 /* Readonly */;
    let mergedInstantiations = false;
    for (const current of containingType.types) {
      const type = getApparentType(current);
      if (!(isErrorType(type) || type.flags & 131072 /* Never */)) {
        const prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment);
        const modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0;
        if (prop) {
          if (prop.flags & 106500 /* ClassMember */) {
            optionalFlag ?? (optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */);
            if (isUnion) {
              optionalFlag |= prop.flags & 16777216 /* Optional */;
            } else {
              optionalFlag &= prop.flags;
            }
          }
          if (!singleProp) {
            singleProp = prop;
          } else if (prop !== singleProp) {
            const isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp);
            if (isInstantiation && compareProperties(singleProp, prop, (a, b) => a === b ? -1 /* True */ : 0 /* False */) === -1 /* True */) {
              mergedInstantiations = !!singleProp.parent && !!length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent));
            } else {
              if (!propSet) {
                propSet = /* @__PURE__ */ new Map();
                propSet.set(getSymbolId(singleProp), singleProp);
              }
              const id = getSymbolId(prop);
              if (!propSet.has(id)) {
                propSet.set(id, prop);
              }
            }
          }
          if (isUnion && isReadonlySymbol(prop)) {
            checkFlags |= 8 /* Readonly */;
          } else if (!isUnion && !isReadonlySymbol(prop)) {
            checkFlags &= ~8 /* Readonly */;
          }
          checkFlags |= (!(modifiers & 6 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | (modifiers & 4 /* Protected */ ? 512 /* ContainsProtected */ : 0) | (modifiers & 2 /* Private */ ? 1024 /* ContainsPrivate */ : 0) | (modifiers & 256 /* Static */ ? 2048 /* ContainsStatic */ : 0);
          if (!isPrototypeProperty(prop)) {
            syntheticFlag = 2 /* SyntheticProperty */;
          }
        } else if (isUnion) {
          const indexInfo = !isLateBoundName(name) && getApplicableIndexInfoForName(type, name);
          if (indexInfo) {
            checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
            indexTypes = append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
          } else if (isObjectLiteralType(type) && !(getObjectFlags(type) & 2097152 /* ContainsSpread */)) {
            checkFlags |= 32 /* WritePartial */;
            indexTypes = append(indexTypes, undefinedType);
          } else {
            checkFlags |= 16 /* ReadPartial */;
          }
        }
      }
    }
    if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */) && !(propSet && getCommonDeclarationsOfSymbols(propSet.values()))) {
      return void 0;
    }
    if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
      if (mergedInstantiations) {
        const links = (_a = tryCast(singleProp, isTransientSymbol)) == null ? void 0 : _a.links;
        const clone = createSymbolWithType(singleProp, links == null ? void 0 : links.type);
        clone.parent = (_c = (_b = singleProp.valueDeclaration) == null ? void 0 : _b.symbol) == null ? void 0 : _c.parent;
        clone.links.containingType = containingType;
        clone.links.mapper = links == null ? void 0 : links.mapper;
        clone.links.writeType = getWriteTypeOfSymbol(singleProp);
        return clone;
      } else {
        return singleProp;
      }
    }
    const props = propSet ? arrayFrom(propSet.values()) : [singleProp];
    let declarations;
    let firstType;
    let nameType;
    const propTypes = [];
    let writeTypes;
    let firstValueDeclaration;
    let hasNonUniformValueDeclaration = false;
    for (const prop of props) {
      if (!firstValueDeclaration) {
        firstValueDeclaration = prop.valueDeclaration;
      } else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
        hasNonUniformValueDeclaration = true;
      }
      declarations = addRange(declarations, prop.declarations);
      const type = getTypeOfSymbol(prop);
      if (!firstType) {
        firstType = type;
        nameType = getSymbolLinks(prop).nameType;
      }
      const writeType = getWriteTypeOfSymbol(prop);
      if (writeTypes || writeType !== type) {
        writeTypes = append(!writeTypes ? propTypes.slice() : writeTypes, writeType);
      }
      if (type !== firstType) {
        checkFlags |= 64 /* HasNonUniformType */;
      }
      if (isLiteralType(type) || isPatternLiteralType(type)) {
        checkFlags |= 128 /* HasLiteralType */;
      }
      if (type.flags & 131072 /* Never */ && type !== uniqueLiteralType) {
        checkFlags |= 131072 /* HasNeverType */;
      }
      propTypes.push(type);
    }
    addRange(propTypes, indexTypes);
    const result = createSymbol(4 /* Property */ | (optionalFlag ?? 0), name, syntheticFlag | checkFlags);
    result.links.containingType = containingType;
    if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
      result.valueDeclaration = firstValueDeclaration;
      if (firstValueDeclaration.symbol.parent) {
        result.parent = firstValueDeclaration.symbol.parent;
      }
    }
    result.declarations = declarations;
    result.links.nameType = nameType;
    if (propTypes.length > 2) {
      result.links.checkFlags |= 65536 /* DeferredType */;
      result.links.deferralParent = containingType;
      result.links.deferralConstituents = propTypes;
      result.links.deferralWriteConstituents = writeTypes;
    } else {
      result.links.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
      if (writeTypes) {
        result.links.writeType = isUnion ? getUnionType(writeTypes) : getIntersectionType(writeTypes);
      }
    }
    return result;
  }
  function getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment) {
    var _a, _b, _c;
    let property = skipObjectFunctionPropertyAugment ? (_a = type.propertyCacheWithoutObjectFunctionPropertyAugment) == null ? void 0 : _a.get(name) : (_b = type.propertyCache) == null ? void 0 : _b.get(name);
    if (!property) {
      property = createUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
      if (property) {
        const properties = skipObjectFunctionPropertyAugment ? type.propertyCacheWithoutObjectFunctionPropertyAugment || (type.propertyCacheWithoutObjectFunctionPropertyAugment = createSymbolTable()) : type.propertyCache || (type.propertyCache = createSymbolTable());
        properties.set(name, property);
        if (skipObjectFunctionPropertyAugment && !(getCheckFlags(property) & 48 /* Partial */) && !((_c = type.propertyCache) == null ? void 0 : _c.get(name))) {
          const properties2 = type.propertyCache || (type.propertyCache = createSymbolTable());
          properties2.set(name, property);
        }
      }
    }
    return property;
  }
  function getCommonDeclarationsOfSymbols(symbols) {
    let commonDeclarations;
    for (const symbol of symbols) {
      if (!symbol.declarations) {
        return void 0;
      }
      if (!commonDeclarations) {
        commonDeclarations = new Set(symbol.declarations);
        continue;
      }
      commonDeclarations.forEach((declaration) => {
        if (!contains(symbol.declarations, declaration)) {
          commonDeclarations.delete(declaration);
        }
      });
      if (commonDeclarations.size === 0) {
        return void 0;
      }
    }
    return commonDeclarations;
  }
  function getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment) {
    const property = getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
    return property && !(getCheckFlags(property) & 16 /* ReadPartial */) ? property : void 0;
  }
  function getReducedType(type) {
    if (type.flags & 1048576 /* Union */ && type.objectFlags & 16777216 /* ContainsIntersections */) {
      return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
    } else if (type.flags & 2097152 /* Intersection */) {
      if (!(type.objectFlags & 16777216 /* IsNeverIntersectionComputed */)) {
        type.objectFlags |= 16777216 /* IsNeverIntersectionComputed */ | (some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 33554432 /* IsNeverIntersection */ : 0);
      }
      return type.objectFlags & 33554432 /* IsNeverIntersection */ ? neverType : type;
    }
    return type;
  }
  function getReducedUnionType(unionType) {
    const reducedTypes = sameMap(unionType.types, getReducedType);
    if (reducedTypes === unionType.types) {
      return unionType;
    }
    const reduced = getUnionType(reducedTypes);
    if (reduced.flags & 1048576 /* Union */) {
      reduced.resolvedReducedType = reduced;
    }
    return reduced;
  }
  function isNeverReducedProperty(prop) {
    return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
  }
  function isDiscriminantWithNeverType(prop) {
    return !(prop.flags & 16777216 /* Optional */) && (getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
  }
  function isConflictingPrivateProperty(prop) {
    return !prop.valueDeclaration && !!(getCheckFlags(prop) & 1024 /* ContainsPrivate */);
  }
  function isGenericReducibleType(type) {
    return !!(type.flags & 1048576 /* Union */ && type.objectFlags & 16777216 /* ContainsIntersections */ && some(type.types, isGenericReducibleType) || type.flags & 2097152 /* Intersection */ && isReducibleIntersection(type));
  }
  function isReducibleIntersection(type) {
    const uniqueFilled = type.uniqueLiteralFilledInstantiation || (type.uniqueLiteralFilledInstantiation = instantiateType(type, uniqueLiteralMapper));
    return getReducedType(uniqueFilled) !== uniqueFilled;
  }
  function elaborateNeverIntersection(errorInfo, type) {
    if (type.flags & 2097152 /* Intersection */ && getObjectFlags(type) & 33554432 /* IsNeverIntersection */) {
      const neverProp = find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
      if (neverProp) {
        return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(
          type,
          /*enclosingDeclaration*/
          void 0,
          536870912 /* NoTypeReduction */
        ), symbolToString(neverProp));
      }
      const privateProp = find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
      if (privateProp) {
        return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(
          type,
          /*enclosingDeclaration*/
          void 0,
          536870912 /* NoTypeReduction */
        ), symbolToString(privateProp));
      }
    }
    return errorInfo;
  }
  function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment, includeTypeOnlyMembers) {
    var _a, _b;
    type = getReducedApparentType(type);
    if (type.flags & 524288 /* Object */) {
      const resolved = resolveStructuredTypeMembers(type);
      const symbol = resolved.members.get(name);
      if (symbol && !includeTypeOnlyMembers && ((_a = type.symbol) == null ? void 0 : _a.flags) & 512 /* ValueModule */ && ((_b = getSymbolLinks(type.symbol).typeOnlyExportStarMap) == null ? void 0 : _b.has(name))) {
        return void 0;
      }
      if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) {
        return symbol;
      }
      if (skipObjectFunctionPropertyAugment) return void 0;
      const functionType = resolved === anyFunctionType ? globalFunctionType : resolved.callSignatures.length ? globalCallableFunctionType : resolved.constructSignatures.length ? globalNewableFunctionType : void 0;
      if (functionType) {
        const symbol2 = getPropertyOfObjectType(functionType, name);
        if (symbol2) {
          return symbol2;
        }
      }
      return getPropertyOfObjectType(globalObjectType, name);
    }
    if (type.flags & 2097152 /* Intersection */) {
      const prop = getPropertyOfUnionOrIntersectionType(
        type,
        name,
        /*skipObjectFunctionPropertyAugment*/
        true
      );
      if (prop) {
        return prop;
      }
      if (!skipObjectFunctionPropertyAugment) {
        return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment);
      }
      return void 0;
    }
    if (type.flags & 1048576 /* Union */) {
      return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment);
    }
    return void 0;
  }
  function getSignaturesOfStructuredType(type, kind) {
    if (type.flags & 3670016 /* StructuredType */) {
      const resolved = resolveStructuredTypeMembers(type);
      return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
    }
    return emptyArray;
  }
  function getSignaturesOfType(type, kind) {
    const result = getSignaturesOfStructuredType(getReducedApparentType(type), kind);
    if (kind === 0 /* Call */ && !length(result) && type.flags & 1048576 /* Union */) {
      if (type.arrayFallbackSignatures) {
        return type.arrayFallbackSignatures;
      }
      let memberName;
      if (everyType(type, (t) => {
        var _a;
        return !!((_a = t.symbol) == null ? void 0 : _a.parent) && isArrayOrTupleSymbol(t.symbol.parent) && (!memberName ? (memberName = t.symbol.escapedName, true) : memberName === t.symbol.escapedName);
      })) {
        const arrayArg = mapType(type, (t) => getMappedType((isReadonlyArraySymbol(t.symbol.parent) ? globalReadonlyArrayType : globalArrayType).typeParameters[0], t.mapper));
        const arrayType = createArrayType(arrayArg, someType(type, (t) => isReadonlyArraySymbol(t.symbol.parent)));
        return type.arrayFallbackSignatures = getSignaturesOfType(getTypeOfPropertyOfType(arrayType, memberName), kind);
      }
      type.arrayFallbackSignatures = result;
    }
    return result;
  }
  function isArrayOrTupleSymbol(symbol) {
    if (!symbol || !globalArrayType.symbol || !globalReadonlyArrayType.symbol) {
      return false;
    }
    return !!getSymbolIfSameReference(symbol, globalArrayType.symbol) || !!getSymbolIfSameReference(symbol, globalReadonlyArrayType.symbol);
  }
  function isReadonlyArraySymbol(symbol) {
    if (!symbol || !globalReadonlyArrayType.symbol) {
      return false;
    }
    return !!getSymbolIfSameReference(symbol, globalReadonlyArrayType.symbol);
  }
  function findIndexInfo(indexInfos, keyType) {
    return find(indexInfos, (info) => info.keyType === keyType);
  }
  function findApplicableIndexInfo(indexInfos, keyType) {
    let stringIndexInfo;
    let applicableInfo;
    let applicableInfos;
    for (const info of indexInfos) {
      if (info.keyType === stringType) {
        stringIndexInfo = info;
      } else if (isApplicableIndexType(keyType, info.keyType)) {
        if (!applicableInfo) {
          applicableInfo = info;
        } else {
          (applicableInfos || (applicableInfos = [applicableInfo])).push(info);
        }
      }
    }
    return applicableInfos ? createIndexInfo(unknownType, getIntersectionType(map(applicableInfos, (info) => info.type)), reduceLeft(
      applicableInfos,
      (isReadonly, info) => isReadonly && info.isReadonly,
      /*initial*/
      true
    )) : applicableInfo ? applicableInfo : stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo : void 0;
  }
  function isApplicableIndexType(source, target) {
    return isTypeAssignableTo(source, target) || target === stringType && isTypeAssignableTo(source, numberType) || target === numberType && (source === numericStringType || !!(source.flags & 128 /* StringLiteral */) && isNumericLiteralName(source.value));
  }
  function getIndexInfosOfStructuredType(type) {
    if (type.flags & 3670016 /* StructuredType */) {
      const resolved = resolveStructuredTypeMembers(type);
      return resolved.indexInfos;
    }
    return emptyArray;
  }
  function getIndexInfosOfType(type) {
    return getIndexInfosOfStructuredType(getReducedApparentType(type));
  }
  function getIndexInfoOfType(type, keyType) {
    return findIndexInfo(getIndexInfosOfType(type), keyType);
  }
  function getIndexTypeOfType(type, keyType) {
    var _a;
    return (_a = getIndexInfoOfType(type, keyType)) == null ? void 0 : _a.type;
  }
  function getApplicableIndexInfos(type, keyType) {
    return getIndexInfosOfType(type).filter((info) => isApplicableIndexType(keyType, info.keyType));
  }
  function getApplicableIndexInfo(type, keyType) {
    return findApplicableIndexInfo(getIndexInfosOfType(type), keyType);
  }
  function getApplicableIndexInfoForName(type, name) {
    return getApplicableIndexInfo(type, isLateBoundName(name) ? esSymbolType : getStringLiteralType(unescapeLeadingUnderscores(name)));
  }
  function getTypeParametersFromDeclaration(declaration) {
    var _a;
    let result;
    for (const node of getEffectiveTypeParameterDeclarations(declaration)) {
      result = appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
    }
    return (result == null ? void 0 : result.length) ? result : isFunctionDeclaration(declaration) ? (_a = getSignatureOfTypeTag(declaration)) == null ? void 0 : _a.typeParameters : void 0;
  }
  function symbolsToArray(symbols) {
    const result = [];
    symbols.forEach((symbol, id) => {
      if (!isReservedMemberName(id)) {
        result.push(symbol);
      }
    });
    return result;
  }
  function tryFindAmbientModule(moduleName, withAugmentations) {
    if (isExternalModuleNameRelative(moduleName)) {
      return void 0;
    }
    const symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
    return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
  }
  function hasEffectiveQuestionToken(node) {
    return hasQuestionToken(node) || isOptionalJSDocPropertyLikeTag(node) || isParameter(node) && isJSDocOptionalParameter(node);
  }
  function isOptionalParameter(node) {
    if (hasEffectiveQuestionToken(node)) {
      return true;
    }
    if (!isParameter(node)) {
      return false;
    }
    if (node.initializer) {
      const signature = getSignatureFromDeclaration(node.parent);
      const parameterIndex = node.parent.parameters.indexOf(node);
      Debug.assert(parameterIndex >= 0);
      return parameterIndex >= getMinArgumentCount(signature, 1 /* StrongArityForUntypedJS */ | 2 /* VoidIsNonOptional */);
    }
    const iife = getImmediatelyInvokedFunctionExpression(node.parent);
    if (iife) {
      return !node.type && !node.dotDotDotToken && node.parent.parameters.indexOf(node) >= getEffectiveCallArguments(iife).length;
    }
    return false;
  }
  function isOptionalPropertyDeclaration(node) {
    return isPropertyDeclaration(node) && !hasAccessorModifier(node) && node.questionToken;
  }
  function createTypePredicate(kind, parameterName, parameterIndex, type) {
    return { kind, parameterName, parameterIndex, type };
  }
  function getMinTypeArgumentCount(typeParameters) {
    let minTypeArgumentCount = 0;
    if (typeParameters) {
      for (let i = 0; i < typeParameters.length; i++) {
        if (!hasTypeParameterDefault(typeParameters[i])) {
          minTypeArgumentCount = i + 1;
        }
      }
    }
    return minTypeArgumentCount;
  }
  function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
    const numTypeParameters = length(typeParameters);
    if (!numTypeParameters) {
      return [];
    }
    const numTypeArguments = length(typeArguments);
    if (isJavaScriptImplicitAny || numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters) {
      const result = typeArguments ? typeArguments.slice() : [];
      for (let i = numTypeArguments; i < numTypeParameters; i++) {
        result[i] = errorType;
      }
      const baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
      for (let i = numTypeArguments; i < numTypeParameters; i++) {
        let defaultType = getDefaultFromTypeParameter(typeParameters[i]);
        if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
          defaultType = anyType;
        }
        result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
      }
      result.length = typeParameters.length;
      return result;
    }
    return typeArguments && typeArguments.slice();
  }
  function getSignatureFromDeclaration(declaration) {
    const links = getNodeLinks(declaration);
    if (!links.resolvedSignature) {
      const parameters = [];
      let flags = 0 /* None */;
      let minArgumentCount = 0;
      let thisParameter;
      let thisTag = isInJSFile(declaration) ? getJSDocThisTag(declaration) : void 0;
      let hasThisParameter = false;
      const iife = getImmediatelyInvokedFunctionExpression(declaration);
      const isJSConstructSignature = isJSDocConstructSignature(declaration);
      const isUntypedSignatureInJSFile = !iife && isInJSFile(declaration) && isValueSignatureDeclaration(declaration) && !hasJSDocParameterTags(declaration) && !getJSDocType(declaration);
      if (isUntypedSignatureInJSFile) {
        flags |= 32 /* IsUntypedSignatureInJSFile */;
      }
      for (let i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
        const param = declaration.parameters[i];
        if (isInJSFile(param) && isJSDocThisTag(param)) {
          thisTag = param;
          continue;
        }
        let paramSymbol = param.symbol;
        const type = isJSDocParameterTag(param) ? param.typeExpression && param.typeExpression.type : param.type;
        if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !isBindingPattern(param.name)) {
          const resolvedSymbol = resolveName(
            param,
            paramSymbol.escapedName,
            111551 /* Value */,
            /*nameNotFoundMessage*/
            void 0,
            /*isUse*/
            false
          );
          paramSymbol = resolvedSymbol;
        }
        if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
          hasThisParameter = true;
          thisParameter = param.symbol;
        } else {
          parameters.push(paramSymbol);
        }
        if (type && type.kind === 201 /* LiteralType */) {
          flags |= 2 /* HasLiteralTypes */;
        }
        const isOptionalParameter2 = hasEffectiveQuestionToken(param) || isParameter(param) && param.initializer || isRestParameter(param) || iife && parameters.length > iife.arguments.length && !type;
        if (!isOptionalParameter2) {
          minArgumentCount = parameters.length;
        }
      }
      if ((declaration.kind === 177 /* GetAccessor */ || declaration.kind === 178 /* SetAccessor */) && hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) {
        const otherKind = declaration.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */;
        const other = getDeclarationOfKind(getSymbolOfDeclaration(declaration), otherKind);
        if (other) {
          thisParameter = getAnnotatedAccessorThisParameter(other);
        }
      }
      if (thisTag && thisTag.typeExpression) {
        thisParameter = createSymbolWithType(createSymbol(1 /* FunctionScopedVariable */, "this" /* This */), getTypeFromTypeNode(thisTag.typeExpression));
      }
      const hostDeclaration = isJSDocSignature(declaration) ? getEffectiveJSDocHost(declaration) : declaration;
      const classType = hostDeclaration && isConstructorDeclaration(hostDeclaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(hostDeclaration.parent.symbol)) : void 0;
      const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
      if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
        flags |= 1 /* HasRestParameter */;
      }
      if (isConstructorTypeNode(declaration) && hasSyntacticModifier(declaration, 64 /* Abstract */) || isConstructorDeclaration(declaration) && hasSyntacticModifier(declaration.parent, 64 /* Abstract */)) {
        flags |= 4 /* Abstract */;
      }
      links.resolvedSignature = createSignature(
        declaration,
        typeParameters,
        thisParameter,
        parameters,
        /*resolvedReturnType*/
        void 0,
        /*resolvedTypePredicate*/
        void 0,
        minArgumentCount,
        flags
      );
    }
    return links.resolvedSignature;
  }
  function maybeAddJsSyntheticRestParameter(declaration, parameters) {
    if (isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
      return false;
    }
    const lastParam = lastOrUndefined(declaration.parameters);
    const lastParamTags = lastParam ? getJSDocParameterTags(lastParam) : getJSDocTags(declaration).filter(isJSDocParameterTag);
    const lastParamVariadicType = firstDefined(lastParamTags, (p) => p.typeExpression && isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : void 0);
    const syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
    if (lastParamVariadicType) {
      syntheticArgsSymbol.links.type = createArrayType(getTypeFromTypeNode(lastParamVariadicType.type));
    } else {
      syntheticArgsSymbol.links.checkFlags |= 65536 /* DeferredType */;
      syntheticArgsSymbol.links.deferralParent = neverType;
      syntheticArgsSymbol.links.deferralConstituents = [anyArrayType];
      syntheticArgsSymbol.links.deferralWriteConstituents = [anyArrayType];
    }
    if (lastParamVariadicType) {
      parameters.pop();
    }
    parameters.push(syntheticArgsSymbol);
    return true;
  }
  function getSignatureOfTypeTag(node) {
    if (!(isInJSFile(node) && isFunctionLikeDeclaration(node))) return void 0;
    const typeTag = getJSDocTypeTag(node);
    return (typeTag == null ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
  }
  function getParameterTypeOfTypeTag(func, parameter) {
    const signature = getSignatureOfTypeTag(func);
    if (!signature) return void 0;
    const pos = func.parameters.indexOf(parameter);
    return parameter.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos);
  }
  function getReturnTypeOfTypeTag(node) {
    const signature = getSignatureOfTypeTag(node);
    return signature && getReturnTypeOfSignature(signature);
  }
  function containsArgumentsReference(declaration) {
    const links = getNodeLinks(declaration);
    if (links.containsArgumentsReference === void 0) {
      if (links.flags & 512 /* CaptureArguments */) {
        links.containsArgumentsReference = true;
      } else {
        links.containsArgumentsReference = traverse(declaration.body);
      }
    }
    return links.containsArgumentsReference;
    function traverse(node) {
      if (!node) return false;
      switch (node.kind) {
        case 80 /* Identifier */:
          return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol;
        case 172 /* PropertyDeclaration */:
        case 174 /* MethodDeclaration */:
        case 177 /* GetAccessor */:
        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) {
            error(typeNode, Diagnostics.Return_type_annotation_circularly_references_itself);
          } else if (noImplicitAny) {
            const declaration = signature.declaration;
            const name = getNameOfDeclaration(declaration);
            if (name) {
              error(name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(name));
            } else {
              error(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions);
            }
          }
        }
        type = anyType;
      }
      signature.resolvedReturnType ?? (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, getEffectiveTypeArguments(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));
        error(
          type.node || currentNode,
          type.target.symbol ? Diagnostics.Type_arguments_for_0_circularly_reference_themselves : Diagnostics.Tuple_type_arguments_circularly_reference_themselves,
          type.target.symbol && symbolToString(type.target.symbol)
        );
      }
    }
    return type.resolvedTypeArguments;
  }
  function getTypeReferenceArity(type) {
    return length(type.target.typeParameters);
  }
  function getTypeFromClassOrInterfaceReference(node, symbol) {
    const type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
    const typeParameters = type.localTypeParameters;
    if (typeParameters) {
      const numTypeArguments = length(node.typeArguments);
      const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
      const isJs = isInJSFile(node);
      const isJsImplicitAny = !noImplicitAny && isJs;
      if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
        const missingAugmentsTag = isJs && isExpressionWithTypeArguments(node) && !isJSDocAugmentsTag(node.parent);
        const 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 */
        );
        error(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) {
        error(
          node,
          minTypeArgumentCount === typeParameters.length ? Diagnostics.Generic_type_0_requires_1_type_argument_s : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments,
          symbolToString(symbol),
          minTypeArgumentCount,
          typeParameters.length
        );
        return errorType;
      }
      const aliasSymbol = getAliasSymbolForTypeNode(node);
      let newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : void 0;
      let aliasTypeArguments;
      if (newAliasSymbol) {
        aliasTypeArguments = getTypeArgumentsForAliasSymbol(newAliasSymbol);
      } else if (isTypeReferenceType(node)) {
        const aliasSymbol2 = resolveTypeReferenceName(
          node,
          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 parent = node.parent;
      if (parent.kind === 169 /* Parameter */) {
        covariant = !covariant;
      }
      if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 194 /* ConditionalType */ && node === parent.trueType) {
        const constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
        if (constraint) {
          constraints = append(constraints, constraint);
        }
      } else if (type.flags & 262144 /* TypeParameter */ && parent.kind === 200 /* MappedType */ && !parent.nameType && node === parent.type) {
        const mappedType = getTypeFromTypeNode(parent);
        if (getTypeParameterFromMappedType(mappedType) === getActualTypeVariable(type)) {
          const typeParameter = getHomomorphicTypeVariable(mappedType);
          if (typeParameter) {
            const constraint = getConstraintOfTypeParameter(typeParameter);
            if (constraint && everyType(constraint, isArrayOrTupleType)) {
              constraints = append(constraints, getUnionType([numberType, numericStringType]));
            }
          }
        }
      }
      node = parent;
    }
    return constraints ? getSubstitutionType(type, getIntersectionType(constraints)) : type;
  }
  function isJSDocTypeReference(node) {
    return !!(node.flags & 16777216 /* JSDoc */) && (node.kind === 183 /* TypeReference */ || node.kind === 205 /* ImportType */);
  }
  function checkNoTypeArguments(node, symbol) {
    if (node.typeArguments) {
      error(node, Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? declarationNameToString(node.typeName) : anon);
      return false;
    }
    return true;
  }
  function getIntendedTypeFromJSDocTypeReference(node) {
    if (isIdentifier(node.typeName)) {
      const typeArgs = node.typeArguments;
      switch (node.typeName.escapedText) {
        case "String":
          checkNoTypeArguments(node);
          return stringType;
        case "Number":
          checkNoTypeArguments(node);
          return numberType;
        case "Boolean":
          checkNoTypeArguments(node);
          return booleanType;
        case "Void":
          checkNoTypeArguments(node);
          return voidType;
        case "Undefined":
          checkNoTypeArguments(node);
          return undefinedType;
        case "Null":
          checkNoTypeArguments(node);
          return nullType;
        case "Function":
        case "function":
          checkNoTypeArguments(node);
          return globalFunctionType;
        case "array":
          return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : void 0;
        case "promise":
          return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : void 0;
        case "Object":
          if (typeArgs && typeArgs.length === 2) {
            if (isJSDocIndexSignature(node)) {
              const indexed = getTypeFromTypeNode(typeArgs[0]);
              const target = getTypeFromTypeNode(typeArgs[1]);
              const indexInfo = indexed === stringType || indexed === numberType ? [createIndexInfo(
                indexed,
                target,
                /*isReadonly*/
                false
              )] : emptyArray;
              return createAnonymousType(
                /*symbol*/
                void 0,
                emptySymbols,
                emptyArray,
                emptyArray,
                indexInfo
              );
            }
            return anyType;
          }
          checkNoTypeArguments(node);
          return !noImplicitAny ? anyType : void 0;
      }
    }
  }
  function getTypeFromJSDocNullableTypeNode(node) {
    const type = getTypeFromTypeNode(node.type);
    return strictNullChecks ? getNullableType(type, 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 */)) {
      error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbolName(symbol));
      return arity ? emptyGenericType : emptyObjectType;
    }
    if (length(type.typeParameters) !== arity) {
      error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity);
      return arity ? emptyGenericType : emptyObjectType;
    }
    return type;
  }
  function getGlobalValueSymbol(name, 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);
        error(decl, Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity);
        return void 0;
      }
    }
    return symbol;
  }
  function getGlobalSymbol(name, meaning, diagnostic) {
    return resolveName(
      /*location*/
      void 0,
      name,
      meaning,
      diagnostic,
      /*isUse*/
      false,
      /*excludeGlobals*/
      false
    );
  }
  function getGlobalType(name, arity, 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 parent = node.parent;
    switch (parent.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(parent);
      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) {
            error(
              currentNode,
              isPartOfTypeNode(currentNode) ? Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent : Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent
            );
            return errorType;
          }
          forEach(elements, (t, n) => {
            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) });
                error(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 });
      error(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
      return false;
    }
    return true;
  }
  function getCrossProductIntersections(types, flags) {
    const count = getCrossProductUnionSize(types);
    const intersections = [];
    for (let i = 0; i < count; i++) {
      const constituents = types.slice();
      let n = i;
      for (let j = types.length - 1; j >= 0; j--) {
        if (types[j].flags & 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 parent = findAncestor(node.parent, (n) => !isAccessExpression(n)) || node.parent;
      if (isCallLikeExpression(parent)) {
        return isCallOrNewExpression(parent) && isIdentifier(node) && hasMatchingArgument(parent, node);
      }
      return every(symbol.declarations, (d) => !isFunctionLike(d) || isDeprecatedDeclaration(d));
    }
    return true;
  }
  function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, accessNode, accessFlags) {
    const accessExpression = accessNode && accessNode.kind === 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))) {
            error(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) {
              error(indexNode, Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value);
              return undefinedType;
            }
            error(indexNode, Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), unescapeLeadingUnderscores(propName));
          } else {
            error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType));
          }
        }
        if (index >= 0) {
          errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType));
          return getTupleElementTypeOutOfStartCount(objectType, index, accessFlags & 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 */) {
              error(accessExpression, Diagnostics.Type_0_is_generic_and_can_only_be_indexed_for_reading, typeToString(originalObjectType));
            } else {
              error(accessExpression, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
            }
          }
          return void 0;
        }
        if (accessNode && indexInfo.keyType === stringType && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
          const indexNode = getIndexNodeForAccessExpression(accessNode);
          error(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 (isObjectLiteralType(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 */) {
          error(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);
            error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "[" + getTextOfNode(accessExpression.argumentExpression) + "]");
          } else if (getIndexTypeOfType(objectType, numberType)) {
            error(accessExpression.argumentExpression, Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
          } else {
            let suggestion;
            if (propName !== void 0 && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
              if (suggestion !== void 0) {
                error(accessExpression.argumentExpression, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
              }
            } else {
              const suggestion2 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
              if (suggestion2 !== void 0) {
                error(accessExpression, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1, typeToString(objectType), suggestion2);
              } else {
                let errorInfo;
                if (indexType.flags & 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 */ && isObjectLiteralType(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 */)) {
        error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
      } else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
        error(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);
        error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeString);
      }
    }
    if (isTypeAny(indexType)) {
      return indexType;
    }
    return void 0;
    function errorIfWritingToReadonlyIndex(indexInfo) {
      if (indexInfo && indexInfo.isReadonly && accessExpression && (isAssignmentTarget(accessExpression) || isDeleteTarget(accessExpression))) {
        error(accessExpression, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
      }
    }
  }
  function getIndexNodeForAccessExpression(accessNode) {
    return accessNode.kind === 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) {
        error(currentNode, Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
        return errorType;
      }
      const checkType = instantiateType(getActualTypeVariable(root.checkType), mapper);
      const extendsType = instantiateType(root.extendsType, mapper);
      if (checkType === errorType || extendsType === errorType) {
        return errorType;
      }
      if (checkType === wildcardType || extendsType === wildcardType) {
        return wildcardType;
      }
      const checkTypeNode = skipTypeParentheses(root.node.checkType);
      const extendsTypeNode = skipTypeParentheses(root.node.extendsType);
      const checkTuples = isSimpleTupleType(checkTypeNode) && isSimpleTupleType(extendsTypeNode) && length(checkTypeNode.elements) === length(extendsTypeNode.elements);
      const checkTypeDeferred = isDeferredType(checkType, checkTuples);
      let combinedMapper;
      if (root.inferTypeParameters) {
        const context = createInferenceContext(
          root.inferTypeParameters,
          /*signature*/
          void 0,
          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)) {
        error(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 : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning);
          const next = symbolFromModule ?? symbolFromVariable;
          if (!next) {
            error(current, Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), declarationNameToString(current));
            return links.resolvedType = errorType;
          }
          getNodeLinks(current).resolvedSymbol = next;
          getNodeLinks(current.parent).resolvedSymbol = next;
          currentNamespace = next;
        }
        links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
      } else {
        if (moduleSymbol.flags & targetMeaning) {
          links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
        } else {
          const errorMessage = targetMeaning === 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;
          error(node, errorMessage, node.argument.literal.text);
          links.resolvedSymbol = unknownSymbol;
          links.resolvedType = errorType;
        }
      }
    }
    return links.resolvedType;
  }
  function resolveImportSymbolType(node, links, symbol, meaning) {
    const resolvedSymbol = resolveSymbol(symbol);
    links.resolvedSymbol = resolvedSymbol;
    if (meaning === 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 parent = container && container.parent;
    if (parent && (isClassLike(parent) || parent.kind === 264 /* InterfaceDeclaration */)) {
      if (!isStatic(container) && (!isConstructorDeclaration(container) || isNodeDescendantOf(node, container.body))) {
        return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(parent)).thisType;
      }
    }
    if (parent && isObjectLiteralExpression(parent) && isBinaryExpression(parent.parent) && getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
      return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.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;
    }
    error(node, Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
    return errorType;
  }
  function getTypeFromThisTypeNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      links.resolvedType = getThisType(node);
    }
    return links.resolvedType;
  }
  function getTypeFromRestTypeNode(node) {
    return getTypeFromTypeNode(getArrayElementTypeNode(node.type) || node.type);
  }
  function getArrayElementTypeNode(node) {
    switch (node.kind) {
      case 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 });
      error(currentNode, Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
      return errorType;
    }
    totalInstantiationCount++;
    instantiationCount++;
    instantiationDepth++;
    const result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments);
    instantiationDepth--;
    return result;
  }
  function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) {
    const flags = type.flags;
    if (flags & 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 = error(
            containingElement.openingElement.tagName,
            Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided,
            childrenPropName,
            typeToString(childrenTargetType)
          );
          if (errorOutputContainer && errorOutputContainer.skipLogging) {
            (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(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 = error(
            containingElement.openingElement.tagName,
            Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided,
            childrenPropName,
            typeToString(childrenTargetType)
          );
          if (errorOutputContainer && errorOutputContainer.skipLogging) {
            (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(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 = error(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 */) && (isObjectLiteralType(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 && isObjectLiteralType(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) && !isObjectLiteralType(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 (isObjectLiteralType(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 = compareProperties(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.le