egment >= 0; segment--) {
      const newSegment = mod10 << 16 | segments[segment];
      const segmentValue = newSegment / 10 | 0;
      segments[segment] = segmentValue;
      mod10 = newSegment - segmentValue * 10;
      if (segmentValue && !segmentsRemaining) {
        firstNonzeroSegment = segment;
        segmentsRemaining = true;
      }
    }
    base10Value = mod10 + base10Value;
  }
  return base10Value;
}
function pseudoBigIntToString({ negative, base10Value }) {
  return (negative && base10Value !== "0" ? "-" : "") + base10Value;
}
function parseValidBigInt(text) {
  const negative = text.startsWith("-");
  const base10Value = parsePseudoBigInt(`${negative ? text.slice(1) : text}n`);
  return { negative, base10Value };
}
function isValidBigIntString(s, roundTripOnly) {
  if (s === "") return false;
  const scanner = createScanner(
    99 /* ESNext */,
    /*skipTrivia*/
    false
  );
  let success = true;
  scanner.setOnError(() => success = false);
  scanner.setText(s + "n");
  let result = scanner.scan();
  const negative = result === 41 /* MinusToken */;
  if (negative) {
    result = scanner.scan();
  }
  const flags = scanner.getTokenFlags();
  return success && result === 10 /* BigIntLiteral */ && scanner.getTokenEnd() === s.length + 1 && !(flags & 512 /* ContainsSeparator */) && (!roundTripOnly || s === pseudoBigIntToString({ negative, base10Value: parsePseudoBigInt(scanner.getTokenValue()) }));
}
function isValidTypeOnlyAliasUseSite(useSite) {
  return !!(useSite.flags & 33554432 /* Ambient */) || isPartOfTypeQuery(useSite) || isIdentifierInNonEmittingHeritageClause(useSite) || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite) || !(isExpressionNode(useSite) || isShorthandPropertyNameUseSite(useSite));
}
function isShorthandPropertyNameUseSite(useSite) {
  return isIdentifier(useSite) && isShorthandPropertyAssignment(useSite.parent) && useSite.parent.name === useSite;
}
function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
  while (node.kind === 80 /* Identifier */ || node.kind === 211 /* PropertyAccessExpression */) {
    node = node.parent;
  }
  if (node.kind !== 167 /* ComputedPropertyName */) {
    return false;
  }
  if (hasSyntacticModifier(node.parent, 64 /* Abstract */)) {
    return true;
  }
  const containerKind = node.parent.parent.kind;
  return containerKind === 264 /* InterfaceDeclaration */ || containerKind === 187 /* TypeLiteral */;
}
function isIdentifierInNonEmittingHeritageClause(node) {
  if (node.kind !== 80 /* Identifier */) return false;
  const heritageClause = findAncestor(node.parent, (parent) => {
    switch (parent.kind) {
      case 298 /* HeritageClause */:
        return true;
      case 211 /* PropertyAccessExpression */:
      case 233 /* ExpressionWithTypeArguments */:
        return false;
      default:
        return "quit";
    }
  });
  return (heritageClause == null ? void 0 : heritageClause.token) === 119 /* ImplementsKeyword */ || (heritageClause == null ? void 0 : heritageClause.parent.kind) === 264 /* InterfaceDeclaration */;
}
function isIdentifierTypeReference(node) {
  return isTypeReferenceNode(node) && isIdentifier(node.typeName);
}
function arrayIsHomogeneous(array, comparer = equateValues) {
  if (array.length < 2) return true;
  const first2 = array[0];
  for (let i = 1, length2 = array.length; i < length2; i++) {
    const target = array[i];
    if (!comparer(first2, target)) return false;
  }
  return true;
}
function setTextRangePos(range, pos) {
  range.pos = pos;
  return range;
}
function setTextRangeEnd(range, end) {
  range.end = end;
  return range;
}
function setTextRangePosEnd(range, pos, end) {
  return setTextRangeEnd(setTextRangePos(range, pos), end);
}
function setTextRangePosWidth(range, pos, width) {
  return setTextRangePosEnd(range, pos, pos + width);
}
function setNodeFlags(node, newFlags) {
  if (node) {
    node.flags = newFlags;
  }
  return node;
}
function setParent(child, parent) {
  if (child && parent) {
    child.parent = parent;
  }
  return child;
}
function setParentRecursive(rootNode, incremental) {
  if (!rootNode) return rootNode;
  forEachChildRecursively(rootNode, isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild);
  return rootNode;
  function bindParentToChildIgnoringJSDoc(child, parent) {
    if (incremental && child.parent === parent) {
      return "skip";
    }
    setParent(child, parent);
  }
  function bindJSDoc(child) {
    if (hasJSDocNodes(child)) {
      for (const doc of child.jsDoc) {
        bindParentToChildIgnoringJSDoc(doc, child);
        forEachChildRecursively(doc, bindParentToChildIgnoringJSDoc);
      }
    }
  }
  function bindParentToChild(child, parent) {
    return bindParentToChildIgnoringJSDoc(child, parent) || bindJSDoc(child);
  }
}
function isPackedElement(node) {
  return !isOmittedExpression(node);
}
function isPackedArrayLiteral(node) {
  return isArrayLiteralExpression(node) && every(node.elements, isPackedElement);
}
function expressionResultIsUnused(node) {
  Debug.assertIsDefined(node.parent);
  while (true) {
    const parent = node.parent;
    if (isParenthesizedExpression(parent)) {
      node = parent;
      continue;
    }
    if (isExpressionStatement(parent) || isVoidExpression(parent) || isForStatement(parent) && (parent.initializer === node || parent.incrementor === node)) {
      return true;
    }
    if (isCommaListExpression(parent)) {
      if (node !== last(parent.elements)) return true;
      node = parent;
      continue;
    }
    if (isBinaryExpression(parent) && parent.operatorToken.kind === 28 /* CommaToken */) {
      if (node === parent.left) return true;
      node = parent;
      continue;
    }
    return false;
  }
}
function containsIgnoredPath(path) {
  return some(ignoredPaths, (p) => path.includes(p));
}
function getContainingNodeArray(node) {
  if (!node.parent) return void 0;
  switch (node.kind) {
    case 168 /* TypeParameter */:
      const { parent: parent2 } = node;
      return parent2.kind === 195 /* InferType */ ? void 0 : parent2.typeParameters;
    case 169 /* Parameter */:
      return node.parent.parameters;
    case 204 /* TemplateLiteralTypeSpan */:
      return node.parent.templateSpans;
    case 239 /* TemplateSpan */:
      return node.parent.templateSpans;
    case 170 /* Decorator */: {
      const { parent: parent3 } = node;
      return canHaveDecorators(parent3) ? parent3.modifiers : void 0;
    }
    case 298 /* HeritageClause */:
      return node.parent.heritageClauses;
  }
  const { parent } = node;
  if (isJSDocTag(node)) {
    return isJSDocTypeLiteral(node.parent) ? void 0 : node.parent.tags;
  }
  switch (parent.kind) {
    case 187 /* TypeLiteral */:
    case 264 /* InterfaceDeclaration */:
      return isTypeElement(node) ? parent.members : void 0;
    case 192 /* UnionType */:
    case 193 /* IntersectionType */:
      return parent.types;
    case 189 /* TupleType */:
    case 209 /* ArrayLiteralExpression */:
    case 356 /* CommaListExpression */:
    case 275 /* NamedImports */:
    case 279 /* NamedExports */:
      return parent.elements;
    case 210 /* ObjectLiteralExpression */:
    case 292 /* JsxAttributes */:
      return parent.properties;
    case 213 /* CallExpression */:
    case 214 /* NewExpression */:
      return isTypeNode(node) ? parent.typeArguments : parent.expression === node ? void 0 : parent.arguments;
    case 284 /* JsxElement */:
    case 288 /* JsxFragment */:
      return isJsxChild(node) ? parent.children : void 0;
    case 286 /* JsxOpeningElement */:
    case 285 /* JsxSelfClosingElement */:
      return isTypeNode(node) ? parent.typeArguments : void 0;
    case 241 /* Block */:
    case 296 /* CaseClause */:
    case 297 /* DefaultClause */:
    case 268 /* ModuleBlock */:
      return parent.statements;
    case 269 /* CaseBlock */:
      return parent.clauses;
    case 263 /* ClassDeclaration */:
    case 231 /* ClassExpression */:
      return isClassElement(node) ? parent.members : void 0;
    case 266 /* EnumDeclaration */:
      return isEnumMember(node) ? parent.members : void 0;
    case 307 /* SourceFile */:
      return parent.statements;
  }
}
function hasContextSensitiveParameters(node) {
  if (!node.typeParameters) {
    if (some(node.parameters, (p) => !getEffectiveTypeAnnotationNode(p))) {
      return true;
    }
    if (node.kind !== 219 /* ArrowFunction */) {
      const parameter = firstOrUndefined(node.parameters);
      if (!(parameter && parameterIsThisKeyword(parameter))) {
        return true;
      }
    }
  }
  return false;
}
function isInfinityOrNaNString(name) {
  return name === "Infinity" || name === "-Infinity" || name === "NaN";
}
function isCatchClauseVariableDeclaration(node) {
  return node.kind === 260 /* VariableDeclaration */ && node.parent.kind === 299 /* CatchClause */;
}
function isFunctionExpressionOrArrowFunction(node) {
  return node.kind === 218 /* FunctionExpression */ || node.kind === 219 /* ArrowFunction */;
}
function isNumericLiteralName(name) {
  return (+name).toString() === name;
}
function createPropertyNameNodeForIdentifierOrLiteral(name, target, singleQuote, stringNamed, isMethod) {
  const isMethodNamedNew = isMethod && name === "new";
  return !isMethodNamedNew && isIdentifierText(name, target) ? factory.createIdentifier(name) : !stringNamed && !isMethodNamedNew && isNumericLiteralName(name) && +name >= 0 ? factory.createNumericLiteral(+name) : factory.createStringLiteral(name, !!singleQuote);
}
function isThisTypeParameter(type) {
  return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
}
function getNodeModulePathParts(fullPath) {
  let topLevelNodeModulesIndex = 0;
  let topLevelPackageNameIndex = 0;
  let packageRootIndex = 0;
  let fileNameIndex = 0;
  let States;
  ((States2) => {
    States2[States2["BeforeNodeModules"] = 0] = "BeforeNodeModules";
    States2[States2["NodeModules"] = 1] = "NodeModules";
    States2[States2["Scope"] = 2] = "Scope";
    States2[States2["PackageContent"] = 3] = "PackageContent";
  })(States || (States = {}));
  let partStart = 0;
  let partEnd = 0;
  let state = 0 /* BeforeNodeModules */;
  while (partEnd >= 0) {
    partStart = partEnd;
    partEnd = fullPath.indexOf("/", partStart + 1);
    switch (state) {
      case 0 /* BeforeNodeModules */:
        if (fullPath.indexOf(nodeModulesPathPart, partStart) === partStart) {
          topLevelNodeModulesIndex = partStart;
          topLevelPackageNameIndex = partEnd;
          state = 1 /* NodeModules */;
        }
        break;
      case 1 /* NodeModules */:
      case 2 /* Scope */:
        if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
          state = 2 /* Scope */;
        } else {
          packageRootIndex = partEnd;
          state = 3 /* PackageContent */;
        }
        break;
      case 3 /* PackageContent */:
        if (fullPath.indexOf(nodeModulesPathPart, partStart) === partStart) {
          state = 1 /* NodeModules */;
        } else {
          state = 3 /* PackageContent */;
        }
        break;
    }
  }
  fileNameIndex = partStart;
  return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex, fileNameIndex } : void 0;
}
function isTypeDeclaration(node) {
  switch (node.kind) {
    case 168 /* TypeParameter */:
    case 263 /* ClassDeclaration */:
    case 264 /* InterfaceDeclaration */:
    case 265 /* TypeAliasDeclaration */:
    case 266 /* EnumDeclaration */:
    case 346 /* JSDocTypedefTag */:
    case 338 /* JSDocCallbackTag */:
    case 340 /* JSDocEnumTag */:
      return true;
    case 273 /* ImportClause */:
      return node.isTypeOnly;
    case 276 /* ImportSpecifier */:
    case 281 /* ExportSpecifier */:
      return node.parent.parent.isTypeOnly;
    default:
      return false;
  }
}
function canHaveExportModifier(node) {
  return isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isInterfaceDeclaration(node) || isTypeDeclaration(node) || isModuleDeclaration(node) && !isExternalModuleAugmentation(node) && !isGlobalScopeAugmentation(node);
}
function isOptionalJSDocPropertyLikeTag(node) {
  if (!isJSDocPropertyLikeTag(node)) {
    return false;
  }
  const { isBracketed, typeExpression } = node;
  return isBracketed || !!typeExpression && typeExpression.type.kind === 316 /* JSDocOptionalType */;
}
function canUsePropertyAccess(name, languageVersion) {
  if (name.length === 0) {
    return false;
  }
  const firstChar = name.charCodeAt(0);
  return firstChar === 35 /* hash */ ? name.length > 1 && isIdentifierStart(name.charCodeAt(1), languageVersion) : isIdentifierStart(firstChar, languageVersion);
}
function isJSDocOptionalParameter(node) {
  return isInJSFile(node) && // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
  (node.type && node.type.kind === 316 /* JSDocOptionalType */ || getJSDocParameterTags(node).some(isOptionalJSDocPropertyLikeTag));
}
function isOptionalDeclaration(declaration) {
  switch (declaration.kind) {
    case 172 /* PropertyDeclaration */:
    case 171 /* PropertySignature */:
      return !!declaration.questionToken;
    case 169 /* Parameter */:
      return !!declaration.questionToken || isJSDocOptionalParameter(declaration);
    case 348 /* JSDocPropertyTag */:
    case 341 /* JSDocParameterTag */:
      return isOptionalJSDocPropertyLikeTag(declaration);
    default:
      return false;
  }
}
function isNonNullAccess(node) {
  const kind = node.kind;
  return (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */) && isNonNullExpression(node.expression);
}
function isJSDocSatisfiesExpression(node) {
  return isInJSFile(node) && isParenthesizedExpression(node) && hasJSDocNodes(node) && !!getJSDocSatisfiesTag(node);
}
function getJSDocSatisfiesExpressionType(node) {
  return Debug.checkDefined(tryGetJSDocSatisfiesTypeNode(node));
}
function tryGetJSDocSatisfiesTypeNode(node) {
  const tag = getJSDocSatisfiesTag(node);
  return tag && tag.typeExpression && tag.typeExpression.type;
}
function getEscapedTextOfJsxAttributeName(node) {
  return isIdentifier(node) ? node.escapedText : getEscapedTextOfJsxNamespacedName(node);
}
function getTextOfJsxAttributeName(node) {
  return isIdentifier(node) ? idText(node) : getTextOfJsxNamespacedName(node);
}
function isJsxAttributeName(node) {
  const kind = node.kind;
  return kind === 80 /* Identifier */ || kind === 295 /* JsxNamespacedName */;
}
function getEscapedTextOfJsxNamespacedName(node) {
  return `${node.namespace.escapedText}:${idText(node.name)}`;
}
function getTextOfJsxNamespacedName(node) {
  return `${idText(node.namespace)}:${idText(node.name)}`;
}
function intrinsicTagNameToString(node) {
  return isIdentifier(node) ? idText(node) : getTextOfJsxNamespacedName(node);
}
function isTypeUsableAsPropertyName(type) {
  return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
}
function getPropertyNameFromType(type) {
  if (type.flags & 8192 /* UniqueESSymbol */) {
    return type.escapedName;
  }
  if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
    return escapeLeadingUnderscores("" + type.value);
  }
  return Debug.fail();
}
function isExpandoPropertyDeclaration(declaration) {
  return !!declaration && (isPropertyAccessExpression(declaration) || isElementAccessExpression(declaration) || isBinaryExpression(declaration));
}
function hasResolutionModeOverride(node) {
  if (node === void 0) {
    return false;
  }
  return !!getResolutionModeOverride(node.attributes);
}
var stringReplace = String.prototype.replace;
function replaceFirstStar(s, replacement) {
  return stringReplace.call(s, "*", replacement);
}
function getNameFromImportAttribute(node) {
  return isIdentifier(node.name) ? node.name.escapedText : escapeLeadingUnderscores(node.name.text);
}
function evaluatorResult(value, isSyntacticallyString = false, resolvedOtherFiles = false, hasExternalReferences = false) {
  return { value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences };
}
function createEvaluator({ evaluateElementAccessExpression, evaluateEntityNameExpression }) {
  function evaluate(expr, location) {
    let isSyntacticallyString = false;
    let resolvedOtherFiles = false;
    let hasExternalReferences = false;
    expr = skipParentheses(expr);
    switch (expr.kind) {
      case 224 /* PrefixUnaryExpression */:
        const result = evaluate(expr.operand, location);
        resolvedOtherFiles = result.resolvedOtherFiles;
        hasExternalReferences = result.hasExternalReferences;
        if (typeof result.value === "number") {
          switch (expr.operator) {
            case 40 /* PlusToken */:
              return evaluatorResult(result.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 41 /* MinusToken */:
              return evaluatorResult(-result.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 55 /* TildeToken */:
              return evaluatorResult(~result.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
          }
        }
        break;
      case 226 /* BinaryExpression */: {
        const left = evaluate(expr.left, location);
        const right = evaluate(expr.right, location);
        isSyntacticallyString = (left.isSyntacticallyString || right.isSyntacticallyString) && expr.operatorToken.kind === 40 /* PlusToken */;
        resolvedOtherFiles = left.resolvedOtherFiles || right.resolvedOtherFiles;
        hasExternalReferences = left.hasExternalReferences || right.hasExternalReferences;
        if (typeof left.value === "number" && typeof right.value === "number") {
          switch (expr.operatorToken.kind) {
            case 52 /* BarToken */:
              return evaluatorResult(left.value | right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 51 /* AmpersandToken */:
              return evaluatorResult(left.value & right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 49 /* GreaterThanGreaterThanToken */:
              return evaluatorResult(left.value >> right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 50 /* GreaterThanGreaterThanGreaterThanToken */:
              return evaluatorResult(left.value >>> right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 48 /* LessThanLessThanToken */:
              return evaluatorResult(left.value << right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 53 /* CaretToken */:
              return evaluatorResult(left.value ^ right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 42 /* AsteriskToken */:
              return evaluatorResult(left.value * right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 44 /* SlashToken */:
              return evaluatorResult(left.value / right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 40 /* PlusToken */:
              return evaluatorResult(left.value + right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 41 /* MinusToken */:
              return evaluatorResult(left.value - right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 45 /* PercentToken */:
              return evaluatorResult(left.value % right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
            case 43 /* AsteriskAsteriskToken */:
              return evaluatorResult(left.value ** right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences);
          }
        } else if ((typeof left.value === "string" || typeof left.value === "number") && (typeof right.value === "string" || typeof right.value === "number") && expr.operatorToken.kind === 40 /* PlusToken */) {
          return evaluatorResult(
            "" + left.value + right.value,
            isSyntacticallyString,
            resolvedOtherFiles,
            hasExternalReferences
          );
        }
        break;
      }
      case 11 /* StringLiteral */:
      case 15 /* NoSubstitutionTemplateLiteral */:
        return evaluatorResult(
          expr.text,
          /*isSyntacticallyString*/
          true
        );
      case 228 /* TemplateExpression */:
        return evaluateTemplateExpression(expr, location);
      case 9 /* NumericLiteral */:
        return evaluatorResult(+expr.text);
      case 80 /* Identifier */:
        return evaluateEntityNameExpression(expr, location);
      case 211 /* PropertyAccessExpression */:
        if (isEntityNameExpression(expr)) {
          return evaluateEntityNameExpression(expr, location);
        }
        break;
      case 212 /* ElementAccessExpression */:
        return evaluateElementAccessExpression(expr, location);
    }
    return evaluatorResult(
      /*value*/
      void 0,
      isSyntacticallyString,
      resolvedOtherFiles,
      hasExternalReferences
    );
  }
  function evaluateTemplateExpression(expr, location) {
    let result = expr.head.text;
    let resolvedOtherFiles = false;
    let hasExternalReferences = false;
    for (const span of expr.templateSpans) {
      const spanResult = evaluate(span.expression, location);
      if (spanResult.value === void 0) {
        return evaluatorResult(
          /*value*/
          void 0,
          /*isSyntacticallyString*/
          true
        );
      }
      result += spanResult.value;
      result += span.literal.text;
      resolvedOtherFiles || (resolvedOtherFiles = spanResult.resolvedOtherFiles);
      hasExternalReferences || (hasExternalReferences = spanResult.hasExternalReferences);
    }
    return evaluatorResult(
      result,
      /*isSyntacticallyString*/
      true,
      resolvedOtherFiles,
      hasExternalReferences
    );
  }
  return evaluate;
}
function isConstAssertion(location) {
  return isAssertionExpression(location) && isConstTypeReference(location.type) || isJSDocTypeTag(location) && isConstTypeReference(location.typeExpression);
}
function findConstructorDeclaration(node) {
  const members = node.members;
  for (const member of members) {
    if (member.kind === 176 /* Constructor */ && nodeIsPresent(member.body)) {
      return member;
    }
  }
}
function createNameResolver({
  compilerOptions,
  requireSymbol,
  argumentsSymbol,
  error,
  getSymbolOfDeclaration,
  globals,
  lookup,
  setRequiresScopeChangeCache = returnUndefined,
  getRequiresScopeChangeCache = returnUndefined,
  onPropertyWithInvalidInitializer = returnFalse,
  onFailedToResolveSymbol = returnUndefined,
  onSuccessfullyResolvedSymbol = returnUndefined
}) {
  var isolatedModulesLikeFlagName = compilerOptions.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules";
  var emitStandardClassFields = getEmitStandardClassFields(compilerOptions);
  var emptySymbols = createSymbolTable();
  return resolveNameHelper;
  function resolveNameHelper(location, nameArg, meaning, nameNotFoundMessage, isUse, excludeGlobals) {
    var _a, _b, _c;
    const originalLocation = location;
    let result;
    let lastLocation;
    let lastSelfReferenceLocation;
    let propertyWithInvalidInitializer;
    let associatedDeclarationForContainingInitializerOrBindingName;
    let withinDeferredContext = false;
    let grandparent;
    const name = isString(nameArg) ? nameArg : nameArg.escapedText;
    loop:
      while (location) {
        if (name === "const" && isConstAssertion(location)) {
          return void 0;
        }
        if (isModuleOrEnumDeclaration(location) && lastLocation && location.name === lastLocation) {
          lastLocation = location;
          location = location.parent;
        }
        if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) {
          if (result = lookup(location.locals, name, meaning)) {
            let useResult = true;
            if (isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
              if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 320 /* JSDoc */) {
                useResult = result.flags & 262144 /* TypeParameter */ ? !!(lastLocation.flags & 16 /* Synthesized */) || // Synthetic fake scopes are added for signatures so type parameters are accessible from them
                lastLocation === location.type || lastLocation.kind === 169 /* Parameter */ || lastLocation.kind === 341 /* JSDocParameterTag */ || lastLocation.kind === 342 /* JSDocReturnTag */ || lastLocation.kind === 168 /* TypeParameter */ : false;
              }
              if (meaning & result.flags & 3 /* Variable */) {
                if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
                  useResult = false;
                } else if (result.flags & 1 /* FunctionScopedVariable */) {
                  useResult = lastLocation.kind === 169 /* Parameter */ || !!(lastLocation.flags & 16 /* Synthesized */) || // Synthetic fake scopes are added for signatures so parameters are accessible from them
                  lastLocation === location.type && !!findAncestor(result.valueDeclaration, isParameter);
                }
              }
            } else if (location.kind === 194 /* ConditionalType */) {
              useResult = lastLocation === location.trueType;
            }
            if (useResult) {
              break loop;
            } else {
              result = void 0;
            }
          }
        }
        withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
        switch (location.kind) {
          case 307 /* SourceFile */:
            if (!isExternalOrCommonJsModule(location)) break;
          // falls through
          case 267 /* ModuleDeclaration */:
            const moduleExports = ((_a = getSymbolOfDeclaration(location)) == null ? void 0 : _a.exports) || emptySymbols;
            if (location.kind === 307 /* SourceFile */ || isModuleDeclaration(location) && location.flags & 33554432 /* Ambient */ && !isGlobalScopeAugmentation(location)) {
              if (result = moduleExports.get("default" /* Default */)) {
                const localSymbol = getLocalSymbolForExportDefault(result);
                if (localSymbol && result.flags & meaning && localSymbol.escapedName === name) {
                  break loop;
                }
                result = void 0;
              }
              const moduleExport = moduleExports.get(name);
              if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && (getDeclarationOfKind(moduleExport, 281 /* ExportSpecifier */) || getDeclarationOfKind(moduleExport, 280 /* NamespaceExport */))) {
                break;
              }
            }
            if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
              if (isSourceFile(location) && location.commonJsModuleIndicator && !((_b = result.declarations) == null ? void 0 : _b.some(isJSDocTypeAlias))) {
                result = void 0;
              } else {
                break loop;
              }
            }
            break;
          case 266 /* EnumDeclaration */:
            if (result = lookup(((_c = getSymbolOfDeclaration(location)) == null ? void 0 : _c.exports) || emptySymbols, name, meaning & 8 /* EnumMember */)) {
              if (nameNotFoundMessage && getIsolatedModules(compilerOptions) && !(location.flags & 33554432 /* Ambient */) && getSourceFileOfNode(location) !== getSourceFileOfNode(result.valueDeclaration)) {
                error(
                  originalLocation,
                  Diagnostics.Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead,
                  unescapeLeadingUnderscores(name),
                  isolatedModulesLikeFlagName,
                  `${unescapeLeadingUnderscores(getSymbolOfDeclaration(location).escapedName)}.${unescapeLeadingUnderscores(name)}`
                );
              }
              break loop;
            }
            break;
          case 172 /* PropertyDeclaration */:
            if (!isStatic(location)) {
              const ctor = findConstructorDeclaration(location.parent);
              if (ctor && ctor.locals) {
                if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
                  Debug.assertNode(location, isPropertyDeclaration);
                  propertyWithInvalidInitializer = location;
                }
              }
            }
            break;
          case 263 /* ClassDeclaration */:
          case 231 /* ClassExpression */:
          case 264 /* InterfaceDeclaration */:
            if (result = lookup(getSymbolOfDeclaration(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
              if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
                result = void 0;
                break;
              }
              if (lastLocation && isStatic(lastLocation)) {
                if (nameNotFoundMessage) {
                  error(originalLocation, Diagnostics.Static_members_cannot_reference_class_type_parameters);
                }
                return void 0;
              }
              break loop;
            }
            if (isClassExpression(location) && meaning & 32 /* Class */) {
              const className = location.name;
              if (className && name === className.escapedText) {
                result = location.symbol;
                break loop;
              }
            }
            break;
          case 233 /* ExpressionWithTypeArguments */:
            if (lastLocation === location.expression && location.parent.token === 96 /* ExtendsKeyword */) {
              const container = location.parent.parent;
              if (isClassLike(container) && (result = lookup(getSymbolOfDeclaration(container).members, name, meaning & 788968 /* Type */))) {
                if (nameNotFoundMessage) {
                  error(originalLocation, Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
                }
                return void 0;
              }
            }
            break;
          // It is not legal to reference a class's own type parameters from a computed property name that
          // belongs to the class. For example:
          //
          //   function foo<T>() { return '' }
          //   class C<T> { // <-- Class's own type parameter T
          //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
          //   }
          //
          case 167 /* ComputedPropertyName */:
            grandparent = location.parent.parent;
            if (isClassLike(grandparent) || grandparent.kind === 264 /* InterfaceDeclaration */) {
              if (result = lookup(getSymbolOfDeclaration(grandparent).members, name, meaning & 788968 /* Type */)) {
                if (nameNotFoundMessage) {
                  error(originalLocation, Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
                }
                return void 0;
              }
            }
            break;
          case 219 /* ArrowFunction */:
            if (getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */) {
              break;
            }
          // falls through
          case 174 /* MethodDeclaration */:
          case 176 /* Constructor */:
          case 177 /* GetAccessor */:
          case 178 /* SetAccessor */:
          case 262 /* FunctionDeclaration */:
            if (meaning & 3 /* Variable */ && name === "arguments") {
              result = argumentsSymbol;
              break loop;
            }
            break;
          case 218 /* FunctionExpression */:
            if (meaning & 3 /* Variable */ && name === "arguments") {
              result = argumentsSymbol;
              break loop;
            }
            if (meaning & 16 /* Function */) {
              const functionName = location.name;
              if (functionName && name === functionName.escapedText) {
                result = location.symbol;
                break loop;
              }
            }
            break;
          case 170 /* Decorator */:
            if (location.parent && location.parent.kind === 169 /* Parameter */) {
              location = location.parent;
            }
            if (location.parent && (isClassElement(location.parent) || location.parent.kind === 263 /* ClassDeclaration */)) {
              location = location.parent;
            }
            break;
          case 346 /* JSDocTypedefTag */:
          case 338 /* JSDocCallbackTag */:
          case 340 /* JSDocEnumTag */:
          case 351 /* JSDocImportTag */:
            const root = getJSDocRoot(location);
            if (root) {
              location = root.parent;
            }
            break;
          case 169 /* Parameter */:
            if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && isBindingPattern(lastLocation))) {
              if (!associatedDeclarationForContainingInitializerOrBindingName) {
                associatedDeclarationForContainingInitializerOrBindingName = location;
              }
            }
            break;
          case 208 /* BindingElement */:
            if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && isBindingPattern(lastLocation))) {
              if (isPartOfParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) {
                associatedDeclarationForContainingInitializerOrBindingName = location;
              }
            }
            break;
          case 195 /* InferType */:
            if (meaning & 262144 /* TypeParameter */) {
              const parameterName = location.typeParameter.name;
              if (parameterName && name === parameterName.escapedText) {
                result = location.typeParameter.symbol;
                break loop;
              }
            }
            break;
          case 281 /* ExportSpecifier */:
            if (lastLocation && lastLocation === location.propertyName && location.parent.parent.moduleSpecifier) {
              location = location.parent.parent.parent;
            }
            break;
        }
        if (isSelfReferenceLocation(location, lastLocation)) {
          lastSelfReferenceLocation = location;
        }
        lastLocation = location;
        location = isJSDocTemplateTag(location) ? getEffectiveContainerForJSDocTemplateTag(location) || location.parent : isJSDocParameterTag(location) || isJSDocReturnTag(location) ? getHostSignatureFromJSDoc(location) || location.parent : location.parent;
      }
    if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
      result.isReferenced |= meaning;
    }
    if (!result) {
      if (lastLocation) {
        Debug.assertNode(lastLocation, isSourceFile);
        if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
          return lastLocation.symbol;
        }
      }
      if (!excludeGlobals) {
        result = lookup(globals, name, meaning);
      }
    }
    if (!result) {
      if (originalLocation && isInJSFile(originalLocation) && originalLocation.parent) {
        if (isRequireCall(
          originalLocation.parent,
          /*requireStringLiteralLikeArgument*/
          false
        )) {
          return requireSymbol;
        }
      }
    }
    if (nameNotFoundMessage) {
      if (propertyWithInvalidInitializer && onPropertyWithInvalidInitializer(originalLocation, name, propertyWithInvalidInitializer, result)) {
        return void 0;
      }
      if (!result) {
        onFailedToResolveSymbol(originalLocation, nameArg, meaning, nameNotFoundMessage);
      } else {
        onSuccessfullyResolvedSymbol(originalLocation, result, meaning, lastLocation, associatedDeclarationForContainingInitializerOrBindingName, withinDeferredContext);
      }
    }
    return result;
  }
  function useOuterVariableScopeInParameter(result, location, lastLocation) {
    const target = getEmitScriptTarget(compilerOptions);
    const functionLocation = location;
    if (isParameter(lastLocation) && functionLocation.body && result.valueDeclaration && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
      if (target >= 2 /* ES2015 */) {
        let declarationRequiresScopeChange = getRequiresScopeChangeCache(functionLocation);
        if (declarationRequiresScopeChange === void 0) {
          declarationRequiresScopeChange = forEach(functionLocation.parameters, requiresScopeChange) || false;
          setRequiresScopeChangeCache(functionLocation, declarationRequiresScopeChange);
        }
        return !declarationRequiresScopeChange;
      }
    }
    return false;
    function requiresScopeChange(node) {
      return requiresScopeChangeWorker(node.name) || !!node.initializer && requiresScopeChangeWorker(node.initializer);
    }
    function requiresScopeChangeWorker(node) {
      switch (node.kind) {
        case 219 /* ArrowFunction */:
        case 218 /* FunctionExpression */:
        case 262 /* FunctionDeclaration */:
        case 176 /* Constructor */:
          return false;
        case 174 /* MethodDeclaration */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
        case 303 /* PropertyAssignment */:
          return requiresScopeChangeWorker(node.name);
        case 172 /* PropertyDeclaration */:
          if (hasStaticModifier(node)) {
            return !emitStandardClassFields;
          }
          return requiresScopeChangeWorker(node.name);
        default:
          if (isNullishCoalesce(node) || isOptionalChain(node)) {
            return target < 7 /* ES2020 */;
          }
          if (isBindingElement(node) && node.dotDotDotToken && isObjectBindingPattern(node.parent)) {
            return target < 4 /* ES2017 */;
          }
          if (isTypeNode(node)) return false;
          return forEachChild(node, requiresScopeChangeWorker) || false;
      }
    }
  }
  function getIsDeferredContext(location, lastLocation) {
    if (location.kind !== 219 /* ArrowFunction */ && location.kind !== 218 /* FunctionExpression */) {
      return isTypeQueryNode(location) || (isFunctionLikeDeclaration(location) || location.kind === 172 /* PropertyDeclaration */ && !isStatic(location)) && (!lastLocation || lastLocation !== location.name);
    }
    if (lastLocation && lastLocation === location.name) {
      return false;
    }
    if (location.asteriskToken || hasSyntacticModifier(location, 1024 /* Async */)) {
      return true;
    }
    return !getImmediatelyInvokedFunctionExpression(location);
  }
  function isSelfReferenceLocation(node, lastLocation) {
    switch (node.kind) {
      case 169 /* Parameter */:
        return !!lastLocation && lastLocation === node.name;
      case 262 /* FunctionDeclaration */:
      case 263 /* ClassDeclaration */:
      case 264 /* InterfaceDeclaration */:
      case 266 /* EnumDeclaration */:
      case 265 /* TypeAliasDeclaration */:
      case 267 /* ModuleDeclaration */:
        return true;
      default:
        return false;
    }
  }
  function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
    if (symbol.declarations) {
      for (const decl of symbol.declarations) {
        if (decl.kind === 168 /* TypeParameter */) {
          const parent = isJSDocTemplateTag(decl.parent) ? getJSDocHost(decl.parent) : decl.parent;
          if (parent === container) {
            return !(isJSDocTemplateTag(decl.parent) && find(decl.parent.parent.tags, isJSDocTypeAlias));
          }
        }
      }
    }
    return false;
  }
}
function isPrimitiveLiteralValue(node, includeBigInt = true) {
  Debug.type(node);
  switch (node.kind) {
    case 112 /* TrueKeyword */:
    case 97 /* FalseKeyword */:
    case 9 /* NumericLiteral */:
    case 11 /* StringLiteral */:
    case 15 /* NoSubstitutionTemplateLiteral */:
      return true;
    case 10 /* BigIntLiteral */:
      return includeBigInt;
    case 224 /* PrefixUnaryExpression */:
      if (node.operator === 41 /* MinusToken */) {
        return isNumericLiteral(node.operand) || includeBigInt && isBigIntLiteral(node.operand);
      }
      if (node.operator === 40 /* PlusToken */) {
        return isNumericLiteral(node.operand);
      }
      return false;
    default:
      assertType(node);
      return false;
  }
}
function unwrapParenthesizedExpression(o) {
  while (o.kind === 217 /* ParenthesizedExpression */) {
    o = o.expression;
  }
  return o;
}
function hasInferredType(node) {
  Debug.type(node);
  switch (node.kind) {
    case 169 /* Parameter */:
    case 171 /* PropertySignature */:
    case 172 /* PropertyDeclaration */:
    case 208 /* BindingElement */:
    case 211 /* PropertyAccessExpression */:
    case 212 /* ElementAccessExpression */:
    case 226 /* BinaryExpression */:
    case 260 /* VariableDeclaration */:
    case 277 /* ExportAssignment */:
    case 303 /* PropertyAssignment */:
    case 304 /* ShorthandPropertyAssignment */:
    case 341 /* JSDocParameterTag */:
    case 348 /* JSDocPropertyTag */:
      return true;
    default:
      assertType(node);
      return false;
  }
}
function isSideEffectImport(node) {
  const ancestor = findAncestor(node, isImportDeclaration);
  return !!ancestor && !ancestor.importClause;
}
var unprefixedNodeCoreModulesList = [
  "assert",
  "assert/strict",
  "async_hooks",
  "buffer",
  "child_process",
  "cluster",
  "console",
  "constants",
  "crypto",
  "dgram",
  "diagnostics_channel",
  "dns",
  "dns/promises",
  "domain",
  "events",
  "fs",
  "fs/promises",
  "http",
  "http2",
  "https",
  "inspector",
  "inspector/promises",
  "module",
  "net",
  "os",
  "path",
  "path/posix",
  "path/win32",
  "perf_hooks",
  "process",
  "punycode",
  "querystring",
  "readline",
  "readline/promises",
  "repl",
  "stream",
  "stream/consumers",
  "stream/promises",
  "stream/web",
  "string_decoder",
  "sys",
  "test/mock_loader",
  "timers",
  "timers/promises",
  "tls",
  "trace_events",
  "tty",
  "url",
  "util",
  "util/types",
  "v8",
  "vm",
  "wasi",
  "worker_threads",
  "zlib"
];
var unprefixedNodeCoreModules = new Set(unprefixedNodeCoreModulesList);
var exclusivelyPrefixedNodeCoreModules = /* @__PURE__ */ new Set([
  "node:sea",
  "node:sqlite",
  "node:test",
  "node:test/reporters"
]);
var nodeCoreModules = /* @__PURE__ */ new Set([
  ...unprefixedNodeCoreModulesList,
  ...unprefixedNodeCoreModulesList.map((name) => `node:${name}`),
  ...exclusivelyPrefixedNodeCoreModules
]);
function forEachDynamicImportOrRequireCall(file, includeTypeSpaceImports, requireStringLiteralLikeArgument, cb) {
  const isJavaScriptFile = isInJSFile(file);
  const r = /import|require/g;
  while (r.exec(file.text) !== null) {
    const node = getNodeAtPosition(
      file,
      r.lastIndex,
      /*includeJSDoc*/
      includeTypeSpaceImports
    );
    if (isJavaScriptFile && isRequireCall(node, requireStringLiteralLikeArgument)) {
      cb(node, node.arguments[0]);
    } else if (isImportCall(node) && node.arguments.length >= 1 && (!requireStringLiteralLikeArgument || isStringLiteralLike(node.arguments[0]))) {
      cb(node, node.arguments[0]);
    } else if (includeTypeSpaceImports && isLiteralImportTypeNode(node)) {
      cb(node, node.argument.literal);
    } else if (includeTypeSpaceImports && isJSDocImportTag(node)) {
      const moduleNameExpr = getExternalModuleName(node);
      if (moduleNameExpr && isStringLiteral(moduleNameExpr) && moduleNameExpr.text) {
        cb(node, moduleNameExpr);
      }
    }
  }
}
function getNodeAtPosition(sourceFile, position, includeJSDoc) {
  const isJavaScriptFile = isInJSFile(sourceFile);
  let current = sourceFile;
  const getContainingChild = (child) => {
    if (child.pos <= position && (position < child.end || position === child.end && child.kind === 1 /* EndOfFileToken */)) {
      return child;
    }
  };
  while (true) {
    const child = isJavaScriptFile && includeJSDoc && hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild);
    if (!child) {
      return current;
    }
    current = child;
  }
}
function isNewScopeNode(node) {
  return isFunctionLike(node) || isJSDocSignature(node) || isMappedTypeNode(node);
}

// src/compiler/factory/baseNodeFactory.ts
function createBaseNodeFactory() {
  let NodeConstructor2;
  let TokenConstructor2;
  let IdentifierConstructor2;
  let PrivateIdentifierConstructor2;
  let SourceFileConstructor2;
  return {
    createBaseSourceFileNode,
    createBaseIdentifierNode,
    createBasePrivateIdentifierNode,
    createBaseTokenNode,
    createBaseNode
  };
  function createBaseSourceFileNode(kind) {
    return new (SourceFileConstructor2 || (SourceFileConstructor2 = objectAllocator.getSourceFileConstructor()))(
      kind,
      /*pos*/
      -1,
      /*end*/
      -1
    );
  }
  function createBaseIdentifierNode(kind) {
    return new (IdentifierConstructor2 || (IdentifierConstructor2 = objectAllocator.getIdentifierConstructor()))(
      kind,
      /*pos*/
      -1,
      /*end*/
      -1
    );
  }
  function createBasePrivateIdentifierNode(kind) {
    return new (PrivateIdentifierConstructor2 || (PrivateIdentifierConstructor2 = objectAllocator.getPrivateIdentifierConstructor()))(
      kind,
      /*pos*/
      -1,
      /*end*/
      -1
    );
  }
  function createBaseTokenNode(kind) {
    return new (TokenConstructor2 || (TokenConstructor2 = objectAllocator.getTokenConstructor()))(
      kind,
      /*pos*/
      -1,
      /*end*/
      -1
    );
  }
  function createBaseNode(kind) {
    return new (NodeConstructor2 || (NodeConstructor2 = objectAllocator.getNodeConstructor()))(
      kind,
      /*pos*/
      -1,
      /*end*/
      -1
    );
  }
}

// src/compiler/factory/parenthesizerRules.ts
function createParenthesizerRules(factory2) {
  let binaryLeftOperandParenthesizerCache;
  let binaryRightOperandParenthesizerCache;
  return {
    getParenthesizeLeftSideOfBinaryForOperator,
    getParenthesizeRightSideOfBinaryForOperator,
    parenthesizeLeftSideOfBinary,
    parenthesizeRightSideOfBinary,
    parenthesizeExpressionOfComputedPropertyName,
    parenthesizeConditionOfConditionalExpression,
    parenthesizeBranchOfConditionalExpression,
    parenthesizeExpressionOfExportDefault,
    parenthesizeExpressionOfNew,
    parenthesizeLeftSideOfAccess,
    parenthesizeOperandOfPostfixUnary,
    parenthesizeOperandOfPrefixUnary,
    parenthesizeExpressionsOfCommaDelimitedList,
    parenthesizeExpressionForDisallowedComma,
    parenthesizeExpressionOfExpressionStatement,
    parenthesizeConciseBodyOfArrowFunction,
    parenthesizeCheckTypeOfConditionalType,
    parenthesizeExtendsTypeOfConditionalType,
    parenthesizeConstituentTypesOfUnionType,
    parenthesizeConstituentTypeOfUnionType,
    parenthesizeConstituentTypesOfIntersectionType,
    parenthesizeConstituentTypeOfIntersectionType,
    parenthesizeOperandOfTypeOperator,
    parenthesizeOperandOfReadonlyTypeOperator,
    parenthesizeNonArrayTypeOfPostfixType,
    parenthesizeElementTypesOfTupleType,
    parenthesizeElementTypeOfTupleType,
    parenthesizeTypeOfOptionalType,
    parenthesizeTypeArguments,
    parenthesizeLeadingTypeArgument
  };
  function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) {
    binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = /* @__PURE__ */ new Map());
    let parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind);
    if (!parenthesizerRule) {
      parenthesizerRule = (node) => parenthesizeLeftSideOfBinary(operatorKind, node);
      binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule);
    }
    return parenthesizerRule;
  }
  function getParenthesizeRightSideOfBinaryForOperator(operatorKind) {
    binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = /* @__PURE__ */ new Map());
    let parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind);
    if (!parenthesizerRule) {
      parenthesizerRule = (node) => parenthesizeRightSideOfBinary(
        operatorKind,
        /*leftSide*/
        void 0,
        node
      );
      binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule);
    }
    return parenthesizerRule;
  }
  function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
    const binaryOperatorPrecedence = getOperatorPrecedence(226 /* BinaryExpression */, binaryOperator);
    const binaryOperatorAssociativity = getOperatorAssociativity(226 /* BinaryExpression */, binaryOperator);
    const emittedOperand = skipPartiallyEmittedExpressions(operand);
    if (!isLeftSideOfBinary && operand.kind === 219 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) {
      return true;
    }
    const operandPrecedence = getExpressionPrecedence(emittedOperand);
    switch (compareValues(operandPrecedence, binaryOperatorPrecedence)) {
      case -1 /* LessThan */:
        if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ && operand.kind === 229 /* YieldExpression */) {
          return false;
        }
        return true;
      case 1 /* GreaterThan */:
        return false;
      case 0 /* EqualTo */:
        if (isLeftSideOfBinary) {
          return binaryOperatorAssociativity === 1 /* Right */;
        } else {
          if (isBinaryExpression(emittedOperand) && emittedOperand.operatorToken.kind === binaryOperator) {
            if (operatorHasAssociativeProperty(binaryOperator)) {
              return false;
            }
            if (binaryOperator === 40 /* PlusToken */) {
              const leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
              if (isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
                return false;
              }
            }
          }
          const operandAssociativity = getExpressionAssociativity(emittedOperand);
          return operandAssociativity === 0 /* Left */;
        }
    }
  }
  function operatorHasAssociativeProperty(binaryOperator) {
    return binaryOperator === 42 /* AsteriskToken */ || binaryOperator === 52 /* BarToken */ || binaryOperator === 51 /* AmpersandToken */ || binaryOperator === 53 /* CaretToken */ || binaryOperator === 28 /* CommaToken */;
  }
  function getLiteralKindOfBinaryPlusOperand(node) {
    node = skipPartiallyEmittedExpressions(node);
    if (isLiteralKind(node.kind)) {
      return node.kind;
    }
    if (node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 40 /* PlusToken */) {
      if (node.cachedLiteralKind !== void 0) {
        return node.cachedLiteralKind;
      }
      const leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
      const literalKind = isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) ? leftKind : 0 /* Unknown */;
      node.cachedLiteralKind = literalKind;
      return literalKind;
    }
    return 0 /* Unknown */;
  }
  function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
    const skipped = skipPartiallyEmittedExpressions(operand);
    if (skipped.kind === 217 /* ParenthesizedExpression */) {
      return operand;
    }
    return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) ? factory2.createParenthesizedExpression(operand) : operand;
  }
  function parenthesizeLeftSideOfBinary(binaryOperator, leftSide) {
    return parenthesizeBinaryOperand(
      binaryOperator,
      leftSide,
      /*isLeftSideOfBinary*/
      true
    );
  }
  function parenthesizeRightSideOfBinary(binaryOperator, leftSide, rightSide) {
    return parenthesizeBinaryOperand(
      binaryOperator,
      rightSide,
      /*isLeftSideOfBinary*/
      false,
      leftSide
    );
  }
  function parenthesizeExpressionOfComputedPropertyName(expression) {
    return isCommaSequence(expression) ? factory2.createParenthesizedExpression(expression) : expression;
  }
  function parenthesizeConditionOfConditionalExpression(condition) {
    const conditionalPrecedence = getOperatorPrecedence(227 /* ConditionalExpression */, 58 /* QuestionToken */);
    const emittedCondition = skipPartiallyEmittedExpressions(condition);
    const conditionPrecedence = getExpressionPrecedence(emittedCondition);
    if (compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
      return factory2.createParenthesizedExpression(condition);
    }
    return condition;
  }
  function parenthesizeBranchOfConditionalExpression(branch) {
    const emittedExpression = skipPartiallyEmittedExpressions(branch);
    return isCommaSequence(emittedExpression) ? factory2.createParenthesizedExpression(branch) : branch;
  }
  function parenthesizeExpressionOfExportDefault(expression) {
    const check = skipPartiallyEmittedExpressions(expression);
    let needsParens = isCommaSequence(check);
    if (!needsParens) {
      switch (getLeftmostExpression(
        check,
        /*stopAtCallExpressions*/
        false
      ).kind) {
        case 231 /* ClassExpression */:
        case 218 /* FunctionExpression */:
          needsParens = true;
      }
    }
    return needsParens ? factory2.createParenthesizedExpression(expression) : expression;
  }
  function parenthesizeExpressionOfNew(expression) {
    const leftmostExpr = getLeftmostExpression(
      expression,
      /*stopAtCallExpressions*/
      true
    );
    switch (leftmostExpr.kind) {
      case 213 /* CallExpression */:
        return factory2.createParenthesizedExpression(expression);
      case 214 /* NewExpression */:
        return !leftmostExpr.arguments ? factory2.createParenthesizedExpression(expression) : expression;
    }
    return parenthesizeLeftSideOfAccess(expression);
  }
  function parenthesizeLeftSideOfAccess(expression, optionalChain) {
    const emittedExpression = skipPartiallyEmittedExpressions(expression);
    if (isLeftHandSideExpression(emittedExpression) && (emittedExpression.kind !== 214 /* NewExpression */ || emittedExpression.arguments) && (optionalChain || !isOptionalChain(emittedExpression))) {
      return expression;
    }
    return setTextRange(factory2.createParenthesizedExpression(expression), expression);
  }
  function parenthesizeOperandOfPostfixUnary(operand) {
    return isLeftHandSideExpression(operand) ? operand : setTextRange(factory2.createParenthesizedExpression(operand), operand);
  }
  function parenthesizeOperandOfPrefixUnary(operand) {
    return isUnaryExpression(operand) ? operand : setTextRange(factory2.createParenthesizedExpression(operand), operand);
  }
  function parenthesizeExpressionsOfCommaDelimitedList(elements) {
    const result = sameMap(elements, parenthesizeExpressionForDisallowedComma);
    return setTextRange(factory2.createNodeArray(result, elements.hasTrailingComma), elements);
  }
  function parenthesizeExpressionForDisallowedComma(expression) {
    const emittedExpression = skipPartiallyEmittedExpressions(expression);
    const expressionPrecedence = getExpressionPrecedence(emittedExpression);
    const commaPrecedence = getOperatorPrecedence(226 /* BinaryExpression */, 28 /* CommaToken */);
    return expressionPrecedence > commaPrecedence ? expression : setTextRange(factory2.createParenthesizedExpression(expression), expression);
  }
  function parenthesizeExpressionOfExpressionStatement(expression) {
    const emittedExpression = skipPartiallyEmittedExpressions(expression);
    if (isCallExpression(emittedExpression)) {
      const callee = emittedExpression.expression;
      const kind = skipPartiallyEmittedExpressions(callee).kind;
      if (kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */) {
        const updated = factory2.updateCallExpression(
          emittedExpression,
          setTextRange(factory2.createParenthesizedExpression(callee), callee),
          emittedExpression.typeArguments,
          emittedExpression.arguments
        );
        return factory2.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */);
      }
    }
    const leftmostExpressionKind = getLeftmostExpression(
      emittedExpression,
      /*stopAtCallExpressions*/
      false
    ).kind;
    if (leftmostExpressionKind === 210 /* ObjectLiteralExpression */ || leftmostExpressionKind === 218 /* FunctionExpression */) {
      return setTextRange(factory2.createParenthesizedExpression(expression), expression);
    }
    return expression;
  }
  function parenthesizeConciseBodyOfArrowFunction(body) {
    if (!isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(
      body,
      /*stopAtCallExpressions*/
      false
    ).kind === 210 /* ObjectLiteralExpression */)) {
      return setTextRange(factory2.createParenthesizedExpression(body), body);
    }
    return body;
  }
  function parenthesizeCheckTypeOfConditionalType(checkType) {
    switch (checkType.kind) {
      case 184 /* FunctionType */:
      case 185 /* ConstructorType */:
      case 194 /* ConditionalType */:
        return factory2.createParenthesizedType(checkType);
    }
    return checkType;
  }
  function parenthesizeExtendsTypeOfConditionalType(extendsType) {
    switch (extendsType.kind) {
      case 194 /* ConditionalType */:
        return factory2.createParenthesizedType(extendsType);
    }
    return extendsType;
  }
  function parenthesizeConstituentTypeOfUnionType(type) {
    switch (type.kind) {
      case 192 /* UnionType */:
      // Not strictly necessary, but a union containing a union should have been flattened
      case 193 /* IntersectionType */:
        return factory2.createParenthesizedType(type);
    }
    return parenthesizeCheckTypeOfConditionalType(type);
  }
  function parenthesizeConstituentTypesOfUnionType(members) {
    return factory2.createNodeArray(sameMap(members, parenthesizeConstituentTypeOfUnionType));
  }
  function parenthesizeConstituentTypeOfIntersectionType(type) {
    switch (type.kind) {
      case 192 /* UnionType */:
      case 193 /* IntersectionType */:
        return factory2.createParenthesizedType(type);
    }
    return parenthesizeConstituentTypeOfUnionType(type);
  }
  function parenthesizeConstituentTypesOfIntersectionType(members) {
    return factory2.createNodeArray(sameMap(members, parenthesizeConstituentTypeOfIntersectionType));
  }
  function parenthesizeOperandOfTypeOperator(type) {
    switch (type.kind) {
      case 193 /* IntersectionType */:
        return factory2.createParenthesizedType(type);
    }
    return parenthesizeConstituentTypeOfIntersectionType(type);
  }
  function parenthesizeOperandOfReadonlyTypeOperator(type) {
    switch (type.kind) {
      case 198 /* TypeOperator */:
        return factory2.createParenthesizedType(type);
    }
    return parenthesizeOperandOfTypeOperator(type);
  }
  function parenthesizeNonArrayTypeOfPostfixType(type) {
    switch (type.kind) {
      case 195 /* InferType */:
      case 198 /* TypeOperator */:
      case 186 /* TypeQuery */:
        return factory2.createParenthesizedType(type);
    }
    return parenthesizeOperandOfTypeOperator(type);
  }
  function parenthesizeElementTypesOfTupleType(types) {
    return factory2.createNodeArray(sameMap(types, parenthesizeElementTypeOfTupleType));
  }
  function parenthesizeElementTypeOfTupleType(type) {
    if (hasJSDocPostfixQuestion(type)) return factory2.createParenthesizedType(type);
    return type;
  }
  function hasJSDocPostfixQuestion(type) {
    if (isJSDocNullableType(type)) return type.postfix;
    if (isNamedTupleMember(type)) return hasJSDocPostfixQuestion(type.type);
    if (isFunctionTypeNode(type) || isConstructorTypeNode(type) || isTypeOperatorNode(type)) return hasJSDocPostfixQuestion(type.type);
    if (isConditionalTypeNode(type)) return hasJSDocPostfixQuestion(type.falseType);
    if (isUnionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.types));
    if (isIntersectionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.types));
    if (isInferTypeNode(type)) return !!type.typeParameter.constraint && hasJSDocPostfixQuestion(type.typeParameter.constraint);
    return false;
  }
  function parenthesizeTypeOfOptionalType(type) {
    if (hasJSDocPostfixQuestion(type)) return factory2.createParenthesizedType(type);
    return parenthesizeNonArrayTypeOfPostfixType(type);
  }
  function parenthesizeLeadingTypeArgument(node) {
    return isFunctionOrConstructorTypeNode(node) && node.typeParameters ? factory2.createParenthesizedType(node) : node;
  }
  function parenthesizeOrdinalTypeArgument(node, i) {
    return i === 0 ? parenthesizeLeadingTypeArgument(node) : node;
  }
  function parenthesizeTypeArguments(typeArguments) {
    if (some(typeArguments)) {
      return factory2.createNodeArray(sameMap(typeArguments, parenthesizeOrdinalTypeArgument));
    }
  }
}
var nullParenthesizerRules = {
  getParenthesizeLeftSideOfBinaryForOperator: (_) => identity,
  getParenthesizeRightSideOfBinaryForOperator: (_) => identity,
  parenthesizeLeftSideOfBinary: (_binaryOperator, leftSide) => leftSide,
  parenthesizeRightSideOfBinary: (_binaryOperator, _leftSide, rightSide) => rightSide,
  parenthesizeExpressionOfComputedPropertyName: identity,
  parenthesizeConditionOfConditionalExpression: identity,
  parenthesizeBranchOfConditionalExpression: identity,
  parenthesizeExpressionOfExportDefault: identity,
  parenthesizeExpressionOfNew: (expression) => cast(expression, isLeftHandSideExpression),
  parenthesizeLeftSideOfAccess: (expression) => cast(expression, isLeftHandSideExpression),
  parenthesizeOperandOfPostfixUnary: (operand) => cast(operand, isLeftHandSideExpression),
  parenthesizeOperandOfPrefixUnary: (operand) => cast(operand, isUnaryExpression),
  parenthesizeExpressionsOfCommaDelimitedList: (nodes) => cast(nodes, isNodeArray),
  parenthesizeExpressionForDisallowedComma: identity,
  parenthesizeExpressionOfExpressionStatement: identity,
  parenthesizeConciseBodyOfArrowFunction: identity,
  parenthesizeCheckTypeOfConditionalType: identity,
  parenthesizeExtendsTypeOfConditionalType: identity,
  parenthesizeConstituentTypesOfUnionType: (nodes) => cast(nodes, isNodeArray),
  parenthesizeConstituentTypeOfUnionType: identity,
  parenthesizeConstituentTypesOfIntersectionType: (nodes) => cast(nodes, isNodeArray),
  parenthesizeConstituentTypeOfIntersectionType: identity,
  parenthesizeOperandOfTypeOperator: identity,
  parenthesizeOperandOfReadonlyTypeOperator: identity,
  parenthesizeNonArrayTypeOfPostfixType: identity,
  parenthesizeElementTypesOfTupleType: (nodes) => cast(nodes, isNodeArray),
  parenthesizeElementTypeOfTupleType: identity,
  parenthesizeTypeOfOptionalType: identity,
  parenthesizeTypeArguments: (nodes) => nodes && cast(nodes, isNodeArray),
  parenthesizeLeadingTypeArgument: identity
};

// src/compiler/factory/nodeConverters.ts
function createNodeConverters(factory2) {
  return {
    convertToFunctionBlock,
    convertToFunctionExpression,
    convertToClassExpression,
    convertToArrayAssignmentElement,
    convertToObjectAssignmentElement,
    convertToAssignmentPattern,
    convertToObjectAssignmentPattern,
    convertToArrayAssignmentPattern,
    convertToAssignmentElementTarget
  };
  function convertToFunctionBlock(node, multiLine) {
    if (isBlock(node)) return node;
    const returnStatement = factory2.createReturnStatement(node);
    setTextRange(returnStatement, node);
    const body = factory2.createBlock([returnStatement], multiLine);
    setTextRange(body, node);
    return body;
  }
  function convertToFunctionExpression(node) {
    var _a;
    if (!node.body) return Debug.fail(`Cannot convert a FunctionDeclaration without a body`);
    const updated = factory2.createFunctionExpression(
      (_a = getModifiers(node)) == null ? void 0 : _a.filter((modifier) => !isExportModifier(modifier) && !isDefaultModifier(modifier)),
      node.asteriskToken,
      node.name,
      node.typeParameters,
      node.parameters,
      node.type,
      node.body
    );
    setOriginalNode(updated, node);
    setTextRange(updated, node);
    if (getStartsOnNewLine(node)) {
      setStartsOnNewLine(
        updated,
        /*newLine*/
        true
      );
    }
    return updated;
  }
  function convertToClassExpression(node) {
    var _a;
    const updated = factory2.createClassExpression(
      (_a = node.modifiers) == null ? void 0 : _a.filter((modifier) => !isExportModifier(modifier) && !isDefaultModifier(modifier)),
      node.name,
      node.typeParameters,
      node.heritageClauses,
      node.members
    );
    setOriginalNode(updated, node);
    setTextRange(updated, node);
    if (getStartsOnNewLine(node)) {
      setStartsOnNewLine(
        updated,
        /*newLine*/
        true
      );
    }
    return updated;
  }
  function convertToArrayAssignmentElement(element) {
    if (isBindingElement(element)) {
      if (element.dotDotDotToken) {
        Debug.assertNode(element.name, isIdentifier);
        return setOriginalNode(setTextRange(factory2.createSpreadElement(element.name), element), element);
      }
      const expression = convertToAssignmentElementTarget(element.name);
      return element.initializer ? setOriginalNode(
        setTextRange(
          factory2.createAssignment(expression, element.initializer),
          element
        ),
        element
      ) : expression;
    }
    return cast(element, isExpression);
  }
  function convertToObjectAssignmentElement(element) {
    if (isBindingElement(element)) {
      if (element.dotDotDotToken) {
        Debug.assertNode(element.name, isIdentifier);
        return setOriginalNode(setTextRange(factory2.createSpreadAssignment(element.name), element), element);
      }
      if (element.propertyName) {
        const expression = convertToAssignmentElementTarget(element.name);
        return setOriginalNode(setTextRange(factory2.createPropertyAssignment(element.propertyName, element.initializer ? factory2.createAssignment(expression, element.initializer) : expression), element), element);
      }
      Debug.assertNode(element.name, isIdentifier);
      return setOriginalNode(setTextRange(factory2.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
    }
    return cast(element, isObjectLiteralElementLike);
  }
  function convertToAssignmentPattern(node) {
    switch (node.kind) {
      case 207 /* ArrayBindingPattern */:
      case 209 /* ArrayLiteralExpression */:
        return convertToArrayAssignmentPattern(node);
      case 206 /* ObjectBindingPattern */:
      case 210 /* ObjectLiteralExpression */:
        return convertToObjectAssignmentPattern(node);
    }
  }
  function convertToObjectAssignmentPattern(node) {
    if (isObjectBindingPattern(node)) {
      return setOriginalNode(
        setTextRange(
          factory2.createObjectLiteralExpression(map(node.elements, convertToObjectAssignmentElement)),
          node
        ),
        node
      );
    }
    return cast(node, isObjectLiteralExpression);
  }
  function convertToArrayAssignmentPattern(node) {
    if (isArrayBindingPattern(node)) {
      return setOriginalNode(
        setTextRange(
          factory2.createArrayLiteralExpression(map(node.elements, convertToArrayAssignmentElement)),
          node
        ),
        node
      );
    }
    return cast(node, isArrayLiteralExpression);
  }
  function convertToAssignmentElementTarget(node) {
    if (isBindingPattern(node)) {
      return convertToAssignmentPattern(node);
    }
    return cast(node, isExpression);
  }
}
var nullNodeConverters = {
  convertToFunctionBlock: notImplemented,
  convertToFunctionExpression: notImplemented,
  convertToClassExpression: notImplemented,
  convertToArrayAssignmentElement: notImplemented,
  convertToObjectAssignmentElement: notImplemented,
  convertToAssignmentPattern: notImplemented,
  convertToObjectAssignmentPattern: notImplemented,
  convertToArrayAssignmentPattern: notImplemented,
  convertToAssignmentElementTarget: notImplemented
};

// src/compiler/factory/nodeFactory.ts
var nextAutoGenerateId = 0;
var nodeFactoryPatchers = [];
function createNodeFactory(flags, baseFactory2) {
  const setOriginal = flags & 8 /* NoOriginalNode */ ? identity : setOriginalNode;
  const parenthesizerRules = memoize(() => flags & 1 /* NoParenthesizerRules */ ? nullParenthesizerRules : createParenthesizerRules(factory2));
  const converters = memoize(() => flags & 2 /* NoNodeConverters */ ? nullNodeConverters : createNodeConverters(factory2));
  const getBinaryCreateFunction = memoizeOne((operator) => (left, right) => createBinaryExpression(left, operator, right));
  const getPrefixUnaryCreateFunction = memoizeOne((operator) => (operand) => createPrefixUnaryExpression(operator, operand));
  const getPostfixUnaryCreateFunction = memoizeOne((operator) => (operand) => createPostfixUnaryExpression(operand, operator));
  const getJSDocPrimaryTypeCreateFunction = memoizeOne((kind) => () => createJSDocPrimaryTypeWorker(kind));
  const getJSDocUnaryTypeCreateFunction = memoizeOne((kind) => (type) => createJSDocUnaryTypeWorker(kind, type));
  const getJSDocUnaryTypeUpdateFunction = memoizeOne((kind) => (node, type) => updateJSDocUnaryTypeWorker(kind, node, type));
  const getJSDocPrePostfixUnaryTypeCreateFunction = memoizeOne((kind) => (type, postfix) => createJSDocPrePostfixUnaryTypeWorker(kind, type, postfix));
  const getJSDocPrePostfixUnaryTypeUpdateFunction = memoizeOne((kind) => (node, type) => updateJSDocPrePostfixUnaryTypeWorker(kind, node, type));
  const getJSDocSimpleTagCreateFunction = memoizeOne((kind) => (tagName, comment) => createJSDocSimpleTagWorker(kind, tagName, comment));
  const getJSDocSimpleTagUpdateFunction = memoizeOne((kind) => (node, tagName, comment) => updateJSDocSimpleTagWorker(kind, node, tagName, comment));
  const getJSDocTypeLikeTagCreateFunction = memoizeOne((kind) => (tagName, typeExpression, comment) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment));
  const getJSDocTypeLikeTagUpdateFunction = memoizeOne((kind) => (node, tagName, typeExpression, comment) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment));
  const factory2 = {
    get parenthesizer() {
      return parenthesizerRules();
    },
    get converters() {
      return converters();
    },
    baseFactory: baseFactory2,
    flags,
    createNodeArray,
    createNumericLiteral,
    createBigIntLiteral,
    createStringLiteral,
    createStringLiteralFromNode,
    createRegularExpressionLiteral,
    createLiteralLikeNode,
    createIdentifier,
    createTempVariable,
    createLoopVariable,
    createUniqueName,
    getGeneratedNameForNode,
    createPrivateIdentifier,
    createUniquePrivateName,
    getGeneratedPrivateNameForNode,
    createToken,
    createSuper,
    createThis,
    createNull,
    createTrue,
    createFalse,
    createModifier,
    createModifiersFromModifierFlags,
    createQualifiedName,
    updateQualifiedName,
    createComputedPropertyName,
    updateComputedPropertyName,
    createTypeParameterDeclaration,
    updateTypeParameterDeclaration,
    createParameterDeclaration,
    updateParameterDeclaration,
    createDecorator,
    updateDecorator,
    createPropertySignature,
    updatePropertySignature,
    createPropertyDeclaration,
    updatePropertyDeclaration,
    createMethodSignature,
    updateMethodSignature,
    createMethodDeclaration,
    updateMethodDeclaration,
    createConstructorDeclaration,
    updateConstructorDeclaration,
    createGetAccessorDeclaration,
    updateGetAccessorDeclaration,
    createSetAccessorDeclaration,
    updateSetAccessorDeclaration,
    createCallSignature,
    updateCallSignature,
    createConstructSignature,
    updateConstructSignature,
    createIndexSignature,
    updateIndexSignature,
    createClassStaticBlockDeclaration,
    updateClassStaticBlockDeclaration,
    createTemplateLiteralTypeSpan,
    updateTemplateLiteralTypeSpan,
    createKeywordTypeNode,
    createTypePredicateNode,
    updateTypePredicateNode,
    createTypeReferenceNode,
    updateTypeReferenceNode,
    createFunctionTypeNode,
    updateFunctionTypeNode,
    createConstructorTypeNode,
    updateConstructorTypeNode,
    createTypeQueryNode,
    updateTypeQueryNode,
    createTypeLiteralNode,
    updateTypeLiteralNode,
    createArrayTypeNode,
    updateArrayTypeNode,
    createTupleTypeNode,
    updateTupleTypeNode,
    createNamedTupleMember,
    updateNamedTupleMember,
    createOptionalTypeNode,
    updateOptionalTypeNode,
    createRestTypeNode,
    updateRestTypeNode,
    createUnionTypeNode,
    updateUnionTypeNode,
    createIntersectionTypeNode,
    updateIntersectionTypeNode,
    createConditionalTypeNode,
    updateConditionalTypeNode,
    createInferTypeNode,
    updateInferTypeNode,
    createImportTypeNode,
    updateImportTypeNode,
    createParenthesizedType,
    updateParenthesizedType,
    createThisTypeNode,
    createTypeOperatorNode,
    updateTypeOperatorNode,
    createIndexedAccessTypeNode,
    updateIndexedAccessTypeNode,
    createMappedTypeNode,
    updateMappedTypeNode,
    createLiteralTypeNode,
    updateLiteralTypeNode,
    createTemplateLiteralType,
    updateTemplateLiteralType,
    createObjectBindingPattern,
    updateObjectBindingPattern,
    createArrayBindingPattern,
    updateArrayBindingPattern,
    createBindingElement,
    updateBindingElement,
    createArrayLiteralExpression,
    updateArrayLiteralExpression,
    createObjectLiteralExpression,
    updateObjectLiteralExpression,
    createPropertyAccessExpression: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ? (expression, name) => setEmitFlags(createPropertyAccessExpression(expression, name), 262144 /* NoIndentation */) : createPropertyAccessExpression,
    updatePropertyAccessExpression,
    createPropertyAccessChain: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ? (expression, questionDotToken, name) => setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), 262144 /* NoIndentation */) : createPropertyAccessChain,
    updatePropertyAccessChain,
    createElementAccessExpression,
    updateElementAccessExpression,
    createElementAccessChain,
    updateElementAccessChain,
    createCallExpression,
    updateCallExpression,
    createCallChain,
    updateCallChain,
    createNewExpression,
    updateNewExpression,
    createTaggedTemplateExpression,
    updateTaggedTemplateExpression,
    createTypeAssertion,
    updateTypeAssertion,
    createParenthesizedExpression,
    updateParenthesizedExpression,
    createFunctionExpression,
    updateFunctionExpression,
    createArrowFunction,
    updateArrowFunction,
    createDeleteExpression,
    updateDeleteExpression,
    createTypeOfExpression,
    updateTypeOfExpression,
    createVoidExpression,
    updateVoidExpression,
    createAwaitExpression,
    updateAwaitExpression,
    createPrefixUnaryExpression,
    updatePrefixUnaryExpression,
    createPostfixUnaryExpression,
    updatePostfixUnaryExpression,
    createBinaryExpression,
    updateBinaryExpression,
    createConditionalExpression,
    updateConditionalExpression,
    createTemplateExpression,
    updateTemplateExpression,
    createTemplateHead,
    createTemplateMiddle,
    createTemplateTail,
    createNoSubstitutionTemplateLiteral,
    createTemplateLiteralLikeNode,
    createYieldExpression,
    updateYieldExpression,
    createSpreadElement,
    updateSpreadElement,
    createClassExpression,
    updateClassExpression,
    createOmittedExpression,
    createExpressionWithTypeArguments,
    updateExpressionWithTypeArguments,
    createAsExpression,
    updateAsExpression,
    createNonNullExpression,
    updateNonNullExpression,
    createSatisfiesExpression,
    updateSatisfiesExpression,
    createNonNullChain,
    updateNonNullChain,
    createMetaProperty,
    updateMetaProperty,
    createTemplateSpan,
    updateTemplateSpan,
    createSemicolonClassElement,
    createBlock,
    updateBlock,
    createVariableStatement,
    updateVariableStatement,
    createEmptyStatement,
    createExpressionStatement,
    updateExpressionStatement,
    createIfStatement,
    updateIfStatement,
    createDoStatement,
    updateDoStatement,
    createWhileStatement,
    updateWhileStatement,
    createForStatement,
    updateForStatement,
    createForInStatement,
    updateForInStatement,
    createForOfStatement,
    updateForOfStatement,
    createContinueStatement,
    updateContinueStatement,
    createBreakStatement,
    updateBreakStatement,
    createReturnStatement,
    updateReturnStatement,
    createWithStatement,
    updateWithStatement,
    createSwitchStatement,
    updateSwitchStatement,
    createLabeledStatement,
    updateLabeledStatement,
    createThrowStatement,
    updateThrowStatement,
    createTryStatement,
    updateTryStatement,
    createDebuggerStatement,
    createVariableDeclaration,
    updateVariableDeclaration,
    createVariableDeclarationList,
    updateVariableDeclarationList,
    createFunctionDeclaration,
    updateFunctionDeclaration,
    createClassDeclaration,
    updateClassDeclaration,
    createInterfaceDeclaration,
    updateInterfaceDeclaration,
    createTypeAliasDeclaration,
    updateTypeAliasDeclaration,
    createEnumDeclaration,
    updateEnumDeclaration,
    createModuleDeclaration,
    updateModuleDeclaration,
    createModuleBlock,
    updateModuleBlock,
    createCaseBlock,
    updateCaseBlock,
    createNamespaceExportDeclaration,
    updateNamespaceExportDeclaration,
    createImportEqualsDeclaration,
    updateImportEqualsDeclaration,
    createImportDeclaration,
    updateImportDeclaration,
    createImportClause,
    updateImportClause,
    createAssertClause,
    updateAssertClause,
    createAssertEntry,
    updateAssertEntry,
    createImportTypeAssertionContainer,
    updateImportTypeAssertionContainer,
    createImportAttributes,
    updateImportAttributes,
    createImportAttribute,
    updateImportAttribute,
    createNamespaceImport,
    updateNamespaceImport,
    createNamespaceExport,
    updateNamespaceExport,
    createNamedImports,
    updateNamedImports,
    createImportSpecifier,
    updateImportSpecifier,
    createExportAssignment,
    updateExportAssignment,
    createExportDeclaration,
    updateExportDeclaration,
    createNamedExports,
    updateNamedExports,
    createExportSpecifier,
    updateExportSpecifier,
    createMissingDeclaration,
    createExternalModuleReference,
    updateExternalModuleReference,
    // lazily load factory members for JSDoc types with similar structure
    get createJSDocAllType() {
      return getJSDocPrimaryTypeCreateFunction(312 /* JSDocAllType */);
    },
    get createJSDocUnknownType() {
      return getJSDocPrimaryTypeCreateFunction(313 /* JSDocUnknownType */);
    },
    get createJSDocNonNullableType() {
      return getJSDocPrePostfixUnaryTypeCreateFunction(315 /* JSDocNonNullableType */);
    },
    get updateJSDocNonNullableType() {
      return getJSDocPrePostfixUnaryTypeUpdateFunction(315 /* JSDocNonNullableType */);
    },
    get createJSDocNullableType() {
      return getJSDocPrePostfixUnaryTypeCreateFunction(314 /* JSDocNullableType */);
    },
    get updateJSDocNullableType() {
      return getJSDocPrePostfixUnaryTypeUpdateFunction(314 /* JSDocNullableType */);
    },
    get createJSDocOptionalType() {
      return getJSDocUnaryTypeCreateFunction(316 /* JSDocOptionalType */);
    },
    get updateJSDocOptionalType() {
      return getJSDocUnaryTypeUpdateFunction(316 /* JSDocOptionalType */);
    },
    get createJSDocVariadicType() {
      return getJSDocUnaryTypeCreateFunction(318 /* JSDocVariadicType */);
    },
    get updateJSDocVariadicType() {
      return getJSDocUnaryTypeUpdateFunction(318 /* JSDocVariadicType */);
    },
    get createJSDocNamepathType() {
      return getJSDocUnaryTypeCreateFunction(319 /* JSDocNamepathType */);
    },
    get updateJSDocNamepathType() {
      return getJSDocUnaryTypeUpdateFunction(319 /* JSDocNamepathType */);
    },
    createJSDocFunctionType,
    updateJSDocFunctionType,
    createJSDocTypeLiteral,
    updateJSDocTypeLiteral,
    createJSDocTypeExpression,
    updateJSDocTypeExpression,
    createJSDocSignature,
    updateJSDocSignature,
    createJSDocTemplateTag,
    updateJSDocTemplateTag,
    createJSDocTypedefTag,
    updateJSDocTypedefTag,
    createJSDocParameterTag,
    updateJSDocParameterTag,
    createJSDocPropertyTag,
    updateJSDocPropertyTag,
    createJSDocCallbackTag,
    updateJSDocCallbackTag,
    createJSDocOverloadTag,
    updateJSDocOverloadTag,
    createJSDocAugmentsTag,
    updateJSDocAugmentsTag,
    createJSDocImplementsTag,
    updateJSDocImplementsTag,
    createJSDocSeeTag,
    updateJSDocSeeTag,
    createJSDocImportTag,
    updateJSDocImportTag,
    createJSDocNameReference,
    updateJSDocNameReference,
    createJSDocMemberName,
    updateJSDocMemberName,
    createJSDocLink,
    updateJSDocLink,
    createJSDocLinkCode,
    updateJSDocLinkCode,
    createJSDocLinkPlain,
    updateJSDocLinkPlain,
    // lazily load factory members for JSDoc tags with similar structure
    get createJSDocTypeTag() {
      return getJSDocTypeLikeTagCreateFunction(344 /* JSDocTypeTag */);
    },
    get updateJSDocTypeTag() {
      return getJSDocTypeLikeTagUpdateFunction(344 /* JSDocTypeTag */);
    },
    get createJSDocReturnTag() {
      return getJSDocTypeLikeTagCreateFunction(342 /* JSDocReturnTag */);
    },
    get updateJSDocReturnTag() {
      return getJSDocTypeLikeTagUpdateFunction(342 /* JSDocReturnTag */);
    },
    get createJSDocThisTag() {
      return getJSDocTypeLikeTagCreateFunction(343 /* JSDocThisTag */);
    },
    get updateJSDocThisTag() {
      return getJSDocTypeLikeTagUpdateFunction(343 /* JSDocThisTag */);
    },
    get createJSDocAuthorTag() {
      return getJSDocSimpleTagCreateFunction(330 /* JSDocAuthorTag */);
    },
    get updateJSDocAuthorTag() {
      return getJSDocSimpleTagUpdateFunction(330 /* JSDocAuthorTag */);
    },
    get createJSDocClassTag() {
      return getJSDocSimpleTagCreateFunction(332 /* JSDocClassTag */);
    },
    get updateJSDocClassTag() {
      return getJSDocSimpleTagUpdateFunction(332 /* JSDocClassTag */);
    },
    get createJSDocPublicTag() {
      return getJSDocSimpleTagCreateFunction(333 /* JSDocPublicTag */);
    },
    get updateJSDocPublicTag() {
      return getJSDocSimpleTagUpdateFunction(333 /* JSDocPublicTag */);
    },
    get createJSDocPrivateTag() {
      return getJSDocSimpleTagCreateFunction(334 /* JSDocPrivateTag */);
    },
    get updateJSDocPrivateTag() {
      return getJSDocSimpleTagUpdateFunction(334 /* JSDocPrivateTag */);
    },
    get createJSDocProtectedTag() {
      return getJSDocSimpleTagCreateFunction(335 /* JSDocProtectedTag */);
    },
    get updateJSDocProtectedTag() {
      return getJSDocSimpleTagUpdateFunction(335 /* JSDocProtectedTag */);
    },
    get createJSDocReadonlyTag() {
      return getJSDocSimpleTagCreateFunction(336 /* JSDocReadonlyTag */);
    },
    get updateJSDocReadonlyTag() {
      return getJSDocSimpleTagUpdateFunction(336 /* JSDocReadonlyTag */);
    },
    get createJSDocOverrideTag() {
      return getJSDocSimpleTagCreateFunction(337 /* JSDocOverrideTag */);
    },
    get updateJSDocOverrideTag() {
      return getJSDocSimpleTagUpdateFunction(337 /* JSDocOverrideTag */);
    },
    get createJSDocDeprecatedTag() {
      return getJSDocSimpleTagCreateFunction(331 /* JSDocDeprecatedTag */);
    },
    get updateJSDocDeprecatedTag() {
      return getJSDocSimpleTagUpdateFunction(331 /* JSDocDeprecatedTag */);
    },
    get createJSDocThrowsTag() {
      return getJSDocTypeLikeTagCreateFunction(349 /* JSDocThrowsTag */);
    },
    get updateJSDocThrowsTag() {
      return getJSDocTypeLikeTagUpdateFunction(349 /* JSDocThrowsTag */);
    },
    get createJSDocSatisfiesTag() {
      return getJSDocTypeLikeTagCreateFunction(350 /* JSDocSatisfiesTag */);
    },
    get updateJSDocSatisfiesTag() {
      return getJSDocTypeLikeTagUpdateFunction(350 /* JSDocSatisfiesTag */);
    },
    createJSDocEnumTag,
    updateJSDocEnumTag,
    createJSDocUnknownTag,
    updateJSDocUnknownTag,
    createJSDocText,
    updateJSDocText,
    createJSDocComment,
    updateJSDocComment,
    createJsxElement,
    updateJsxElement,
    createJsxSelfClosingElement,
    updateJsxSelfClosingElement,
    createJsxOpeningElement,
    updateJsxOpeningElement,
    createJsxClosingElement,
    updateJsxClosingElement,
    createJsxFragment,
    createJsxText,
    updateJsxText,
    createJsxOpeningFragment,
    createJsxJsxClosingFragment,
    updateJsxFragment,
    createJsxAttribute,
    updateJsxAttribute,
    createJsxAttributes,
    updateJsxAttributes,
    createJsxSpreadAttribute,
    updateJsxSpreadAttribute,
    createJsxExpression,
    updateJsxExpression,
    createJsxNamespacedName,
    updateJsxNamespacedName,
    createCaseClause,
    updateCaseClause,
    createDefaultClause,
    updateDefaultClause,
    createHeritageClause,
    updateHeritageClause,
    createCatchClause,
    updateCatchClause,
    createPropertyAssignment,
    updatePropertyAssignment,
    createShorthandPropertyAssignment,
    updateShorthandPropertyAssignment,
    createSpreadAssignment,
    updateSpreadAssignment,
    createEnumMember,
    updateEnumMember,
    createSourceFile: createSourceFile2,
    updateSourceFile,
    createRedirectedSourceFile,
    createBundle,
    updateBundle,
    createSyntheticExpression,
    createSyntaxList,
    createNotEmittedStatement,
    createNotEmittedTypeElement,
    createPartiallyEmittedExpression,
    updatePartiallyEmittedExpression,
    createCommaListExpression,
    updateCommaListExpression,
    createSyntheticReferenceExpression,
    updateSyntheticReferenceExpression,
    cloneNode,
    // Lazily load factory methods for common operator factories and utilities
    get createComma() {
      return getBinaryCreateFunction(28 /* CommaToken */);
    },
    get createAssignment() {
      return getBinaryCreateFunction(64 /* EqualsToken */);
    },
    get createLogicalOr() {
      return getBinaryCreateFunction(57 /* BarBarToken */);
    },
    get createLogicalAnd() {
      return getBinaryCreateFunction(56 /* AmpersandAmpersandToken */);
    },
    get createBitwiseOr() {
      return getBinaryCreateFunction(52 /* BarToken */);
    },
    get createBitwiseXor() {
      return getBinaryCreateFunction(53 /* CaretToken */);
    },
    get createBitwiseAnd() {
      return getBinaryCreateFunction(51 /* AmpersandToken */);
    },
    get createStrictEquality() {
      return getBinaryCreateFunction(37 /* EqualsEqualsEqualsToken */);
    },
    get createStrictInequality() {
      return getBinaryCreateFunction(38 /* ExclamationEqualsEqualsToken */);
    },
    get createEquality() {
      return getBinaryCreateFunction(35 /* EqualsEqualsToken */);
    },
    get createInequality() {
      return getBinaryCreateFunction(36 /* ExclamationEqualsToken */);
    },
    get createLessThan() {
      return getBinaryCreateFunction(30 /* LessThanToken */);
    },
    get createLessThanEquals() {
      return getBinaryCreateFunction(33 /* LessThanEqualsToken */);
    },
    get createGreaterThan() {
      return getBinaryCreateFunction(32 /* GreaterThanToken */);
    },
    get createGreaterThanEquals() {
      return getBinaryCreateFunction(34 /* GreaterThanEqualsToken */);
    },
    get createLeftShift() {
      return getBinaryCreateFunction(48 /* LessThanLessThanToken */);
    },
    get createRightShift() {
      return getBinaryCreateFunction(49 /* GreaterThanGreaterThanToken */);
    },
    get createUnsignedRightShift() {
      return getBinaryCreateFunction(50 /* GreaterThanGreaterThanGreaterThanToken */);
    },
    get createAdd() {
      return getBinaryCreateFunction(40 /* PlusToken */);
    },
    get createSubtract() {
      return getBinaryCreateFunction(41 /* MinusToken */);
    },
    get createMultiply() {
      return getBinaryCreateFunction(42 /* AsteriskToken */);
    },
    get createDivide() {
      return getBinaryCreateFunction(44 /* SlashToken */);
    },
    get createModulo() {
      return getBinaryCreateFunction(45 /* PercentToken */);
    },
    get createExponent() {
      return getBinaryCreateFunction(43 /* AsteriskAsteriskToken */);
    },
    get createPrefixPlus() {
      return getPrefixUnaryCreateFunction(40 /* PlusToken */);
    },
    get createPrefixMinus() {
      return getPrefixUnaryCreateFunction(41 /* MinusToken */);
    },
    get createPrefixIncrement() {
      return getPrefixUnaryCreateFunction(46 /* PlusPlusToken */);
    },
    get createPrefixDecrement() {
      return getPrefixUnaryCreateFunction(47 /* MinusMinusToken */);
    },
    get createBitwiseNot() {
      return getPrefixUnaryCreateFunction(55 /* TildeToken */);
    },
    get createLogicalNot() {
      return getPrefixUnaryCreateFunction(54 /* ExclamationToken */);
    },
    get createPostfixIncrement() {
      return getPostfixUnaryCreateFunction(46 /* PlusPlusToken */);
    },
    get createPostfixDecrement() {
      return getPostfixUnaryCreateFunction(47 /* MinusMinusToken */);
    },
    // Compound nodes
    createImmediatelyInvokedFunctionExpression,
    createImmediatelyInvokedArrowFunction,
    createVoidZero,
    createExportDefault,
    createExternalModuleExport,
    createTypeCheck,
    createIsNotTypeCheck,
    createMethodCall,
    createGlobalMethodCall,
    createFunctionBindCall,
    createFunctionCallCall,
    createFunctionApplyCall,
    createArraySliceCall,
    createArrayConcatCall,
    createObjectDefinePropertyCall,
    createObjectGetOwnPropertyDescriptorCall,
    createReflectGetCall,
    createReflectSetCall,
    createPropertyDescriptor,
    createCallBinding,
    createAssignmentTargetWrapper,
    // Utilities
    inlineExpressions,
    getInternalName,
    getLocalName,
    getExportName,
    getDeclarationName,
    getNamespaceMemberName,
    getExternalModuleOrNamespaceExportName,
    restoreOuterExpressions,
    restoreEnclosingLabel,
    createUseStrictPrologue,
    copyPrologue,
    copyStandardPrologue,
    copyCustomPrologue,
    ensureUseStrict,
    liftToBlock,
    mergeLexicalEnvironment,
    replaceModifiers,
    replaceDecoratorsAndModifiers,
    replacePropertyName
  };
  forEach(nodeFactoryPatchers, (fn) => fn(factory2));
  return factory2;
  function createNodeArray(elements, hasTrailingComma) {
    if (elements === void 0 || elements === emptyArray) {
      elements = [];
    } else if (isNodeArray(elements)) {
      if (hasTrailingComma === void 0 || elements.hasTrailingComma === hasTrailingComma) {
        if (elements.transformFlags === void 0) {
          aggregateChildrenFlags(elements);
        }
        Debug.attachNodeArrayDebugInfo(elements);
        return elements;
      }
      const array2 = elements.slice();
      array2.pos = elements.pos;
      array2.end = elements.end;
      array2.hasTrailingComma = hasTrailingComma;
      array2.transformFlags = elements.transformFlags;
      Debug.attachNodeArrayDebugInfo(array2);
      return array2;
    }
    const length2 = elements.length;
    const array = length2 >= 1 && length2 <= 4 ? elements.slice() : elements;
    array.pos = -1;
    array.end = -1;
    array.hasTrailingComma = !!hasTrailingComma;
    array.transformFlags = 0 /* None */;
    aggregateChildrenFlags(array);
    Debug.attachNodeArrayDebugInfo(array);
    return array;
  }
  function createBaseNode(kind) {
    return baseFactory2.createBaseNode(kind);
  }
  function createBaseDeclaration(kind) {
    const node = createBaseNode(kind);
    node.symbol = void 0;
    node.localSymbol = void 0;
    return node;
  }
  function finishUpdateBaseSignatureDeclaration(updated, original) {
    if (updated !== original) {
      updated.typeArguments = original.typeArguments;
    }
    return update(updated, original);
  }
  function createNumericLiteral(value, numericLiteralFlags = 0 /* None */) {
    const text = typeof value === "number" ? value + "" : value;
    Debug.assert(text.charCodeAt(0) !== 45 /* minus */, "Negative numbers should be created in combination with createPrefixUnaryExpression");
    const node = createBaseDeclaration(9 /* NumericLiteral */);
    node.text = text;
    node.numericLiteralFlags = numericLiteralFlags;
    if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) node.transformFlags |= 1024 /* ContainsES2015 */;
    return node;
  }
  function createBigIntLiteral(value) {
    const node = createBaseToken(10 /* BigIntLiteral */);
    node.text = typeof value === "string" ? value : pseudoBigIntToString(value) + "n";
    node.transformFlags |= 32 /* ContainsES2020 */;
    return node;
  }
  function createBaseStringLiteral(text, isSingleQuote) {
    const node = createBaseDeclaration(11 /* StringLiteral */);
    node.text = text;
    node.singleQuote = isSingleQuote;
    return node;
  }
  function createStringLiteral(text, isSingleQuote, hasExtendedUnicodeEscape) {
    const node = createBaseStringLiteral(text, isSingleQuote);
    node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape;
    if (hasExtendedUnicodeEscape) node.transformFlags |= 1024 /* ContainsES2015 */;
    return node;
  }
  function createStringLiteralFromNode(sourceNode) {
    const node = createBaseStringLiteral(
      getTextOfIdentifierOrLiteral(sourceNode),
      /*isSingleQuote*/
      void 0
    );
    node.textSourceNode = sourceNode;
    return node;
  }
  function createRegularExpressionLiteral(text) {
    const node = createBaseToken(14 /* RegularExpressionLiteral */);
    node.text = text;
    return node;
  }
  function createLiteralLikeNode(kind, text) {
    switch (kind) {
      case 9 /* NumericLiteral */:
        return createNumericLiteral(
          text,
          /*numericLiteralFlags*/
          0
        );
      case 10 /* BigIntLiteral */:
        return createBigIntLiteral(text);
      case 11 /* StringLiteral */:
        return createStringLiteral(
          text,
          /*isSingleQuote*/
          void 0
        );
      case 12 /* JsxText */:
        return createJsxText(
          text,
          /*containsOnlyTriviaWhiteSpaces*/
          false
        );
      case 13 /* JsxTextAllWhiteSpaces */:
        return createJsxText(
          text,
          /*containsOnlyTriviaWhiteSpaces*/
          true
        );
      case 14 /* RegularExpressionLiteral */:
        return createRegularExpressionLiteral(text);
      case 15 /* NoSubstitutionTemplateLiteral */:
        return createTemplateLiteralLikeNode(
          kind,
          text,
          /*rawText*/
          void 0,
          /*templateFlags*/
          0
        );
    }
  }
  function createBaseIdentifier(escapedText) {
    const node = baseFactory2.createBaseIdentifierNode(80 /* Identifier */);
    node.escapedText = escapedText;
    node.jsDoc = void 0;
    node.flowNode = void 0;
    node.symbol = void 0;
    return node;
  }
  function createBaseGeneratedIdentifier(text, autoGenerateFlags, prefix, suffix) {
    const node = createBaseIdentifier(escapeLeadingUnderscores(text));
    setIdentifierAutoGenerate(node, {
      flags: autoGenerateFlags,
      id: nextAutoGenerateId,
      prefix,
      suffix
    });
    nextAutoGenerateId++;
    return node;
  }
  function createIdentifier(text, originalKeywordKind, hasExtendedUnicodeEscape) {
    if (originalKeywordKind === void 0 && text) {
      originalKeywordKind = stringToToken(text);
    }
    if (originalKeywordKind === 80 /* Identifier */) {
      originalKeywordKind = void 0;
    }
    const node = createBaseIdentifier(escapeLeadingUnderscores(text));
    if (hasExtendedUnicodeEscape) node.flags |= 256 /* IdentifierHasExtendedUnicodeEscape */;
    if (node.escapedText === "await") {
      node.transformFlags |= 67108864 /* ContainsPossibleTopLevelAwait */;
    }
    if (node.flags & 256 /* IdentifierHasExtendedUnicodeEscape */) {
      node.transformFlags |= 1024 /* ContainsES2015 */;
    }
    return node;
  }
  function createTempVariable(recordTempVariable, reservedInNestedScopes, prefix, suffix) {
    let flags2 = 1 /* Auto */;
    if (reservedInNestedScopes) flags2 |= 8 /* ReservedInNestedScopes */;
    const name = createBaseGeneratedIdentifier("", flags2, prefix, suffix);
    if (recordTempVariable) {
      recordTempVariable(name);
    }
    return name;
  }
  function createLoopVariable(reservedInNestedScopes) {
    let flags2 = 2 /* Loop */;
    if (reservedInNestedScopes) flags2 |= 8 /* ReservedInNestedScopes */;
    return createBaseGeneratedIdentifier(
      "",
      flags2,
      /*prefix*/
      void 0,
      /*suffix*/
      void 0
    );
  }
  function createUniqueName(text, flags2 = 0 /* None */, prefix, suffix) {
    Debug.assert(!(flags2 & 7 /* KindMask */), "Argument out of range: flags");
    Debug.assert((flags2 & (16 /* Optimistic */ | 32 /* FileLevel */)) !== 32 /* FileLevel */, "GeneratedIdentifierFlags.FileLevel cannot be set without also setting GeneratedIdentifierFlags.Optimistic");
    return createBaseGeneratedIdentifier(text, 3 /* Unique */ | flags2, prefix, suffix);
  }
  function getGeneratedNameForNode(node, flags2 = 0, prefix, suffix) {
    Debug.assert(!(flags2 & 7 /* KindMask */), "Argument out of range: flags");
    const text = !node ? "" : isMemberName(node) ? formatGeneratedName(
      /*privateName*/
      false,
      prefix,
      node,
      suffix,
      idText
    ) : `generated@${getNodeId(node)}`;
    if (prefix || suffix) flags2 |= 16 /* Optimistic */;
    const name = createBaseGeneratedIdentifier(text, 4 /* Node */ | flags2, prefix, suffix);
    name.original = node;
    return name;
  }
  function createBasePrivateIdentifier(escapedText) {
    const node = baseFactory2.createBasePrivateIdentifierNode(81 /* PrivateIdentifier */);
    node.escapedText = escapedText;
    node.transformFlags |= 16777216 /* ContainsClassFields */;
    return node;
  }
  function createPrivateIdentifier(text) {
    if (!startsWith(text, "#")) Debug.fail("First character of private identifier must be #: " + text);
    return createBasePrivateIdentifier(escapeLeadingUnderscores(text));
  }
  function createBaseGeneratedPrivateIdentifier(text, autoGenerateFlags, prefix, suffix) {
    const node = createBasePrivateIdentifier(escapeLeadingUnderscores(text));
    setIdentifierAutoGenerate(node, {
      flags: autoGenerateFlags,
      id: nextAutoGenerateId,
      prefix,
      suffix
    });
    nextAutoGenerateId++;
    return node;
  }
  function createUniquePrivateName(text, prefix, suffix) {
    if (text && !startsWith(text, "#")) Debug.fail("First character of private identifier must be #: " + text);
    const autoGenerateFlags = 8 /* ReservedInNestedScopes */ | (text ? 3 /* Unique */ : 1 /* Auto */);
    return createBaseGeneratedPrivateIdentifier(text ?? "", autoGenerateFlags, prefix, suffix);
  }
  function getGeneratedPrivateNameForNode(node, prefix, suffix) {
    const text = isMemberName(node) ? formatGeneratedName(
      /*privateName*/
      true,
      prefix,
      node,
      suffix,
      idText
    ) : `#generated@${getNodeId(node)}`;
    const flags2 = prefix || suffix ? 16 /* Optimistic */ : 0 /* None */;
    const name = createBaseGeneratedPrivateIdentifier(text, 4 /* Node */ | flags2, prefix, suffix);
    name.original = node;
    return name;
  }
  function createBaseToken(kind) {
    return baseFactory2.createBaseTokenNode(kind);
  }
  function createToken(token) {
    Debug.assert(token >= 0 /* FirstToken */ && token <= 165 /* LastToken */, "Invalid token");
    Debug.assert(token <= 15 /* FirstTemplateToken */ || token >= 18 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals.");
    Debug.assert(token <= 9 /* FirstLiteralToken */ || token >= 15 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals.");
    Debug.assert(token !== 80 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers");
    const node = createBaseToken(token);
    let transformFlags = 0 /* None */;
    switch (token) {
      case 134 /* AsyncKeyword */:
        transformFlags = 256 /* ContainsES2017 */ | 128 /* ContainsES2018 */;
        break;
      case 160 /* UsingKeyword */:
        transformFlags = 4 /* ContainsESNext */;
        break;
      case 125 /* PublicKeyword */:
      case 123 /* PrivateKeyword */:
      case 124 /* ProtectedKeyword */:
      case 148 /* ReadonlyKeyword */:
      case 128 /* AbstractKeyword */:
      case 138 /* DeclareKeyword */:
      case 87 /* ConstKeyword */:
      case 133 /* AnyKeyword */:
      case 150 /* NumberKeyword */:
      case 163 /* BigIntKeyword */:
      case 146 /* NeverKeyword */:
      case 151 /* ObjectKeyword */:
      case 103 /* InKeyword */:
      case 147 /* OutKeyword */:
      case 164 /* OverrideKeyword */:
      case 154 /* StringKeyword */:
      case 136 /* BooleanKeyword */:
      case 155 /* SymbolKeyword */:
      case 116 /* VoidKeyword */:
      case 159 /* UnknownKeyword */:
      case 157 /* UndefinedKeyword */:
        transformFlags = 1 /* ContainsTypeScript */;
        break;
      case 108 /* SuperKeyword */:
        transformFlags = 1024 /* ContainsES2015 */ | 134217728 /* ContainsLexicalSuper */;
        node.flowNode = void 0;
        break;
      case 126 /* StaticKeyword */:
        transformFlags = 1024 /* ContainsES2015 */;
        break;
      case 129 /* AccessorKeyword */:
        transformFlags = 16777216 /* ContainsClassFields */;
        break;
      case 110 /* ThisKeyword */:
        transformFlags = 16384 /* ContainsLexicalThis */;
        node.flowNode = void 0;
        break;
    }
    if (transformFlags) {
      node.transformFlags |= transformFlags;
    }
    return node;
  }
  function createSuper() {
    return createToken(108 /* SuperKeyword */);
  }
  function createThis() {
    return createToken(110 /* ThisKeyword */);
  }
  function createNull() {
    return createToken(106 /* NullKeyword */);
  }
  function createTrue() {
    return createToken(112 /* TrueKeyword */);
  }
  function createFalse() {
    return createToken(97 /* FalseKeyword */);
  }
  function createModifier(kind) {
    return createToken(kind);
  }
  function createModifiersFromModifierFlags(flags2) {
    const result = [];
    if (flags2 & 32 /* Export */) result.push(createModifier(95 /* ExportKeyword */));
    if (flags2 & 128 /* Ambient */) result.push(createModifier(138 /* DeclareKeyword */));
    if (flags2 & 2048 /* Default */) result.push(createModifier(90 /* DefaultKeyword */));
    if (flags2 & 4096 /* Const */) result.push(createModifier(87 /* ConstKeyword */));
    if (flags2 & 1 /* Public */) result.push(createModifier(125 /* PublicKeyword */));
    if (flags2 & 2 /* Private */) result.push(createModifier(123 /* PrivateKeyword */));
    if (flags2 & 4 /* Protected */) result.push(createModifier(124 /* ProtectedKeyword */));
    if (flags2 & 64 /* Abstract */) result.push(createModifier(128 /* AbstractKeyword */));
    if (flags2 & 256 /* Static */) result.push(createModifier(126 /* StaticKeyword */));
    if (flags2 & 16 /* Override */) result.push(createModifier(164 /* OverrideKeyword */));
    if (flags2 & 8 /* Readonly */) result.push(createModifier(148 /* ReadonlyKeyword */));
    if (flags2 & 512 /* Accessor */) result.push(createModifier(129 /* AccessorKeyword */));
    if (flags2 & 1024 /* Async */) result.push(createModifier(134 /* AsyncKeyword */));
    if (flags2 & 8192 /* In */) result.push(createModifier(103 /* InKeyword */));
    if (flags2 & 16384 /* Out */) result.push(createModifier(147 /* OutKeyword */));
    return result.length ? result : void 0;
  }
  function createQualifiedName(left, right) {
    const node = createBaseNode(166 /* QualifiedName */);
    node.left = left;
    node.right = asName(right);
    node.transformFlags |= propagateChildFlags(node.left) | propagateIdentifierNameFlags(node.right);
    node.flowNode = void 0;
    return node;
  }
  function updateQualifiedName(node, left, right) {
    return node.left !== left || node.right !== right ? update(createQualifiedName(left, right), node) : node;
  }
  function createComputedPropertyName(expression) {
    const node = createBaseNode(167 /* ComputedPropertyName */);
    node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression);
    node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* ContainsES2015 */ | 131072 /* ContainsComputedPropertyName */;
    return node;
  }
  function updateComputedPropertyName(node, expression) {
    return node.expression !== expression ? update(createComputedPropertyName(expression), node) : node;
  }
  function createTypeParameterDeclaration(modifiers, name, constraint, defaultType) {
    const node = createBaseDeclaration(168 /* TypeParameter */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.constraint = constraint;
    node.default = defaultType;
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.expression = void 0;
    node.jsDoc = void 0;
    return node;
  }
  function updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType) {
    return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint || node.default !== defaultType ? update(createTypeParameterDeclaration(modifiers, name, constraint, defaultType), node) : node;
  }
  function createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) {
    const node = createBaseDeclaration(169 /* Parameter */);
    node.modifiers = asNodeArray(modifiers);
    node.dotDotDotToken = dotDotDotToken;
    node.name = asName(name);
    node.questionToken = questionToken;
    node.type = type;
    node.initializer = asInitializer(initializer);
    if (isThisIdentifier(node.name)) {
      node.transformFlags = 1 /* ContainsTypeScript */;
    } else {
      node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.initializer) | (node.questionToken ?? node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (node.dotDotDotToken ?? node.initializer ? 1024 /* ContainsES2015 */ : 0 /* None */) | (modifiersToFlags(node.modifiers) & 31 /* ParameterPropertyModifier */ ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */);
    }
    node.jsDoc = void 0;
    return node;
  }
  function updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
    return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node;
  }
  function createDecorator(expression) {
    const node = createBaseNode(170 /* Decorator */);
    node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(
      expression,
      /*optionalChain*/
      false
    );
    node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */ | 8192 /* ContainsTypeScriptClassSyntax */ | 33554432 /* ContainsDecorators */;
    return node;
  }
  function updateDecorator(node, expression) {
    return node.expression !== expression ? update(createDecorator(expression), node) : node;
  }
  function createPropertySignature(modifiers, name, questionToken, type) {
    const node = createBaseDeclaration(171 /* PropertySignature */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.type = type;
    node.questionToken = questionToken;
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.initializer = void 0;
    node.jsDoc = void 0;
    return node;
  }
  function updatePropertySignature(node, modifiers, name, questionToken, type) {
    return node.modifiers !== modifiers || node.name !== name || node.questionToken !== questionToken || node.type !== type ? finishUpdatePropertySignature(createPropertySignature(modifiers, name, questionToken, type), node) : node;
  }
  function finishUpdatePropertySignature(updated, original) {
    if (updated !== original) {
      updated.initializer = original.initializer;
    }
    return update(updated, original);
  }
  function createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer) {
    const node = createBaseDeclaration(172 /* PropertyDeclaration */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.questionToken = questionOrExclamationToken && isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0;
    node.exclamationToken = questionOrExclamationToken && isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0;
    node.type = type;
    node.initializer = asInitializer(initializer);
    const isAmbient = node.flags & 33554432 /* Ambient */ || modifiersToFlags(node.modifiers) & 128 /* Ambient */;
    node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (isAmbient || node.questionToken || node.exclamationToken || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (isComputedPropertyName(node.name) || modifiersToFlags(node.modifiers) & 256 /* Static */ && node.initializer ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */) | 16777216 /* ContainsClassFields */;
    node.jsDoc = void 0;
    return node;
  }
  function updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer) {
    return node.modifiers !== modifiers || node.name !== name || node.questionToken !== (questionOrExclamationToken !== void 0 && isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0) || node.exclamationToken !== (questionOrExclamationToken !== void 0 && isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0) || node.type !== type || node.initializer !== initializer ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) : node;
  }
  function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) {
    const node = createBaseDeclaration(173 /* MethodSignature */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.questionToken = questionToken;
    node.typeParameters = asNodeArray(typeParameters);
    node.parameters = asNodeArray(parameters);
    node.type = type;
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.typeArguments = void 0;
    return node;
  }
  function updateMethodSignature(node, modifiers, name, questionToken, typeParameters, parameters, type) {
    return node.modifiers !== modifiers || node.name !== name || node.questionToken !== questionToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) : node;
  }
  function createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
    const node = createBaseDeclaration(174 /* MethodDeclaration */);
    node.modifiers = asNodeArray(modifiers);
    node.asteriskToken = asteriskToken;
    node.name = asName(name);
    node.questionToken = questionToken;
    node.exclamationToken = void 0;
    node.typeParameters = asNodeArray(typeParameters);
    node.parameters = createNodeArray(parameters);
    node.type = type;
    node.body = body;
    if (!node.body) {
      node.transformFlags = 1 /* ContainsTypeScript */;
    } else {
      const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */;
      const isGenerator = !!node.asteriskToken;
      const isAsyncGenerator = isAsync && isGenerator;
      node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (isAsyncGenerator ? 128 /* ContainsES2018 */ : isAsync ? 256 /* ContainsES2017 */ : isGenerator ? 2048 /* ContainsGenerator */ : 0 /* None */) | (node.questionToken || node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | 1024 /* ContainsES2015 */;
    }
    node.typeArguments = void 0;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.flowNode = void 0;
    node.endFlowNode = void 0;
    node.returnFlowNode = void 0;
    return node;
  }
  function updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
    return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.questionToken !== questionToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? finishUpdateMethodDeclaration(createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node;
  }
  function finishUpdateMethodDeclaration(updated, original) {
    if (updated !== original) {
      updated.exclamationToken = original.exclamationToken;
    }
    return update(updated, original);
  }
  function createClassStaticBlockDeclaration(body) {
    const node = createBaseDeclaration(175 /* ClassStaticBlockDeclaration */);
    node.body = body;
    node.transformFlags = propagateChildFlags(body) | 16777216 /* ContainsClassFields */;
    node.modifiers = void 0;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.endFlowNode = void 0;
    node.returnFlowNode = void 0;
    return node;
  }
  function updateClassStaticBlockDeclaration(node, body) {
    return node.body !== body ? finishUpdateClassStaticBlockDeclaration(createClassStaticBlockDeclaration(body), node) : node;
  }
  function finishUpdateClassStaticBlockDeclaration(updated, original) {
    if (updated !== original) {
      updated.modifiers = original.modifiers;
    }
    return update(updated, original);
  }
  function createConstructorDeclaration(modifiers, parameters, body) {
    const node = createBaseDeclaration(176 /* Constructor */);
    node.modifiers = asNodeArray(modifiers);
    node.parameters = createNodeArray(parameters);
    node.body = body;
    if (!node.body) {
      node.transformFlags = 1 /* ContainsTypeScript */;
    } else {
      node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | 1024 /* ContainsES2015 */;
    }
    node.typeParameters = void 0;
    node.type = void 0;
    node.typeArguments = void 0;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.endFlowNode = void 0;
    node.returnFlowNode = void 0;
    return node;
  }
  function updateConstructorDeclaration(node, modifiers, parameters, body) {
    return node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body ? finishUpdateConstructorDeclaration(createConstructorDeclaration(modifiers, parameters, body), node) : node;
  }
  function finishUpdateConstructorDeclaration(updated, original) {
    if (updated !== original) {
      updated.typeParameters = original.typeParameters;
      updated.type = original.type;
    }
    return finishUpdateBaseSignatureDeclaration(updated, original);
  }
  function createGetAccessorDeclaration(modifiers, name, parameters, type, body) {
    const node = createBaseDeclaration(177 /* GetAccessor */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.parameters = createNodeArray(parameters);
    node.type = type;
    node.body = body;
    if (!node.body) {
      node.transformFlags = 1 /* ContainsTypeScript */;
    } else {
      node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (node.type ? 1 /* ContainsTypeScript */ : 0 /* None */);
    }
    node.typeArguments = void 0;
    node.typeParameters = void 0;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.flowNode = void 0;
    node.endFlowNode = void 0;
    node.returnFlowNode = void 0;
    return node;
  }
  function updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body) {
    return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body ? finishUpdateGetAccessorDeclaration(createGetAccessorDeclaration(modifiers, name, parameters, type, body), node) : node;
  }
  function finishUpdateGetAccessorDeclaration(updated, original) {
    if (updated !== original) {
      updated.typeParameters = original.typeParameters;
    }
    return finishUpdateBaseSignatureDeclaration(updated, original);
  }
  function createSetAccessorDeclaration(modifiers, name, parameters, body) {
    const node = createBaseDeclaration(178 /* SetAccessor */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.parameters = createNodeArray(parameters);
    node.body = body;
    if (!node.body) {
      node.transformFlags = 1 /* ContainsTypeScript */;
    } else {
      node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (node.type ? 1 /* ContainsTypeScript */ : 0 /* None */);
    }
    node.typeArguments = void 0;
    node.typeParameters = void 0;
    node.type = void 0;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.flowNode = void 0;
    node.endFlowNode = void 0;
    node.returnFlowNode = void 0;
    return node;
  }
  function updateSetAccessorDeclaration(node, modifiers, name, parameters, body) {
    return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body ? finishUpdateSetAccessorDeclaration(createSetAccessorDeclaration(modifiers, name, parameters, body), node) : node;
  }
  function finishUpdateSetAccessorDeclaration(updated, original) {
    if (updated !== original) {
      updated.typeParameters = original.typeParameters;
      updated.type = original.type;
    }
    return finishUpdateBaseSignatureDeclaration(updated, original);
  }
  function createCallSignature(typeParameters, parameters, type) {
    const node = createBaseDeclaration(179 /* CallSignature */);
    node.typeParameters = asNodeArray(typeParameters);
    node.parameters = asNodeArray(parameters);
    node.type = type;
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.typeArguments = void 0;
    return node;
  }
  function updateCallSignature(node, typeParameters, parameters, type) {
    return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) : node;
  }
  function createConstructSignature(typeParameters, parameters, type) {
    const node = createBaseDeclaration(180 /* ConstructSignature */);
    node.typeParameters = asNodeArray(typeParameters);
    node.parameters = asNodeArray(parameters);
    node.type = type;
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.typeArguments = void 0;
    return node;
  }
  function updateConstructSignature(node, typeParameters, parameters, type) {
    return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) : node;
  }
  function createIndexSignature(modifiers, parameters, type) {
    const node = createBaseDeclaration(181 /* IndexSignature */);
    node.modifiers = asNodeArray(modifiers);
    node.parameters = asNodeArray(parameters);
    node.type = type;
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.typeArguments = void 0;
    return node;
  }
  function updateIndexSignature(node, modifiers, parameters, type) {
    return node.parameters !== parameters || node.type !== type || node.modifiers !== modifiers ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) : node;
  }
  function createTemplateLiteralTypeSpan(type, literal) {
    const node = createBaseNode(204 /* TemplateLiteralTypeSpan */);
    node.type = type;
    node.literal = literal;
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateTemplateLiteralTypeSpan(node, type, literal) {
    return node.type !== type || node.literal !== literal ? update(createTemplateLiteralTypeSpan(type, literal), node) : node;
  }
  function createKeywordTypeNode(kind) {
    return createToken(kind);
  }
  function createTypePredicateNode(assertsModifier, parameterName, type) {
    const node = createBaseNode(182 /* TypePredicate */);
    node.assertsModifier = assertsModifier;
    node.parameterName = asName(parameterName);
    node.type = type;
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateTypePredicateNode(node, assertsModifier, parameterName, type) {
    return node.assertsModifier !== assertsModifier || node.parameterName !== parameterName || node.type !== type ? update(createTypePredicateNode(assertsModifier, parameterName, type), node) : node;
  }
  function createTypeReferenceNode(typeName, typeArguments) {
    const node = createBaseNode(183 /* TypeReference */);
    node.typeName = asName(typeName);
    node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments));
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateTypeReferenceNode(node, typeName, typeArguments) {
    return node.typeName !== typeName || node.typeArguments !== typeArguments ? update(createTypeReferenceNode(typeName, typeArguments), node) : node;
  }
  function createFunctionTypeNode(typeParameters, parameters, type) {
    const node = createBaseDeclaration(184 /* FunctionType */);
    node.typeParameters = asNodeArray(typeParameters);
    node.parameters = asNodeArray(parameters);
    node.type = type;
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.modifiers = void 0;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.typeArguments = void 0;
    return node;
  }
  function updateFunctionTypeNode(node, typeParameters, parameters, type) {
    return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateFunctionTypeNode(createFunctionTypeNode(typeParameters, parameters, type), node) : node;
  }
  function finishUpdateFunctionTypeNode(updated, original) {
    if (updated !== original) {
      updated.modifiers = original.modifiers;
    }
    return finishUpdateBaseSignatureDeclaration(updated, original);
  }
  function createConstructorTypeNode(...args) {
    return args.length === 4 ? createConstructorTypeNode1(...args) : args.length === 3 ? createConstructorTypeNode2(...args) : Debug.fail("Incorrect number of arguments specified.");
  }
  function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) {
    const node = createBaseDeclaration(185 /* ConstructorType */);
    node.modifiers = asNodeArray(modifiers);
    node.typeParameters = asNodeArray(typeParameters);
    node.parameters = asNodeArray(parameters);
    node.type = type;
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.typeArguments = void 0;
    return node;
  }
  function createConstructorTypeNode2(typeParameters, parameters, type) {
    return createConstructorTypeNode1(
      /*modifiers*/
      void 0,
      typeParameters,
      parameters,
      type
    );
  }
  function updateConstructorTypeNode(...args) {
    return args.length === 5 ? updateConstructorTypeNode1(...args) : args.length === 4 ? updateConstructorTypeNode2(...args) : Debug.fail("Incorrect number of arguments specified.");
  }
  function updateConstructorTypeNode1(node, modifiers, typeParameters, parameters, type) {
    return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) : node;
  }
  function updateConstructorTypeNode2(node, typeParameters, parameters, type) {
    return updateConstructorTypeNode1(node, node.modifiers, typeParameters, parameters, type);
  }
  function createTypeQueryNode(exprName, typeArguments) {
    const node = createBaseNode(186 /* TypeQuery */);
    node.exprName = exprName;
    node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateTypeQueryNode(node, exprName, typeArguments) {
    return node.exprName !== exprName || node.typeArguments !== typeArguments ? update(createTypeQueryNode(exprName, typeArguments), node) : node;
  }
  function createTypeLiteralNode(members) {
    const node = createBaseDeclaration(187 /* TypeLiteral */);
    node.members = createNodeArray(members);
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateTypeLiteralNode(node, members) {
    return node.members !== members ? update(createTypeLiteralNode(members), node) : node;
  }
  function createArrayTypeNode(elementType) {
    const node = createBaseNode(188 /* ArrayType */);
    node.elementType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(elementType);
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateArrayTypeNode(node, elementType) {
    return node.elementType !== elementType ? update(createArrayTypeNode(elementType), node) : node;
  }
  function createTupleTypeNode(elements) {
    const node = createBaseNode(189 /* TupleType */);
    node.elements = createNodeArray(parenthesizerRules().parenthesizeElementTypesOfTupleType(elements));
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateTupleTypeNode(node, elements) {
    return node.elements !== elements ? update(createTupleTypeNode(elements), node) : node;
  }
  function createNamedTupleMember(dotDotDotToken, name, questionToken, type) {
    const node = createBaseDeclaration(202 /* NamedTupleMember */);
    node.dotDotDotToken = dotDotDotToken;
    node.name = name;
    node.questionToken = questionToken;
    node.type = type;
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.jsDoc = void 0;
    return node;
  }
  function updateNamedTupleMember(node, dotDotDotToken, name, questionToken, type) {
    return node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node) : node;
  }
  function createOptionalTypeNode(type) {
    const node = createBaseNode(190 /* OptionalType */);
    node.type = parenthesizerRules().parenthesizeTypeOfOptionalType(type);
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateOptionalTypeNode(node, type) {
    return node.type !== type ? update(createOptionalTypeNode(type), node) : node;
  }
  function createRestTypeNode(type) {
    const node = createBaseNode(191 /* RestType */);
    node.type = type;
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateRestTypeNode(node, type) {
    return node.type !== type ? update(createRestTypeNode(type), node) : node;
  }
  function createUnionOrIntersectionTypeNode(kind, types, parenthesize) {
    const node = createBaseNode(kind);
    node.types = factory2.createNodeArray(parenthesize(types));
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateUnionOrIntersectionTypeNode(node, types, parenthesize) {
    return node.types !== types ? update(createUnionOrIntersectionTypeNode(node.kind, types, parenthesize), node) : node;
  }
  function createUnionTypeNode(types) {
    return createUnionOrIntersectionTypeNode(192 /* UnionType */, types, parenthesizerRules().parenthesizeConstituentTypesOfUnionType);
  }
  function updateUnionTypeNode(node, types) {
    return updateUnionOrIntersectionTypeNode(node, types, parenthesizerRules().parenthesizeConstituentTypesOfUnionType);
  }
  function createIntersectionTypeNode(types) {
    return createUnionOrIntersectionTypeNode(193 /* IntersectionType */, types, parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType);
  }
  function updateIntersectionTypeNode(node, types) {
    return updateUnionOrIntersectionTypeNode(node, types, parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType);
  }
  function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
    const node = createBaseNode(194 /* ConditionalType */);
    node.checkType = parenthesizerRules().parenthesizeCheckTypeOfConditionalType(checkType);
    node.extendsType = parenthesizerRules().parenthesizeExtendsTypeOfConditionalType(extendsType);
    node.trueType = trueType;
    node.falseType = falseType;
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.locals = void 0;
    node.nextContainer = void 0;
    return node;
  }
  function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
    return node.checkType !== checkType || node.extendsType !== extendsType || node.trueType !== trueType || node.falseType !== falseType ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) : node;
  }
  function createInferTypeNode(typeParameter) {
    const node = createBaseNode(195 /* InferType */);
    node.typeParameter = typeParameter;
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateInferTypeNode(node, typeParameter) {
    return node.typeParameter !== typeParameter ? update(createInferTypeNode(typeParameter), node) : node;
  }
  function createTemplateLiteralType(head, templateSpans) {
    const node = createBaseNode(203 /* TemplateLiteralType */);
    node.head = head;
    node.templateSpans = createNodeArray(templateSpans);
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateTemplateLiteralType(node, head, templateSpans) {
    return node.head !== head || node.templateSpans !== templateSpans ? update(createTemplateLiteralType(head, templateSpans), node) : node;
  }
  function createImportTypeNode(argument, attributes, qualifier, typeArguments, isTypeOf = false) {
    const node = createBaseNode(205 /* ImportType */);
    node.argument = argument;
    node.attributes = attributes;
    if (node.assertions && node.assertions.assertClause && node.attributes) {
      node.assertions.assertClause = node.attributes;
    }
    node.qualifier = qualifier;
    node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
    node.isTypeOf = isTypeOf;
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateImportTypeNode(node, argument, attributes, qualifier, typeArguments, isTypeOf = node.isTypeOf) {
    return node.argument !== argument || node.attributes !== attributes || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf ? update(createImportTypeNode(argument, attributes, qualifier, typeArguments, isTypeOf), node) : node;
  }
  function createParenthesizedType(type) {
    const node = createBaseNode(196 /* ParenthesizedType */);
    node.type = type;
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateParenthesizedType(node, type) {
    return node.type !== type ? update(createParenthesizedType(type), node) : node;
  }
  function createThisTypeNode() {
    const node = createBaseNode(197 /* ThisType */);
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function createTypeOperatorNode(operator, type) {
    const node = createBaseNode(198 /* TypeOperator */);
    node.operator = operator;
    node.type = operator === 148 /* ReadonlyKeyword */ ? parenthesizerRules().parenthesizeOperandOfReadonlyTypeOperator(type) : parenthesizerRules().parenthesizeOperandOfTypeOperator(type);
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateTypeOperatorNode(node, type) {
    return node.type !== type ? update(createTypeOperatorNode(node.operator, type), node) : node;
  }
  function createIndexedAccessTypeNode(objectType, indexType) {
    const node = createBaseNode(199 /* IndexedAccessType */);
    node.objectType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(objectType);
    node.indexType = indexType;
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateIndexedAccessTypeNode(node, objectType, indexType) {
    return node.objectType !== objectType || node.indexType !== indexType ? update(createIndexedAccessTypeNode(objectType, indexType), node) : node;
  }
  function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) {
    const node = createBaseDeclaration(200 /* MappedType */);
    node.readonlyToken = readonlyToken;
    node.typeParameter = typeParameter;
    node.nameType = nameType;
    node.questionToken = questionToken;
    node.type = type;
    node.members = members && createNodeArray(members);
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.locals = void 0;
    node.nextContainer = void 0;
    return node;
  }
  function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type, members) {
    return node.readonlyToken !== readonlyToken || node.typeParameter !== typeParameter || node.nameType !== nameType || node.questionToken !== questionToken || node.type !== type || node.members !== members ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) : node;
  }
  function createLiteralTypeNode(literal) {
    const node = createBaseNode(201 /* LiteralType */);
    node.literal = literal;
    node.transformFlags = 1 /* ContainsTypeScript */;
    return node;
  }
  function updateLiteralTypeNode(node, literal) {
    return node.literal !== literal ? update(createLiteralTypeNode(literal), node) : node;
  }
  function createObjectBindingPattern(elements) {
    const node = createBaseNode(206 /* ObjectBindingPattern */);
    node.elements = createNodeArray(elements);
    node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* ContainsES2015 */ | 524288 /* ContainsBindingPattern */;
    if (node.transformFlags & 32768 /* ContainsRestOrSpread */) {
      node.transformFlags |= 128 /* ContainsES2018 */ | 65536 /* ContainsObjectRestOrSpread */;
    }
    return node;
  }
  function updateObjectBindingPattern(node, elements) {
    return node.elements !== elements ? update(createObjectBindingPattern(elements), node) : node;
  }
  function createArrayBindingPattern(elements) {
    const node = createBaseNode(207 /* ArrayBindingPattern */);
    node.elements = createNodeArray(elements);
    node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* ContainsES2015 */ | 524288 /* ContainsBindingPattern */;
    return node;
  }
  function updateArrayBindingPattern(node, elements) {
    return node.elements !== elements ? update(createArrayBindingPattern(elements), node) : node;
  }
  function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
    const node = createBaseDeclaration(208 /* BindingElement */);
    node.dotDotDotToken = dotDotDotToken;
    node.propertyName = asName(propertyName);
    node.name = asName(name);
    node.initializer = asInitializer(initializer);
    node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.propertyName) | propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (node.dotDotDotToken ? 32768 /* ContainsRestOrSpread */ : 0 /* None */) | 1024 /* ContainsES2015 */;
    node.flowNode = void 0;
    return node;
  }
  function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
    return node.propertyName !== propertyName || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.initializer !== initializer ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) : node;
  }
  function createArrayLiteralExpression(elements, multiLine) {
    const node = createBaseNode(209 /* ArrayLiteralExpression */);
    const lastElement = elements && lastOrUndefined(elements);
    const elementsArray = createNodeArray(elements, lastElement && isOmittedExpression(lastElement) ? true : void 0);
    node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(elementsArray);
    node.multiLine = multiLine;
    node.transformFlags |= propagateChildrenFlags(node.elements);
    return node;
  }
  function updateArrayLiteralExpression(node, elements) {
    return node.elements !== elements ? update(createArrayLiteralExpression(elements, node.multiLine), node) : node;
  }
  function createObjectLiteralExpression(properties, multiLine) {
    const node = createBaseDeclaration(210 /* ObjectLiteralExpression */);
    node.properties = createNodeArray(properties);
    node.multiLine = multiLine;
    node.transformFlags |= propagateChildrenFlags(node.properties);
    node.jsDoc = void 0;
    return node;
  }
  function updateObjectLiteralExpression(node, properties) {
    return node.properties !== properties ? update(createObjectLiteralExpression(properties, node.multiLine), node) : node;
  }
  function createBasePropertyAccessExpression(expression, questionDotToken, name) {
    const node = createBaseDeclaration(211 /* PropertyAccessExpression */);
    node.expression = expression;
    node.questionDotToken = questionDotToken;
    node.name = name;
    node.transformFlags = propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | (isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : propagateChildFlags(node.name) | 536870912 /* ContainsPrivateIdentifierInExpression */);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function createPropertyAccessExpression(expression, name) {
    const node = createBasePropertyAccessExpression(
      parenthesizerRules().parenthesizeLeftSideOfAccess(
        expression,
        /*optionalChain*/
        false
      ),
      /*questionDotToken*/
      void 0,
      asName(name)
    );
    if (isSuperKeyword(expression)) {
      node.transformFlags |= 256 /* ContainsES2017 */ | 128 /* ContainsES2018 */;
    }
    return node;
  }
  function updatePropertyAccessExpression(node, expression, name) {
    if (isPropertyAccessChain(node)) {
      return updatePropertyAccessChain(node, expression, node.questionDotToken, cast(name, isIdentifier));
    }
    return node.expression !== expression || node.name !== name ? update(createPropertyAccessExpression(expression, name), node) : node;
  }
  function createPropertyAccessChain(expression, questionDotToken, name) {
    const node = createBasePropertyAccessExpression(
      parenthesizerRules().parenthesizeLeftSideOfAccess(
        expression,
        /*optionalChain*/
        true
      ),
      questionDotToken,
      asName(name)
    );
    node.flags |= 64 /* OptionalChain */;
    node.transformFlags |= 32 /* ContainsES2020 */;
    return node;
  }
  function updatePropertyAccessChain(node, expression, questionDotToken, name) {
    Debug.assert(!!(node.flags & 64 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
    return node.expression !== expression || node.questionDotToken !== questionDotToken || node.name !== name ? update(createPropertyAccessChain(expression, questionDotToken, name), node) : node;
  }
  function createBaseElementAccessExpression(expression, questionDotToken, argumentExpression) {
    const node = createBaseDeclaration(212 /* ElementAccessExpression */);
    node.expression = expression;
    node.questionDotToken = questionDotToken;
    node.argumentExpression = argumentExpression;
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildFlags(node.argumentExpression);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function createElementAccessExpression(expression, index) {
    const node = createBaseElementAccessExpression(
      parenthesizerRules().parenthesizeLeftSideOfAccess(
        expression,
        /*optionalChain*/
        false
      ),
      /*questionDotToken*/
      void 0,
      asExpression(index)
    );
    if (isSuperKeyword(expression)) {
      node.transformFlags |= 256 /* ContainsES2017 */ | 128 /* ContainsES2018 */;
    }
    return node;
  }
  function updateElementAccessExpression(node, expression, argumentExpression) {
    if (isElementAccessChain(node)) {
      return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
    }
    return node.expression !== expression || node.argumentExpression !== argumentExpression ? update(createElementAccessExpression(expression, argumentExpression), node) : node;
  }
  function createElementAccessChain(expression, questionDotToken, index) {
    const node = createBaseElementAccessExpression(
      parenthesizerRules().parenthesizeLeftSideOfAccess(
        expression,
        /*optionalChain*/
        true
      ),
      questionDotToken,
      asExpression(index)
    );
    node.flags |= 64 /* OptionalChain */;
    node.transformFlags |= 32 /* ContainsES2020 */;
    return node;
  }
  function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
    Debug.assert(!!(node.flags & 64 /* OptionalChain */), "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
    return node.expression !== expression || node.questionDotToken !== questionDotToken || node.argumentExpression !== argumentExpression ? update(createElementAccessChain(expression, questionDotToken, argumentExpression), node) : node;
  }
  function createBaseCallExpression(expression, questionDotToken, typeArguments, argumentsArray) {
    const node = createBaseDeclaration(213 /* CallExpression */);
    node.expression = expression;
    node.questionDotToken = questionDotToken;
    node.typeArguments = typeArguments;
    node.arguments = argumentsArray;
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments);
    if (node.typeArguments) {
      node.transformFlags |= 1 /* ContainsTypeScript */;
    }
    if (isSuperProperty(node.expression)) {
      node.transformFlags |= 16384 /* ContainsLexicalThis */;
    }
    return node;
  }
  function createCallExpression(expression, typeArguments, argumentsArray) {
    const node = createBaseCallExpression(
      parenthesizerRules().parenthesizeLeftSideOfAccess(
        expression,
        /*optionalChain*/
        false
      ),
      /*questionDotToken*/
      void 0,
      asNodeArray(typeArguments),
      parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray))
    );
    if (isImportKeyword(node.expression)) {
      node.transformFlags |= 8388608 /* ContainsDynamicImport */;
    }
    return node;
  }
  function updateCallExpression(node, expression, typeArguments, argumentsArray) {
    if (isCallChain(node)) {
      return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
    }
    return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray ? update(createCallExpression(expression, typeArguments, argumentsArray), node) : node;
  }
  function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
    const node = createBaseCallExpression(
      parenthesizerRules().parenthesizeLeftSideOfAccess(
        expression,
        /*optionalChain*/
        true
      ),
      questionDotToken,
      asNodeArray(typeArguments),
      parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray))
    );
    node.flags |= 64 /* OptionalChain */;
    node.transformFlags |= 32 /* ContainsES2020 */;
    return node;
  }
  function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
    Debug.assert(!!(node.flags & 64 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
    return node.expression !== expression || node.questionDotToken !== questionDotToken || node.typeArguments !== typeArguments || node.arguments !== argumentsArray ? update(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node) : node;
  }
  function createNewExpression(expression, typeArguments, argumentsArray) {
    const node = createBaseDeclaration(214 /* NewExpression */);
    node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression);
    node.typeArguments = asNodeArray(typeArguments);
    node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : void 0;
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | 32 /* ContainsES2020 */;
    if (node.typeArguments) {
      node.transformFlags |= 1 /* ContainsTypeScript */;
    }
    return node;
  }
  function updateNewExpression(node, expression, typeArguments, argumentsArray) {
    return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray ? update(createNewExpression(expression, typeArguments, argumentsArray), node) : node;
  }
  function createTaggedTemplateExpression(tag, typeArguments, template) {
    const node = createBaseNode(215 /* TaggedTemplateExpression */);
    node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(
      tag,
      /*optionalChain*/
      false
    );
    node.typeArguments = asNodeArray(typeArguments);
    node.template = template;
    node.transformFlags |= propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | 1024 /* ContainsES2015 */;
    if (node.typeArguments) {
      node.transformFlags |= 1 /* ContainsTypeScript */;
    }
    if (hasInvalidEscape(node.template)) {
      node.transformFlags |= 128 /* ContainsES2018 */;
    }
    return node;
  }
  function updateTaggedTemplateExpression(node, tag, typeArguments, template) {
    return node.tag !== tag || node.typeArguments !== typeArguments || node.template !== template ? update(createTaggedTemplateExpression(tag, typeArguments, template), node) : node;
  }
  function createTypeAssertion(type, expression) {
    const node = createBaseNode(216 /* TypeAssertionExpression */);
    node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
    node.type = type;
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | 1 /* ContainsTypeScript */;
    return node;
  }
  function updateTypeAssertion(node, type, expression) {
    return node.type !== type || node.expression !== expression ? update(createTypeAssertion(type, expression), node) : node;
  }
  function createParenthesizedExpression(expression) {
    const node = createBaseNode(217 /* ParenthesizedExpression */);
    node.expression = expression;
    node.transformFlags = propagateChildFlags(node.expression);
    node.jsDoc = void 0;
    return node;
  }
  function updateParenthesizedExpression(node, expression) {
    return node.expression !== expression ? update(createParenthesizedExpression(expression), node) : node;
  }
  function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
    const node = createBaseDeclaration(218 /* FunctionExpression */);
    node.modifiers = asNodeArray(modifiers);
    node.asteriskToken = asteriskToken;
    node.name = asName(name);
    node.typeParameters = asNodeArray(typeParameters);
    node.parameters = createNodeArray(parameters);
    node.type = type;
    node.body = body;
    const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */;
    const isGenerator = !!node.asteriskToken;
    const isAsyncGenerator = isAsync && isGenerator;
    node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (isAsyncGenerator ? 128 /* ContainsES2018 */ : isAsync ? 256 /* ContainsES2017 */ : isGenerator ? 2048 /* ContainsGenerator */ : 0 /* None */) | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | 4194304 /* ContainsHoistedDeclarationOrCompletion */;
    node.typeArguments = void 0;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.flowNode = void 0;
    node.endFlowNode = void 0;
    node.returnFlowNode = void 0;
    return node;
  }
  function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
    return node.name !== name || node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node;
  }
  function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
    const node = createBaseDeclaration(219 /* ArrowFunction */);
    node.modifiers = asNodeArray(modifiers);
    node.typeParameters = asNodeArray(typeParameters);
    node.parameters = createNodeArray(parameters);
    node.type = type;
    node.equalsGreaterThanToken = equalsGreaterThanToken ?? createToken(39 /* EqualsGreaterThanToken */);
    node.body = parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body);
    const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */;
    node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.equalsGreaterThanToken) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (isAsync ? 256 /* ContainsES2017 */ | 16384 /* ContainsLexicalThis */ : 0 /* None */) | 1024 /* ContainsES2015 */;
    node.typeArguments = void 0;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.flowNode = void 0;
    node.endFlowNode = void 0;
    node.returnFlowNode = void 0;
    return node;
  }
  function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
    return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node;
  }
  function createDeleteExpression(expression) {
    const node = createBaseNode(220 /* DeleteExpression */);
    node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
    node.transformFlags |= propagateChildFlags(node.expression);
    return node;
  }
  function updateDeleteExpression(node, expression) {
    return node.expression !== expression ? update(createDeleteExpression(expression), node) : node;
  }
  function createTypeOfExpression(expression) {
    const node = createBaseNode(221 /* TypeOfExpression */);
    node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
    node.transformFlags |= propagateChildFlags(node.expression);
    return node;
  }
  function updateTypeOfExpression(node, expression) {
    return node.expression !== expression ? update(createTypeOfExpression(expression), node) : node;
  }
  function createVoidExpression(expression) {
    const node = createBaseNode(222 /* VoidExpression */);
    node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
    node.transformFlags |= propagateChildFlags(node.expression);
    return node;
  }
  function updateVoidExpression(node, expression) {
    return node.expression !== expression ? update(createVoidExpression(expression), node) : node;
  }
  function createAwaitExpression(expression) {
    const node = createBaseNode(223 /* AwaitExpression */);
    node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
    node.transformFlags |= propagateChildFlags(node.expression) | 256 /* ContainsES2017 */ | 128 /* ContainsES2018 */ | 2097152 /* ContainsAwait */;
    return node;
  }
  function updateAwaitExpression(node, expression) {
    return node.expression !== expression ? update(createAwaitExpression(expression), node) : node;
  }
  function createPrefixUnaryExpression(operator, operand) {
    const node = createBaseNode(224 /* PrefixUnaryExpression */);
    node.operator = operator;
    node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand);
    node.transformFlags |= propagateChildFlags(node.operand);
    if ((operator === 46 /* PlusPlusToken */ || operator === 47 /* MinusMinusToken */) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand)) {
      node.transformFlags |= 268435456 /* ContainsUpdateExpressionForIdentifier */;
    }
    return node;
  }
  function updatePrefixUnaryExpression(node, operand) {
    return node.operand !== operand ? update(createPrefixUnaryExpression(node.operator, operand), node) : node;
  }
  function createPostfixUnaryExpression(operand, operator) {
    const node = createBaseNode(225 /* PostfixUnaryExpression */);
    node.operator = operator;
    node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand);
    node.transformFlags |= propagateChildFlags(node.operand);
    if (isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand)) {
      node.transformFlags |= 268435456 /* ContainsUpdateExpressionForIdentifier */;
    }
    return node;
  }
  function updatePostfixUnaryExpression(node, operand) {
    return node.operand !== operand ? update(createPostfixUnaryExpression(operand, node.operator), node) : node;
  }
  function createBinaryExpression(left, operator, right) {
    const node = createBaseDeclaration(226 /* BinaryExpression */);
    const operatorToken = asToken(operator);
    const operatorKind = operatorToken.kind;
    node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left);
    node.operatorToken = operatorToken;
    node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right);
    node.transformFlags |= propagateChildFlags(node.left) | propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right);
    if (operatorKind === 61 /* QuestionQuestionToken */) {
      node.transformFlags |= 32 /* ContainsES2020 */;
    } else if (operatorKind === 64 /* EqualsToken */) {
      if (isObjectLiteralExpression(node.left)) {
        node.transformFlags |= 1024 /* ContainsES2015 */ | 128 /* ContainsES2018 */ | 4096 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left);
      } else if (isArrayLiteralExpression(node.left)) {
        node.transformFlags |= 1024 /* ContainsES2015 */ | 4096 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left);
      }
    } else if (operatorKind === 43 /* AsteriskAsteriskToken */ || operatorKind === 68 /* AsteriskAsteriskEqualsToken */) {
      node.transformFlags |= 512 /* ContainsES2016 */;
    } else if (isLogicalOrCoalescingAssignmentOperator(operatorKind)) {
      node.transformFlags |= 16 /* ContainsES2021 */;
    }
    if (operatorKind === 103 /* InKeyword */ && isPrivateIdentifier(node.left)) {
      node.transformFlags |= 536870912 /* ContainsPrivateIdentifierInExpression */;
    }
    node.jsDoc = void 0;
    return node;
  }
  function propagateAssignmentPatternFlags(node) {
    return containsObjectRestOrSpread(node) ? 65536 /* ContainsObjectRestOrSpread */ : 0 /* None */;
  }
  function updateBinaryExpression(node, left, operator, right) {
    return node.left !== left || node.operatorToken !== operator || node.right !== right ? update(createBinaryExpression(left, operator, right), node) : node;
  }
  function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) {
    const node = createBaseNode(227 /* ConditionalExpression */);
    node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition);
    node.questionToken = questionToken ?? createToken(58 /* QuestionToken */);
    node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue);
    node.colonToken = colonToken ?? createToken(59 /* ColonToken */);
    node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse);
    node.transformFlags |= propagateChildFlags(node.condition) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.whenTrue) | propagateChildFlags(node.colonToken) | propagateChildFlags(node.whenFalse);
    return node;
  }
  function updateConditionalExpression(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
    return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue || node.colonToken !== colonToken || node.whenFalse !== whenFalse ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node) : node;
  }
  function createTemplateExpression(head, templateSpans) {
    const node = createBaseNode(228 /* TemplateExpression */);
    node.head = head;
    node.templateSpans = createNodeArray(templateSpans);
    node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | 1024 /* ContainsES2015 */;
    return node;
  }
  function updateTemplateExpression(node, head, templateSpans) {
    return node.head !== head || node.templateSpans !== templateSpans ? update(createTemplateExpression(head, templateSpans), node) : node;
  }
  function checkTemplateLiteralLikeNode(kind, text, rawText, templateFlags = 0 /* None */) {
    Debug.assert(!(templateFlags & ~7176 /* TemplateLiteralLikeFlags */), "Unsupported template flags.");
    let cooked = void 0;
    if (rawText !== void 0 && rawText !== text) {
      cooked = getCookedText(kind, rawText);
      if (typeof cooked === "object") {
        return Debug.fail("Invalid raw text");
      }
    }
    if (text === void 0) {
      if (cooked === void 0) {
        return Debug.fail("Arguments 'text' and 'rawText' may not both be undefined.");
      }
      text = cooked;
    } else if (cooked !== void 0) {
      Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
    }
    return text;
  }
  function getTransformFlagsOfTemplateLiteralLike(templateFlags) {
    let transformFlags = 1024 /* ContainsES2015 */;
    if (templateFlags) {
      transformFlags |= 128 /* ContainsES2018 */;
    }
    return transformFlags;
  }
  function createTemplateLiteralLikeToken(kind, text, rawText, templateFlags) {
    const node = createBaseToken(kind);
    node.text = text;
    node.rawText = rawText;
    node.templateFlags = templateFlags & 7176 /* TemplateLiteralLikeFlags */;
    node.transformFlags = getTransformFlagsOfTemplateLiteralLike(node.templateFlags);
    return node;
  }
  function createTemplateLiteralLikeDeclaration(kind, text, rawText, templateFlags) {
    const node = createBaseDeclaration(kind);
    node.text = text;
    node.rawText = rawText;
    node.templateFlags = templateFlags & 7176 /* TemplateLiteralLikeFlags */;
    node.transformFlags = getTransformFlagsOfTemplateLiteralLike(node.templateFlags);
    return node;
  }
  function createTemplateLiteralLikeNode(kind, text, rawText, templateFlags) {
    if (kind === 15 /* NoSubstitutionTemplateLiteral */) {
      return createTemplateLiteralLikeDeclaration(kind, text, rawText, templateFlags);
    }
    return createTemplateLiteralLikeToken(kind, text, rawText, templateFlags);
  }
  function createTemplateHead(text, rawText, templateFlags) {
    text = checkTemplateLiteralLikeNode(16 /* TemplateHead */, text, rawText, templateFlags);
    return createTemplateLiteralLikeNode(16 /* TemplateHead */, text, rawText, templateFlags);
  }
  function createTemplateMiddle(text, rawText, templateFlags) {
    text = checkTemplateLiteralLikeNode(16 /* TemplateHead */, text, rawText, templateFlags);
    return createTemplateLiteralLikeNode(17 /* TemplateMiddle */, text, rawText, templateFlags);
  }
  function createTemplateTail(text, rawText, templateFlags) {
    text = checkTemplateLiteralLikeNode(16 /* TemplateHead */, text, rawText, templateFlags);
    return createTemplateLiteralLikeNode(18 /* TemplateTail */, text, rawText, templateFlags);
  }
  function createNoSubstitutionTemplateLiteral(text, rawText, templateFlags) {
    text = checkTemplateLiteralLikeNode(16 /* TemplateHead */, text, rawText, templateFlags);
    return createTemplateLiteralLikeDeclaration(15 /* NoSubstitutionTemplateLiteral */, text, rawText, templateFlags);
  }
  function createYieldExpression(asteriskToken, expression) {
    Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression.");
    const node = createBaseNode(229 /* YieldExpression */);
    node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
    node.asteriskToken = asteriskToken;
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | 1024 /* ContainsES2015 */ | 128 /* ContainsES2018 */ | 1048576 /* ContainsYield */;
    return node;
  }
  function updateYieldExpression(node, asteriskToken, expression) {
    return node.expression !== expression || node.asteriskToken !== asteriskToken ? update(createYieldExpression(asteriskToken, expression), node) : node;
  }
  function createSpreadElement(expression) {
    const node = createBaseNode(230 /* SpreadElement */);
    node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
    node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* ContainsES2015 */ | 32768 /* ContainsRestOrSpread */;
    return node;
  }
  function updateSpreadElement(node, expression) {
    return node.expression !== expression ? update(createSpreadElement(expression), node) : node;
  }
  function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
    const node = createBaseDeclaration(231 /* ClassExpression */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.typeParameters = asNodeArray(typeParameters);
    node.heritageClauses = asNodeArray(heritageClauses);
    node.members = createNodeArray(members);
    node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.heritageClauses) | propagateChildrenFlags(node.members) | (node.typeParameters ? 1 /* ContainsTypeScript */ : 0 /* None */) | 1024 /* ContainsES2015 */;
    node.jsDoc = void 0;
    return node;
  }
  function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
    return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node;
  }
  function createOmittedExpression() {
    return createBaseNode(232 /* OmittedExpression */);
  }
  function createExpressionWithTypeArguments(expression, typeArguments) {
    const node = createBaseNode(233 /* ExpressionWithTypeArguments */);
    node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(
      expression,
      /*optionalChain*/
      false
    );
    node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | 1024 /* ContainsES2015 */;
    return node;
  }
  function updateExpressionWithTypeArguments(node, expression, typeArguments) {
    return node.expression !== expression || node.typeArguments !== typeArguments ? update(createExpressionWithTypeArguments(expression, typeArguments), node) : node;
  }
  function createAsExpression(expression, type) {
    const node = createBaseNode(234 /* AsExpression */);
    node.expression = expression;
    node.type = type;
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | 1 /* ContainsTypeScript */;
    return node;
  }
  function updateAsExpression(node, expression, type) {
    return node.expression !== expression || node.type !== type ? update(createAsExpression(expression, type), node) : node;
  }
  function createNonNullExpression(expression) {
    const node = createBaseNode(235 /* NonNullExpression */);
    node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(
      expression,
      /*optionalChain*/
      false
    );
    node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */;
    return node;
  }
  function updateNonNullExpression(node, expression) {
    if (isNonNullChain(node)) {
      return updateNonNullChain(node, expression);
    }
    return node.expression !== expression ? update(createNonNullExpression(expression), node) : node;
  }
  function createSatisfiesExpression(expression, type) {
    const node = createBaseNode(238 /* SatisfiesExpression */);
    node.expression = expression;
    node.type = type;
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | 1 /* ContainsTypeScript */;
    return node;
  }
  function updateSatisfiesExpression(node, expression, type) {
    return node.expression !== expression || node.type !== type ? update(createSatisfiesExpression(expression, type), node) : node;
  }
  function createNonNullChain(expression) {
    const node = createBaseNode(235 /* NonNullExpression */);
    node.flags |= 64 /* OptionalChain */;
    node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(
      expression,
      /*optionalChain*/
      true
    );
    node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */;
    return node;
  }
  function updateNonNullChain(node, expression) {
    Debug.assert(!!(node.flags & 64 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
    return node.expression !== expression ? update(createNonNullChain(expression), node) : node;
  }
  function createMetaProperty(keywordToken, name) {
    const node = createBaseNode(236 /* MetaProperty */);
    node.keywordToken = keywordToken;
    node.name = name;
    node.transformFlags |= propagateChildFlags(node.name);
    switch (keywordToken) {
      case 105 /* NewKeyword */:
        node.transformFlags |= 1024 /* ContainsES2015 */;
        break;
      case 102 /* ImportKeyword */:
        node.transformFlags |= 32 /* ContainsES2020 */;
        break;
      default:
        return Debug.assertNever(keywordToken);
    }
    node.flowNode = void 0;
    return node;
  }
  function updateMetaProperty(node, name) {
    return node.name !== name ? update(createMetaProperty(node.keywordToken, name), node) : node;
  }
  function createTemplateSpan(expression, literal) {
    const node = createBaseNode(239 /* TemplateSpan */);
    node.expression = expression;
    node.literal = literal;
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | 1024 /* ContainsES2015 */;
    return node;
  }
  function updateTemplateSpan(node, expression, literal) {
    return node.expression !== expression || node.literal !== literal ? update(createTemplateSpan(expression, literal), node) : node;
  }
  function createSemicolonClassElement() {
    const node = createBaseNode(240 /* SemicolonClassElement */);
    node.transformFlags |= 1024 /* ContainsES2015 */;
    return node;
  }
  function createBlock(statements, multiLine) {
    const node = createBaseNode(241 /* Block */);
    node.statements = createNodeArray(statements);
    node.multiLine = multiLine;
    node.transformFlags |= propagateChildrenFlags(node.statements);
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    return node;
  }
  function updateBlock(node, statements) {
    return node.statements !== statements ? update(createBlock(statements, node.multiLine), node) : node;
  }
  function createVariableStatement(modifiers, declarationList) {
    const node = createBaseNode(243 /* VariableStatement */);
    node.modifiers = asNodeArray(modifiers);
    node.declarationList = isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
    node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.declarationList);
    if (modifiersToFlags(node.modifiers) & 128 /* Ambient */) {
      node.transformFlags = 1 /* ContainsTypeScript */;
    }
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateVariableStatement(node, modifiers, declarationList) {
    return node.modifiers !== modifiers || node.declarationList !== declarationList ? update(createVariableStatement(modifiers, declarationList), node) : node;
  }
  function createEmptyStatement() {
    const node = createBaseNode(242 /* EmptyStatement */);
    node.jsDoc = void 0;
    return node;
  }
  function createExpressionStatement(expression) {
    const node = createBaseNode(244 /* ExpressionStatement */);
    node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression);
    node.transformFlags |= propagateChildFlags(node.expression);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateExpressionStatement(node, expression) {
    return node.expression !== expression ? update(createExpressionStatement(expression), node) : node;
  }
  function createIfStatement(expression, thenStatement, elseStatement) {
    const node = createBaseNode(245 /* IfStatement */);
    node.expression = expression;
    node.thenStatement = asEmbeddedStatement(thenStatement);
    node.elseStatement = asEmbeddedStatement(elseStatement);
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thenStatement) | propagateChildFlags(node.elseStatement);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateIfStatement(node, expression, thenStatement, elseStatement) {
    return node.expression !== expression || node.thenStatement !== thenStatement || node.elseStatement !== elseStatement ? update(createIfStatement(expression, thenStatement, elseStatement), node) : node;
  }
  function createDoStatement(statement, expression) {
    const node = createBaseNode(246 /* DoStatement */);
    node.statement = asEmbeddedStatement(statement);
    node.expression = expression;
    node.transformFlags |= propagateChildFlags(node.statement) | propagateChildFlags(node.expression);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateDoStatement(node, statement, expression) {
    return node.statement !== statement || node.expression !== expression ? update(createDoStatement(statement, expression), node) : node;
  }
  function createWhileStatement(expression, statement) {
    const node = createBaseNode(247 /* WhileStatement */);
    node.expression = expression;
    node.statement = asEmbeddedStatement(statement);
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.statement);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateWhileStatement(node, expression, statement) {
    return node.expression !== expression || node.statement !== statement ? update(createWhileStatement(expression, statement), node) : node;
  }
  function createForStatement(initializer, condition, incrementor, statement) {
    const node = createBaseNode(248 /* ForStatement */);
    node.initializer = initializer;
    node.condition = condition;
    node.incrementor = incrementor;
    node.statement = asEmbeddedStatement(statement);
    node.transformFlags |= propagateChildFlags(node.initializer) | propagateChildFlags(node.condition) | propagateChildFlags(node.incrementor) | propagateChildFlags(node.statement);
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateForStatement(node, initializer, condition, incrementor, statement) {
    return node.initializer !== initializer || node.condition !== condition || node.incrementor !== incrementor || node.statement !== statement ? update(createForStatement(initializer, condition, incrementor, statement), node) : node;
  }
  function createForInStatement(initializer, expression, statement) {
    const node = createBaseNode(249 /* ForInStatement */);
    node.initializer = initializer;
    node.expression = expression;
    node.statement = asEmbeddedStatement(statement);
    node.transformFlags |= propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement);
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateForInStatement(node, initializer, expression, statement) {
    return node.initializer !== initializer || node.expression !== expression || node.statement !== statement ? update(createForInStatement(initializer, expression, statement), node) : node;
  }
  function createForOfStatement(awaitModifier, initializer, expression, statement) {
    const node = createBaseNode(250 /* ForOfStatement */);
    node.awaitModifier = awaitModifier;
    node.initializer = initializer;
    node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
    node.statement = asEmbeddedStatement(statement);
    node.transformFlags |= propagateChildFlags(node.awaitModifier) | propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | 1024 /* ContainsES2015 */;
    if (awaitModifier) node.transformFlags |= 128 /* ContainsES2018 */;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateForOfStatement(node, awaitModifier, initializer, expression, statement) {
    return node.awaitModifier !== awaitModifier || node.initializer !== initializer || node.expression !== expression || node.statement !== statement ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node) : node;
  }
  function createContinueStatement(label) {
    const node = createBaseNode(251 /* ContinueStatement */);
    node.label = asName(label);
    node.transformFlags |= propagateChildFlags(node.label) | 4194304 /* ContainsHoistedDeclarationOrCompletion */;
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateContinueStatement(node, label) {
    return node.label !== label ? update(createContinueStatement(label), node) : node;
  }
  function createBreakStatement(label) {
    const node = createBaseNode(252 /* BreakStatement */);
    node.label = asName(label);
    node.transformFlags |= propagateChildFlags(node.label) | 4194304 /* ContainsHoistedDeclarationOrCompletion */;
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateBreakStatement(node, label) {
    return node.label !== label ? update(createBreakStatement(label), node) : node;
  }
  function createReturnStatement(expression) {
    const node = createBaseNode(253 /* ReturnStatement */);
    node.expression = expression;
    node.transformFlags |= propagateChildFlags(node.expression) | 128 /* ContainsES2018 */ | 4194304 /* ContainsHoistedDeclarationOrCompletion */;
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateReturnStatement(node, expression) {
    return node.expression !== expression ? update(createReturnStatement(expression), node) : node;
  }
  function createWithStatement(expression, statement) {
    const node = createBaseNode(254 /* WithStatement */);
    node.expression = expression;
    node.statement = asEmbeddedStatement(statement);
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.statement);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateWithStatement(node, expression, statement) {
    return node.expression !== expression || node.statement !== statement ? update(createWithStatement(expression, statement), node) : node;
  }
  function createSwitchStatement(expression, caseBlock) {
    const node = createBaseNode(255 /* SwitchStatement */);
    node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
    node.caseBlock = caseBlock;
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.caseBlock);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    node.possiblyExhaustive = false;
    return node;
  }
  function updateSwitchStatement(node, expression, caseBlock) {
    return node.expression !== expression || node.caseBlock !== caseBlock ? update(createSwitchStatement(expression, caseBlock), node) : node;
  }
  function createLabeledStatement(label, statement) {
    const node = createBaseNode(256 /* LabeledStatement */);
    node.label = asName(label);
    node.statement = asEmbeddedStatement(statement);
    node.transformFlags |= propagateChildFlags(node.label) | propagateChildFlags(node.statement);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateLabeledStatement(node, label, statement) {
    return node.label !== label || node.statement !== statement ? update(createLabeledStatement(label, statement), node) : node;
  }
  function createThrowStatement(expression) {
    const node = createBaseNode(257 /* ThrowStatement */);
    node.expression = expression;
    node.transformFlags |= propagateChildFlags(node.expression);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateThrowStatement(node, expression) {
    return node.expression !== expression ? update(createThrowStatement(expression), node) : node;
  }
  function createTryStatement(tryBlock, catchClause, finallyBlock) {
    const node = createBaseNode(258 /* TryStatement */);
    node.tryBlock = tryBlock;
    node.catchClause = catchClause;
    node.finallyBlock = finallyBlock;
    node.transformFlags |= propagateChildFlags(node.tryBlock) | propagateChildFlags(node.catchClause) | propagateChildFlags(node.finallyBlock);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function updateTryStatement(node, tryBlock, catchClause, finallyBlock) {
    return node.tryBlock !== tryBlock || node.catchClause !== catchClause || node.finallyBlock !== finallyBlock ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node) : node;
  }
  function createDebuggerStatement() {
    const node = createBaseNode(259 /* DebuggerStatement */);
    node.jsDoc = void 0;
    node.flowNode = void 0;
    return node;
  }
  function createVariableDeclaration(name, exclamationToken, type, initializer) {
    const node = createBaseDeclaration(260 /* VariableDeclaration */);
    node.name = asName(name);
    node.exclamationToken = exclamationToken;
    node.type = type;
    node.initializer = asInitializer(initializer);
    node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (node.exclamationToken ?? node.type ? 1 /* ContainsTypeScript */ : 0 /* None */);
    node.jsDoc = void 0;
    return node;
  }
  function updateVariableDeclaration(node, name, exclamationToken, type, initializer) {
    return node.name !== name || node.type !== type || node.exclamationToken !== exclamationToken || node.initializer !== initializer ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node) : node;
  }
  function createVariableDeclarationList(declarations, flags2 = 0 /* None */) {
    const node = createBaseNode(261 /* VariableDeclarationList */);
    node.flags |= flags2 & 7 /* BlockScoped */;
    node.declarations = createNodeArray(declarations);
    node.transformFlags |= propagateChildrenFlags(node.declarations) | 4194304 /* ContainsHoistedDeclarationOrCompletion */;
    if (flags2 & 7 /* BlockScoped */) {
      node.transformFlags |= 1024 /* ContainsES2015 */ | 262144 /* ContainsBlockScopedBinding */;
    }
    if (flags2 & 4 /* Using */) {
      node.transformFlags |= 4 /* ContainsESNext */;
    }
    return node;
  }
  function updateVariableDeclarationList(node, declarations) {
    return node.declarations !== declarations ? update(createVariableDeclarationList(declarations, node.flags), node) : node;
  }
  function createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
    const node = createBaseDeclaration(262 /* FunctionDeclaration */);
    node.modifiers = asNodeArray(modifiers);
    node.asteriskToken = asteriskToken;
    node.name = asName(name);
    node.typeParameters = asNodeArray(typeParameters);
    node.parameters = createNodeArray(parameters);
    node.type = type;
    node.body = body;
    if (!node.body || modifiersToFlags(node.modifiers) & 128 /* Ambient */) {
      node.transformFlags = 1 /* ContainsTypeScript */;
    } else {
      const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */;
      const isGenerator = !!node.asteriskToken;
      const isAsyncGenerator = isAsync && isGenerator;
      node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (isAsyncGenerator ? 128 /* ContainsES2018 */ : isAsync ? 256 /* ContainsES2017 */ : isGenerator ? 2048 /* ContainsGenerator */ : 0 /* None */) | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | 4194304 /* ContainsHoistedDeclarationOrCompletion */;
    }
    node.typeArguments = void 0;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.endFlowNode = void 0;
    node.returnFlowNode = void 0;
    return node;
  }
  function updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
    return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? finishUpdateFunctionDeclaration(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node;
  }
  function finishUpdateFunctionDeclaration(updated, original) {
    if (updated !== original) {
      if (updated.modifiers === original.modifiers) {
        updated.modifiers = original.modifiers;
      }
    }
    return finishUpdateBaseSignatureDeclaration(updated, original);
  }
  function createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) {
    const node = createBaseDeclaration(263 /* ClassDeclaration */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.typeParameters = asNodeArray(typeParameters);
    node.heritageClauses = asNodeArray(heritageClauses);
    node.members = createNodeArray(members);
    if (modifiersToFlags(node.modifiers) & 128 /* Ambient */) {
      node.transformFlags = 1 /* ContainsTypeScript */;
    } else {
      node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.heritageClauses) | propagateChildrenFlags(node.members) | (node.typeParameters ? 1 /* ContainsTypeScript */ : 0 /* None */) | 1024 /* ContainsES2015 */;
      if (node.transformFlags & 8192 /* ContainsTypeScriptClassSyntax */) {
        node.transformFlags |= 1 /* ContainsTypeScript */;
      }
    }
    node.jsDoc = void 0;
    return node;
  }
  function updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) {
    return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node;
  }
  function createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) {
    const node = createBaseDeclaration(264 /* InterfaceDeclaration */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.typeParameters = asNodeArray(typeParameters);
    node.heritageClauses = asNodeArray(heritageClauses);
    node.members = createNodeArray(members);
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.jsDoc = void 0;
    return node;
  }
  function updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) {
    return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node;
  }
  function createTypeAliasDeclaration(modifiers, name, typeParameters, type) {
    const node = createBaseDeclaration(265 /* TypeAliasDeclaration */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.typeParameters = asNodeArray(typeParameters);
    node.type = type;
    node.transformFlags = 1 /* ContainsTypeScript */;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    return node;
  }
  function updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type) {
    return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type ? update(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node;
  }
  function createEnumDeclaration(modifiers, name, members) {
    const node = createBaseDeclaration(266 /* EnumDeclaration */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.members = createNodeArray(members);
    node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.name) | propagateChildrenFlags(node.members) | 1 /* ContainsTypeScript */;
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    node.jsDoc = void 0;
    return node;
  }
  function updateEnumDeclaration(node, modifiers, name, members) {
    return node.modifiers !== modifiers || node.name !== name || node.members !== members ? update(createEnumDeclaration(modifiers, name, members), node) : node;
  }
  function createModuleDeclaration(modifiers, name, body, flags2 = 0 /* None */) {
    const node = createBaseDeclaration(267 /* ModuleDeclaration */);
    node.modifiers = asNodeArray(modifiers);
    node.flags |= flags2 & (32 /* Namespace */ | 8 /* NestedNamespace */ | 2048 /* GlobalAugmentation */);
    node.name = name;
    node.body = body;
    if (modifiersToFlags(node.modifiers) & 128 /* Ambient */) {
      node.transformFlags = 1 /* ContainsTypeScript */;
    } else {
      node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.name) | propagateChildFlags(node.body) | 1 /* ContainsTypeScript */;
    }
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    return node;
  }
  function updateModuleDeclaration(node, modifiers, name, body) {
    return node.modifiers !== modifiers || node.name !== name || node.body !== body ? update(createModuleDeclaration(modifiers, name, body, node.flags), node) : node;
  }
  function createModuleBlock(statements) {
    const node = createBaseNode(268 /* ModuleBlock */);
    node.statements = createNodeArray(statements);
    node.transformFlags |= propagateChildrenFlags(node.statements);
    node.jsDoc = void 0;
    return node;
  }
  function updateModuleBlock(node, statements) {
    return node.statements !== statements ? update(createModuleBlock(statements), node) : node;
  }
  function createCaseBlock(clauses) {
    const node = createBaseNode(269 /* CaseBlock */);
    node.clauses = createNodeArray(clauses);
    node.transformFlags |= propagateChildrenFlags(node.clauses);
    node.locals = void 0;
    node.nextContainer = void 0;
    return node;
  }
  function updateCaseBlock(node, clauses) {
    return node.clauses !== clauses ? update(createCaseBlock(clauses), node) : node;
  }
  function createNamespaceExportDeclaration(name) {
    const node = createBaseDeclaration(270 /* NamespaceExportDeclaration */);
    node.name = asName(name);
    node.transformFlags |= propagateIdentifierNameFlags(node.name) | 1 /* ContainsTypeScript */;
    node.modifiers = void 0;
    node.jsDoc = void 0;
    return node;
  }
  function updateNamespaceExportDeclaration(node, name) {
    return node.name !== name ? finishUpdateNamespaceExportDeclaration(createNamespaceExportDeclaration(name), node) : node;
  }
  function finishUpdateNamespaceExportDeclaration(updated, original) {
    if (updated !== original) {
      updated.modifiers = original.modifiers;
    }
    return update(updated, original);
  }
  function createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference) {
    const node = createBaseDeclaration(271 /* ImportEqualsDeclaration */);
    node.modifiers = asNodeArray(modifiers);
    node.name = asName(name);
    node.isTypeOnly = isTypeOnly;
    node.moduleReference = moduleReference;
    node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateIdentifierNameFlags(node.name) | propagateChildFlags(node.moduleReference);
    if (!isExternalModuleReference(node.moduleReference)) {
      node.transformFlags |= 1 /* ContainsTypeScript */;
    }
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    node.jsDoc = void 0;
    return node;
  }
  function updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference) {
    return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.name !== name || node.moduleReference !== moduleReference ? update(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node;
  }
  function createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes) {
    const node = createBaseNode(272 /* ImportDeclaration */);
    node.modifiers = asNodeArray(modifiers);
    node.importClause = importClause;
    node.moduleSpecifier = moduleSpecifier;
    node.attributes = node.assertClause = attributes;
    node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier);
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    node.jsDoc = void 0;
    return node;
  }
  function updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, attributes) {
    return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? update(createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes), node) : node;
  }
  function createImportClause(isTypeOnly, name, namedBindings) {
    const node = createBaseDeclaration(273 /* ImportClause */);
    node.isTypeOnly = isTypeOnly;
    node.name = name;
    node.namedBindings = namedBindings;
    node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.namedBindings);
    if (isTypeOnly) {
      node.transformFlags |= 1 /* ContainsTypeScript */;
    }
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    return node;
  }
  function updateImportClause(node, isTypeOnly, name, namedBindings) {
    return node.isTypeOnly !== isTypeOnly || node.name !== name || node.namedBindings !== namedBindings ? update(createImportClause(isTypeOnly, name, namedBindings), node) : node;
  }
  function createAssertClause(elements, multiLine) {
    const node = createBaseNode(300 /* AssertClause */);
    node.elements = createNodeArray(elements);
    node.multiLine = multiLine;
    node.token = 132 /* AssertKeyword */;
    node.transformFlags |= 4 /* ContainsESNext */;
    return node;
  }
  function updateAssertClause(node, elements, multiLine) {
    return node.elements !== elements || node.multiLine !== multiLine ? update(createAssertClause(elements, multiLine), node) : node;
  }
  function createAssertEntry(name, value) {
    const node = createBaseNode(301 /* AssertEntry */);
    node.name = name;
    node.value = value;
    node.transformFlags |= 4 /* ContainsESNext */;
    return node;
  }
  function updateAssertEntry(node, name, value) {
    return node.name !== name || node.value !== value ? update(createAssertEntry(name, value), node) : node;
  }
  function createImportTypeAssertionContainer(clause, multiLine) {
    const node = createBaseNode(302 /* ImportTypeAssertionContainer */);
    node.assertClause = clause;
    node.multiLine = multiLine;
    return node;
  }
  function updateImportTypeAssertionContainer(node, clause, multiLine) {
    return node.assertClause !== clause || node.multiLine !== multiLine ? update(createImportTypeAssertionContainer(clause, multiLine), node) : node;
  }
  function createImportAttributes(elements, multiLine, token) {
    const node = createBaseNode(300 /* ImportAttributes */);
    node.token = token ?? 118 /* WithKeyword */;
    node.elements = createNodeArray(elements);
    node.multiLine = multiLine;
    node.transformFlags |= 4 /* ContainsESNext */;
    return node;
  }
  function updateImportAttributes(node, elements, multiLine) {
    return node.elements !== elements || node.multiLine !== multiLine ? update(createImportAttributes(elements, multiLine, node.token), node) : node;
  }
  function createImportAttribute(name, value) {
    const node = createBaseNode(301 /* ImportAttribute */);
    node.name = name;
    node.value = value;
    node.transformFlags |= 4 /* ContainsESNext */;
    return node;
  }
  function updateImportAttribute(node, name, value) {
    return node.name !== name || node.value !== value ? update(createImportAttribute(name, value), node) : node;
  }
  function createNamespaceImport(name) {
    const node = createBaseDeclaration(274 /* NamespaceImport */);
    node.name = name;
    node.transformFlags |= propagateChildFlags(node.name);
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    return node;
  }
  function updateNamespaceImport(node, name) {
    return node.name !== name ? update(createNamespaceImport(name), node) : node;
  }
  function createNamespaceExport(name) {
    const node = createBaseDeclaration(280 /* NamespaceExport */);
    node.name = name;
    node.transformFlags |= propagateChildFlags(node.name) | 32 /* ContainsES2020 */;
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    return node;
  }
  function updateNamespaceExport(node, name) {
    return node.name !== name ? update(createNamespaceExport(name), node) : node;
  }
  function createNamedImports(elements) {
    const node = createBaseNode(275 /* NamedImports */);
    node.elements = createNodeArray(elements);
    node.transformFlags |= propagateChildrenFlags(node.elements);
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    return node;
  }
  function updateNamedImports(node, elements) {
    return node.elements !== elements ? update(createNamedImports(elements), node) : node;
  }
  function createImportSpecifier(isTypeOnly, propertyName, name) {
    const node = createBaseDeclaration(276 /* ImportSpecifier */);
    node.isTypeOnly = isTypeOnly;
    node.propertyName = propertyName;
    node.name = name;
    node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name);
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    return node;
  }
  function updateImportSpecifier(node, isTypeOnly, propertyName, name) {
    return node.isTypeOnly !== isTypeOnly || node.propertyName !== propertyName || node.name !== name ? update(createImportSpecifier(isTypeOnly, propertyName, name), node) : node;
  }
  function createExportAssignment(modifiers, isExportEquals, expression) {
    const node = createBaseDeclaration(277 /* ExportAssignment */);
    node.modifiers = asNodeArray(modifiers);
    node.isExportEquals = isExportEquals;
    node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(
      64 /* EqualsToken */,
      /*leftSide*/
      void 0,
      expression
    ) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression);
    node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression);
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    node.jsDoc = void 0;
    return node;
  }
  function updateExportAssignment(node, modifiers, expression) {
    return node.modifiers !== modifiers || node.expression !== expression ? update(createExportAssignment(modifiers, node.isExportEquals, expression), node) : node;
  }
  function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes) {
    const node = createBaseDeclaration(278 /* ExportDeclaration */);
    node.modifiers = asNodeArray(modifiers);
    node.isTypeOnly = isTypeOnly;
    node.exportClause = exportClause;
    node.moduleSpecifier = moduleSpecifier;
    node.attributes = node.assertClause = attributes;
    node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier);
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    node.jsDoc = void 0;
    return node;
  }
  function updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes) {
    return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes), node) : node;
  }
  function finishUpdateExportDeclaration(updated, original) {
    if (updated !== original) {
      if (updated.modifiers === original.modifiers) {
        updated.modifiers = original.modifiers;
      }
    }
    return update(updated, original);
  }
  function createNamedExports(elements) {
    const node = createBaseNode(279 /* NamedExports */);
    node.elements = createNodeArray(elements);
    node.transformFlags |= propagateChildrenFlags(node.elements);
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    return node;
  }
  function updateNamedExports(node, elements) {
    return node.elements !== elements ? update(createNamedExports(elements), node) : node;
  }
  function createExportSpecifier(isTypeOnly, propertyName, name) {
    const node = createBaseNode(281 /* ExportSpecifier */);
    node.isTypeOnly = isTypeOnly;
    node.propertyName = asName(propertyName);
    node.name = asName(name);
    node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name);
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    node.jsDoc = void 0;
    return node;
  }
  function updateExportSpecifier(node, isTypeOnly, propertyName, name) {
    return node.isTypeOnly !== isTypeOnly || node.propertyName !== propertyName || node.name !== name ? update(createExportSpecifier(isTypeOnly, propertyName, name), node) : node;
  }
  function createMissingDeclaration() {
    const node = createBaseDeclaration(282 /* MissingDeclaration */);
    node.jsDoc = void 0;
    return node;
  }
  function createExternalModuleReference(expression) {
    const node = createBaseNode(283 /* ExternalModuleReference */);
    node.expression = expression;
    node.transformFlags |= propagateChildFlags(node.expression);
    node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */;
    return node;
  }
  function updateExternalModuleReference(node, expression) {
    return node.expression !== expression ? update(createExternalModuleReference(expression), node) : node;
  }
  function createJSDocPrimaryTypeWorker(kind) {
    return createBaseNode(kind);
  }
  function createJSDocPrePostfixUnaryTypeWorker(kind, type, postfix = false) {
    const node = createJSDocUnaryTypeWorker(
      kind,
      postfix ? type && parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(type) : type
    );
    node.postfix = postfix;
    return node;
  }
  function createJSDocUnaryTypeWorker(kind, type) {
    const node = createBaseNode(kind);
    node.type = type;
    return node;
  }
  function updateJSDocPrePostfixUnaryTypeWorker(kind, node, type) {
    return node.type !== type ? update(createJSDocPrePostfixUnaryTypeWorker(kind, type, node.postfix), node) : node;
  }
  function updateJSDocUnaryTypeWorker(kind, node, type) {
    return node.type !== type ? update(createJSDocUnaryTypeWorker(kind, type), node) : node;
  }
  function createJSDocFunctionType(parameters, type) {
    const node = createBaseDeclaration(317 /* JSDocFunctionType */);
    node.parameters = asNodeArray(parameters);
    node.type = type;
    node.transformFlags = propagateChildrenFlags(node.parameters) | (node.type ? 1 /* ContainsTypeScript */ : 0 /* None */);
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    node.typeArguments = void 0;
    return node;
  }
  function updateJSDocFunctionType(node, parameters, type) {
    return node.parameters !== parameters || node.type !== type ? update(createJSDocFunctionType(parameters, type), node) : node;
  }
  function createJSDocTypeLiteral(propertyTags, isArrayType = false) {
    const node = createBaseDeclaration(322 /* JSDocTypeLiteral */);
    node.jsDocPropertyTags = asNodeArray(propertyTags);
    node.isArrayType = isArrayType;
    return node;
  }
  function updateJSDocTypeLiteral(node, propertyTags, isArrayType) {
    return node.jsDocPropertyTags !== propertyTags || node.isArrayType !== isArrayType ? update(createJSDocTypeLiteral(propertyTags, isArrayType), node) : node;
  }
  function createJSDocTypeExpression(type) {
    const node = createBaseNode(309 /* JSDocTypeExpression */);
    node.type = type;
    return node;
  }
  function updateJSDocTypeExpression(node, type) {
    return node.type !== type ? update(createJSDocTypeExpression(type), node) : node;
  }
  function createJSDocSignature(typeParameters, parameters, type) {
    const node = createBaseDeclaration(323 /* JSDocSignature */);
    node.typeParameters = asNodeArray(typeParameters);
    node.parameters = createNodeArray(parameters);
    node.type = type;
    node.jsDoc = void 0;
    node.locals = void 0;
    node.nextContainer = void 0;
    return node;
  }
  function updateJSDocSignature(node, typeParameters, parameters, type) {
    return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? update(createJSDocSignature(typeParameters, parameters, type), node) : node;
  }
  function getDefaultTagName(node) {
    const defaultTagName = getDefaultTagNameForKind(node.kind);
    return node.tagName.escapedText === escapeLeadingUnderscores(defaultTagName) ? node.tagName : createIdentifier(defaultTagName);
  }
  function createBaseJSDocTag(kind, tagName, comment) {
    const node = createBaseNode(kind);
    node.tagName = tagName;
    node.comment = comment;
    return node;
  }
  function createBaseJSDocTagDeclaration(kind, tagName, comment) {
    const node = createBaseDeclaration(kind);
    node.tagName = tagName;
    node.comment = comment;
    return node;
  }
  function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) {
    const node = createBaseJSDocTag(345 /* JSDocTemplateTag */, tagName ?? createIdentifier("template"), comment);
    node.constraint = constraint;
    node.typeParameters = createNodeArray(typeParameters);
    return node;
  }
  function updateJSDocTemplateTag(node, tagName = getDefaultTagName(node), constraint, typeParameters, comment) {
    return node.tagName !== tagName || node.constraint !== constraint || node.typeParameters !== typeParameters || node.comment !== comment ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node) : node;
  }
  function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) {
    const node = createBaseJSDocTagDeclaration(346 /* JSDocTypedefTag */, tagName ?? createIdentifier("typedef"), comment);
    node.typeExpression = typeExpression;
    node.fullName = fullName;
    node.name = getJSDocTypeAliasName(fullName);
    node.locals = void 0;
    node.nextContainer = void 0;
    return node;
  }
  function updateJSDocTypedefTag(node, tagName = getDefaultTagName(node), typeExpression, fullName, comment) {
    return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName || node.comment !== comment ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node) : node;
  }
  function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
    const node = createBaseJSDocTagDeclaration(341 /* JSDocParameterTag */, tagName ?? createIdentifier("param"), comment);
    node.typeExpression = typeExpression;
    node.name = name;
    node.isNameFirst = !!isNameFirst;
    node.isBracketed = isBracketed;
    return node;
  }
  function updateJSDocParameterTag(node, tagName = getDefaultTagName(node), name, isBracketed, typeExpression, isNameFirst, comment) {
    return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed || node.typeExpression !== typeExpression || node.isNameFirst !== isNameFirst || node.comment !== comment ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) : node;
  }
  function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
    const node = createBaseJSDocTagDeclaration(348 /* JSDocPropertyTag */, tagName ?? createIdentifier("prop"), comment);
    node.typeExpression = typeExpression;
    node.name = name;
    node.isNameFirst = !!isNameFirst;
    node.isBracketed = isBracketed;
    return node;
  }
  function updateJSDocPropertyTag(node, tagName = getDefaultTagName(node), name, isBracketed, typeExpression, isNameFirst, comment) {
    return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed || node.typeExpression !== typeExpression || node.isNameFirst !== isNameFirst || node.comment !== comment ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) : node;
  }
  function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) {
    const node = createBaseJSDocTagDeclaration(338 /* JSDocCallbackTag */, tagName ?? createIdentifier("callback"), comment);
    node.typeExpression = typeExpression;
    node.fullName = fullName;
    node.name = getJSDocTypeAliasName(fullName);
    node.locals = void 0;
    node.nextContainer = void 0;
    return node;
  }
  function updateJSDocCallbackTag(node, tagName = getDefaultTagName(node), typeExpression, fullName, comment) {
    return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName || node.comment !== comment ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node) : node;
  }
  function createJSDocOverloadTag(tagName, typeExpression, comment) {
    const node = createBaseJSDocTag(339 /* JSDocOverloadTag */, tagName ?? createIdentifier("overload"), comment);
    node.typeExpression = typeExpression;
    return node;
  }
  function updateJSDocOverloadTag(node, tagName = getDefaultTagName(node), typeExpression, comment) {
    return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocOverloadTag(tagName, typeExpression, comment), node) : node;
  }
  function createJSDocAugmentsTag(tagName, className, comment) {
    const node = createBaseJSDocTag(328 /* JSDocAugmentsTag */, tagName ?? createIdentifier("augments"), comment);
    node.class = className;
    return node;
  }
  function updateJSDocAugmentsTag(node, tagName = getDefaultTagName(node), className, comment) {
    return node.tagName !== tagName || node.class !== className || node.comment !== comment ? update(createJSDocAugmentsTag(tagName, className, comment), node) : node;
  }
  function createJSDocImplementsTag(tagName, className, comment) {
    const node = createBaseJSDocTag(329 /* JSDocImplementsTag */, tagName ?? createIdentifier("implements"), comment);
    node.class = className;
    return node;
  }
  function createJSDocSeeTag(tagName, name, comment) {
    const node = createBaseJSDocTag(347 /* JSDocSeeTag */, tagName ?? createIdentifier("see"), comment);
    node.name = name;
    return node;
  }
  function updateJSDocSeeTag(node, tagName, name, comment) {
    return node.tagName !== tagName || node.name !== name || node.comment !== comment ? update(createJSDocSeeTag(tagName, name, comment), node) : node;
  }
  function createJSDocNameReference(name) {
    const node = createBaseNode(310 /* JSDocNameReference */);
    node.name = name;
    return node;
  }
  function updateJSDocNameReference(node, name) {
    return node.name !== name ? update(createJSDocNameReference(name), node) : node;
  }
  function createJSDocMemberName(left, right) {
    const node = createBaseNode(311 /* JSDocMemberName */);
    node.left = left;
    node.right = right;
    node.transformFlags |= propagateChildFlags(node.left) | propagateChildFlags(node.right);
    return node;
  }
  function updateJSDocMemberName(node, left, right) {
    return node.left !== left || node.right !== right ? update(createJSDocMemberName(left, right), node) : node;
  }
  function createJSDocLink(name, text) {
    const node = createBaseNode(324 /* JSDocLink */);
    node.name = name;
    node.text = text;
    return node;
  }
  function updateJSDocLink(node, name, text) {
    return node.name !== name ? update(createJSDocLink(name, text), node) : node;
  }
  function createJSDocLinkCode(name, text) {
    const node = createBaseNode(325 /* JSDocLinkCode */);
    node.name = name;
    node.text = text;
    return node;
  }
  function updateJSDocLinkCode(node, name, text) {
    return node.name !== name ? update(createJSDocLinkCode(name, text), node) : node;
  }
  function createJSDocLinkPlain(name, text) {
    const node = createBaseNode(326 /* JSDocLinkPlain */);
    node.name = name;
    node.text = text;
    return node;
  }
  function updateJSDocLinkPlain(node, name, text) {
    return node.name !== name ? update(createJSDocLinkPlain(name, text), node) : node;
  }
  function updateJSDocImplementsTag(node, tagName = getDefaultTagName(node), className, comment) {
    return node.tagName !== tagName || node.class !== className || node.comment !== comment ? update(createJSDocImplementsTag(tagName, className, comment), node) : node;
  }
  function createJSDocSimpleTagWorker(kind, tagName, comment) {
    const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment);
    return node;
  }
  function updateJSDocSimpleTagWorker(kind, node, tagName = getDefaultTagName(node), comment) {
    return node.tagName !== tagName || node.comment !== comment ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) : node;
  }
  function createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment) {
    const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment);
    node.typeExpression = typeExpression;
    return node;
  }
  function updateJSDocTypeLikeTagWorker(kind, node, tagName = getDefaultTagName(node), typeExpression, comment) {
    return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment), node) : node;
  }
  function createJSDocUnknownTag(tagName, comment) {
    const node = createBaseJSDocTag(327 /* JSDocTag */, tagName, comment);
    return node;
  }
  function updateJSDocUnknownTag(node, tagName, comment) {
    return node.tagName !== tagName || node.comment !== comment ? update(createJSDocUnknownTag(tagName, comment), node) : node;
  }
  function createJSDocEnumTag(tagName, typeExpression, comment) {
    const node = createBaseJSDocTagDeclaration(340 /* JSDocEnumTag */, tagName ?? createIdentifier(getDefaultTagNameForKind(340 /* JSDocEnumTag */)), comment);
    node.typeExpression = typeExpression;
    node.locals = void 0;
    node.nextContainer = void 0;
    return node;
  }
  function updateJSDocEnumTag(node, tagName = getDefaultTagName(node), typeExpression, comment) {
    return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocEnumTag(tagName, typeExpression, comment), node) : node;
  }
  function createJSDocImportTag(tagName, importClause, moduleSpecifier, attributes, comment) {
    const node = createBaseJSDocTag(351 /* JSDocImportTag */, tagName ?? createIdentifier("import"), comment);
    node.importClause = importClause;
    node.moduleSpecifier = moduleSpecifier;
    node.attributes = attributes;
    node.comment = comment;
    return node;
  }
  function updateJSDocImportTag(node, tagName, importClause, moduleSpecifier, attributes, comment) {
    return node.tagName !== tagName || node.comment !== comment || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? update(createJSDocImportTag(tagName, importClause, moduleSpecifier, attributes, comment), node) : node;
  }
  function createJSDocText(text) {
    const node = createBaseNode(321 /* JSDocText */);
    node.text = text;
    return node;
  }
  function updateJSDocText(node, text) {
    return node.text !== text ? update(createJSDocText(text), node) : node;
  }
  function createJSDocComment(comment, tags) {
    const node = createBaseNode(320 /* JSDoc */);
    node.comment = comment;
    node.tags = asNodeArray(tags);
    return node;
  }
  function updateJSDocComment(node, comment, tags) {
    return node.comment !== comment || node.tags !== tags ? update(createJSDocComment(comment, tags), node) : node;
  }
  function createJsxElement(openingElement, children, closingElement) {
    const node = createBaseNode(284 /* JsxElement */);
    node.openingElement = openingElement;
    node.children = createNodeArray(children);
    node.closingElement = closingElement;
    node.transformFlags |= propagateChildFlags(node.openingElement) | propagateChildrenFlags(node.children) | propagateChildFlags(node.closingElement) | 2 /* ContainsJsx */;
    return node;
  }
  function updateJsxElement(node, openingElement, children, closingElement) {
    return node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement ? update(createJsxElement(openingElement, children, closingElement), node) : node;
  }
  function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
    const node = createBaseNode(285 /* JsxSelfClosingElement */);
    node.tagName = tagName;
    node.typeArguments = asNodeArray(typeArguments);
    node.attributes = attributes;
    node.transformFlags |= propagateChildFlags(node.tagName) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.attributes) | 2 /* ContainsJsx */;
    if (node.typeArguments) {
      node.transformFlags |= 1 /* ContainsTypeScript */;
    }
    return node;
  }
  function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
    return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node;
  }
  function createJsxOpeningElement(tagName, typeArguments, attributes) {
    const node = createBaseNode(286 /* JsxOpeningElement */);
    node.tagName = tagName;
    node.typeArguments = asNodeArray(typeArguments);
    node.attributes = attributes;
    node.transformFlags |= propagateChildFlags(node.tagName) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.attributes) | 2 /* ContainsJsx */;
    if (typeArguments) {
      node.transformFlags |= 1 /* ContainsTypeScript */;
    }
    return node;
  }
  function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
    return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node;
  }
  function createJsxClosingElement(tagName) {
    const node = createBaseNode(287 /* JsxClosingElement */);
    node.tagName = tagName;
    node.transformFlags |= propagateChildFlags(node.tagName) | 2 /* ContainsJsx */;
    return node;
  }
  function updateJsxClosingElement(node, tagName) {
    return node.tagName !== tagName ? update(createJsxClosingElement(tagName), node) : node;
  }
  function createJsxFragment(openingFragment, children, closingFragment) {
    const node = createBaseNode(288 /* JsxFragment */);
    node.openingFragment = openingFragment;
    node.children = createNodeArray(children);
    node.closingFragment = closingFragment;
    node.transformFlags |= propagateChildFlags(node.openingFragment) | propagateChildrenFlags(node.children) | propagateChildFlags(node.closingFragment) | 2 /* ContainsJsx */;
    return node;
  }
  function updateJsxFragment(node, openingFragment, children, closingFragment) {
    return node.openingFragment !== openingFragment || node.children !== children || node.closingFragment !== closingFragment ? update(createJsxFragment(openingFragment, children, closingFragment), node) : node;
  }
  function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
    const node = createBaseNode(12 /* JsxText */);
    node.text = text;
    node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
    node.transformFlags |= 2 /* ContainsJsx */;
    return node;
  }
  function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
    return node.text !== text || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces ? update(createJsxText(text, containsOnlyTriviaWhiteSpaces), node) : node;
  }
  function createJsxOpeningFragment() {
    const node = createBaseNode(289 /* JsxOpeningFragment */);
    node.transformFlags |= 2 /* ContainsJsx */;
    return node;
  }
  function createJsxJsxClosingFragment() {
    const node = createBaseNode(290 /* JsxClosingFragment */);
    node.transformFlags |= 2 /* ContainsJsx */;
    return node;
  }
  function createJsxAttribute(name, initializer) {
    const node = createBaseDeclaration(291 /* JsxAttribute */);
    node.name = name;
    node.initializer = initializer;
    node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer) | 2 /* ContainsJsx */;
    return node;
  }
  function updateJsxAttribute(node, name, initializer) {
    return node.name !== name || node.initializer !== initializer ? update(createJsxAttribute(name, initializer), node) : node;
  }
  function createJsxAttributes(properties) {
    const node = createBaseDeclaration(292 /* JsxAttributes */);
    node.properties = createNodeArray(properties);
    node.transformFlags |= propagateChildrenFlags(node.properties) | 2 /* ContainsJsx */;
    return node;
  }
  function updateJsxAttributes(node, properties) {
    return node.properties !== properties ? update(createJsxAttributes(properties), node) : node;
  }
  function createJsxSpreadAttribute(expression) {
    const node = createBaseNode(293 /* JsxSpreadAttribute */);
    node.expression = expression;
    node.transformFlags |= propagateChildFlags(node.expression) | 2 /* ContainsJsx */;
    return node;
  }
  function updateJsxSpreadAttribute(node, expression) {
    return node.expression !== expression ? update(createJsxSpreadAttribute(expression), node) : node;
  }
  function createJsxExpression(dotDotDotToken, expression) {
    const node = createBaseNode(294 /* JsxExpression */);
    node.dotDotDotToken = dotDotDotToken;
    node.expression = expression;
    node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | propagateChildFlags(node.expression) | 2 /* ContainsJsx */;
    return node;
  }
  function updateJsxExpression(node, expression) {
    return node.expression !== expression ? update(createJsxExpression(node.dotDotDotToken, expression), node) : node;
  }
  function createJsxNamespacedName(namespace, name) {
    const node = createBaseNode(295 /* JsxNamespacedName */);
    node.namespace = namespace;
    node.name = name;
    node.transformFlags |= propagateChildFlags(node.namespace) | propagateChildFlags(node.name) | 2 /* ContainsJsx */;
    return node;
  }
  function updateJsxNamespacedName(node, namespace, name) {
    return node.namespace !== namespace || node.name !== name ? update(createJsxNamespacedName(namespace, name), node) : node;
  }
  function createCaseClause(expression, statements) {
    const node = createBaseNode(296 /* CaseClause */);
    node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
    node.statements = createNodeArray(statements);
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.statements);
    node.jsDoc = void 0;
    return node;
  }
  function updateCaseClause(node, expression, statements) {
    return node.expression !== expression || node.statements !== statements ? update(createCaseClause(expression, statements), node) : node;
  }
  function createDefaultClause(statements) {
    const node = createBaseNode(297 /* DefaultClause */);
    node.statements = createNodeArray(statements);
    node.transformFlags = propagateChildrenFlags(node.statements);
    return node;
  }
  function updateDefaultClause(node, statements) {
    return node.statements !== statements ? update(createDefaultClause(statements), node) : node;
  }
  function createHeritageClause(token, types) {
    const node = createBaseNode(298 /* HeritageClause */);
    node.token = token;
    node.types = createNodeArray(types);
    node.transformFlags |= propagateChildrenFlags(node.types);
    switch (token) {
      case 96 /* ExtendsKeyword */:
        node.transformFlags |= 1024 /* ContainsES2015 */;
        break;
      case 119 /* ImplementsKeyword */:
        node.transformFlags |= 1 /* ContainsTypeScript */;
        break;
      default:
        return Debug.assertNever(token);
    }
    return node;
  }
  function updateHeritageClause(node, types) {
    return node.types !== types ? update(createHeritageClause(node.token, types), node) : node;
  }
  function createCatchClause(variableDeclaration, block) {
    const node = createBaseNode(299 /* CatchClause */);
    node.variableDeclaration = asVariableDeclaration(variableDeclaration);
    node.block = block;
    node.transformFlags |= propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block) | (!variableDeclaration ? 64 /* ContainsES2019 */ : 0 /* None */);
    node.locals = void 0;
    node.nextContainer = void 0;
    return node;
  }
  function updateCatchClause(node, variableDeclaration, block) {
    return node.variableDeclaration !== variableDeclaration || node.block !== block ? update(createCatchClause(variableDeclaration, block), node) : node;
  }
  function createPropertyAssignment(name, initializer) {
    const node = createBaseDeclaration(303 /* PropertyAssignment */);
    node.name = asName(name);
    node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
    node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer);
    node.modifiers = void 0;
    node.questionToken = void 0;
    node.exclamationToken = void 0;
    node.jsDoc = void 0;
    return node;
  }
  function updatePropertyAssignment(node, name, initializer) {
    return node.name !== name || node.initializer !== initializer ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node) : node;
  }
  function finishUpdatePropertyAssignment(updated, original) {
    if (updated !== original) {
      updated.modifiers = original.modifiers;
      updated.questionToken = original.questionToken;
      updated.exclamationToken = original.exclamationToken;
    }
    return update(updated, original);
  }
  function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
    const node = createBaseDeclaration(304 /* ShorthandPropertyAssignment */);
    node.name = asName(name);
    node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer);
    node.transformFlags |= propagateIdentifierNameFlags(node.name) | propagateChildFlags(node.objectAssignmentInitializer) | 1024 /* ContainsES2015 */;
    node.equalsToken = void 0;
    node.modifiers = void 0;
    node.questionToken = void 0;
    node.exclamationToken = void 0;
    node.jsDoc = void 0;
    return node;
  }
  function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
    return node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) : node;
  }
  function finishUpdateShorthandPropertyAssignment(updated, original) {
    if (updated !== original) {
      updated.modifiers = original.modifiers;
      updated.questionToken = original.questionToken;
      updated.exclamationToken = original.exclamationToken;
      updated.equalsToken = original.equalsToken;
    }
    return update(updated, original);
  }
  function createSpreadAssignment(expression) {
    const node = createBaseDeclaration(305 /* SpreadAssignment */);
    node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
    node.transformFlags |= propagateChildFlags(node.expression) | 128 /* ContainsES2018 */ | 65536 /* ContainsObjectRestOrSpread */;
    node.jsDoc = void 0;
    return node;
  }
  function updateSpreadAssignment(node, expression) {
    return node.expression !== expression ? update(createSpreadAssignment(expression), node) : node;
  }
  function createEnumMember(name, initializer) {
    const node = createBaseDeclaration(306 /* EnumMember */);
    node.name = asName(name);
    node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
    node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer) | 1 /* ContainsTypeScript */;
    node.jsDoc = void 0;
    return node;
  }
  function updateEnumMember(node, name, initializer) {
    return node.name !== name || node.initializer !== initializer ? update(createEnumMember(name, initializer), node) : node;
  }
  function createSourceFile2(statements, endOfFileToken, flags2) {
    const node = baseFactory2.createBaseSourceFileNode(307 /* SourceFile */);
    node.statements = createNodeArray(statements);
    node.endOfFileToken = endOfFileToken;
    node.flags |= flags2;
    node.text = "";
    node.fileName = "";
    node.path = "";
    node.resolvedPath = "";
    node.originalFileName = "";
    node.languageVersion = 1 /* ES5 */;
    node.languageVariant = 0;
    node.scriptKind = 0;
    node.isDeclarationFile = false;
    node.hasNoDefaultLib = false;
    node.transformFlags |= propagateChildrenFlags(node.statements) | propagateChildFlags(node.endOfFileToken);
    node.locals = void 0;
    node.nextContainer = void 0;
    node.endFlowNode = void 0;
    node.nodeCount = 0;
    node.identifierCount = 0;
    node.symbolCount = 0;
    node.parseDiagnostics = void 0;
    node.bindDiagnostics = void 0;
    node.bindSuggestionDiagnostics = void 0;
    node.lineMap = void 0;
    node.externalModuleIndicator = void 0;
    node.setExternalModuleIndicator = void 0;
    node.pragmas = void 0;
    node.checkJsDirective = void 0;
    node.referencedFiles = void 0;
    node.typeReferenceDirectives = void 0;
    node.libReferenceDirectives = void 0;
    node.amdDependencies = void 0;
    node.commentDirectives = void 0;
    node.identifiers = void 0;
    node.packageJsonLocations = void 0;
    node.packageJsonScope = void 0;
    node.imports = void 0;
    node.moduleAugmentations = void 0;
    node.ambientModuleNames = void 0;
    node.classifiableNames = void 0;
    node.impliedNodeFormat = void 0;
    return node;
  }
  function createRedirectedSourceFile(redirectInfo) {
    const node = Object.create(redirectInfo.redirectTarget);
    Object.defineProperties(node, {
      id: {
        get() {
          return this.redirectInfo.redirectTarget.id;
        },
        set(value) {
          this.redirectInfo.redirectTarget.id = value;
        }
      },
      symbol: {
        get() {
          return this.redirectInfo.redirectTarget.symbol;
        },
        set(value) {
          this.redirectInfo.redirectTarget.symbol = value;
        }
      }
    });
    node.redirectInfo = redirectInfo;
    return node;
  }
  function cloneRedirectedSourceFile(source) {
    const node = createRedirectedSourceFile(source.redirectInfo);
    node.flags |= source.flags & ~16 /* Synthesized */;
    node.fileName = source.fileName;
    node.path = source.path;
    node.resolvedPath = source.resolvedPath;
    node.originalFileName = source.originalFileName;
    node.packageJsonLocations = source.packageJsonLocations;
    node.packageJsonScope = source.packageJsonScope;
    node.emitNode = void 0;
    return node;
  }
  function cloneSourceFileWorker(source) {
    const node = baseFactory2.createBaseSourceFileNode(307 /* SourceFile */);
    node.flags |= source.flags & ~16 /* Synthesized */;
    for (const p in source) {
      if (hasProperty(node, p) || !hasProperty(source, p)) {
        continue;
      }
      if (p === "emitNode") {
        node.emitNode = void 0;
        continue;
      }
      node[p] = source[p];
    }
    return node;
  }
  function cloneSourceFile(source) {
    const node = source.redirectInfo ? cloneRedirectedSourceFile(source) : cloneSourceFileWorker(source);
    setOriginal(node, source);
    return node;
  }
  function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
    const node = cloneSourceFile(source);
    node.statements = createNodeArray(statements);
    node.isDeclarationFile = isDeclarationFile;
    node.referencedFiles = referencedFiles;
    node.typeReferenceDirectives = typeReferences;
    node.hasNoDefaultLib = hasNoDefaultLib;
    node.libReferenceDirectives = libReferences;
    node.transformFlags = propagateChildrenFlags(node.statements) | propagateChildFlags(node.endOfFileToken);
    return node;
  }
  function updateSourceFile(node, statements, isDeclarationFile = node.isDeclarationFile, referencedFiles = node.referencedFiles, typeReferenceDirectives = node.typeReferenceDirectives, hasNoDefaultLib = node.hasNoDefaultLib, libReferenceDirectives = node.libReferenceDirectives) {
    return node.statements !== statements || node.isDeclarationFile !== isDeclarationFile || node.referencedFiles !== referencedFiles || node.typeReferenceDirectives !== typeReferenceDirectives || node.hasNoDefaultLib !== hasNoDefaultLib || node.libReferenceDirectives !== libReferenceDirectives ? update(cloneSourceFileWithChanges(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives), node) : node;
  }
  function createBundle(sourceFiles) {
    const node = createBaseNode(308 /* Bundle */);
    node.sourceFiles = sourceFiles;
    node.syntheticFileReferences = void 0;
    node.syntheticTypeReferences = void 0;
    node.syntheticLibReferences = void 0;
    node.hasNoDefaultLib = void 0;
    return node;
  }
  function updateBundle(node, sourceFiles) {
    return node.sourceFiles !== sourceFiles ? update(createBundle(sourceFiles), node) : node;
  }
  function createSyntheticExpression(type, isSpread = false, tupleNameSource) {
    const node = createBaseNode(237 /* SyntheticExpression */);
    node.type = type;
    node.isSpread = isSpread;
    node.tupleNameSource = tupleNameSource;
    return node;
  }
  function createSyntaxList(children) {
    const node = createBaseNode(352 /* SyntaxList */);
    node._children = children;
    return node;
  }
  function createNotEmittedStatement(original) {
    const node = createBaseNode(353 /* NotEmittedStatement */);
    node.original = original;
    setTextRange(node, original);
    return node;
  }
  function createPartiallyEmittedExpression(expression, original) {
    const node = createBaseNode(355 /* PartiallyEmittedExpression */);
    node.expression = expression;
    node.original = original;
    node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */;
    setTextRange(node, original);
    return node;
  }
  function updatePartiallyEmittedExpression(node, expression) {
    return node.expression !== expression ? update(createPartiallyEmittedExpression(expression, node.original), node) : node;
  }
  function createNotEmittedTypeElement() {
    return createBaseNode(354 /* NotEmittedTypeElement */);
  }
  function flattenCommaElements(node) {
    if (nodeIsSynthesized(node) && !isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
      if (isCommaListExpression(node)) {
        return node.elements;
      }
      if (isBinaryExpression(node) && isCommaToken(node.operatorToken)) {
        return [node.left, node.right];
      }
    }
    return node;
  }
  function createCommaListExpression(elements) {
    const node = createBaseNode(356 /* CommaListExpression */);
    node.elements = createNodeArray(sameFlatMap(elements, flattenCommaElements));
    node.transformFlags |= propagateChildrenFlags(node.elements);
    return node;
  }
  function updateCommaListExpression(node, elements) {
    return node.elements !== elements ? update(createCommaListExpression(elements), node) : node;
  }
  function createSyntheticReferenceExpression(expression, thisArg) {
    const node = createBaseNode(357 /* SyntheticReferenceExpression */);
    node.expression = expression;
    node.thisArg = thisArg;
    node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thisArg);
    return node;
  }
  function updateSyntheticReferenceExpression(node, expression, thisArg) {
    return node.expression !== expression || node.thisArg !== thisArg ? update(createSyntheticReferenceExpression(expression, thisArg), node) : node;
  }
  function cloneGeneratedIdentifier(node) {
    const clone = createBaseIdentifier(node.escapedText);
    clone.flags |= node.flags & ~16 /* Synthesized */;
    clone.transformFlags = node.transformFlags;
    setOriginal(clone, node);
    setIdentifierAutoGenerate(clone, { ...node.emitNode.autoGenerate });
    return clone;
  }
  function cloneIdentifier(node) {
    const clone = createBaseIdentifier(node.escapedText);
    clone.flags |= node.flags & ~16 /* Synthesized */;
    clone.jsDoc = node.jsDoc;
    clone.flowNode = node.flowNode;
    clone.symbol = node.symbol;
    clone.transformFlags = node.transformFlags;
    setOriginal(clone, node);
    const typeArguments = getIdentifierTypeArguments(node);
    if (typeArguments) setIdentifierTypeArguments(clone, typeArguments);
    return clone;
  }
  function cloneGeneratedPrivateIdentifier(node) {
    const clone = createBasePrivateIdentifier(node.escapedText);
    clone.flags |= node.flags & ~16 /* Synthesized */;
    clone.transformFlags = node.transformFlags;
    setOriginal(clone, node);
    setIdentifierAutoGenerate(clone, { ...node.emitNode.autoGenerate });
    return clone;
  }
  function clonePrivateIdentifier(node) {
    const clone = createBasePrivateIdentifier(node.escapedText);
    clone.flags |= node.flags & ~16 /* Synthesized */;
    clone.transformFlags = node.transformFlags;
    setOriginal(clone, node);
    return clone;
  }
  function cloneNode(node) {
    if (node === void 0) {
      return node;
    }
    if (isSourceFile(node)) {
      return cloneSourceFile(node);
    }
    if (isGeneratedIdentifier(node)) {
      return cloneGeneratedIdentifier(node);
    }
    if (isIdentifier(node)) {
      return cloneIdentifier(node);
    }
    if (isGeneratedPrivateIdentifier(node)) {
      return cloneGeneratedPrivateIdentifier(node);
    }
    if (isPrivateIdentifier(node)) {
      return clonePrivateIdentifier(node);
    }
    const clone = !isNodeKind(node.kind) ? baseFactory2.createBaseTokenNode(node.kind) : baseFactory2.createBaseNode(node.kind);
    clone.flags |= node.flags & ~16 /* Synthesized */;
    clone.transformFlags = node.transformFlags;
    setOriginal(clone, node);
    for (const key in node) {
      if (hasProperty(clone, key) || !hasProperty(node, key)) {
        continue;
      }
      clone[key] = node[key];
    }
    return clone;
  }
  function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
    return createCallExpression(
      createFunctionExpression(
        /*modifiers*/
        void 0,
        /*asteriskToken*/
        void 0,
        /*name*/
        void 0,
        /*typeParameters*/
        void 0,
        /*parameters*/
        param ? [param] : [],
        /*type*/
        void 0,
        createBlock(
          statements,
          /*multiLine*/
          true
        )
      ),
      /*typeArguments*/
      void 0,
      /*argumentsArray*/
      paramValue ? [paramValue] : []
    );
  }
  function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
    return createCallExpression(
      createArrowFunction(
        /*modifiers*/
        void 0,
        /*typeParameters*/
        void 0,
        /*parameters*/
        param ? [param] : [],
        /*type*/
        void 0,
        /*equalsGreaterThanToken*/
        void 0,
        createBlock(
          statements,
          /*multiLine*/
          true
        )
      ),
      /*typeArguments*/
      void 0,
      /*argumentsArray*/
      paramValue ? [paramValue] : []
    );
  }
  function createVoidZero() {
    return createVoidExpression(createNumericLiteral("0"));
  }
  function createExportDefault(expression) {
    return createExportAssignment(
      /*modifiers*/
      void 0,
      /*isExportEquals*/
      false,
      expression
    );
  }
  function createExternalModuleExport(exportName) {
    return createExportDeclaration(
      /*modifiers*/
      void 0,
      /*isTypeOnly*/
      false,
      createNamedExports([
        createExportSpecifier(
          /*isTypeOnly*/
          false,
          /*propertyName*/
          void 0,
          exportName
        )
      ])
    );
  }
  function createTypeCheck(value, tag) {
    return tag === "null" ? factory2.createStrictEquality(value, createNull()) : tag === "undefined" ? factory2.createStrictEquality(value, createVoidZero()) : factory2.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag));
  }
  function createIsNotTypeCheck(value, tag) {
    return tag === "null" ? factory2.createStrictInequality(value, createNull()) : tag === "undefined" ? factory2.createStrictInequality(value, createVoidZero()) : factory2.createStrictInequality(createTypeOfExpression(value), createStringLiteral(tag));
  }
  function createMethodCall(object, methodName, argumentsList) {
    if (isCallChain(object)) {
      return createCallChain(
        createPropertyAccessChain(
          object,
          /*questionDotToken*/
          void 0,
          methodName
        ),
        /*questionDotToken*/
        void 0,
        /*typeArguments*/
        void 0,
        argumentsList
      );
    }
    return createCallExpression(
      createPropertyAccessExpression(object, methodName),
      /*typeArguments*/
      void 0,
      argumentsList
    );
  }
  function createFunctionBindCall(target, thisArg, argumentsList) {
    return createMethodCall(target, "bind", [thisArg, ...argumentsList]);
  }
  function createFunctionCallCall(target, thisArg, argumentsList) {
    return createMethodCall(target, "call", [thisArg, ...argumentsList]);
  }
  function createFunctionApplyCall(target, thisArg, argumentsExpression) {
    return createMethodCall(target, "apply", [thisArg, argumentsExpression]);
  }
  function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
    return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
  }
  function createArraySliceCall(array, start) {
    return createMethodCall(array, "slice", start === void 0 ? [] : [asExpression(start)]);
  }
  function createArrayConcatCall(array, argumentsList) {
    return createMethodCall(array, "concat", argumentsList);
  }
  function createObjectDefinePropertyCall(target, propertyName, attributes) {
    return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
  }
  function createObjectGetOwnPropertyDescriptorCall(target, propertyName) {
    return createGlobalMethodCall("Object", "getOwnPropertyDescriptor", [target, asExpression(propertyName)]);
  }
  function createReflectGetCall(target, propertyKey, receiver) {
    return createGlobalMethodCall("Reflect", "get", receiver ? [target, propertyKey, receiver] : [target, propertyKey]);
  }
  function createReflectSetCall(target, propertyKey, value, receiver) {
    return createGlobalMethodCall("Reflect", "set", receiver ? [target, propertyKey, value, receiver] : [target, propertyKey, value]);
  }
  function tryAddPropertyAssignment(properties, propertyName, expression) {
    if (expression) {
      properties.push(createPropertyAssignment(propertyName, expression));
      return true;
    }
    return false;
  }
  function createPropertyDescriptor(attributes, singleLine) {
    const properties = [];
    tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
    tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
    let isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
    isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
    let isAccessor2 = tryAddPropertyAssignment(properties, "get", attributes.get);
    isAccessor2 = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor2;
    Debug.assert(!(isData && isAccessor2), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
    return createObjectLiteralExpression(properties, !singleLine);
  }
  function updateOuterExpression(outerExpression, expression) {
    switch (outerExpression.kind) {
      case 217 /* ParenthesizedExpression */:
        return updateParenthesizedExpression(outerExpression, expression);
      case 216 /* TypeAssertionExpression */:
        return updateTypeAssertion(outerExpression, outerExpression.type, expression);
      case 234 /* AsExpression */:
        return updateAsExpression(outerExpression, expression, outerExpression.type);
      case 238 /* SatisfiesExpression */:
        return updateSatisfiesExpression(outerExpression, expression, outerExpression.type);
      case 235 /* NonNullExpression */:
        return updateNonNullExpression(outerExpression, expression);
      case 233 /* ExpressionWithTypeArguments */:
        return updateExpressionWithTypeArguments(outerExpression, expression, outerExpression.typeArguments);
      case 355 /* PartiallyEmittedExpression */:
        return updatePartiallyEmittedExpression(outerExpression, expression);
    }
  }
  function isIgnorableParen(node) {
    return isParenthesizedExpression(node) && nodeIsSynthesized(node) && nodeIsSynthesized(getSourceMapRange(node)) && nodeIsSynthesized(getCommentRange(node)) && !some(getSyntheticLeadingComments(node)) && !some(getSyntheticTrailingComments(node));
  }
  function restoreOuterExpressions(outerExpression, innerExpression, kinds = 31 /* All */) {
    if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
      return updateOuterExpression(
        outerExpression,
        restoreOuterExpressions(outerExpression.expression, innerExpression)
      );
    }
    return innerExpression;
  }
  function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
    if (!outermostLabeledStatement) {
      return node;
    }
    const updated = updateLabeledStatement(
      outermostLabeledStatement,
      outermostLabeledStatement.label,
      isLabeledStatement(outermostLabeledStatement.statement) ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node
    );
    if (afterRestoreLabelCallback) {
      afterRestoreLabelCallback(outermostLabeledStatement);
    }
    return updated;
  }
  function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
    const target = skipParentheses(node);
    switch (target.kind) {
      case 80 /* Identifier */:
        return cacheIdentifiers;
      case 110 /* ThisKeyword */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 11 /* StringLiteral */:
        return false;
      case 209 /* ArrayLiteralExpression */:
        const elements = target.elements;
        if (elements.length === 0) {
          return false;
        }
        return true;
      case 210 /* ObjectLiteralExpression */:
        return target.properties.length > 0;
      default:
        return true;
    }
  }
  function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers = false) {
    const callee = skipOuterExpressions(expression, 31 /* All */);
    let thisArg;
    let target;
    if (isSuperProperty(callee)) {
      thisArg = createThis();
      target = callee;
    } else if (isSuperKeyword(callee)) {
      thisArg = createThis();
      target = languageVersion !== void 0 && languageVersion < 2 /* ES2015 */ ? setTextRange(createIdentifier("_super"), callee) : callee;
    } else if (getEmitFlags(callee) & 8192 /* HelperName */) {
      thisArg = createVoidZero();
      target = parenthesizerRules().parenthesizeLeftSideOfAccess(
        callee,
        /*optionalChain*/
        false
      );
    } else if (isPropertyAccessExpression(callee)) {
      if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
        thisArg = createTempVariable(recordTempVariable);
        target = createPropertyAccessExpression(
          setTextRange(
            factory2.createAssignment(
              thisArg,
              callee.expression
            ),
            callee.expression
          ),
          callee.name
        );
        setTextRange(target, callee);
      } else {
        thisArg = callee.expression;
        target = callee;
      }
    } else if (isElementAccessExpression(callee)) {
      if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
        thisArg = createTempVariable(recordTempVariable);
        target = createElementAccessExpression(
          setTextRange(
            factory2.createAssignment(
              thisArg,
              callee.expression
            ),
            callee.expression
          ),
          callee.argumentExpression
        );
        setTextRange(target, callee);
      } else {
        thisArg = callee.expression;
        target = callee;
      }
    } else {
      thisArg = createVoidZero();
      target = parenthesizerRules().parenthesizeLeftSideOfAccess(
        expression,
        /*optionalChain*/
        false
      );
    }
    return { target, thisArg };
  }
  function createAssignmentTargetWrapper(paramName, expression) {
    return createPropertyAccessExpression(
      // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
      createParenthesizedExpression(
        createObjectLiteralExpression([
          createSetAccessorDeclaration(
            /*modifiers*/
            void 0,
            "value",
            [createParameterDeclaration(
              /*modifiers*/
              void 0,
              /*dotDotDotToken*/
              void 0,
              paramName,
              /*questionToken*/
              void 0,
              /*type*/
              void 0,
              /*initializer*/
              void 0
            )],
            createBlock([
              createExpressionStatement(expression)
            ])
          )
        ])
      ),
      "value"
    );
  }
  function inlineExpressions(expressions) {
    return expressions.length > 10 ? createCommaListExpression(expressions) : reduceLeft(expressions, factory2.createComma);
  }
  function getName(node, allowComments, allowSourceMaps, emitFlags = 0, ignoreAssignedName) {
    const nodeName = ignoreAssignedName ? node && getNonAssignedNameOfDeclaration(node) : getNameOfDeclaration(node);
    if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) {
      const name = setParent(setTextRange(cloneNode(nodeName), nodeName), nodeName.parent);
      emitFlags |= getEmitFlags(nodeName);
      if (!allowSourceMaps) emitFlags |= 96 /* NoSourceMap */;
      if (!allowComments) emitFlags |= 3072 /* NoComments */;
      if (emitFlags) setEmitFlags(name, emitFlags);
      return name;
    }
    return getGeneratedNameForNode(node);
  }
  function getInternalName(node, allowComments, allowSourceMaps) {
    return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */ | 65536 /* InternalName */);
  }
  function getLocalName(node, allowComments, allowSourceMaps, ignoreAssignedName) {
    return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */, ignoreAssignedName);
  }
  function getExportName(node, allowComments, allowSourceMaps) {
    return getName(node, allowComments, allowSourceMaps, 16384 /* ExportName */);
  }
  function getDeclarationName(node, allowComments, allowSourceMaps) {
    return getName(node, allowComments, allowSourceMaps);
  }
  function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
    const qualifiedName = createPropertyAccessExpression(ns, nodeIsSynthesized(name) ? name : cloneNode(name));
    setTextRange(qualifiedName, name);
    let emitFlags = 0;
    if (!allowSourceMaps) emitFlags |= 96 /* NoSourceMap */;
    if (!allowComments) emitFlags |= 3072 /* NoComments */;
    if (emitFlags) setEmitFlags(qualifiedName, emitFlags);
    return qualifiedName;
  }
  function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
    if (ns && hasSyntacticModifier(node, 32 /* Export */)) {
      return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
    }
    return getExportName(node, allowComments, allowSourceMaps);
  }
  function copyPrologue(source, target, ensureUseStrict2, visitor) {
    const offset = copyStandardPrologue(source, target, 0, ensureUseStrict2);
    return copyCustomPrologue(source, target, offset, visitor);
  }
  function isUseStrictPrologue2(node) {
    return isStringLiteral(node.expression) && node.expression.text === "use strict";
  }
  function createUseStrictPrologue() {
    return startOnNewLine(createExpressionStatement(createStringLiteral("use strict")));
  }
  function copyStandardPrologue(source, target, statementOffset = 0, ensureUseStrict2) {
    Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
    let foundUseStrict = false;
    const numStatements = source.length;
    while (statementOffset < numStatements) {
      const statement = source[statementOffset];
      if (isPrologueDirective(statement)) {
        if (isUseStrictPrologue2(statement)) {
          foundUseStrict = true;
        }
        target.push(statement);
      } else {
        break;
      }
      statementOffset++;
    }
    if (ensureUseStrict2 && !foundUseStrict) {
      target.push(createUseStrictPrologue());
    }
    return statementOffset;
  }
  function copyCustomPrologue(source, target, statementOffset, visitor, filter2 = returnTrue) {
    const numStatements = source.length;
    while (statementOffset !== void 0 && statementOffset < numStatements) {
      const statement = source[statementOffset];
      if (getEmitFlags(statement) & 2097152 /* CustomPrologue */ && filter2(statement)) {
        append(target, visitor ? visitNode(statement, visitor, isStatement) : statement);
      } else {
        break;
      }
      statementOffset++;
    }
    return statementOffset;
  }
  function ensureUseStrict(statements) {
    const foundUseStrict = findUseStrictPrologue(statements);
    if (!foundUseStrict) {
      return setTextRange(createNodeArray([createUseStrictPrologue(), ...statements]), statements);
    }
    return statements;
  }
  function liftToBlock(nodes) {
    Debug.assert(every(nodes, isStatementOrBlock), "Cannot lift nodes to a Block.");
    return singleOrUndefined(nodes) || createBlock(nodes);
  }
  function findSpanEnd(array, test, start) {
    let i = start;
    while (i < array.length && test(array[i])) {
      i++;
    }
    return i;
  }
  function mergeLexicalEnvironment(statements, declarations) {
    if (!some(declarations)) {
      return statements;
    }
    const leftStandardPrologueEnd = findSpanEnd(statements, isPrologueDirective, 0);
    const leftHoistedFunctionsEnd = findSpanEnd(statements, isHoistedFunction, leftStandardPrologueEnd);
    const leftHoistedVariablesEnd = findSpanEnd(statements, isHoistedVariableStatement, leftHoistedFunctionsEnd);
    const rightStandardPrologueEnd = findSpanEnd(declarations, isPrologueDirective, 0);
    const rightHoistedFunctionsEnd = findSpanEnd(declarations, isHoistedFunction, rightStandardPrologueEnd);
    const rightHoistedVariablesEnd = findSpanEnd(declarations, isHoistedVariableStatement, rightHoistedFunctionsEnd);
    const rightCustomPrologueEnd = findSpanEnd(declarations, isCustomPrologue, rightHoistedVariablesEnd);
    Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
    const left = isNodeArray(statements) ? statements.slice() : statements;
    if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
      left.splice(leftHoistedVariablesEnd, 0, ...declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd));
    }
    if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
      left.splice(leftHoistedFunctionsEnd, 0, ...declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd));
    }
    if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
      left.splice(leftStandardPrologueEnd, 0, ...declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd));
    }
    if (rightStandardPrologueEnd > 0) {
      if (leftStandardPrologueEnd === 0) {
        left.splice(0, 0, ...declarations.slice(0, rightStandardPrologueEnd));
      } else {
        const leftPrologues = /* @__PURE__ */ new Map();
        for (let i = 0; i < leftStandardPrologueEnd; i++) {
          const leftPrologue = statements[i];
          leftPrologues.set(leftPrologue.expression.text, true);
        }
        for (let i = rightStandardPrologueEnd - 1; i >= 0; i--) {
          const rightPrologue = declarations[i];
          if (!leftPrologues.has(rightPrologue.expression.text)) {
            left.unshift(rightPrologue);
          }
        }
      }
    }
    if (isNodeArray(statements)) {
      return setTextRange(createNodeArray(left, statements.hasTrailingComma), statements);
    }
    return statements;
  }
  function replaceModifiers(node, modifiers) {
    let modifierArray;
    if (typeof modifiers === "number") {
      modifierArray = createModifiersFromModifierFlags(modifiers);
    } else {
      modifierArray = modifiers;
    }
    return isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.attributes) : isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.attributes) : Debug.assertNever(node);
  }
  function replaceDecoratorsAndModifiers(node, modifierArray) {
    return isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : Debug.assertNever(node);
  }
  function replacePropertyName(node, name) {
    switch (node.kind) {
      case 177 /* GetAccessor */:
        return updateGetAccessorDeclaration(node, node.modifiers, name, node.parameters, node.type, node.body);
      case 178 /* SetAccessor */:
        return updateSetAccessorDeclaration(node, node.modifiers, name, node.parameters, node.body);
      case 174 /* MethodDeclaration */:
        return updateMethodDeclaration(node, node.modifiers, node.asteriskToken, name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body);
      case 173 /* MethodSignature */:
        return updateMethodSignature(node, node.modifiers, name, node.questionToken, node.typeParameters, node.parameters, node.type);
      case 172 /* PropertyDeclaration */:
        return updatePropertyDeclaration(node, node.modifiers, name, node.questionToken ?? node.exclamationToken, node.type, node.initializer);
      case 171 /* PropertySignature */:
        return updatePropertySignature(node, node.modifiers, name, node.questionToken, node.type);
      case 303 /* PropertyAssignment */:
        return updatePropertyAssignment(node, name, node.initializer);
    }
  }
  function asNodeArray(array) {
    return array ? createNodeArray(array) : void 0;
  }
  function asName(name) {
    return typeof name === "string" ? createIdentifier(name) : name;
  }
  function asExpression(value) {
    return typeof value === "string" ? createStringLiteral(value) : typeof value === "number" ? createNumericLiteral(value) : typeof value === "boolean" ? value ? createTrue() : createFalse() : value;
  }
  function asInitializer(node) {
    return node && parenthesizerRules().parenthesizeExpressionForDisallowedComma(node);
  }
  function asToken(value) {
    return typeof value === "number" ? createToken(value) : value;
  }
  function asEmbeddedStatement(statement) {
    return statement && isNotEmittedStatement(statement) ? setTextRange(setOriginal(createEmptyStatement(), statement), statement) : statement;
  }
  function asVariableDeclaration(variableDeclaration) {
    if (typeof variableDeclaration === "string" || variableDeclaration && !isVariableDeclaration(variableDeclaration)) {
      return createVariableDeclaration(
        variableDeclaration,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        /*initializer*/
        void 0
      );
    }
    return variableDeclaration;
  }
  function update(updated, original) {
    if (updated !== original) {
      setOriginal(updated, original);
      setTextRange(updated, original);
    }
    return updated;
  }
}
function getDefaultTagNameForKind(kind) {
  switch (kind) {
    case 344 /* JSDocTypeTag */:
      return "type";
    case 342 /* JSDocReturnTag */:
      return "returns";
    case 343 /* JSDocThisTag */:
      return "this";
    case 340 /* JSDocEnumTag */:
      return "enum";
    case 330 /* JSDocAuthorTag */:
      return "author";
    case 332 /* JSDocClassTag */:
      return "class";
    case 333 /* JSDocPublicTag */:
      return "public";
    case 334 /* JSDocPrivateTag */:
      return "private";
    case 335 /* JSDocProtectedTag */:
      return "protected";
    case 336 /* JSDocReadonlyTag */:
      return "readonly";
    case 337 /* JSDocOverrideTag */:
      return "override";
    case 345 /* JSDocTemplateTag */:
      return "template";
    case 346 /* JSDocTypedefTag */:
      return "typedef";
    case 341 /* JSDocParameterTag */:
      return "param";
    case 348 /* JSDocPropertyTag */:
      return "prop";
    case 338 /* JSDocCallbackTag */:
      return "callback";
    case 339 /* JSDocOverloadTag */:
      return "overload";
    case 328 /* JSDocAugmentsTag */:
      return "augments";
    case 329 /* JSDocImplementsTag */:
      return "implements";
    case 351 /* JSDocImportTag */:
      return "import";
    default:
      return Debug.fail(`Unsupported kind: ${Debug.formatSyntaxKind(kind)}`);
  }
}
var rawTextScanner;
var invalidValueSentinel = {};
function getCookedText(kind, rawText) {
  if (!rawTextScanner) {
    rawTextScanner = createScanner(
      99 /* Latest */,
      /*skipTrivia*/
      false,
      0 /* Standard */
    );
  }
  switch (kind) {
    case 15 /* NoSubstitutionTemplateLiteral */:
      rawTextScanner.setText("`" + rawText + "`");
      break;
    case 16 /* TemplateHead */:
      rawTextScanner.setText("`" + rawText + "${");
      break;
    case 17 /* TemplateMiddle */:
      rawTextScanner.setText("}" + rawText + "${");
      break;
    case 18 /* TemplateTail */:
      rawTextScanner.setText("}" + rawText + "`");
      break;
  }
  let token = rawTextScanner.scan();
  if (token === 20 /* CloseBraceToken */) {
    token = rawTextScanner.reScanTemplateToken(
      /*isTaggedTemplate*/
      false
    );
  }
  if (rawTextScanner.isUnterminated()) {
    rawTextScanner.setText(void 0);
    return invalidValueSentinel;
  }
  let tokenValue;
  switch (token) {
    case 15 /* NoSubstitutionTemplateLiteral */:
    case 16 /* TemplateHead */:
    case 17 /* TemplateMiddle */:
    case 18 /* TemplateTail */:
      tokenValue = rawTextScanner.getTokenValue();
      break;
  }
  if (tokenValue === void 0 || rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
    rawTextScanner.setText(void 0);
    return invalidValueSentinel;
  }
  rawTextScanner.setText(void 0);
  return tokenValue;
}
function propagateNameFlags(node) {
  return node && isIdentifier(node) ? propagateIdentifierNameFlags(node) : propagateChildFlags(node);
}
function propagateIdentifierNameFlags(node) {
  return propagateChildFlags(node) & ~67108864 /* ContainsPossibleTopLevelAwait */;
}
function propagatePropertyNameFlagsOfChild(node, transformFlags) {
  return transformFlags | node.transformFlags & 134234112 /* PropertyNamePropagatingFlags */;
}
function propagateChildFlags(child) {
  if (!child) return 0 /* None */;
  const childFlags = child.transformFlags & ~getTransformFlagsSubtreeExclusions(child.kind);
  return isNamedDeclaration(child) && isPropertyName(child.name) ? propagatePropertyNameFlagsOfChild(child.name, childFlags) : childFlags;
}
function propagateChildrenFlags(children) {
  return children ? children.transformFlags : 0 /* None */;
}
function aggregateChildrenFlags(children) {
  let subtreeFlags = 0 /* None */;
  for (const child of children) {
    subtreeFlags |= propagateChildFlags(child);
  }
  children.transformFlags = subtreeFlags;
}
function getTransformFlagsSubtreeExclusions(kind) {
  if (kind >= 182 /* FirstTypeNode */ && kind <= 205 /* LastTypeNode */) {
    return -2 /* TypeExcludes */;
  }
  switch (kind) {
    case 213 /* CallExpression */:
    case 214 /* NewExpression */:
    case 209 /* ArrayLiteralExpression */:
      return -2147450880 /* ArrayLiteralOrCallOrNewExcludes */;
    case 267 /* ModuleDeclaration */:
      return -1941676032 /* ModuleExcludes */;
    case 169 /* Parameter */:
      return -2147483648 /* ParameterExcludes */;
    case 219 /* ArrowFunction */:
      return -2072174592 /* ArrowFunctionExcludes */;
    case 218 /* FunctionExpression */:
    case 262 /* FunctionDeclaration */:
      return -1937940480 /* FunctionExcludes */;
    case 261 /* VariableDeclarationList */:
      return -2146893824 /* VariableDeclarationListExcludes */;
    case 263 /* ClassDeclaration */:
    case 231 /* ClassExpression */:
      return -2147344384 /* ClassExcludes */;
    case 176 /* Constructor */:
      return -1937948672 /* ConstructorExcludes */;
    case 172 /* PropertyDeclaration */:
      return -2013249536 /* PropertyExcludes */;
    case 174 /* MethodDeclaration */:
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
      return -2005057536 /* MethodOrAccessorExcludes */;
    case 133 /* AnyKeyword */:
    case 150 /* NumberKeyword */:
    case 163 /* BigIntKeyword */:
    case 146 /* NeverKeyword */:
    case 154 /* StringKeyword */:
    case 151 /* ObjectKeyword */:
    case 136 /* BooleanKeyword */:
    case 155 /* SymbolKeyword */:
    case 116 /* VoidKeyword */:
    case 168 /* TypeParameter */:
    case 171 /* PropertySignature */:
    case 173 /* MethodSignature */:
    case 179 /* CallSignature */:
    case 180 /* ConstructSignature */:
    case 181 /* IndexSignature */:
    case 264 /* InterfaceDeclaration */:
    case 265 /* TypeAliasDeclaration */:
      return -2 /* TypeExcludes */;
    case 210 /* ObjectLiteralExpression */:
      return -2147278848 /* ObjectLiteralExcludes */;
    case 299 /* CatchClause */:
      return -2147418112 /* CatchClauseExcludes */;
    case 206 /* ObjectBindingPattern */:
    case 207 /* ArrayBindingPattern */:
      return -2147450880 /* BindingPatternExcludes */;
    case 216 /* TypeAssertionExpression */:
    case 238 /* SatisfiesExpression */:
    case 234 /* AsExpression */:
    case 355 /* PartiallyEmittedExpression */:
    case 217 /* ParenthesizedExpression */:
    case 108 /* SuperKeyword */:
      return -2147483648 /* OuterExpressionExcludes */;
    case 211 /* PropertyAccessExpression */:
    case 212 /* ElementAccessExpression */:
      return -2147483648 /* PropertyAccessExcludes */;
    default:
      return -2147483648 /* NodeExcludes */;
  }
}
var baseFactory = createBaseNodeFactory();
function makeSynthetic(node) {
  node.flags |= 16 /* Synthesized */;
  return node;
}
var syntheticFactory = {
  createBaseSourceFileNode: (kind) => makeSynthetic(baseFactory.createBaseSourceFileNode(kind)),
  createBaseIdentifierNode: (kind) => makeSynthetic(baseFactory.createBaseIdentifierNode(kind)),
  createBasePrivateIdentifierNode: (kind) => makeSynthetic(baseFactory.createBasePrivateIdentifierNode(kind)),
  createBaseTokenNode: (kind) => makeSynthetic(baseFactory.createBaseTokenNode(kind)),
  createBaseNode: (kind) => makeSynthetic(baseFactory.createBaseNode(kind))
};
var factory = createNodeFactory(4 /* NoIndentationOnFreshPropertyAccess */, syntheticFactory);
function setOriginalNode(node, original) {
  if (node.original !== original) {
    node.original = original;
    if (original) {
      const emitNode = original.emitNode;
      if (emitNode) node.emitNode = mergeEmitNode(emitNode, node.emitNode);
    }
  }
  return node;
}
function mergeEmitNode(sourceEmitNode, destEmitNode) {
  const {
    flags,
    internalFlags,
    leadingComments,
    trailingComments,
    commentRange,
    sourceMapRange,
    tokenSourceMapRanges,
    constantValue,
    helpers,
    startsOnNewLine,
    snippetElement,
    classThis,
    assignedName
  } = sourceEmitNode;
  if (!destEmitNode) destEmitNode = {};
  if (flags) {
    destEmitNode.flags = flags;
  }
  if (internalFlags) {
    destEmitNode.internalFlags = internalFlags & ~8 /* Immutable */;
  }
  if (leadingComments) {
    destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments);
  }
  if (trailingComments) {
    destEmitNode.trailingComments = addRange(trailingComments.slice(), destEmitNode.trailingComments);
  }
  if (commentRange) {
    destEmitNode.commentRange = commentRange;
  }
  if (sourceMapRange) {
    destEmitNode.sourceMapRange = sourceMapRange;
  }
  if (tokenSourceMapRanges) {
    destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
  }
  if (constantValue !== void 0) {
    destEmitNode.constantValue = constantValue;
  }
  if (helpers) {
    for (const helper of helpers) {
      destEmitNode.helpers = appendIfUnique(destEmitNode.helpers, helper);
    }
  }
  if (startsOnNewLine !== void 0) {
    destEmitNode.startsOnNewLine = startsOnNewLine;
  }
  if (snippetElement !== void 0) {
    destEmitNode.snippetElement = snippetElement;
  }
  if (classThis) {
    destEmitNode.classThis = classThis;
  }
  if (assignedName) {
    destEmitNode.assignedName = assignedName;
  }
  return destEmitNode;
}
function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
  if (!destRanges) destRanges = [];
  for (const key in sourceRanges) {
    destRanges[key] = sourceRanges[key];
  }
  return destRanges;
}

// src/compiler/factory/emitNode.ts
function getOrCreateEmitNode(node) {
  if (!node.emitNode) {
    if (isParseTreeNode(node)) {
      if (node.kind === 307 /* SourceFile */) {
        return node.emitNode = { annotatedNodes: [node] };
      }
      const sourceFile = getSourceFileOfNode(getParseTreeNode(getSourceFileOfNode(node))) ?? Debug.fail("Could not determine parsed source file.");
      getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
    }
    node.emitNode = {};
  } else {
    Debug.assert(!(node.emitNode.internalFlags & 8 /* Immutable */), "Invalid attempt to mutate an immutable node.");
  }
  return node.emitNode;
}
function disposeEmitNodes(sourceFile) {
  var _a, _b;
  const annotatedNodes = (_b = (_a = getSourceFileOfNode(getParseTreeNode(sourceFile))) == null ? void 0 : _a.emitNode) == null ? void 0 : _b.annotatedNodes;
  if (annotatedNodes) {
    for (const node of annotatedNodes) {
      node.emitNode = void 0;
    }
  }
}
function removeAllComments(node) {
  const emitNode = getOrCreateEmitNode(node);
  emitNode.flags |= 3072 /* NoComments */;
  emitNode.leadingComments = void 0;
  emitNode.trailingComments = void 0;
  return node;
}
function setEmitFlags(node, emitFlags) {
  getOrCreateEmitNode(node).flags = emitFlags;
  return node;
}
function addEmitFlags(node, emitFlags) {
  const emitNode = getOrCreateEmitNode(node);
  emitNode.flags = emitNode.flags | emitFlags;
  return node;
}
function setInternalEmitFlags(node, emitFlags) {
  getOrCreateEmitNode(node).internalFlags = emitFlags;
  return node;
}
function addInternalEmitFlags(node, emitFlags) {
  const emitNode = getOrCreateEmitNode(node);
  emitNode.internalFlags = emitNode.internalFlags | emitFlags;
  return node;
}
function getSourceMapRange(node) {
  var _a;
  return ((_a = node.emitNode) == null ? void 0 : _a.sourceMapRange) ?? node;
}
function setSourceMapRange(node, range) {
  getOrCreateEmitNode(node).sourceMapRange = range;
  return node;
}
function setTokenSourceMapRange(node, token, range) {
  const emitNode = getOrCreateEmitNode(node);
  const tokenSourceMapRanges = emitNode.tokenSourceMapRanges ?? (emitNode.tokenSourceMapRanges = []);
  tokenSourceMapRanges[token] = range;
  return node;
}
function getStartsOnNewLine(node) {
  var _a;
  return (_a = node.emitNode) == null ? void 0 : _a.startsOnNewLine;
}
function setStartsOnNewLine(node, newLine) {
  getOrCreateEmitNode(node).startsOnNewLine = newLine;
  return node;
}
function getCommentRange(node) {
  var _a;
  return ((_a = node.emitNode) == null ? void 0 : _a.commentRange) ?? node;
}
function setCommentRange(node, range) {
  getOrCreateEmitNode(node).commentRange = range;
  return node;
}
function getSyntheticLeadingComments(node) {
  var _a;
  return (_a = node.emitNode) == null ? void 0 : _a.leadingComments;
}
function setSyntheticLeadingComments(node, comments) {
  getOrCreateEmitNode(node).leadingComments = comments;
  return node;
}
function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
  return setSyntheticLeadingComments(node, append(getSyntheticLeadingComments(node), { kind, pos: -1, end: -1, hasTrailingNewLine, text }));
}
function getSyntheticTrailingComments(node) {
  var _a;
  return (_a = node.emitNode) == null ? void 0 : _a.trailingComments;
}
function setSyntheticTrailingComments(node, comments) {
  getOrCreateEmitNode(node).trailingComments = comments;
  return node;
}
function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
  return setSyntheticTrailingComments(node, append(getSyntheticTrailingComments(node), { kind, pos: -1, end: -1, hasTrailingNewLine, text }));
}
function moveSyntheticComments(node, original) {
  setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
  setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
  const emit = getOrCreateEmitNode(original);
  emit.leadingComments = void 0;
  emit.trailingComments = void 0;
  return node;
}
function getConstantValue(node) {
  var _a;
  return (_a = node.emitNode) == null ? void 0 : _a.constantValue;
}
function setConstantValue(node, value) {
  const emitNode = getOrCreateEmitNode(node);
  emitNode.constantValue = value;
  return node;
}
function addEmitHelper(node, helper) {
  const emitNode = getOrCreateEmitNode(node);
  emitNode.helpers = append(emitNode.helpers, helper);
  return node;
}
function addEmitHelpers(node, helpers) {
  if (some(helpers)) {
    const emitNode = getOrCreateEmitNode(node);
    for (const helper of helpers) {
      emitNode.helpers = appendIfUnique(emitNode.helpers, helper);
    }
  }
  return node;
}
function getEmitHelpers(node) {
  var _a;
  return (_a = node.emitNode) == null ? void 0 : _a.helpers;
}
function moveEmitHelpers(source, target, predicate) {
  const sourceEmitNode = source.emitNode;
  const sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
  if (!some(sourceEmitHelpers)) return;
  const targetEmitNode = getOrCreateEmitNode(target);
  let helpersRemoved = 0;
  for (let i = 0; i < sourceEmitHelpers.length; i++) {
    const helper = sourceEmitHelpers[i];
    if (predicate(helper)) {
      helpersRemoved++;
      targetEmitNode.helpers = appendIfUnique(targetEmitNode.helpers, helper);
    } else if (helpersRemoved > 0) {
      sourceEmitHelpers[i - helpersRemoved] = helper;
    }
  }
  if (helpersRemoved > 0) {
    sourceEmitHelpers.length -= helpersRemoved;
  }
}
function getSnippetElement(node) {
  var _a;
  return (_a = node.emitNode) == null ? void 0 : _a.snippetElement;
}
function setTypeNode(node, type) {
  const emitNode = getOrCreateEmitNode(node);
  emitNode.typeNode = type;
  return node;
}
function getTypeNode(node) {
  var _a;
  return (_a = node.emitNode) == null ? void 0 : _a.typeNode;
}
function setIdentifierTypeArguments(node, typeArguments) {
  getOrCreateEmitNode(node).identifierTypeArguments = typeArguments;
  return node;
}
function getIdentifierTypeArguments(node) {
  var _a;
  return (_a = node.emitNode) == null ? void 0 : _a.identifierTypeArguments;
}
function setIdentifierAutoGenerate(node, autoGenerate) {
  getOrCreateEmitNode(node).autoGenerate = autoGenerate;
  return node;
}
function setIdentifierGeneratedImportReference(node, value) {
  getOrCreateEmitNode(node).generatedImportReference = value;
  return node;
}
function getIdentifierGeneratedImportReference(node) {
  var _a;
  return (_a = node.emitNode) == null ? void 0 : _a.generatedImportReference;
}

// src/compiler/factory/emitHelpers.ts
function createEmitHelperFactory(context) {
  const factory2 = context.factory;
  const immutableTrue = memoize(() => setInternalEmitFlags(factory2.createTrue(), 8 /* Immutable */));
  const immutableFalse = memoize(() => setInternalEmitFlags(factory2.createFalse(), 8 /* Immutable */));
  return {
    getUnscopedHelperName,
    // TypeScript Helpers
    createDecorateHelper,
    createMetadataHelper,
    createParamHelper,
    // ES Decorators Helpers
    createESDecorateHelper,
    createRunInitializersHelper,
    // ES2018 Helpers
    createAssignHelper,
    createAwaitHelper,
    createAsyncGeneratorHelper,
    createAsyncDelegatorHelper,
    createAsyncValuesHelper,
    // ES2018 Destructuring Helpers
    createRestHelper,
    // ES2017 Helpers
    createAwaiterHelper,
    // ES2015 Helpers
    createExtendsHelper,
    createTemplateObjectHelper,
    createSpreadArrayHelper,
    createPropKeyHelper,
    createSetFunctionNameHelper,
    // ES2015 Destructuring Helpers
    createValuesHelper,
    createReadHelper,
    // ES2015 Generator Helpers
    createGeneratorHelper,
    // ES Module Helpers
    createImportStarHelper,
    createImportStarCallbackHelper,
    createImportDefaultHelper,
    createExportStarHelper,
    // Class Fields Helpers
    createClassPrivateFieldGetHelper,
    createClassPrivateFieldSetHelper,
    createClassPrivateFieldInHelper,
    // 'using' helpers
    createAddDisposableResourceHelper,
    createDisposeResourcesHelper,
    // --rewriteRelativeImportExtensions helpers
    createRewriteRelativeImportExtensionsHelper
  };
  function getUnscopedHelperName(name) {
    return setEmitFlags(factory2.createIdentifier(name), 8192 /* HelperName */ | 4 /* AdviseOnEmitNode */);
  }
  function createDecorateHelper(decoratorExpressions, target, memberName, descriptor) {
    context.requestEmitHelper(decorateHelper);
    const argumentsArray = [];
    argumentsArray.push(factory2.createArrayLiteralExpression(
      decoratorExpressions,
      /*multiLine*/
      true
    ));
    argumentsArray.push(target);
    if (memberName) {
      argumentsArray.push(memberName);
      if (descriptor) {
        argumentsArray.push(descriptor);
      }
    }
    return factory2.createCallExpression(
      getUnscopedHelperName("__decorate"),
      /*typeArguments*/
      void 0,
      argumentsArray
    );
  }
  function createMetadataHelper(metadataKey, metadataValue) {
    context.requestEmitHelper(metadataHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__metadata"),
      /*typeArguments*/
      void 0,
      [
        factory2.createStringLiteral(metadataKey),
        metadataValue
      ]
    );
  }
  function createParamHelper(expression, parameterOffset, location) {
    context.requestEmitHelper(paramHelper);
    return setTextRange(
      factory2.createCallExpression(
        getUnscopedHelperName("__param"),
        /*typeArguments*/
        void 0,
        [
          factory2.createNumericLiteral(parameterOffset + ""),
          expression
        ]
      ),
      location
    );
  }
  function createESDecorateClassContextObject(contextIn) {
    const properties = [
      factory2.createPropertyAssignment(factory2.createIdentifier("kind"), factory2.createStringLiteral("class")),
      factory2.createPropertyAssignment(factory2.createIdentifier("name"), contextIn.name),
      factory2.createPropertyAssignment(factory2.createIdentifier("metadata"), contextIn.metadata)
    ];
    return factory2.createObjectLiteralExpression(properties);
  }
  function createESDecorateClassElementAccessGetMethod(elementName) {
    const accessor = elementName.computed ? factory2.createElementAccessExpression(factory2.createIdentifier("obj"), elementName.name) : factory2.createPropertyAccessExpression(factory2.createIdentifier("obj"), elementName.name);
    return factory2.createPropertyAssignment(
      "get",
      factory2.createArrowFunction(
        /*modifiers*/
        void 0,
        /*typeParameters*/
        void 0,
        [factory2.createParameterDeclaration(
          /*modifiers*/
          void 0,
          /*dotDotDotToken*/
          void 0,
          factory2.createIdentifier("obj")
        )],
        /*type*/
        void 0,
        /*equalsGreaterThanToken*/
        void 0,
        accessor
      )
    );
  }
  function createESDecorateClassElementAccessSetMethod(elementName) {
    const accessor = elementName.computed ? factory2.createElementAccessExpression(factory2.createIdentifier("obj"), elementName.name) : factory2.createPropertyAccessExpression(factory2.createIdentifier("obj"), elementName.name);
    return factory2.createPropertyAssignment(
      "set",
      factory2.createArrowFunction(
        /*modifiers*/
        void 0,
        /*typeParameters*/
        void 0,
        [
          factory2.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            factory2.createIdentifier("obj")
          ),
          factory2.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            factory2.createIdentifier("value")
          )
        ],
        /*type*/
        void 0,
        /*equalsGreaterThanToken*/
        void 0,
        factory2.createBlock([
          factory2.createExpressionStatement(
            factory2.createAssignment(
              accessor,
              factory2.createIdentifier("value")
            )
          )
        ])
      )
    );
  }
  function createESDecorateClassElementAccessHasMethod(elementName) {
    const propertyName = elementName.computed ? elementName.name : isIdentifier(elementName.name) ? factory2.createStringLiteralFromNode(elementName.name) : elementName.name;
    return factory2.createPropertyAssignment(
      "has",
      factory2.createArrowFunction(
        /*modifiers*/
        void 0,
        /*typeParameters*/
        void 0,
        [factory2.createParameterDeclaration(
          /*modifiers*/
          void 0,
          /*dotDotDotToken*/
          void 0,
          factory2.createIdentifier("obj")
        )],
        /*type*/
        void 0,
        /*equalsGreaterThanToken*/
        void 0,
        factory2.createBinaryExpression(
          propertyName,
          103 /* InKeyword */,
          factory2.createIdentifier("obj")
        )
      )
    );
  }
  function createESDecorateClassElementAccessObject(name, access) {
    const properties = [];
    properties.push(createESDecorateClassElementAccessHasMethod(name));
    if (access.get) properties.push(createESDecorateClassElementAccessGetMethod(name));
    if (access.set) properties.push(createESDecorateClassElementAccessSetMethod(name));
    return factory2.createObjectLiteralExpression(properties);
  }
  function createESDecorateClassElementContextObject(contextIn) {
    const properties = [
      factory2.createPropertyAssignment(factory2.createIdentifier("kind"), factory2.createStringLiteral(contextIn.kind)),
      factory2.createPropertyAssignment(factory2.createIdentifier("name"), contextIn.name.computed ? contextIn.name.name : factory2.createStringLiteralFromNode(contextIn.name.name)),
      factory2.createPropertyAssignment(factory2.createIdentifier("static"), contextIn.static ? factory2.createTrue() : factory2.createFalse()),
      factory2.createPropertyAssignment(factory2.createIdentifier("private"), contextIn.private ? factory2.createTrue() : factory2.createFalse()),
      factory2.createPropertyAssignment(factory2.createIdentifier("access"), createESDecorateClassElementAccessObject(contextIn.name, contextIn.access)),
      factory2.createPropertyAssignment(factory2.createIdentifier("metadata"), contextIn.metadata)
    ];
    return factory2.createObjectLiteralExpression(properties);
  }
  function createESDecorateContextObject(contextIn) {
    return contextIn.kind === "class" ? createESDecorateClassContextObject(contextIn) : createESDecorateClassElementContextObject(contextIn);
  }
  function createESDecorateHelper(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    context.requestEmitHelper(esDecorateHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__esDecorate"),
      /*typeArguments*/
      void 0,
      [
        ctor ?? factory2.createNull(),
        descriptorIn ?? factory2.createNull(),
        decorators,
        createESDecorateContextObject(contextIn),
        initializers,
        extraInitializers
      ]
    );
  }
  function createRunInitializersHelper(thisArg, initializers, value) {
    context.requestEmitHelper(runInitializersHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__runInitializers"),
      /*typeArguments*/
      void 0,
      value ? [thisArg, initializers, value] : [thisArg, initializers]
    );
  }
  function createAssignHelper(attributesSegments) {
    if (getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
      return factory2.createCallExpression(
        factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "assign"),
        /*typeArguments*/
        void 0,
        attributesSegments
      );
    }
    context.requestEmitHelper(assignHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__assign"),
      /*typeArguments*/
      void 0,
      attributesSegments
    );
  }
  function createAwaitHelper(expression) {
    context.requestEmitHelper(awaitHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__await"),
      /*typeArguments*/
      void 0,
      [expression]
    );
  }
  function createAsyncGeneratorHelper(generatorFunc, hasLexicalThis) {
    context.requestEmitHelper(awaitHelper);
    context.requestEmitHelper(asyncGeneratorHelper);
    (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 524288 /* AsyncFunctionBody */ | 1048576 /* ReuseTempVariableScope */;
    return factory2.createCallExpression(
      getUnscopedHelperName("__asyncGenerator"),
      /*typeArguments*/
      void 0,
      [
        hasLexicalThis ? factory2.createThis() : factory2.createVoidZero(),
        factory2.createIdentifier("arguments"),
        generatorFunc
      ]
    );
  }
  function createAsyncDelegatorHelper(expression) {
    context.requestEmitHelper(awaitHelper);
    context.requestEmitHelper(asyncDelegator);
    return factory2.createCallExpression(
      getUnscopedHelperName("__asyncDelegator"),
      /*typeArguments*/
      void 0,
      [expression]
    );
  }
  function createAsyncValuesHelper(expression) {
    context.requestEmitHelper(asyncValues);
    return factory2.createCallExpression(
      getUnscopedHelperName("__asyncValues"),
      /*typeArguments*/
      void 0,
      [expression]
    );
  }
  function createRestHelper(value, elements, computedTempVariables, location) {
    context.requestEmitHelper(restHelper);
    const propertyNames = [];
    let computedTempVariableOffset = 0;
    for (let i = 0; i < elements.length - 1; i++) {
      const propertyName = getPropertyNameOfBindingOrAssignmentElement(elements[i]);
      if (propertyName) {
        if (isComputedPropertyName(propertyName)) {
          Debug.assertIsDefined(computedTempVariables, "Encountered computed property name but 'computedTempVariables' argument was not provided.");
          const temp = computedTempVariables[computedTempVariableOffset];
          computedTempVariableOffset++;
          propertyNames.push(
            factory2.createConditionalExpression(
              factory2.createTypeCheck(temp, "symbol"),
              /*questionToken*/
              void 0,
              temp,
              /*colonToken*/
              void 0,
              factory2.createAdd(temp, factory2.createStringLiteral(""))
            )
          );
        } else {
          propertyNames.push(factory2.createStringLiteralFromNode(propertyName));
        }
      }
    }
    return factory2.createCallExpression(
      getUnscopedHelperName("__rest"),
      /*typeArguments*/
      void 0,
      [
        value,
        setTextRange(
          factory2.createArrayLiteralExpression(propertyNames),
          location
        )
      ]
    );
  }
  function createAwaiterHelper(hasLexicalThis, argumentsExpression, promiseConstructor, parameters, body) {
    context.requestEmitHelper(awaiterHelper);
    const generatorFunc = factory2.createFunctionExpression(
      /*modifiers*/
      void 0,
      factory2.createToken(42 /* AsteriskToken */),
      /*name*/
      void 0,
      /*typeParameters*/
      void 0,
      parameters ?? [],
      /*type*/
      void 0,
      body
    );
    (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 524288 /* AsyncFunctionBody */ | 1048576 /* ReuseTempVariableScope */;
    return factory2.createCallExpression(
      getUnscopedHelperName("__awaiter"),
      /*typeArguments*/
      void 0,
      [
        hasLexicalThis ? factory2.createThis() : factory2.createVoidZero(),
        argumentsExpression ?? factory2.createVoidZero(),
        promiseConstructor ? createExpressionFromEntityName(factory2, promiseConstructor) : factory2.createVoidZero(),
        generatorFunc
      ]
    );
  }
  function createExtendsHelper(name) {
    context.requestEmitHelper(extendsHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__extends"),
      /*typeArguments*/
      void 0,
      [name, factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */)]
    );
  }
  function createTemplateObjectHelper(cooked, raw) {
    context.requestEmitHelper(templateObjectHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__makeTemplateObject"),
      /*typeArguments*/
      void 0,
      [cooked, raw]
    );
  }
  function createSpreadArrayHelper(to, from, packFrom) {
    context.requestEmitHelper(spreadArrayHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__spreadArray"),
      /*typeArguments*/
      void 0,
      [to, from, packFrom ? immutableTrue() : immutableFalse()]
    );
  }
  function createPropKeyHelper(expr) {
    context.requestEmitHelper(propKeyHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__propKey"),
      /*typeArguments*/
      void 0,
      [expr]
    );
  }
  function createSetFunctionNameHelper(f, name, prefix) {
    context.requestEmitHelper(setFunctionNameHelper);
    return context.factory.createCallExpression(
      getUnscopedHelperName("__setFunctionName"),
      /*typeArguments*/
      void 0,
      prefix ? [f, name, context.factory.createStringLiteral(prefix)] : [f, name]
    );
  }
  function createValuesHelper(expression) {
    context.requestEmitHelper(valuesHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__values"),
      /*typeArguments*/
      void 0,
      [expression]
    );
  }
  function createReadHelper(iteratorRecord, count) {
    context.requestEmitHelper(readHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__read"),
      /*typeArguments*/
      void 0,
      count !== void 0 ? [iteratorRecord, factory2.createNumericLiteral(count + "")] : [iteratorRecord]
    );
  }
  function createGeneratorHelper(body) {
    context.requestEmitHelper(generatorHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__generator"),
      /*typeArguments*/
      void 0,
      [factory2.createThis(), body]
    );
  }
  function createImportStarHelper(expression) {
    context.requestEmitHelper(importStarHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__importStar"),
      /*typeArguments*/
      void 0,
      [expression]
    );
  }
  function createImportStarCallbackHelper() {
    context.requestEmitHelper(importStarHelper);
    return getUnscopedHelperName("__importStar");
  }
  function createImportDefaultHelper(expression) {
    context.requestEmitHelper(importDefaultHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__importDefault"),
      /*typeArguments*/
      void 0,
      [expression]
    );
  }
  function createExportStarHelper(moduleExpression, exportsExpression = factory2.createIdentifier("exports")) {
    context.requestEmitHelper(exportStarHelper);
    context.requestEmitHelper(createBindingHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__exportStar"),
      /*typeArguments*/
      void 0,
      [moduleExpression, exportsExpression]
    );
  }
  function createClassPrivateFieldGetHelper(receiver, state, kind, f) {
    context.requestEmitHelper(classPrivateFieldGetHelper);
    let args;
    if (!f) {
      args = [receiver, state, factory2.createStringLiteral(kind)];
    } else {
      args = [receiver, state, factory2.createStringLiteral(kind), f];
    }
    return factory2.createCallExpression(
      getUnscopedHelperName("__classPrivateFieldGet"),
      /*typeArguments*/
      void 0,
      args
    );
  }
  function createClassPrivateFieldSetHelper(receiver, state, value, kind, f) {
    context.requestEmitHelper(classPrivateFieldSetHelper);
    let args;
    if (!f) {
      args = [receiver, state, value, factory2.createStringLiteral(kind)];
    } else {
      args = [receiver, state, value, factory2.createStringLiteral(kind), f];
    }
    return factory2.createCallExpression(
      getUnscopedHelperName("__classPrivateFieldSet"),
      /*typeArguments*/
      void 0,
      args
    );
  }
  function createClassPrivateFieldInHelper(state, receiver) {
    context.requestEmitHelper(classPrivateFieldInHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__classPrivateFieldIn"),
      /*typeArguments*/
      void 0,
      [state, receiver]
    );
  }
  function createAddDisposableResourceHelper(envBinding, value, async) {
    context.requestEmitHelper(addDisposableResourceHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__addDisposableResource"),
      /*typeArguments*/
      void 0,
      [envBinding, value, async ? factory2.createTrue() : factory2.createFalse()]
    );
  }
  function createDisposeResourcesHelper(envBinding) {
    context.requestEmitHelper(disposeResourcesHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__disposeResources"),
      /*typeArguments*/
      void 0,
      [envBinding]
    );
  }
  function createRewriteRelativeImportExtensionsHelper(expression) {
    context.requestEmitHelper(rewriteRelativeImportExtensionsHelper);
    return factory2.createCallExpression(
      getUnscopedHelperName("__rewriteRelativeImportExtension"),
      /*typeArguments*/
      void 0,
      context.getCompilerOptions().jsx === 1 /* Preserve */ ? [expression, factory2.createTrue()] : [expression]
    );
  }
}
function compareEmitHelpers(x, y) {
  if (x === y) return 0 /* EqualTo */;
  if (x.priority === y.priority) return 0 /* EqualTo */;
  if (x.priority === void 0) return 1 /* GreaterThan */;
  if (y.priority === void 0) return -1 /* LessThan */;
  return compareValues(x.priority, y.priority);
}
function helperString(input, ...args) {
  return (uniqueName) => {
    let result = "";
    for (let i = 0; i < args.length; i++) {
      result += input[i];
      result += uniqueName(args[i]);
    }
    result += input[input.length - 1];
    return result;
  };
}
var decorateHelper = {
  name: "typescript:decorate",
  importName: "__decorate",
  scoped: false,
  priority: 2,
  text: `
            var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
                var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
                if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
                else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
                return c > 3 && r && Object.defineProperty(target, key, r), r;
            };`
};
var metadataHelper = {
  name: "typescript:metadata",
  importName: "__metadata",
  scoped: false,
  priority: 3,
  text: `
            var __metadata = (this && this.__metadata) || function (k, v) {
                if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
            };`
};
var paramHelper = {
  name: "typescript:param",
  importName: "__param",
  scoped: false,
  priority: 4,
  text: `
            var __param = (this && this.__param) || function (paramIndex, decorator) {
                return function (target, key) { decorator(target, key, paramIndex); }
            };`
};
var esDecorateHelper = {
  name: "typescript:esDecorate",
  importName: "__esDecorate",
  scoped: false,
  priority: 2,
  text: `
        var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
            function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
            var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
            var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
            var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
            var _, done = false;
            for (var i = decorators.length - 1; i >= 0; i--) {
                var context = {};
                for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
                for (var p in contextIn.access) context.access[p] = contextIn.access[p];
                context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
                var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
                if (kind === "accessor") {
                    if (result === void 0) continue;
                    if (result === null || typeof result !== "object") throw new TypeError("Object expected");
                    if (_ = accept(result.get)) descriptor.get = _;
                    if (_ = accept(result.set)) descriptor.set = _;
                    if (_ = accept(result.init)) initializers.unshift(_);
                }
                else if (_ = accept(result)) {
                    if (kind === "field") initializers.unshift(_);
                    else descriptor[key] = _;
                }
            }
            if (target) Object.defineProperty(target, contextIn.name, descriptor);
            done = true;
        };`
};
var runInitializersHelper = {
  name: "typescript:runInitializers",
  importName: "__runInitializers",
  scoped: false,
  priority: 2,
  text: `
        var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
            var useValue = arguments.length > 2;
            for (var i = 0; i < initializers.length; i++) {
                value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
            }
            return useValue ? value : void 0;
        };`
};
var assignHelper = {
  name: "typescript:assign",
  importName: "__assign",
  scoped: false,
  priority: 1,
  text: `
            var __assign = (this && this.__assign) || function () {
                __assign = Object.assign || function(t) {
                    for (var s, i = 1, n = arguments.length; i < n; i++) {
                        s = arguments[i];
                        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                            t[p] = s[p];
                    }
                    return t;
                };
                return __assign.apply(this, arguments);
            };`
};
var awaitHelper = {
  name: "typescript:await",
  importName: "__await",
  scoped: false,
  text: `
            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }`
};
var asyncGeneratorHelper = {
  name: "typescript:asyncGenerator",
  importName: "__asyncGenerator",
  scoped: false,
  dependencies: [awaitHelper],
  text: `
        var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
            if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
            var g = generator.apply(thisArg, _arguments || []), i, q = [];
            return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
            function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
            function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
            function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
            function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
            function fulfill(value) { resume("next", value); }
            function reject(value) { resume("throw", value); }
            function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
        };`
};
var asyncDelegator = {
  name: "typescript:asyncDelegator",
  importName: "__asyncDelegator",
  scoped: false,
  dependencies: [awaitHelper],
  text: `
            var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {
                var i, p;
                return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
                function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
            };`
};
var asyncValues = {
  name: "typescript:asyncValues",
  importName: "__asyncValues",
  scoped: false,
  text: `
            var __asyncValues = (this && this.__asyncValues) || function (o) {
                if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
                var m = o[Symbol.asyncIterator], i;
                return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
                function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
                function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
            };`
};
var restHelper = {
  name: "typescript:rest",
  importName: "__rest",
  scoped: false,
  text: `
            var __rest = (this && this.__rest) || function (s, e) {
                var t = {};
                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
                    t[p] = s[p];
                if (s != null && typeof Object.getOwnPropertySymbols === "function")
                    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                        if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                            t[p[i]] = s[p[i]];
                    }
                return t;
            };`
};
var awaiterHelper = {
  name: "typescript:awaiter",
  importName: "__awaiter",
  scoped: false,
  priority: 5,
  text: `
            var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
                function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
                return new (P || (P = Promise))(function (resolve, reject) {
                    function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
                    function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
                    function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
                    step((generator = generator.apply(thisArg, _arguments || [])).next());
                });
            };`
};
var extendsHelper = {
  name: "typescript:extends",
  importName: "__extends",
  scoped: false,
  priority: 0,
  text: `
            var __extends = (this && this.__extends) || (function () {
                var extendStatics = function (d, b) {
                    extendStatics = Object.setPrototypeOf ||
                        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
                        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
                    return extendStatics(d, b);
                };

                return function (d, b) {
                    if (typeof b !== "function" && b !== null)
                        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
                    extendStatics(d, b);
                    function __() { this.constructor = d; }
                    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
                };
            })();`
};
var templateObjectHelper = {
  name: "typescript:makeTemplateObject",
  importName: "__makeTemplateObject",
  scoped: false,
  priority: 0,
  text: `
            var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
                if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
                return cooked;
            };`
};
var readHelper = {
  name: "typescript:read",
  importName: "__read",
  scoped: false,
  text: `
            var __read = (this && this.__read) || function (o, n) {
                var m = typeof Symbol === "function" && o[Symbol.iterator];
                if (!m) return o;
                var i = m.call(o), r, ar = [], e;
                try {
                    while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
                }
                catch (error) { e = { error: error }; }
                finally {
                    try {
                        if (r && !r.done && (m = i["return"])) m.call(i);
                    }
                    finally { if (e) throw e.error; }
                }
                return ar;
            };`
};
var spreadArrayHelper = {
  name: "typescript:spreadArray",
  importName: "__spreadArray",
  scoped: false,
  text: `
            var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
                if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
                    if (ar || !(i in from)) {
                        if (!ar) ar = Array.prototype.slice.call(from, 0, i);
                        ar[i] = from[i];
                    }
                }
                return to.concat(ar || Array.prototype.slice.call(from));
            };`
};
var propKeyHelper = {
  name: "typescript:propKey",
  importName: "__propKey",
  scoped: false,
  text: `
        var __propKey = (this && this.__propKey) || function (x) {
            return typeof x === "symbol" ? x : "".concat(x);
        };`
};
var setFunctionNameHelper = {
  name: "typescript:setFunctionName",
  importName: "__setFunctionName",
  scoped: false,
  text: `
        var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
            if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
            return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
        };`
};
var valuesHelper = {
  name: "typescript:values",
  importName: "__values",
  scoped: false,
  text: `
            var __values = (this && this.__values) || function(o) {
                var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
                if (m) return m.call(o);
                if (o && typeof o.length === "number") return {
                    next: function () {
                        if (o && i >= o.length) o = void 0;
                        return { value: o && o[i++], done: !o };
                    }
                };
                throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
            };`
};
var generatorHelper = {
  name: "typescript:generator",
  importName: "__generator",
  scoped: false,
  priority: 6,
  text: `
            var __generator = (this && this.__generator) || function (thisArg, body) {
                var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
                return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
                function verb(n) { return function (v) { return step([n, v]); }; }
                function step(op) {
                    if (f) throw new TypeError("Generator is already executing.");
                    while (g && (g = 0, op[0] && (_ = 0)), _) try {
                        if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                        if (y = 0, t) op = [op[0] & 2, t.value];
                        switch (op[0]) {
                            case 0: case 1: t = op; break;
                            case 4: _.label++; return { value: op[1], done: false };
                            case 5: _.label++; y = op[1]; op = [0]; continue;
                            case 7: op = _.ops.pop(); _.trys.pop(); continue;
                            default:
                                if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                                if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                                if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                                if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                                if (t[2]) _.ops.pop();
                                _.trys.pop(); continue;
                        }
                        op = body.call(thisArg, _);
                    } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
                    if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
                }
            };`
};
var createBindingHelper = {
  name: "typescript:commonjscreatebinding",
  importName: "__createBinding",
  scoped: false,
  priority: 1,
  text: `
            var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
                if (k2 === undefined) k2 = k;
                var desc = Object.getOwnPropertyDescriptor(m, k);
                if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
                  desc = { enumerable: true, get: function() { return m[k]; } };
                }
                Object.defineProperty(o, k2, desc);
            }) : (function(o, m, k, k2) {
                if (k2 === undefined) k2 = k;
                o[k2] = m[k];
            }));`
};
var setModuleDefaultHelper = {
  name: "typescript:commonjscreatevalue",
  importName: "__setModuleDefault",
  scoped: false,
  priority: 1,
  text: `
            var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
                Object.defineProperty(o, "default", { enumerable: true, value: v });
            }) : function(o, v) {
                o["default"] = v;
            });`
};
var importStarHelper = {
  name: "typescript:commonjsimportstar",
  importName: "__importStar",
  scoped: false,
  dependencies: [createBindingHelper, setModuleDefaultHelper],
  priority: 2,
  text: `
            var __importStar = (this && this.__importStar) || (function () {
                var ownKeys = function(o) {
                    ownKeys = Object.getOwnPropertyNames || function (o) {
                        var ar = [];
                        for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
                        return ar;
                    };
                    return ownKeys(o);
                };
                return function (mod) {
                    if (mod && mod.__esModule) return mod;
                    var result = {};
                    if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
                    __setModuleDefault(result, mod);
                    return result;
                };
            })();`
};
var importDefaultHelper = {
  name: "typescript:commonjsimportdefault",
  importName: "__importDefault",
  scoped: false,
  text: `
            var __importDefault = (this && this.__importDefault) || function (mod) {
                return (mod && mod.__esModule) ? mod : { "default": mod };
            };`
};
var exportStarHelper = {
  name: "typescript:export-star",
  importName: "__exportStar",
  scoped: false,
  dependencies: [createBindingHelper],
  priority: 2,
  text: `
            var __exportStar = (this && this.__exportStar) || function(m, exports) {
                for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
            };`
};
var classPrivateFieldGetHelper = {
  name: "typescript:classPrivateFieldGet",
  importName: "__classPrivateFieldGet",
  scoped: false,
  text: `
            var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
                if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
                if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
                return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
            };`
};
var classPrivateFieldSetHelper = {
  name: "typescript:classPrivateFieldSet",
  importName: "__classPrivateFieldSet",
  scoped: false,
  text: `
            var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
                if (kind === "m") throw new TypeError("Private method is not writable");
                if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
                if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
                return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
            };`
};
var classPrivateFieldInHelper = {
  name: "typescript:classPrivateFieldIn",
  importName: "__classPrivateFieldIn",
  scoped: false,
  text: `
            var __classPrivateFieldIn = (this && this.__classPrivateFieldIn) || function(state, receiver) {
                if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
                return typeof state === "function" ? receiver === state : state.has(receiver);
            };`
};
var addDisposableResourceHelper = {
  name: "typescript:addDisposableResource",
  importName: "__addDisposableResource",
  scoped: false,
  text: `
        var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
            if (value !== null && value !== void 0) {
                if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
                var dispose, inner;
                if (async) {
                    if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
                    dispose = value[Symbol.asyncDispose];
                }
                if (dispose === void 0) {
                    if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
                    dispose = value[Symbol.dispose];
                    if (async) inner = dispose;
                }
                if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
                if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
                env.stack.push({ value: value, dispose: dispose, async: async });
            }
            else if (async) {
                env.stack.push({ async: true });
            }
            return value;
        };`
};
var disposeResourcesHelper = {
  name: "typescript:disposeResources",
  importName: "__disposeResources",
  scoped: false,
  text: `
        var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
            return function (env) {
                function fail(e) {
                    env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
                    env.hasError = true;
                }
                var r, s = 0;
                function next() {
                    while (r = env.stack.pop()) {
                        try {
                            if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                            if (r.dispose) {
                                var result = r.dispose.call(r.value);
                                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                            }
                            else s |= 1;
                        }
                        catch (e) {
                            fail(e);
                        }
                    }
                    if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
                    if (env.hasError) throw env.error;
                }
                return next();
            };
        })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
            var e = new Error(message);
            return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
        });`
};
var rewriteRelativeImportExtensionsHelper = {
  name: "typescript:rewriteRelativeImportExtensions",
  importName: "__rewriteRelativeImportExtension",
  scoped: false,
  text: `
        var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
            if (typeof path === "string" && /^\\.\\.?\\//.test(path)) {
                return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
                    return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
                });
            }
            return path;
        };`
};
var asyncSuperHelper = {
  name: "typescript:async-super",
  scoped: true,
  text: helperString`
            const ${"_superIndex"} = name => super[name];`
};
var advancedAsyncSuperHelper = {
  name: "typescript:advanced-async-super",
  scoped: true,
  text: helperString`
            const ${"_superIndex"} = (function (geti, seti) {
                const cache = Object.create(null);
                return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });
            })(name => super[name], (name, value) => super[name] = value);`
};
function isCallToHelper(firstSegment, helperName) {
  return isCallExpression(firstSegment) && isIdentifier(firstSegment.expression) && (getEmitFlags(firstSegment.expression) & 8192 /* HelperName */) !== 0 && firstSegment.expression.escapedText === helperName;
}

// src/compiler/factory/nodeTests.ts
function isNumericLiteral(node) {
  return node.kind === 9 /* NumericLiteral */;
}
function isBigIntLiteral(node) {
  return node.kind === 10 /* BigIntLiteral */;
}
function isStringLiteral(node) {
  return node.kind === 11 /* StringLiteral */;
}
function isJsxText(node) {
  return node.kind === 12 /* JsxText */;
}
function isNoSubstitutionTemplateLiteral(node) {
  return node.kind === 15 /* NoSubstitutionTemplateLiteral */;
}
function isTemplateHead(node) {
  return node.kind === 16 /* TemplateHead */;
}
function isDotDotDotToken(node) {
  return node.kind === 26 /* DotDotDotToken */;
}
function isCommaToken(node) {
  return node.kind === 28 /* CommaToken */;
}
function isPlusToken(node) {
  return node.kind === 40 /* PlusToken */;
}
function isMinusToken(node) {
  return node.kind === 41 /* MinusToken */;
}
function isAsteriskToken(node) {
  return node.kind === 42 /* AsteriskToken */;
}
function isExclamationToken(node) {
  return node.kind === 54 /* ExclamationToken */;
}
function isQuestionToken(node) {
  return node.kind === 58 /* QuestionToken */;
}
function isColonToken(node) {
  return node.kind === 59 /* ColonToken */;
}
function isQuestionDotToken(node) {
  return node.kind === 29 /* QuestionDotToken */;
}
function isEqualsGreaterThanToken(node) {
  return node.kind === 39 /* EqualsGreaterThanToken */;
}
function isIdentifier(node) {
  return node.kind === 80 /* Identifier */;
}
function isPrivateIdentifier(node) {
  return node.kind === 81 /* PrivateIdentifier */;
}
function isExportModifier(node) {
  return node.kind === 95 /* ExportKeyword */;
}
function isDefaultModifier(node) {
  return node.kind === 90 /* DefaultKeyword */;
}
function isAsyncModifier(node) {
  return node.kind === 134 /* AsyncKeyword */;
}
function isAssertsKeyword(node) {
  return node.kind === 131 /* AssertsKeyword */;
}
function isAwaitKeyword(node) {
  return node.kind === 135 /* AwaitKeyword */;
}
function isReadonlyKeyword(node) {
  return node.kind === 148 /* ReadonlyKeyword */;
}
function isStaticModifier(node) {
  return node.kind === 126 /* StaticKeyword */;
}
function isAccessorModifier(node) {
  return node.kind === 129 /* AccessorKeyword */;
}
function isSuperKeyword(node) {
  return node.kind === 108 /* SuperKeyword */;
}
function isImportKeyword(node) {
  return node.kind === 102 /* ImportKeyword */;
}
function isQualifiedName(node) {
  return node.kind === 166 /* QualifiedName */;
}
function isComputedPropertyName(node) {
  return node.kind === 167 /* ComputedPropertyName */;
}
function isTypeParameterDeclaration(node) {
  return node.kind === 168 /* TypeParameter */;
}
function isParameter(node) {
  return node.kind === 169 /* Parameter */;
}
function isDecorator(node) {
  return node.kind === 170 /* Decorator */;
}
function isPropertySignature(node) {
  return node.kind === 171 /* PropertySignature */;
}
function isPropertyDeclaration(node) {
  return node.kind === 172 /* PropertyDeclaration */;
}
function isMethodSignature(node) {
  return node.kind === 173 /* MethodSignature */;
}
function isMethodDeclaration(node) {
  return node.kind === 174 /* MethodDeclaration */;
}
function isClassStaticBlockDeclaration(node) {
  return node.kind === 175 /* ClassStaticBlockDeclaration */;
}
function isConstructorDeclaration(node) {
  return node.kind === 176 /* Constructor */;
}
function isGetAccessorDeclaration(node) {
  return node.kind === 177 /* GetAccessor */;
}
function isSetAccessorDeclaration(node) {
  return node.kind === 178 /* SetAccessor */;
}
function isCallSignatureDeclaration(node) {
  return node.kind === 179 /* CallSignature */;
}
function isConstructSignatureDeclaration(node) {
  return node.kind === 180 /* ConstructSignature */;
}
function isIndexSignatureDeclaration(node) {
  return node.kind === 181 /* IndexSignature */;
}
function isTypePredicateNode(node) {
  return node.kind === 182 /* TypePredicate */;
}
function isTypeReferenceNode(node) {
  return node.kind === 183 /* TypeReference */;
}
function isFunctionTypeNode(node) {
  return node.kind === 184 /* FunctionType */;
}
function isConstructorTypeNode(node) {
  return node.kind === 185 /* ConstructorType */;
}
function isTypeQueryNode(node) {
  return node.kind === 186 /* TypeQuery */;
}
function isTypeLiteralNode(node) {
  return node.kind === 187 /* TypeLiteral */;
}
function isArrayTypeNode(node) {
  return node.kind === 188 /* ArrayType */;
}
function isTupleTypeNode(node) {
  return node.kind === 189 /* TupleType */;
}
function isNamedTupleMember(node) {
  return node.kind === 202 /* NamedTupleMember */;
}
function isOptionalTypeNode(node) {
  return node.kind === 190 /* OptionalType */;
}
function isRestTypeNode(node) {
  return node.kind === 191 /* RestType */;
}
function isUnionTypeNode(node) {
  return node.kind === 192 /* UnionType */;
}
function isIntersectionTypeNode(node) {
  return node.kind === 193 /* IntersectionType */;
}
function isConditionalTypeNode(node) {
  return node.kind === 194 /* ConditionalType */;
}
function isInferTypeNode(node) {
  return node.kind === 195 /* InferType */;
}
function isParenthesizedTypeNode(node) {
  return node.kind === 196 /* ParenthesizedType */;
}
function isThisTypeNode(node) {
  return node.kind === 197 /* ThisType */;
}
function isTypeOperatorNode(node) {
  return node.kind === 198 /* TypeOperator */;
}
function isIndexedAccessTypeNode(node) {
  return node.kind === 199 /* IndexedAccessType */;
}
function isMappedTypeNode(node) {
  return node.kind === 200 /* MappedType */;
}
function isLiteralTypeNode(node) {
  return node.kind === 201 /* LiteralType */;
}
function isImportTypeNode(node) {
  return node.kind === 205 /* ImportType */;
}
function isTemplateLiteralTypeSpan(node) {
  return node.kind === 204 /* TemplateLiteralTypeSpan */;
}
function isObjectBindingPattern(node) {
  return node.kind === 206 /* ObjectBindingPattern */;
}
function isArrayBindingPattern(node) {
  return node.kind === 207 /* ArrayBindingPattern */;
}
function isBindingElement(node) {
  return node.kind === 208 /* BindingElement */;
}
function isArrayLiteralExpression(node) {
  return node.kind === 209 /* ArrayLiteralExpression */;
}
function isObjectLiteralExpression(node) {
  return node.kind === 210 /* ObjectLiteralExpression */;
}
function isPropertyAccessExpression(node) {
  return node.kind === 211 /* PropertyAccessExpression */;
}
function isElementAccessExpression(node) {
  return node.kind === 212 /* ElementAccessExpression */;
}
function isCallExpression(node) {
  return node.kind === 213 /* CallExpression */;
}
function isNewExpression(node) {
  return node.kind === 214 /* NewExpression */;
}
function isTaggedTemplateExpression(node) {
  return node.kind === 215 /* TaggedTemplateExpression */;
}
function isTypeAssertionExpression(node) {
  return node.kind === 216 /* TypeAssertionExpression */;
}
function isParenthesizedExpression(node) {
  return node.kind === 217 /* ParenthesizedExpression */;
}
function isFunctionExpression(node) {
  return node.kind === 218 /* FunctionExpression */;
}
function isArrowFunction(node) {
  return node.kind === 219 /* ArrowFunction */;
}
function isTypeOfExpression(node) {
  return node.kind === 221 /* TypeOfExpression */;
}
function isVoidExpression(node) {
  return node.kind === 222 /* VoidExpression */;
}
function isAwaitExpression(node) {
  return node.kind === 223 /* AwaitExpression */;
}
function isPrefixUnaryExpression(node) {
  return node.kind === 224 /* PrefixUnaryExpression */;
}
function isPostfixUnaryExpression(node) {
  return node.kind === 225 /* PostfixUnaryExpression */;
}
function isBinaryExpression(node) {
  return node.kind === 226 /* BinaryExpression */;
}
function isConditionalExpression(node) {
  return node.kind === 227 /* ConditionalExpression */;
}
function isSpreadElement(node) {
  return node.kind === 230 /* SpreadElement */;
}
function isClassExpression(node) {
  return node.kind === 231 /* ClassExpression */;
}
function isOmittedExpression(node) {
  return node.kind === 232 /* OmittedExpression */;
}
function isExpressionWithTypeArguments(node) {
  return node.kind === 233 /* ExpressionWithTypeArguments */;
}
function isAsExpression(node) {
  return node.kind === 234 /* AsExpression */;
}
function isSatisfiesExpression(node) {
  return node.kind === 238 /* SatisfiesExpression */;
}
function isNonNullExpression(node) {
  return node.kind === 235 /* NonNullExpression */;
}
function isMetaProperty(node) {
  return node.kind === 236 /* MetaProperty */;
}
function isPartiallyEmittedExpression(node) {
  return node.kind === 355 /* PartiallyEmittedExpression */;
}
function isCommaListExpression(node) {
  return node.kind === 356 /* CommaListExpression */;
}
function isTemplateSpan(node) {
  return node.kind === 239 /* TemplateSpan */;
}
function isSemicolonClassElement(node) {
  return node.kind === 240 /* SemicolonClassElement */;
}
function isBlock(node) {
  return node.kind === 241 /* Block */;
}
function isVariableStatement(node) {
  return node.kind === 243 /* VariableStatement */;
}
function isEmptyStatement(node) {
  return node.kind === 242 /* EmptyStatement */;
}
function isExpressionStatement(node) {
  return node.kind === 244 /* ExpressionStatement */;
}
function isIfStatement(node) {
  return node.kind === 245 /* IfStatement */;
}
function isForStatement(node) {
  return node.kind === 248 /* ForStatement */;
}
function isForInStatement(node) {
  return node.kind === 249 /* ForInStatement */;
}
function isForOfStatement(node) {
  return node.kind === 250 /* ForOfStatement */;
}
function isReturnStatement(node) {
  return node.kind === 253 /* ReturnStatement */;
}
function isWithStatement(node) {
  return node.kind === 254 /* WithStatement */;
}
function isSwitchStatement(node) {
  return node.kind === 255 /* SwitchStatement */;
}
function isLabeledStatement(node) {
  return node.kind === 256 /* LabeledStatement */;
}
function isTryStatement(node) {
  return node.kind === 258 /* TryStatement */;
}
function isVariableDeclaration(node) {
  return node.kind === 260 /* VariableDeclaration */;
}
function isVariableDeclarationList(node) {
  return node.kind === 261 /* VariableDeclarationList */;
}
function isFunctionDeclaration(node) {
  return node.kind === 262 /* FunctionDeclaration */;
}
function isClassDeclaration(node) {
  return node.kind === 263 /* ClassDeclaration */;
}
function isInterfaceDeclaration(node) {
  return node.kind === 264 /* InterfaceDeclaration */;
}
function isTypeAliasDeclaration(node) {
  return node.kind === 265 /* TypeAliasDeclaration */;
}
function isEnumDeclaration(node) {
  return node.kind === 266 /* EnumDeclaration */;
}
function isModuleDeclaration(node) {
  return node.kind === 267 /* ModuleDeclaration */;
}
function isModuleBlock(node) {
  return node.kind === 268 /* ModuleBlock */;
}
function isCaseBlock(node) {
  return node.kind === 269 /* CaseBlock */;
}
function isNamespaceExportDeclaration(node) {
  return node.kind === 270 /* NamespaceExportDeclaration */;
}
function isImportEqualsDeclaration(node) {
  return node.kind === 271 /* ImportEqualsDeclaration */;
}
function isImportDeclaration(node) {
  return node.kind === 272 /* ImportDeclaration */;
}
function isImportClause(node) {
  return node.kind === 273 /* ImportClause */;
}
function isAssertClause(node) {
  return node.kind === 300 /* AssertClause */;
}
function isImportAttributes(node) {
  return node.kind === 300 /* ImportAttributes */;
}
function isImportAttribute(node) {
  return node.kind === 301 /* ImportAttribute */;
}
function isNamespaceImport(node) {
  return node.kind === 274 /* NamespaceImport */;
}
function isNamespaceExport(node) {
  return node.kind === 280 /* NamespaceExport */;
}
function isNamedImports(node) {
  return node.kind === 275 /* NamedImports */;
}
function isImportSpecifier(node) {
  return node.kind === 276 /* ImportSpecifier */;
}
function isExportAssignment(node) {
  return node.kind === 277 /* ExportAssignment */;
}
function isExportDeclaration(node) {
  return node.kind === 278 /* ExportDeclaration */;
}
function isNamedExports(node) {
  return node.kind === 279 /* NamedExports */;
}
function isExportSpecifier(node) {
  return node.kind === 281 /* ExportSpecifier */;
}
function isModuleExportName(node) {
  return node.kind === 80 /* Identifier */ || node.kind === 11 /* StringLiteral */;
}
function isNotEmittedStatement(node) {
  return node.kind === 353 /* NotEmittedStatement */;
}
function isSyntheticReference(node) {
  return node.kind === 357 /* SyntheticReferenceExpression */;
}
function isExternalModuleReference(node) {
  return node.kind === 283 /* ExternalModuleReference */;
}
function isJsxElement(node) {
  return node.kind === 284 /* JsxElement */;
}
function isJsxSelfClosingElement(node) {
  return node.kind === 285 /* JsxSelfClosingElement */;
}
function isJsxOpeningElement(node) {
  return node.kind === 286 /* JsxOpeningElement */;
}
function isJsxClosingElement(node) {
  return node.kind === 287 /* JsxClosingElement */;
}
function isJsxFragment(node) {
  return node.kind === 288 /* JsxFragment */;
}
function isJsxOpeningFragment(node) {
  return node.kind === 289 /* JsxOpeningFragment */;
}
function isJsxClosingFragment(node) {
  return node.kind === 290 /* JsxClosingFragment */;
}
function isJsxAttribute(node) {
  return node.kind === 291 /* JsxAttribute */;
}
function isJsxAttributes(node) {
  return node.kind === 292 /* JsxAttributes */;
}
function isJsxSpreadAttribute(node) {
  return node.kind === 293 /* JsxSpreadAttribute */;
}
function isJsxExpression(node) {
  return node.kind === 294 /* JsxExpression */;
}
function isJsxNamespacedName(node) {
  return node.kind === 295 /* JsxNamespacedName */;
}
function isCaseClause(node) {
  return node.kind === 296 /* CaseClause */;
}
function isDefaultClause(node) {
  return node.kind === 297 /* DefaultClause */;
}
function isHeritageClause(node) {
  return node.kind === 298 /* HeritageClause */;
}
function isCatchClause(node) {
  return node.kind === 299 /* CatchClause */;
}
function isPropertyAssignment(node) {
  return node.kind === 303 /* PropertyAssignment */;
}
function isShorthandPropertyAssignment(node) {
  return node.kind === 304 /* ShorthandPropertyAssignment */;
}
function isSpreadAssignment(node) {
  return node.kind === 305 /* SpreadAssignment */;
}
function isEnumMember(node) {
  return node.kind === 306 /* EnumMember */;
}
function isSourceFile(node) {
  return node.kind === 307 /* SourceFile */;
}
function isBundle(node) {
  return node.kind === 308 /* Bundle */;
}
function isJSDocTypeExpression(node) {
  return node.kind === 309 /* JSDocTypeExpression */;
}
function isJSDocNameReference(node) {
  return node.kind === 310 /* JSDocNameReference */;
}
function isJSDocMemberName(node) {
  return node.kind === 311 /* JSDocMemberName */;
}
function isJSDocAllType(node) {
  return node.kind === 312 /* JSDocAllType */;
}
function isJSDocUnknownType(node) {
  return node.kind === 313 /* JSDocUnknownType */;
}
function isJSDocNullableType(node) {
  return node.kind === 314 /* JSDocNullableType */;
}
function isJSDocNonNullableType(node) {
  return node.kind === 315 /* JSDocNonNullableType */;
}
function isJSDocOptionalType(node) {
  return node.kind === 316 /* JSDocOptionalType */;
}
function isJSDocFunctionType(node) {
  return node.kind === 317 /* JSDocFunctionType */;
}
function isJSDocVariadicType(node) {
  return node.kind === 318 /* JSDocVariadicType */;
}
function isJSDoc(node) {
  return node.kind === 320 /* JSDoc */;
}
function isJSDocTypeLiteral(node) {
  return node.kind === 322 /* JSDocTypeLiteral */;
}
function isJSDocSignature(node) {
  return node.kind === 323 /* JSDocSignature */;
}
function isJSDocAugmentsTag(node) {
  return node.kind === 328 /* JSDocAugmentsTag */;
}
function isJSDocClassTag(node) {
  return node.kind === 332 /* JSDocClassTag */;
}
function isJSDocCallbackTag(node) {
  return node.kind === 338 /* JSDocCallbackTag */;
}
function isJSDocPublicTag(node) {
  return node.kind === 333 /* JSDocPublicTag */;
}
function isJSDocPrivateTag(node) {
  return node.kind === 334 /* JSDocPrivateTag */;
}
function isJSDocProtectedTag(node) {
  return node.kind === 335 /* JSDocProtectedTag */;
}
function isJSDocReadonlyTag(node) {
  return node.kind === 336 /* JSDocReadonlyTag */;
}
function isJSDocOverrideTag(node) {
  return node.kind === 337 /* JSDocOverrideTag */;
}
function isJSDocOverloadTag(node) {
  return node.kind === 339 /* JSDocOverloadTag */;
}
function isJSDocDeprecatedTag(node) {
  return node.kind === 331 /* JSDocDeprecatedTag */;
}
function isJSDocEnumTag(node) {
  return node.kind === 340 /* JSDocEnumTag */;
}
function isJSDocParameterTag(node) {
  return node.kind === 341 /* JSDocParameterTag */;
}
function isJSDocReturnTag(node) {
  return node.kind === 342 /* JSDocReturnTag */;
}
function isJSDocThisTag(node) {
  return node.kind === 343 /* JSDocThisTag */;
}
function isJSDocTypeTag(node) {
  return node.kind === 344 /* JSDocTypeTag */;
}
function isJSDocTemplateTag(node) {
  return node.kind === 345 /* JSDocTemplateTag */;
}
function isJSDocTypedefTag(node) {
  return node.kind === 346 /* JSDocTypedefTag */;
}
function isJSDocPropertyTag(node) {
  return node.kind === 348 /* JSDocPropertyTag */;
}
function isJSDocImplementsTag(node) {
  return node.kind === 329 /* JSDocImplementsTag */;
}
function isJSDocSatisfiesTag(node) {
  return node.kind === 350 /* JSDocSatisfiesTag */;
}
function isJSDocImportTag(node) {
  return node.kind === 351 /* JSDocImportTag */;
}

// src/compiler/factory/nodeChildren.ts
var sourceFileToNodeChildren = /* @__PURE__ */ new WeakMap();
function getNodeChildren(node, sourceFile) {
  var _a;
  const kind = node.kind;
  if (!isNodeKind(kind)) {
    return emptyArray;
  }
  if (kind === 352 /* SyntaxList */) {
    return node._children;
  }
  return (_a = sourceFileToNodeChildren.get(sourceFile)) == null ? void 0 : _a.get(node);
}
function unsetNodeChildren(node, origSourceFile) {
  var _a;
  if (node.kind === 352 /* SyntaxList */) {
    Debug.fail("Did not expect to unset the children of a SyntaxList.");
  }
  (_a = sourceFileToNodeChildren.get(origSourceFile)) == null ? void 0 : _a.delete(node);
}
function transferSourceFileChildren(sourceFile, targetSourceFile) {
  const map2 = sourceFileToNodeChildren.get(sourceFile);
  if (map2 !== void 0) {
    sourceFileToNodeChildren.delete(sourceFile);
    sourceFileToNodeChildren.set(targetSourceFile, map2);
  }
}

// src/compiler/factory/utilities.ts
function createEmptyExports(factory2) {
  return factory2.createExportDeclaration(
    /*modifiers*/
    void 0,
    /*isTypeOnly*/
    false,
    factory2.createNamedExports([]),
    /*moduleSpecifier*/
    void 0
  );
}
function createMemberAccessForPropertyName(factory2, target, memberName, location) {
  if (isComputedPropertyName(memberName)) {
    return setTextRange(factory2.createElementAccessExpression(target, memberName.expression), location);
  } else {
    const expression = setTextRange(
      isMemberName(memberName) ? factory2.createPropertyAccessExpression(target, memberName) : factory2.createElementAccessExpression(target, memberName),
      memberName
    );
    addEmitFlags(expression, 128 /* NoNestedSourceMaps */);
    return expression;
  }
}
function createReactNamespace(reactNamespace, parent) {
  const react = parseNodeFactory.createIdentifier(reactNamespace || "React");
  setParent(react, getParseTreeNode(parent));
  return react;
}
function createJsxFactoryExpressionFromEntityName(factory2, jsxFactory, parent) {
  if (isQualifiedName(jsxFactory)) {
    const left = createJsxFactoryExpressionFromEntityName(factory2, jsxFactory.left, parent);
    const right = factory2.createIdentifier(idText(jsxFactory.right));
    right.escapedText = jsxFactory.right.escapedText;
    return factory2.createPropertyAccessExpression(left, right);
  } else {
    return createReactNamespace(idText(jsxFactory), parent);
  }
}
function createJsxFactoryExpression(factory2, jsxFactoryEntity, reactNamespace, parent) {
  return jsxFactoryEntity ? createJsxFactoryExpressionFromEntityName(factory2, jsxFactoryEntity, parent) : factory2.createPropertyAccessExpression(
    createReactNamespace(reactNamespace, parent),
    "createElement"
  );
}
function createJsxFragmentFactoryExpression(factory2, jsxFragmentFactoryEntity, reactNamespace, parent) {
  return jsxFragmentFactoryEntity ? createJsxFactoryExpressionFromEntityName(factory2, jsxFragmentFactoryEntity, parent) : factory2.createPropertyAccessExpression(
    createReactNamespace(reactNamespace, parent),
    "Fragment"
  );
}
function createExpressionForJsxElement(factory2, callee, tagName, props, children, location) {
  const argumentsList = [tagName];
  if (props) {
    argumentsList.push(props);
  }
  if (children && children.length > 0) {
    if (!props) {
      argumentsList.push(factory2.createNull());
    }
    if (children.length > 1) {
      for (const child of children) {
        startOnNewLine(child);
        argumentsList.push(child);
      }
    } else {
      argumentsList.push(children[0]);
    }
  }
  return setTextRange(
    factory2.createCallExpression(
      callee,
      /*typeArguments*/
      void 0,
      argumentsList
    ),
    location
  );
}
function createExpressionForJsxFragment(factory2, jsxFactoryEntity, jsxFragmentFactoryEntity, reactNamespace, children, parentElement, location) {
  const tagName = createJsxFragmentFactoryExpression(factory2, jsxFragmentFactoryEntity, reactNamespace, parentElement);
  const argumentsList = [tagName, factory2.createNull()];
  if (children && children.length > 0) {
    if (children.length > 1) {
      for (const child of children) {
        startOnNewLine(child);
        argumentsList.push(child);
      }
    } else {
      argumentsList.push(children[0]);
    }
  }
  return setTextRange(
    factory2.createCallExpression(
      createJsxFactoryExpression(factory2, jsxFactoryEntity, reactNamespace, parentElement),
      /*typeArguments*/
      void 0,
      argumentsList
    ),
    location
  );
}
function createForOfBindingStatement(factory2, node, boundValue) {
  if (isVariableDeclarationList(node)) {
    const firstDeclaration = first(node.declarations);
    const updatedDeclaration = factory2.updateVariableDeclaration(
      firstDeclaration,
      firstDeclaration.name,
      /*exclamationToken*/
      void 0,
      /*type*/
      void 0,
      boundValue
    );
    return setTextRange(
      factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.updateVariableDeclarationList(node, [updatedDeclaration])
      ),
      /*location*/
      node
    );
  } else {
    const updatedExpression = setTextRange(
      factory2.createAssignment(node, boundValue),
      /*location*/
      node
    );
    return setTextRange(
      factory2.createExpressionStatement(updatedExpression),
      /*location*/
      node
    );
  }
}
function createExpressionFromEntityName(factory2, node) {
  if (isQualifiedName(node)) {
    const left = createExpressionFromEntityName(factory2, node.left);
    const right = setParent(setTextRange(factory2.cloneNode(node.right), node.right), node.right.parent);
    return setTextRange(factory2.createPropertyAccessExpression(left, right), node);
  } else {
    return setParent(setTextRange(factory2.cloneNode(node), node), node.parent);
  }
}
function createExpressionForPropertyName(factory2, memberName) {
  if (isIdentifier(memberName)) {
    return factory2.createStringLiteralFromNode(memberName);
  } else if (isComputedPropertyName(memberName)) {
    return setParent(setTextRange(factory2.cloneNode(memberName.expression), memberName.expression), memberName.expression.parent);
  } else {
    return setParent(setTextRange(factory2.cloneNode(memberName), memberName), memberName.parent);
  }
}
function createExpressionForAccessorDeclaration(factory2, properties, property, receiver, multiLine) {
  const { firstAccessor, getAccessor, setAccessor } = getAllAccessorDeclarations(properties, property);
  if (property === firstAccessor) {
    return setTextRange(
      factory2.createObjectDefinePropertyCall(
        receiver,
        createExpressionForPropertyName(factory2, property.name),
        factory2.createPropertyDescriptor({
          enumerable: factory2.createFalse(),
          configurable: true,
          get: getAccessor && setTextRange(
            setOriginalNode(
              factory2.createFunctionExpression(
                getModifiers(getAccessor),
                /*asteriskToken*/
                void 0,
                /*name*/
                void 0,
                /*typeParameters*/
                void 0,
                getAccessor.parameters,
                /*type*/
                void 0,
                getAccessor.body
                // TODO: GH#18217
              ),
              getAccessor
            ),
            getAccessor
          ),
          set: setAccessor && setTextRange(
            setOriginalNode(
              factory2.createFunctionExpression(
                getModifiers(setAccessor),
                /*asteriskToken*/
                void 0,
                /*name*/
                void 0,
                /*typeParameters*/
                void 0,
                setAccessor.parameters,
                /*type*/
                void 0,
                setAccessor.body
                // TODO: GH#18217
              ),
              setAccessor
            ),
            setAccessor
          )
        }, !multiLine)
      ),
      firstAccessor
    );
  }
  return void 0;
}
function createExpressionForPropertyAssignment(factory2, property, receiver) {
  return setOriginalNode(
    setTextRange(
      factory2.createAssignment(
        createMemberAccessForPropertyName(
          factory2,
          receiver,
          property.name,
          /*location*/
          property.name
        ),
        property.initializer
      ),
      property
    ),
    property
  );
}
function createExpressionForShorthandPropertyAssignment(factory2, property, receiver) {
  return setOriginalNode(
    setTextRange(
      factory2.createAssignment(
        createMemberAccessForPropertyName(
          factory2,
          receiver,
          property.name,
          /*location*/
          property.name
        ),
        factory2.cloneNode(property.name)
      ),
      /*location*/
      property
    ),
    /*original*/
    property
  );
}
function createExpressionForMethodDeclaration(factory2, method, receiver) {
  return setOriginalNode(
    setTextRange(
      factory2.createAssignment(
        createMemberAccessForPropertyName(
          factory2,
          receiver,
          method.name,
          /*location*/
          method.name
        ),
        setOriginalNode(
          setTextRange(
            factory2.createFunctionExpression(
              getModifiers(method),
              method.asteriskToken,
              /*name*/
              void 0,
              /*typeParameters*/
              void 0,
              method.parameters,
              /*type*/
              void 0,
              method.body
              // TODO: GH#18217
            ),
            /*location*/
            method
          ),
          /*original*/
          method
        )
      ),
      /*location*/
      method
    ),
    /*original*/
    method
  );
}
function createExpressionForObjectLiteralElementLike(factory2, node, property, receiver) {
  if (property.name && isPrivateIdentifier(property.name)) {
    Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
  }
  switch (property.kind) {
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
      return createExpressionForAccessorDeclaration(factory2, node.properties, property, receiver, !!node.multiLine);
    case 303 /* PropertyAssignment */:
      return createExpressionForPropertyAssignment(factory2, property, receiver);
    case 304 /* ShorthandPropertyAssignment */:
      return createExpressionForShorthandPropertyAssignment(factory2, property, receiver);
    case 174 /* MethodDeclaration */:
      return createExpressionForMethodDeclaration(factory2, property, receiver);
  }
}
function expandPreOrPostfixIncrementOrDecrementExpression(factory2, node, expression, recordTempVariable, resultVariable) {
  const operator = node.operator;
  Debug.assert(operator === 46 /* PlusPlusToken */ || operator === 47 /* MinusMinusToken */, "Expected 'node' to be a pre- or post-increment or pre- or post-decrement expression");
  const temp = factory2.createTempVariable(recordTempVariable);
  expression = factory2.createAssignment(temp, expression);
  setTextRange(expression, node.operand);
  let operation = isPrefixUnaryExpression(node) ? factory2.createPrefixUnaryExpression(operator, temp) : factory2.createPostfixUnaryExpression(temp, operator);
  setTextRange(operation, node);
  if (resultVariable) {
    operation = factory2.createAssignment(resultVariable, operation);
    setTextRange(operation, node);
  }
  expression = factory2.createComma(expression, operation);
  setTextRange(expression, node);
  if (isPostfixUnaryExpression(node)) {
    expression = factory2.createComma(expression, temp);
    setTextRange(expression, node);
  }
  return expression;
}
function isInternalName(node) {
  return (getEmitFlags(node) & 65536 /* InternalName */) !== 0;
}
function isLocalName(node) {
  return (getEmitFlags(node) & 32768 /* LocalName */) !== 0;
}
function isExportName(node) {
  return (getEmitFlags(node) & 16384 /* ExportName */) !== 0;
}
function isUseStrictPrologue(node) {
  return isStringLiteral(node.expression) && node.expression.text === "use strict";
}
function findUseStrictPrologue(statements) {
  for (const statement of statements) {
    if (isPrologueDirective(statement)) {
      if (isUseStrictPrologue(statement)) {
        return statement;
      }
    } else {
      break;
    }
  }
  return void 0;
}
function startsWithUseStrict(statements) {
  const firstStatement = firstOrUndefined(statements);
  return firstStatement !== void 0 && isPrologueDirective(firstStatement) && isUseStrictPrologue(firstStatement);
}
function isCommaExpression(node) {
  return node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 28 /* CommaToken */;
}
function isCommaSequence(node) {
  return isCommaExpression(node) || isCommaListExpression(node);
}
function isJSDocTypeAssertion(node) {
  return isParenthesizedExpression(node) && isInJSFile(node) && !!getJSDocTypeTag(node);
}
function getJSDocTypeAssertionType(node) {
  const type = getJSDocType(node);
  Debug.assertIsDefined(type);
  return type;
}
function isOuterExpression(node, kinds = 31 /* All */) {
  switch (node.kind) {
    case 217 /* ParenthesizedExpression */:
      if (kinds & -2147483648 /* ExcludeJSDocTypeAssertion */ && isJSDocTypeAssertion(node)) {
        return false;
      }
      return (kinds & 1 /* Parentheses */) !== 0;
    case 216 /* TypeAssertionExpression */:
    case 234 /* AsExpression */:
    case 238 /* SatisfiesExpression */:
      return (kinds & 2 /* TypeAssertions */) !== 0;
    case 233 /* ExpressionWithTypeArguments */:
      return (kinds & 16 /* ExpressionsWithTypeArguments */) !== 0;
    case 235 /* NonNullExpression */:
      return (kinds & 4 /* NonNullAssertions */) !== 0;
    case 355 /* PartiallyEmittedExpression */:
      return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
  }
  return false;
}
function skipOuterExpressions(node, kinds = 31 /* All */) {
  while (isOuterExpression(node, kinds)) {
    node = node.expression;
  }
  return node;
}
function walkUpOuterExpressions(node, kinds = 31 /* All */) {
  let parent = node.parent;
  while (isOuterExpression(parent, kinds)) {
    parent = parent.parent;
    Debug.assert(parent);
  }
  return parent;
}
function startOnNewLine(node) {
  return setStartsOnNewLine(
    node,
    /*newLine*/
    true
  );
}
function getExternalHelpersModuleName(node) {
  const parseNode = getOriginalNode(node, isSourceFile);
  const emitNode = parseNode && parseNode.emitNode;
  return emitNode && emitNode.externalHelpersModuleName;
}
function hasRecordedExternalHelpers(sourceFile) {
  const parseNode = getOriginalNode(sourceFile, isSourceFile);
  const emitNode = parseNode && parseNode.emitNode;
  return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
}
function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
  if (compilerOptions.importHelpers && isEffectiveExternalModule(sourceFile, compilerOptions)) {
    const moduleKind = getEmitModuleKind(compilerOptions);
    const impliedModuleKind = getImpliedNodeFormatForEmitWorker(sourceFile, compilerOptions);
    const helpers = getImportedHelpers(sourceFile);
    if (moduleKind >= 5 /* ES2015 */ && moduleKind <= 99 /* ESNext */ || impliedModuleKind === 99 /* ESNext */ || impliedModuleKind === void 0 && moduleKind === 200 /* Preserve */) {
      if (helpers) {
        const helperNames = [];
        for (const helper of helpers) {
          const importName = helper.importName;
          if (importName) {
            pushIfUnique(helperNames, importName);
          }
        }
        if (some(helperNames)) {
          helperNames.sort(compareStringsCaseSensitive);
          const namedBindings = nodeFactory.createNamedImports(
            map(helperNames, (name) => isFileLevelUniqueName(sourceFile, name) ? nodeFactory.createImportSpecifier(
              /*isTypeOnly*/
              false,
              /*propertyName*/
              void 0,
              nodeFactory.createIdentifier(name)
            ) : nodeFactory.createImportSpecifier(
              /*isTypeOnly*/
              false,
              nodeFactory.createIdentifier(name),
              helperFactory.getUnscopedHelperName(name)
            ))
          );
          const parseNode = getOriginalNode(sourceFile, isSourceFile);
          const emitNode = getOrCreateEmitNode(parseNode);
          emitNode.externalHelpers = true;
          const externalHelpersImportDeclaration = nodeFactory.createImportDeclaration(
            /*modifiers*/
            void 0,
            nodeFactory.createImportClause(
              /*isTypeOnly*/
              false,
              /*name*/
              void 0,
              namedBindings
            ),
            nodeFactory.createStringLiteral(externalHelpersModuleNameText),
            /*attributes*/
            void 0
          );
          addInternalEmitFlags(externalHelpersImportDeclaration, 2 /* NeverApplyImportHelper */);
          return externalHelpersImportDeclaration;
        }
      }
    } else {
      const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, helpers, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
      if (externalHelpersModuleName) {
        const externalHelpersImportDeclaration = nodeFactory.createImportEqualsDeclaration(
          /*modifiers*/
          void 0,
          /*isTypeOnly*/
          false,
          externalHelpersModuleName,
          nodeFactory.createExternalModuleReference(nodeFactory.createStringLiteral(externalHelpersModuleNameText))
        );
        addInternalEmitFlags(externalHelpersImportDeclaration, 2 /* NeverApplyImportHelper */);
        return externalHelpersImportDeclaration;
      }
    }
  }
}
function getImportedHelpers(sourceFile) {
  return filter(getEmitHelpers(sourceFile), (helper) => !helper.scoped);
}
function getOrCreateExternalHelpersModuleNameIfNeeded(factory2, node, compilerOptions, helpers, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
  const externalHelpersModuleName = getExternalHelpersModuleName(node);
  if (externalHelpersModuleName) {
    return externalHelpersModuleName;
  }
  const create = some(helpers) || (hasExportStarsToExportValues || getESModuleInterop(compilerOptions) && hasImportStarOrImportDefault) && getEmitModuleFormatOfFileWorker(node, compilerOptions) < 4 /* System */;
  if (create) {
    const parseNode = getOriginalNode(node, isSourceFile);
    const emitNode = getOrCreateEmitNode(parseNode);
    return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory2.createUniqueName(externalHelpersModuleNameText));
  }
}
function getLocalNameForExternalImport(factory2, node, sourceFile) {
  const namespaceDeclaration = getNamespaceDeclarationNode(node);
  if (namespaceDeclaration && !isDefaultImport(node) && !isExportNamespaceAsDefaultDeclaration(node)) {
    const name = namespaceDeclaration.name;
    if (name.kind === 11 /* StringLiteral */) {
      return factory2.getGeneratedNameForNode(node);
    }
    return isGeneratedIdentifier(name) ? name : factory2.createIdentifier(getSourceTextOfNodeFromSourceFile(sourceFile, name) || idText(name));
  }
  if (node.kind === 272 /* ImportDeclaration */ && node.importClause) {
    return factory2.getGeneratedNameForNode(node);
  }
  if (node.kind === 278 /* ExportDeclaration */ && node.moduleSpecifier) {
    return factory2.getGeneratedNameForNode(node);
  }
  return void 0;
}
function getExternalModuleNameLiteral(factory2, importNode, sourceFile, host, resolver, compilerOptions) {
  const moduleName = getExternalModuleName(importNode);
  if (moduleName && isStringLiteral(moduleName)) {
    return tryGetModuleNameFromDeclaration(importNode, host, factory2, resolver, compilerOptions) || tryRenameExternalModule(factory2, moduleName, sourceFile) || factory2.cloneNode(moduleName);
  }
  return void 0;
}
function tryRenameExternalModule(factory2, moduleName, sourceFile) {
  const rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
  return rename ? factory2.createStringLiteral(rename) : void 0;
}
function tryGetModuleNameFromFile(factory2, file, host, options) {
  if (!file) {
    return void 0;
  }
  if (file.moduleName) {
    return factory2.createStringLiteral(file.moduleName);
  }
  if (!file.isDeclarationFile && options.outFile) {
    return factory2.createStringLiteral(getExternalModuleNameFromPath(host, file.fileName));
  }
  return void 0;
}
function tryGetModuleNameFromDeclaration(declaration, host, factory2, resolver, compilerOptions) {
  return tryGetModuleNameFromFile(factory2, resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
}
function getInitializerOfBindingOrAssignmentElement(bindingElement) {
  if (isDeclarationBindingElement(bindingElement)) {
    return bindingElement.initializer;
  }
  if (isPropertyAssignment(bindingElement)) {
    const initializer = bindingElement.initializer;
    return isAssignmentExpression(
      initializer,
      /*excludeCompoundAssignment*/
      true
    ) ? initializer.right : void 0;
  }
  if (isShorthandPropertyAssignment(bindingElement)) {
    return bindingElement.objectAssignmentInitializer;
  }
  if (isAssignmentExpression(
    bindingElement,
    /*excludeCompoundAssignment*/
    true
  )) {
    return bindingElement.right;
  }
  if (isSpreadElement(bindingElement)) {
    return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
  }
}
function getTargetOfBindingOrAssignmentElement(bindingElement) {
  if (isDeclarationBindingElement(bindingElement)) {
    return bindingElement.name;
  }
  if (isObjectLiteralElementLike(bindingElement)) {
    switch (bindingElement.kind) {
      case 303 /* PropertyAssignment */:
        return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
      case 304 /* ShorthandPropertyAssignment */:
        return bindingElement.name;
      case 305 /* SpreadAssignment */:
        return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
    }
    return void 0;
  }
  if (isAssignmentExpression(
    bindingElement,
    /*excludeCompoundAssignment*/
    true
  )) {
    return getTargetOfBindingOrAssignmentElement(bindingElement.left);
  }
  if (isSpreadElement(bindingElement)) {
    return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
  }
  return bindingElement;
}
function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
  switch (bindingElement.kind) {
    case 169 /* Parameter */:
    case 208 /* BindingElement */:
      return bindingElement.dotDotDotToken;
    case 230 /* SpreadElement */:
    case 305 /* SpreadAssignment */:
      return bindingElement;
  }
  return void 0;
}
function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
  const propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
  Debug.assert(!!propertyName || isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
  return propertyName;
}
function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
  switch (bindingElement.kind) {
    case 208 /* BindingElement */:
      if (bindingElement.propertyName) {
        const propertyName = bindingElement.propertyName;
        if (isPrivateIdentifier(propertyName)) {
          return Debug.failBadSyntaxKind(propertyName);
        }
        return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName;
      }
      break;
    case 303 /* PropertyAssignment */:
      if (bindingElement.name) {
        const propertyName = bindingElement.name;
        if (isPrivateIdentifier(propertyName)) {
          return Debug.failBadSyntaxKind(propertyName);
        }
        return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName;
      }
      break;
    case 305 /* SpreadAssignment */:
      if (bindingElement.name && isPrivateIdentifier(bindingElement.name)) {
        return Debug.failBadSyntaxKind(bindingElement.name);
      }
      return bindingElement.name;
  }
  const target = getTargetOfBindingOrAssignmentElement(bindingElement);
  if (target && isPropertyName(target)) {
    return target;
  }
}
function isStringOrNumericLiteral(node) {
  const kind = node.kind;
  return kind === 11 /* StringLiteral */ || kind === 9 /* NumericLiteral */;
}
function getElementsOfBindingOrAssignmentPattern(name) {
  switch (name.kind) {
    case 206 /* ObjectBindingPattern */:
    case 207 /* ArrayBindingPattern */:
    case 209 /* ArrayLiteralExpression */:
      return name.elements;
    case 210 /* ObjectLiteralExpression */:
      return name.properties;
  }
}
function getJSDocTypeAliasName(fullName) {
  if (fullName) {
    let rightNode = fullName;
    while (true) {
      if (isIdentifier(rightNode) || !rightNode.body) {
        return isIdentifier(rightNode) ? rightNode : rightNode.name;
      }
      rightNode = rightNode.body;
    }
  }
}
function canHaveIllegalTypeParameters(node) {
  const kind = node.kind;
  return kind === 176 /* Constructor */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */;
}
function canHaveIllegalDecorators(node) {
  const kind = node.kind;
  return kind === 303 /* PropertyAssignment */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 262 /* FunctionDeclaration */ || kind === 176 /* Constructor */ || kind === 181 /* IndexSignature */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 282 /* MissingDeclaration */ || kind === 243 /* VariableStatement */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 278 /* ExportDeclaration */ || kind === 277 /* ExportAssignment */;
}
function canHaveIllegalModifiers(node) {
  const kind = node.kind;
  return kind === 175 /* ClassStaticBlockDeclaration */ || kind === 303 /* PropertyAssignment */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 282 /* MissingDeclaration */ || kind === 270 /* NamespaceExportDeclaration */;
}
function isQuestionOrExclamationToken(node) {
  return isQuestionToken(node) || isExclamationToken(node);
}
function isIdentifierOrThisTypeNode(node) {
  return isIdentifier(node) || isThisTypeNode(node);
}
function isReadonlyKeywordOrPlusOrMinusToken(node) {
  return isReadonlyKeyword(node) || isPlusToken(node) || isMinusToken(node);
}
function isQuestionOrPlusOrMinusToken(node) {
  return isQuestionToken(node) || isPlusToken(node) || isMinusToken(node);
}
function isModuleName(node) {
  return isIdentifier(node) || isStringLiteral(node);
}
function isExponentiationOperator(kind) {
  return kind === 43 /* AsteriskAsteriskToken */;
}
function isMultiplicativeOperator(kind) {
  return kind === 42 /* AsteriskToken */ || kind === 44 /* SlashToken */ || kind === 45 /* PercentToken */;
}
function isMultiplicativeOperatorOrHigher(kind) {
  return isExponentiationOperator(kind) || isMultiplicativeOperator(kind);
}
function isAdditiveOperator(kind) {
  return kind === 40 /* PlusToken */ || kind === 41 /* MinusToken */;
}
function isAdditiveOperatorOrHigher(kind) {
  return isAdditiveOperator(kind) || isMultiplicativeOperatorOrHigher(kind);
}
function isShiftOperator(kind) {
  return kind === 48 /* LessThanLessThanToken */ || kind === 49 /* GreaterThanGreaterThanToken */ || kind === 50 /* GreaterThanGreaterThanGreaterThanToken */;
}
function isShiftOperatorOrHigher(kind) {
  return isShiftOperator(kind) || isAdditiveOperatorOrHigher(kind);
}
function isRelationalOperator(kind) {
  return kind === 30 /* LessThanToken */ || kind === 33 /* LessThanEqualsToken */ || kind === 32 /* GreaterThanToken */ || kind === 34 /* GreaterThanEqualsToken */ || kind === 104 /* InstanceOfKeyword */ || kind === 103 /* InKeyword */;
}
function isRelationalOperatorOrHigher(kind) {
  return isRelationalOperator(kind) || isShiftOperatorOrHigher(kind);
}
function isEqualityOperator(kind) {
  return kind === 35 /* EqualsEqualsToken */ || kind === 37 /* EqualsEqualsEqualsToken */ || kind === 36 /* ExclamationEqualsToken */ || kind === 38 /* ExclamationEqualsEqualsToken */;
}
function isEqualityOperatorOrHigher(kind) {
  return isEqualityOperator(kind) || isRelationalOperatorOrHigher(kind);
}
function isBitwiseOperator(kind) {
  return kind === 51 /* AmpersandToken */ || kind === 52 /* BarToken */ || kind === 53 /* CaretToken */;
}
function isBitwiseOperatorOrHigher(kind) {
  return isBitwiseOperator(kind) || isEqualityOperatorOrHigher(kind);
}
function isLogicalOperator2(kind) {
  return kind === 56 /* AmpersandAmpersandToken */ || kind === 57 /* BarBarToken */;
}
function isLogicalOperatorOrHigher(kind) {
  return isLogicalOperator2(kind) || isBitwiseOperatorOrHigher(kind);
}
function isAssignmentOperatorOrHigher(kind) {
  return kind === 61 /* QuestionQuestionToken */ || isLogicalOperatorOrHigher(kind) || isAssignmentOperator(kind);
}
function isBinaryOperator(kind) {
  return isAssignmentOperatorOrHigher(kind) || kind === 28 /* CommaToken */;
}
function isBinaryOperatorToken(node) {
  return isBinaryOperator(node.kind);
}
var BinaryExpressionState;
((BinaryExpressionState2) => {
  function enter(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, outerState) {
    const prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : void 0;
    Debug.assertEqual(stateStack[stackIndex], enter);
    userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState);
    stateStack[stackIndex] = nextState(machine, enter);
    return stackIndex;
  }
  BinaryExpressionState2.enter = enter;
  function left(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) {
    Debug.assertEqual(stateStack[stackIndex], left);
    Debug.assertIsDefined(machine.onLeft);
    stateStack[stackIndex] = nextState(machine, left);
    const nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]);
    if (nextNode) {
      checkCircularity(stackIndex, nodeStack, nextNode);
      return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode);
    }
    return stackIndex;
  }
  BinaryExpressionState2.left = left;
  function operator(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) {
    Debug.assertEqual(stateStack[stackIndex], operator);
    Debug.assertIsDefined(machine.onOperator);
    stateStack[stackIndex] = nextState(machine, operator);
    machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]);
    return stackIndex;
  }
  BinaryExpressionState2.operator = operator;
  function right(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) {
    Debug.assertEqual(stateStack[stackIndex], right);
    Debug.assertIsDefined(machine.onRight);
    stateStack[stackIndex] = nextState(machine, right);
    const nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]);
    if (nextNode) {
      checkCircularity(stackIndex, nodeStack, nextNode);
      return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode);
    }
    return stackIndex;
  }
  BinaryExpressionState2.right = right;
  function exit(machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, _outerState) {
    Debug.assertEqual(stateStack[stackIndex], exit);
    stateStack[stackIndex] = nextState(machine, exit);
    const result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]);
    if (stackIndex > 0) {
      stackIndex--;
      if (machine.foldState) {
        const side = stateStack[stackIndex] === exit ? "right" : "left";
        userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side);
      }
    } else {
      resultHolder.value = result;
    }
    return stackIndex;
  }
  BinaryExpressionState2.exit = exit;
  function done(_machine, stackIndex, stateStack, _nodeStack, _userStateStack, _resultHolder, _outerState) {
    Debug.assertEqual(stateStack[stackIndex], done);
    return stackIndex;
  }
  BinaryExpressionState2.done = done;
  function nextState(machine, currentState) {
    switch (currentState) {
      case enter:
        if (machine.onLeft) return left;
      // falls through
      case left:
        if (machine.onOperator) return operator;
      // falls through
      case operator:
        if (machine.onRight) return right;
      // falls through
      case right:
        return exit;
      case exit:
        return done;
      case done:
        return done;
      default:
        Debug.fail("Invalid state");
    }
  }
  BinaryExpressionState2.nextState = nextState;
  function pushStack(stackIndex, stateStack, nodeStack, userStateStack, node) {
    stackIndex++;
    stateStack[stackIndex] = enter;
    nodeStack[stackIndex] = node;
    userStateStack[stackIndex] = void 0;
    return stackIndex;
  }
  function checkCircularity(stackIndex, nodeStack, node) {
    if (Debug.shouldAssert(2 /* Aggressive */)) {
      while (stackIndex >= 0) {
        Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected.");
        stackIndex--;
      }
    }
  }
})(BinaryExpressionState || (BinaryExpressionState = {}));
var BinaryExpressionStateMachine = class {
  constructor(onEnter, onLeft, onOperator, onRight, onExit, foldState) {
    this.onEnter = onEnter;
    this.onLeft = onLeft;
    this.onOperator = onOperator;
    this.onRight = onRight;
    this.onExit = onExit;
    this.foldState = foldState;
  }
};
function createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState) {
  const machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState);
  return trampoline;
  function trampoline(node, outerState) {
    const resultHolder = { value: void 0 };
    const stateStack = [BinaryExpressionState.enter];
    const nodeStack = [node];
    const userStateStack = [void 0];
    let stackIndex = 0;
    while (stateStack[stackIndex] !== BinaryExpressionState.done) {
      stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState);
    }
    Debug.assertEqual(stackIndex, 0);
    return resultHolder.value;
  }
}
function isExportOrDefaultKeywordKind(kind) {
  return kind === 95 /* ExportKeyword */ || kind === 90 /* DefaultKeyword */;
}
function isExportOrDefaultModifier(node) {
  const kind = node.kind;
  return isExportOrDefaultKeywordKind(kind);
}
function elideNodes(factory2, nodes) {
  if (nodes === void 0) return void 0;
  if (nodes.length === 0) return nodes;
  return setTextRange(factory2.createNodeArray([], nodes.hasTrailingComma), nodes);
}
function getNodeForGeneratedName(name) {
  var _a;
  const autoGenerate = name.emitNode.autoGenerate;
  if (autoGenerate.flags & 4 /* Node */) {
    const autoGenerateId = autoGenerate.id;
    let node = name;
    let original = node.original;
    while (original) {
      node = original;
      const autoGenerate2 = (_a = node.emitNode) == null ? void 0 : _a.autoGenerate;
      if (isMemberName(node) && (autoGenerate2 === void 0 || !!(autoGenerate2.flags & 4 /* Node */) && autoGenerate2.id !== autoGenerateId)) {
        break;
      }
      original = node.original;
    }
    return node;
  }
  return name;
}
function formatGeneratedNamePart(part, generateName) {
  return typeof part === "object" ? formatGeneratedName(
    /*privateName*/
    false,
    part.prefix,
    part.node,
    part.suffix,
    generateName
  ) : typeof part === "string" ? part.length > 0 && part.charCodeAt(0) === 35 /* hash */ ? part.slice(1) : part : "";
}
function formatIdentifier(name, generateName) {
  return typeof name === "string" ? name : formatIdentifierWorker(name, Debug.checkDefined(generateName));
}
function formatIdentifierWorker(node, generateName) {
  return isGeneratedPrivateIdentifier(node) ? generateName(node).slice(1) : isGeneratedIdentifier(node) ? generateName(node) : isPrivateIdentifier(node) ? node.escapedText.slice(1) : idText(node);
}
function formatGeneratedName(privateName, prefix, baseName, suffix, generateName) {
  prefix = formatGeneratedNamePart(prefix, generateName);
  suffix = formatGeneratedNamePart(suffix, generateName);
  baseName = formatIdentifier(baseName, generateName);
  return `${privateName ? "#" : ""}${prefix}${baseName}${suffix}`;
}
function createAccessorPropertyBackingField(factory2, node, modifiers, initializer) {
  return factory2.updatePropertyDeclaration(
    node,
    modifiers,
    factory2.getGeneratedPrivateNameForNode(
      node.name,
      /*prefix*/
      void 0,
      "_accessor_storage"
    ),
    /*questionOrExclamationToken*/
    void 0,
    /*type*/
    void 0,
    initializer
  );
}
function createAccessorPropertyGetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) {
  return factory2.createGetAccessorDeclaration(
    modifiers,
    name,
    [],
    /*type*/
    void 0,
    factory2.createBlock([
      factory2.createReturnStatement(
        factory2.createPropertyAccessExpression(
          receiver,
          factory2.getGeneratedPrivateNameForNode(
            node.name,
            /*prefix*/
            void 0,
            "_accessor_storage"
          )
        )
      )
    ])
  );
}
function createAccessorPropertySetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) {
  return factory2.createSetAccessorDeclaration(
    modifiers,
    name,
    [factory2.createParameterDeclaration(
      /*modifiers*/
      void 0,
      /*dotDotDotToken*/
      void 0,
      "value"
    )],
    factory2.createBlock([
      factory2.createExpressionStatement(
        factory2.createAssignment(
          factory2.createPropertyAccessExpression(
            receiver,
            factory2.getGeneratedPrivateNameForNode(
              node.name,
              /*prefix*/
              void 0,
              "_accessor_storage"
            )
          ),
          factory2.createIdentifier("value")
        )
      )
    ])
  );
}
function findComputedPropertyNameCacheAssignment(name) {
  let node = name.expression;
  while (true) {
    node = skipOuterExpressions(node);
    if (isCommaListExpression(node)) {
      node = last(node.elements);
      continue;
    }
    if (isCommaExpression(node)) {
      node = node.right;
      continue;
    }
    if (isAssignmentExpression(
      node,
      /*excludeCompoundAssignment*/
      true
    ) && isGeneratedIdentifier(node.left)) {
      return node;
    }
    break;
  }
}
function isSyntheticParenthesizedExpression(node) {
  return isParenthesizedExpression(node) && nodeIsSynthesized(node) && !node.emitNode;
}
function flattenCommaListWorker(node, expressions) {
  if (isSyntheticParenthesizedExpression(node)) {
    flattenCommaListWorker(node.expression, expressions);
  } else if (isCommaExpression(node)) {
    flattenCommaListWorker(node.left, expressions);
    flattenCommaListWorker(node.right, expressions);
  } else if (isCommaListExpression(node)) {
    for (const child of node.elements) {
      flattenCommaListWorker(child, expressions);
    }
  } else {
    expressions.push(node);
  }
}
function flattenCommaList(node) {
  const expressions = [];
  flattenCommaListWorker(node, expressions);
  return expressions;
}
function containsObjectRestOrSpread(node) {
  if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */) return true;
  if (node.transformFlags & 128 /* ContainsES2018 */) {
    for (const element of getElementsOfBindingOrAssignmentPattern(node)) {
      const target = getTargetOfBindingOrAssignmentElement(element);
      if (target && isAssignmentPattern(target)) {
        if (target.transformFlags & 65536 /* ContainsObjectRestOrSpread */) {
          return true;
        }
        if (target.transformFlags & 128 /* ContainsES2018 */) {
          if (containsObjectRestOrSpread(target)) return true;
        }
      }
    }
  }
  return false;
}

// src/compiler/factory/utilitiesPublic.ts
function setTextRange(range, location) {
  return location ? setTextRangePosEnd(range, location.pos, location.end) : range;
}
function canHaveModifiers(node) {
  const kind = node.kind;
  return kind === 168 /* TypeParameter */ || kind === 169 /* Parameter */ || kind === 171 /* PropertySignature */ || kind === 172 /* PropertyDeclaration */ || kind === 173 /* MethodSignature */ || kind === 174 /* MethodDeclaration */ || kind === 176 /* Constructor */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 181 /* IndexSignature */ || kind === 185 /* ConstructorType */ || kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */ || kind === 231 /* ClassExpression */ || kind === 243 /* VariableStatement */ || kind === 262 /* FunctionDeclaration */ || kind === 263 /* ClassDeclaration */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 277 /* ExportAssignment */ || kind === 278 /* ExportDeclaration */;
}
function canHaveDecorators(node) {
  const kind = node.kind;
  return kind === 169 /* Parameter */ || kind === 172 /* PropertyDeclaration */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 231 /* ClassExpression */ || kind === 263 /* ClassDeclaration */;
}

// src/compiler/parser.ts
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var PrivateIdentifierConstructor;
var SourceFileConstructor;
var parseBaseNodeFactory = {
  createBaseSourceFileNode: (kind) => new (SourceFileConstructor || (SourceFileConstructor = objectAllocator.getSourceFileConstructor()))(kind, -1, -1),
  createBaseIdentifierNode: (kind) => new (IdentifierConstructor || (IdentifierConstructor = objectAllocator.getIdentifierConstructor()))(kind, -1, -1),
  createBasePrivateIdentifierNode: (kind) => new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1),
  createBaseTokenNode: (kind) => new (TokenConstructor || (TokenConstructor = objectAllocator.getTokenConstructor()))(kind, -1, -1),
  createBaseNode: (kind) => new (NodeConstructor || (NodeConstructor = objectAllocator.getNodeConstructor()))(kind, -1, -1)
};
var parseNodeFactory = createNodeFactory(1 /* NoParenthesizerRules */, parseBaseNodeFactory);
function visitNode2(cbNode, node) {
  return node && cbNode(node);
}
function visitNodes(cbNode, cbNodes, nodes) {
  if (nodes) {
    if (cbNodes) {
      return cbNodes(nodes);
    }
    for (const node of nodes) {
      const result = cbNode(node);
      if (result) {
        return result;
      }
    }
  }
}
function isJSDocLikeText(text, start) {
  return text.charCodeAt(start + 1) === 42 /* asterisk */ && text.charCodeAt(start + 2) === 42 /* asterisk */ && text.charCodeAt(start + 3) !== 47 /* slash */;
}
function isFileProbablyExternalModule(sourceFile) {
  return forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || getImportMetaIfNecessary(sourceFile);
}
function isAnExternalModuleIndicatorNode(node) {
  return canHaveModifiers(node) && hasModifierOfKind(node, 95 /* ExportKeyword */) || isImportEqualsDeclaration(node) && isExternalModuleReference(node.moduleReference) || isImportDeclaration(node) || isExportAssignment(node) || isExportDeclaration(node) ? node : void 0;
}
function getImportMetaIfNecessary(sourceFile) {
  return sourceFile.flags & 8388608 /* PossiblyContainsImportMeta */ ? walkTreeForImportMeta(sourceFile) : void 0;
}
function walkTreeForImportMeta(node) {
  return isImportMeta2(node) ? node : forEachChild(node, walkTreeForImportMeta);
}
function hasModifierOfKind(node, kind) {
  return some(node.modifiers, (m) => m.kind === kind);
}
function isImportMeta2(node) {
  return isMetaProperty(node) && node.keywordToken === 102 /* ImportKeyword */ && node.name.escapedText === "meta";
}
var forEachChildTable = {
  [166 /* QualifiedName */]: function forEachChildInQualifiedName(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.left) || visitNode2(cbNode, node.right);
  },
  [168 /* TypeParameter */]: function forEachChildInTypeParameter(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.constraint) || visitNode2(cbNode, node.default) || visitNode2(cbNode, node.expression);
  },
  [304 /* ShorthandPropertyAssignment */]: function forEachChildInShorthandPropertyAssignment(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.equalsToken) || visitNode2(cbNode, node.objectAssignmentInitializer);
  },
  [305 /* SpreadAssignment */]: function forEachChildInSpreadAssignment(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [169 /* Parameter */]: function forEachChildInParameter(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer);
  },
  [172 /* PropertyDeclaration */]: function forEachChildInPropertyDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer);
  },
  [171 /* PropertySignature */]: function forEachChildInPropertySignature(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer);
  },
  [303 /* PropertyAssignment */]: function forEachChildInPropertyAssignment(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.initializer);
  },
  [260 /* VariableDeclaration */]: function forEachChildInVariableDeclaration(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer);
  },
  [208 /* BindingElement */]: function forEachChildInBindingElement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.propertyName) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.initializer);
  },
  [181 /* IndexSignature */]: function forEachChildInIndexSignature(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type);
  },
  [185 /* ConstructorType */]: function forEachChildInConstructorType(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type);
  },
  [184 /* FunctionType */]: function forEachChildInFunctionType(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type);
  },
  [179 /* CallSignature */]: forEachChildInCallOrConstructSignature,
  [180 /* ConstructSignature */]: forEachChildInCallOrConstructSignature,
  [174 /* MethodDeclaration */]: function forEachChildInMethodDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body);
  },
  [173 /* MethodSignature */]: function forEachChildInMethodSignature(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type);
  },
  [176 /* Constructor */]: function forEachChildInConstructor(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body);
  },
  [177 /* GetAccessor */]: function forEachChildInGetAccessor(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body);
  },
  [178 /* SetAccessor */]: function forEachChildInSetAccessor(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body);
  },
  [262 /* FunctionDeclaration */]: function forEachChildInFunctionDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body);
  },
  [218 /* FunctionExpression */]: function forEachChildInFunctionExpression(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body);
  },
  [219 /* ArrowFunction */]: function forEachChildInArrowFunction(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.equalsGreaterThanToken) || visitNode2(cbNode, node.body);
  },
  [175 /* ClassStaticBlockDeclaration */]: function forEachChildInClassStaticBlockDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.body);
  },
  [183 /* TypeReference */]: function forEachChildInTypeReference(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments);
  },
  [182 /* TypePredicate */]: function forEachChildInTypePredicate(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.assertsModifier) || visitNode2(cbNode, node.parameterName) || visitNode2(cbNode, node.type);
  },
  [186 /* TypeQuery */]: function forEachChildInTypeQuery(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.exprName) || visitNodes(cbNode, cbNodes, node.typeArguments);
  },
  [187 /* TypeLiteral */]: function forEachChildInTypeLiteral(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.members);
  },
  [188 /* ArrayType */]: function forEachChildInArrayType(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.elementType);
  },
  [189 /* TupleType */]: function forEachChildInTupleType(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.elements);
  },
  [192 /* UnionType */]: forEachChildInUnionOrIntersectionType,
  [193 /* IntersectionType */]: forEachChildInUnionOrIntersectionType,
  [194 /* ConditionalType */]: function forEachChildInConditionalType(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.checkType) || visitNode2(cbNode, node.extendsType) || visitNode2(cbNode, node.trueType) || visitNode2(cbNode, node.falseType);
  },
  [195 /* InferType */]: function forEachChildInInferType(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.typeParameter);
  },
  [205 /* ImportType */]: function forEachChildInImportType(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.argument) || visitNode2(cbNode, node.attributes) || visitNode2(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments);
  },
  [302 /* ImportTypeAssertionContainer */]: function forEachChildInImportTypeAssertionContainer(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.assertClause);
  },
  [196 /* ParenthesizedType */]: forEachChildInParenthesizedTypeOrTypeOperator,
  [198 /* TypeOperator */]: forEachChildInParenthesizedTypeOrTypeOperator,
  [199 /* IndexedAccessType */]: function forEachChildInIndexedAccessType(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.objectType) || visitNode2(cbNode, node.indexType);
  },
  [200 /* MappedType */]: function forEachChildInMappedType(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.readonlyToken) || visitNode2(cbNode, node.typeParameter) || visitNode2(cbNode, node.nameType) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type) || visitNodes(cbNode, cbNodes, node.members);
  },
  [201 /* LiteralType */]: function forEachChildInLiteralType(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.literal);
  },
  [202 /* NamedTupleMember */]: function forEachChildInNamedTupleMember(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type);
  },
  [206 /* ObjectBindingPattern */]: forEachChildInObjectOrArrayBindingPattern,
  [207 /* ArrayBindingPattern */]: forEachChildInObjectOrArrayBindingPattern,
  [209 /* ArrayLiteralExpression */]: function forEachChildInArrayLiteralExpression(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.elements);
  },
  [210 /* ObjectLiteralExpression */]: function forEachChildInObjectLiteralExpression(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.properties);
  },
  [211 /* PropertyAccessExpression */]: function forEachChildInPropertyAccessExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.questionDotToken) || visitNode2(cbNode, node.name);
  },
  [212 /* ElementAccessExpression */]: function forEachChildInElementAccessExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.questionDotToken) || visitNode2(cbNode, node.argumentExpression);
  },
  [213 /* CallExpression */]: forEachChildInCallOrNewExpression,
  [214 /* NewExpression */]: forEachChildInCallOrNewExpression,
  [215 /* TaggedTemplateExpression */]: function forEachChildInTaggedTemplateExpression(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.tag) || visitNode2(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode2(cbNode, node.template);
  },
  [216 /* TypeAssertionExpression */]: function forEachChildInTypeAssertionExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.type) || visitNode2(cbNode, node.expression);
  },
  [217 /* ParenthesizedExpression */]: function forEachChildInParenthesizedExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [220 /* DeleteExpression */]: function forEachChildInDeleteExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [221 /* TypeOfExpression */]: function forEachChildInTypeOfExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [222 /* VoidExpression */]: function forEachChildInVoidExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [224 /* PrefixUnaryExpression */]: function forEachChildInPrefixUnaryExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.operand);
  },
  [229 /* YieldExpression */]: function forEachChildInYieldExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.expression);
  },
  [223 /* AwaitExpression */]: function forEachChildInAwaitExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [225 /* PostfixUnaryExpression */]: function forEachChildInPostfixUnaryExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.operand);
  },
  [226 /* BinaryExpression */]: function forEachChildInBinaryExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.left) || visitNode2(cbNode, node.operatorToken) || visitNode2(cbNode, node.right);
  },
  [234 /* AsExpression */]: function forEachChildInAsExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.type);
  },
  [235 /* NonNullExpression */]: function forEachChildInNonNullExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [238 /* SatisfiesExpression */]: function forEachChildInSatisfiesExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.type);
  },
  [236 /* MetaProperty */]: function forEachChildInMetaProperty(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.name);
  },
  [227 /* ConditionalExpression */]: function forEachChildInConditionalExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.condition) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.whenTrue) || visitNode2(cbNode, node.colonToken) || visitNode2(cbNode, node.whenFalse);
  },
  [230 /* SpreadElement */]: function forEachChildInSpreadElement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [241 /* Block */]: forEachChildInBlock,
  [268 /* ModuleBlock */]: forEachChildInBlock,
  [307 /* SourceFile */]: function forEachChildInSourceFile(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.statements) || visitNode2(cbNode, node.endOfFileToken);
  },
  [243 /* VariableStatement */]: function forEachChildInVariableStatement(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.declarationList);
  },
  [261 /* VariableDeclarationList */]: function forEachChildInVariableDeclarationList(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.declarations);
  },
  [244 /* ExpressionStatement */]: function forEachChildInExpressionStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [245 /* IfStatement */]: function forEachChildInIfStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.thenStatement) || visitNode2(cbNode, node.elseStatement);
  },
  [246 /* DoStatement */]: function forEachChildInDoStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.statement) || visitNode2(cbNode, node.expression);
  },
  [247 /* WhileStatement */]: function forEachChildInWhileStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement);
  },
  [248 /* ForStatement */]: function forEachChildInForStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.initializer) || visitNode2(cbNode, node.condition) || visitNode2(cbNode, node.incrementor) || visitNode2(cbNode, node.statement);
  },
  [249 /* ForInStatement */]: function forEachChildInForInStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.initializer) || visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement);
  },
  [250 /* ForOfStatement */]: function forEachChildInForOfStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.awaitModifier) || visitNode2(cbNode, node.initializer) || visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement);
  },
  [251 /* ContinueStatement */]: forEachChildInContinueOrBreakStatement,
  [252 /* BreakStatement */]: forEachChildInContinueOrBreakStatement,
  [253 /* ReturnStatement */]: function forEachChildInReturnStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [254 /* WithStatement */]: function forEachChildInWithStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement);
  },
  [255 /* SwitchStatement */]: function forEachChildInSwitchStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.caseBlock);
  },
  [269 /* CaseBlock */]: function forEachChildInCaseBlock(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.clauses);
  },
  [296 /* CaseClause */]: function forEachChildInCaseClause(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements);
  },
  [297 /* DefaultClause */]: function forEachChildInDefaultClause(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.statements);
  },
  [256 /* LabeledStatement */]: function forEachChildInLabeledStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.label) || visitNode2(cbNode, node.statement);
  },
  [257 /* ThrowStatement */]: function forEachChildInThrowStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [258 /* TryStatement */]: function forEachChildInTryStatement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.tryBlock) || visitNode2(cbNode, node.catchClause) || visitNode2(cbNode, node.finallyBlock);
  },
  [299 /* CatchClause */]: function forEachChildInCatchClause(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.variableDeclaration) || visitNode2(cbNode, node.block);
  },
  [170 /* Decorator */]: function forEachChildInDecorator(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [263 /* ClassDeclaration */]: forEachChildInClassDeclarationOrExpression,
  [231 /* ClassExpression */]: forEachChildInClassDeclarationOrExpression,
  [264 /* InterfaceDeclaration */]: function forEachChildInInterfaceDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members);
  },
  [265 /* TypeAliasDeclaration */]: function forEachChildInTypeAliasDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode2(cbNode, node.type);
  },
  [266 /* EnumDeclaration */]: function forEachChildInEnumDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members);
  },
  [306 /* EnumMember */]: function forEachChildInEnumMember(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.initializer);
  },
  [267 /* ModuleDeclaration */]: function forEachChildInModuleDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.body);
  },
  [271 /* ImportEqualsDeclaration */]: function forEachChildInImportEqualsDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.moduleReference);
  },
  [272 /* ImportDeclaration */]: function forEachChildInImportDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.importClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.attributes);
  },
  [273 /* ImportClause */]: function forEachChildInImportClause(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.namedBindings);
  },
  [300 /* ImportAttributes */]: function forEachChildInImportAttributes(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.elements);
  },
  [301 /* ImportAttribute */]: function forEachChildInImportAttribute(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.value);
  },
  [270 /* NamespaceExportDeclaration */]: function forEachChildInNamespaceExportDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name);
  },
  [274 /* NamespaceImport */]: function forEachChildInNamespaceImport(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.name);
  },
  [280 /* NamespaceExport */]: function forEachChildInNamespaceExport(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.name);
  },
  [275 /* NamedImports */]: forEachChildInNamedImportsOrExports,
  [279 /* NamedExports */]: forEachChildInNamedImportsOrExports,
  [278 /* ExportDeclaration */]: function forEachChildInExportDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.exportClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.attributes);
  },
  [276 /* ImportSpecifier */]: forEachChildInImportOrExportSpecifier,
  [281 /* ExportSpecifier */]: forEachChildInImportOrExportSpecifier,
  [277 /* ExportAssignment */]: function forEachChildInExportAssignment(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.expression);
  },
  [228 /* TemplateExpression */]: function forEachChildInTemplateExpression(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
  },
  [239 /* TemplateSpan */]: function forEachChildInTemplateSpan(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.literal);
  },
  [203 /* TemplateLiteralType */]: function forEachChildInTemplateLiteralType(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
  },
  [204 /* TemplateLiteralTypeSpan */]: function forEachChildInTemplateLiteralTypeSpan(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.type) || visitNode2(cbNode, node.literal);
  },
  [167 /* ComputedPropertyName */]: function forEachChildInComputedPropertyName(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [298 /* HeritageClause */]: function forEachChildInHeritageClause(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.types);
  },
  [233 /* ExpressionWithTypeArguments */]: function forEachChildInExpressionWithTypeArguments(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments);
  },
  [283 /* ExternalModuleReference */]: function forEachChildInExternalModuleReference(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [282 /* MissingDeclaration */]: function forEachChildInMissingDeclaration(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.modifiers);
  },
  [356 /* CommaListExpression */]: function forEachChildInCommaListExpression(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.elements);
  },
  [284 /* JsxElement */]: function forEachChildInJsxElement(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode2(cbNode, node.closingElement);
  },
  [288 /* JsxFragment */]: function forEachChildInJsxFragment(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode2(cbNode, node.closingFragment);
  },
  [285 /* JsxSelfClosingElement */]: forEachChildInJsxOpeningOrSelfClosingElement,
  [286 /* JsxOpeningElement */]: forEachChildInJsxOpeningOrSelfClosingElement,
  [292 /* JsxAttributes */]: function forEachChildInJsxAttributes(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.properties);
  },
  [291 /* JsxAttribute */]: function forEachChildInJsxAttribute(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.initializer);
  },
  [293 /* JsxSpreadAttribute */]: function forEachChildInJsxSpreadAttribute(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.expression);
  },
  [294 /* JsxExpression */]: function forEachChildInJsxExpression(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.expression);
  },
  [287 /* JsxClosingElement */]: function forEachChildInJsxClosingElement(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.tagName);
  },
  [295 /* JsxNamespacedName */]: function forEachChildInJsxNamespacedName(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.namespace) || visitNode2(cbNode, node.name);
  },
  [190 /* OptionalType */]: forEachChildInOptionalRestOrJSDocParameterModifier,
  [191 /* RestType */]: forEachChildInOptionalRestOrJSDocParameterModifier,
  [309 /* JSDocTypeExpression */]: forEachChildInOptionalRestOrJSDocParameterModifier,
  [315 /* JSDocNonNullableType */]: forEachChildInOptionalRestOrJSDocParameterModifier,
  [314 /* JSDocNullableType */]: forEachChildInOptionalRestOrJSDocParameterModifier,
  [316 /* JSDocOptionalType */]: forEachChildInOptionalRestOrJSDocParameterModifier,
  [318 /* JSDocVariadicType */]: forEachChildInOptionalRestOrJSDocParameterModifier,
  [317 /* JSDocFunctionType */]: function forEachChildInJSDocFunctionType(node, cbNode, cbNodes) {
    return visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type);
  },
  [320 /* JSDoc */]: function forEachChildInJSDoc(node, cbNode, cbNodes) {
    return (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)) || visitNodes(cbNode, cbNodes, node.tags);
  },
  [347 /* JSDocSeeTag */]: function forEachChildInJSDocSeeTag(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.name) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment));
  },
  [310 /* JSDocNameReference */]: function forEachChildInJSDocNameReference(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.name);
  },
  [311 /* JSDocMemberName */]: function forEachChildInJSDocMemberName(node, cbNode, _cbNodes) {
    return visitNode2(cbNode, node.left) || visitNode2(cbNode, node.right);
  },
  [341 /* JSDocParameterTag */]: forEachChildInJSDocParameterOrPropertyTag,
  [348 /* JSDocPropertyTag */]: forEachChildInJSDocParameterOrPropertyTag,
  [330 /* JSDocAuthorTag */]: function forEachChildInJSDocAuthorTag(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.tagName) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment));
  },
  [329 /* JSDocImplementsTag */]: function forEachChildInJSDocImplementsTag(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.class) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment));
  },
  [328 /* JSDocAugmentsTag */]: function forEachChildInJSDocAugmentsTag(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.class) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment));
  },
  [345 /* JSDocTemplateTag */]: function forEachChildInJSDocTemplateTag(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment));
  },
  [346 /* JSDocTypedefTag */]: function forEachChildInJSDocTypedefTag(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.tagName) || (node.typeExpression && node.typeExpression.kind === 309 /* JSDocTypeExpression */ ? visitNode2(cbNode, node.typeExpression) || visitNode2(cbNode, node.fullName) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)) : visitNode2(cbNode, node.fullName) || visitNode2(cbNode, node.typeExpression) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)));
  },
  [338 /* JSDocCallbackTag */]: function forEachChildInJSDocCallbackTag(node, cbNode, cbNodes) {
    return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.fullName) || visitNode2(cbNode, node.typeExpression) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment));
  },
  [342 /* JSDocReturnTag */]: forEachChildInJSDocTypeLikeTag,
  [344 /* JSDocTypeTag */]: forEachChildInJSDocTypeLikeTag,
  [343 /* JSDocThisTag */]: forEachChildInJSDocTypeLikeTag,
  [340 /* JSDocEnumTag */]: forEachChildInJSDocTypeLikeTag,
  [350 /* JSDocSatisfiesTag */]: forEachChildInJSDocTypeLikeTag,
  [349 /* JSDocThrowsTag */]: forEachChildInJSDocTypeLikeTag,
  [339 /* JSDocOverloadTag */]: forEachChildInJSDocTypeLikeTag,
  [323 /* JSDocSignature */]: function forEachChildInJSDocSignature(node, cbNode, _cbNodes) {
    return forEach(node.typeParameters, cbNode) || forEach(node.parameters, cbNode) || visitNode2(cbNode, node.type);
  },
  [324 /* JSDocLink */]: forEachChildInJSDocLinkCodeOrPlain,
  [325 /* JSDocLinkCode */]: forEachChildInJSDocLinkCodeOrPlain,
  [326 /* JSDocLinkPlain */]: forEachChildInJSDocLinkCodeOrPlain,
  [322 /* JSDocTypeLiteral */]: function forEachChildInJSDocTypeLiteral(node, cbNode, _cbNodes) {
    return forEach(node.jsDocPropertyTags, cbNode);
  },
  [327 /* JSDocTag */]: forEachChildInJSDocTag,
  [332 /* JSDocClassTag */]: forEachChildInJSDocTag,
  [333 /* JSDocPublicTag */]: forEachChildInJSDocTag,
  [334 /* JSDocPrivateTag */]: forEachChildInJSDocTag,
  [335 /* JSDocProtectedTag */]: forEachChildInJSDocTag,
  [336 /* JSDocReadonlyTag */]: forEachChildInJSDocTag,
  [331 /* JSDocDeprecatedTag */]: forEachChildInJSDocTag,
  [337 /* JSDocOverrideTag */]: forEachChildInJSDocTag,
  [351 /* JSDocImportTag */]: forEachChildInJSDocImportTag,
  [355 /* PartiallyEmittedExpression */]: forEachChildInPartiallyEmittedExpression
};
function forEachChildInCallOrConstructSignature(node, cbNode, cbNodes) {
  return visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type);
}
function forEachChildInUnionOrIntersectionType(node, cbNode, cbNodes) {
  return visitNodes(cbNode, cbNodes, node.types);
}
function forEachChildInParenthesizedTypeOrTypeOperator(node, cbNode, _cbNodes) {
  return visitNode2(cbNode, node.type);
}
function forEachChildInObjectOrArrayBindingPattern(node, cbNode, cbNodes) {
  return visitNodes(cbNode, cbNodes, node.elements);
}
function forEachChildInCallOrNewExpression(node, cbNode, cbNodes) {
  return visitNode2(cbNode, node.expression) || // TODO: should we separate these branches out?
  visitNode2(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments);
}
function forEachChildInBlock(node, cbNode, cbNodes) {
  return visitNodes(cbNode, cbNodes, node.statements);
}
function forEachChildInContinueOrBreakStatement(node, cbNode, _cbNodes) {
  return visitNode2(cbNode, node.label);
}
function forEachChildInClassDeclarationOrExpression(node, cbNode, cbNodes) {
  return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members);
}
function forEachChildInNamedImportsOrExports(node, cbNode, cbNodes) {
  return visitNodes(cbNode, cbNodes, node.elements);
}
function forEachChildInImportOrExportSpecifier(node, cbNode, _cbNodes) {
  return visitNode2(cbNode, node.propertyName) || visitNode2(cbNode, node.name);
}
function forEachChildInJsxOpeningOrSelfClosingElement(node, cbNode, cbNodes) {
  return visitNode2(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode2(cbNode, node.attributes);
}
function forEachChildInOptionalRestOrJSDocParameterModifier(node, cbNode, _cbNodes) {
  return visitNode2(cbNode, node.type);
}
function forEachChildInJSDocParameterOrPropertyTag(node, cbNode, cbNodes) {
  return visitNode2(cbNode, node.tagName) || (node.isNameFirst ? visitNode2(cbNode, node.name) || visitNode2(cbNode, node.typeExpression) : visitNode2(cbNode, node.typeExpression) || visitNode2(cbNode, node.name)) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment));
}
function forEachChildInJSDocTypeLikeTag(node, cbNode, cbNodes) {
  return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.typeExpression) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment));
}
function forEachChildInJSDocLinkCodeOrPlain(node, cbNode, _cbNodes) {
  return visitNode2(cbNode, node.name);
}
function forEachChildInJSDocTag(node, cbNode, cbNodes) {
  return visitNode2(cbNode, node.tagName) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment));
}
function forEachChildInJSDocImportTag(node, cbNode, cbNodes) {
  return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.importClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.attributes) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment));
}
function forEachChildInPartiallyEmittedExpression(node, cbNode, _cbNodes) {
  return visitNode2(cbNode, node.expression);
}
function forEachChild(node, cbNode, cbNodes) {
  if (node === void 0 || node.kind <= 165 /* LastToken */) {
    return;
  }
  const fn = forEachChildTable[node.kind];
  return fn === void 0 ? void 0 : fn(node, cbNode, cbNodes);
}
function forEachChildRecursively(rootNode, cbNode, cbNodes) {
  const queue = gatherPossibleChildren(rootNode);
  const parents = [];
  while (parents.length < queue.length) {
    parents.push(rootNode);
  }
  while (queue.length !== 0) {
    const current = queue.pop();
    const parent = parents.pop();
    if (isArray(current)) {
      if (cbNodes) {
        const res = cbNodes(current, parent);
        if (res) {
          if (res === "skip") continue;
          return res;
        }
      }
      for (let i = current.length - 1; i >= 0; --i) {
        queue.push(current[i]);
        parents.push(parent);
      }
    } else {
      const res = cbNode(current, parent);
      if (res) {
        if (res === "skip") continue;
        return res;
      }
      if (current.kind >= 166 /* FirstNode */) {
        for (const child of gatherPossibleChildren(current)) {
          queue.push(child);
          parents.push(current);
        }
      }
    }
  }
}
function gatherPossibleChildren(node) {
  const children = [];
  forEachChild(node, addWorkItem, addWorkItem);
  return children;
  function addWorkItem(n) {
    children.unshift(n);
  }
}
function setExternalModuleIndicator(sourceFile) {
  sourceFile.externalModuleIndicator = isFileProbablyExternalModule(sourceFile);
}
function createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes = false, scriptKind) {
  var _a, _b;
  (_a = tracing) == null ? void 0 : _a.push(
    tracing.Phase.Parse,
    "createSourceFile",
    { path: fileName },
    /*separateBeginAndEnd*/
    true
  );
  mark("beforeParse");
  let result;
  const {
    languageVersion,
    setExternalModuleIndicator: overrideSetExternalModuleIndicator,
    impliedNodeFormat: format,
    jsDocParsingMode
  } = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : { languageVersion: languageVersionOrOptions };
  if (languageVersion === 100 /* JSON */) {
    result = Parser.parseSourceFile(
      fileName,
      sourceText,
      languageVersion,
      /*syntaxCursor*/
      void 0,
      setParentNodes,
      6 /* JSON */,
      noop,
      jsDocParsingMode
    );
  } else {
    const setIndicator = format === void 0 ? overrideSetExternalModuleIndicator : (file) => {
      file.impliedNodeFormat = format;
      return (overrideSetExternalModuleIndicator || setExternalModuleIndicator)(file);
    };
    result = Parser.parseSourceFile(
      fileName,
      sourceText,
      languageVersion,
      /*syntaxCursor*/
      void 0,
      setParentNodes,
      scriptKind,
      setIndicator,
      jsDocParsingMode
    );
  }
  mark("afterParse");
  measure("Parse", "beforeParse", "afterParse");
  (_b = tracing) == null ? void 0 : _b.pop();
  return result;
}
function parseIsolatedEntityName(text, languageVersion) {
  return Parser.parseIsolatedEntityName(text, languageVersion);
}
function parseJsonText(fileName, sourceText) {
  return Parser.parseJsonText(fileName, sourceText);
}
function isExternalModule(file) {
  return file.externalModuleIndicator !== void 0;
}
var Parser;
((Parser2) => {
  var scanner = createScanner(
    99 /* Latest */,
    /*skipTrivia*/
    true
  );
  var disallowInAndDecoratorContext = 8192 /* DisallowInContext */ | 32768 /* DecoratorContext */;
  var NodeConstructor2;
  var TokenConstructor2;
  var IdentifierConstructor2;
  var PrivateIdentifierConstructor2;
  var SourceFileConstructor2;
  function countNode(node) {
    nodeCount++;
    return node;
  }
  var baseNodeFactory = {
    createBaseSourceFileNode: (kind) => countNode(new SourceFileConstructor2(
      kind,
      /*pos*/
      0,
      /*end*/
      0
    )),
    createBaseIdentifierNode: (kind) => countNode(new IdentifierConstructor2(
      kind,
      /*pos*/
      0,
      /*end*/
      0
    )),
    createBasePrivateIdentifierNode: (kind) => countNode(new PrivateIdentifierConstructor2(
      kind,
      /*pos*/
      0,
      /*end*/
      0
    )),
    createBaseTokenNode: (kind) => countNode(new TokenConstructor2(
      kind,
      /*pos*/
      0,
      /*end*/
      0
    )),
    createBaseNode: (kind) => countNode(new NodeConstructor2(
      kind,
      /*pos*/
      0,
      /*end*/
      0
    ))
  };
  var factory2 = createNodeFactory(1 /* NoParenthesizerRules */ | 2 /* NoNodeConverters */ | 8 /* NoOriginalNode */, baseNodeFactory);
  var {
    createNodeArray: factoryCreateNodeArray,
    createNumericLiteral: factoryCreateNumericLiteral,
    createStringLiteral: factoryCreateStringLiteral,
    createLiteralLikeNode: factoryCreateLiteralLikeNode,
    createIdentifier: factoryCreateIdentifier,
    createPrivateIdentifier: factoryCreatePrivateIdentifier,
    createToken: factoryCreateToken,
    createArrayLiteralExpression: factoryCreateArrayLiteralExpression,
    createObjectLiteralExpression: factoryCreateObjectLiteralExpression,
    createPropertyAccessExpression: factoryCreatePropertyAccessExpression,
    createPropertyAccessChain: factoryCreatePropertyAccessChain,
    createElementAccessExpression: factoryCreateElementAccessExpression,
    createElementAccessChain: factoryCreateElementAccessChain,
    createCallExpression: factoryCreateCallExpression,
    createCallChain: factoryCreateCallChain,
    createNewExpression: factoryCreateNewExpression,
    createParenthesizedExpression: factoryCreateParenthesizedExpression,
    createBlock: factoryCreateBlock,
    createVariableStatement: factoryCreateVariableStatement,
    createExpressionStatement: factoryCreateExpressionStatement,
    createIfStatement: factoryCreateIfStatement,
    createWhileStatement: factoryCreateWhileStatement,
    createForStatement: factoryCreateForStatement,
    createForOfStatement: factoryCreateForOfStatement,
    createVariableDeclaration: factoryCreateVariableDeclaration,
    createVariableDeclarationList: factoryCreateVariableDeclarationList
  } = factory2;
  var fileName;
  var sourceFlags;
  var sourceText;
  var languageVersion;
  var scriptKind;
  var languageVariant;
  var parseDiagnostics;
  var jsDocDiagnostics;
  var syntaxCursor;
  var currentToken;
  var nodeCount;
  var identifiers;
  var identifierCount;
  var parsingContext;
  var notParenthesizedArrow;
  var contextFlags;
  var topLevel = true;
  var parseErrorBeforeNextFinishedNode = false;
  function parseSourceFile(fileName2, sourceText2, languageVersion2, syntaxCursor2, setParentNodes = false, scriptKind2, setExternalModuleIndicatorOverride, jsDocParsingMode = 0 /* ParseAll */) {
    var _a;
    scriptKind2 = ensureScriptKind(fileName2, scriptKind2);
    if (scriptKind2 === 6 /* JSON */) {
      const result2 = parseJsonText2(fileName2, sourceText2, languageVersion2, syntaxCursor2, setParentNodes);
      convertToJson(
        result2,
        (_a = result2.statements[0]) == null ? void 0 : _a.expression,
        result2.parseDiagnostics,
        /*returnValue*/
        false,
        /*jsonConversionNotifier*/
        void 0
      );
      result2.referencedFiles = emptyArray;
      result2.typeReferenceDirectives = emptyArray;
      result2.libReferenceDirectives = emptyArray;
      result2.amdDependencies = emptyArray;
      result2.hasNoDefaultLib = false;
      result2.pragmas = emptyMap;
      return result2;
    }
    initializeState(fileName2, sourceText2, languageVersion2, syntaxCursor2, scriptKind2, jsDocParsingMode);
    const result = parseSourceFileWorker(languageVersion2, setParentNodes, scriptKind2, setExternalModuleIndicatorOverride || setExternalModuleIndicator, jsDocParsingMode);
    clearState();
    return result;
  }
  Parser2.parseSourceFile = parseSourceFile;
  function parseIsolatedEntityName2(content, languageVersion2) {
    initializeState(
      "",
      content,
      languageVersion2,
      /*syntaxCursor*/
      void 0,
      1 /* JS */,
      0 /* ParseAll */
    );
    nextToken();
    const entityName = parseEntityName(
      /*allowReservedWords*/
      true
    );
    const isValid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
    clearState();
    return isValid ? entityName : void 0;
  }
  Parser2.parseIsolatedEntityName = parseIsolatedEntityName2;
  function parseJsonText2(fileName2, sourceText2, languageVersion2 = 2 /* ES2015 */, syntaxCursor2, setParentNodes = false) {
    initializeState(fileName2, sourceText2, languageVersion2, syntaxCursor2, 6 /* JSON */, 0 /* ParseAll */);
    sourceFlags = contextFlags;
    nextToken();
    const pos = getNodePos();
    let statements, endOfFileToken;
    if (token() === 1 /* EndOfFileToken */) {
      statements = createNodeArray([], pos, pos);
      endOfFileToken = parseTokenNode();
    } else {
      let expressions;
      while (token() !== 1 /* EndOfFileToken */) {
        let expression2;
        switch (token()) {
          case 23 /* OpenBracketToken */:
            expression2 = parseArrayLiteralExpression();
            break;
          case 112 /* TrueKeyword */:
          case 97 /* FalseKeyword */:
          case 106 /* NullKeyword */:
            expression2 = parseTokenNode();
            break;
          case 41 /* MinusToken */:
            if (lookAhead(() => nextToken() === 9 /* NumericLiteral */ && nextToken() !== 59 /* ColonToken */)) {
              expression2 = parsePrefixUnaryExpression();
            } else {
              expression2 = parseObjectLiteralExpression();
            }
            break;
          case 9 /* NumericLiteral */:
          case 11 /* StringLiteral */:
            if (lookAhead(() => nextToken() !== 59 /* ColonToken */)) {
              expression2 = parseLiteralNode();
              break;
            }
          // falls through
          default:
            expression2 = parseObjectLiteralExpression();
            break;
        }
        if (expressions && isArray(expressions)) {
          expressions.push(expression2);
        } else if (expressions) {
          expressions = [expressions, expression2];
        } else {
          expressions = expression2;
          if (token() !== 1 /* EndOfFileToken */) {
            parseErrorAtCurrentToken(Diagnostics.Unexpected_token);
          }
        }
      }
      const expression = isArray(expressions) ? finishNode(factoryCreateArrayLiteralExpression(expressions), pos) : Debug.checkDefined(expressions);
      const statement = factoryCreateExpressionStatement(expression);
      finishNode(statement, pos);
      statements = createNodeArray([statement], pos);
      endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, Diagnostics.Unexpected_token);
    }
    const sourceFile = createSourceFile2(
      fileName2,
      2 /* ES2015 */,
      6 /* JSON */,
      /*isDeclarationFile*/
      false,
      statements,
      endOfFileToken,
      sourceFlags,
      noop
    );
    if (setParentNodes) {
      fixupParentReferences(sourceFile);
    }
    sourceFile.nodeCount = nodeCount;
    sourceFile.identifierCount = identifierCount;
    sourceFile.identifiers = identifiers;
    sourceFile.parseDiagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile);
    if (jsDocDiagnostics) {
      sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
    }
    const result = sourceFile;
    clearState();
    return result;
  }
  Parser2.parseJsonText = parseJsonText2;
  function initializeState(_fileName, _sourceText, _languageVersion, _syntaxCursor, _scriptKind, _jsDocParsingMode) {
    NodeConstructor2 = objectAllocator.getNodeConstructor();
    TokenConstructor2 = objectAllocator.getTokenConstructor();
    IdentifierConstructor2 = objectAllocator.getIdentifierConstructor();
    PrivateIdentifierConstructor2 = objectAllocator.getPrivateIdentifierConstructor();
    SourceFileConstructor2 = objectAllocator.getSourceFileConstructor();
    fileName = normalizePath(_fileName);
    sourceText = _sourceText;
    languageVersion = _languageVersion;
    syntaxCursor = _syntaxCursor;
    scriptKind = _scriptKind;
    languageVariant = getLanguageVariant(_scriptKind);
    parseDiagnostics = [];
    parsingContext = 0;
    identifiers = /* @__PURE__ */ new Map();
    identifierCount = 0;
    nodeCount = 0;
    sourceFlags = 0;
    topLevel = true;
    switch (scriptKind) {
      case 1 /* JS */:
      case 2 /* JSX */:
        contextFlags = 524288 /* JavaScriptFile */;
        break;
      case 6 /* JSON */:
        contextFlags = 524288 /* JavaScriptFile */ | 134217728 /* JsonFile */;
        break;
      default:
        contextFlags = 0 /* None */;
        break;
    }
    parseErrorBeforeNextFinishedNode = false;
    scanner.setText(sourceText);
    scanner.setOnError(scanError);
    scanner.setScriptTarget(languageVersion);
    scanner.setLanguageVariant(languageVariant);
    scanner.setScriptKind(scriptKind);
    scanner.setJSDocParsingMode(_jsDocParsingMode);
  }
  function clearState() {
    scanner.clearCommentDirectives();
    scanner.setText("");
    scanner.setOnError(void 0);
    scanner.setScriptKind(0 /* Unknown */);
    scanner.setJSDocParsingMode(0 /* ParseAll */);
    sourceText = void 0;
    languageVersion = void 0;
    syntaxCursor = void 0;
    scriptKind = void 0;
    languageVariant = void 0;
    sourceFlags = 0;
    parseDiagnostics = void 0;
    jsDocDiagnostics = void 0;
    parsingContext = 0;
    identifiers = void 0;
    notParenthesizedArrow = void 0;
    topLevel = true;
  }
  function parseSourceFileWorker(languageVersion2, setParentNodes, scriptKind2, setExternalModuleIndicator2, jsDocParsingMode) {
    const isDeclarationFile = isDeclarationFileName(fileName);
    if (isDeclarationFile) {
      contextFlags |= 33554432 /* Ambient */;
    }
    sourceFlags = contextFlags;
    nextToken();
    const statements = parseList(0 /* SourceElements */, parseStatement);
    Debug.assert(token() === 1 /* EndOfFileToken */);
    const endHasJSDoc = hasPrecedingJSDocComment();
    const endOfFileToken = withJSDoc(parseTokenNode(), endHasJSDoc);
    const sourceFile = createSourceFile2(fileName, languageVersion2, scriptKind2, isDeclarationFile, statements, endOfFileToken, sourceFlags, setExternalModuleIndicator2);
    processCommentPragmas(sourceFile, sourceText);
    processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
    sourceFile.commentDirectives = scanner.getCommentDirectives();
    sourceFile.nodeCount = nodeCount;
    sourceFile.identifierCount = identifierCount;
    sourceFile.identifiers = identifiers;
    sourceFile.parseDiagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile);
    sourceFile.jsDocParsingMode = jsDocParsingMode;
    if (jsDocDiagnostics) {
      sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
    }
    if (setParentNodes) {
      fixupParentReferences(sourceFile);
    }
    return sourceFile;
    function reportPragmaDiagnostic(pos, end, diagnostic) {
      parseDiagnostics.push(createDetachedDiagnostic(fileName, sourceText, pos, end, diagnostic));
    }
  }
  let hasDeprecatedTag = false;
  function withJSDoc(node, hasJSDoc) {
    if (!hasJSDoc) {
      return node;
    }
    Debug.assert(!node.jsDoc);
    const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), (comment) => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos));
    if (jsDoc.length) node.jsDoc = jsDoc;
    if (hasDeprecatedTag) {
      hasDeprecatedTag = false;
      node.flags |= 536870912 /* Deprecated */;
    }
    return node;
  }
  function reparseTopLevelAwait(sourceFile) {
    const savedSyntaxCursor = syntaxCursor;
    const baseSyntaxCursor = IncrementalParser.createSyntaxCursor(sourceFile);
    syntaxCursor = { currentNode: currentNode2 };
    const statements = [];
    const savedParseDiagnostics = parseDiagnostics;
    parseDiagnostics = [];
    let pos = 0;
    let start = findNextStatementWithAwait(sourceFile.statements, 0);
    while (start !== -1) {
      const prevStatement = sourceFile.statements[pos];
      const nextStatement = sourceFile.statements[start];
      addRange(statements, sourceFile.statements, pos, start);
      pos = findNextStatementWithoutAwait(sourceFile.statements, start);
      const diagnosticStart = findIndex(savedParseDiagnostics, (diagnostic) => diagnostic.start >= prevStatement.pos);
      const diagnosticEnd = diagnosticStart >= 0 ? findIndex(savedParseDiagnostics, (diagnostic) => diagnostic.start >= nextStatement.pos, diagnosticStart) : -1;
      if (diagnosticStart >= 0) {
        addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart, diagnosticEnd >= 0 ? diagnosticEnd : void 0);
      }
      speculationHelper(() => {
        const savedContextFlags = contextFlags;
        contextFlags |= 65536 /* AwaitContext */;
        scanner.resetTokenState(nextStatement.pos);
        nextToken();
        while (token() !== 1 /* EndOfFileToken */) {
          const startPos = scanner.getTokenFullStart();
          const statement = parseListElement(0 /* SourceElements */, parseStatement);
          statements.push(statement);
          if (startPos === scanner.getTokenFullStart()) {
            nextToken();
          }
          if (pos >= 0) {
            const nonAwaitStatement = sourceFile.statements[pos];
            if (statement.end === nonAwaitStatement.pos) {
              break;
            }
            if (statement.end > nonAwaitStatement.pos) {
              pos = findNextStatementWithoutAwait(sourceFile.statements, pos + 1);
            }
          }
        }
        contextFlags = savedContextFlags;
      }, 2 /* Reparse */);
      start = pos >= 0 ? findNextStatementWithAwait(sourceFile.statements, pos) : -1;
    }
    if (pos >= 0) {
      const prevStatement = sourceFile.statements[pos];
      addRange(statements, sourceFile.statements, pos);
      const diagnosticStart = findIndex(savedParseDiagnostics, (diagnostic) => diagnostic.start >= prevStatement.pos);
      if (diagnosticStart >= 0) {
        addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart);
      }
    }
    syntaxCursor = savedSyntaxCursor;
    return factory2.updateSourceFile(sourceFile, setTextRange(factoryCreateNodeArray(statements), sourceFile.statements));
    function containsPossibleTopLevelAwait(node) {
      return !(node.flags & 65536 /* AwaitContext */) && !!(node.transformFlags & 67108864 /* ContainsPossibleTopLevelAwait */);
    }
    function findNextStatementWithAwait(statements2, start2) {
      for (let i = start2; i < statements2.length; i++) {
        if (containsPossibleTopLevelAwait(statements2[i])) {
          return i;
        }
      }
      return -1;
    }
    function findNextStatementWithoutAwait(statements2, start2) {
      for (let i = start2; i < statements2.length; i++) {
        if (!containsPossibleTopLevelAwait(statements2[i])) {
          return i;
        }
      }
      return -1;
    }
    function currentNode2(position) {
      const node = baseSyntaxCursor.currentNode(position);
      if (topLevel && node && containsPossibleTopLevelAwait(node)) {
        markAsIntersectingIncrementalChange(node);
      }
      return node;
    }
  }
  function fixupParentReferences(rootNode) {
    setParentRecursive(
      rootNode,
      /*incremental*/
      true
    );
  }
  Parser2.fixupParentReferences = fixupParentReferences;
  function createSourceFile2(fileName2, languageVersion2, scriptKind2, isDeclarationFile, statements, endOfFileToken, flags, setExternalModuleIndicator2) {
    let sourceFile = factory2.createSourceFile(statements, endOfFileToken, flags);
    setTextRangePosWidth(sourceFile, 0, sourceText.length);
    setFields(sourceFile);
    if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 67108864 /* ContainsPossibleTopLevelAwait */) {
      const oldSourceFile = sourceFile;
      sourceFile = reparseTopLevelAwait(sourceFile);
      if (oldSourceFile !== sourceFile) setFields(sourceFile);
    }
    return sourceFile;
    function setFields(sourceFile2) {
      sourceFile2.text = sourceText;
      sourceFile2.bindDiagnostics = [];
      sourceFile2.bindSuggestionDiagnostics = void 0;
      sourceFile2.languageVersion = languageVersion2;
      sourceFile2.fileName = fileName2;
      sourceFile2.languageVariant = getLanguageVariant(scriptKind2);
      sourceFile2.isDeclarationFile = isDeclarationFile;
      sourceFile2.scriptKind = scriptKind2;
      setExternalModuleIndicator2(sourceFile2);
      sourceFile2.setExternalModuleIndicator = setExternalModuleIndicator2;
    }
  }
  function setContextFlag(val, flag) {
    if (val) {
      contextFlags |= flag;
    } else {
      contextFlags &= ~flag;
    }
  }
  function setDisallowInContext(val) {
    setContextFlag(val, 8192 /* DisallowInContext */);
  }
  function setYieldContext(val) {
    setContextFlag(val, 16384 /* YieldContext */);
  }
  function setDecoratorContext(val) {
    setContextFlag(val, 32768 /* DecoratorContext */);
  }
  function setAwaitContext(val) {
    setContextFlag(val, 65536 /* AwaitContext */);
  }
  function doOutsideOfContext(context, func) {
    const contextFlagsToClear = context & contextFlags;
    if (contextFlagsToClear) {
      setContextFlag(
        /*val*/
        false,
        contextFlagsToClear
      );
      const result = func();
      setContextFlag(
        /*val*/
        true,
        contextFlagsToClear
      );
      return result;
    }
    return func();
  }
  function doInsideOfContext(context, func) {
    const contextFlagsToSet = context & ~contextFlags;
    if (contextFlagsToSet) {
      setContextFlag(
        /*val*/
        true,
        contextFlagsToSet
      );
      const result = func();
      setContextFlag(
        /*val*/
        false,
        contextFlagsToSet
      );
      return result;
    }
    return func();
  }
  function allowInAnd(func) {
    return doOutsideOfContext(8192 /* DisallowInContext */, func);
  }
  function disallowInAnd(func) {
    return doInsideOfContext(8192 /* DisallowInContext */, func);
  }
  function allowConditionalTypesAnd(func) {
    return doOutsideOfContext(131072 /* DisallowConditionalTypesContext */, func);
  }
  function disallowConditionalTypesAnd(func) {
    return doInsideOfContext(131072 /* DisallowConditionalTypesContext */, func);
  }
  function doInYieldContext(func) {
    return doInsideOfContext(16384 /* YieldContext */, func);
  }
  function doInDecoratorContext(func) {
    return doInsideOfContext(32768 /* DecoratorContext */, func);
  }
  function doInAwaitContext(func) {
    return doInsideOfContext(65536 /* AwaitContext */, func);
  }
  function doOutsideOfAwaitContext(func) {
    return doOutsideOfContext(65536 /* AwaitContext */, func);
  }
  function doInYieldAndAwaitContext(func) {
    return doInsideOfContext(16384 /* YieldContext */ | 65536 /* AwaitContext */, func);
  }
  function doOutsideOfYieldAndAwaitContext(func) {
    return doOutsideOfContext(16384 /* YieldContext */ | 65536 /* AwaitContext */, func);
  }
  function inContext(flags) {
    return (contextFlags & flags) !== 0;
  }
  function inYieldContext() {
    return inContext(16384 /* YieldContext */);
  }
  function inDisallowInContext() {
    return inContext(8192 /* DisallowInContext */);
  }
  function inDisallowConditionalTypesContext() {
    return inContext(131072 /* DisallowConditionalTypesContext */);
  }
  function inDecoratorContext() {
    return inContext(32768 /* DecoratorContext */);
  }
  function inAwaitContext() {
    return inContext(65536 /* AwaitContext */);
  }
  function parseErrorAtCurrentToken(message, ...args) {
    return parseErrorAt(scanner.getTokenStart(), scanner.getTokenEnd(), message, ...args);
  }
  function parseErrorAtPosition(start, length2, message, ...args) {
    const lastError = lastOrUndefined(parseDiagnostics);
    let result;
    if (!lastError || start !== lastError.start) {
      result = createDetachedDiagnostic(fileName, sourceText, start, length2, message, ...args);
      parseDiagnostics.push(result);
    }
    parseErrorBeforeNextFinishedNode = true;
    return result;
  }
  function parseErrorAt(start, end, message, ...args) {
    return parseErrorAtPosition(start, end - start, message, ...args);
  }
  function parseErrorAtRange(range, message, ...args) {
    parseErrorAt(range.pos, range.end, message, ...args);
  }
  function scanError(message, length2, arg0) {
    parseErrorAtPosition(scanner.getTokenEnd(), length2, message, arg0);
  }
  function getNodePos() {
    return scanner.getTokenFullStart();
  }
  function hasPrecedingJSDocComment() {
    return scanner.hasPrecedingJSDocComment();
  }
  function token() {
    return currentToken;
  }
  function nextTokenWithoutCheck() {
    return currentToken = scanner.scan();
  }
  function nextTokenAnd(func) {
    nextToken();
    return func();
  }
  function nextToken() {
    if (isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
      parseErrorAt(scanner.getTokenStart(), scanner.getTokenEnd(), Diagnostics.Keywords_cannot_contain_escape_characters);
    }
    return nextTokenWithoutCheck();
  }
  function nextTokenJSDoc() {
    return currentToken = scanner.scanJsDocToken();
  }
  function nextJSDocCommentTextToken(inBackticks) {
    return currentToken = scanner.scanJSDocCommentTextToken(inBackticks);
  }
  function reScanGreaterToken() {
    return currentToken = scanner.reScanGreaterToken();
  }
  function reScanSlashToken() {
    return currentToken = scanner.reScanSlashToken();
  }
  function reScanTemplateToken(isTaggedTemplate) {
    return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
  }
  function reScanLessThanToken() {
    return currentToken = scanner.reScanLessThanToken();
  }
  function reScanHashToken() {
    return currentToken = scanner.reScanHashToken();
  }
  function scanJsxIdentifier() {
    return currentToken = scanner.scanJsxIdentifier();
  }
  function scanJsxText() {
    return currentToken = scanner.scanJsxToken();
  }
  function scanJsxAttributeValue() {
    return currentToken = scanner.scanJsxAttributeValue();
  }
  function speculationHelper(callback, speculationKind) {
    const saveToken = currentToken;
    const saveParseDiagnosticsLength = parseDiagnostics.length;
    const saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
    const saveContextFlags = contextFlags;
    const result = speculationKind !== 0 /* TryParse */ ? scanner.lookAhead(callback) : scanner.tryScan(callback);
    Debug.assert(saveContextFlags === contextFlags);
    if (!result || speculationKind !== 0 /* TryParse */) {
      currentToken = saveToken;
      if (speculationKind !== 2 /* Reparse */) {
        parseDiagnostics.length = saveParseDiagnosticsLength;
      }
      parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
    }
    return result;
  }
  function lookAhead(callback) {
    return speculationHelper(callback, 1 /* Lookahead */);
  }
  function tryParse(callback) {
    return speculationHelper(callback, 0 /* TryParse */);
  }
  function isBindingIdentifier() {
    if (token() === 80 /* Identifier */) {
      return true;
    }
    return token() > 118 /* LastReservedWord */;
  }
  function isIdentifier2() {
    if (token() === 80 /* Identifier */) {
      return true;
    }
    if (token() === 127 /* YieldKeyword */ && inYieldContext()) {
      return false;
    }
    if (token() === 135 /* AwaitKeyword */ && inAwaitContext()) {
      return false;
    }
    return token() > 118 /* LastReservedWord */;
  }
  function parseExpected(kind, diagnosticMessage, shouldAdvance = true) {
    if (token() === kind) {
      if (shouldAdvance) {
        nextToken();
      }
      return true;
    }
    if (diagnosticMessage) {
      parseErrorAtCurrentToken(diagnosticMessage);
    } else {
      parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(kind));
    }
    return false;
  }
  const viableKeywordSuggestions = Object.keys(textToKeywordObj).filter((keyword) => keyword.length > 2);
  function parseErrorForMissingSemicolonAfter(node) {
    if (isTaggedTemplateExpression(node)) {
      parseErrorAt(skipTrivia(sourceText, node.template.pos), node.template.end, Diagnostics.Module_declaration_names_may_only_use_or_quoted_strings);
      return;
    }
    const expressionText = isIdentifier(node) ? idText(node) : void 0;
    if (!expressionText || !isIdentifierText(expressionText, languageVersion)) {
      parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(27 /* SemicolonToken */));
      return;
    }
    const pos = skipTrivia(sourceText, node.pos);
    switch (expressionText) {
      case "const":
      case "let":
      case "var":
        parseErrorAt(pos, node.end, Diagnostics.Variable_declaration_not_allowed_at_this_location);
        return;
      case "declare":
        return;
      case "interface":
        parseErrorForInvalidName(Diagnostics.Interface_name_cannot_be_0, Diagnostics.Interface_must_be_given_a_name, 19 /* OpenBraceToken */);
        return;
      case "is":
        parseErrorAt(pos, scanner.getTokenStart(), Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
        return;
      case "module":
      case "namespace":
        parseErrorForInvalidName(Diagnostics.Namespace_name_cannot_be_0, Diagnostics.Namespace_must_be_given_a_name, 19 /* OpenBraceToken */);
        return;
      case "type":
        parseErrorForInvalidName(Diagnostics.Type_alias_name_cannot_be_0, Diagnostics.Type_alias_must_be_given_a_name, 64 /* EqualsToken */);
        return;
    }
    const suggestion = getSpellingSuggestion(expressionText, viableKeywordSuggestions, identity) ?? getSpaceSuggestion(expressionText);
    if (suggestion) {
      parseErrorAt(pos, node.end, Diagnostics.Unknown_keyword_or_identifier_Did_you_mean_0, suggestion);
      return;
    }
    if (token() === 0 /* Unknown */) {
      return;
    }
    parseErrorAt(pos, node.end, Diagnostics.Unexpected_keyword_or_identifier);
  }
  function parseErrorForInvalidName(nameDiagnostic, blankDiagnostic, tokenIfBlankName) {
    if (token() === tokenIfBlankName) {
      parseErrorAtCurrentToken(blankDiagnostic);
    } else {
      parseErrorAtCurrentToken(nameDiagnostic, scanner.getTokenValue());
    }
  }
  function getSpaceSuggestion(expressionText) {
    for (const keyword of viableKeywordSuggestions) {
      if (expressionText.length > keyword.length + 2 && startsWith(expressionText, keyword)) {
        return `${keyword} ${expressionText.slice(keyword.length)}`;
      }
    }
    return void 0;
  }
  function parseSemicolonAfterPropertyName(name, type, initializer) {
    if (token() === 60 /* AtToken */ && !scanner.hasPrecedingLineBreak()) {
      parseErrorAtCurrentToken(Diagnostics.Decorators_must_precede_the_name_and_all_keywords_of_property_declarations);
      return;
    }
    if (token() === 21 /* OpenParenToken */) {
      parseErrorAtCurrentToken(Diagnostics.Cannot_start_a_function_call_in_a_type_annotation);
      nextToken();
      return;
    }
    if (type && !canParseSemicolon()) {
      if (initializer) {
        parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(27 /* SemicolonToken */));
      } else {
        parseErrorAtCurrentToken(Diagnostics.Expected_for_property_initializer);
      }
      return;
    }
    if (tryParseSemicolon()) {
      return;
    }
    if (initializer) {
      parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(27 /* SemicolonToken */));
      return;
    }
    parseErrorForMissingSemicolonAfter(name);
  }
  function parseExpectedJSDoc(kind) {
    if (token() === kind) {
      nextTokenJSDoc();
      return true;
    }
    Debug.assert(isKeywordOrPunctuation(kind));
    parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(kind));
    return false;
  }
  function parseExpectedMatchingBrackets(openKind, closeKind, openParsed, openPosition) {
    if (token() === closeKind) {
      nextToken();
      return;
    }
    const lastError = parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(closeKind));
    if (!openParsed) {
      return;
    }
    if (lastError) {
      addRelatedInfo(
        lastError,
        createDetachedDiagnostic(fileName, sourceText, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind))
      );
    }
  }
  function parseOptional(t) {
    if (token() === t) {
      nextToken();
      return true;
    }
    return false;
  }
  function parseOptionalToken(t) {
    if (token() === t) {
      return parseTokenNode();
    }
    return void 0;
  }
  function parseOptionalTokenJSDoc(t) {
    if (token() === t) {
      return parseTokenNodeJSDoc();
    }
    return void 0;
  }
  function parseExpectedToken(t, diagnosticMessage, arg0) {
    return parseOptionalToken(t) || createMissingNode(
      t,
      /*reportAtCurrentPosition*/
      false,
      diagnosticMessage || Diagnostics._0_expected,
      arg0 || tokenToString(t)
    );
  }
  function parseExpectedTokenJSDoc(t) {
    const optional = parseOptionalTokenJSDoc(t);
    if (optional) return optional;
    Debug.assert(isKeywordOrPunctuation(t));
    return createMissingNode(
      t,
      /*reportAtCurrentPosition*/
      false,
      Diagnostics._0_expected,
      tokenToString(t)
    );
  }
  function parseTokenNode() {
    const pos = getNodePos();
    const kind = token();
    nextToken();
    return finishNode(factoryCreateToken(kind), pos);
  }
  function parseTokenNodeJSDoc() {
    const pos = getNodePos();
    const kind = token();
    nextTokenJSDoc();
    return finishNode(factoryCreateToken(kind), pos);
  }
  function canParseSemicolon() {
    if (token() === 27 /* SemicolonToken */) {
      return true;
    }
    return token() === 20 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
  }
  function tryParseSemicolon() {
    if (!canParseSemicolon()) {
      return false;
    }
    if (token() === 27 /* SemicolonToken */) {
      nextToken();
    }
    return true;
  }
  function parseSemicolon() {
    return tryParseSemicolon() || parseExpected(27 /* SemicolonToken */);
  }
  function createNodeArray(elements, pos, end, hasTrailingComma) {
    const array = factoryCreateNodeArray(elements, hasTrailingComma);
    setTextRangePosEnd(array, pos, end ?? scanner.getTokenFullStart());
    return array;
  }
  function finishNode(node, pos, end) {
    setTextRangePosEnd(node, pos, end ?? scanner.getTokenFullStart());
    if (contextFlags) {
      node.flags |= contextFlags;
    }
    if (parseErrorBeforeNextFinishedNode) {
      parseErrorBeforeNextFinishedNode = false;
      node.flags |= 262144 /* ThisNodeHasError */;
    }
    return node;
  }
  function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, ...args) {
    if (reportAtCurrentPosition) {
      parseErrorAtPosition(scanner.getTokenFullStart(), 0, diagnosticMessage, ...args);
    } else if (diagnosticMessage) {
      parseErrorAtCurrentToken(diagnosticMessage, ...args);
    }
    const pos = getNodePos();
    const result = kind === 80 /* Identifier */ ? factoryCreateIdentifier(
      "",
      /*originalKeywordKind*/
      void 0
    ) : isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode(
      kind,
      "",
      "",
      /*templateFlags*/
      void 0
    ) : kind === 9 /* NumericLiteral */ ? factoryCreateNumericLiteral(
      "",
      /*numericLiteralFlags*/
      void 0
    ) : kind === 11 /* StringLiteral */ ? factoryCreateStringLiteral(
      "",
      /*isSingleQuote*/
      void 0
    ) : kind === 282 /* MissingDeclaration */ ? factory2.createMissingDeclaration() : factoryCreateToken(kind);
    return finishNode(result, pos);
  }
  function internIdentifier(text) {
    let identifier = identifiers.get(text);
    if (identifier === void 0) {
      identifiers.set(text, identifier = text);
    }
    return identifier;
  }
  function createIdentifier(isIdentifier3, diagnosticMessage, privateIdentifierDiagnosticMessage) {
    if (isIdentifier3) {
      identifierCount++;
      const pos = scanner.hasPrecedingJSDocLeadingAsterisks() ? scanner.getTokenStart() : getNodePos();
      const originalKeywordKind = token();
      const text = internIdentifier(scanner.getTokenValue());
      const hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape();
      nextTokenWithoutCheck();
      return finishNode(factoryCreateIdentifier(text, originalKeywordKind, hasExtendedUnicodeEscape), pos);
    }
    if (token() === 81 /* PrivateIdentifier */) {
      parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
      return createIdentifier(
        /*isIdentifier*/
        true
      );
    }
    if (token() === 0 /* Unknown */ && scanner.tryScan(() => scanner.reScanInvalidIdentifier() === 80 /* Identifier */)) {
      return createIdentifier(
        /*isIdentifier*/
        true
      );
    }
    identifierCount++;
    const reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
    const isReservedWord = scanner.isReservedWord();
    const msgArg = scanner.getTokenText();
    const defaultMessage = isReservedWord ? Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : Diagnostics.Identifier_expected;
    return createMissingNode(80 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
  }
  function parseBindingIdentifier(privateIdentifierDiagnosticMessage) {
    return createIdentifier(
      isBindingIdentifier(),
      /*diagnosticMessage*/
      void 0,
      privateIdentifierDiagnosticMessage
    );
  }
  function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
    return createIdentifier(isIdentifier2(), diagnosticMessage, privateIdentifierDiagnosticMessage);
  }
  function parseIdentifierName(diagnosticMessage) {
    return createIdentifier(tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
  }
  function parseIdentifierNameErrorOnUnicodeEscapeSequence() {
    if (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape()) {
      parseErrorAtCurrentToken(Diagnostics.Unicode_escape_sequence_cannot_appear_here);
    }
    return createIdentifier(tokenIsIdentifierOrKeyword(token()));
  }
  function isLiteralPropertyName() {
    return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */;
  }
  function isImportAttributeName2() {
    return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */;
  }
  function parsePropertyNameWorker(allowComputedPropertyNames) {
    if (token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */) {
      const node = parseLiteralNode();
      node.text = internIdentifier(node.text);
      return node;
    }
    if (allowComputedPropertyNames && token() === 23 /* OpenBracketToken */) {
      return parseComputedPropertyName();
    }
    if (token() === 81 /* PrivateIdentifier */) {
      return parsePrivateIdentifier();
    }
    return parseIdentifierName();
  }
  function parsePropertyName() {
    return parsePropertyNameWorker(
      /*allowComputedPropertyNames*/
      true
    );
  }
  function parseComputedPropertyName() {
    const pos = getNodePos();
    parseExpected(23 /* OpenBracketToken */);
    const expression = allowInAnd(parseExpression);
    parseExpected(24 /* CloseBracketToken */);
    return finishNode(factory2.createComputedPropertyName(expression), pos);
  }
  function parsePrivateIdentifier() {
    const pos = getNodePos();
    const node = factoryCreatePrivateIdentifier(internIdentifier(scanner.getTokenValue()));
    nextToken();
    return finishNode(node, pos);
  }
  function parseContextualModifier(t) {
    return token() === t && tryParse(nextTokenCanFollowModifier);
  }
  function nextTokenIsOnSameLineAndCanFollowModifier() {
    nextToken();
    if (scanner.hasPrecedingLineBreak()) {
      return false;
    }
    return canFollowModifier();
  }
  function nextTokenCanFollowModifier() {
    switch (token()) {
      case 87 /* ConstKeyword */:
        return nextToken() === 94 /* EnumKeyword */;
      case 95 /* ExportKeyword */:
        nextToken();
        if (token() === 90 /* DefaultKeyword */) {
          return lookAhead(nextTokenCanFollowDefaultKeyword);
        }
        if (token() === 156 /* TypeKeyword */) {
          return lookAhead(nextTokenCanFollowExportModifier);
        }
        return canFollowExportModifier();
      case 90 /* DefaultKeyword */:
        return nextTokenCanFollowDefaultKeyword();
      case 126 /* StaticKeyword */:
        nextToken();
        return canFollowModifier();
      case 139 /* GetKeyword */:
      case 153 /* SetKeyword */:
        nextToken();
        return canFollowGetOrSetKeyword();
      default:
        return nextTokenIsOnSameLineAndCanFollowModifier();
    }
  }
  function canFollowExportModifier() {
    return token() === 60 /* AtToken */ || token() !== 42 /* AsteriskToken */ && token() !== 130 /* AsKeyword */ && token() !== 19 /* OpenBraceToken */ && canFollowModifier();
  }
  function nextTokenCanFollowExportModifier() {
    nextToken();
    return canFollowExportModifier();
  }
  function parseAnyContextualModifier() {
    return isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
  }
  function canFollowModifier() {
    return token() === 23 /* OpenBracketToken */ || token() === 19 /* OpenBraceToken */ || token() === 42 /* AsteriskToken */ || token() === 26 /* DotDotDotToken */ || isLiteralPropertyName();
  }
  function canFollowGetOrSetKeyword() {
    return token() === 23 /* OpenBracketToken */ || isLiteralPropertyName();
  }
  function nextTokenCanFollowDefaultKeyword() {
    nextToken();
    return token() === 86 /* ClassKeyword */ || token() === 100 /* FunctionKeyword */ || token() === 120 /* InterfaceKeyword */ || token() === 60 /* AtToken */ || token() === 128 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine) || token() === 134 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine);
  }
  function isListElement(parsingContext2, inErrorRecovery) {
    const node = currentNode(parsingContext2);
    if (node) {
      return true;
    }
    switch (parsingContext2) {
      case 0 /* SourceElements */:
      case 1 /* BlockStatements */:
      case 3 /* SwitchClauseStatements */:
        return !(token() === 27 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
      case 2 /* SwitchClauses */:
        return token() === 84 /* CaseKeyword */ || token() === 90 /* DefaultKeyword */;
      case 4 /* TypeMembers */:
        return lookAhead(isTypeMemberStart);
      case 5 /* ClassMembers */:
        return lookAhead(isClassMemberStart) || token() === 27 /* SemicolonToken */ && !inErrorRecovery;
      case 6 /* EnumMembers */:
        return token() === 23 /* OpenBracketToken */ || isLiteralPropertyName();
      case 12 /* ObjectLiteralMembers */:
        switch (token()) {
          case 23 /* OpenBracketToken */:
          case 42 /* AsteriskToken */:
          case 26 /* DotDotDotToken */:
          case 25 /* DotToken */:
            return true;
          default:
            return isLiteralPropertyName();
        }
      case 18 /* RestProperties */:
        return isLiteralPropertyName();
      case 9 /* ObjectBindingElements */:
        return token() === 23 /* OpenBracketToken */ || token() === 26 /* DotDotDotToken */ || isLiteralPropertyName();
      case 24 /* ImportAttributes */:
        return isImportAttributeName2();
      case 7 /* HeritageClauseElement */:
        if (token() === 19 /* OpenBraceToken */) {
          return lookAhead(isValidHeritageClauseObjectLiteral);
        }
        if (!inErrorRecovery) {
          return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
        } else {
          return isIdentifier2() && !isHeritageClauseExtendsOrImplementsKeyword();
        }
      case 8 /* VariableDeclarations */:
        return isBindingIdentifierOrPrivateIdentifierOrPattern();
      case 10 /* ArrayBindingElements */:
        return token() === 28 /* CommaToken */ || token() === 26 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern();
      case 19 /* TypeParameters */:
        return token() === 103 /* InKeyword */ || token() === 87 /* ConstKeyword */ || isIdentifier2();
      case 15 /* ArrayLiteralMembers */:
        switch (token()) {
          case 28 /* CommaToken */:
          case 25 /* DotToken */:
            return true;
        }
      // falls through
      case 11 /* ArgumentExpressions */:
        return token() === 26 /* DotDotDotToken */ || isStartOfExpression();
      case 16 /* Parameters */:
        return isStartOfParameter(
          /*isJSDocParameter*/
          false
        );
      case 17 /* JSDocParameters */:
        return isStartOfParameter(
          /*isJSDocParameter*/
          true
        );
      case 20 /* TypeArguments */:
      case 21 /* TupleElementTypes */:
        return token() === 28 /* CommaToken */ || isStartOfType();
      case 22 /* HeritageClauses */:
        return isHeritageClause2();
      case 23 /* ImportOrExportSpecifiers */:
        if (token() === 161 /* FromKeyword */ && lookAhead(nextTokenIsStringLiteral)) {
          return false;
        }
        if (token() === 11 /* StringLiteral */) {
          return true;
        }
        return tokenIsIdentifierOrKeyword(token());
      case 13 /* JsxAttributes */:
        return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */;
      case 14 /* JsxChildren */:
        return true;
      case 25 /* JSDocComment */:
        return true;
      case 26 /* Count */:
        return Debug.fail("ParsingContext.Count used as a context");
      // Not a real context, only a marker.
      default:
        Debug.assertNever(parsingContext2, "Non-exhaustive case in 'isListElement'.");
    }
  }
  function isValidHeritageClauseObjectLiteral() {
    Debug.assert(token() === 19 /* OpenBraceToken */);
    if (nextToken() === 20 /* CloseBraceToken */) {
      const next = nextToken();
      return next === 28 /* CommaToken */ || next === 19 /* OpenBraceToken */ || next === 96 /* ExtendsKeyword */ || next === 119 /* ImplementsKeyword */;
    }
    return true;
  }
  function nextTokenIsIdentifier() {
    nextToken();
    return isIdentifier2();
  }
  function nextTokenIsIdentifierOrKeyword() {
    nextToken();
    return tokenIsIdentifierOrKeyword(token());
  }
  function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
    nextToken();
    return tokenIsIdentifierOrKeywordOrGreaterThan(token());
  }
  function isHeritageClauseExtendsOrImplementsKeyword() {
    if (token() === 119 /* ImplementsKeyword */ || token() === 96 /* ExtendsKeyword */) {
      return lookAhead(nextTokenIsStartOfExpression);
    }
    return false;
  }
  function nextTokenIsStartOfExpression() {
    nextToken();
    return isStartOfExpression();
  }
  function nextTokenIsStartOfType() {
    nextToken();
    return isStartOfType();
  }
  function isListTerminator(kind) {
    if (token() === 1 /* EndOfFileToken */) {
      return true;
    }
    switch (kind) {
      case 1 /* BlockStatements */:
      case 2 /* SwitchClauses */:
      case 4 /* TypeMembers */:
      case 5 /* ClassMembers */:
      case 6 /* EnumMembers */:
      case 12 /* ObjectLiteralMembers */:
      case 9 /* ObjectBindingElements */:
      case 23 /* ImportOrExportSpecifiers */:
      case 24 /* ImportAttributes */:
        return token() === 20 /* CloseBraceToken */;
      case 3 /* SwitchClauseStatements */:
        return token() === 20 /* CloseBraceToken */ || token() === 84 /* CaseKeyword */ || token() === 90 /* DefaultKeyword */;
      case 7 /* HeritageClauseElement */:
        return token() === 19 /* OpenBraceToken */ || token() === 96 /* ExtendsKeyword */ || token() === 119 /* ImplementsKeyword */;
      case 8 /* VariableDeclarations */:
        return isVariableDeclaratorListTerminator();
      case 19 /* TypeParameters */:
        return token() === 32 /* GreaterThanToken */ || token() === 21 /* OpenParenToken */ || token() === 19 /* OpenBraceToken */ || token() === 96 /* ExtendsKeyword */ || token() === 119 /* ImplementsKeyword */;
      case 11 /* ArgumentExpressions */:
        return token() === 22 /* CloseParenToken */ || token() === 27 /* SemicolonToken */;
      case 15 /* ArrayLiteralMembers */:
      case 21 /* TupleElementTypes */:
      case 10 /* ArrayBindingElements */:
        return token() === 24 /* CloseBracketToken */;
      case 17 /* JSDocParameters */:
      case 16 /* Parameters */:
      case 18 /* RestProperties */:
        return token() === 22 /* CloseParenToken */ || token() === 24 /* CloseBracketToken */;
      case 20 /* TypeArguments */:
        return token() !== 28 /* CommaToken */;
      case 22 /* HeritageClauses */:
        return token() === 19 /* OpenBraceToken */ || token() === 20 /* CloseBraceToken */;
      case 13 /* JsxAttributes */:
        return token() === 32 /* GreaterThanToken */ || token() === 44 /* SlashToken */;
      case 14 /* JsxChildren */:
        return token() === 30 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
      default:
        return false;
    }
  }
  function isVariableDeclaratorListTerminator() {
    if (canParseSemicolon()) {
      return true;
    }
    if (isInOrOfKeyword(token())) {
      return true;
    }
    if (token() === 39 /* EqualsGreaterThanToken */) {
      return true;
    }
    return false;
  }
  function isInSomeParsingContext() {
    Debug.assert(parsingContext, "Missing parsing context");
    for (let kind = 0; kind < 26 /* Count */; kind++) {
      if (parsingContext & 1 << kind) {
        if (isListElement(
          kind,
          /*inErrorRecovery*/
          true
        ) || isListTerminator(kind)) {
          return true;
        }
      }
    }
    return false;
  }
  function parseList(kind, parseElement) {
    const saveParsingContext = parsingContext;
    parsingContext |= 1 << kind;
    const list = [];
    const listPos = getNodePos();
    while (!isListTerminator(kind)) {
      if (isListElement(
        kind,
        /*inErrorRecovery*/
        false
      )) {
        list.push(parseListElement(kind, parseElement));
        continue;
      }
      if (abortParsingListOrMoveToNextToken(kind)) {
        break;
      }
    }
    parsingContext = saveParsingContext;
    return createNodeArray(list, listPos);
  }
  function parseListElement(parsingContext2, parseElement) {
    const node = currentNode(parsingContext2);
    if (node) {
      return consumeNode(node);
    }
    return parseElement();
  }
  function currentNode(parsingContext2, pos) {
    var _a;
    if (!syntaxCursor || !isReusableParsingContext(parsingContext2) || parseErrorBeforeNextFinishedNode) {
      return void 0;
    }
    const node = syntaxCursor.currentNode(pos ?? scanner.getTokenFullStart());
    if (nodeIsMissing(node) || intersectsIncrementalChange(node) || containsParseError(node)) {
      return void 0;
    }
    const nodeContextFlags = node.flags & 101441536 /* ContextFlags */;
    if (nodeContextFlags !== contextFlags) {
      return void 0;
    }
    if (!canReuseNode(node, parsingContext2)) {
      return void 0;
    }
    if (canHaveJSDoc(node) && ((_a = node.jsDoc) == null ? void 0 : _a.jsDocCache)) {
      node.jsDoc.jsDocCache = void 0;
    }
    return node;
  }
  function consumeNode(node) {
    scanner.resetTokenState(node.end);
    nextToken();
    return node;
  }
  function isReusableParsingContext(parsingContext2) {
    switch (parsingContext2) {
      case 5 /* ClassMembers */:
      case 2 /* SwitchClauses */:
      case 0 /* SourceElements */:
      case 1 /* BlockStatements */:
      case 3 /* SwitchClauseStatements */:
      case 6 /* EnumMembers */:
      case 4 /* TypeMembers */:
      case 8 /* VariableDeclarations */:
      case 17 /* JSDocParameters */:
      case 16 /* Parameters */:
        return true;
    }
    return false;
  }
  function canReuseNode(node, parsingContext2) {
    switch (parsingContext2) {
      case 5 /* ClassMembers */:
        return isReusableClassMember(node);
      case 2 /* SwitchClauses */:
        return isReusableSwitchClause(node);
      case 0 /* SourceElements */:
      case 1 /* BlockStatements */:
      case 3 /* SwitchClauseStatements */:
        return isReusableStatement(node);
      case 6 /* EnumMembers */:
        return isReusableEnumMember(node);
      case 4 /* TypeMembers */:
        return isReusableTypeMember(node);
      case 8 /* VariableDeclarations */:
        return isReusableVariableDeclaration(node);
      case 17 /* JSDocParameters */:
      case 16 /* Parameters */:
        return isReusableParameter(node);
    }
    return false;
  }
  function isReusableClassMember(node) {
    if (node) {
      switch (node.kind) {
        case 176 /* Constructor */:
        case 181 /* IndexSignature */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
        case 172 /* PropertyDeclaration */:
        case 240 /* SemicolonClassElement */:
          return true;
        case 174 /* MethodDeclaration */:
          const methodDeclaration = node;
          const nameIsConstructor = methodDeclaration.name.kind === 80 /* Identifier */ && methodDeclaration.name.escapedText === "constructor";
          return !nameIsConstructor;
      }
    }
    return false;
  }
  function isReusableSwitchClause(node) {
    if (node) {
      switch (node.kind) {
        case 296 /* CaseClause */:
        case 297 /* DefaultClause */:
          return true;
      }
    }
    return false;
  }
  function isReusableStatement(node) {
    if (node) {
      switch (node.kind) {
        case 262 /* FunctionDeclaration */:
        case 243 /* VariableStatement */:
        case 241 /* Block */:
        case 245 /* IfStatement */:
        case 244 /* ExpressionStatement */:
        case 257 /* ThrowStatement */:
        case 253 /* ReturnStatement */:
        case 255 /* SwitchStatement */:
        case 252 /* BreakStatement */:
        case 251 /* ContinueStatement */:
        case 249 /* ForInStatement */:
        case 250 /* ForOfStatement */:
        case 248 /* ForStatement */:
        case 247 /* WhileStatement */:
        case 254 /* WithStatement */:
        case 242 /* EmptyStatement */:
        case 258 /* TryStatement */:
        case 256 /* LabeledStatement */:
        case 246 /* DoStatement */:
        case 259 /* DebuggerStatement */:
        case 272 /* ImportDeclaration */:
        case 271 /* ImportEqualsDeclaration */:
        case 278 /* ExportDeclaration */:
        case 277 /* ExportAssignment */:
        case 267 /* ModuleDeclaration */:
        case 263 /* ClassDeclaration */:
        case 264 /* InterfaceDeclaration */:
        case 266 /* EnumDeclaration */:
        case 265 /* TypeAliasDeclaration */:
          return true;
      }
    }
    return false;
  }
  function isReusableEnumMember(node) {
    return node.kind === 306 /* EnumMember */;
  }
  function isReusableTypeMember(node) {
    if (node) {
      switch (node.kind) {
        case 180 /* ConstructSignature */:
        case 173 /* MethodSignature */:
        case 181 /* IndexSignature */:
        case 171 /* PropertySignature */:
        case 179 /* CallSignature */:
          return true;
      }
    }
    return false;
  }
  function isReusableVariableDeclaration(node) {
    if (node.kind !== 260 /* VariableDeclaration */) {
      return false;
    }
    const variableDeclarator = node;
    return variableDeclarator.initializer === void 0;
  }
  function isReusableParameter(node) {
    if (node.kind !== 169 /* Parameter */) {
      return false;
    }
    const parameter = node;
    return parameter.initializer === void 0;
  }
  function abortParsingListOrMoveToNextToken(kind) {
    parsingContextErrors(kind);
    if (isInSomeParsingContext()) {
      return true;
    }
    nextToken();
    return false;
  }
  function parsingContextErrors(context) {
    switch (context) {
      case 0 /* SourceElements */:
        return token() === 90 /* DefaultKeyword */ ? parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(95 /* ExportKeyword */)) : parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected);
      case 1 /* BlockStatements */:
        return parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected);
      case 2 /* SwitchClauses */:
        return parseErrorAtCurrentToken(Diagnostics.case_or_default_expected);
      case 3 /* SwitchClauseStatements */:
        return parseErrorAtCurrentToken(Diagnostics.Statement_expected);
      case 18 /* RestProperties */:
      // fallthrough
      case 4 /* TypeMembers */:
        return parseErrorAtCurrentToken(Diagnostics.Property_or_signature_expected);
      case 5 /* ClassMembers */:
        return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected);
      case 6 /* EnumMembers */:
        return parseErrorAtCurrentToken(Diagnostics.Enum_member_expected);
      case 7 /* HeritageClauseElement */:
        return parseErrorAtCurrentToken(Diagnostics.Expression_expected);
      case 8 /* VariableDeclarations */:
        return isKeyword(token()) ? parseErrorAtCurrentToken(Diagnostics._0_is_not_allowed_as_a_variable_declaration_name, tokenToString(token())) : parseErrorAtCurrentToken(Diagnostics.Variable_declaration_expected);
      case 9 /* ObjectBindingElements */:
        return parseErrorAtCurrentToken(Diagnostics.Property_destructuring_pattern_expected);
      case 10 /* ArrayBindingElements */:
        return parseErrorAtCurrentToken(Diagnostics.Array_element_destructuring_pattern_expected);
      case 11 /* ArgumentExpressions */:
        return parseErrorAtCurrentToken(Diagnostics.Argument_expression_expected);
      case 12 /* ObjectLiteralMembers */:
        return parseErrorAtCurrentToken(Diagnostics.Property_assignment_expected);
      case 15 /* ArrayLiteralMembers */:
        return parseErrorAtCurrentToken(Diagnostics.Expression_or_comma_expected);
      case 17 /* JSDocParameters */:
        return parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected);
      case 16 /* Parameters */:
        return isKeyword(token()) ? parseErrorAtCurrentToken(Diagnostics._0_is_not_allowed_as_a_parameter_name, tokenToString(token())) : parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected);
      case 19 /* TypeParameters */:
        return parseErrorAtCurrentToken(Diagnostics.Type_parameter_declaration_expected);
      case 20 /* TypeArguments */:
        return parseErrorAtCurrentToken(Diagnostics.Type_argument_expected);
      case 21 /* TupleElementTypes */:
        return parseErrorAtCurrentToken(Diagnostics.Type_expected);
      case 22 /* HeritageClauses */:
        return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_expected);
      case 23 /* ImportOrExportSpecifiers */:
        if (token() === 161 /* FromKeyword */) {
          return parseErrorAtCurrentToken(Diagnostics._0_expected, "}");
        }
        return parseErrorAtCurrentToken(Diagnostics.Identifier_expected);
      case 13 /* JsxAttributes */:
        return parseErrorAtCurrentToken(Diagnostics.Identifier_expected);
      case 14 /* JsxChildren */:
        return parseErrorAtCurrentToken(Diagnostics.Identifier_expected);
      case 24 /* ImportAttributes */:
        return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected);
      case 25 /* JSDocComment */:
        return parseErrorAtCurrentToken(Diagnostics.Identifier_expected);
      case 26 /* Count */:
        return Debug.fail("ParsingContext.Count used as a context");
      // Not a real context, only a marker.
      default:
        Debug.assertNever(context);
    }
  }
  function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
    const saveParsingContext = parsingContext;
    parsingContext |= 1 << kind;
    const list = [];
    const listPos = getNodePos();
    let commaStart = -1;
    while (true) {
      if (isListElement(
        kind,
        /*inErrorRecovery*/
        false
      )) {
        const startPos = scanner.getTokenFullStart();
        const result = parseListElement(kind, parseElement);
        if (!result) {
          parsingContext = saveParsingContext;
          return void 0;
        }
        list.push(result);
        commaStart = scanner.getTokenStart();
        if (parseOptional(28 /* CommaToken */)) {
          continue;
        }
        commaStart = -1;
        if (isListTerminator(kind)) {
          break;
        }
        parseExpected(28 /* CommaToken */, getExpectedCommaDiagnostic(kind));
        if (considerSemicolonAsDelimiter && token() === 27 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
          nextToken();
        }
        if (startPos === scanner.getTokenFullStart()) {
          nextToken();
        }
        continue;
      }
      if (isListTerminator(kind)) {
        break;
      }
      if (abortParsingListOrMoveToNextToken(kind)) {
        break;
      }
    }
    parsingContext = saveParsingContext;
    return createNodeArray(
      list,
      listPos,
      /*end*/
      void 0,
      commaStart >= 0
    );
  }
  function getExpectedCommaDiagnostic(kind) {
    return kind === 6 /* EnumMembers */ ? Diagnostics.An_enum_member_name_must_be_followed_by_a_or : void 0;
  }
  function createMissingList() {
    const list = createNodeArray([], getNodePos());
    list.isMissingList = true;
    return list;
  }
  function isMissingList(arr) {
    return !!arr.isMissingList;
  }
  function parseBracketedList(kind, parseElement, open, close) {
    if (parseExpected(open)) {
      const result = parseDelimitedList(kind, parseElement);
      parseExpected(close);
      return result;
    }
    return createMissingList();
  }
  function parseEntityName(allowReservedWords, diagnosticMessage) {
    const pos = getNodePos();
    let entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
    while (parseOptional(25 /* DotToken */)) {
      if (token() === 30 /* LessThanToken */) {
        break;
      }
      entity = finishNode(
        factory2.createQualifiedName(
          entity,
          parseRightSideOfDot(
            allowReservedWords,
            /*allowPrivateIdentifiers*/
            false,
            /*allowUnicodeEscapeSequenceInIdentifierName*/
            true
          )
        ),
        pos
      );
    }
    return entity;
  }
  function createQualifiedName(entity, name) {
    return finishNode(factory2.createQualifiedName(entity, name), entity.pos);
  }
  function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers, allowUnicodeEscapeSequenceInIdentifierName) {
    if (scanner.hasPrecedingLineBreak() && tokenIsIdentifierOrKeyword(token())) {
      const matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
      if (matchesPattern) {
        return createMissingNode(
          80 /* Identifier */,
          /*reportAtCurrentPosition*/
          true,
          Diagnostics.Identifier_expected
        );
      }
    }
    if (token() === 81 /* PrivateIdentifier */) {
      const node = parsePrivateIdentifier();
      return allowPrivateIdentifiers ? node : createMissingNode(
        80 /* Identifier */,
        /*reportAtCurrentPosition*/
        true,
        Diagnostics.Identifier_expected
      );
    }
    if (allowIdentifierNames) {
      return allowUnicodeEscapeSequenceInIdentifierName ? parseIdentifierName() : parseIdentifierNameErrorOnUnicodeEscapeSequence();
    }
    return parseIdentifier();
  }
  function parseTemplateSpans(isTaggedTemplate) {
    const pos = getNodePos();
    const list = [];
    let node;
    do {
      node = parseTemplateSpan(isTaggedTemplate);
      list.push(node);
    } while (node.literal.kind === 17 /* TemplateMiddle */);
    return createNodeArray(list, pos);
  }
  function parseTemplateExpression(isTaggedTemplate) {
    const pos = getNodePos();
    return finishNode(
      factory2.createTemplateExpression(
        parseTemplateHead(isTaggedTemplate),
        parseTemplateSpans(isTaggedTemplate)
      ),
      pos
    );
  }
  function parseTemplateType() {
    const pos = getNodePos();
    return finishNode(
      factory2.createTemplateLiteralType(
        parseTemplateHead(
          /*isTaggedTemplate*/
          false
        ),
        parseTemplateTypeSpans()
      ),
      pos
    );
  }
  function parseTemplateTypeSpans() {
    const pos = getNodePos();
    const list = [];
    let node;
    do {
      node = parseTemplateTypeSpan();
      list.push(node);
    } while (node.literal.kind === 17 /* TemplateMiddle */);
    return createNodeArray(list, pos);
  }
  function parseTemplateTypeSpan() {
    const pos = getNodePos();
    return finishNode(
      factory2.createTemplateLiteralTypeSpan(
        parseType(),
        parseLiteralOfTemplateSpan(
          /*isTaggedTemplate*/
          false
        )
      ),
      pos
    );
  }
  function parseLiteralOfTemplateSpan(isTaggedTemplate) {
    if (token() === 20 /* CloseBraceToken */) {
      reScanTemplateToken(isTaggedTemplate);
      return parseTemplateMiddleOrTemplateTail();
    } else {
      return parseExpectedToken(18 /* TemplateTail */, Diagnostics._0_expected, tokenToString(20 /* CloseBraceToken */));
    }
  }
  function parseTemplateSpan(isTaggedTemplate) {
    const pos = getNodePos();
    return finishNode(
      factory2.createTemplateSpan(
        allowInAnd(parseExpression),
        parseLiteralOfTemplateSpan(isTaggedTemplate)
      ),
      pos
    );
  }
  function parseLiteralNode() {
    return parseLiteralLikeNode(token());
  }
  function parseTemplateHead(isTaggedTemplate) {
    if (!isTaggedTemplate && scanner.getTokenFlags() & 26656 /* IsInvalid */) {
      reScanTemplateToken(
        /*isTaggedTemplate*/
        false
      );
    }
    const fragment = parseLiteralLikeNode(token());
    Debug.assert(fragment.kind === 16 /* TemplateHead */, "Template head has wrong token kind");
    return fragment;
  }
  function parseTemplateMiddleOrTemplateTail() {
    const fragment = parseLiteralLikeNode(token());
    Debug.assert(fragment.kind === 17 /* TemplateMiddle */ || fragment.kind === 18 /* TemplateTail */, "Template fragment has wrong token kind");
    return fragment;
  }
  function getTemplateLiteralRawText(kind) {
    const isLast = kind === 15 /* NoSubstitutionTemplateLiteral */ || kind === 18 /* TemplateTail */;
    const tokenText = scanner.getTokenText();
    return tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
  }
  function parseLiteralLikeNode(kind) {
    const pos = getNodePos();
    const node = isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode(kind, scanner.getTokenValue(), getTemplateLiteralRawText(kind), scanner.getTokenFlags() & 7176 /* TemplateLiteralLikeFlags */) : (
      // Note that theoretically the following condition would hold true literals like 009,
      // which is not octal. But because of how the scanner separates the tokens, we would
      // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
      // We also do not need to check for negatives because any prefix operator would be part of a
      // parent unary expression.
      kind === 9 /* NumericLiteral */ ? factoryCreateNumericLiteral(scanner.getTokenValue(), scanner.getNumericLiteralFlags()) : kind === 11 /* StringLiteral */ ? factoryCreateStringLiteral(
        scanner.getTokenValue(),
        /*isSingleQuote*/
        void 0,
        scanner.hasExtendedUnicodeEscape()
      ) : isLiteralKind(kind) ? factoryCreateLiteralLikeNode(kind, scanner.getTokenValue()) : Debug.fail()
    );
    if (scanner.hasExtendedUnicodeEscape()) {
      node.hasExtendedUnicodeEscape = true;
    }
    if (scanner.isUnterminated()) {
      node.isUnterminated = true;
    }
    nextToken();
    return finishNode(node, pos);
  }
  function parseEntityNameOfTypeReference() {
    return parseEntityName(
      /*allowReservedWords*/
      true,
      Diagnostics.Type_expected
    );
  }
  function parseTypeArgumentsOfTypeReference() {
    if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 30 /* LessThanToken */) {
      return parseBracketedList(20 /* TypeArguments */, parseType, 30 /* LessThanToken */, 32 /* GreaterThanToken */);
    }
  }
  function parseTypeReference() {
    const pos = getNodePos();
    return finishNode(
      factory2.createTypeReferenceNode(
        parseEntityNameOfTypeReference(),
        parseTypeArgumentsOfTypeReference()
      ),
      pos
    );
  }
  function typeHasArrowFunctionBlockingParseError(node) {
    switch (node.kind) {
      case 183 /* TypeReference */:
        return nodeIsMissing(node.typeName);
      case 184 /* FunctionType */:
      case 185 /* ConstructorType */: {
        const { parameters, type } = node;
        return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
      }
      case 196 /* ParenthesizedType */:
        return typeHasArrowFunctionBlockingParseError(node.type);
      default:
        return false;
    }
  }
  function parseThisTypePredicate(lhs) {
    nextToken();
    return finishNode(factory2.createTypePredicateNode(
      /*assertsModifier*/
      void 0,
      lhs,
      parseType()
    ), lhs.pos);
  }
  function parseThisTypeNode() {
    const pos = getNodePos();
    nextToken();
    return finishNode(factory2.createThisTypeNode(), pos);
  }
  function parseJSDocAllType() {
    const pos = getNodePos();
    nextToken();
    return finishNode(factory2.createJSDocAllType(), pos);
  }
  function parseJSDocNonNullableType() {
    const pos = getNodePos();
    nextToken();
    return finishNode(factory2.createJSDocNonNullableType(
      parseNonArrayType(),
      /*postfix*/
      false
    ), pos);
  }
  function parseJSDocUnknownOrNullableType() {
    const pos = getNodePos();
    nextToken();
    if (token() === 28 /* CommaToken */ || token() === 20 /* CloseBraceToken */ || token() === 22 /* CloseParenToken */ || token() === 32 /* GreaterThanToken */ || token() === 64 /* EqualsToken */ || token() === 52 /* BarToken */) {
      return finishNode(factory2.createJSDocUnknownType(), pos);
    } else {
      return finishNode(factory2.createJSDocNullableType(
        parseType(),
        /*postfix*/
        false
      ), pos);
    }
  }
  function parseJSDocFunctionType() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    if (tryParse(nextTokenIsOpenParen)) {
      const parameters = parseParameters(4 /* Type */ | 32 /* JSDoc */);
      const type = parseReturnType(
        59 /* ColonToken */,
        /*isType*/
        false
      );
      return withJSDoc(finishNode(factory2.createJSDocFunctionType(parameters, type), pos), hasJSDoc);
    }
    return finishNode(factory2.createTypeReferenceNode(
      parseIdentifierName(),
      /*typeArguments*/
      void 0
    ), pos);
  }
  function parseJSDocParameter() {
    const pos = getNodePos();
    let name;
    if (token() === 110 /* ThisKeyword */ || token() === 105 /* NewKeyword */) {
      name = parseIdentifierName();
      parseExpected(59 /* ColonToken */);
    }
    return finishNode(
      factory2.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier?
        name,
        /*questionToken*/
        void 0,
        parseJSDocType(),
        /*initializer*/
        void 0
      ),
      pos
    );
  }
  function parseJSDocType() {
    scanner.setSkipJsDocLeadingAsterisks(true);
    const pos = getNodePos();
    if (parseOptional(144 /* ModuleKeyword */)) {
      const moduleTag = factory2.createJSDocNamepathType(
        /*type*/
        void 0
      );
      terminate:
        while (true) {
          switch (token()) {
            case 20 /* CloseBraceToken */:
            case 1 /* EndOfFileToken */:
            case 28 /* CommaToken */:
            case 5 /* WhitespaceTrivia */:
              break terminate;
            default:
              nextTokenJSDoc();
          }
        }
      scanner.setSkipJsDocLeadingAsterisks(false);
      return finishNode(moduleTag, pos);
    }
    const hasDotDotDot = parseOptional(26 /* DotDotDotToken */);
    let type = parseTypeOrTypePredicate();
    scanner.setSkipJsDocLeadingAsterisks(false);
    if (hasDotDotDot) {
      type = finishNode(factory2.createJSDocVariadicType(type), pos);
    }
    if (token() === 64 /* EqualsToken */) {
      nextToken();
      return finishNode(factory2.createJSDocOptionalType(type), pos);
    }
    return type;
  }
  function parseTypeQuery() {
    const pos = getNodePos();
    parseExpected(114 /* TypeOfKeyword */);
    const entityName = parseEntityName(
      /*allowReservedWords*/
      true
    );
    const typeArguments = !scanner.hasPrecedingLineBreak() ? tryParseTypeArguments() : void 0;
    return finishNode(factory2.createTypeQueryNode(entityName, typeArguments), pos);
  }
  function parseTypeParameter() {
    const pos = getNodePos();
    const modifiers = parseModifiers(
      /*allowDecorators*/
      false,
      /*permitConstAsModifier*/
      true
    );
    const name = parseIdentifier();
    let constraint;
    let expression;
    if (parseOptional(96 /* ExtendsKeyword */)) {
      if (isStartOfType() || !isStartOfExpression()) {
        constraint = parseType();
      } else {
        expression = parseUnaryExpressionOrHigher();
      }
    }
    const defaultType = parseOptional(64 /* EqualsToken */) ? parseType() : void 0;
    const node = factory2.createTypeParameterDeclaration(modifiers, name, constraint, defaultType);
    node.expression = expression;
    return finishNode(node, pos);
  }
  function parseTypeParameters() {
    if (token() === 30 /* LessThanToken */) {
      return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 30 /* LessThanToken */, 32 /* GreaterThanToken */);
    }
  }
  function isStartOfParameter(isJSDocParameter) {
    return token() === 26 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern() || isModifierKind(token()) || token() === 60 /* AtToken */ || isStartOfType(
      /*inStartOfParameter*/
      !isJSDocParameter
    );
  }
  function parseNameOfParameter(modifiers) {
    const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
    if (getFullWidth(name) === 0 && !some(modifiers) && isModifierKind(token())) {
      nextToken();
    }
    return name;
  }
  function isParameterNameStart() {
    return isBindingIdentifier() || token() === 23 /* OpenBracketToken */ || token() === 19 /* OpenBraceToken */;
  }
  function parseParameter(inOuterAwaitContext) {
    return parseParameterWorker(inOuterAwaitContext);
  }
  function parseParameterForSpeculation(inOuterAwaitContext) {
    return parseParameterWorker(
      inOuterAwaitContext,
      /*allowAmbiguity*/
      false
    );
  }
  function parseParameterWorker(inOuterAwaitContext, allowAmbiguity = true) {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    const modifiers = inOuterAwaitContext ? doInAwaitContext(() => parseModifiers(
      /*allowDecorators*/
      true
    )) : doOutsideOfAwaitContext(() => parseModifiers(
      /*allowDecorators*/
      true
    ));
    if (token() === 110 /* ThisKeyword */) {
      const node2 = factory2.createParameterDeclaration(
        modifiers,
        /*dotDotDotToken*/
        void 0,
        createIdentifier(
          /*isIdentifier*/
          true
        ),
        /*questionToken*/
        void 0,
        parseTypeAnnotation(),
        /*initializer*/
        void 0
      );
      const modifier = firstOrUndefined(modifiers);
      if (modifier) {
        parseErrorAtRange(modifier, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters);
      }
      return withJSDoc(finishNode(node2, pos), hasJSDoc);
    }
    const savedTopLevel = topLevel;
    topLevel = false;
    const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */);
    if (!allowAmbiguity && !isParameterNameStart()) {
      return void 0;
    }
    const node = withJSDoc(
      finishNode(
        factory2.createParameterDeclaration(
          modifiers,
          dotDotDotToken,
          parseNameOfParameter(modifiers),
          parseOptionalToken(58 /* QuestionToken */),
          parseTypeAnnotation(),
          parseInitializer()
        ),
        pos
      ),
      hasJSDoc
    );
    topLevel = savedTopLevel;
    return node;
  }
  function parseReturnType(returnToken, isType) {
    if (shouldParseReturnType(returnToken, isType)) {
      return allowConditionalTypesAnd(parseTypeOrTypePredicate);
    }
  }
  function shouldParseReturnType(returnToken, isType) {
    if (returnToken === 39 /* EqualsGreaterThanToken */) {
      parseExpected(returnToken);
      return true;
    } else if (parseOptional(59 /* ColonToken */)) {
      return true;
    } else if (isType && token() === 39 /* EqualsGreaterThanToken */) {
      parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(59 /* ColonToken */));
      nextToken();
      return true;
    }
    return false;
  }
  function parseParametersWorker(flags, allowAmbiguity) {
    const savedYieldContext = inYieldContext();
    const savedAwaitContext = inAwaitContext();
    setYieldContext(!!(flags & 1 /* Yield */));
    setAwaitContext(!!(flags & 2 /* Await */));
    const parameters = flags & 32 /* JSDoc */ ? parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : parseDelimitedList(16 /* Parameters */, () => allowAmbiguity ? parseParameter(savedAwaitContext) : parseParameterForSpeculation(savedAwaitContext));
    setYieldContext(savedYieldContext);
    setAwaitContext(savedAwaitContext);
    return parameters;
  }
  function parseParameters(flags) {
    if (!parseExpected(21 /* OpenParenToken */)) {
      return createMissingList();
    }
    const parameters = parseParametersWorker(
      flags,
      /*allowAmbiguity*/
      true
    );
    parseExpected(22 /* CloseParenToken */);
    return parameters;
  }
  function parseTypeMemberSemicolon() {
    if (parseOptional(28 /* CommaToken */)) {
      return;
    }
    parseSemicolon();
  }
  function parseSignatureMember(kind) {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    if (kind === 180 /* ConstructSignature */) {
      parseExpected(105 /* NewKeyword */);
    }
    const typeParameters = parseTypeParameters();
    const parameters = parseParameters(4 /* Type */);
    const type = parseReturnType(
      59 /* ColonToken */,
      /*isType*/
      true
    );
    parseTypeMemberSemicolon();
    const node = kind === 179 /* CallSignature */ ? factory2.createCallSignature(typeParameters, parameters, type) : factory2.createConstructSignature(typeParameters, parameters, type);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function isIndexSignature() {
    return token() === 23 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
  }
  function isUnambiguouslyIndexSignature() {
    nextToken();
    if (token() === 26 /* DotDotDotToken */ || token() === 24 /* CloseBracketToken */) {
      return true;
    }
    if (isModifierKind(token())) {
      nextToken();
      if (isIdentifier2()) {
        return true;
      }
    } else if (!isIdentifier2()) {
      return false;
    } else {
      nextToken();
    }
    if (token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */) {
      return true;
    }
    if (token() !== 58 /* QuestionToken */) {
      return false;
    }
    nextToken();
    return token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || token() === 24 /* CloseBracketToken */;
  }
  function parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers) {
    const parameters = parseBracketedList(16 /* Parameters */, () => parseParameter(
      /*inOuterAwaitContext*/
      false
    ), 23 /* OpenBracketToken */, 24 /* CloseBracketToken */);
    const type = parseTypeAnnotation();
    parseTypeMemberSemicolon();
    const node = factory2.createIndexSignature(modifiers, parameters, type);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) {
    const name = parsePropertyName();
    const questionToken = parseOptionalToken(58 /* QuestionToken */);
    let node;
    if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */) {
      const typeParameters = parseTypeParameters();
      const parameters = parseParameters(4 /* Type */);
      const type = parseReturnType(
        59 /* ColonToken */,
        /*isType*/
        true
      );
      node = factory2.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type);
    } else {
      const type = parseTypeAnnotation();
      node = factory2.createPropertySignature(modifiers, name, questionToken, type);
      if (token() === 64 /* EqualsToken */) node.initializer = parseInitializer();
    }
    parseTypeMemberSemicolon();
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function isTypeMemberStart() {
    if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ || token() === 139 /* GetKeyword */ || token() === 153 /* SetKeyword */) {
      return true;
    }
    let idToken = false;
    while (isModifierKind(token())) {
      idToken = true;
      nextToken();
    }
    if (token() === 23 /* OpenBracketToken */) {
      return true;
    }
    if (isLiteralPropertyName()) {
      idToken = true;
      nextToken();
    }
    if (idToken) {
      return token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ || token() === 58 /* QuestionToken */ || token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || canParseSemicolon();
    }
    return false;
  }
  function parseTypeMember() {
    if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */) {
      return parseSignatureMember(179 /* CallSignature */);
    }
    if (token() === 105 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
      return parseSignatureMember(180 /* ConstructSignature */);
    }
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    const modifiers = parseModifiers(
      /*allowDecorators*/
      false
    );
    if (parseContextualModifier(139 /* GetKeyword */)) {
      return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */, 4 /* Type */);
    }
    if (parseContextualModifier(153 /* SetKeyword */)) {
      return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */, 4 /* Type */);
    }
    if (isIndexSignature()) {
      return parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers);
    }
    return parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers);
  }
  function nextTokenIsOpenParenOrLessThan() {
    nextToken();
    return token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */;
  }
  function nextTokenIsDot() {
    return nextToken() === 25 /* DotToken */;
  }
  function nextTokenIsOpenParenOrLessThanOrDot() {
    switch (nextToken()) {
      case 21 /* OpenParenToken */:
      case 30 /* LessThanToken */:
      case 25 /* DotToken */:
        return true;
    }
    return false;
  }
  function parseTypeLiteral() {
    const pos = getNodePos();
    return finishNode(factory2.createTypeLiteralNode(parseObjectTypeMembers()), pos);
  }
  function parseObjectTypeMembers() {
    let members;
    if (parseExpected(19 /* OpenBraceToken */)) {
      members = parseList(4 /* TypeMembers */, parseTypeMember);
      parseExpected(20 /* CloseBraceToken */);
    } else {
      members = createMissingList();
    }
    return members;
  }
  function isStartOfMappedType() {
    nextToken();
    if (token() === 40 /* PlusToken */ || token() === 41 /* MinusToken */) {
      return nextToken() === 148 /* ReadonlyKeyword */;
    }
    if (token() === 148 /* ReadonlyKeyword */) {
      nextToken();
    }
    return token() === 23 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 103 /* InKeyword */;
  }
  function parseMappedTypeParameter() {
    const pos = getNodePos();
    const name = parseIdentifierName();
    parseExpected(103 /* InKeyword */);
    const type = parseType();
    return finishNode(factory2.createTypeParameterDeclaration(
      /*modifiers*/
      void 0,
      name,
      type,
      /*defaultType*/
      void 0
    ), pos);
  }
  function parseMappedType() {
    const pos = getNodePos();
    parseExpected(19 /* OpenBraceToken */);
    let readonlyToken;
    if (token() === 148 /* ReadonlyKeyword */ || token() === 40 /* PlusToken */ || token() === 41 /* MinusToken */) {
      readonlyToken = parseTokenNode();
      if (readonlyToken.kind !== 148 /* ReadonlyKeyword */) {
        parseExpected(148 /* ReadonlyKeyword */);
      }
    }
    parseExpected(23 /* OpenBracketToken */);
    const typeParameter = parseMappedTypeParameter();
    const nameType = parseOptional(130 /* AsKeyword */) ? parseType() : void 0;
    parseExpected(24 /* CloseBracketToken */);
    let questionToken;
    if (token() === 58 /* QuestionToken */ || token() === 40 /* PlusToken */ || token() === 41 /* MinusToken */) {
      questionToken = parseTokenNode();
      if (questionToken.kind !== 58 /* QuestionToken */) {
        parseExpected(58 /* QuestionToken */);
      }
    }
    const type = parseTypeAnnotation();
    parseSemicolon();
    const members = parseList(4 /* TypeMembers */, parseTypeMember);
    parseExpected(20 /* CloseBraceToken */);
    return finishNode(factory2.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos);
  }
  function parseTupleElementType() {
    const pos = getNodePos();
    if (parseOptional(26 /* DotDotDotToken */)) {
      return finishNode(factory2.createRestTypeNode(parseType()), pos);
    }
    const type = parseType();
    if (isJSDocNullableType(type) && type.pos === type.type.pos) {
      const node = factory2.createOptionalTypeNode(type.type);
      setTextRange(node, type);
      node.flags = type.flags;
      return node;
    }
    return type;
  }
  function isNextTokenColonOrQuestionColon() {
    return nextToken() === 59 /* ColonToken */ || token() === 58 /* QuestionToken */ && nextToken() === 59 /* ColonToken */;
  }
  function isTupleElementName() {
    if (token() === 26 /* DotDotDotToken */) {
      return tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon();
    }
    return tokenIsIdentifierOrKeyword(token()) && isNextTokenColonOrQuestionColon();
  }
  function parseTupleElementNameOrTupleElementType() {
    if (lookAhead(isTupleElementName)) {
      const pos = getNodePos();
      const hasJSDoc = hasPrecedingJSDocComment();
      const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */);
      const name = parseIdentifierName();
      const questionToken = parseOptionalToken(58 /* QuestionToken */);
      parseExpected(59 /* ColonToken */);
      const type = parseTupleElementType();
      const node = factory2.createNamedTupleMember(dotDotDotToken, name, questionToken, type);
      return withJSDoc(finishNode(node, pos), hasJSDoc);
    }
    return parseTupleElementType();
  }
  function parseTupleType() {
    const pos = getNodePos();
    return finishNode(
      factory2.createTupleTypeNode(
        parseBracketedList(21 /* TupleElementTypes */, parseTupleElementNameOrTupleElementType, 23 /* OpenBracketToken */, 24 /* CloseBracketToken */)
      ),
      pos
    );
  }
  function parseParenthesizedType() {
    const pos = getNodePos();
    parseExpected(21 /* OpenParenToken */);
    const type = parseType();
    parseExpected(22 /* CloseParenToken */);
    return finishNode(factory2.createParenthesizedType(type), pos);
  }
  function parseModifiersForConstructorType() {
    let modifiers;
    if (token() === 128 /* AbstractKeyword */) {
      const pos = getNodePos();
      nextToken();
      const modifier = finishNode(factoryCreateToken(128 /* AbstractKeyword */), pos);
      modifiers = createNodeArray([modifier], pos);
    }
    return modifiers;
  }
  function parseFunctionOrConstructorType() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    const modifiers = parseModifiersForConstructorType();
    const isConstructorType = parseOptional(105 /* NewKeyword */);
    Debug.assert(!modifiers || isConstructorType, "Per isStartOfFunctionOrConstructorType, a function type cannot have modifiers.");
    const typeParameters = parseTypeParameters();
    const parameters = parseParameters(4 /* Type */);
    const type = parseReturnType(
      39 /* EqualsGreaterThanToken */,
      /*isType*/
      false
    );
    const node = isConstructorType ? factory2.createConstructorTypeNode(modifiers, typeParameters, parameters, type) : factory2.createFunctionTypeNode(typeParameters, parameters, type);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseKeywordAndNoDot() {
    const node = parseTokenNode();
    return token() === 25 /* DotToken */ ? void 0 : node;
  }
  function parseLiteralTypeNode(negative) {
    const pos = getNodePos();
    if (negative) {
      nextToken();
    }
    let expression = token() === 112 /* TrueKeyword */ || token() === 97 /* FalseKeyword */ || token() === 106 /* NullKeyword */ ? parseTokenNode() : parseLiteralLikeNode(token());
    if (negative) {
      expression = finishNode(factory2.createPrefixUnaryExpression(41 /* MinusToken */, expression), pos);
    }
    return finishNode(factory2.createLiteralTypeNode(expression), pos);
  }
  function isStartOfTypeOfImportType() {
    nextToken();
    return token() === 102 /* ImportKeyword */;
  }
  function parseImportType() {
    sourceFlags |= 4194304 /* PossiblyContainsDynamicImport */;
    const pos = getNodePos();
    const isTypeOf = parseOptional(114 /* TypeOfKeyword */);
    parseExpected(102 /* ImportKeyword */);
    parseExpected(21 /* OpenParenToken */);
    const type = parseType();
    let attributes;
    if (parseOptional(28 /* CommaToken */)) {
      const openBracePosition = scanner.getTokenStart();
      parseExpected(19 /* OpenBraceToken */);
      const currentToken2 = token();
      if (currentToken2 === 118 /* WithKeyword */ || currentToken2 === 132 /* AssertKeyword */) {
        nextToken();
      } else {
        parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(118 /* WithKeyword */));
      }
      parseExpected(59 /* ColonToken */);
      attributes = parseImportAttributes(
        currentToken2,
        /*skipKeyword*/
        true
      );
      if (!parseExpected(20 /* CloseBraceToken */)) {
        const lastError = lastOrUndefined(parseDiagnostics);
        if (lastError && lastError.code === Diagnostics._0_expected.code) {
          addRelatedInfo(
            lastError,
            createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}")
          );
        }
      }
    }
    parseExpected(22 /* CloseParenToken */);
    const qualifier = parseOptional(25 /* DotToken */) ? parseEntityNameOfTypeReference() : void 0;
    const typeArguments = parseTypeArgumentsOfTypeReference();
    return finishNode(factory2.createImportTypeNode(type, attributes, qualifier, typeArguments, isTypeOf), pos);
  }
  function nextTokenIsNumericOrBigIntLiteral() {
    nextToken();
    return token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */;
  }
  function parseNonArrayType() {
    switch (token()) {
      case 133 /* AnyKeyword */:
      case 159 /* UnknownKeyword */:
      case 154 /* StringKeyword */:
      case 150 /* NumberKeyword */:
      case 163 /* BigIntKeyword */:
      case 155 /* SymbolKeyword */:
      case 136 /* BooleanKeyword */:
      case 157 /* UndefinedKeyword */:
      case 146 /* NeverKeyword */:
      case 151 /* ObjectKeyword */:
        return tryParse(parseKeywordAndNoDot) || parseTypeReference();
      case 67 /* AsteriskEqualsToken */:
        scanner.reScanAsteriskEqualsToken();
      // falls through
      case 42 /* AsteriskToken */:
        return parseJSDocAllType();
      case 61 /* QuestionQuestionToken */:
        scanner.reScanQuestionToken();
      // falls through
      case 58 /* QuestionToken */:
        return parseJSDocUnknownOrNullableType();
      case 100 /* FunctionKeyword */:
        return parseJSDocFunctionType();
      case 54 /* ExclamationToken */:
        return parseJSDocNonNullableType();
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 11 /* StringLiteral */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 106 /* NullKeyword */:
        return parseLiteralTypeNode();
      case 41 /* MinusToken */:
        return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(
          /*negative*/
          true
        ) : parseTypeReference();
      case 116 /* VoidKeyword */:
        return parseTokenNode();
      case 110 /* ThisKeyword */: {
        const thisKeyword = parseThisTypeNode();
        if (token() === 142 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
          return parseThisTypePredicate(thisKeyword);
        } else {
          return thisKeyword;
        }
      }
      case 114 /* TypeOfKeyword */:
        return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
      case 19 /* OpenBraceToken */:
        return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
      case 23 /* OpenBracketToken */:
        return parseTupleType();
      case 21 /* OpenParenToken */:
        return parseParenthesizedType();
      case 102 /* ImportKeyword */:
        return parseImportType();
      case 131 /* AssertsKeyword */:
        return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
      case 16 /* TemplateHead */:
        return parseTemplateType();
      default:
        return parseTypeReference();
    }
  }
  function isStartOfType(inStartOfParameter) {
    switch (token()) {
      case 133 /* AnyKeyword */:
      case 159 /* UnknownKeyword */:
      case 154 /* StringKeyword */:
      case 150 /* NumberKeyword */:
      case 163 /* BigIntKeyword */:
      case 136 /* BooleanKeyword */:
      case 148 /* ReadonlyKeyword */:
      case 155 /* SymbolKeyword */:
      case 158 /* UniqueKeyword */:
      case 116 /* VoidKeyword */:
      case 157 /* UndefinedKeyword */:
      case 106 /* NullKeyword */:
      case 110 /* ThisKeyword */:
      case 114 /* TypeOfKeyword */:
      case 146 /* NeverKeyword */:
      case 19 /* OpenBraceToken */:
      case 23 /* OpenBracketToken */:
      case 30 /* LessThanToken */:
      case 52 /* BarToken */:
      case 51 /* AmpersandToken */:
      case 105 /* NewKeyword */:
      case 11 /* StringLiteral */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 151 /* ObjectKeyword */:
      case 42 /* AsteriskToken */:
      case 58 /* QuestionToken */:
      case 54 /* ExclamationToken */:
      case 26 /* DotDotDotToken */:
      case 140 /* InferKeyword */:
      case 102 /* ImportKeyword */:
      case 131 /* AssertsKeyword */:
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 16 /* TemplateHead */:
        return true;
      case 100 /* FunctionKeyword */:
        return !inStartOfParameter;
      case 41 /* MinusToken */:
        return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
      case 21 /* OpenParenToken */:
        return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
      default:
        return isIdentifier2();
    }
  }
  function isStartOfParenthesizedOrFunctionType() {
    nextToken();
    return token() === 22 /* CloseParenToken */ || isStartOfParameter(
      /*isJSDocParameter*/
      false
    ) || isStartOfType();
  }
  function parsePostfixTypeOrHigher() {
    const pos = getNodePos();
    let type = parseNonArrayType();
    while (!scanner.hasPrecedingLineBreak()) {
      switch (token()) {
        case 54 /* ExclamationToken */:
          nextToken();
          type = finishNode(factory2.createJSDocNonNullableType(
            type,
            /*postfix*/
            true
          ), pos);
          break;
        case 58 /* QuestionToken */:
          if (lookAhead(nextTokenIsStartOfType)) {
            return type;
          }
          nextToken();
          type = finishNode(factory2.createJSDocNullableType(
            type,
            /*postfix*/
            true
          ), pos);
          break;
        case 23 /* OpenBracketToken */:
          parseExpected(23 /* OpenBracketToken */);
          if (isStartOfType()) {
            const indexType = parseType();
            parseExpected(24 /* CloseBracketToken */);
            type = finishNode(factory2.createIndexedAccessTypeNode(type, indexType), pos);
          } else {
            parseExpected(24 /* CloseBracketToken */);
            type = finishNode(factory2.createArrayTypeNode(type), pos);
          }
          break;
        default:
          return type;
      }
    }
    return type;
  }
  function parseTypeOperator(operator) {
    const pos = getNodePos();
    parseExpected(operator);
    return finishNode(factory2.createTypeOperatorNode(operator, parseTypeOperatorOrHigher()), pos);
  }
  function tryParseConstraintOfInferType() {
    if (parseOptional(96 /* ExtendsKeyword */)) {
      const constraint = disallowConditionalTypesAnd(parseType);
      if (inDisallowConditionalTypesContext() || token() !== 58 /* QuestionToken */) {
        return constraint;
      }
    }
  }
  function parseTypeParameterOfInferType() {
    const pos = getNodePos();
    const name = parseIdentifier();
    const constraint = tryParse(tryParseConstraintOfInferType);
    const node = factory2.createTypeParameterDeclaration(
      /*modifiers*/
      void 0,
      name,
      constraint
    );
    return finishNode(node, pos);
  }
  function parseInferType() {
    const pos = getNodePos();
    parseExpected(140 /* InferKeyword */);
    return finishNode(factory2.createInferTypeNode(parseTypeParameterOfInferType()), pos);
  }
  function parseTypeOperatorOrHigher() {
    const operator = token();
    switch (operator) {
      case 143 /* KeyOfKeyword */:
      case 158 /* UniqueKeyword */:
      case 148 /* ReadonlyKeyword */:
        return parseTypeOperator(operator);
      case 140 /* InferKeyword */:
        return parseInferType();
    }
    return allowConditionalTypesAnd(parsePostfixTypeOrHigher);
  }
  function parseFunctionOrConstructorTypeToError(isInUnionType) {
    if (isStartOfFunctionTypeOrConstructorType()) {
      const type = parseFunctionOrConstructorType();
      let diagnostic;
      if (isFunctionTypeNode(type)) {
        diagnostic = isInUnionType ? Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_a_union_type : Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
      } else {
        diagnostic = isInUnionType ? Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type : Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
      }
      parseErrorAtRange(type, diagnostic);
      return type;
    }
    return void 0;
  }
  function parseUnionOrIntersectionType(operator, parseConstituentType, createTypeNode) {
    const pos = getNodePos();
    const isUnionType = operator === 52 /* BarToken */;
    const hasLeadingOperator = parseOptional(operator);
    let type = hasLeadingOperator && parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType();
    if (token() === operator || hasLeadingOperator) {
      const types = [type];
      while (parseOptional(operator)) {
        types.push(parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType());
      }
      type = finishNode(createTypeNode(createNodeArray(types, pos)), pos);
    }
    return type;
  }
  function parseIntersectionTypeOrHigher() {
    return parseUnionOrIntersectionType(51 /* AmpersandToken */, parseTypeOperatorOrHigher, factory2.createIntersectionTypeNode);
  }
  function parseUnionTypeOrHigher() {
    return parseUnionOrIntersectionType(52 /* BarToken */, parseIntersectionTypeOrHigher, factory2.createUnionTypeNode);
  }
  function nextTokenIsNewKeyword() {
    nextToken();
    return token() === 105 /* NewKeyword */;
  }
  function isStartOfFunctionTypeOrConstructorType() {
    if (token() === 30 /* LessThanToken */) {
      return true;
    }
    if (token() === 21 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType)) {
      return true;
    }
    return token() === 105 /* NewKeyword */ || token() === 128 /* AbstractKeyword */ && lookAhead(nextTokenIsNewKeyword);
  }
  function skipParameterStart() {
    if (isModifierKind(token())) {
      parseModifiers(
        /*allowDecorators*/
        false
      );
    }
    if (isIdentifier2() || token() === 110 /* ThisKeyword */) {
      nextToken();
      return true;
    }
    if (token() === 23 /* OpenBracketToken */ || token() === 19 /* OpenBraceToken */) {
      const previousErrorCount = parseDiagnostics.length;
      parseIdentifierOrPattern();
      return previousErrorCount === parseDiagnostics.length;
    }
    return false;
  }
  function isUnambiguouslyStartOfFunctionType() {
    nextToken();
    if (token() === 22 /* CloseParenToken */ || token() === 26 /* DotDotDotToken */) {
      return true;
    }
    if (skipParameterStart()) {
      if (token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || token() === 58 /* QuestionToken */ || token() === 64 /* EqualsToken */) {
        return true;
      }
      if (token() === 22 /* CloseParenToken */) {
        nextToken();
        if (token() === 39 /* EqualsGreaterThanToken */) {
          return true;
        }
      }
    }
    return false;
  }
  function parseTypeOrTypePredicate() {
    const pos = getNodePos();
    const typePredicateVariable = isIdentifier2() && tryParse(parseTypePredicatePrefix);
    const type = parseType();
    if (typePredicateVariable) {
      return finishNode(factory2.createTypePredicateNode(
        /*assertsModifier*/
        void 0,
        typePredicateVariable,
        type
      ), pos);
    } else {
      return type;
    }
  }
  function parseTypePredicatePrefix() {
    const id = parseIdentifier();
    if (token() === 142 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
      nextToken();
      return id;
    }
  }
  function parseAssertsTypePredicate() {
    const pos = getNodePos();
    const assertsModifier = parseExpectedToken(131 /* AssertsKeyword */);
    const parameterName = token() === 110 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
    const type = parseOptional(142 /* IsKeyword */) ? parseType() : void 0;
    return finishNode(factory2.createTypePredicateNode(assertsModifier, parameterName, type), pos);
  }
  function parseType() {
    if (contextFlags & 81920 /* TypeExcludesFlags */) {
      return doOutsideOfContext(81920 /* TypeExcludesFlags */, parseType);
    }
    if (isStartOfFunctionTypeOrConstructorType()) {
      return parseFunctionOrConstructorType();
    }
    const pos = getNodePos();
    const type = parseUnionTypeOrHigher();
    if (!inDisallowConditionalTypesContext() && !scanner.hasPrecedingLineBreak() && parseOptional(96 /* ExtendsKeyword */)) {
      const extendsType = disallowConditionalTypesAnd(parseType);
      parseExpected(58 /* QuestionToken */);
      const trueType = allowConditionalTypesAnd(parseType);
      parseExpected(59 /* ColonToken */);
      const falseType = allowConditionalTypesAnd(parseType);
      return finishNode(factory2.createConditionalTypeNode(type, extendsType, trueType, falseType), pos);
    }
    return type;
  }
  function parseTypeAnnotation() {
    return parseOptional(59 /* ColonToken */) ? parseType() : void 0;
  }
  function isStartOfLeftHandSideExpression() {
    switch (token()) {
      case 110 /* ThisKeyword */:
      case 108 /* SuperKeyword */:
      case 106 /* NullKeyword */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 11 /* StringLiteral */:
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 16 /* TemplateHead */:
      case 21 /* OpenParenToken */:
      case 23 /* OpenBracketToken */:
      case 19 /* OpenBraceToken */:
      case 100 /* FunctionKeyword */:
      case 86 /* ClassKeyword */:
      case 105 /* NewKeyword */:
      case 44 /* SlashToken */:
      case 69 /* SlashEqualsToken */:
      case 80 /* Identifier */:
        return true;
      case 102 /* ImportKeyword */:
        return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
      default:
        return isIdentifier2();
    }
  }
  function isStartOfExpression() {
    if (isStartOfLeftHandSideExpression()) {
      return true;
    }
    switch (token()) {
      case 40 /* PlusToken */:
      case 41 /* MinusToken */:
      case 55 /* TildeToken */:
      case 54 /* ExclamationToken */:
      case 91 /* DeleteKeyword */:
      case 114 /* TypeOfKeyword */:
      case 116 /* VoidKeyword */:
      case 46 /* PlusPlusToken */:
      case 47 /* MinusMinusToken */:
      case 30 /* LessThanToken */:
      case 135 /* AwaitKeyword */:
      case 127 /* YieldKeyword */:
      case 81 /* PrivateIdentifier */:
      case 60 /* AtToken */:
        return true;
      default:
        if (isBinaryOperator2()) {
          return true;
        }
        return isIdentifier2();
    }
  }
  function isStartOfExpressionStatement() {
    return token() !== 19 /* OpenBraceToken */ && token() !== 100 /* FunctionKeyword */ && token() !== 86 /* ClassKeyword */ && token() !== 60 /* AtToken */ && isStartOfExpression();
  }
  function parseExpression() {
    const saveDecoratorContext = inDecoratorContext();
    if (saveDecoratorContext) {
      setDecoratorContext(
        /*val*/
        false
      );
    }
    const pos = getNodePos();
    let expr = parseAssignmentExpressionOrHigher(
      /*allowReturnTypeInArrowFunction*/
      true
    );
    let operatorToken;
    while (operatorToken = parseOptionalToken(28 /* CommaToken */)) {
      expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(
        /*allowReturnTypeInArrowFunction*/
        true
      ), pos);
    }
    if (saveDecoratorContext) {
      setDecoratorContext(
        /*val*/
        true
      );
    }
    return expr;
  }
  function parseInitializer() {
    return parseOptional(64 /* EqualsToken */) ? parseAssignmentExpressionOrHigher(
      /*allowReturnTypeInArrowFunction*/
      true
    ) : void 0;
  }
  function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) {
    if (isYieldExpression()) {
      return parseYieldExpression();
    }
    const arrowExpression = tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) || tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction);
    if (arrowExpression) {
      return arrowExpression;
    }
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    const expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
    if (expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */) {
      return parseSimpleArrowFunctionExpression(
        pos,
        expr,
        allowReturnTypeInArrowFunction,
        hasJSDoc,
        /*asyncModifier*/
        void 0
      );
    }
    if (isLeftHandSideExpression(expr) && isAssignmentOperator(reScanGreaterToken())) {
      return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos);
    }
    return parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction);
  }
  function isYieldExpression() {
    if (token() === 127 /* YieldKeyword */) {
      if (inYieldContext()) {
        return true;
      }
      return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
    }
    return false;
  }
  function nextTokenIsIdentifierOnSameLine() {
    nextToken();
    return !scanner.hasPrecedingLineBreak() && isIdentifier2();
  }
  function parseYieldExpression() {
    const pos = getNodePos();
    nextToken();
    if (!scanner.hasPrecedingLineBreak() && (token() === 42 /* AsteriskToken */ || isStartOfExpression())) {
      return finishNode(
        factory2.createYieldExpression(
          parseOptionalToken(42 /* AsteriskToken */),
          parseAssignmentExpressionOrHigher(
            /*allowReturnTypeInArrowFunction*/
            true
          )
        ),
        pos
      );
    } else {
      return finishNode(factory2.createYieldExpression(
        /*asteriskToken*/
        void 0,
        /*expression*/
        void 0
      ), pos);
    }
  }
  function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier) {
    Debug.assert(token() === 39 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
    const parameter = factory2.createParameterDeclaration(
      /*modifiers*/
      void 0,
      /*dotDotDotToken*/
      void 0,
      identifier,
      /*questionToken*/
      void 0,
      /*type*/
      void 0,
      /*initializer*/
      void 0
    );
    finishNode(parameter, identifier.pos);
    const parameters = createNodeArray([parameter], parameter.pos, parameter.end);
    const equalsGreaterThanToken = parseExpectedToken(39 /* EqualsGreaterThanToken */);
    const body = parseArrowFunctionExpressionBody(
      /*isAsync*/
      !!asyncModifier,
      allowReturnTypeInArrowFunction
    );
    const node = factory2.createArrowFunction(
      asyncModifier,
      /*typeParameters*/
      void 0,
      parameters,
      /*type*/
      void 0,
      equalsGreaterThanToken,
      body
    );
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) {
    const triState = isParenthesizedArrowFunctionExpression();
    if (triState === 0 /* False */) {
      return void 0;
    }
    return triState === 1 /* True */ ? parseParenthesizedArrowFunctionExpression(
      /*allowAmbiguity*/
      true,
      /*allowReturnTypeInArrowFunction*/
      true
    ) : tryParse(() => parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction));
  }
  function isParenthesizedArrowFunctionExpression() {
    if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ || token() === 134 /* AsyncKeyword */) {
      return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
    }
    if (token() === 39 /* EqualsGreaterThanToken */) {
      return 1 /* True */;
    }
    return 0 /* False */;
  }
  function isParenthesizedArrowFunctionExpressionWorker() {
    if (token() === 134 /* AsyncKeyword */) {
      nextToken();
      if (scanner.hasPrecedingLineBreak()) {
        return 0 /* False */;
      }
      if (token() !== 21 /* OpenParenToken */ && token() !== 30 /* LessThanToken */) {
        return 0 /* False */;
      }
    }
    const first2 = token();
    const second = nextToken();
    if (first2 === 21 /* OpenParenToken */) {
      if (second === 22 /* CloseParenToken */) {
        const third = nextToken();
        switch (third) {
          case 39 /* EqualsGreaterThanToken */:
          case 59 /* ColonToken */:
          case 19 /* OpenBraceToken */:
            return 1 /* True */;
          default:
            return 0 /* False */;
        }
      }
      if (second === 23 /* OpenBracketToken */ || second === 19 /* OpenBraceToken */) {
        return 2 /* Unknown */;
      }
      if (second === 26 /* DotDotDotToken */) {
        return 1 /* True */;
      }
      if (isModifierKind(second) && second !== 134 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
        if (nextToken() === 130 /* AsKeyword */) {
          return 0 /* False */;
        }
        return 1 /* True */;
      }
      if (!isIdentifier2() && second !== 110 /* ThisKeyword */) {
        return 0 /* False */;
      }
      switch (nextToken()) {
        case 59 /* ColonToken */:
          return 1 /* True */;
        case 58 /* QuestionToken */:
          nextToken();
          if (token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || token() === 64 /* EqualsToken */ || token() === 22 /* CloseParenToken */) {
            return 1 /* True */;
          }
          return 0 /* False */;
        case 28 /* CommaToken */:
        case 64 /* EqualsToken */:
        case 22 /* CloseParenToken */:
          return 2 /* Unknown */;
      }
      return 0 /* False */;
    } else {
      Debug.assert(first2 === 30 /* LessThanToken */);
      if (!isIdentifier2() && token() !== 87 /* ConstKeyword */) {
        return 0 /* False */;
      }
      if (languageVariant === 1 /* JSX */) {
        const isArrowFunctionInJsx = lookAhead(() => {
          parseOptional(87 /* ConstKeyword */);
          const third = nextToken();
          if (third === 96 /* ExtendsKeyword */) {
            const fourth = nextToken();
            switch (fourth) {
              case 64 /* EqualsToken */:
              case 32 /* GreaterThanToken */:
              case 44 /* SlashToken */:
                return false;
              default:
                return true;
            }
          } else if (third === 28 /* CommaToken */ || third === 64 /* EqualsToken */) {
            return true;
          }
          return false;
        });
        if (isArrowFunctionInJsx) {
          return 1 /* True */;
        }
        return 0 /* False */;
      }
      return 2 /* Unknown */;
    }
  }
  function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) {
    const tokenPos = scanner.getTokenStart();
    if (notParenthesizedArrow == null ? void 0 : notParenthesizedArrow.has(tokenPos)) {
      return void 0;
    }
    const result = parseParenthesizedArrowFunctionExpression(
      /*allowAmbiguity*/
      false,
      allowReturnTypeInArrowFunction
    );
    if (!result) {
      (notParenthesizedArrow || (notParenthesizedArrow = /* @__PURE__ */ new Set())).add(tokenPos);
    }
    return result;
  }
  function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction) {
    if (token() === 134 /* AsyncKeyword */) {
      if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
        const pos = getNodePos();
        const hasJSDoc = hasPrecedingJSDocComment();
        const asyncModifier = parseModifiersForArrowFunction();
        const expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
        return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier);
      }
    }
    return void 0;
  }
  function isUnParenthesizedAsyncArrowFunctionWorker() {
    if (token() === 134 /* AsyncKeyword */) {
      nextToken();
      if (scanner.hasPrecedingLineBreak() || token() === 39 /* EqualsGreaterThanToken */) {
        return 0 /* False */;
      }
      const expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
      if (!scanner.hasPrecedingLineBreak() && expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */) {
        return 1 /* True */;
      }
    }
    return 0 /* False */;
  }
  function parseParenthesizedArrowFunctionExpression(allowAmbiguity, allowReturnTypeInArrowFunction) {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    const modifiers = parseModifiersForArrowFunction();
    const isAsync = some(modifiers, isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
    const typeParameters = parseTypeParameters();
    let parameters;
    if (!parseExpected(21 /* OpenParenToken */)) {
      if (!allowAmbiguity) {
        return void 0;
      }
      parameters = createMissingList();
    } else {
      if (!allowAmbiguity) {
        const maybeParameters = parseParametersWorker(isAsync, allowAmbiguity);
        if (!maybeParameters) {
          return void 0;
        }
        parameters = maybeParameters;
      } else {
        parameters = parseParametersWorker(isAsync, allowAmbiguity);
      }
      if (!parseExpected(22 /* CloseParenToken */) && !allowAmbiguity) {
        return void 0;
      }
    }
    const hasReturnColon = token() === 59 /* ColonToken */;
    const type = parseReturnType(
      59 /* ColonToken */,
      /*isType*/
      false
    );
    if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) {
      return void 0;
    }
    let unwrappedType = type;
    while ((unwrappedType == null ? void 0 : unwrappedType.kind) === 196 /* ParenthesizedType */) {
      unwrappedType = unwrappedType.type;
    }
    const hasJSDocFunctionType = unwrappedType && isJSDocFunctionType(unwrappedType);
    if (!allowAmbiguity && token() !== 39 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 19 /* OpenBraceToken */)) {
      return void 0;
    }
    const lastToken = token();
    const equalsGreaterThanToken = parseExpectedToken(39 /* EqualsGreaterThanToken */);
    const body = lastToken === 39 /* EqualsGreaterThanToken */ || lastToken === 19 /* OpenBraceToken */ ? parseArrowFunctionExpressionBody(some(modifiers, isAsyncModifier), allowReturnTypeInArrowFunction) : parseIdentifier();
    if (!allowReturnTypeInArrowFunction && hasReturnColon) {
      if (token() !== 59 /* ColonToken */) {
        return void 0;
      }
    }
    const node = factory2.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseArrowFunctionExpressionBody(isAsync, allowReturnTypeInArrowFunction) {
    if (token() === 19 /* OpenBraceToken */) {
      return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
    }
    if (token() !== 27 /* SemicolonToken */ && token() !== 100 /* FunctionKeyword */ && token() !== 86 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) {
      return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
    }
    const savedTopLevel = topLevel;
    topLevel = false;
    const node = isAsync ? doInAwaitContext(() => parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction)) : doOutsideOfAwaitContext(() => parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction));
    topLevel = savedTopLevel;
    return node;
  }
  function parseConditionalExpressionRest(leftOperand, pos, allowReturnTypeInArrowFunction) {
    const questionToken = parseOptionalToken(58 /* QuestionToken */);
    if (!questionToken) {
      return leftOperand;
    }
    let colonToken;
    return finishNode(
      factory2.createConditionalExpression(
        leftOperand,
        questionToken,
        doOutsideOfContext(disallowInAndDecoratorContext, () => parseAssignmentExpressionOrHigher(
          /*allowReturnTypeInArrowFunction*/
          false
        )),
        colonToken = parseExpectedToken(59 /* ColonToken */),
        nodeIsPresent(colonToken) ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode(
          80 /* Identifier */,
          /*reportAtCurrentPosition*/
          false,
          Diagnostics._0_expected,
          tokenToString(59 /* ColonToken */)
        )
      ),
      pos
    );
  }
  function parseBinaryExpressionOrHigher(precedence) {
    const pos = getNodePos();
    const leftOperand = parseUnaryExpressionOrHigher();
    return parseBinaryExpressionRest(precedence, leftOperand, pos);
  }
  function isInOrOfKeyword(t) {
    return t === 103 /* InKeyword */ || t === 165 /* OfKeyword */;
  }
  function parseBinaryExpressionRest(precedence, leftOperand, pos) {
    while (true) {
      reScanGreaterToken();
      const newPrecedence = getBinaryOperatorPrecedence(token());
      const consumeCurrentOperator = token() === 43 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence;
      if (!consumeCurrentOperator) {
        break;
      }
      if (token() === 103 /* InKeyword */ && inDisallowInContext()) {
        break;
      }
      if (token() === 130 /* AsKeyword */ || token() === 152 /* SatisfiesKeyword */) {
        if (scanner.hasPrecedingLineBreak()) {
          break;
        } else {
          const keywordKind = token();
          nextToken();
          leftOperand = keywordKind === 152 /* SatisfiesKeyword */ ? makeSatisfiesExpression(leftOperand, parseType()) : makeAsExpression(leftOperand, parseType());
        }
      } else {
        leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence), pos);
      }
    }
    return leftOperand;
  }
  function isBinaryOperator2() {
    if (inDisallowInContext() && token() === 103 /* InKeyword */) {
      return false;
    }
    return getBinaryOperatorPrecedence(token()) > 0;
  }
  function makeSatisfiesExpression(left, right) {
    return finishNode(factory2.createSatisfiesExpression(left, right), left.pos);
  }
  function makeBinaryExpression(left, operatorToken, right, pos) {
    return finishNode(factory2.createBinaryExpression(left, operatorToken, right), pos);
  }
  function makeAsExpression(left, right) {
    return finishNode(factory2.createAsExpression(left, right), left.pos);
  }
  function parsePrefixUnaryExpression() {
    const pos = getNodePos();
    return finishNode(factory2.createPrefixUnaryExpression(token(), nextTokenAnd(parseSimpleUnaryExpression)), pos);
  }
  function parseDeleteExpression() {
    const pos = getNodePos();
    return finishNode(factory2.createDeleteExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
  }
  function parseTypeOfExpression() {
    const pos = getNodePos();
    return finishNode(factory2.createTypeOfExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
  }
  function parseVoidExpression() {
    const pos = getNodePos();
    return finishNode(factory2.createVoidExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
  }
  function isAwaitExpression2() {
    if (token() === 135 /* AwaitKeyword */) {
      if (inAwaitContext()) {
        return true;
      }
      return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
    }
    return false;
  }
  function parseAwaitExpression() {
    const pos = getNodePos();
    return finishNode(factory2.createAwaitExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
  }
  function parseUnaryExpressionOrHigher() {
    if (isUpdateExpression()) {
      const pos = getNodePos();
      const updateExpression = parseUpdateExpression();
      return token() === 43 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(token()), updateExpression, pos) : updateExpression;
    }
    const unaryOperator = token();
    const simpleUnaryExpression = parseSimpleUnaryExpression();
    if (token() === 43 /* AsteriskAsteriskToken */) {
      const pos = skipTrivia(sourceText, simpleUnaryExpression.pos);
      const { end } = simpleUnaryExpression;
      if (simpleUnaryExpression.kind === 216 /* TypeAssertionExpression */) {
        parseErrorAt(pos, end, Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses);
      } else {
        Debug.assert(isKeywordOrPunctuation(unaryOperator));
        parseErrorAt(pos, end, Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, tokenToString(unaryOperator));
      }
    }
    return simpleUnaryExpression;
  }
  function parseSimpleUnaryExpression() {
    switch (token()) {
      case 40 /* PlusToken */:
      case 41 /* MinusToken */:
      case 55 /* TildeToken */:
      case 54 /* ExclamationToken */:
        return parsePrefixUnaryExpression();
      case 91 /* DeleteKeyword */:
        return parseDeleteExpression();
      case 114 /* TypeOfKeyword */:
        return parseTypeOfExpression();
      case 116 /* VoidKeyword */:
        return parseVoidExpression();
      case 30 /* LessThanToken */:
        if (languageVariant === 1 /* JSX */) {
          return parseJsxElementOrSelfClosingElementOrFragment(
            /*inExpressionContext*/
            true,
            /*topInvalidNodePosition*/
            void 0,
            /*openingTag*/
            void 0,
            /*mustBeUnary*/
            true
          );
        }
        return parseTypeAssertion();
      case 135 /* AwaitKeyword */:
        if (isAwaitExpression2()) {
          return parseAwaitExpression();
        }
      // falls through
      default:
        return parseUpdateExpression();
    }
  }
  function isUpdateExpression() {
    switch (token()) {
      case 40 /* PlusToken */:
      case 41 /* MinusToken */:
      case 55 /* TildeToken */:
      case 54 /* ExclamationToken */:
      case 91 /* DeleteKeyword */:
      case 114 /* TypeOfKeyword */:
      case 116 /* VoidKeyword */:
      case 135 /* AwaitKeyword */:
        return false;
      case 30 /* LessThanToken */:
        if (languageVariant !== 1 /* JSX */) {
          return false;
        }
      // We are in JSX context and the token is part of JSXElement.
      // falls through
      default:
        return true;
    }
  }
  function parseUpdateExpression() {
    if (token() === 46 /* PlusPlusToken */ || token() === 47 /* MinusMinusToken */) {
      const pos = getNodePos();
      return finishNode(factory2.createPrefixUnaryExpression(token(), nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos);
    } else if (languageVariant === 1 /* JSX */ && token() === 30 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
      return parseJsxElementOrSelfClosingElementOrFragment(
        /*inExpressionContext*/
        true
      );
    }
    const expression = parseLeftHandSideExpressionOrHigher();
    Debug.assert(isLeftHandSideExpression(expression));
    if ((token() === 46 /* PlusPlusToken */ || token() === 47 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
      const operator = token();
      nextToken();
      return finishNode(factory2.createPostfixUnaryExpression(expression, operator), expression.pos);
    }
    return expression;
  }
  function parseLeftHandSideExpressionOrHigher() {
    const pos = getNodePos();
    let expression;
    if (token() === 102 /* ImportKeyword */) {
      if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
        sourceFlags |= 4194304 /* PossiblyContainsDynamicImport */;
        expression = parseTokenNode();
      } else if (lookAhead(nextTokenIsDot)) {
        nextToken();
        nextToken();
        expression = finishNode(factory2.createMetaProperty(102 /* ImportKeyword */, parseIdentifierName()), pos);
        sourceFlags |= 8388608 /* PossiblyContainsImportMeta */;
      } else {
        expression = parseMemberExpressionOrHigher();
      }
    } else {
      expression = token() === 108 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
    }
    return parseCallExpressionRest(pos, expression);
  }
  function parseMemberExpressionOrHigher() {
    const pos = getNodePos();
    const expression = parsePrimaryExpression();
    return parseMemberExpressionRest(
      pos,
      expression,
      /*allowOptionalChain*/
      true
    );
  }
  function parseSuperExpression() {
    const pos = getNodePos();
    let expression = parseTokenNode();
    if (token() === 30 /* LessThanToken */) {
      const startPos = getNodePos();
      const typeArguments = tryParse(parseTypeArgumentsInExpression);
      if (typeArguments !== void 0) {
        parseErrorAt(startPos, getNodePos(), Diagnostics.super_may_not_use_type_arguments);
        if (!isTemplateStartOfTaggedTemplate()) {
          expression = factory2.createExpressionWithTypeArguments(expression, typeArguments);
        }
      }
    }
    if (token() === 21 /* OpenParenToken */ || token() === 25 /* DotToken */ || token() === 23 /* OpenBracketToken */) {
      return expression;
    }
    parseExpectedToken(25 /* DotToken */, Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
    return finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot(
      /*allowIdentifierNames*/
      true,
      /*allowPrivateIdentifiers*/
      true,
      /*allowUnicodeEscapeSequenceInIdentifierName*/
      true
    )), pos);
  }
  function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext, topInvalidNodePosition, openingTag, mustBeUnary = false) {
    const pos = getNodePos();
    const opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
    let result;
    if (opening.kind === 286 /* JsxOpeningElement */) {
      let children = parseJsxChildren(opening);
      let closingElement;
      const lastChild = children[children.length - 1];
      if ((lastChild == null ? void 0 : lastChild.kind) === 284 /* JsxElement */ && !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName) && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName)) {
        const end = lastChild.children.end;
        const newLast = finishNode(
          factory2.createJsxElement(
            lastChild.openingElement,
            lastChild.children,
            finishNode(factory2.createJsxClosingElement(finishNode(factoryCreateIdentifier(""), end, end)), end, end)
          ),
          lastChild.openingElement.pos,
          end
        );
        children = createNodeArray([...children.slice(0, children.length - 1), newLast], children.pos, end);
        closingElement = lastChild.closingElement;
      } else {
        closingElement = parseJsxClosingElement(opening, inExpressionContext);
        if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) {
          if (openingTag && isJsxOpeningElement(openingTag) && tagNamesAreEquivalent(closingElement.tagName, openingTag.tagName)) {
            parseErrorAtRange(opening.tagName, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, opening.tagName));
          } else {
            parseErrorAtRange(closingElement.tagName, Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, getTextOfNodeFromSourceText(sourceText, opening.tagName));
          }
        }
      }
      result = finishNode(factory2.createJsxElement(opening, children, closingElement), pos);
    } else if (opening.kind === 289 /* JsxOpeningFragment */) {
      result = finishNode(factory2.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos);
    } else {
      Debug.assert(opening.kind === 285 /* JsxSelfClosingElement */);
      result = opening;
    }
    if (!mustBeUnary && inExpressionContext && token() === 30 /* LessThanToken */) {
      const topBadPos = typeof topInvalidNodePosition === "undefined" ? result.pos : topInvalidNodePosition;
      const invalidElement = tryParse(() => parseJsxElementOrSelfClosingElementOrFragment(
        /*inExpressionContext*/
        true,
        topBadPos
      ));
      if (invalidElement) {
        const operatorToken = createMissingNode(
          28 /* CommaToken */,
          /*reportAtCurrentPosition*/
          false
        );
        setTextRangePosWidth(operatorToken, invalidElement.pos, 0);
        parseErrorAt(skipTrivia(sourceText, topBadPos), invalidElement.end, Diagnostics.JSX_expressions_must_have_one_parent_element);
        return finishNode(factory2.createBinaryExpression(result, operatorToken, invalidElement), pos);
      }
    }
    return result;
  }
  function parseJsxText() {
    const pos = getNodePos();
    const node = factory2.createJsxText(scanner.getTokenValue(), currentToken === 13 /* JsxTextAllWhiteSpaces */);
    currentToken = scanner.scanJsxToken();
    return finishNode(node, pos);
  }
  function parseJsxChild(openingTag, token2) {
    switch (token2) {
      case 1 /* EndOfFileToken */:
        if (isJsxOpeningFragment(openingTag)) {
          parseErrorAtRange(openingTag, Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
        } else {
          const tag = openingTag.tagName;
          const start = Math.min(skipTrivia(sourceText, tag.pos), tag.end);
          parseErrorAt(start, tag.end, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
        }
        return void 0;
      case 31 /* LessThanSlashToken */:
      case 7 /* ConflictMarkerTrivia */:
        return void 0;
      case 12 /* JsxText */:
      case 13 /* JsxTextAllWhiteSpaces */:
        return parseJsxText();
      case 19 /* OpenBraceToken */:
        return parseJsxExpression(
          /*inExpressionContext*/
          false
        );
      case 30 /* LessThanToken */:
        return parseJsxElementOrSelfClosingElementOrFragment(
          /*inExpressionContext*/
          false,
          /*topInvalidNodePosition*/
          void 0,
          openingTag
        );
      default:
        return Debug.assertNever(token2);
    }
  }
  function parseJsxChildren(openingTag) {
    const list = [];
    const listPos = getNodePos();
    const saveParsingContext = parsingContext;
    parsingContext |= 1 << 14 /* JsxChildren */;
    while (true) {
      const child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
      if (!child) break;
      list.push(child);
      if (isJsxOpeningElement(openingTag) && (child == null ? void 0 : child.kind) === 284 /* JsxElement */ && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName) && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName)) {
        break;
      }
    }
    parsingContext = saveParsingContext;
    return createNodeArray(list, listPos);
  }
  function parseJsxAttributes() {
    const pos = getNodePos();
    return finishNode(factory2.createJsxAttributes(parseList(13 /* JsxAttributes */, parseJsxAttribute)), pos);
  }
  function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
    const pos = getNodePos();
    parseExpected(30 /* LessThanToken */);
    if (token() === 32 /* GreaterThanToken */) {
      scanJsxText();
      return finishNode(factory2.createJsxOpeningFragment(), pos);
    }
    const tagName = parseJsxElementName();
    const typeArguments = (contextFlags & 524288 /* JavaScriptFile */) === 0 ? tryParseTypeArguments() : void 0;
    const attributes = parseJsxAttributes();
    let node;
    if (token() === 32 /* GreaterThanToken */) {
      scanJsxText();
      node = factory2.createJsxOpeningElement(tagName, typeArguments, attributes);
    } else {
      parseExpected(44 /* SlashToken */);
      if (parseExpected(
        32 /* GreaterThanToken */,
        /*diagnosticMessage*/
        void 0,
        /*shouldAdvance*/
        false
      )) {
        if (inExpressionContext) {
          nextToken();
        } else {
          scanJsxText();
        }
      }
      node = factory2.createJsxSelfClosingElement(tagName, typeArguments, attributes);
    }
    return finishNode(node, pos);
  }
  function parseJsxElementName() {
    const pos = getNodePos();
    const initialExpression = parseJsxTagName();
    if (isJsxNamespacedName(initialExpression)) {
      return initialExpression;
    }
    let expression = initialExpression;
    while (parseOptional(25 /* DotToken */)) {
      expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot(
        /*allowIdentifierNames*/
        true,
        /*allowPrivateIdentifiers*/
        false,
        /*allowUnicodeEscapeSequenceInIdentifierName*/
        false
      )), pos);
    }
    return expression;
  }
  function parseJsxTagName() {
    const pos = getNodePos();
    scanJsxIdentifier();
    const isThis = token() === 110 /* ThisKeyword */;
    const tagName = parseIdentifierNameErrorOnUnicodeEscapeSequence();
    if (parseOptional(59 /* ColonToken */)) {
      scanJsxIdentifier();
      return finishNode(factory2.createJsxNamespacedName(tagName, parseIdentifierNameErrorOnUnicodeEscapeSequence()), pos);
    }
    return isThis ? finishNode(factory2.createToken(110 /* ThisKeyword */), pos) : tagName;
  }
  function parseJsxExpression(inExpressionContext) {
    const pos = getNodePos();
    if (!parseExpected(19 /* OpenBraceToken */)) {
      return void 0;
    }
    let dotDotDotToken;
    let expression;
    if (token() !== 20 /* CloseBraceToken */) {
      if (!inExpressionContext) {
        dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */);
      }
      expression = parseExpression();
    }
    if (inExpressionContext) {
      parseExpected(20 /* CloseBraceToken */);
    } else {
      if (parseExpected(
        20 /* CloseBraceToken */,
        /*diagnosticMessage*/
        void 0,
        /*shouldAdvance*/
        false
      )) {
        scanJsxText();
      }
    }
    return finishNode(factory2.createJsxExpression(dotDotDotToken, expression), pos);
  }
  function parseJsxAttribute() {
    if (token() === 19 /* OpenBraceToken */) {
      return parseJsxSpreadAttribute();
    }
    const pos = getNodePos();
    return finishNode(factory2.createJsxAttribute(parseJsxAttributeName(), parseJsxAttributeValue()), pos);
  }
  function parseJsxAttributeValue() {
    if (token() === 64 /* EqualsToken */) {
      if (scanJsxAttributeValue() === 11 /* StringLiteral */) {
        return parseLiteralNode();
      }
      if (token() === 19 /* OpenBraceToken */) {
        return parseJsxExpression(
          /*inExpressionContext*/
          true
        );
      }
      if (token() === 30 /* LessThanToken */) {
        return parseJsxElementOrSelfClosingElementOrFragment(
          /*inExpressionContext*/
          true
        );
      }
      parseErrorAtCurrentToken(Diagnostics.or_JSX_element_expected);
    }
    return void 0;
  }
  function parseJsxAttributeName() {
    const pos = getNodePos();
    scanJsxIdentifier();
    const attrName = parseIdentifierNameErrorOnUnicodeEscapeSequence();
    if (parseOptional(59 /* ColonToken */)) {
      scanJsxIdentifier();
      return finishNode(factory2.createJsxNamespacedName(attrName, parseIdentifierNameErrorOnUnicodeEscapeSequence()), pos);
    }
    return attrName;
  }
  function parseJsxSpreadAttribute() {
    const pos = getNodePos();
    parseExpected(19 /* OpenBraceToken */);
    parseExpected(26 /* DotDotDotToken */);
    const expression = parseExpression();
    parseExpected(20 /* CloseBraceToken */);
    return finishNode(factory2.createJsxSpreadAttribute(expression), pos);
  }
  function parseJsxClosingElement(open, inExpressionContext) {
    const pos = getNodePos();
    parseExpected(31 /* LessThanSlashToken */);
    const tagName = parseJsxElementName();
    if (parseExpected(
      32 /* GreaterThanToken */,
      /*diagnosticMessage*/
      void 0,
      /*shouldAdvance*/
      false
    )) {
      if (inExpressionContext || !tagNamesAreEquivalent(open.tagName, tagName)) {
        nextToken();
      } else {
        scanJsxText();
      }
    }
    return finishNode(factory2.createJsxClosingElement(tagName), pos);
  }
  function parseJsxClosingFragment(inExpressionContext) {
    const pos = getNodePos();
    parseExpected(31 /* LessThanSlashToken */);
    if (parseExpected(
      32 /* GreaterThanToken */,
      Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment,
      /*shouldAdvance*/
      false
    )) {
      if (inExpressionContext) {
        nextToken();
      } else {
        scanJsxText();
      }
    }
    return finishNode(factory2.createJsxJsxClosingFragment(), pos);
  }
  function parseTypeAssertion() {
    Debug.assert(languageVariant !== 1 /* JSX */, "Type assertions should never be parsed in JSX; they should be parsed as comparisons or JSX elements/fragments.");
    const pos = getNodePos();
    parseExpected(30 /* LessThanToken */);
    const type = parseType();
    parseExpected(32 /* GreaterThanToken */);
    const expression = parseSimpleUnaryExpression();
    return finishNode(factory2.createTypeAssertion(type, expression), pos);
  }
  function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
    nextToken();
    return tokenIsIdentifierOrKeyword(token()) || token() === 23 /* OpenBracketToken */ || isTemplateStartOfTaggedTemplate();
  }
  function isStartOfOptionalPropertyOrElementAccessChain() {
    return token() === 29 /* QuestionDotToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
  }
  function tryReparseOptionalChain(node) {
    if (node.flags & 64 /* OptionalChain */) {
      return true;
    }
    if (isNonNullExpression(node)) {
      let expr = node.expression;
      while (isNonNullExpression(expr) && !(expr.flags & 64 /* OptionalChain */)) {
        expr = expr.expression;
      }
      if (expr.flags & 64 /* OptionalChain */) {
        while (isNonNullExpression(node)) {
          node.flags |= 64 /* OptionalChain */;
          node = node.expression;
        }
        return true;
      }
    }
    return false;
  }
  function parsePropertyAccessExpressionRest(pos, expression, questionDotToken) {
    const name = parseRightSideOfDot(
      /*allowIdentifierNames*/
      true,
      /*allowPrivateIdentifiers*/
      true,
      /*allowUnicodeEscapeSequenceInIdentifierName*/
      true
    );
    const isOptionalChain2 = questionDotToken || tryReparseOptionalChain(expression);
    const propertyAccess = isOptionalChain2 ? factoryCreatePropertyAccessChain(expression, questionDotToken, name) : factoryCreatePropertyAccessExpression(expression, name);
    if (isOptionalChain2 && isPrivateIdentifier(propertyAccess.name)) {
      parseErrorAtRange(propertyAccess.name, Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
    }
    if (isExpressionWithTypeArguments(expression) && expression.typeArguments) {
      const pos2 = expression.typeArguments.pos - 1;
      const end = skipTrivia(sourceText, expression.typeArguments.end) + 1;
      parseErrorAt(pos2, end, Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access);
    }
    return finishNode(propertyAccess, pos);
  }
  function parseElementAccessExpressionRest(pos, expression, questionDotToken) {
    let argumentExpression;
    if (token() === 24 /* CloseBracketToken */) {
      argumentExpression = createMissingNode(
        80 /* Identifier */,
        /*reportAtCurrentPosition*/
        true,
        Diagnostics.An_element_access_expression_should_take_an_argument
      );
    } else {
      const argument = allowInAnd(parseExpression);
      if (isStringOrNumericLiteralLike(argument)) {
        argument.text = internIdentifier(argument.text);
      }
      argumentExpression = argument;
    }
    parseExpected(24 /* CloseBracketToken */);
    const indexedAccess = questionDotToken || tryReparseOptionalChain(expression) ? factoryCreateElementAccessChain(expression, questionDotToken, argumentExpression) : factoryCreateElementAccessExpression(expression, argumentExpression);
    return finishNode(indexedAccess, pos);
  }
  function parseMemberExpressionRest(pos, expression, allowOptionalChain) {
    while (true) {
      let questionDotToken;
      let isPropertyAccess = false;
      if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
        questionDotToken = parseExpectedToken(29 /* QuestionDotToken */);
        isPropertyAccess = tokenIsIdentifierOrKeyword(token());
      } else {
        isPropertyAccess = parseOptional(25 /* DotToken */);
      }
      if (isPropertyAccess) {
        expression = parsePropertyAccessExpressionRest(pos, expression, questionDotToken);
        continue;
      }
      if ((questionDotToken || !inDecoratorContext()) && parseOptional(23 /* OpenBracketToken */)) {
        expression = parseElementAccessExpressionRest(pos, expression, questionDotToken);
        continue;
      }
      if (isTemplateStartOfTaggedTemplate()) {
        expression = !questionDotToken && expression.kind === 233 /* ExpressionWithTypeArguments */ ? parseTaggedTemplateRest(pos, expression.expression, questionDotToken, expression.typeArguments) : parseTaggedTemplateRest(
          pos,
          expression,
          questionDotToken,
          /*typeArguments*/
          void 0
        );
        continue;
      }
      if (!questionDotToken) {
        if (token() === 54 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
          nextToken();
          expression = finishNode(factory2.createNonNullExpression(expression), pos);
          continue;
        }
        const typeArguments = tryParse(parseTypeArgumentsInExpression);
        if (typeArguments) {
          expression = finishNode(factory2.createExpressionWithTypeArguments(expression, typeArguments), pos);
          continue;
        }
      }
      return expression;
    }
  }
  function isTemplateStartOfTaggedTemplate() {
    return token() === 15 /* NoSubstitutionTemplateLiteral */ || token() === 16 /* TemplateHead */;
  }
  function parseTaggedTemplateRest(pos, tag, questionDotToken, typeArguments) {
    const tagExpression = factory2.createTaggedTemplateExpression(
      tag,
      typeArguments,
      token() === 15 /* NoSubstitutionTemplateLiteral */ ? (reScanTemplateToken(
        /*isTaggedTemplate*/
        true
      ), parseLiteralNode()) : parseTemplateExpression(
        /*isTaggedTemplate*/
        true
      )
    );
    if (questionDotToken || tag.flags & 64 /* OptionalChain */) {
      tagExpression.flags |= 64 /* OptionalChain */;
    }
    tagExpression.questionDotToken = questionDotToken;
    return finishNode(tagExpression, pos);
  }
  function parseCallExpressionRest(pos, expression) {
    while (true) {
      expression = parseMemberExpressionRest(
        pos,
        expression,
        /*allowOptionalChain*/
        true
      );
      let typeArguments;
      const questionDotToken = parseOptionalToken(29 /* QuestionDotToken */);
      if (questionDotToken) {
        typeArguments = tryParse(parseTypeArgumentsInExpression);
        if (isTemplateStartOfTaggedTemplate()) {
          expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments);
          continue;
        }
      }
      if (typeArguments || token() === 21 /* OpenParenToken */) {
        if (!questionDotToken && expression.kind === 233 /* ExpressionWithTypeArguments */) {
          typeArguments = expression.typeArguments;
          expression = expression.expression;
        }
        const argumentList = parseArgumentList();
        const callExpr = questionDotToken || tryReparseOptionalChain(expression) ? factoryCreateCallChain(expression, questionDotToken, typeArguments, argumentList) : factoryCreateCallExpression(expression, typeArguments, argumentList);
        expression = finishNode(callExpr, pos);
        continue;
      }
      if (questionDotToken) {
        const name = createMissingNode(
          80 /* Identifier */,
          /*reportAtCurrentPosition*/
          false,
          Diagnostics.Identifier_expected
        );
        expression = finishNode(factoryCreatePropertyAccessChain(expression, questionDotToken, name), pos);
      }
      break;
    }
    return expression;
  }
  function parseArgumentList() {
    parseExpected(21 /* OpenParenToken */);
    const result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
    parseExpected(22 /* CloseParenToken */);
    return result;
  }
  function parseTypeArgumentsInExpression() {
    if ((contextFlags & 524288 /* JavaScriptFile */) !== 0) {
      return void 0;
    }
    if (reScanLessThanToken() !== 30 /* LessThanToken */) {
      return void 0;
    }
    nextToken();
    const typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
    if (reScanGreaterToken() !== 32 /* GreaterThanToken */) {
      return void 0;
    }
    nextToken();
    return typeArguments && canFollowTypeArgumentsInExpression() ? typeArguments : void 0;
  }
  function canFollowTypeArgumentsInExpression() {
    switch (token()) {
      // These tokens can follow a type argument list in a call expression.
      case 21 /* OpenParenToken */:
      // foo<x>(
      case 15 /* NoSubstitutionTemplateLiteral */:
      // foo<T> `...`
      case 16 /* TemplateHead */:
        return true;
      // A type argument list followed by `<` never makes sense, and a type argument list followed
      // by `>` is ambiguous with a (re-scanned) `>>` operator, so we disqualify both. Also, in
      // this context, `+` and `-` are unary operators, not binary operators.
      case 30 /* LessThanToken */:
      case 32 /* GreaterThanToken */:
      case 40 /* PlusToken */:
      case 41 /* MinusToken */:
        return false;
    }
    return scanner.hasPrecedingLineBreak() || isBinaryOperator2() || !isStartOfExpression();
  }
  function parsePrimaryExpression() {
    switch (token()) {
      case 15 /* NoSubstitutionTemplateLiteral */:
        if (scanner.getTokenFlags() & 26656 /* IsInvalid */) {
          reScanTemplateToken(
            /*isTaggedTemplate*/
            false
          );
        }
      // falls through
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 11 /* StringLiteral */:
        return parseLiteralNode();
      case 110 /* ThisKeyword */:
      case 108 /* SuperKeyword */:
      case 106 /* NullKeyword */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
        return parseTokenNode();
      case 21 /* OpenParenToken */:
        return parseParenthesizedExpression();
      case 23 /* OpenBracketToken */:
        return parseArrayLiteralExpression();
      case 19 /* OpenBraceToken */:
        return parseObjectLiteralExpression();
      case 134 /* AsyncKeyword */:
        if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
          break;
        }
        return parseFunctionExpression();
      case 60 /* AtToken */:
        return parseDecoratedExpression();
      case 86 /* ClassKeyword */:
        return parseClassExpression();
      case 100 /* FunctionKeyword */:
        return parseFunctionExpression();
      case 105 /* NewKeyword */:
        return parseNewExpressionOrNewDotTarget();
      case 44 /* SlashToken */:
      case 69 /* SlashEqualsToken */:
        if (reScanSlashToken() === 14 /* RegularExpressionLiteral */) {
          return parseLiteralNode();
        }
        break;
      case 16 /* TemplateHead */:
        return parseTemplateExpression(
          /*isTaggedTemplate*/
          false
        );
      case 81 /* PrivateIdentifier */:
        return parsePrivateIdentifier();
    }
    return parseIdentifier(Diagnostics.Expression_expected);
  }
  function parseParenthesizedExpression() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(21 /* OpenParenToken */);
    const expression = allowInAnd(parseExpression);
    parseExpected(22 /* CloseParenToken */);
    return withJSDoc(finishNode(factoryCreateParenthesizedExpression(expression), pos), hasJSDoc);
  }
  function parseSpreadElement() {
    const pos = getNodePos();
    parseExpected(26 /* DotDotDotToken */);
    const expression = parseAssignmentExpressionOrHigher(
      /*allowReturnTypeInArrowFunction*/
      true
    );
    return finishNode(factory2.createSpreadElement(expression), pos);
  }
  function parseArgumentOrArrayLiteralElement() {
    return token() === 26 /* DotDotDotToken */ ? parseSpreadElement() : token() === 28 /* CommaToken */ ? finishNode(factory2.createOmittedExpression(), getNodePos()) : parseAssignmentExpressionOrHigher(
      /*allowReturnTypeInArrowFunction*/
      true
    );
  }
  function parseArgumentExpression() {
    return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
  }
  function parseArrayLiteralExpression() {
    const pos = getNodePos();
    const openBracketPosition = scanner.getTokenStart();
    const openBracketParsed = parseExpected(23 /* OpenBracketToken */);
    const multiLine = scanner.hasPrecedingLineBreak();
    const elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
    parseExpectedMatchingBrackets(23 /* OpenBracketToken */, 24 /* CloseBracketToken */, openBracketParsed, openBracketPosition);
    return finishNode(factoryCreateArrayLiteralExpression(elements, multiLine), pos);
  }
  function parseObjectLiteralElement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    if (parseOptionalToken(26 /* DotDotDotToken */)) {
      const expression = parseAssignmentExpressionOrHigher(
        /*allowReturnTypeInArrowFunction*/
        true
      );
      return withJSDoc(finishNode(factory2.createSpreadAssignment(expression), pos), hasJSDoc);
    }
    const modifiers = parseModifiers(
      /*allowDecorators*/
      true
    );
    if (parseContextualModifier(139 /* GetKeyword */)) {
      return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */, 0 /* None */);
    }
    if (parseContextualModifier(153 /* SetKeyword */)) {
      return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */, 0 /* None */);
    }
    const asteriskToken = parseOptionalToken(42 /* AsteriskToken */);
    const tokenIsIdentifier = isIdentifier2();
    const name = parsePropertyName();
    const questionToken = parseOptionalToken(58 /* QuestionToken */);
    const exclamationToken = parseOptionalToken(54 /* ExclamationToken */);
    if (asteriskToken || token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */) {
      return parseMethodDeclaration(pos, hasJSDoc, modifiers, asteriskToken, name, questionToken, exclamationToken);
    }
    let node;
    const isShorthandPropertyAssignment2 = tokenIsIdentifier && token() !== 59 /* ColonToken */;
    if (isShorthandPropertyAssignment2) {
      const equalsToken = parseOptionalToken(64 /* EqualsToken */);
      const objectAssignmentInitializer = equalsToken ? allowInAnd(() => parseAssignmentExpressionOrHigher(
        /*allowReturnTypeInArrowFunction*/
        true
      )) : void 0;
      node = factory2.createShorthandPropertyAssignment(name, objectAssignmentInitializer);
      node.equalsToken = equalsToken;
    } else {
      parseExpected(59 /* ColonToken */);
      const initializer = allowInAnd(() => parseAssignmentExpressionOrHigher(
        /*allowReturnTypeInArrowFunction*/
        true
      ));
      node = factory2.createPropertyAssignment(name, initializer);
    }
    node.modifiers = modifiers;
    node.questionToken = questionToken;
    node.exclamationToken = exclamationToken;
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseObjectLiteralExpression() {
    const pos = getNodePos();
    const openBracePosition = scanner.getTokenStart();
    const openBraceParsed = parseExpected(19 /* OpenBraceToken */);
    const multiLine = scanner.hasPrecedingLineBreak();
    const properties = parseDelimitedList(
      12 /* ObjectLiteralMembers */,
      parseObjectLiteralElement,
      /*considerSemicolonAsDelimiter*/
      true
    );
    parseExpectedMatchingBrackets(19 /* OpenBraceToken */, 20 /* CloseBraceToken */, openBraceParsed, openBracePosition);
    return finishNode(factoryCreateObjectLiteralExpression(properties, multiLine), pos);
  }
  function parseFunctionExpression() {
    const savedDecoratorContext = inDecoratorContext();
    setDecoratorContext(
      /*val*/
      false
    );
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    const modifiers = parseModifiers(
      /*allowDecorators*/
      false
    );
    parseExpected(100 /* FunctionKeyword */);
    const asteriskToken = parseOptionalToken(42 /* AsteriskToken */);
    const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
    const isAsync = some(modifiers, isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
    const name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) : isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) : isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) : parseOptionalBindingIdentifier();
    const typeParameters = parseTypeParameters();
    const parameters = parseParameters(isGenerator | isAsync);
    const type = parseReturnType(
      59 /* ColonToken */,
      /*isType*/
      false
    );
    const body = parseFunctionBlock(isGenerator | isAsync);
    setDecoratorContext(savedDecoratorContext);
    const node = factory2.createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseOptionalBindingIdentifier() {
    return isBindingIdentifier() ? parseBindingIdentifier() : void 0;
  }
  function parseNewExpressionOrNewDotTarget() {
    const pos = getNodePos();
    parseExpected(105 /* NewKeyword */);
    if (parseOptional(25 /* DotToken */)) {
      const name = parseIdentifierName();
      return finishNode(factory2.createMetaProperty(105 /* NewKeyword */, name), pos);
    }
    const expressionPos = getNodePos();
    let expression = parseMemberExpressionRest(
      expressionPos,
      parsePrimaryExpression(),
      /*allowOptionalChain*/
      false
    );
    let typeArguments;
    if (expression.kind === 233 /* ExpressionWithTypeArguments */) {
      typeArguments = expression.typeArguments;
      expression = expression.expression;
    }
    if (token() === 29 /* QuestionDotToken */) {
      parseErrorAtCurrentToken(Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, getTextOfNodeFromSourceText(sourceText, expression));
    }
    const argumentList = token() === 21 /* OpenParenToken */ ? parseArgumentList() : void 0;
    return finishNode(factoryCreateNewExpression(expression, typeArguments, argumentList), pos);
  }
  function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    const openBracePosition = scanner.getTokenStart();
    const openBraceParsed = parseExpected(19 /* OpenBraceToken */, diagnosticMessage);
    if (openBraceParsed || ignoreMissingOpenBrace) {
      const multiLine = scanner.hasPrecedingLineBreak();
      const statements = parseList(1 /* BlockStatements */, parseStatement);
      parseExpectedMatchingBrackets(19 /* OpenBraceToken */, 20 /* CloseBraceToken */, openBraceParsed, openBracePosition);
      const result = withJSDoc(finishNode(factoryCreateBlock(statements, multiLine), pos), hasJSDoc);
      if (token() === 64 /* EqualsToken */) {
        parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_whole_assignment_in_parentheses);
        nextToken();
      }
      return result;
    } else {
      const statements = createMissingList();
      return withJSDoc(finishNode(factoryCreateBlock(
        statements,
        /*multiLine*/
        void 0
      ), pos), hasJSDoc);
    }
  }
  function parseFunctionBlock(flags, diagnosticMessage) {
    const savedYieldContext = inYieldContext();
    setYieldContext(!!(flags & 1 /* Yield */));
    const savedAwaitContext = inAwaitContext();
    setAwaitContext(!!(flags & 2 /* Await */));
    const savedTopLevel = topLevel;
    topLevel = false;
    const saveDecoratorContext = inDecoratorContext();
    if (saveDecoratorContext) {
      setDecoratorContext(
        /*val*/
        false
      );
    }
    const block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
    if (saveDecoratorContext) {
      setDecoratorContext(
        /*val*/
        true
      );
    }
    topLevel = savedTopLevel;
    setYieldContext(savedYieldContext);
    setAwaitContext(savedAwaitContext);
    return block;
  }
  function parseEmptyStatement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(27 /* SemicolonToken */);
    return withJSDoc(finishNode(factory2.createEmptyStatement(), pos), hasJSDoc);
  }
  function parseIfStatement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(101 /* IfKeyword */);
    const openParenPosition = scanner.getTokenStart();
    const openParenParsed = parseExpected(21 /* OpenParenToken */);
    const expression = allowInAnd(parseExpression);
    parseExpectedMatchingBrackets(21 /* OpenParenToken */, 22 /* CloseParenToken */, openParenParsed, openParenPosition);
    const thenStatement = parseStatement();
    const elseStatement = parseOptional(93 /* ElseKeyword */) ? parseStatement() : void 0;
    return withJSDoc(finishNode(factoryCreateIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc);
  }
  function parseDoStatement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(92 /* DoKeyword */);
    const statement = parseStatement();
    parseExpected(117 /* WhileKeyword */);
    const openParenPosition = scanner.getTokenStart();
    const openParenParsed = parseExpected(21 /* OpenParenToken */);
    const expression = allowInAnd(parseExpression);
    parseExpectedMatchingBrackets(21 /* OpenParenToken */, 22 /* CloseParenToken */, openParenParsed, openParenPosition);
    parseOptional(27 /* SemicolonToken */);
    return withJSDoc(finishNode(factory2.createDoStatement(statement, expression), pos), hasJSDoc);
  }
  function parseWhileStatement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(117 /* WhileKeyword */);
    const openParenPosition = scanner.getTokenStart();
    const openParenParsed = parseExpected(21 /* OpenParenToken */);
    const expression = allowInAnd(parseExpression);
    parseExpectedMatchingBrackets(21 /* OpenParenToken */, 22 /* CloseParenToken */, openParenParsed, openParenPosition);
    const statement = parseStatement();
    return withJSDoc(finishNode(factoryCreateWhileStatement(expression, statement), pos), hasJSDoc);
  }
  function parseForOrForInOrForOfStatement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(99 /* ForKeyword */);
    const awaitToken = parseOptionalToken(135 /* AwaitKeyword */);
    parseExpected(21 /* OpenParenToken */);
    let initializer;
    if (token() !== 27 /* SemicolonToken */) {
      if (token() === 115 /* VarKeyword */ || token() === 121 /* LetKeyword */ || token() === 87 /* ConstKeyword */ || token() === 160 /* UsingKeyword */ && lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf) || // this one is meant to allow of
      token() === 135 /* AwaitKeyword */ && lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine)) {
        initializer = parseVariableDeclarationList(
          /*inForStatementInitializer*/
          true
        );
      } else {
        initializer = disallowInAnd(parseExpression);
      }
    }
    let node;
    if (awaitToken ? parseExpected(165 /* OfKeyword */) : parseOptional(165 /* OfKeyword */)) {
      const expression = allowInAnd(() => parseAssignmentExpressionOrHigher(
        /*allowReturnTypeInArrowFunction*/
        true
      ));
      parseExpected(22 /* CloseParenToken */);
      node = factoryCreateForOfStatement(awaitToken, initializer, expression, parseStatement());
    } else if (parseOptional(103 /* InKeyword */)) {
      const expression = allowInAnd(parseExpression);
      parseExpected(22 /* CloseParenToken */);
      node = factory2.createForInStatement(initializer, expression, parseStatement());
    } else {
      parseExpected(27 /* SemicolonToken */);
      const condition = token() !== 27 /* SemicolonToken */ && token() !== 22 /* CloseParenToken */ ? allowInAnd(parseExpression) : void 0;
      parseExpected(27 /* SemicolonToken */);
      const incrementor = token() !== 22 /* CloseParenToken */ ? allowInAnd(parseExpression) : void 0;
      parseExpected(22 /* CloseParenToken */);
      node = factoryCreateForStatement(initializer, condition, incrementor, parseStatement());
    }
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseBreakOrContinueStatement(kind) {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(kind === 252 /* BreakStatement */ ? 83 /* BreakKeyword */ : 88 /* ContinueKeyword */);
    const label = canParseSemicolon() ? void 0 : parseIdentifier();
    parseSemicolon();
    const node = kind === 252 /* BreakStatement */ ? factory2.createBreakStatement(label) : factory2.createContinueStatement(label);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseReturnStatement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(107 /* ReturnKeyword */);
    const expression = canParseSemicolon() ? void 0 : allowInAnd(parseExpression);
    parseSemicolon();
    return withJSDoc(finishNode(factory2.createReturnStatement(expression), pos), hasJSDoc);
  }
  function parseWithStatement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(118 /* WithKeyword */);
    const openParenPosition = scanner.getTokenStart();
    const openParenParsed = parseExpected(21 /* OpenParenToken */);
    const expression = allowInAnd(parseExpression);
    parseExpectedMatchingBrackets(21 /* OpenParenToken */, 22 /* CloseParenToken */, openParenParsed, openParenPosition);
    const statement = doInsideOfContext(67108864 /* InWithStatement */, parseStatement);
    return withJSDoc(finishNode(factory2.createWithStatement(expression, statement), pos), hasJSDoc);
  }
  function parseCaseClause() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(84 /* CaseKeyword */);
    const expression = allowInAnd(parseExpression);
    parseExpected(59 /* ColonToken */);
    const statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
    return withJSDoc(finishNode(factory2.createCaseClause(expression, statements), pos), hasJSDoc);
  }
  function parseDefaultClause() {
    const pos = getNodePos();
    parseExpected(90 /* DefaultKeyword */);
    parseExpected(59 /* ColonToken */);
    const statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
    return finishNode(factory2.createDefaultClause(statements), pos);
  }
  function parseCaseOrDefaultClause() {
    return token() === 84 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
  }
  function parseCaseBlock() {
    const pos = getNodePos();
    parseExpected(19 /* OpenBraceToken */);
    const clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
    parseExpected(20 /* CloseBraceToken */);
    return finishNode(factory2.createCaseBlock(clauses), pos);
  }
  function parseSwitchStatement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(109 /* SwitchKeyword */);
    parseExpected(21 /* OpenParenToken */);
    const expression = allowInAnd(parseExpression);
    parseExpected(22 /* CloseParenToken */);
    const caseBlock = parseCaseBlock();
    return withJSDoc(finishNode(factory2.createSwitchStatement(expression, caseBlock), pos), hasJSDoc);
  }
  function parseThrowStatement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(111 /* ThrowKeyword */);
    let expression = scanner.hasPrecedingLineBreak() ? void 0 : allowInAnd(parseExpression);
    if (expression === void 0) {
      identifierCount++;
      expression = finishNode(factoryCreateIdentifier(""), getNodePos());
    }
    if (!tryParseSemicolon()) {
      parseErrorForMissingSemicolonAfter(expression);
    }
    return withJSDoc(finishNode(factory2.createThrowStatement(expression), pos), hasJSDoc);
  }
  function parseTryStatement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(113 /* TryKeyword */);
    const tryBlock = parseBlock(
      /*ignoreMissingOpenBrace*/
      false
    );
    const catchClause = token() === 85 /* CatchKeyword */ ? parseCatchClause() : void 0;
    let finallyBlock;
    if (!catchClause || token() === 98 /* FinallyKeyword */) {
      parseExpected(98 /* FinallyKeyword */, Diagnostics.catch_or_finally_expected);
      finallyBlock = parseBlock(
        /*ignoreMissingOpenBrace*/
        false
      );
    }
    return withJSDoc(finishNode(factory2.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc);
  }
  function parseCatchClause() {
    const pos = getNodePos();
    parseExpected(85 /* CatchKeyword */);
    let variableDeclaration;
    if (parseOptional(21 /* OpenParenToken */)) {
      variableDeclaration = parseVariableDeclaration();
      parseExpected(22 /* CloseParenToken */);
    } else {
      variableDeclaration = void 0;
    }
    const block = parseBlock(
      /*ignoreMissingOpenBrace*/
      false
    );
    return finishNode(factory2.createCatchClause(variableDeclaration, block), pos);
  }
  function parseDebuggerStatement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    parseExpected(89 /* DebuggerKeyword */);
    parseSemicolon();
    return withJSDoc(finishNode(factory2.createDebuggerStatement(), pos), hasJSDoc);
  }
  function parseExpressionOrLabeledStatement() {
    const pos = getNodePos();
    let hasJSDoc = hasPrecedingJSDocComment();
    let node;
    const hasParen = token() === 21 /* OpenParenToken */;
    const expression = allowInAnd(parseExpression);
    if (isIdentifier(expression) && parseOptional(59 /* ColonToken */)) {
      node = factory2.createLabeledStatement(expression, parseStatement());
    } else {
      if (!tryParseSemicolon()) {
        parseErrorForMissingSemicolonAfter(expression);
      }
      node = factoryCreateExpressionStatement(expression);
      if (hasParen) {
        hasJSDoc = false;
      }
    }
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function nextTokenIsIdentifierOrKeywordOnSameLine() {
    nextToken();
    return tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
  }
  function nextTokenIsClassKeywordOnSameLine() {
    nextToken();
    return token() === 86 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
  }
  function nextTokenIsFunctionKeywordOnSameLine() {
    nextToken();
    return token() === 100 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
  }
  function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
    nextToken();
    return (tokenIsIdentifierOrKeyword(token()) || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */ || token() === 11 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
  }
  function isDeclaration2() {
    while (true) {
      switch (token()) {
        case 115 /* VarKeyword */:
        case 121 /* LetKeyword */:
        case 87 /* ConstKeyword */:
        case 100 /* FunctionKeyword */:
        case 86 /* ClassKeyword */:
        case 94 /* EnumKeyword */:
          return true;
        case 160 /* UsingKeyword */:
          return isUsingDeclaration();
        case 135 /* AwaitKeyword */:
          return isAwaitUsingDeclaration();
        // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
        // however, an identifier cannot be followed by another identifier on the same line. This is what we
        // count on to parse out the respective declarations. For instance, we exploit this to say that
        //
        //    namespace n
        //
        // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
        //
        //    namespace
        //    n
        //
        // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
        // We need to look one token ahead to see if it permissible to try parsing a declaration.
        //
        // *Note*: 'interface' is actually a strict mode reserved word. So while
        //
        //   "use strict"
        //   interface
        //   I {}
        //
        // could be legal, it would add complexity for very little gain.
        case 120 /* InterfaceKeyword */:
        case 156 /* TypeKeyword */:
          return nextTokenIsIdentifierOnSameLine();
        case 144 /* ModuleKeyword */:
        case 145 /* NamespaceKeyword */:
          return nextTokenIsIdentifierOrStringLiteralOnSameLine();
        case 128 /* AbstractKeyword */:
        case 129 /* AccessorKeyword */:
        case 134 /* AsyncKeyword */:
        case 138 /* DeclareKeyword */:
        case 123 /* PrivateKeyword */:
        case 124 /* ProtectedKeyword */:
        case 125 /* PublicKeyword */:
        case 148 /* ReadonlyKeyword */:
          const previousToken = token();
          nextToken();
          if (scanner.hasPrecedingLineBreak()) {
            return false;
          }
          if (previousToken === 138 /* DeclareKeyword */ && token() === 156 /* TypeKeyword */) {
            return true;
          }
          continue;
        case 162 /* GlobalKeyword */:
          nextToken();
          return token() === 19 /* OpenBraceToken */ || token() === 80 /* Identifier */ || token() === 95 /* ExportKeyword */;
        case 102 /* ImportKeyword */:
          nextToken();
          return token() === 11 /* StringLiteral */ || token() === 42 /* AsteriskToken */ || token() === 19 /* OpenBraceToken */ || tokenIsIdentifierOrKeyword(token());
        case 95 /* ExportKeyword */:
          let currentToken2 = nextToken();
          if (currentToken2 === 156 /* TypeKeyword */) {
            currentToken2 = lookAhead(nextToken);
          }
          if (currentToken2 === 64 /* EqualsToken */ || currentToken2 === 42 /* AsteriskToken */ || currentToken2 === 19 /* OpenBraceToken */ || currentToken2 === 90 /* DefaultKeyword */ || currentToken2 === 130 /* AsKeyword */ || currentToken2 === 60 /* AtToken */) {
            return true;
          }
          continue;
        case 126 /* StaticKeyword */:
          nextToken();
          continue;
        default:
          return false;
      }
    }
  }
  function isStartOfDeclaration() {
    return lookAhead(isDeclaration2);
  }
  function isStartOfStatement() {
    switch (token()) {
      case 60 /* AtToken */:
      case 27 /* SemicolonToken */:
      case 19 /* OpenBraceToken */:
      case 115 /* VarKeyword */:
      case 121 /* LetKeyword */:
      case 160 /* UsingKeyword */:
      case 100 /* FunctionKeyword */:
      case 86 /* ClassKeyword */:
      case 94 /* EnumKeyword */:
      case 101 /* IfKeyword */:
      case 92 /* DoKeyword */:
      case 117 /* WhileKeyword */:
      case 99 /* ForKeyword */:
      case 88 /* ContinueKeyword */:
      case 83 /* BreakKeyword */:
      case 107 /* ReturnKeyword */:
      case 118 /* WithKeyword */:
      case 109 /* SwitchKeyword */:
      case 111 /* ThrowKeyword */:
      case 113 /* TryKeyword */:
      case 89 /* DebuggerKeyword */:
      // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
      // however, we say they are here so that we may gracefully parse them and error later.
      // falls through
      case 85 /* CatchKeyword */:
      case 98 /* FinallyKeyword */:
        return true;
      case 102 /* ImportKeyword */:
        return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
      case 87 /* ConstKeyword */:
      case 95 /* ExportKeyword */:
        return isStartOfDeclaration();
      case 134 /* AsyncKeyword */:
      case 138 /* DeclareKeyword */:
      case 120 /* InterfaceKeyword */:
      case 144 /* ModuleKeyword */:
      case 145 /* NamespaceKeyword */:
      case 156 /* TypeKeyword */:
      case 162 /* GlobalKeyword */:
        return true;
      case 129 /* AccessorKeyword */:
      case 125 /* PublicKeyword */:
      case 123 /* PrivateKeyword */:
      case 124 /* ProtectedKeyword */:
      case 126 /* StaticKeyword */:
      case 148 /* ReadonlyKeyword */:
        return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
      default:
        return isStartOfExpression();
    }
  }
  function nextTokenIsBindingIdentifierOrStartOfDestructuring() {
    nextToken();
    return isBindingIdentifier() || token() === 19 /* OpenBraceToken */ || token() === 23 /* OpenBracketToken */;
  }
  function isLetDeclaration() {
    return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuring);
  }
  function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf() {
    return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(
      /*disallowOf*/
      true
    );
  }
  function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf) {
    nextToken();
    if (disallowOf && token() === 165 /* OfKeyword */) return false;
    return (isBindingIdentifier() || token() === 19 /* OpenBraceToken */) && !scanner.hasPrecedingLineBreak();
  }
  function isUsingDeclaration() {
    return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine);
  }
  function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine(disallowOf) {
    if (nextToken() === 160 /* UsingKeyword */) {
      return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf);
    }
    return false;
  }
  function isAwaitUsingDeclaration() {
    return lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine);
  }
  function parseStatement() {
    switch (token()) {
      case 27 /* SemicolonToken */:
        return parseEmptyStatement();
      case 19 /* OpenBraceToken */:
        return parseBlock(
          /*ignoreMissingOpenBrace*/
          false
        );
      case 115 /* VarKeyword */:
        return parseVariableStatement(
          getNodePos(),
          hasPrecedingJSDocComment(),
          /*modifiers*/
          void 0
        );
      case 121 /* LetKeyword */:
        if (isLetDeclaration()) {
          return parseVariableStatement(
            getNodePos(),
            hasPrecedingJSDocComment(),
            /*modifiers*/
            void 0
          );
        }
        break;
      case 135 /* AwaitKeyword */:
        if (isAwaitUsingDeclaration()) {
          return parseVariableStatement(
            getNodePos(),
            hasPrecedingJSDocComment(),
            /*modifiers*/
            void 0
          );
        }
        break;
      case 160 /* UsingKeyword */:
        if (isUsingDeclaration()) {
          return parseVariableStatement(
            getNodePos(),
            hasPrecedingJSDocComment(),
            /*modifiers*/
            void 0
          );
        }
        break;
      case 100 /* FunctionKeyword */:
        return parseFunctionDeclaration(
          getNodePos(),
          hasPrecedingJSDocComment(),
          /*modifiers*/
          void 0
        );
      case 86 /* ClassKeyword */:
        return parseClassDeclaration(
          getNodePos(),
          hasPrecedingJSDocComment(),
          /*modifiers*/
          void 0
        );
      case 101 /* IfKeyword */:
        return parseIfStatement();
      case 92 /* DoKeyword */:
        return parseDoStatement();
      case 117 /* WhileKeyword */:
        return parseWhileStatement();
      case 99 /* ForKeyword */:
        return parseForOrForInOrForOfStatement();
      case 88 /* ContinueKeyword */:
        return parseBreakOrContinueStatement(251 /* ContinueStatement */);
      case 83 /* BreakKeyword */:
        return parseBreakOrContinueStatement(252 /* BreakStatement */);
      case 107 /* ReturnKeyword */:
        return parseReturnStatement();
      case 118 /* WithKeyword */:
        return parseWithStatement();
      case 109 /* SwitchKeyword */:
        return parseSwitchStatement();
      case 111 /* ThrowKeyword */:
        return parseThrowStatement();
      case 113 /* TryKeyword */:
      // Include 'catch' and 'finally' for error recovery.
      // falls through
      case 85 /* CatchKeyword */:
      case 98 /* FinallyKeyword */:
        return parseTryStatement();
      case 89 /* DebuggerKeyword */:
        return parseDebuggerStatement();
      case 60 /* AtToken */:
        return parseDeclaration();
      case 134 /* AsyncKeyword */:
      case 120 /* InterfaceKeyword */:
      case 156 /* TypeKeyword */:
      case 144 /* ModuleKeyword */:
      case 145 /* NamespaceKeyword */:
      case 138 /* DeclareKeyword */:
      case 87 /* ConstKeyword */:
      case 94 /* EnumKeyword */:
      case 95 /* ExportKeyword */:
      case 102 /* ImportKeyword */:
      case 123 /* PrivateKeyword */:
      case 124 /* ProtectedKeyword */:
      case 125 /* PublicKeyword */:
      case 128 /* AbstractKeyword */:
      case 129 /* AccessorKeyword */:
      case 126 /* StaticKeyword */:
      case 148 /* ReadonlyKeyword */:
      case 162 /* GlobalKeyword */:
        if (isStartOfDeclaration()) {
          return parseDeclaration();
        }
        break;
    }
    return parseExpressionOrLabeledStatement();
  }
  function isDeclareModifier(modifier) {
    return modifier.kind === 138 /* DeclareKeyword */;
  }
  function parseDeclaration() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    const modifiers = parseModifiers(
      /*allowDecorators*/
      true
    );
    const isAmbient = some(modifiers, isDeclareModifier);
    if (isAmbient) {
      const node = tryReuseAmbientDeclaration(pos);
      if (node) {
        return node;
      }
      for (const m of modifiers) {
        m.flags |= 33554432 /* Ambient */;
      }
      return doInsideOfContext(33554432 /* Ambient */, () => parseDeclarationWorker(pos, hasJSDoc, modifiers));
    } else {
      return parseDeclarationWorker(pos, hasJSDoc, modifiers);
    }
  }
  function tryReuseAmbientDeclaration(pos) {
    return doInsideOfContext(33554432 /* Ambient */, () => {
      const node = currentNode(parsingContext, pos);
      if (node) {
        return consumeNode(node);
      }
    });
  }
  function parseDeclarationWorker(pos, hasJSDoc, modifiersIn) {
    switch (token()) {
      case 115 /* VarKeyword */:
      case 121 /* LetKeyword */:
      case 87 /* ConstKeyword */:
      case 160 /* UsingKeyword */:
      case 135 /* AwaitKeyword */:
        return parseVariableStatement(pos, hasJSDoc, modifiersIn);
      case 100 /* FunctionKeyword */:
        return parseFunctionDeclaration(pos, hasJSDoc, modifiersIn);
      case 86 /* ClassKeyword */:
        return parseClassDeclaration(pos, hasJSDoc, modifiersIn);
      case 120 /* InterfaceKeyword */:
        return parseInterfaceDeclaration(pos, hasJSDoc, modifiersIn);
      case 156 /* TypeKeyword */:
        return parseTypeAliasDeclaration(pos, hasJSDoc, modifiersIn);
      case 94 /* EnumKeyword */:
        return parseEnumDeclaration(pos, hasJSDoc, modifiersIn);
      case 162 /* GlobalKeyword */:
      case 144 /* ModuleKeyword */:
      case 145 /* NamespaceKeyword */:
        return parseModuleDeclaration(pos, hasJSDoc, modifiersIn);
      case 102 /* ImportKeyword */:
        return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, modifiersIn);
      case 95 /* ExportKeyword */:
        nextToken();
        switch (token()) {
          case 90 /* DefaultKeyword */:
          case 64 /* EqualsToken */:
            return parseExportAssignment(pos, hasJSDoc, modifiersIn);
          case 130 /* AsKeyword */:
            return parseNamespaceExportDeclaration(pos, hasJSDoc, modifiersIn);
          default:
            return parseExportDeclaration(pos, hasJSDoc, modifiersIn);
        }
      default:
        if (modifiersIn) {
          const missing = createMissingNode(
            282 /* MissingDeclaration */,
            /*reportAtCurrentPosition*/
            true,
            Diagnostics.Declaration_expected
          );
          setTextRangePos(missing, pos);
          missing.modifiers = modifiersIn;
          return missing;
        }
        return void 0;
    }
  }
  function nextTokenIsStringLiteral() {
    return nextToken() === 11 /* StringLiteral */;
  }
  function nextTokenIsFromKeywordOrEqualsToken() {
    nextToken();
    return token() === 161 /* FromKeyword */ || token() === 64 /* EqualsToken */;
  }
  function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
    nextToken();
    return !scanner.hasPrecedingLineBreak() && (isIdentifier2() || token() === 11 /* StringLiteral */);
  }
  function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
    if (token() !== 19 /* OpenBraceToken */) {
      if (flags & 4 /* Type */) {
        parseTypeMemberSemicolon();
        return;
      }
      if (canParseSemicolon()) {
        parseSemicolon();
        return;
      }
    }
    return parseFunctionBlock(flags, diagnosticMessage);
  }
  function parseArrayBindingElement() {
    const pos = getNodePos();
    if (token() === 28 /* CommaToken */) {
      return finishNode(factory2.createOmittedExpression(), pos);
    }
    const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */);
    const name = parseIdentifierOrPattern();
    const initializer = parseInitializer();
    return finishNode(factory2.createBindingElement(
      dotDotDotToken,
      /*propertyName*/
      void 0,
      name,
      initializer
    ), pos);
  }
  function parseObjectBindingElement() {
    const pos = getNodePos();
    const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */);
    const tokenIsIdentifier = isBindingIdentifier();
    let propertyName = parsePropertyName();
    let name;
    if (tokenIsIdentifier && token() !== 59 /* ColonToken */) {
      name = propertyName;
      propertyName = void 0;
    } else {
      parseExpected(59 /* ColonToken */);
      name = parseIdentifierOrPattern();
    }
    const initializer = parseInitializer();
    return finishNode(factory2.createBindingElement(dotDotDotToken, propertyName, name, initializer), pos);
  }
  function parseObjectBindingPattern() {
    const pos = getNodePos();
    parseExpected(19 /* OpenBraceToken */);
    const elements = allowInAnd(() => parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement));
    parseExpected(20 /* CloseBraceToken */);
    return finishNode(factory2.createObjectBindingPattern(elements), pos);
  }
  function parseArrayBindingPattern() {
    const pos = getNodePos();
    parseExpected(23 /* OpenBracketToken */);
    const elements = allowInAnd(() => parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement));
    parseExpected(24 /* CloseBracketToken */);
    return finishNode(factory2.createArrayBindingPattern(elements), pos);
  }
  function isBindingIdentifierOrPrivateIdentifierOrPattern() {
    return token() === 19 /* OpenBraceToken */ || token() === 23 /* OpenBracketToken */ || token() === 81 /* PrivateIdentifier */ || isBindingIdentifier();
  }
  function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
    if (token() === 23 /* OpenBracketToken */) {
      return parseArrayBindingPattern();
    }
    if (token() === 19 /* OpenBraceToken */) {
      return parseObjectBindingPattern();
    }
    return parseBindingIdentifier(privateIdentifierDiagnosticMessage);
  }
  function parseVariableDeclarationAllowExclamation() {
    return parseVariableDeclaration(
      /*allowExclamation*/
      true
    );
  }
  function parseVariableDeclaration(allowExclamation) {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
    let exclamationToken;
    if (allowExclamation && name.kind === 80 /* Identifier */ && token() === 54 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
      exclamationToken = parseTokenNode();
    }
    const type = parseTypeAnnotation();
    const initializer = isInOrOfKeyword(token()) ? void 0 : parseInitializer();
    const node = factoryCreateVariableDeclaration(name, exclamationToken, type, initializer);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseVariableDeclarationList(inForStatementInitializer) {
    const pos = getNodePos();
    let flags = 0;
    switch (token()) {
      case 115 /* VarKeyword */:
        break;
      case 121 /* LetKeyword */:
        flags |= 1 /* Let */;
        break;
      case 87 /* ConstKeyword */:
        flags |= 2 /* Const */;
        break;
      case 160 /* UsingKeyword */:
        flags |= 4 /* Using */;
        break;
      case 135 /* AwaitKeyword */:
        Debug.assert(isAwaitUsingDeclaration());
        flags |= 6 /* AwaitUsing */;
        nextToken();
        break;
      default:
        Debug.fail();
    }
    nextToken();
    let declarations;
    if (token() === 165 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
      declarations = createMissingList();
    } else {
      const savedDisallowIn = inDisallowInContext();
      setDisallowInContext(inForStatementInitializer);
      declarations = parseDelimitedList(
        8 /* VariableDeclarations */,
        inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation
      );
      setDisallowInContext(savedDisallowIn);
    }
    return finishNode(factoryCreateVariableDeclarationList(declarations, flags), pos);
  }
  function canFollowContextualOfKeyword() {
    return nextTokenIsIdentifier() && nextToken() === 22 /* CloseParenToken */;
  }
  function parseVariableStatement(pos, hasJSDoc, modifiers) {
    const declarationList = parseVariableDeclarationList(
      /*inForStatementInitializer*/
      false
    );
    parseSemicolon();
    const node = factoryCreateVariableStatement(modifiers, declarationList);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseFunctionDeclaration(pos, hasJSDoc, modifiers) {
    const savedAwaitContext = inAwaitContext();
    const modifierFlags = modifiersToFlags(modifiers);
    parseExpected(100 /* FunctionKeyword */);
    const asteriskToken = parseOptionalToken(42 /* AsteriskToken */);
    const name = modifierFlags & 2048 /* Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier();
    const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
    const isAsync = modifierFlags & 1024 /* Async */ ? 2 /* Await */ : 0 /* None */;
    const typeParameters = parseTypeParameters();
    if (modifierFlags & 32 /* Export */) setAwaitContext(
      /*value*/
      true
    );
    const parameters = parseParameters(isGenerator | isAsync);
    const type = parseReturnType(
      59 /* ColonToken */,
      /*isType*/
      false
    );
    const body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, Diagnostics.or_expected);
    setAwaitContext(savedAwaitContext);
    const node = factory2.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseConstructorName() {
    if (token() === 137 /* ConstructorKeyword */) {
      return parseExpected(137 /* ConstructorKeyword */);
    }
    if (token() === 11 /* StringLiteral */ && lookAhead(nextToken) === 21 /* OpenParenToken */) {
      return tryParse(() => {
        const literalNode = parseLiteralNode();
        return literalNode.text === "constructor" ? literalNode : void 0;
      });
    }
  }
  function tryParseConstructorDeclaration(pos, hasJSDoc, modifiers) {
    return tryParse(() => {
      if (parseConstructorName()) {
        const typeParameters = parseTypeParameters();
        const parameters = parseParameters(0 /* None */);
        const type = parseReturnType(
          59 /* ColonToken */,
          /*isType*/
          false
        );
        const body = parseFunctionBlockOrSemicolon(0 /* None */, Diagnostics.or_expected);
        const node = factory2.createConstructorDeclaration(modifiers, parameters, body);
        node.typeParameters = typeParameters;
        node.type = type;
        return withJSDoc(finishNode(node, pos), hasJSDoc);
      }
    });
  }
  function parseMethodDeclaration(pos, hasJSDoc, modifiers, asteriskToken, name, questionToken, exclamationToken, diagnosticMessage) {
    const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
    const isAsync = some(modifiers, isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
    const typeParameters = parseTypeParameters();
    const parameters = parseParameters(isGenerator | isAsync);
    const type = parseReturnType(
      59 /* ColonToken */,
      /*isType*/
      false
    );
    const body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
    const node = factory2.createMethodDeclaration(
      modifiers,
      asteriskToken,
      name,
      questionToken,
      typeParameters,
      parameters,
      type,
      body
    );
    node.exclamationToken = exclamationToken;
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parsePropertyDeclaration(pos, hasJSDoc, modifiers, name, questionToken) {
    const exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(54 /* ExclamationToken */) : void 0;
    const type = parseTypeAnnotation();
    const initializer = doOutsideOfContext(16384 /* YieldContext */ | 65536 /* AwaitContext */ | 8192 /* DisallowInContext */, parseInitializer);
    parseSemicolonAfterPropertyName(name, type, initializer);
    const node = factory2.createPropertyDeclaration(
      modifiers,
      name,
      questionToken || exclamationToken,
      type,
      initializer
    );
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers) {
    const asteriskToken = parseOptionalToken(42 /* AsteriskToken */);
    const name = parsePropertyName();
    const questionToken = parseOptionalToken(58 /* QuestionToken */);
    if (asteriskToken || token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */) {
      return parseMethodDeclaration(
        pos,
        hasJSDoc,
        modifiers,
        asteriskToken,
        name,
        questionToken,
        /*exclamationToken*/
        void 0,
        Diagnostics.or_expected
      );
    }
    return parsePropertyDeclaration(pos, hasJSDoc, modifiers, name, questionToken);
  }
  function parseAccessorDeclaration(pos, hasJSDoc, modifiers, kind, flags) {
    const name = parsePropertyName();
    const typeParameters = parseTypeParameters();
    const parameters = parseParameters(0 /* None */);
    const type = parseReturnType(
      59 /* ColonToken */,
      /*isType*/
      false
    );
    const body = parseFunctionBlockOrSemicolon(flags);
    const node = kind === 177 /* GetAccessor */ ? factory2.createGetAccessorDeclaration(modifiers, name, parameters, type, body) : factory2.createSetAccessorDeclaration(modifiers, name, parameters, body);
    node.typeParameters = typeParameters;
    if (isSetAccessorDeclaration(node)) node.type = type;
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function isClassMemberStart() {
    let idToken;
    if (token() === 60 /* AtToken */) {
      return true;
    }
    while (isModifierKind(token())) {
      idToken = token();
      if (isClassMemberModifier(idToken)) {
        return true;
      }
      nextToken();
    }
    if (token() === 42 /* AsteriskToken */) {
      return true;
    }
    if (isLiteralPropertyName()) {
      idToken = token();
      nextToken();
    }
    if (token() === 23 /* OpenBracketToken */) {
      return true;
    }
    if (idToken !== void 0) {
      if (!isKeyword(idToken) || idToken === 153 /* SetKeyword */ || idToken === 139 /* GetKeyword */) {
        return true;
      }
      switch (token()) {
        case 21 /* OpenParenToken */:
        // Method declaration
        case 30 /* LessThanToken */:
        // Generic Method declaration
        case 54 /* ExclamationToken */:
        // Non-null assertion on property name
        case 59 /* ColonToken */:
        // Type Annotation for declaration
        case 64 /* EqualsToken */:
        // Initializer for declaration
        case 58 /* QuestionToken */:
          return true;
        default:
          return canParseSemicolon();
      }
    }
    return false;
  }
  function parseClassStaticBlockDeclaration(pos, hasJSDoc, modifiers) {
    parseExpectedToken(126 /* StaticKeyword */);
    const body = parseClassStaticBlockBody();
    const node = withJSDoc(finishNode(factory2.createClassStaticBlockDeclaration(body), pos), hasJSDoc);
    node.modifiers = modifiers;
    return node;
  }
  function parseClassStaticBlockBody() {
    const savedYieldContext = inYieldContext();
    const savedAwaitContext = inAwaitContext();
    setYieldContext(false);
    setAwaitContext(true);
    const body = parseBlock(
      /*ignoreMissingOpenBrace*/
      false
    );
    setYieldContext(savedYieldContext);
    setAwaitContext(savedAwaitContext);
    return body;
  }
  function parseDecoratorExpression() {
    if (inAwaitContext() && token() === 135 /* AwaitKeyword */) {
      const pos = getNodePos();
      const awaitExpression = parseIdentifier(Diagnostics.Expression_expected);
      nextToken();
      const memberExpression = parseMemberExpressionRest(
        pos,
        awaitExpression,
        /*allowOptionalChain*/
        true
      );
      return parseCallExpressionRest(pos, memberExpression);
    }
    return parseLeftHandSideExpressionOrHigher();
  }
  function tryParseDecorator() {
    const pos = getNodePos();
    if (!parseOptional(60 /* AtToken */)) {
      return void 0;
    }
    const expression = doInDecoratorContext(parseDecoratorExpression);
    return finishNode(factory2.createDecorator(expression), pos);
  }
  function tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock) {
    const pos = getNodePos();
    const kind = token();
    if (token() === 87 /* ConstKeyword */ && permitConstAsModifier) {
      if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
        return void 0;
      }
    } else if (stopOnStartOfClassStaticBlock && token() === 126 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) {
      return void 0;
    } else if (hasSeenStaticModifier && token() === 126 /* StaticKeyword */) {
      return void 0;
    } else {
      if (!parseAnyContextualModifier()) {
        return void 0;
      }
    }
    return finishNode(factoryCreateToken(kind), pos);
  }
  function parseModifiers(allowDecorators, permitConstAsModifier, stopOnStartOfClassStaticBlock) {
    const pos = getNodePos();
    let list;
    let decorator, modifier, hasSeenStaticModifier = false, hasLeadingModifier = false, hasTrailingDecorator = false;
    if (allowDecorators && token() === 60 /* AtToken */) {
      while (decorator = tryParseDecorator()) {
        list = append(list, decorator);
      }
    }
    while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) {
      if (modifier.kind === 126 /* StaticKeyword */) hasSeenStaticModifier = true;
      list = append(list, modifier);
      hasLeadingModifier = true;
    }
    if (hasLeadingModifier && allowDecorators && token() === 60 /* AtToken */) {
      while (decorator = tryParseDecorator()) {
        list = append(list, decorator);
        hasTrailingDecorator = true;
      }
    }
    if (hasTrailingDecorator) {
      while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) {
        if (modifier.kind === 126 /* StaticKeyword */) hasSeenStaticModifier = true;
        list = append(list, modifier);
      }
    }
    return list && createNodeArray(list, pos);
  }
  function parseModifiersForArrowFunction() {
    let modifiers;
    if (token() === 134 /* AsyncKeyword */) {
      const pos = getNodePos();
      nextToken();
      const modifier = finishNode(factoryCreateToken(134 /* AsyncKeyword */), pos);
      modifiers = createNodeArray([modifier], pos);
    }
    return modifiers;
  }
  function parseClassElement() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    if (token() === 27 /* SemicolonToken */) {
      nextToken();
      return withJSDoc(finishNode(factory2.createSemicolonClassElement(), pos), hasJSDoc);
    }
    const modifiers = parseModifiers(
      /*allowDecorators*/
      true,
      /*permitConstAsModifier*/
      true,
      /*stopOnStartOfClassStaticBlock*/
      true
    );
    if (token() === 126 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) {
      return parseClassStaticBlockDeclaration(pos, hasJSDoc, modifiers);
    }
    if (parseContextualModifier(139 /* GetKeyword */)) {
      return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */, 0 /* None */);
    }
    if (parseContextualModifier(153 /* SetKeyword */)) {
      return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */, 0 /* None */);
    }
    if (token() === 137 /* ConstructorKeyword */ || token() === 11 /* StringLiteral */) {
      const constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, modifiers);
      if (constructorDeclaration) {
        return constructorDeclaration;
      }
    }
    if (isIndexSignature()) {
      return parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers);
    }
    if (tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */ || token() === 42 /* AsteriskToken */ || token() === 23 /* OpenBracketToken */) {
      const isAmbient = some(modifiers, isDeclareModifier);
      if (isAmbient) {
        for (const m of modifiers) {
          m.flags |= 33554432 /* Ambient */;
        }
        return doInsideOfContext(33554432 /* Ambient */, () => parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers));
      } else {
        return parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers);
      }
    }
    if (modifiers) {
      const name = createMissingNode(
        80 /* Identifier */,
        /*reportAtCurrentPosition*/
        true,
        Diagnostics.Declaration_expected
      );
      return parsePropertyDeclaration(
        pos,
        hasJSDoc,
        modifiers,
        name,
        /*questionToken*/
        void 0
      );
    }
    return Debug.fail("Should not have attempted to parse class member declaration.");
  }
  function parseDecoratedExpression() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    const modifiers = parseModifiers(
      /*allowDecorators*/
      true
    );
    if (token() === 86 /* ClassKeyword */) {
      return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, 231 /* ClassExpression */);
    }
    const missing = createMissingNode(
      282 /* MissingDeclaration */,
      /*reportAtCurrentPosition*/
      true,
      Diagnostics.Expression_expected
    );
    setTextRangePos(missing, pos);
    missing.modifiers = modifiers;
    return missing;
  }
  function parseClassExpression() {
    return parseClassDeclarationOrExpression(
      getNodePos(),
      hasPrecedingJSDocComment(),
      /*modifiers*/
      void 0,
      231 /* ClassExpression */
    );
  }
  function parseClassDeclaration(pos, hasJSDoc, modifiers) {
    return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, 263 /* ClassDeclaration */);
  }
  function parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, kind) {
    const savedAwaitContext = inAwaitContext();
    parseExpected(86 /* ClassKeyword */);
    const name = parseNameOfClassDeclarationOrExpression();
    const typeParameters = parseTypeParameters();
    if (some(modifiers, isExportModifier)) setAwaitContext(
      /*value*/
      true
    );
    const heritageClauses = parseHeritageClauses();
    let members;
    if (parseExpected(19 /* OpenBraceToken */)) {
      members = parseClassMembers();
      parseExpected(20 /* CloseBraceToken */);
    } else {
      members = createMissingList();
    }
    setAwaitContext(savedAwaitContext);
    const node = kind === 263 /* ClassDeclaration */ ? factory2.createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) : factory2.createClassExpression(modifiers, name, typeParameters, heritageClauses, members);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseNameOfClassDeclarationOrExpression() {
    return isBindingIdentifier() && !isImplementsClause() ? createIdentifier(isBindingIdentifier()) : void 0;
  }
  function isImplementsClause() {
    return token() === 119 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
  }
  function parseHeritageClauses() {
    if (isHeritageClause2()) {
      return parseList(22 /* HeritageClauses */, parseHeritageClause);
    }
    return void 0;
  }
  function parseHeritageClause() {
    const pos = getNodePos();
    const tok = token();
    Debug.assert(tok === 96 /* ExtendsKeyword */ || tok === 119 /* ImplementsKeyword */);
    nextToken();
    const types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
    return finishNode(factory2.createHeritageClause(tok, types), pos);
  }
  function parseExpressionWithTypeArguments() {
    const pos = getNodePos();
    const expression = parseLeftHandSideExpressionOrHigher();
    if (expression.kind === 233 /* ExpressionWithTypeArguments */) {
      return expression;
    }
    const typeArguments = tryParseTypeArguments();
    return finishNode(factory2.createExpressionWithTypeArguments(expression, typeArguments), pos);
  }
  function tryParseTypeArguments() {
    return token() === 30 /* LessThanToken */ ? parseBracketedList(20 /* TypeArguments */, parseType, 30 /* LessThanToken */, 32 /* GreaterThanToken */) : void 0;
  }
  function isHeritageClause2() {
    return token() === 96 /* ExtendsKeyword */ || token() === 119 /* ImplementsKeyword */;
  }
  function parseClassMembers() {
    return parseList(5 /* ClassMembers */, parseClassElement);
  }
  function parseInterfaceDeclaration(pos, hasJSDoc, modifiers) {
    parseExpected(120 /* InterfaceKeyword */);
    const name = parseIdentifier();
    const typeParameters = parseTypeParameters();
    const heritageClauses = parseHeritageClauses();
    const members = parseObjectTypeMembers();
    const node = factory2.createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseTypeAliasDeclaration(pos, hasJSDoc, modifiers) {
    parseExpected(156 /* TypeKeyword */);
    if (scanner.hasPrecedingLineBreak()) {
      parseErrorAtCurrentToken(Diagnostics.Line_break_not_permitted_here);
    }
    const name = parseIdentifier();
    const typeParameters = parseTypeParameters();
    parseExpected(64 /* EqualsToken */);
    const type = token() === 141 /* IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType();
    parseSemicolon();
    const node = factory2.createTypeAliasDeclaration(modifiers, name, typeParameters, type);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseEnumMember() {
    const pos = getNodePos();
    const hasJSDoc = hasPrecedingJSDocComment();
    const name = parsePropertyName();
    const initializer = allowInAnd(parseInitializer);
    return withJSDoc(finishNode(factory2.createEnumMember(name, initializer), pos), hasJSDoc);
  }
  function parseEnumDeclaration(pos, hasJSDoc, modifiers) {
    parseExpected(94 /* EnumKeyword */);
    const name = parseIdentifier();
    let members;
    if (parseExpected(19 /* OpenBraceToken */)) {
      members = doOutsideOfYieldAndAwaitContext(() => parseDelimitedList(6 /* EnumMembers */, parseEnumMember));
      parseExpected(20 /* CloseBraceToken */);
    } else {
      members = createMissingList();
    }
    const node = factory2.createEnumDeclaration(modifiers, name, members);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseModuleBlock() {
    const pos = getNodePos();
    let statements;
    if (parseExpected(19 /* OpenBraceToken */)) {
      statements = parseList(1 /* BlockStatements */, parseStatement);
      parseExpected(20 /* CloseBraceToken */);
    } else {
      statements = createMissingList();
    }
    return finishNode(factory2.createModuleBlock(statements), pos);
  }
  function parseModuleOrNamespaceDeclaration(pos, hasJSDoc, modifiers, flags) {
    const namespaceFlag = flags & 32 /* Namespace */;
    const name = flags & 8 /* NestedNamespace */ ? parseIdentifierName() : parseIdentifier();
    const body = parseOptional(25 /* DotToken */) ? parseModuleOrNamespaceDeclaration(
      getNodePos(),
      /*hasJSDoc*/
      false,
      /*modifiers*/
      void 0,
      8 /* NestedNamespace */ | namespaceFlag
    ) : parseModuleBlock();
    const node = factory2.createModuleDeclaration(modifiers, name, body, flags);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn) {
    let flags = 0;
    let name;
    if (token() === 162 /* GlobalKeyword */) {
      name = parseIdentifier();
      flags |= 2048 /* GlobalAugmentation */;
    } else {
      name = parseLiteralNode();
      name.text = internIdentifier(name.text);
    }
    let body;
    if (token() === 19 /* OpenBraceToken */) {
      body = parseModuleBlock();
    } else {
      parseSemicolon();
    }
    const node = factory2.createModuleDeclaration(modifiersIn, name, body, flags);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseModuleDeclaration(pos, hasJSDoc, modifiersIn) {
    let flags = 0;
    if (token() === 162 /* GlobalKeyword */) {
      return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn);
    } else if (parseOptional(145 /* NamespaceKeyword */)) {
      flags |= 32 /* Namespace */;
    } else {
      parseExpected(144 /* ModuleKeyword */);
      if (token() === 11 /* StringLiteral */) {
        return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn);
      }
    }
    return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, modifiersIn, flags);
  }
  function isExternalModuleReference2() {
    return token() === 149 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen);
  }
  function nextTokenIsOpenParen() {
    return nextToken() === 21 /* OpenParenToken */;
  }
  function nextTokenIsOpenBrace() {
    return nextToken() === 19 /* OpenBraceToken */;
  }
  function nextTokenIsSlash() {
    return nextToken() === 44 /* SlashToken */;
  }
  function parseNamespaceExportDeclaration(pos, hasJSDoc, modifiers) {
    parseExpected(130 /* AsKeyword */);
    parseExpected(145 /* NamespaceKeyword */);
    const name = parseIdentifier();
    parseSemicolon();
    const node = factory2.createNamespaceExportDeclaration(name);
    node.modifiers = modifiers;
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, modifiers) {
    parseExpected(102 /* ImportKeyword */);
    const afterImportPos = scanner.getTokenFullStart();
    let identifier;
    if (isIdentifier2()) {
      identifier = parseIdentifier();
    }
    let isTypeOnly = false;
    if ((identifier == null ? void 0 : identifier.escapedText) === "type" && (token() !== 161 /* FromKeyword */ || isIdentifier2() && lookAhead(nextTokenIsFromKeywordOrEqualsToken)) && (isIdentifier2() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
      isTypeOnly = true;
      identifier = isIdentifier2() ? parseIdentifier() : void 0;
    }
    if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
      return parseImportEqualsDeclaration(pos, hasJSDoc, modifiers, identifier, isTypeOnly);
    }
    const importClause = tryParseImportClause(identifier, afterImportPos, isTypeOnly);
    const moduleSpecifier = parseModuleSpecifier();
    const attributes = tryParseImportAttributes();
    parseSemicolon();
    const node = factory2.createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function tryParseImportClause(identifier, pos, isTypeOnly, skipJsDocLeadingAsterisks = false) {
    let importClause;
    if (identifier || // import id
    token() === 42 /* AsteriskToken */ || // import *
    token() === 19 /* OpenBraceToken */) {
      importClause = parseImportClause(identifier, pos, isTypeOnly, skipJsDocLeadingAsterisks);
      parseExpected(161 /* FromKeyword */);
    }
    return importClause;
  }
  function tryParseImportAttributes() {
    const currentToken2 = token();
    if ((currentToken2 === 118 /* WithKeyword */ || currentToken2 === 132 /* AssertKeyword */) && !scanner.hasPrecedingLineBreak()) {
      return parseImportAttributes(currentToken2);
    }
  }
  function parseImportAttribute() {
    const pos = getNodePos();
    const name = tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(11 /* StringLiteral */);
    parseExpected(59 /* ColonToken */);
    const value = parseAssignmentExpressionOrHigher(
      /*allowReturnTypeInArrowFunction*/
      true
    );
    return finishNode(factory2.createImportAttribute(name, value), pos);
  }
  function parseImportAttributes(token2, skipKeyword) {
    const pos = getNodePos();
    if (!skipKeyword) {
      parseExpected(token2);
    }
    const openBracePosition = scanner.getTokenStart();
    if (parseExpected(19 /* OpenBraceToken */)) {
      const multiLine = scanner.hasPrecedingLineBreak();
      const elements = parseDelimitedList(
        24 /* ImportAttributes */,
        parseImportAttribute,
        /*considerSemicolonAsDelimiter*/
        true
      );
      if (!parseExpected(20 /* CloseBraceToken */)) {
        const lastError = lastOrUndefined(parseDiagnostics);
        if (lastError && lastError.code === Diagnostics._0_expected.code) {
          addRelatedInfo(
            lastError,
            createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}")
          );
        }
      }
      return finishNode(factory2.createImportAttributes(elements, multiLine, token2), pos);
    } else {
      const elements = createNodeArray(
        [],
        getNodePos(),
        /*end*/
        void 0,
        /*hasTrailingComma*/
        false
      );
      return finishNode(factory2.createImportAttributes(
        elements,
        /*multiLine*/
        false,
        token2
      ), pos);
    }
  }
  function tokenAfterImportDefinitelyProducesImportDeclaration() {
    return token() === 42 /* AsteriskToken */ || token() === 19 /* OpenBraceToken */;
  }
  function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
    return token() === 28 /* CommaToken */ || token() === 161 /* FromKeyword */;
  }
  function parseImportEqualsDeclaration(pos, hasJSDoc, modifiers, identifier, isTypeOnly) {
    parseExpected(64 /* EqualsToken */);
    const moduleReference = parseModuleReference();
    parseSemicolon();
    const node = factory2.createImportEqualsDeclaration(modifiers, isTypeOnly, identifier, moduleReference);
    const finished = withJSDoc(finishNode(node, pos), hasJSDoc);
    return finished;
  }
  function parseImportClause(identifier, pos, isTypeOnly, skipJsDocLeadingAsterisks) {
    let namedBindings;
    if (!identifier || parseOptional(28 /* CommaToken */)) {
      if (skipJsDocLeadingAsterisks) scanner.setSkipJsDocLeadingAsterisks(true);
      namedBindings = token() === 42 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(275 /* NamedImports */);
      if (skipJsDocLeadingAsterisks) scanner.setSkipJsDocLeadingAsterisks(false);
    }
    return finishNode(factory2.createImportClause(isTypeOnly, identifier, namedBindings), pos);
  }
  function parseModuleReference() {
    return isExternalModuleReference2() ? parseExternalModuleReference() : parseEntityName(
      /*allowReservedWords*/
      false
    );
  }
  function parseExternalModuleReference() {
    const pos = getNodePos();
    parseExpected(149 /* RequireKeyword */);
    parseExpected(21 /* OpenParenToken */);
    const expression = parseModuleSpecifier();
    parseExpected(22 /* CloseParenToken */);
    return finishNode(factory2.createExternalModuleReference(expression), pos);
  }
  function parseModuleSpecifier() {
    if (token() === 11 /* StringLiteral */) {
      const result = parseLiteralNode();
      result.text = internIdentifier(result.text);
      return result;
    } else {
      return parseExpression();
    }
  }
  function parseNamespaceImport() {
    const pos = getNodePos();
    parseExpected(42 /* AsteriskToken */);
    parseExpected(130 /* AsKeyword */);
    const name = parseIdentifier();
    return finishNode(factory2.createNamespaceImport(name), pos);
  }
  function canParseModuleExportName() {
    return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */;
  }
  function parseModuleExportName(parseName) {
    return token() === 11 /* StringLiteral */ ? parseLiteralNode() : parseName();
  }
  function parseNamedImportsOrExports(kind) {
    const pos = getNodePos();
    const node = kind === 275 /* NamedImports */ ? factory2.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 19 /* OpenBraceToken */, 20 /* CloseBraceToken */)) : factory2.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 19 /* OpenBraceToken */, 20 /* CloseBraceToken */));
    return finishNode(node, pos);
  }
  function parseExportSpecifier() {
    const hasJSDoc = hasPrecedingJSDocComment();
    return withJSDoc(parseImportOrExportSpecifier(281 /* ExportSpecifier */), hasJSDoc);
  }
  function parseImportSpecifier() {
    return parseImportOrExportSpecifier(276 /* ImportSpecifier */);
  }
  function parseImportOrExportSpecifier(kind) {
    const pos = getNodePos();
    let checkIdentifierIsKeyword = isKeyword(token()) && !isIdentifier2();
    let checkIdentifierStart = scanner.getTokenStart();
    let checkIdentifierEnd = scanner.getTokenEnd();
    let isTypeOnly = false;
    let propertyName;
    let canParseAsKeyword = true;
    let name = parseModuleExportName(parseIdentifierName);
    if (name.kind === 80 /* Identifier */ && name.escapedText === "type") {
      if (token() === 130 /* AsKeyword */) {
        const firstAs = parseIdentifierName();
        if (token() === 130 /* AsKeyword */) {
          const secondAs = parseIdentifierName();
          if (canParseModuleExportName()) {
            isTypeOnly = true;
            propertyName = firstAs;
            name = parseModuleExportName(parseNameWithKeywordCheck);
            canParseAsKeyword = false;
          } else {
            propertyName = name;
            name = secondAs;
            canParseAsKeyword = false;
          }
        } else if (canParseModuleExportName()) {
          propertyName = name;
          canParseAsKeyword = false;
          name = parseModuleExportName(parseNameWithKeywordCheck);
        } else {
          isTypeOnly = true;
          name = firstAs;
        }
      } else if (canParseModuleExportName()) {
        isTypeOnly = true;
        name = parseModuleExportName(parseNameWithKeywordCheck);
      }
    }
    if (canParseAsKeyword && token() === 130 /* AsKeyword */) {
      propertyName = name;
      parseExpected(130 /* AsKeyword */);
      name = parseModuleExportName(parseNameWithKeywordCheck);
    }
    if (kind === 276 /* ImportSpecifier */) {
      if (name.kind !== 80 /* Identifier */) {
        parseErrorAt(skipTrivia(sourceText, name.pos), name.end, Diagnostics.Identifier_expected);
        name = setTextRangePosEnd(createMissingNode(
          80 /* Identifier */,
          /*reportAtCurrentPosition*/
          false
        ), name.pos, name.pos);
      } else if (checkIdentifierIsKeyword) {
        parseErrorAt(checkIdentifierStart, checkIdentifierEnd, Diagnostics.Identifier_expected);
      }
    }
    const node = kind === 276 /* ImportSpecifier */ ? factory2.createImportSpecifier(isTypeOnly, propertyName, name) : factory2.createExportSpecifier(isTypeOnly, propertyName, name);
    return finishNode(node, pos);
    function parseNameWithKeywordCheck() {
      checkIdentifierIsKeyword = isKeyword(token()) && !isIdentifier2();
      checkIdentifierStart = scanner.getTokenStart();
      checkIdentifierEnd = scanner.getTokenEnd();
      return parseIdentifierName();
    }
  }
  function parseNamespaceExport(pos) {
    return finishNode(factory2.createNamespaceExport(parseModuleExportName(parseIdentifierName)), pos);
  }
  function parseExportDeclaration(pos, hasJSDoc, modifiers) {
    const savedAwaitContext = inAwaitContext();
    setAwaitContext(
      /*value*/
      true
    );
    let exportClause;
    let moduleSpecifier;
    let attributes;
    const isTypeOnly = parseOptional(156 /* TypeKeyword */);
    const namespaceExportPos = getNodePos();
    if (parseOptional(42 /* AsteriskToken */)) {
      if (parseOptional(130 /* AsKeyword */)) {
        exportClause = parseNamespaceExport(namespaceExportPos);
      }
      parseExpected(161 /* FromKeyword */);
      moduleSpecifier = parseModuleSpecifier();
    } else {
      exportClause = parseNamedImportsOrExports(279 /* NamedExports */);
      if (token() === 161 /* FromKeyword */ || token() === 11 /* StringLiteral */ && !scanner.hasPrecedingLineBreak()) {
        parseExpected(161 /* FromKeyword */);
        moduleSpecifier = parseModuleSpecifier();
      }
    }
    const currentToken2 = token();
    if (moduleSpecifier && (currentToken2 === 118 /* WithKeyword */ || currentToken2 === 132 /* AssertKeyword */) && !scanner.hasPrecedingLineBreak()) {
      attributes = parseImportAttributes(currentToken2);
    }
    parseSemicolon();
    setAwaitContext(savedAwaitContext);
    const node = factory2.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  function parseExportAssignment(pos, hasJSDoc, modifiers) {
    const savedAwaitContext = inAwaitContext();
    setAwaitContext(
      /*value*/
      true
    );
    let isExportEquals;
    if (parseOptional(64 /* EqualsToken */)) {
      isExportEquals = true;
    } else {
      parseExpected(90 /* DefaultKeyword */);
    }
    const expression = parseAssignmentExpressionOrHigher(
      /*allowReturnTypeInArrowFunction*/
      true
    );
    parseSemicolon();
    setAwaitContext(savedAwaitContext);
    const node = factory2.createExportAssignment(modifiers, isExportEquals, expression);
    return withJSDoc(finishNode(node, pos), hasJSDoc);
  }
  let ParsingContext;
  ((ParsingContext2) => {
    ParsingContext2[ParsingContext2["SourceElements"] = 0] = "SourceElements";
    ParsingContext2[ParsingContext2["BlockStatements"] = 1] = "BlockStatements";
    ParsingContext2[ParsingContext2["SwitchClauses"] = 2] = "SwitchClauses";
    ParsingContext2[ParsingContext2["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
    ParsingContext2[ParsingContext2["TypeMembers"] = 4] = "TypeMembers";
    ParsingContext2[ParsingContext2["ClassMembers"] = 5] = "ClassMembers";
    ParsingContext2[ParsingContext2["EnumMembers"] = 6] = "EnumMembers";
    ParsingContext2[ParsingContext2["HeritageClauseElement"] = 7] = "HeritageClauseElement";
    ParsingContext2[ParsingContext2["VariableDeclarations"] = 8] = "VariableDeclarations";
    ParsingContext2[ParsingContext2["ObjectBindingElements"] = 9] = "ObjectBindingElements";
    ParsingContext2[ParsingContext2["ArrayBindingElements"] = 10] = "ArrayBindingElements";
    ParsingContext2[ParsingContext2["ArgumentExpressions"] = 11] = "ArgumentExpressions";
    ParsingContext2[ParsingContext2["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
    ParsingContext2[ParsingContext2["JsxAttributes"] = 13] = "JsxAttributes";
    ParsingContext2[ParsingContext2["JsxChildren"] = 14] = "JsxChildren";
    ParsingContext2[ParsingContext2["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
    ParsingContext2[ParsingContext2["Parameters"] = 16] = "Parameters";
    ParsingContext2[ParsingContext2["JSDocParameters"] = 17] = "JSDocParameters";
    ParsingContext2[ParsingContext2["RestProperties"] = 18] = "RestProperties";
    ParsingContext2[ParsingContext2["TypeParameters"] = 19] = "TypeParameters";
    ParsingContext2[ParsingContext2["TypeArguments"] = 20] = "TypeArguments";
    ParsingContext2[ParsingContext2["TupleElementTypes"] = 21] = "TupleElementTypes";
    ParsingContext2[ParsingContext2["HeritageClauses"] = 22] = "HeritageClauses";
    ParsingContext2[ParsingContext2["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
    ParsingContext2[ParsingContext2["ImportAttributes"] = 24] = "ImportAttributes";
    ParsingContext2[ParsingContext2["JSDocComment"] = 25] = "JSDocComment";
    ParsingContext2[ParsingContext2["Count"] = 26] = "Count";
  })(ParsingContext || (ParsingContext = {}));
  let Tristate;
  ((Tristate2) => {
    Tristate2[Tristate2["False"] = 0] = "False";
    Tristate2[Tristate2["True"] = 1] = "True";
    Tristate2[Tristate2["Unknown"] = 2] = "Unknown";
  })(Tristate || (Tristate = {}));
  let JSDocParser;
  ((JSDocParser2) => {
    function parseJSDocTypeExpressionForTests(content, start, length2) {
      initializeState(
        "file.js",
        content,
        99 /* Latest */,
        /*syntaxCursor*/
        void 0,
        1 /* JS */,
        0 /* ParseAll */
      );
      scanner.setText(content, start, length2);
      currentToken = scanner.scan();
      const jsDocTypeExpression = parseJSDocTypeExpression();
      const sourceFile = createSourceFile2(
        "file.js",
        99 /* Latest */,
        1 /* JS */,
        /*isDeclarationFile*/
        false,
        [],
        factoryCreateToken(1 /* EndOfFileToken */),
        0 /* None */,
        noop
      );
      const diagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile);
      if (jsDocDiagnostics) {
        sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
      }
      clearState();
      return jsDocTypeExpression ? { jsDocTypeExpression, diagnostics } : void 0;
    }
    JSDocParser2.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
    function parseJSDocTypeExpression(mayOmitBraces) {
      const pos = getNodePos();
      const hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(19 /* OpenBraceToken */);
      const type = doInsideOfContext(16777216 /* JSDoc */, parseJSDocType);
      if (!mayOmitBraces || hasBrace) {
        parseExpectedJSDoc(20 /* CloseBraceToken */);
      }
      const result = factory2.createJSDocTypeExpression(type);
      fixupParentReferences(result);
      return finishNode(result, pos);
    }
    JSDocParser2.parseJSDocTypeExpression = parseJSDocTypeExpression;
    function parseJSDocNameReference() {
      const pos = getNodePos();
      const hasBrace = parseOptional(19 /* OpenBraceToken */);
      const p2 = getNodePos();
      let entityName = parseEntityName(
        /*allowReservedWords*/
        false
      );
      while (token() === 81 /* PrivateIdentifier */) {
        reScanHashToken();
        nextTokenJSDoc();
        entityName = finishNode(factory2.createJSDocMemberName(entityName, parseIdentifier()), p2);
      }
      if (hasBrace) {
        parseExpectedJSDoc(20 /* CloseBraceToken */);
      }
      const result = factory2.createJSDocNameReference(entityName);
      fixupParentReferences(result);
      return finishNode(result, pos);
    }
    JSDocParser2.parseJSDocNameReference = parseJSDocNameReference;
    function parseIsolatedJSDocComment(content, start, length2) {
      initializeState(
        "",
        content,
        99 /* Latest */,
        /*syntaxCursor*/
        void 0,
        1 /* JS */,
        0 /* ParseAll */
      );
      const jsDoc = doInsideOfContext(16777216 /* JSDoc */, () => parseJSDocCommentWorker(start, length2));
      const sourceFile = { languageVariant: 0 /* Standard */, text: content };
      const diagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile);
      clearState();
      return jsDoc ? { jsDoc, diagnostics } : void 0;
    }
    JSDocParser2.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
    function parseJSDocComment(parent, start, length2) {
      const saveToken = currentToken;
      const saveParseDiagnosticsLength = parseDiagnostics.length;
      const saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
      const comment = doInsideOfContext(16777216 /* JSDoc */, () => parseJSDocCommentWorker(start, length2));
      setParent(comment, parent);
      if (contextFlags & 524288 /* JavaScriptFile */) {
        if (!jsDocDiagnostics) {
          jsDocDiagnostics = [];
        }
        addRange(jsDocDiagnostics, parseDiagnostics, saveParseDiagnosticsLength);
      }
      currentToken = saveToken;
      parseDiagnostics.length = saveParseDiagnosticsLength;
      parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
      return comment;
    }
    JSDocParser2.parseJSDocComment = parseJSDocComment;
    let JSDocState;
    ((JSDocState2) => {
      JSDocState2[JSDocState2["BeginningOfLine"] = 0] = "BeginningOfLine";
      JSDocState2[JSDocState2["SawAsterisk"] = 1] = "SawAsterisk";
      JSDocState2[JSDocState2["SavingComments"] = 2] = "SavingComments";
      JSDocState2[JSDocState2["SavingBackticks"] = 3] = "SavingBackticks";
    })(JSDocState || (JSDocState = {}));
    let PropertyLikeParse;
    ((PropertyLikeParse2) => {
      PropertyLikeParse2[PropertyLikeParse2["Property"] = 1] = "Property";
      PropertyLikeParse2[PropertyLikeParse2["Parameter"] = 2] = "Parameter";
      PropertyLikeParse2[PropertyLikeParse2["CallbackParameter"] = 4] = "CallbackParameter";
    })(PropertyLikeParse || (PropertyLikeParse = {}));
    function parseJSDocCommentWorker(start = 0, length2) {
      const content = sourceText;
      const end = length2 === void 0 ? content.length : start + length2;
      length2 = end - start;
      Debug.assert(start >= 0);
      Debug.assert(start <= end);
      Debug.assert(end <= content.length);
      if (!isJSDocLikeText(content, start)) {
        return void 0;
      }
      let tags;
      let tagsPos;
      let tagsEnd;
      let linkEnd;
      let commentsPos;
      let comments = [];
      const parts = [];
      const saveParsingContext = parsingContext;
      parsingContext |= 1 << 25 /* JSDocComment */;
      const result = scanner.scanRange(start + 3, length2 - 5, doJSDocScan);
      parsingContext = saveParsingContext;
      return result;
      function doJSDocScan() {
        let state = 1 /* SawAsterisk */;
        let margin;
        let indent2 = start - (content.lastIndexOf("\n", start) + 1) + 4;
        function pushComment(text) {
          if (!margin) {
            margin = indent2;
          }
          comments.push(text);
          indent2 += text.length;
        }
        nextTokenJSDoc();
        while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) ;
        if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
          state = 0 /* BeginningOfLine */;
          indent2 = 0;
        }
        loop:
          while (true) {
            switch (token()) {
              case 60 /* AtToken */:
                removeTrailingWhitespace(comments);
                if (!commentsPos) commentsPos = getNodePos();
                addTag(parseTag(indent2));
                state = 0 /* BeginningOfLine */;
                margin = void 0;
                break;
              case 4 /* NewLineTrivia */:
                comments.push(scanner.getTokenText());
                state = 0 /* BeginningOfLine */;
                indent2 = 0;
                break;
              case 42 /* AsteriskToken */:
                const asterisk = scanner.getTokenText();
                if (state === 1 /* SawAsterisk */) {
                  state = 2 /* SavingComments */;
                  pushComment(asterisk);
                } else {
                  Debug.assert(state === 0 /* BeginningOfLine */);
                  state = 1 /* SawAsterisk */;
                  indent2 += asterisk.length;
                }
                break;
              case 5 /* WhitespaceTrivia */:
                Debug.assert(state !== 2 /* SavingComments */, "whitespace shouldn't come from the scanner while saving top-level comment text");
                const whitespace = scanner.getTokenText();
                if (margin !== void 0 && indent2 + whitespace.length > margin) {
                  comments.push(whitespace.slice(margin - indent2));
                }
                indent2 += whitespace.length;
                break;
              case 1 /* EndOfFileToken */:
                break loop;
              case 82 /* JSDocCommentTextToken */:
                state = 2 /* SavingComments */;
                pushComment(scanner.getTokenValue());
                break;
              case 19 /* OpenBraceToken */:
                state = 2 /* SavingComments */;
                const commentEnd = scanner.getTokenFullStart();
                const linkStart = scanner.getTokenEnd() - 1;
                const link = parseJSDocLink(linkStart);
                if (link) {
                  if (!linkEnd) {
                    removeLeadingNewlines(comments);
                  }
                  parts.push(finishNode(factory2.createJSDocText(comments.join("")), linkEnd ?? start, commentEnd));
                  parts.push(link);
                  comments = [];
                  linkEnd = scanner.getTokenEnd();
                  break;
                }
              // fallthrough if it's not a {@link sequence
              default:
                state = 2 /* SavingComments */;
                pushComment(scanner.getTokenText());
                break;
            }
            if (state === 2 /* SavingComments */) {
              nextJSDocCommentTextToken(
                /*inBackticks*/
                false
              );
            } else {
              nextTokenJSDoc();
            }
          }
        const trimmedComments = comments.join("").trimEnd();
        if (parts.length && trimmedComments.length) {
          parts.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd ?? start, commentsPos));
        }
        if (parts.length && tags) Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set");
        const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd);
        return finishNode(factory2.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : trimmedComments.length ? trimmedComments : void 0, tagsArray), start, end);
      }
      function removeLeadingNewlines(comments2) {
        while (comments2.length && (comments2[0] === "\n" || comments2[0] === "\r")) {
          comments2.shift();
        }
      }
      function removeTrailingWhitespace(comments2) {
        while (comments2.length) {
          const trimmed = comments2[comments2.length - 1].trimEnd();
          if (trimmed === "") {
            comments2.pop();
          } else if (trimmed.length < comments2[comments2.length - 1].length) {
            comments2[comments2.length - 1] = trimmed;
            break;
          } else {
            break;
          }
        }
      }
      function isNextNonwhitespaceTokenEndOfFile() {
        while (true) {
          nextTokenJSDoc();
          if (token() === 1 /* EndOfFileToken */) {
            return true;
          }
          if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
            return false;
          }
        }
      }
      function skipWhitespace() {
        if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
          if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
            return;
          }
        }
        while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
          nextTokenJSDoc();
        }
      }
      function skipWhitespaceOrAsterisk() {
        if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
          if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
            return "";
          }
        }
        let precedingLineBreak = scanner.hasPrecedingLineBreak();
        let seenLineBreak = false;
        let indentText = "";
        while (precedingLineBreak && token() === 42 /* AsteriskToken */ || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
          indentText += scanner.getTokenText();
          if (token() === 4 /* NewLineTrivia */) {
            precedingLineBreak = true;
            seenLineBreak = true;
            indentText = "";
          } else if (token() === 42 /* AsteriskToken */) {
            precedingLineBreak = false;
          }
          nextTokenJSDoc();
        }
        return seenLineBreak ? indentText : "";
      }
      function parseTag(margin) {
        Debug.assert(token() === 60 /* AtToken */);
        const start2 = scanner.getTokenStart();
        nextTokenJSDoc();
        const tagName = parseJSDocIdentifierName(
          /*message*/
          void 0
        );
        const indentText = skipWhitespaceOrAsterisk();
        let tag;
        switch (tagName.escapedText) {
          case "author":
            tag = parseAuthorTag(start2, tagName, margin, indentText);
            break;
          case "implements":
            tag = parseImplementsTag(start2, tagName, margin, indentText);
            break;
          case "augments":
          case "extends":
            tag = parseAugmentsTag(start2, tagName, margin, indentText);
            break;
          case "class":
          case "constructor":
            tag = parseSimpleTag(start2, factory2.createJSDocClassTag, tagName, margin, indentText);
            break;
          case "public":
            tag = parseSimpleTag(start2, factory2.createJSDocPublicTag, tagName, margin, indentText);
            break;
          case "private":
            tag = parseSimpleTag(start2, factory2.createJSDocPrivateTag, tagName, margin, indentText);
            break;
          case "protected":
            tag = parseSimpleTag(start2, factory2.createJSDocProtectedTag, tagName, margin, indentText);
            break;
          case "readonly":
            tag = parseSimpleTag(start2, factory2.createJSDocReadonlyTag, tagName, margin, indentText);
            break;
          case "override":
            tag = parseSimpleTag(start2, factory2.createJSDocOverrideTag, tagName, margin, indentText);
            break;
          case "deprecated":
            hasDeprecatedTag = true;
            tag = parseSimpleTag(start2, factory2.createJSDocDeprecatedTag, tagName, margin, indentText);
            break;
          case "this":
            tag = parseThisTag(start2, tagName, margin, indentText);
            break;
          case "enum":
            tag = parseEnumTag(start2, tagName, margin, indentText);
            break;
          case "arg":
          case "argument":
          case "param":
            return parseParameterOrPropertyTag(start2, tagName, 2 /* Parameter */, margin);
          case "return":
          case "returns":
            tag = parseReturnTag(start2, tagName, margin, indentText);
            break;
          case "template":
            tag = parseTemplateTag(start2, tagName, margin, indentText);
            break;
          case "type":
            tag = parseTypeTag(start2, tagName, margin, indentText);
            break;
          case "typedef":
            tag = parseTypedefTag(start2, tagName, margin, indentText);
            break;
          case "callback":
            tag = parseCallbackTag(start2, tagName, margin, indentText);
            break;
          case "overload":
            tag = parseOverloadTag(start2, tagName, margin, indentText);
            break;
          case "satisfies":
            tag = parseSatisfiesTag(start2, tagName, margin, indentText);
            break;
          case "see":
            tag = parseSeeTag(start2, tagName, margin, indentText);
            break;
          case "exception":
          case "throws":
            tag = parseThrowsTag(start2, tagName, margin, indentText);
            break;
          case "import":
            tag = parseImportTag(start2, tagName, margin, indentText);
            break;
          default:
            tag = parseUnknownTag(start2, tagName, margin, indentText);
            break;
        }
        return tag;
      }
      function parseTrailingTagComments(pos, end2, margin, indentText) {
        if (!indentText) {
          margin += end2 - pos;
        }
        return parseTagComments(margin, indentText.slice(margin));
      }
      function parseTagComments(indent2, initialMargin) {
        const commentsPos2 = getNodePos();
        let comments2 = [];
        const parts2 = [];
        let linkEnd2;
        let state = 0 /* BeginningOfLine */;
        let margin;
        function pushComment(text) {
          if (!margin) {
            margin = indent2;
          }
          comments2.push(text);
          indent2 += text.length;
        }
        if (initialMargin !== void 0) {
          if (initialMargin !== "") {
            pushComment(initialMargin);
          }
          state = 1 /* SawAsterisk */;
        }
        let tok = token();
        loop:
          while (true) {
            switch (tok) {
              case 4 /* NewLineTrivia */:
                state = 0 /* BeginningOfLine */;
                comments2.push(scanner.getTokenText());
                indent2 = 0;
                break;
              case 60 /* AtToken */:
                scanner.resetTokenState(scanner.getTokenEnd() - 1);
                break loop;
              case 1 /* EndOfFileToken */:
                break loop;
              case 5 /* WhitespaceTrivia */:
                Debug.assert(state !== 2 /* SavingComments */ && state !== 3 /* SavingBackticks */, "whitespace shouldn't come from the scanner while saving comment text");
                const whitespace = scanner.getTokenText();
                if (margin !== void 0 && indent2 + whitespace.length > margin) {
                  comments2.push(whitespace.slice(margin - indent2));
                  state = 2 /* SavingComments */;
                }
                indent2 += whitespace.length;
                break;
              case 19 /* OpenBraceToken */:
                state = 2 /* SavingComments */;
                const commentEnd = scanner.getTokenFullStart();
                const linkStart = scanner.getTokenEnd() - 1;
                const link = parseJSDocLink(linkStart);
                if (link) {
                  parts2.push(finishNode(factory2.createJSDocText(comments2.join("")), linkEnd2 ?? commentsPos2, commentEnd));
                  parts2.push(link);
                  comments2 = [];
                  linkEnd2 = scanner.getTokenEnd();
                } else {
                  pushComment(scanner.getTokenText());
                }
                break;
              case 62 /* BacktickToken */:
                if (state === 3 /* SavingBackticks */) {
                  state = 2 /* SavingComments */;
                } else {
                  state = 3 /* SavingBackticks */;
                }
                pushComment(scanner.getTokenText());
                break;
              case 82 /* JSDocCommentTextToken */:
                if (state !== 3 /* SavingBackticks */) {
                  state = 2 /* SavingComments */;
                }
                pushComment(scanner.getTokenValue());
                break;
              case 42 /* AsteriskToken */:
                if (state === 0 /* BeginningOfLine */) {
                  state = 1 /* SawAsterisk */;
                  indent2 += 1;
                  break;
                }
              // record the * as a comment
              // falls through
              default:
                if (state !== 3 /* SavingBackticks */) {
                  state = 2 /* SavingComments */;
                }
                pushComment(scanner.getTokenText());
                break;
            }
            if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
              tok = nextJSDocCommentTextToken(state === 3 /* SavingBackticks */);
            } else {
              tok = nextTokenJSDoc();
            }
          }
        removeLeadingNewlines(comments2);
        const trimmedComments = comments2.join("").trimEnd();
        if (parts2.length) {
          if (trimmedComments.length) {
            parts2.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd2 ?? commentsPos2));
          }
          return createNodeArray(parts2, commentsPos2, scanner.getTokenEnd());
        } else if (trimmedComments.length) {
          return trimmedComments;
        }
      }
      function parseJSDocLink(start2) {
        const linkType = tryParse(parseJSDocLinkPrefix);
        if (!linkType) {
          return void 0;
        }
        nextTokenJSDoc();
        skipWhitespace();
        const name = parseJSDocLinkName();
        const text = [];
        while (token() !== 20 /* CloseBraceToken */ && token() !== 4 /* NewLineTrivia */ && token() !== 1 /* EndOfFileToken */) {
          text.push(scanner.getTokenText());
          nextTokenJSDoc();
        }
        const create = linkType === "link" ? factory2.createJSDocLink : linkType === "linkcode" ? factory2.createJSDocLinkCode : factory2.createJSDocLinkPlain;
        return finishNode(create(name, text.join("")), start2, scanner.getTokenEnd());
      }
      function parseJSDocLinkName() {
        if (tokenIsIdentifierOrKeyword(token())) {
          const pos = getNodePos();
          let name = parseIdentifierName();
          while (parseOptional(25 /* DotToken */)) {
            name = finishNode(factory2.createQualifiedName(name, token() === 81 /* PrivateIdentifier */ ? createMissingNode(
              80 /* Identifier */,
              /*reportAtCurrentPosition*/
              false
            ) : parseIdentifierName()), pos);
          }
          while (token() === 81 /* PrivateIdentifier */) {
            reScanHashToken();
            nextTokenJSDoc();
            name = finishNode(factory2.createJSDocMemberName(name, parseIdentifier()), pos);
          }
          return name;
        }
        return void 0;
      }
      function parseJSDocLinkPrefix() {
        skipWhitespaceOrAsterisk();
        if (token() === 19 /* OpenBraceToken */ && nextTokenJSDoc() === 60 /* AtToken */ && tokenIsIdentifierOrKeyword(nextTokenJSDoc())) {
          const kind = scanner.getTokenValue();
          if (isJSDocLinkTag(kind)) return kind;
        }
      }
      function isJSDocLinkTag(kind) {
        return kind === "link" || kind === "linkcode" || kind === "linkplain";
      }
      function parseUnknownTag(start2, tagName, indent2, indentText) {
        return finishNode(factory2.createJSDocUnknownTag(tagName, parseTrailingTagComments(start2, getNodePos(), indent2, indentText)), start2);
      }
      function addTag(tag) {
        if (!tag) {
          return;
        }
        if (!tags) {
          tags = [tag];
          tagsPos = tag.pos;
        } else {
          tags.push(tag);
        }
        tagsEnd = tag.end;
      }
      function tryParseTypeExpression() {
        skipWhitespaceOrAsterisk();
        return token() === 19 /* OpenBraceToken */ ? parseJSDocTypeExpression() : void 0;
      }
      function parseBracketNameInPropertyAndParamTag() {
        const isBracketed = parseOptionalJsdoc(23 /* OpenBracketToken */);
        if (isBracketed) {
          skipWhitespace();
        }
        const isBackquoted = parseOptionalJsdoc(62 /* BacktickToken */);
        const name = parseJSDocEntityName();
        if (isBackquoted) {
          parseExpectedTokenJSDoc(62 /* BacktickToken */);
        }
        if (isBracketed) {
          skipWhitespace();
          if (parseOptionalToken(64 /* EqualsToken */)) {
            parseExpression();
          }
          parseExpected(24 /* CloseBracketToken */);
        }
        return { name, isBracketed };
      }
      function isObjectOrObjectArrayTypeReference(node) {
        switch (node.kind) {
          case 151 /* ObjectKeyword */:
            return true;
          case 188 /* ArrayType */:
            return isObjectOrObjectArrayTypeReference(node.elementType);
          default:
            return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
        }
      }
      function parseParameterOrPropertyTag(start2, tagName, target, indent2) {
        let typeExpression = tryParseTypeExpression();
        let isNameFirst = !typeExpression;
        skipWhitespaceOrAsterisk();
        const { name, isBracketed } = parseBracketNameInPropertyAndParamTag();
        const indentText = skipWhitespaceOrAsterisk();
        if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) {
          typeExpression = tryParseTypeExpression();
        }
        const comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText);
        const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target, indent2);
        if (nestedTypeLiteral) {
          typeExpression = nestedTypeLiteral;
          isNameFirst = true;
        }
        const result2 = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment);
        return finishNode(result2, start2);
      }
      function parseNestedTypeLiteral(typeExpression, name, target, indent2) {
        if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
          const pos = getNodePos();
          let child;
          let children;
          while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent2, name))) {
            if (child.kind === 341 /* JSDocParameterTag */ || child.kind === 348 /* JSDocPropertyTag */) {
              children = append(children, child);
            } else if (child.kind === 345 /* JSDocTemplateTag */) {
              parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag);
            }
          }
          if (children) {
            const literal = finishNode(factory2.createJSDocTypeLiteral(children, typeExpression.type.kind === 188 /* ArrayType */), pos);
            return finishNode(factory2.createJSDocTypeExpression(literal), pos);
          }
        }
      }
      function parseReturnTag(start2, tagName, indent2, indentText) {
        if (some(tags, isJSDocReturnTag)) {
          parseErrorAt(tagName.pos, scanner.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.escapedText));
        }
        const typeExpression = tryParseTypeExpression();
        return finishNode(factory2.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), indent2, indentText)), start2);
      }
      function parseTypeTag(start2, tagName, indent2, indentText) {
        if (some(tags, isJSDocTypeTag)) {
          parseErrorAt(tagName.pos, scanner.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.escapedText));
        }
        const typeExpression = parseJSDocTypeExpression(
          /*mayOmitBraces*/
          true
        );
        const comments2 = indent2 !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), indent2, indentText) : void 0;
        return finishNode(factory2.createJSDocTypeTag(tagName, typeExpression, comments2), start2);
      }
      function parseSeeTag(start2, tagName, indent2, indentText) {
        const isMarkdownOrJSDocLink = token() === 23 /* OpenBracketToken */ || lookAhead(() => nextTokenJSDoc() === 60 /* AtToken */ && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && isJSDocLinkTag(scanner.getTokenValue()));
        const nameExpression = isMarkdownOrJSDocLink ? void 0 : parseJSDocNameReference();
        const comments2 = indent2 !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), indent2, indentText) : void 0;
        return finishNode(factory2.createJSDocSeeTag(tagName, nameExpression, comments2), start2);
      }
      function parseThrowsTag(start2, tagName, indent2, indentText) {
        const typeExpression = tryParseTypeExpression();
        const comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText);
        return finishNode(factory2.createJSDocThrowsTag(tagName, typeExpression, comment), start2);
      }
      function parseAuthorTag(start2, tagName, indent2, indentText) {
        const commentStart = getNodePos();
        const textOnly = parseAuthorNameAndEmail();
        let commentEnd = scanner.getTokenFullStart();
        const comments2 = parseTrailingTagComments(start2, commentEnd, indent2, indentText);
        if (!comments2) {
          commentEnd = scanner.getTokenFullStart();
        }
        const allParts = typeof comments2 !== "string" ? createNodeArray(concatenate([finishNode(textOnly, commentStart, commentEnd)], comments2), commentStart) : textOnly.text + comments2;
        return finishNode(factory2.createJSDocAuthorTag(tagName, allParts), start2);
      }
      function parseAuthorNameAndEmail() {
        const comments2 = [];
        let inEmail = false;
        let token2 = scanner.getToken();
        while (token2 !== 1 /* EndOfFileToken */ && token2 !== 4 /* NewLineTrivia */) {
          if (token2 === 30 /* LessThanToken */) {
            inEmail = true;
          } else if (token2 === 60 /* AtToken */ && !inEmail) {
            break;
          } else if (token2 === 32 /* GreaterThanToken */ && inEmail) {
            comments2.push(scanner.getTokenText());
            scanner.resetTokenState(scanner.getTokenEnd());
            break;
          }
          comments2.push(scanner.getTokenText());
          token2 = nextTokenJSDoc();
        }
        return factory2.createJSDocText(comments2.join(""));
      }
      function parseImplementsTag(start2, tagName, margin, indentText) {
        const className = parseExpressionWithTypeArgumentsForAugments();
        return finishNode(factory2.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2);
      }
      function parseAugmentsTag(start2, tagName, margin, indentText) {
        const className = parseExpressionWithTypeArgumentsForAugments();
        return finishNode(factory2.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2);
      }
      function parseSatisfiesTag(start2, tagName, margin, indentText) {
        const typeExpression = parseJSDocTypeExpression(
          /*mayOmitBraces*/
          false
        );
        const comments2 = margin !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), margin, indentText) : void 0;
        return finishNode(factory2.createJSDocSatisfiesTag(tagName, typeExpression, comments2), start2);
      }
      function parseImportTag(start2, tagName, margin, indentText) {
        const afterImportTagPos = scanner.getTokenFullStart();
        let identifier;
        if (isIdentifier2()) {
          identifier = parseIdentifier();
        }
        const importClause = tryParseImportClause(
          identifier,
          afterImportTagPos,
          /*isTypeOnly*/
          true,
          /*skipJsDocLeadingAsterisks*/
          true
        );
        const moduleSpecifier = parseModuleSpecifier();
        const attributes = tryParseImportAttributes();
        const comments2 = margin !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), margin, indentText) : void 0;
        return finishNode(factory2.createJSDocImportTag(tagName, importClause, moduleSpecifier, attributes, comments2), start2);
      }
      function parseExpressionWithTypeArgumentsForAugments() {
        const usedBrace = parseOptional(19 /* OpenBraceToken */);
        const pos = getNodePos();
        const expression = parsePropertyAccessEntityNameExpression();
        scanner.setSkipJsDocLeadingAsterisks(true);
        const typeArguments = tryParseTypeArguments();
        scanner.setSkipJsDocLeadingAsterisks(false);
        const node = factory2.createExpressionWithTypeArguments(expression, typeArguments);
        const res = finishNode(node, pos);
        if (usedBrace) {
          parseExpected(20 /* CloseBraceToken */);
        }
        return res;
      }
      function parsePropertyAccessEntityNameExpression() {
        const pos = getNodePos();
        let node = parseJSDocIdentifierName();
        while (parseOptional(25 /* DotToken */)) {
          const name = parseJSDocIdentifierName();
          node = finishNode(factoryCreatePropertyAccessExpression(node, name), pos);
        }
        return node;
      }
      function parseSimpleTag(start2, createTag, tagName, margin, indentText) {
        return finishNode(createTag(tagName, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2);
      }
      function parseThisTag(start2, tagName, margin, indentText) {
        const typeExpression = parseJSDocTypeExpression(
          /*mayOmitBraces*/
          true
        );
        skipWhitespace();
        return finishNode(factory2.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2);
      }
      function parseEnumTag(start2, tagName, margin, indentText) {
        const typeExpression = parseJSDocTypeExpression(
          /*mayOmitBraces*/
          true
        );
        skipWhitespace();
        return finishNode(factory2.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2);
      }
      function parseTypedefTag(start2, tagName, indent2, indentText) {
        let typeExpression = tryParseTypeExpression();
        skipWhitespaceOrAsterisk();
        const fullName = parseJSDocTypeNameWithNamespace();
        skipWhitespace();
        let comment = parseTagComments(indent2);
        let end2;
        if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
          let child;
          let childTypeTag;
          let jsDocPropertyTags;
          let hasChildren = false;
          while (child = tryParse(() => parseChildPropertyTag(indent2))) {
            if (child.kind === 345 /* JSDocTemplateTag */) {
              break;
            }
            hasChildren = true;
            if (child.kind === 344 /* JSDocTypeTag */) {
              if (childTypeTag) {
                const lastError = parseErrorAtCurrentToken(Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags);
                if (lastError) {
                  addRelatedInfo(lastError, createDetachedDiagnostic(fileName, sourceText, 0, 0, Diagnostics.The_tag_was_first_specified_here));
                }
                break;
              } else {
                childTypeTag = child;
              }
            } else {
              jsDocPropertyTags = append(jsDocPropertyTags, child);
            }
          }
          if (hasChildren) {
            const isArrayType = typeExpression && typeExpression.type.kind === 188 /* ArrayType */;
            const jsdocTypeLiteral = factory2.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType);
            typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral, start2);
            end2 = typeExpression.end;
          }
        }
        end2 = end2 || comment !== void 0 ? getNodePos() : (fullName ?? typeExpression ?? tagName).end;
        if (!comment) {
          comment = parseTrailingTagComments(start2, end2, indent2, indentText);
        }
        const typedefTag = factory2.createJSDocTypedefTag(tagName, typeExpression, fullName, comment);
        return finishNode(typedefTag, start2, end2);
      }
      function parseJSDocTypeNameWithNamespace(nested) {
        const start2 = scanner.getTokenStart();
        if (!tokenIsIdentifierOrKeyword(token())) {
          return void 0;
        }
        const typeNameOrNamespaceName = parseJSDocIdentifierName();
        if (parseOptional(25 /* DotToken */)) {
          const body = parseJSDocTypeNameWithNamespace(
            /*nested*/
            true
          );
          const jsDocNamespaceNode = factory2.createModuleDeclaration(
            /*modifiers*/
            void 0,
            typeNameOrNamespaceName,
            body,
            nested ? 8 /* NestedNamespace */ : void 0
          );
          return finishNode(jsDocNamespaceNode, start2);
        }
        if (nested) {
          typeNameOrNamespaceName.flags |= 4096 /* IdentifierIsInJSDocNamespace */;
        }
        return typeNameOrNamespaceName;
      }
      function parseCallbackTagParameters(indent2) {
        const pos = getNodePos();
        let child;
        let parameters;
        while (child = tryParse(() => parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent2))) {
          if (child.kind === 345 /* JSDocTemplateTag */) {
            parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag);
            break;
          }
          parameters = append(parameters, child);
        }
        return createNodeArray(parameters || [], pos);
      }
      function parseJSDocSignature(start2, indent2) {
        const parameters = parseCallbackTagParameters(indent2);
        const returnTag = tryParse(() => {
          if (parseOptionalJsdoc(60 /* AtToken */)) {
            const tag = parseTag(indent2);
            if (tag && tag.kind === 342 /* JSDocReturnTag */) {
              return tag;
            }
          }
        });
        return finishNode(factory2.createJSDocSignature(
          /*typeParameters*/
          void 0,
          parameters,
          returnTag
        ), start2);
      }
      function parseCallbackTag(start2, tagName, indent2, indentText) {
        const fullName = parseJSDocTypeNameWithNamespace();
        skipWhitespace();
        let comment = parseTagComments(indent2);
        const typeExpression = parseJSDocSignature(start2, indent2);
        if (!comment) {
          comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText);
        }
        const end2 = comment !== void 0 ? getNodePos() : typeExpression.end;
        return finishNode(factory2.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start2, end2);
      }
      function parseOverloadTag(start2, tagName, indent2, indentText) {
        skipWhitespace();
        let comment = parseTagComments(indent2);
        const typeExpression = parseJSDocSignature(start2, indent2);
        if (!comment) {
          comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText);
        }
        const end2 = comment !== void 0 ? getNodePos() : typeExpression.end;
        return finishNode(factory2.createJSDocOverloadTag(tagName, typeExpression, comment), start2, end2);
      }
      function escapedTextsEqual(a, b) {
        while (!isIdentifier(a) || !isIdentifier(b)) {
          if (!isIdentifier(a) && !isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
            a = a.left;
            b = b.left;
          } else {
            return false;
          }
        }
        return a.escapedText === b.escapedText;
      }
      function parseChildPropertyTag(indent2) {
        return parseChildParameterOrPropertyTag(1 /* Property */, indent2);
      }
      function parseChildParameterOrPropertyTag(target, indent2, name) {
        let canParseTag = true;
        let seenAsterisk = false;
        while (true) {
          switch (nextTokenJSDoc()) {
            case 60 /* AtToken */:
              if (canParseTag) {
                const child = tryParseChildTag(target, indent2);
                if (child && (child.kind === 341 /* JSDocParameterTag */ || child.kind === 348 /* JSDocPropertyTag */) && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
                  return false;
                }
                return child;
              }
              seenAsterisk = false;
              break;
            case 4 /* NewLineTrivia */:
              canParseTag = true;
              seenAsterisk = false;
              break;
            case 42 /* AsteriskToken */:
              if (seenAsterisk) {
                canParseTag = false;
              }
              seenAsterisk = true;
              break;
            case 80 /* Identifier */:
              canParseTag = false;
              break;
            case 1 /* EndOfFileToken */:
              return false;
          }
        }
      }
      function tryParseChildTag(target, indent2) {
        Debug.assert(token() === 60 /* AtToken */);
        const start2 = scanner.getTokenFullStart();
        nextTokenJSDoc();
        const tagName = parseJSDocIdentifierName();
        const indentText = skipWhitespaceOrAsterisk();
        let t;
        switch (tagName.escapedText) {
          case "type":
            return target === 1 /* Property */ && parseTypeTag(start2, tagName);
          case "prop":
          case "property":
            t = 1 /* Property */;
            break;
          case "arg":
          case "argument":
          case "param":
            t = 2 /* Parameter */ | 4 /* CallbackParameter */;
            break;
          case "template":
            return parseTemplateTag(start2, tagName, indent2, indentText);
          case "this":
            return parseThisTag(start2, tagName, indent2, indentText);
          default:
            return false;
        }
        if (!(target & t)) {
          return false;
        }
        return parseParameterOrPropertyTag(start2, tagName, target, indent2);
      }
      function parseTemplateTagTypeParameter() {
        const typeParameterPos = getNodePos();
        const isBracketed = parseOptionalJsdoc(23 /* OpenBracketToken */);
        if (isBracketed) {
          skipWhitespace();
        }
        const modifiers = parseModifiers(
          /*allowDecorators*/
          false,
          /*permitConstAsModifier*/
          true
        );
        const name = parseJSDocIdentifierName(Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
        let defaultType;
        if (isBracketed) {
          skipWhitespace();
          parseExpected(64 /* EqualsToken */);
          defaultType = doInsideOfContext(16777216 /* JSDoc */, parseJSDocType);
          parseExpected(24 /* CloseBracketToken */);
        }
        if (nodeIsMissing(name)) {
          return void 0;
        }
        return finishNode(factory2.createTypeParameterDeclaration(
          modifiers,
          name,
          /*constraint*/
          void 0,
          defaultType
        ), typeParameterPos);
      }
      function parseTemplateTagTypeParameters() {
        const pos = getNodePos();
        const typeParameters = [];
        do {
          skipWhitespace();
          const node = parseTemplateTagTypeParameter();
          if (node !== void 0) {
            typeParameters.push(node);
          }
          skipWhitespaceOrAsterisk();
        } while (parseOptionalJsdoc(28 /* CommaToken */));
        return createNodeArray(typeParameters, pos);
      }
      function parseTemplateTag(start2, tagName, indent2, indentText) {
        const constraint = token() === 19 /* OpenBraceToken */ ? parseJSDocTypeExpression() : void 0;
        const typeParameters = parseTemplateTagTypeParameters();
        return finishNode(factory2.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start2, getNodePos(), indent2, indentText)), start2);
      }
      function parseOptionalJsdoc(t) {
        if (token() === t) {
          nextTokenJSDoc();
          return true;
        }
        return false;
      }
      function parseJSDocEntityName() {
        let entity = parseJSDocIdentifierName();
        if (parseOptional(23 /* OpenBracketToken */)) {
          parseExpected(24 /* CloseBracketToken */);
        }
        while (parseOptional(25 /* DotToken */)) {
          const name = parseJSDocIdentifierName();
          if (parseOptional(23 /* OpenBracketToken */)) {
            parseExpected(24 /* CloseBracketToken */);
          }
          entity = createQualifiedName(entity, name);
        }
        return entity;
      }
      function parseJSDocIdentifierName(message) {
        if (!tokenIsIdentifierOrKeyword(token())) {
          return createMissingNode(
            80 /* Identifier */,
            /*reportAtCurrentPosition*/
            !message,
            message || Diagnostics.Identifier_expected
          );
        }
        identifierCount++;
        const start2 = scanner.getTokenStart();
        const end2 = scanner.getTokenEnd();
        const originalKeywordKind = token();
        const text = internIdentifier(scanner.getTokenValue());
        const result2 = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start2, end2);
        nextTokenJSDoc();
        return result2;
      }
    }
  })(JSDocParser = Parser2.JSDocParser || (Parser2.JSDocParser = {}));
})(Parser || (Parser = {}));
var incrementallyParsedFiles = /* @__PURE__ */ new WeakSet();
function markAsIncrementallyParsed(sourceFile) {
  if (incrementallyParsedFiles.has(sourceFile)) {
    Debug.fail("Source file has already been incrementally parsed");
  }
  incrementallyParsedFiles.add(sourceFile);
}
var intersectingChangeSet = /* @__PURE__ */ new WeakSet();
function intersectsIncrementalChange(node) {
  return intersectingChangeSet.has(node);
}
function markAsIntersectingIncrementalChange(node) {
  intersectingChangeSet.add(node);
}
var IncrementalParser;
((IncrementalParser2) => {
  function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
    aggressiveChecks = aggressiveChecks || Debug.shouldAssert(2 /* Aggressive */);
    checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
    if (textChangeRangeIsUnchanged(textChangeRange)) {
      return sourceFile;
    }
    if (sourceFile.statements.length === 0) {
      return Parser.parseSourceFile(
        sourceFile.fileName,
        newText,
        sourceFile.languageVersion,
        /*syntaxCursor*/
        void 0,
        /*setParentNodes*/
        true,
        sourceFile.scriptKind,
        sourceFile.setExternalModuleIndicator,
        sourceFile.jsDocParsingMode
      );
    }
    markAsIncrementallyParsed(sourceFile);
    Parser.fixupParentReferences(sourceFile);
    const oldText = sourceFile.text;
    const syntaxCursor = createSyntaxCursor(sourceFile);
    const changeRange = extendToAffectedRange(sourceFile, textChangeRange);
    checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
    Debug.assert(changeRange.span.start <= textChangeRange.span.start);
    Debug.assert(textSpanEnd(changeRange.span) === textSpanEnd(textChangeRange.span));
    Debug.assert(textSpanEnd(textChangeRangeNewSpan(changeRange)) === textSpanEnd(textChangeRangeNewSpan(textChangeRange)));
    const delta = textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
    updateTokenPositionsAndMarkElements(sourceFile, changeRange.span.start, textSpanEnd(changeRange.span), textSpanEnd(textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
    const result = Parser.parseSourceFile(
      sourceFile.fileName,
      newText,
      sourceFile.languageVersion,
      syntaxCursor,
      /*setParentNodes*/
      true,
      sourceFile.scriptKind,
      sourceFile.setExternalModuleIndicator,
      sourceFile.jsDocParsingMode
    );
    result.commentDirectives = getNewCommentDirectives(
      sourceFile.commentDirectives,
      result.commentDirectives,
      changeRange.span.start,
      textSpanEnd(changeRange.span),
      delta,
      oldText,
      newText,
      aggressiveChecks
    );
    result.impliedNodeFormat = sourceFile.impliedNodeFormat;
    transferSourceFileChildren(sourceFile, result);
    return result;
  }
  IncrementalParser2.updateSourceFile = updateSourceFile;
  function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
    if (!oldDirectives) return newDirectives;
    let commentDirectives;
    let addedNewlyScannedDirectives = false;
    for (const directive of oldDirectives) {
      const { range, type } = directive;
      if (range.end < changeStart) {
        commentDirectives = append(commentDirectives, directive);
      } else if (range.pos > changeRangeOldEnd) {
        addNewlyScannedDirectives();
        const updatedDirective = {
          range: { pos: range.pos + delta, end: range.end + delta },
          type
        };
        commentDirectives = append(commentDirectives, updatedDirective);
        if (aggressiveChecks) {
          Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
        }
      }
    }
    addNewlyScannedDirectives();
    return commentDirectives;
    function addNewlyScannedDirectives() {
      if (addedNewlyScannedDirectives) return;
      addedNewlyScannedDirectives = true;
      if (!commentDirectives) {
        commentDirectives = newDirectives;
      } else if (newDirectives) {
        commentDirectives.push(...newDirectives);
      }
    }
  }
  function moveElementEntirelyPastChangeRange(element, origSourceFile, isArray2, delta, oldText, newText, aggressiveChecks) {
    if (isArray2) {
      visitArray2(element);
    } else {
      visitNode3(element);
    }
    return;
    function visitNode3(node) {
      let text = "";
      if (aggressiveChecks && shouldCheckNode(node)) {
        text = oldText.substring(node.pos, node.end);
      }
      unsetNodeChildren(node, origSourceFile);
      setTextRangePosEnd(node, node.pos + delta, node.end + delta);
      if (aggressiveChecks && shouldCheckNode(node)) {
        Debug.assert(text === newText.substring(node.pos, node.end));
      }
      forEachChild(node, visitNode3, visitArray2);
      if (hasJSDocNodes(node)) {
        for (const jsDocComment of node.jsDoc) {
          visitNode3(jsDocComment);
        }
      }
      checkNodePositions(node, aggressiveChecks);
    }
    function visitArray2(array) {
      setTextRangePosEnd(array, array.pos + delta, array.end + delta);
      for (const node of array) {
        visitNode3(node);
      }
    }
  }
  function shouldCheckNode(node) {
    switch (node.kind) {
      case 11 /* StringLiteral */:
      case 9 /* NumericLiteral */:
      case 80 /* Identifier */:
        return true;
    }
    return false;
  }
  function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
    Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
    Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
    Debug.assert(element.pos <= element.end);
    const pos = Math.min(element.pos, changeRangeNewEnd);
    const end = element.end >= changeRangeOldEnd ? (
      // Element ends after the change range.  Always adjust the end pos.
      element.end + delta
    ) : (
      // Element ends in the change range.  The element will keep its position if
      // possible. Or Move backward to the new-end if it's in the 'Y' range.
      Math.min(element.end, changeRangeNewEnd)
    );
    Debug.assert(pos <= end);
    if (element.parent) {
      const parent = element.parent;
      Debug.assertGreaterThanOrEqual(pos, parent.pos);
      Debug.assertLessThanOrEqual(end, parent.end);
    }
    setTextRangePosEnd(element, pos, end);
  }
  function checkNodePositions(node, aggressiveChecks) {
    if (aggressiveChecks) {
      let pos = node.pos;
      const visitNode3 = (child) => {
        Debug.assert(child.pos >= pos);
        pos = child.end;
      };
      if (hasJSDocNodes(node)) {
        for (const jsDocComment of node.jsDoc) {
          visitNode3(jsDocComment);
        }
      }
      forEachChild(node, visitNode3);
      Debug.assert(pos <= node.end);
    }
  }
  function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
    visitNode3(sourceFile);
    return;
    function visitNode3(child) {
      Debug.assert(child.pos <= child.end);
      if (child.pos > changeRangeOldEnd) {
        moveElementEntirelyPastChangeRange(
          child,
          sourceFile,
          /*isArray*/
          false,
          delta,
          oldText,
          newText,
          aggressiveChecks
        );
        return;
      }
      const fullEnd = child.end;
      if (fullEnd >= changeStart) {
        markAsIntersectingIncrementalChange(child);
        unsetNodeChildren(child, sourceFile);
        adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
        forEachChild(child, visitNode3, visitArray2);
        if (hasJSDocNodes(child)) {
          for (const jsDocComment of child.jsDoc) {
            visitNode3(jsDocComment);
          }
        }
        checkNodePositions(child, aggressiveChecks);
        return;
      }
      Debug.assert(fullEnd < changeStart);
    }
    function visitArray2(array) {
      Debug.assert(array.pos <= array.end);
      if (array.pos > changeRangeOldEnd) {
        moveElementEntirelyPastChangeRange(
          array,
          sourceFile,
          /*isArray*/
          true,
          delta,
          oldText,
          newText,
          aggressiveChecks
        );
        return;
      }
      const fullEnd = array.end;
      if (fullEnd >= changeStart) {
        markAsIntersectingIncrementalChange(array);
        adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
        for (const node of array) {
          visitNode3(node);
        }
        return;
      }
      Debug.assert(fullEnd < changeStart);
    }
  }
  function extendToAffectedRange(sourceFile, changeRange) {
    const maxLookahead = 1;
    let start = changeRange.span.start;
    for (let i = 0; start > 0 && i <= maxLookahead; i++) {
      const nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
      Debug.assert(nearestNode.pos <= start);
      const position = nearestNode.pos;
      start = Math.max(0, position - 1);
    }
    const finalSpan = createTextSpanFromBounds(start, textSpanEnd(changeRange.span));
    const finalLength = changeRange.newLength + (changeRange.span.start - start);
    return createTextChangeRange(finalSpan, finalLength);
  }
  function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
    let bestResult = sourceFile;
    let lastNodeEntirelyBeforePosition;
    forEachChild(sourceFile, visit);
    if (lastNodeEntirelyBeforePosition) {
      const lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
      if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
        bestResult = lastChildOfLastEntireNodeBeforePosition;
      }
    }
    return bestResult;
    function getLastDescendant(node) {
      while (true) {
        const lastChild = getLastChild(node);
        if (lastChild) {
          node = lastChild;
        } else {
          return node;
        }
      }
    }
    function visit(child) {
      if (nodeIsMissing(child)) {
        return;
      }
      if (child.pos <= position) {
        if (child.pos >= bestResult.pos) {
          bestResult = child;
        }
        if (position < child.end) {
          forEachChild(child, visit);
          return true;
        } else {
          Debug.assert(child.end <= position);
          lastNodeEntirelyBeforePosition = child;
        }
      } else {
        Debug.assert(child.pos > position);
        return true;
      }
    }
  }
  function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
    const oldText = sourceFile.text;
    if (textChangeRange) {
      Debug.assert(oldText.length - textChangeRange.span.length + textChangeRange.newLength === newText.length);
      if (aggressiveChecks || Debug.shouldAssert(3 /* VeryAggressive */)) {
        const oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
        const newTextPrefix = newText.substr(0, textChangeRange.span.start);
        Debug.assert(oldTextPrefix === newTextPrefix);
        const oldTextSuffix = oldText.substring(textSpanEnd(textChangeRange.span), oldText.length);
        const newTextSuffix = newText.substring(textSpanEnd(textChangeRangeNewSpan(textChangeRange)), newText.length);
        Debug.assert(oldTextSuffix === newTextSuffix);
      }
    }
  }
  function createSyntaxCursor(sourceFile) {
    let currentArray = sourceFile.statements;
    let currentArrayIndex = 0;
    Debug.assert(currentArrayIndex < currentArray.length);
    let current = currentArray[currentArrayIndex];
    let lastQueriedPosition = -1 /* Value */;
    return {
      currentNode(position) {
        if (position !== lastQueriedPosition) {
          if (current && current.end === position && currentArrayIndex < currentArray.length - 1) {
            currentArrayIndex++;
            current = currentArray[currentArrayIndex];
          }
          if (!current || current.pos !== position) {
            findHighestListElementThatStartsAtPosition(position);
          }
        }
        lastQueriedPosition = position;
        Debug.assert(!current || current.pos === position);
        return current;
      }
    };
    function findHighestListElementThatStartsAtPosition(position) {
      currentArray = void 0;
      currentArrayIndex = -1 /* Value */;
      current = void 0;
      forEachChild(sourceFile, visitNode3, visitArray2);
      return;
      function visitNode3(node) {
        if (position >= node.pos && position < node.end) {
          forEachChild(node, visitNode3, visitArray2);
          return true;
        }
        return false;
      }
      function visitArray2(array) {
        if (position >= array.pos && position < array.end) {
          for (let i = 0; i < array.length; i++) {
            const child = array[i];
            if (child) {
              if (child.pos === position) {
                currentArray = array;
                currentArrayIndex = i;
                current = child;
                return true;
              } else {
                if (child.pos < position && position < child.end) {
                  forEachChild(child, visitNode3, visitArray2);
                  return true;
                }
              }
            }
          }
        }
        return false;
      }
    }
  }
  IncrementalParser2.createSyntaxCursor = createSyntaxCursor;
  let InvalidPosition;
  ((InvalidPosition2) => {
    InvalidPosition2[InvalidPosition2["Value"] = -1] = "Value";
  })(InvalidPosition || (InvalidPosition = {}));
})(IncrementalParser || (IncrementalParser = {}));
function isDeclarationFileName(fileName) {
  return getDeclarationFileExtension(fileName) !== void 0;
}
function getDeclarationFileExtension(fileName) {
  const standardExtension = getAnyExtensionFromPath(
    fileName,
    supportedDeclarationExtensions,
    /*ignoreCase*/
    false
  );
  if (standardExtension) {
    return standardExtension;
  }
  if (fileExtensionIs(fileName, ".ts" /* Ts */)) {
    const baseName = getBaseFileName(fileName);
    const index = baseName.lastIndexOf(".d.");
    if (index >= 0) {
      return baseName.substring(index);
    }
  }
  return void 0;
}
function parseResolutionMode(mode, pos, end, reportDiagnostic) {
  if (!mode) {
    return void 0;
  }
  if (mode === "import") {
    return 99 /* ESNext */;
  }
  if (mode === "require") {
    return 1 /* CommonJS */;
  }
  reportDiagnostic(pos, end - pos, Diagnostics.resolution_mode_should_be_either_require_or_import);
  return void 0;
}
function processCommentPragmas(context, sourceText) {
  const pragmas = [];
  for (const range of getLeadingCommentRanges(sourceText, 0) || emptyArray) {
    const comment = sourceText.substring(range.pos, range.end);
    extractPragmas(pragmas, range, comment);
  }
  context.pragmas = /* @__PURE__ */ new Map();
  for (const pragma of pragmas) {
    if (context.pragmas.has(pragma.name)) {
      const currentValue = context.pragmas.get(pragma.name);
      if (currentValue instanceof Array) {
        currentValue.push(pragma.args);
      } else {
        context.pragmas.set(pragma.name, [currentValue, pragma.args]);
      }
      continue;
    }
    context.pragmas.set(pragma.name, pragma.args);
  }
}
function processPragmasIntoFields(context, reportDiagnostic) {
  context.checkJsDirective = void 0;
  context.referencedFiles = [];
  context.typeReferenceDirectives = [];
  context.libReferenceDirectives = [];
  context.amdDependencies = [];
  context.hasNoDefaultLib = false;
  context.pragmas.forEach((entryOrList, key) => {
    switch (key) {
      case "reference": {
        const referencedFiles = context.referencedFiles;
        const typeReferenceDirectives = context.typeReferenceDirectives;
        const libReferenceDirectives = context.libReferenceDirectives;
        forEach(toArray(entryOrList), (arg) => {
          const { types, lib, path, ["resolution-mode"]: res, preserve: _preserve } = arg.arguments;
          const preserve = _preserve === "true" ? true : void 0;
          if (arg.arguments["no-default-lib"] === "true") {
            context.hasNoDefaultLib = true;
          } else if (types) {
            const parsed = parseResolutionMode(res, types.pos, types.end, reportDiagnostic);
            typeReferenceDirectives.push({ pos: types.pos, end: types.end, fileName: types.value, ...parsed ? { resolutionMode: parsed } : {}, ...preserve ? { preserve } : {} });
          } else if (lib) {
            libReferenceDirectives.push({ pos: lib.pos, end: lib.end, fileName: lib.value, ...preserve ? { preserve } : {} });
          } else if (path) {
            referencedFiles.push({ pos: path.pos, end: path.end, fileName: path.value, ...preserve ? { preserve } : {} });
          } else {
            reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, Diagnostics.Invalid_reference_directive_syntax);
          }
        });
        break;
      }
      case "amd-dependency": {
        context.amdDependencies = map(
          toArray(entryOrList),
          (x) => ({ name: x.arguments.name, path: x.arguments.path })
        );
        break;
      }
      case "amd-module": {
        if (entryOrList instanceof Array) {
          for (const entry of entryOrList) {
            if (context.moduleName) {
              reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
            }
            context.moduleName = entry.arguments.name;
          }
        } else {
          context.moduleName = entryOrList.arguments.name;
        }
        break;
      }
      case "ts-nocheck":
      case "ts-check": {
        forEach(toArray(entryOrList), (entry) => {
          if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
            context.checkJsDirective = {
              enabled: key === "ts-check",
              end: entry.range.end,
              pos: entry.range.pos
            };
          }
        });
        break;
      }
      case "jsx":
      case "jsxfrag":
      case "jsximportsource":
      case "jsxruntime":
        return;
      // Accessed directly
      default:
        Debug.fail("Unhandled pragma kind");
    }
  });
}
var namedArgRegExCache = /* @__PURE__ */ new Map();
function getNamedArgRegEx(name) {
  if (namedArgRegExCache.has(name)) {
    return namedArgRegExCache.get(name);
  }
  const result = new RegExp(`(\\s${name}\\s*=\\s*)(?:(?:'([^']*)')|(?:"([^"]*)"))`, "im");
  namedArgRegExCache.set(name, result);
  return result;
}
var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/m;
var singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)((?:[^\S\r\n]|:).*)?$/m;
function extractPragmas(pragmas, range, text) {
  const tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
  if (tripleSlash) {
    const name = tripleSlash[1].toLowerCase();
    const pragma = commentPragmas[name];
    if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
      return;
    }
    if (pragma.args) {
      const argument = {};
      for (const arg of pragma.args) {
        const matcher = getNamedArgRegEx(arg.name);
        const matchResult = matcher.exec(text);
        if (!matchResult && !arg.optional) {
          return;
        } else if (matchResult) {
          const value = matchResult[2] || matchResult[3];
          if (arg.captureSpan) {
            const startPos = range.pos + matchResult.index + matchResult[1].length + 1;
            argument[arg.name] = {
              value,
              pos: startPos,
              end: startPos + value.length
            };
          } else {
            argument[arg.name] = value;
          }
        }
      }
      pragmas.push({ name, args: { arguments: argument, range } });
    } else {
      pragmas.push({ name, args: { arguments: {}, range } });
    }
    return;
  }
  const singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
  if (singleLine) {
    return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
  }
  if (range.kind === 3 /* MultiLineCommentTrivia */) {
    const multiLinePragmaRegEx = /@(\S+)(\s+(?:\S.*)?)?$/gm;
    let multiLineMatch;
    while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
      addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
    }
  }
}
function addPragmaForMatch(pragmas, range, kind, match) {
  if (!match) return;
  const name = match[1].toLowerCase();
  const pragma = commentPragmas[name];
  if (!pragma || !(pragma.kind & kind)) {
    return;
  }
  const args = match[2];
  const argument = getNamedPragmaArguments(pragma, args);
  if (argument === "fail") return;
  pragmas.push({ name, args: { arguments: argument, range } });
  return;
}
function getNamedPragmaArguments(pragma, text) {
  if (!text) return {};
  if (!pragma.args) return {};
  const args = text.trim().split(/\s+/);
  const argMap = {};
  for (let i = 0; i < pragma.args.length; i++) {
    const argument = pragma.args[i];
    if (!args[i] && !argument.optional) {
      return "fail";
    }
    if (argument.captureSpan) {
      return Debug.fail("Capture spans not yet implemented for non-xml pragmas");
    }
    argMap[argument.name] = args[i];
  }
  return argMap;
}
function tagNamesAreEquivalent(lhs, rhs) {
  if (lhs.kind !== rhs.kind) {
    return false;
  }
  if (lhs.kind === 80 /* Identifier */) {
    return lhs.escapedText === rhs.escapedText;
  }
  if (lhs.kind === 110 /* ThisKeyword */) {
    return true;
  }
  if (lhs.kind === 295 /* JsxNamespacedName */) {
    return lhs.namespace.escapedText === rhs.namespace.escapedText && lhs.name.escapedText === rhs.name.escapedText;
  }
  return lhs.name.escapedText === rhs.name.escapedText && tagNamesAreEquivalent(lhs.expression, rhs.expression);
}

// src/compiler/commandLineParser.ts
var compileOnSaveCommandLineOption = {
  name: "compileOnSave",
  type: "boolean",
  defaultValueDescription: false
};
var jsxOptionMap = new Map(Object.entries({
  "preserve": 1 /* Preserve */,
  "react-native": 3 /* ReactNative */,
  "react": 2 /* React */,
  "react-jsx": 4 /* ReactJSX */,
  "react-jsxdev": 5 /* ReactJSXDev */
}));
var inverseJsxOptionMap = new Map(mapIterator(jsxOptionMap.entries(), ([key, value]) => ["" + value, key]));
var libEntries = [
  // JavaScript only
  ["es5", "lib.es5.d.ts"],
  ["es6", "lib.es2015.d.ts"],
  ["es2015", "lib.es2015.d.ts"],
  ["es7", "lib.es2016.d.ts"],
  ["es2016", "lib.es2016.d.ts"],
  ["es2017", "lib.es2017.d.ts"],
  ["es2018", "lib.es2018.d.ts"],
  ["es2019", "lib.es2019.d.ts"],
  ["es2020", "lib.es2020.d.ts"],
  ["es2021", "lib.es2021.d.ts"],
  ["es2022", "lib.es2022.d.ts"],
  ["es2023", "lib.es2023.d.ts"],
  ["es2024", "lib.es2024.d.ts"],
  ["esnext", "lib.esnext.d.ts"],
  // Host only
  ["dom", "lib.dom.d.ts"],
  ["dom.iterable", "lib.dom.iterable.d.ts"],
  ["dom.asynciterable", "lib.dom.asynciterable.d.ts"],
  ["webworker", "lib.webworker.d.ts"],
  ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
  ["webworker.iterable", "lib.webworker.iterable.d.ts"],
  ["webworker.asynciterable", "lib.webworker.asynciterable.d.ts"],
  ["scripthost", "lib.scripthost.d.ts"],
  // ES2015 Or ESNext By-feature options
  ["es2015.core", "lib.es2015.core.d.ts"],
  ["es2015.collection", "lib.es2015.collection.d.ts"],
  ["es2015.generator", "lib.es2015.generator.d.ts"],
  ["es2015.iterable", "lib.es2015.iterable.d.ts"],
  ["es2015.promise", "lib.es2015.promise.d.ts"],
  ["es2015.proxy", "lib.es2015.proxy.d.ts"],
  ["es2015.reflect", "lib.es2015.reflect.d.ts"],
  ["es2015.symbol", "lib.es2015.symbol.d.ts"],
  ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
  ["es2016.array.include", "lib.es2016.array.include.d.ts"],
  ["es2016.intl", "lib.es2016.intl.d.ts"],
  ["es2017.arraybuffer", "lib.es2017.arraybuffer.d.ts"],
  ["es2017.date", "lib.es2017.date.d.ts"],
  ["es2017.object", "lib.es2017.object.d.ts"],
  ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
  ["es2017.string", "lib.es2017.string.d.ts"],
  ["es2017.intl", "lib.es2017.intl.d.ts"],
  ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
  ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
  ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
  ["es2018.intl", "lib.es2018.intl.d.ts"],
  ["es2018.promise", "lib.es2018.promise.d.ts"],
  ["es2018.regexp", "lib.es2018.regexp.d.ts"],
  ["es2019.array", "lib.es2019.array.d.ts"],
  ["es2019.object", "lib.es2019.object.d.ts"],
  ["es2019.string", "lib.es2019.string.d.ts"],
  ["es2019.symbol", "lib.es2019.symbol.d.ts"],
  ["es2019.intl", "lib.es2019.intl.d.ts"],
  ["es2020.bigint", "lib.es2020.bigint.d.ts"],
  ["es2020.date", "lib.es2020.date.d.ts"],
  ["es2020.promise", "lib.es2020.promise.d.ts"],
  ["es2020.sharedmemory", "lib.es2020.sharedmemory.d.ts"],
  ["es2020.string", "lib.es2020.string.d.ts"],
  ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
  ["es2020.intl", "lib.es2020.intl.d.ts"],
  ["es2020.number", "lib.es2020.number.d.ts"],
  ["es2021.promise", "lib.es2021.promise.d.ts"],
  ["es2021.string", "lib.es2021.string.d.ts"],
  ["es2021.weakref", "lib.es2021.weakref.d.ts"],
  ["es2021.intl", "lib.es2021.intl.d.ts"],
  ["es2022.array", "lib.es2022.array.d.ts"],
  ["es2022.error", "lib.es2022.error.d.ts"],
  ["es2022.intl", "lib.es2022.intl.d.ts"],
  ["es2022.object", "lib.es2022.object.d.ts"],
  ["es2022.string", "lib.es2022.string.d.ts"],
  ["es2022.regexp", "lib.es2022.regexp.d.ts"],
  ["es2023.array", "lib.es2023.array.d.ts"],
  ["es2023.collection", "lib.es2023.collection.d.ts"],
  ["es2023.intl", "lib.es2023.intl.d.ts"],
  ["es2024.arraybuffer", "lib.es2024.arraybuffer.d.ts"],
  ["es2024.collection", "lib.es2024.collection.d.ts"],
  ["es2024.object", "lib.es2024.object.d.ts"],
  ["es2024.promise", "lib.es2024.promise.d.ts"],
  ["es2024.regexp", "lib.es2024.regexp.d.ts"],
  ["es2024.sharedmemory", "lib.es2024.sharedmemory.d.ts"],
  ["es2024.string", "lib.es2024.string.d.ts"],
  ["esnext.array", "lib.es2023.array.d.ts"],
  ["esnext.collection", "lib.esnext.collection.d.ts"],
  ["esnext.symbol", "lib.es2019.symbol.d.ts"],
  ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
  ["esnext.intl", "lib.esnext.intl.d.ts"],
  ["esnext.disposable", "lib.esnext.disposable.d.ts"],
  ["esnext.bigint", "lib.es2020.bigint.d.ts"],
  ["esnext.string", "lib.es2022.string.d.ts"],
  ["esnext.promise", "lib.es2024.promise.d.ts"],
  ["esnext.weakref", "lib.es2021.weakref.d.ts"],
  ["esnext.decorators", "lib.esnext.decorators.d.ts"],
  ["esnext.object", "lib.es2024.object.d.ts"],
  ["esnext.array", "lib.esnext.array.d.ts"],
  ["esnext.regexp", "lib.es2024.regexp.d.ts"],
  ["esnext.string", "lib.es2024.string.d.ts"],
  ["esnext.iterator", "lib.esnext.iterator.d.ts"],
  ["decorators", "lib.decorators.d.ts"],
  ["decorators.legacy", "lib.decorators.legacy.d.ts"]
];
var libs = libEntries.map((entry) => entry[0]);
var libMap = new Map(libEntries);
var optionsForWatch = [
  {
    name: "watchFile",
    type: new Map(Object.entries({
      fixedpollinginterval: 0 /* FixedPollingInterval */,
      prioritypollinginterval: 1 /* PriorityPollingInterval */,
      dynamicprioritypolling: 2 /* DynamicPriorityPolling */,
      fixedchunksizepolling: 3 /* FixedChunkSizePolling */,
      usefsevents: 4 /* UseFsEvents */,
      usefseventsonparentdirectory: 5 /* UseFsEventsOnParentDirectory */
    })),
    category: Diagnostics.Watch_and_Build_Modes,
    description: Diagnostics.Specify_how_the_TypeScript_watch_mode_works,
    defaultValueDescription: 4 /* UseFsEvents */
  },
  {
    name: "watchDirectory",
    type: new Map(Object.entries({
      usefsevents: 0 /* UseFsEvents */,
      fixedpollinginterval: 1 /* FixedPollingInterval */,
      dynamicprioritypolling: 2 /* DynamicPriorityPolling */,
      fixedchunksizepolling: 3 /* FixedChunkSizePolling */
    })),
    category: Diagnostics.Watch_and_Build_Modes,
    description: Diagnostics.Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality,
    defaultValueDescription: 0 /* UseFsEvents */
  },
  {
    name: "fallbackPolling",
    type: new Map(Object.entries({
      fixedinterval: 0 /* FixedInterval */,
      priorityinterval: 1 /* PriorityInterval */,
      dynamicpriority: 2 /* DynamicPriority */,
      fixedchunksize: 3 /* FixedChunkSize */
    })),
    category: Diagnostics.Watch_and_Build_Modes,
    description: Diagnostics.Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers,
    defaultValueDescription: 1 /* PriorityInterval */
  },
  {
    name: "synchronousWatchDirectory",
    type: "boolean",
    category: Diagnostics.Watch_and_Build_Modes,
    description: Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
    defaultValueDescription: false
  },
  {
    name: "excludeDirectories",
    type: "list",
    element: {
      name: "excludeDirectory",
      type: "string",
      isFilePath: true,
      extraValidation: specToDiagnostic
    },
    allowConfigDirTemplateSubstitution: true,
    category: Diagnostics.Watch_and_Build_Modes,
    description: Diagnostics.Remove_a_list_of_directories_from_the_watch_process
  },
  {
    name: "excludeFiles",
    type: "list",
    element: {
      name: "excludeFile",
      type: "string",
      isFilePath: true,
      extraValidation: specToDiagnostic
    },
    allowConfigDirTemplateSubstitution: true,
    category: Diagnostics.Watch_and_Build_Modes,
    description: Diagnostics.Remove_a_list_of_files_from_the_watch_mode_s_processing
  }
];
var commonOptionsWithBuild = [
  {
    name: "help",
    shortName: "h",
    type: "boolean",
    showInSimplifiedHelpView: true,
    isCommandLineOnly: true,
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Print_this_message,
    defaultValueDescription: false
  },
  {
    name: "help",
    shortName: "?",
    type: "boolean",
    isCommandLineOnly: true,
    category: Diagnostics.Command_line_Options,
    defaultValueDescription: false
  },
  {
    name: "watch",
    shortName: "w",
    type: "boolean",
    showInSimplifiedHelpView: true,
    isCommandLineOnly: true,
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Watch_input_files,
    defaultValueDescription: false
  },
  {
    name: "preserveWatchOutput",
    type: "boolean",
    showInSimplifiedHelpView: false,
    category: Diagnostics.Output_Formatting,
    description: Diagnostics.Disable_wiping_the_console_in_watch_mode,
    defaultValueDescription: false
  },
  {
    name: "listFiles",
    type: "boolean",
    category: Diagnostics.Compiler_Diagnostics,
    description: Diagnostics.Print_all_of_the_files_read_during_the_compilation,
    defaultValueDescription: false
  },
  {
    name: "explainFiles",
    type: "boolean",
    category: Diagnostics.Compiler_Diagnostics,
    description: Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included,
    defaultValueDescription: false
  },
  {
    name: "listEmittedFiles",
    type: "boolean",
    category: Diagnostics.Compiler_Diagnostics,
    description: Diagnostics.Print_the_names_of_emitted_files_after_a_compilation,
    defaultValueDescription: false
  },
  {
    name: "pretty",
    type: "boolean",
    showInSimplifiedHelpView: true,
    category: Diagnostics.Output_Formatting,
    description: Diagnostics.Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read,
    defaultValueDescription: true
  },
  {
    name: "traceResolution",
    type: "boolean",
    category: Diagnostics.Compiler_Diagnostics,
    description: Diagnostics.Log_paths_used_during_the_moduleResolution_process,
    defaultValueDescription: false
  },
  {
    name: "diagnostics",
    type: "boolean",
    category: Diagnostics.Compiler_Diagnostics,
    description: Diagnostics.Output_compiler_performance_information_after_building,
    defaultValueDescription: false
  },
  {
    name: "extendedDiagnostics",
    type: "boolean",
    category: Diagnostics.Compiler_Diagnostics,
    description: Diagnostics.Output_more_detailed_compiler_performance_information_after_building,
    defaultValueDescription: false
  },
  {
    name: "generateCpuProfile",
    type: "string",
    isFilePath: true,
    paramType: Diagnostics.FILE_OR_DIRECTORY,
    category: Diagnostics.Compiler_Diagnostics,
    description: Diagnostics.Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging,
    defaultValueDescription: "profile.cpuprofile"
  },
  {
    name: "generateTrace",
    type: "string",
    isFilePath: true,
    paramType: Diagnostics.DIRECTORY,
    category: Diagnostics.Compiler_Diagnostics,
    description: Diagnostics.Generates_an_event_trace_and_a_list_of_types
  },
  {
    name: "incremental",
    shortName: "i",
    type: "boolean",
    category: Diagnostics.Projects,
    description: Diagnostics.Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects,
    transpileOptionValue: void 0,
    defaultValueDescription: Diagnostics.false_unless_composite_is_set
  },
  {
    name: "declaration",
    shortName: "d",
    type: "boolean",
    // Not setting affectsEmit because we calculate this flag might not affect full emit
    affectsBuildInfo: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Emit,
    transpileOptionValue: void 0,
    description: Diagnostics.Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project,
    defaultValueDescription: Diagnostics.false_unless_composite_is_set
  },
  {
    name: "declarationMap",
    type: "boolean",
    // Not setting affectsEmit because we calculate this flag might not affect full emit
    affectsBuildInfo: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Emit,
    defaultValueDescription: false,
    description: Diagnostics.Create_sourcemaps_for_d_ts_files
  },
  {
    name: "emitDeclarationOnly",
    type: "boolean",
    // Not setting affectsEmit because we calculate this flag might not affect full emit
    affectsBuildInfo: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files,
    transpileOptionValue: void 0,
    defaultValueDescription: false
  },
  {
    name: "sourceMap",
    type: "boolean",
    // Not setting affectsEmit because we calculate this flag might not affect full emit
    affectsBuildInfo: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Emit,
    defaultValueDescription: false,
    description: Diagnostics.Create_source_map_files_for_emitted_JavaScript_files
  },
  {
    name: "inlineSourceMap",
    type: "boolean",
    // Not setting affectsEmit because we calculate this flag might not affect full emit
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript,
    defaultValueDescription: false
  },
  {
    name: "noCheck",
    type: "boolean",
    showInSimplifiedHelpView: false,
    category: Diagnostics.Compiler_Diagnostics,
    description: Diagnostics.Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported,
    transpileOptionValue: true,
    defaultValueDescription: false
    // Not setting affectsSemanticDiagnostics or affectsBuildInfo because we dont want all diagnostics to go away, its handled in builder
  },
  {
    name: "noEmit",
    type: "boolean",
    showInSimplifiedHelpView: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Disable_emitting_files_from_a_compilation,
    transpileOptionValue: void 0,
    defaultValueDescription: false
  },
  {
    name: "assumeChangesOnlyAffectDirectDependencies",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Watch_and_Build_Modes,
    description: Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it,
    defaultValueDescription: false
  },
  {
    name: "locale",
    type: "string",
    category: Diagnostics.Command_line_Options,
    isCommandLineOnly: true,
    description: Diagnostics.Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit,
    defaultValueDescription: Diagnostics.Platform_specific
  }
];
var targetOptionDeclaration = {
  name: "target",
  shortName: "t",
  type: new Map(Object.entries({
    es3: 0 /* ES3 */,
    es5: 1 /* ES5 */,
    es6: 2 /* ES2015 */,
    es2015: 2 /* ES2015 */,
    es2016: 3 /* ES2016 */,
    es2017: 4 /* ES2017 */,
    es2018: 5 /* ES2018 */,
    es2019: 6 /* ES2019 */,
    es2020: 7 /* ES2020 */,
    es2021: 8 /* ES2021 */,
    es2022: 9 /* ES2022 */,
    es2023: 10 /* ES2023 */,
    es2024: 11 /* ES2024 */,
    esnext: 99 /* ESNext */
  })),
  affectsSourceFile: true,
  affectsModuleResolution: true,
  affectsEmit: true,
  affectsBuildInfo: true,
  deprecatedKeys: /* @__PURE__ */ new Set(["es3"]),
  paramType: Diagnostics.VERSION,
  showInSimplifiedHelpView: true,
  category: Diagnostics.Language_and_Environment,
  description: Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations,
  defaultValueDescription: 1 /* ES5 */
};
var moduleOptionDeclaration = {
  name: "module",
  shortName: "m",
  type: new Map(Object.entries({
    none: 0 /* None */,
    commonjs: 1 /* CommonJS */,
    amd: 2 /* AMD */,
    system: 4 /* System */,
    umd: 3 /* UMD */,
    es6: 5 /* ES2015 */,
    es2015: 5 /* ES2015 */,
    es2020: 6 /* ES2020 */,
    es2022: 7 /* ES2022 */,
    esnext: 99 /* ESNext */,
    node16: 100 /* Node16 */,
    nodenext: 199 /* NodeNext */,
    preserve: 200 /* Preserve */
  })),
  affectsSourceFile: true,
  affectsModuleResolution: true,
  affectsEmit: true,
  affectsBuildInfo: true,
  paramType: Diagnostics.KIND,
  showInSimplifiedHelpView: true,
  category: Diagnostics.Modules,
  description: Diagnostics.Specify_what_module_code_is_generated,
  defaultValueDescription: void 0
};
var commandOptionsWithoutBuild = [
  // CommandLine only options
  {
    name: "all",
    type: "boolean",
    showInSimplifiedHelpView: true,
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Show_all_compiler_options,
    defaultValueDescription: false
  },
  {
    name: "version",
    shortName: "v",
    type: "boolean",
    showInSimplifiedHelpView: true,
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Print_the_compiler_s_version,
    defaultValueDescription: false
  },
  {
    name: "init",
    type: "boolean",
    showInSimplifiedHelpView: true,
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
    defaultValueDescription: false
  },
  {
    name: "project",
    shortName: "p",
    type: "string",
    isFilePath: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Command_line_Options,
    paramType: Diagnostics.FILE_OR_DIRECTORY,
    description: Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json
  },
  {
    name: "showConfig",
    type: "boolean",
    showInSimplifiedHelpView: true,
    category: Diagnostics.Command_line_Options,
    isCommandLineOnly: true,
    description: Diagnostics.Print_the_final_configuration_instead_of_building,
    defaultValueDescription: false
  },
  {
    name: "listFilesOnly",
    type: "boolean",
    category: Diagnostics.Command_line_Options,
    isCommandLineOnly: true,
    description: Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing,
    defaultValueDescription: false
  },
  // Basic
  targetOptionDeclaration,
  moduleOptionDeclaration,
  {
    name: "lib",
    type: "list",
    element: {
      name: "lib",
      type: libMap,
      defaultValueDescription: void 0
    },
    affectsProgramStructure: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment,
    transpileOptionValue: void 0
  },
  {
    name: "allowJs",
    type: "boolean",
    allowJsFlag: true,
    affectsBuildInfo: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.JavaScript_Support,
    description: Diagnostics.Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files,
    defaultValueDescription: false
  },
  {
    name: "checkJs",
    type: "boolean",
    affectsModuleResolution: true,
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.JavaScript_Support,
    description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files,
    defaultValueDescription: false
  },
  {
    name: "jsx",
    type: jsxOptionMap,
    affectsSourceFile: true,
    affectsEmit: true,
    affectsBuildInfo: true,
    affectsModuleResolution: true,
    // The checker emits an error when it sees JSX but this option is not set in compilerOptions.
    // This is effectively a semantic error, so mark this option as affecting semantic diagnostics
    // so we know to refresh errors when this option is changed.
    affectsSemanticDiagnostics: true,
    paramType: Diagnostics.KIND,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Specify_what_JSX_code_is_generated,
    defaultValueDescription: void 0
  },
  {
    name: "outFile",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    affectsDeclarationPath: true,
    isFilePath: true,
    paramType: Diagnostics.FILE,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output,
    transpileOptionValue: void 0
  },
  {
    name: "outDir",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    affectsDeclarationPath: true,
    isFilePath: true,
    paramType: Diagnostics.DIRECTORY,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Specify_an_output_folder_for_all_emitted_files
  },
  {
    name: "rootDir",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    affectsDeclarationPath: true,
    isFilePath: true,
    paramType: Diagnostics.LOCATION,
    category: Diagnostics.Modules,
    description: Diagnostics.Specify_the_root_folder_within_your_source_files,
    defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files
  },
  {
    name: "composite",
    type: "boolean",
    // Not setting affectsEmit because we calculate this flag might not affect full emit
    affectsBuildInfo: true,
    isTSConfigOnly: true,
    category: Diagnostics.Projects,
    transpileOptionValue: void 0,
    defaultValueDescription: false,
    description: Diagnostics.Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references
  },
  {
    name: "tsBuildInfoFile",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    isFilePath: true,
    paramType: Diagnostics.FILE,
    category: Diagnostics.Projects,
    transpileOptionValue: void 0,
    defaultValueDescription: ".tsbuildinfo",
    description: Diagnostics.Specify_the_path_to_tsbuildinfo_incremental_compilation_file
  },
  {
    name: "removeComments",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Emit,
    defaultValueDescription: false,
    description: Diagnostics.Disable_emitting_comments
  },
  {
    name: "importHelpers",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    affectsSourceFile: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file,
    defaultValueDescription: false
  },
  {
    name: "importsNotUsedAsValues",
    type: new Map(Object.entries({
      remove: 0 /* Remove */,
      preserve: 1 /* Preserve */,
      error: 2 /* Error */
    })),
    affectsEmit: true,
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types,
    defaultValueDescription: 0 /* Remove */
  },
  {
    name: "downlevelIteration",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration,
    defaultValueDescription: false
  },
  {
    name: "isolatedModules",
    type: "boolean",
    category: Diagnostics.Interop_Constraints,
    description: Diagnostics.Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports,
    transpileOptionValue: true,
    defaultValueDescription: false
  },
  {
    name: "verbatimModuleSyntax",
    type: "boolean",
    affectsEmit: true,
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Interop_Constraints,
    description: Diagnostics.Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_in_the_output_file_s_format_based_on_the_module_setting,
    defaultValueDescription: false
  },
  {
    name: "isolatedDeclarations",
    type: "boolean",
    category: Diagnostics.Interop_Constraints,
    description: Diagnostics.Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files,
    defaultValueDescription: false,
    affectsBuildInfo: true,
    affectsSemanticDiagnostics: true
  },
  // Strict Type Checks
  {
    name: "strict",
    type: "boolean",
    // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here
    // The value of each strictFlag depends on own strictFlag value or this and never accessed directly.
    // But we need to store `strict` in builf info, even though it won't be examined directly, so that the
    // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly
    affectsBuildInfo: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Enable_all_strict_type_checking_options,
    defaultValueDescription: false
  },
  {
    name: "noImplicitAny",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    strictFlag: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type,
    defaultValueDescription: Diagnostics.false_unless_strict_is_set
  },
  {
    name: "strictNullChecks",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    strictFlag: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.When_type_checking_take_into_account_null_and_undefined,
    defaultValueDescription: Diagnostics.false_unless_strict_is_set
  },
  {
    name: "strictFunctionTypes",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    strictFlag: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible,
    defaultValueDescription: Diagnostics.false_unless_strict_is_set
  },
  {
    name: "strictBindCallApply",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    strictFlag: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function,
    defaultValueDescription: Diagnostics.false_unless_strict_is_set
  },
  {
    name: "strictPropertyInitialization",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    strictFlag: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor,
    defaultValueDescription: Diagnostics.false_unless_strict_is_set
  },
  {
    name: "strictBuiltinIteratorReturn",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    strictFlag: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any,
    defaultValueDescription: Diagnostics.false_unless_strict_is_set
  },
  {
    name: "noImplicitThis",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    strictFlag: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any,
    defaultValueDescription: Diagnostics.false_unless_strict_is_set
  },
  {
    name: "useUnknownInCatchVariables",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    strictFlag: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any,
    defaultValueDescription: Diagnostics.false_unless_strict_is_set
  },
  {
    name: "alwaysStrict",
    type: "boolean",
    affectsSourceFile: true,
    affectsEmit: true,
    affectsBuildInfo: true,
    strictFlag: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Ensure_use_strict_is_always_emitted,
    defaultValueDescription: Diagnostics.false_unless_strict_is_set
  },
  // Additional Checks
  {
    name: "noUnusedLocals",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read,
    defaultValueDescription: false
  },
  {
    name: "noUnusedParameters",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read,
    defaultValueDescription: false
  },
  {
    name: "exactOptionalPropertyTypes",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined,
    defaultValueDescription: false
  },
  {
    name: "noImplicitReturns",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function,
    defaultValueDescription: false
  },
  {
    name: "noFallthroughCasesInSwitch",
    type: "boolean",
    affectsBindDiagnostics: true,
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements,
    defaultValueDescription: false
  },
  {
    name: "noUncheckedIndexedAccess",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index,
    defaultValueDescription: false
  },
  {
    name: "noImplicitOverride",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier,
    defaultValueDescription: false
  },
  {
    name: "noPropertyAccessFromIndexSignature",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    showInSimplifiedHelpView: false,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type,
    defaultValueDescription: false
  },
  // Module Resolution
  {
    name: "moduleResolution",
    type: new Map(Object.entries({
      // N.B. The first entry specifies the value shown in `tsc --init`
      node10: 2 /* Node10 */,
      node: 2 /* Node10 */,
      classic: 1 /* Classic */,
      node16: 3 /* Node16 */,
      nodenext: 99 /* NodeNext */,
      bundler: 100 /* Bundler */
    })),
    deprecatedKeys: /* @__PURE__ */ new Set(["node"]),
    affectsSourceFile: true,
    affectsModuleResolution: true,
    paramType: Diagnostics.STRATEGY,
    category: Diagnostics.Modules,
    description: Diagnostics.Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier,
    defaultValueDescription: Diagnostics.module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node
  },
  {
    name: "baseUrl",
    type: "string",
    affectsModuleResolution: true,
    isFilePath: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Specify_the_base_directory_to_resolve_non_relative_module_names
  },
  {
    // this option can only be specified in tsconfig.json
    // use type = object to copy the value as-is
    name: "paths",
    type: "object",
    affectsModuleResolution: true,
    allowConfigDirTemplateSubstitution: true,
    isTSConfigOnly: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations,
    transpileOptionValue: void 0
  },
  {
    // this option can only be specified in tsconfig.json
    // use type = object to copy the value as-is
    name: "rootDirs",
    type: "list",
    isTSConfigOnly: true,
    element: {
      name: "rootDirs",
      type: "string",
      isFilePath: true
    },
    affectsModuleResolution: true,
    allowConfigDirTemplateSubstitution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules,
    transpileOptionValue: void 0,
    defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files
  },
  {
    name: "typeRoots",
    type: "list",
    element: {
      name: "typeRoots",
      type: "string",
      isFilePath: true
    },
    affectsModuleResolution: true,
    allowConfigDirTemplateSubstitution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types
  },
  {
    name: "types",
    type: "list",
    element: {
      name: "types",
      type: "string"
    },
    affectsProgramStructure: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file,
    transpileOptionValue: void 0
  },
  {
    name: "allowSyntheticDefaultImports",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Interop_Constraints,
    description: Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export,
    defaultValueDescription: Diagnostics.module_system_or_esModuleInterop
  },
  {
    name: "esModuleInterop",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsEmit: true,
    affectsBuildInfo: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Interop_Constraints,
    description: Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility,
    defaultValueDescription: false
  },
  {
    name: "preserveSymlinks",
    type: "boolean",
    category: Diagnostics.Interop_Constraints,
    description: Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node,
    defaultValueDescription: false
  },
  {
    name: "allowUmdGlobalAccess",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Allow_accessing_UMD_globals_from_modules,
    defaultValueDescription: false
  },
  {
    name: "moduleSuffixes",
    type: "list",
    element: {
      name: "suffix",
      type: "string"
    },
    listPreserveFalsyValues: true,
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.List_of_file_name_suffixes_to_search_when_resolving_a_module
  },
  {
    name: "allowImportingTsExtensions",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noEmit_or_emitDeclarationOnly_to_be_set,
    defaultValueDescription: false,
    transpileOptionValue: void 0
  },
  {
    name: "rewriteRelativeImportExtensions",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_in_output_files,
    defaultValueDescription: false
  },
  {
    name: "resolvePackageJsonExports",
    type: "boolean",
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Use_the_package_json_exports_field_when_resolving_package_imports,
    defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false
  },
  {
    name: "resolvePackageJsonImports",
    type: "boolean",
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Use_the_package_json_imports_field_when_resolving_imports,
    defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false
  },
  {
    name: "customConditions",
    type: "list",
    element: {
      name: "condition",
      type: "string"
    },
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports
  },
  {
    name: "noUncheckedSideEffectImports",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Check_side_effect_imports,
    defaultValueDescription: false
  },
  // Source Maps
  {
    name: "sourceRoot",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    paramType: Diagnostics.LOCATION,
    category: Diagnostics.Emit,
    description: Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code
  },
  {
    name: "mapRoot",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    paramType: Diagnostics.LOCATION,
    category: Diagnostics.Emit,
    description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations
  },
  {
    name: "inlineSources",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript,
    defaultValueDescription: false
  },
  // Experimental
  {
    name: "experimentalDecorators",
    type: "boolean",
    affectsEmit: true,
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Enable_experimental_support_for_legacy_experimental_decorators,
    defaultValueDescription: false
  },
  {
    name: "emitDecoratorMetadata",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files,
    defaultValueDescription: false
  },
  // Advanced
  {
    name: "jsxFactory",
    type: "string",
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h,
    defaultValueDescription: "`React.createElement`"
  },
  {
    name: "jsxFragmentFactory",
    type: "string",
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragment_or_Fragment,
    defaultValueDescription: "React.Fragment"
  },
  {
    name: "jsxImportSource",
    type: "string",
    affectsSemanticDiagnostics: true,
    affectsEmit: true,
    affectsBuildInfo: true,
    affectsModuleResolution: true,
    affectsSourceFile: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk,
    defaultValueDescription: "react"
  },
  {
    name: "resolveJsonModule",
    type: "boolean",
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Enable_importing_json_files,
    defaultValueDescription: false
  },
  {
    name: "allowArbitraryExtensions",
    type: "boolean",
    affectsProgramStructure: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present,
    defaultValueDescription: false
  },
  {
    name: "out",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    affectsDeclarationPath: true,
    isFilePath: false,
    // This is intentionally broken to support compatibility with existing tsconfig files
    // for correct behaviour, please use outFile
    category: Diagnostics.Backwards_Compatibility,
    paramType: Diagnostics.FILE,
    transpileOptionValue: void 0,
    description: Diagnostics.Deprecated_setting_Use_outFile_instead
  },
  {
    name: "reactNamespace",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit,
    defaultValueDescription: "`React`"
  },
  {
    name: "skipDefaultLibCheck",
    type: "boolean",
    // We need to store these to determine whether `lib` files need to be rechecked
    affectsBuildInfo: true,
    category: Diagnostics.Completeness,
    description: Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript,
    defaultValueDescription: false
  },
  {
    name: "charset",
    type: "string",
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files,
    defaultValueDescription: "utf8"
  },
  {
    name: "emitBOM",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files,
    defaultValueDescription: false
  },
  {
    name: "newLine",
    type: new Map(Object.entries({
      crlf: 0 /* CarriageReturnLineFeed */,
      lf: 1 /* LineFeed */
    })),
    affectsEmit: true,
    affectsBuildInfo: true,
    paramType: Diagnostics.NEWLINE,
    category: Diagnostics.Emit,
    description: Diagnostics.Set_the_newline_character_for_emitting_files,
    defaultValueDescription: "lf"
  },
  {
    name: "noErrorTruncation",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Output_Formatting,
    description: Diagnostics.Disable_truncating_types_in_error_messages,
    defaultValueDescription: false
  },
  {
    name: "noLib",
    type: "boolean",
    category: Diagnostics.Language_and_Environment,
    affectsProgramStructure: true,
    description: Diagnostics.Disable_including_any_library_files_including_the_default_lib_d_ts,
    // We are not returning a sourceFile for lib file when asked by the program,
    // so pass --noLib to avoid reporting a file not found error.
    transpileOptionValue: true,
    defaultValueDescription: false
  },
  {
    name: "noResolve",
    type: "boolean",
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add_to_a_project,
    // We are not doing a full typecheck, we are not resolving the whole context,
    // so pass --noResolve to avoid reporting missing file errors.
    transpileOptionValue: true,
    defaultValueDescription: false
  },
  {
    name: "stripInternal",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments,
    defaultValueDescription: false
  },
  {
    name: "disableSizeLimit",
    type: "boolean",
    affectsProgramStructure: true,
    category: Diagnostics.Editor_Support,
    description: Diagnostics.Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server,
    defaultValueDescription: false
  },
  {
    name: "disableSourceOfProjectReferenceRedirect",
    type: "boolean",
    isTSConfigOnly: true,
    category: Diagnostics.Projects,
    description: Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects,
    defaultValueDescription: false
  },
  {
    name: "disableSolutionSearching",
    type: "boolean",
    isTSConfigOnly: true,
    category: Diagnostics.Projects,
    description: Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing,
    defaultValueDescription: false
  },
  {
    name: "disableReferencedProjectLoad",
    type: "boolean",
    isTSConfigOnly: true,
    category: Diagnostics.Projects,
    description: Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript,
    defaultValueDescription: false
  },
  {
    name: "noImplicitUseStrict",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files,
    defaultValueDescription: false
  },
  {
    name: "noEmitHelpers",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output,
    defaultValueDescription: false
  },
  {
    name: "noEmitOnError",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    transpileOptionValue: void 0,
    description: Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported,
    defaultValueDescription: false
  },
  {
    name: "preserveConstEnums",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code,
    defaultValueDescription: false
  },
  {
    name: "declarationDir",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    affectsDeclarationPath: true,
    isFilePath: true,
    paramType: Diagnostics.DIRECTORY,
    category: Diagnostics.Emit,
    transpileOptionValue: void 0,
    description: Diagnostics.Specify_the_output_directory_for_generated_declaration_files
  },
  {
    name: "skipLibCheck",
    type: "boolean",
    // We need to store these to determine whether `lib` files need to be rechecked
    affectsBuildInfo: true,
    category: Diagnostics.Completeness,
    description: Diagnostics.Skip_type_checking_all_d_ts_files,
    defaultValueDescription: false
  },
  {
    name: "allowUnusedLabels",
    type: "boolean",
    affectsBindDiagnostics: true,
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Disable_error_reporting_for_unused_labels,
    defaultValueDescription: void 0
  },
  {
    name: "allowUnreachableCode",
    type: "boolean",
    affectsBindDiagnostics: true,
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Disable_error_reporting_for_unreachable_code,
    defaultValueDescription: void 0
  },
  {
    name: "suppressExcessPropertyErrors",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals,
    defaultValueDescription: false
  },
  {
    name: "suppressImplicitAnyIndexErrors",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures,
    defaultValueDescription: false
  },
  {
    name: "forceConsistentCasingInFileNames",
    type: "boolean",
    affectsModuleResolution: true,
    category: Diagnostics.Interop_Constraints,
    description: Diagnostics.Ensure_that_casing_is_correct_in_imports,
    defaultValueDescription: true
  },
  {
    name: "maxNodeModuleJsDepth",
    type: "number",
    affectsModuleResolution: true,
    category: Diagnostics.JavaScript_Support,
    description: Diagnostics.Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs,
    defaultValueDescription: 0
  },
  {
    name: "noStrictGenericChecks",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
    defaultValueDescription: false
  },
  {
    name: "useDefineForClassFields",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Emit_ECMAScript_standard_compliant_class_fields,
    defaultValueDescription: Diagnostics.true_for_ES2022_and_above_including_ESNext
  },
  {
    name: "preserveValueImports",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed,
    defaultValueDescription: false
  },
  {
    name: "keyofStringsOnly",
    type: "boolean",
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option,
    defaultValueDescription: false
  },
  {
    // A list of plugins to load in the language service
    name: "plugins",
    type: "list",
    isTSConfigOnly: true,
    element: {
      name: "plugin",
      type: "object"
    },
    description: Diagnostics.Specify_a_list_of_language_service_plugins_to_include,
    category: Diagnostics.Editor_Support
  },
  {
    name: "moduleDetection",
    type: new Map(Object.entries({
      auto: 2 /* Auto */,
      legacy: 1 /* Legacy */,
      force: 3 /* Force */
    })),
    affectsSourceFile: true,
    affectsModuleResolution: true,
    description: Diagnostics.Control_what_method_is_used_to_detect_module_format_JS_files,
    category: Diagnostics.Language_and_Environment,
    defaultValueDescription: Diagnostics.auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules
  },
  {
    name: "ignoreDeprecations",
    type: "string",
    defaultValueDescription: void 0
  }
];
var optionDeclarations = [
  ...commonOptionsWithBuild,
  ...commandOptionsWithoutBuild
];
var semanticDiagnosticsOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsSemanticDiagnostics);
var affectsEmitOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsEmit);
var affectsDeclarationPathOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsDeclarationPath);
var moduleResolutionOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsModuleResolution);
var sourceFileAffectingCompilerOptions = optionDeclarations.filter((option) => !!option.affectsSourceFile || !!option.affectsBindDiagnostics);
var optionsAffectingProgramStructure = optionDeclarations.filter((option) => !!option.affectsProgramStructure);
var transpileOptionValueCompilerOptions = optionDeclarations.filter((option) => hasProperty(option, "transpileOptionValue"));
var configDirTemplateSubstitutionOptions = optionDeclarations.filter(
  (option) => option.allowConfigDirTemplateSubstitution || !option.isCommandLineOnly && option.isFilePath
);
var configDirTemplateSubstitutionWatchOptions = optionsForWatch.filter(
  (option) => option.allowConfigDirTemplateSubstitution || !option.isCommandLineOnly && option.isFilePath
);
var commandLineOptionOfCustomType = optionDeclarations.filter(isCommandLineOptionOfCustomType);
function isCommandLineOptionOfCustomType(option) {
  return !isString(option.type);
}
var tscBuildOption = {
  name: "build",
  type: "boolean",
  shortName: "b",
  showInSimplifiedHelpView: true,
  category: Diagnostics.Command_line_Options,
  description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date,
  defaultValueDescription: false
};
var optionsForBuild = [
  tscBuildOption,
  {
    name: "verbose",
    shortName: "v",
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Enable_verbose_logging,
    type: "boolean",
    defaultValueDescription: false
  },
  {
    name: "dry",
    shortName: "d",
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
    type: "boolean",
    defaultValueDescription: false
  },
  {
    name: "force",
    shortName: "f",
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
    type: "boolean",
    defaultValueDescription: false
  },
  {
    name: "clean",
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Delete_the_outputs_of_all_projects,
    type: "boolean",
    defaultValueDescription: false
  },
  {
    name: "stopBuildOnErrors",
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Skip_building_downstream_projects_on_error_in_upstream_project,
    type: "boolean",
    defaultValueDescription: false
  }
];
var buildOpts = [
  ...commonOptionsWithBuild,
  ...optionsForBuild
];
var typeAcquisitionDeclarations = [
  {
    name: "enable",
    type: "boolean",
    defaultValueDescription: false
  },
  {
    name: "include",
    type: "list",
    element: {
      name: "include",
      type: "string"
    }
  },
  {
    name: "exclude",
    type: "list",
    element: {
      name: "exclude",
      type: "string"
    }
  },
  {
    name: "disableFilenameBasedTypeAcquisition",
    type: "boolean",
    defaultValueDescription: false
  }
];
function createOptionNameMap(optionDeclarations2) {
  const optionsNameMap = /* @__PURE__ */ new Map();
  const shortOptionNames = /* @__PURE__ */ new Map();
  forEach(optionDeclarations2, (option) => {
    optionsNameMap.set(option.name.toLowerCase(), option);
    if (option.shortName) {
      shortOptionNames.set(option.shortName, option.name);
    }
  });
  return { optionsNameMap, shortOptionNames };
}
var optionsNameMapCache;
function getOptionsNameMap() {
  return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(optionDeclarations));
}
var compilerOptionsAlternateMode = {
  diagnostic: Diagnostics.Compiler_option_0_may_only_be_used_with_build,
  getOptionsNameMap: getBuildOptionsNameMap
};
var defaultInitCompilerOptions = {
  module: 1 /* CommonJS */,
  target: 3 /* ES2016 */,
  strict: true,
  esModuleInterop: true,
  forceConsistentCasingInFileNames: true,
  skipLibCheck: true
};
function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
  const namesOfType = arrayFrom(opt.type.keys());
  const stringNames = (opt.deprecatedKeys ? namesOfType.filter((k) => !opt.deprecatedKeys.has(k)) : namesOfType).map((key) => `'${key}'`).join(", ");
  return createDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, stringNames);
}
function parseCustomTypeOption(opt, value, errors) {
  return convertJsonOptionOfCustomType(opt, (value ?? "").trim(), errors);
}
function parseListTypeOption(opt, value = "", errors) {
  value = value.trim();
  if (startsWith(value, "-")) {
    return void 0;
  }
  if (opt.type === "listOrElement" && !value.includes(",")) {
    return validateJsonOptionValue(opt, value, errors);
  }
  if (value === "") {
    return [];
  }
  const values = value.split(",");
  switch (opt.element.type) {
    case "number":
      return mapDefined(values, (v) => validateJsonOptionValue(opt.element, parseInt(v), errors));
    case "string":
      return mapDefined(values, (v) => validateJsonOptionValue(opt.element, v || "", errors));
    case "boolean":
    case "object":
      return Debug.fail(`List of ${opt.element.type} is not yet supported.`);
    default:
      return mapDefined(values, (v) => parseCustomTypeOption(opt.element, v, errors));
  }
}
function getOptionName(option) {
  return option.name;
}
function createUnknownOptionError(unknownOption, diagnostics, unknownOptionErrorText, node, sourceFile) {
  var _a;
  const otherOption = (_a = diagnostics.alternateMode) == null ? void 0 : _a.getOptionsNameMap().optionsNameMap.get(unknownOption.toLowerCase());
  if (otherOption) {
    return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(
      sourceFile,
      node,
      otherOption !== tscBuildOption ? diagnostics.alternateMode.diagnostic : Diagnostics.Option_build_must_be_the_first_command_line_argument,
      unknownOption
    );
  }
  const possibleOption = getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
  return possibleOption ? createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
}
function parseCommandLineWorker(diagnostics, commandLine, readFile) {
  const options = {};
  let watchOptions;
  const fileNames = [];
  const errors = [];
  parseStrings(commandLine);
  return {
    options,
    watchOptions,
    fileNames,
    errors
  };
  function parseStrings(args) {
    let i = 0;
    while (i < args.length) {
      const s = args[i];
      i++;
      if (s.charCodeAt(0) === 64 /* at */) {
        parseResponseFile(s.slice(1));
      } else if (s.charCodeAt(0) === 45 /* minus */) {
        const inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
        const opt = getOptionDeclarationFromName(
          diagnostics.getOptionsNameMap,
          inputOptionName,
          /*allowShort*/
          true
        );
        if (opt) {
          i = parseOptionValue(args, i, diagnostics, opt, options, errors);
        } else {
          const watchOpt = getOptionDeclarationFromName(
            watchOptionsDidYouMeanDiagnostics.getOptionsNameMap,
            inputOptionName,
            /*allowShort*/
            true
          );
          if (watchOpt) {
            i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
          } else {
            errors.push(createUnknownOptionError(inputOptionName, diagnostics, s));
          }
        }
      } else {
        fileNames.push(s);
      }
    }
  }
  function parseResponseFile(fileName) {
    const text = tryReadFile(fileName, readFile || ((fileName2) => sys.readFile(fileName2)));
    if (!isString(text)) {
      errors.push(text);
      return;
    }
    const args = [];
    let pos = 0;
    while (true) {
      while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) pos++;
      if (pos >= text.length) break;
      const start = pos;
      if (text.charCodeAt(start) === 34 /* doubleQuote */) {
        pos++;
        while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) pos++;
        if (pos < text.length) {
          args.push(text.substring(start + 1, pos));
          pos++;
        } else {
          errors.push(createCompilerDiagnostic(Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
        }
      } else {
        while (text.charCodeAt(pos) > 32 /* space */) pos++;
        args.push(text.substring(start, pos));
      }
    }
    parseStrings(args);
  }
}
function parseOptionValue(args, i, diagnostics, opt, options, errors) {
  if (opt.isTSConfigOnly) {
    const optValue = args[i];
    if (optValue === "null") {
      options[opt.name] = void 0;
      i++;
    } else if (opt.type === "boolean") {
      if (optValue === "false") {
        options[opt.name] = validateJsonOptionValue(
          opt,
          /*value*/
          false,
          errors
        );
        i++;
      } else {
        if (optValue === "true") i++;
        errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name));
      }
    } else {
      errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name));
      if (optValue && !startsWith(optValue, "-")) i++;
    }
  } else {
    if (!args[i] && opt.type !== "boolean") {
      errors.push(createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
    }
    if (args[i] !== "null") {
      switch (opt.type) {
        case "number":
          options[opt.name] = validateJsonOptionValue(opt, parseInt(args[i]), errors);
          i++;
          break;
        case "boolean":
          const optValue = args[i];
          options[opt.name] = validateJsonOptionValue(opt, optValue !== "false", errors);
          if (optValue === "false" || optValue === "true") {
            i++;
          }
          break;
        case "string":
          options[opt.name] = validateJsonOptionValue(opt, args[i] || "", errors);
          i++;
          break;
        case "list":
          const result = parseListTypeOption(opt, args[i], errors);
          options[opt.name] = result || [];
          if (result) {
            i++;
          }
          break;
        case "listOrElement":
          Debug.fail("listOrElement not supported here");
          break;
        // If not a primitive, the possible types are specified in what is effectively a map of options.
        default:
          options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
          i++;
          break;
      }
    } else {
      options[opt.name] = void 0;
      i++;
    }
  }
  return i;
}
var compilerOptionsDidYouMeanDiagnostics = {
  alternateMode: compilerOptionsAlternateMode,
  getOptionsNameMap,
  optionDeclarations,
  unknownOptionDiagnostic: Diagnostics.Unknown_compiler_option_0,
  unknownDidYouMeanDiagnostic: Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
  optionTypeMismatchDiagnostic: Diagnostics.Compiler_option_0_expects_an_argument
};
function parseCommandLine(commandLine, readFile) {
  return parseCommandLineWorker(compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
}
function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort = false) {
  optionName = optionName.toLowerCase();
  const { optionsNameMap, shortOptionNames } = getOptionNameMap();
  if (allowShort) {
    const short = shortOptionNames.get(optionName);
    if (short !== void 0) {
      optionName = short;
    }
  }
  return optionsNameMap.get(optionName);
}
var buildOptionsNameMapCache;
function getBuildOptionsNameMap() {
  return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(buildOpts));
}
var buildOptionsAlternateMode = {
  diagnostic: Diagnostics.Compiler_option_0_may_not_be_used_with_build,
  getOptionsNameMap
};
var buildOptionsDidYouMeanDiagnostics = {
  alternateMode: buildOptionsAlternateMode,
  getOptionsNameMap: getBuildOptionsNameMap,
  optionDeclarations: buildOpts,
  unknownOptionDiagnostic: Diagnostics.Unknown_build_option_0,
  unknownDidYouMeanDiagnostic: Diagnostics.Unknown_build_option_0_Did_you_mean_1,
  optionTypeMismatchDiagnostic: Diagnostics.Build_option_0_requires_a_value_of_type_1
};
function parseBuildCommand(commandLine) {
  const { options, watchOptions, fileNames: projects, errors } = parseCommandLineWorker(
    buildOptionsDidYouMeanDiagnostics,
    commandLine
  );
  const buildOptions = options;
  if (projects.length === 0) {
    projects.push(".");
  }
  if (buildOptions.clean && buildOptions.force) {
    errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
  }
  if (buildOptions.clean && buildOptions.verbose) {
    errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
  }
  if (buildOptions.clean && buildOptions.watch) {
    errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
  }
  if (buildOptions.watch && buildOptions.dry) {
    errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
  }
  return { buildOptions, watchOptions, projects, errors };
}
function getDiagnosticText(message, ...args) {
  return cast(createCompilerDiagnostic(message, ...args).messageText, isString);
}
function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
  const configFileText = tryReadFile(configFileName, (fileName) => host.readFile(fileName));
  if (!isString(configFileText)) {
    host.onUnRecoverableConfigFileDiagnostic(configFileText);
    return void 0;
  }
  const result = parseJsonText(configFileName, configFileText);
  const cwd = host.getCurrentDirectory();
  result.path = toPath(configFileName, cwd, createGetCanonicalFileName(host.useCaseSensitiveFileNames));
  result.resolvedPath = result.path;
  result.originalFileName = result.fileName;
  return parseJsonSourceFileConfigFileContent(
    result,
    host,
    getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd),
    optionsToExtend,
    getNormalizedAbsolutePath(configFileName, cwd),
    /*resolutionStack*/
    void 0,
    extraFileExtensions,
    extendedConfigCache,
    watchOptionsToExtend
  );
}
function parseConfigFileTextToJson(fileName, jsonText) {
  const jsonSourceFile = parseJsonText(fileName, jsonText);
  return {
    config: convertConfigFileToObject(
      jsonSourceFile,
      jsonSourceFile.parseDiagnostics,
      /*jsonConversionNotifier*/
      void 0
    ),
    error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : void 0
  };
}
function readJsonConfigFile(fileName, readFile) {
  const textOrDiagnostic = tryReadFile(fileName, readFile);
  return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : { fileName, parseDiagnostics: [textOrDiagnostic] };
}
function tryReadFile(fileName, readFile) {
  let text;
  try {
    text = readFile(fileName);
  } catch (e) {
    return createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
  }
  return text === void 0 ? createCompilerDiagnostic(Diagnostics.Cannot_read_file_0, fileName) : text;
}
function commandLineOptionsToMap(options) {
  return arrayToMap(options, getOptionName);
}
var typeAcquisitionDidYouMeanDiagnostics = {
  optionDeclarations: typeAcquisitionDeclarations,
  unknownOptionDiagnostic: Diagnostics.Unknown_type_acquisition_option_0,
  unknownDidYouMeanDiagnostic: Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1
};
var watchOptionsNameMapCache;
function getWatchOptionsNameMap() {
  return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(optionsForWatch));
}
var watchOptionsDidYouMeanDiagnostics = {
  getOptionsNameMap: getWatchOptionsNameMap,
  optionDeclarations: optionsForWatch,
  unknownOptionDiagnostic: Diagnostics.Unknown_watch_option_0,
  unknownDidYouMeanDiagnostic: Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
  optionTypeMismatchDiagnostic: Diagnostics.Watch_option_0_requires_a_value_of_type_1
};
var commandLineCompilerOptionsMapCache;
function getCommandLineCompilerOptionsMap() {
  return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(optionDeclarations));
}
var commandLineWatchOptionsMapCache;
function getCommandLineWatchOptionsMap() {
  return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(optionsForWatch));
}
var commandLineTypeAcquisitionMapCache;
function getCommandLineTypeAcquisitionMap() {
  return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(typeAcquisitionDeclarations));
}
var extendsOptionDeclaration = {
  name: "extends",
  type: "listOrElement",
  element: {
    name: "extends",
    type: "string"
  },
  category: Diagnostics.File_Management,
  disallowNullOrUndefined: true
};
var compilerOptionsDeclaration = {
  name: "compilerOptions",
  type: "object",
  elementOptions: getCommandLineCompilerOptionsMap(),
  extraKeyDiagnostics: compilerOptionsDidYouMeanDiagnostics
};
var watchOptionsDeclaration = {
  name: "watchOptions",
  type: "object",
  elementOptions: getCommandLineWatchOptionsMap(),
  extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics
};
var typeAcquisitionDeclaration = {
  name: "typeAcquisition",
  type: "object",
  elementOptions: getCommandLineTypeAcquisitionMap(),
  extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
};
var _tsconfigRootOptions;
function getTsconfigRootOptionsMap() {
  if (_tsconfigRootOptions === void 0) {
    _tsconfigRootOptions = {
      name: void 0,
      // should never be needed since this is root
      type: "object",
      elementOptions: commandLineOptionsToMap([
        compilerOptionsDeclaration,
        watchOptionsDeclaration,
        typeAcquisitionDeclaration,
        extendsOptionDeclaration,
        {
          name: "references",
          type: "list",
          element: {
            name: "references",
            type: "object"
          },
          category: Diagnostics.Projects
        },
        {
          name: "files",
          type: "list",
          element: {
            name: "files",
            type: "string"
          },
          category: Diagnostics.File_Management
        },
        {
          name: "include",
          type: "list",
          element: {
            name: "include",
            type: "string"
          },
          category: Diagnostics.File_Management,
          defaultValueDescription: Diagnostics.if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk
        },
        {
          name: "exclude",
          type: "list",
          element: {
            name: "exclude",
            type: "string"
          },
          category: Diagnostics.File_Management,
          defaultValueDescription: Diagnostics.node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified
        },
        compileOnSaveCommandLineOption
      ])
    };
  }
  return _tsconfigRootOptions;
}
function convertConfigFileToObject(sourceFile, errors, jsonConversionNotifier) {
  var _a;
  const rootExpression = (_a = sourceFile.statements[0]) == null ? void 0 : _a.expression;
  if (rootExpression && rootExpression.kind !== 210 /* ObjectLiteralExpression */) {
    errors.push(createDiagnosticForNodeInSourceFile(
      sourceFile,
      rootExpression,
      Diagnostics.The_root_value_of_a_0_file_must_be_an_object,
      getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json"
    ));
    if (isArrayLiteralExpression(rootExpression)) {
      const firstObject = find(rootExpression.elements, isObjectLiteralExpression);
      if (firstObject) {
        return convertToJson(
          sourceFile,
          firstObject,
          errors,
          /*returnValue*/
          true,
          jsonConversionNotifier
        );
      }
    }
    return {};
  }
  return convertToJson(
    sourceFile,
    rootExpression,
    errors,
    /*returnValue*/
    true,
    jsonConversionNotifier
  );
}
function convertToObject(sourceFile, errors) {
  var _a;
  return convertToJson(
    sourceFile,
    (_a = sourceFile.statements[0]) == null ? void 0 : _a.expression,
    errors,
    /*returnValue*/
    true,
    /*jsonConversionNotifier*/
    void 0
  );
}
function convertToJson(sourceFile, rootExpression, errors, returnValue, jsonConversionNotifier) {
  if (!rootExpression) {
    return returnValue ? {} : void 0;
  }
  return convertPropertyValueToJson(rootExpression, jsonConversionNotifier == null ? void 0 : jsonConversionNotifier.rootOptions);
  function convertObjectLiteralExpressionToJson(node, objectOption) {
    var _a;
    const result = returnValue ? {} : void 0;
    for (const element of node.properties) {
      if (element.kind !== 303 /* PropertyAssignment */) {
        errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element, Diagnostics.Property_assignment_expected));
        continue;
      }
      if (element.questionToken) {
        errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
      }
      if (!isDoubleQuotedString(element.name)) {
        errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element.name, Diagnostics.String_literal_with_double_quotes_expected));
      }
      const textOfKey = isComputedNonLiteralName(element.name) ? void 0 : getTextOfPropertyName(element.name);
      const keyText = textOfKey && unescapeLeadingUnderscores(textOfKey);
      const option = keyText ? (_a = objectOption == null ? void 0 : objectOption.elementOptions) == null ? void 0 : _a.get(keyText) : void 0;
      const value = convertPropertyValueToJson(element.initializer, option);
      if (typeof keyText !== "undefined") {
        if (returnValue) {
          result[keyText] = value;
        }
        jsonConversionNotifier == null ? void 0 : jsonConversionNotifier.onPropertySet(keyText, value, element, objectOption, option);
      }
    }
    return result;
  }
  function convertArrayLiteralExpressionToJson(elements, elementOption) {
    if (!returnValue) {
      elements.forEach((element) => convertPropertyValueToJson(element, elementOption));
      return void 0;
    }
    return filter(elements.map((element) => convertPropertyValueToJson(element, elementOption)), (v) => v !== void 0);
  }
  function convertPropertyValueToJson(valueExpression, option) {
    switch (valueExpression.kind) {
      case 112 /* TrueKeyword */:
        return true;
      case 97 /* FalseKeyword */:
        return false;
      case 106 /* NullKeyword */:
        return null;
      // eslint-disable-line no-restricted-syntax
      case 11 /* StringLiteral */:
        if (!isDoubleQuotedString(valueExpression)) {
          errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.String_literal_with_double_quotes_expected));
        }
        return valueExpression.text;
      case 9 /* NumericLiteral */:
        return Number(valueExpression.text);
      case 224 /* PrefixUnaryExpression */:
        if (valueExpression.operator !== 41 /* MinusToken */ || valueExpression.operand.kind !== 9 /* NumericLiteral */) {
          break;
        }
        return -Number(valueExpression.operand.text);
      case 210 /* ObjectLiteralExpression */:
        const objectLiteralExpression = valueExpression;
        return convertObjectLiteralExpressionToJson(objectLiteralExpression, option);
      case 209 /* ArrayLiteralExpression */:
        return convertArrayLiteralExpressionToJson(
          valueExpression.elements,
          option && option.element
        );
    }
    if (option) {
      errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
    } else {
      errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal));
    }
    return void 0;
  }
  function isDoubleQuotedString(node) {
    return isStringLiteral(node) && isStringDoubleQuoted(node, sourceFile);
  }
}
function getCompilerOptionValueTypeString(option) {
  return option.type === "listOrElement" ? `${getCompilerOptionValueTypeString(option.element)} or Array` : option.type === "list" ? "Array" : isString(option.type) ? option.type : "string";
}
function isCompilerOptionsValue(option, value) {
  if (option) {
    if (isNullOrUndefined(value)) return !option.disallowNullOrUndefined;
    if (option.type === "list") {
      return isArray(value);
    }
    if (option.type === "listOrElement") {
      return isArray(value) || isCompilerOptionsValue(option.element, value);
    }
    const expectedType = isString(option.type) ? option.type : "string";
    return typeof value === expectedType;
  }
  return false;
}
function convertToTSConfig(configParseResult, configFileName, host) {
  var _a, _b, _c;
  const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
  const files = map(
    filter(
      configParseResult.fileNames,
      !((_b = (_a = configParseResult.options.configFile) == null ? void 0 : _a.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs) ? returnTrue : matchesSpecs(
        configFileName,
        configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs,
        configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs,
        host
      )
    ),
    (f) => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName)
  );
  const pathOptions = { configFilePath: getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames };
  const optionMap = serializeCompilerOptions(configParseResult.options, pathOptions);
  const watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
  const config = {
    compilerOptions: {
      ...optionMapToObject(optionMap),
      showConfig: void 0,
      configFile: void 0,
      configFilePath: void 0,
      help: void 0,
      init: void 0,
      listFiles: void 0,
      listEmittedFiles: void 0,
      project: void 0,
      build: void 0,
      version: void 0
    },
    watchOptions: watchOptionMap && optionMapToObject(watchOptionMap),
    references: map(configParseResult.projectReferences, (r) => ({ ...r, path: r.originalPath ? r.originalPath : "", originalPath: void 0 })),
    files: length(files) ? files : void 0,
    ...((_c = configParseResult.options.configFile) == null ? void 0 : _c.configFileSpecs) ? {
      include: filterSameAsDefaultInclude(configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs),
      exclude: configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs
    } : {},
    compileOnSave: !!configParseResult.compileOnSave ? true : void 0
  };
  const providedKeys = new Set(optionMap.keys());
  const impliedCompilerOptions = {};
  for (const option in computedOptions) {
    if (!providedKeys.has(option) && optionDependsOn(option, providedKeys)) {
      const implied = computedOptions[option].computeValue(configParseResult.options);
      const defaultValue = computedOptions[option].computeValue({});
      if (implied !== defaultValue) {
        impliedCompilerOptions[option] = computedOptions[option].computeValue(configParseResult.options);
      }
    }
  }
  assign(config.compilerOptions, optionMapToObject(serializeCompilerOptions(impliedCompilerOptions, pathOptions)));
  return config;
}
function optionDependsOn(option, dependsOn) {
  const seen = /* @__PURE__ */ new Set();
  return optionDependsOnRecursive(option);
  function optionDependsOnRecursive(option2) {
    var _a;
    if (addToSeen(seen, option2)) {
      return some((_a = computedOptions[option2]) == null ? void 0 : _a.dependencies, (dep) => dependsOn.has(dep) || optionDependsOnRecursive(dep));
    }
    return false;
  }
}
function optionMapToObject(optionMap) {
  return Object.fromEntries(optionMap);
}
function filterSameAsDefaultInclude(specs) {
  if (!length(specs)) return void 0;
  if (length(specs) !== 1) return specs;
  if (specs[0] === defaultIncludeSpec) return void 0;
  return specs;
}
function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
  if (!includeSpecs) return returnTrue;
  const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
  const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
  const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
  if (includeRe) {
    if (excludeRe) {
      return (path2) => !(includeRe.test(path2) && !excludeRe.test(path2));
    }
    return (path2) => !includeRe.test(path2);
  }
  if (excludeRe) {
    return (path2) => excludeRe.test(path2);
  }
  return returnTrue;
}
function getCustomTypeMapOfCommandLineOption(optionDefinition) {
  switch (optionDefinition.type) {
    case "string":
    case "number":
    case "boolean":
    case "object":
      return void 0;
    case "list":
    case "listOrElement":
      return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
    default:
      return optionDefinition.type;
  }
}
function getNameOfCompilerOptionValue(value, customTypeMap) {
  return forEachEntry(customTypeMap, (mapValue, key) => {
    if (mapValue === value) {
      return key;
    }
  });
}
function serializeCompilerOptions(options, pathOptions) {
  return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
}
function serializeWatchOptions(options) {
  return serializeOptionBaseObject(options, getWatchOptionsNameMap());
}
function serializeOptionBaseObject(options, { optionsNameMap }, pathOptions) {
  const result = /* @__PURE__ */ new Map();
  const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
  for (const name in options) {
    if (hasProperty(options, name)) {
      if (optionsNameMap.has(name) && (optionsNameMap.get(name).category === Diagnostics.Command_line_Options || optionsNameMap.get(name).category === Diagnostics.Output_Formatting)) {
        continue;
      }
      const value = options[name];
      const optionDefinition = optionsNameMap.get(name.toLowerCase());
      if (optionDefinition) {
        Debug.assert(optionDefinition.type !== "listOrElement");
        const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition);
        if (!customTypeMap) {
          if (pathOptions && optionDefinition.isFilePath) {
            result.set(name, getRelativePathFromFile(pathOptions.configFilePath, getNormalizedAbsolutePath(value, getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
          } else if (pathOptions && optionDefinition.type === "list" && optionDefinition.element.isFilePath) {
            result.set(name, value.map((v) => getRelativePathFromFile(pathOptions.configFilePath, getNormalizedAbsolutePath(v, getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)));
          } else {
            result.set(name, value);
          }
        } else {
          if (optionDefinition.type === "list") {
            result.set(name, value.map((element) => getNameOfCompilerOptionValue(element, customTypeMap)));
          } else {
            result.set(name, getNameOfCompilerOptionValue(value, customTypeMap));
          }
        }
      }
    }
  }
  return result;
}
function getCompilerOptionsDiffValue(options, newLine) {
  const compilerOptionsMap = getSerializedCompilerOption(options);
  return getOverwrittenDefaultOptions();
  function makePadding(paddingLength) {
    return Array(paddingLength + 1).join(" ");
  }
  function getOverwrittenDefaultOptions() {
    const result = [];
    const tab = makePadding(2);
    commandOptionsWithoutBuild.forEach((cmd) => {
      if (!compilerOptionsMap.has(cmd.name)) {
        return;
      }
      const newValue = compilerOptionsMap.get(cmd.name);
      const defaultValue = getDefaultValueForOption(cmd);
      if (newValue !== defaultValue) {
        result.push(`${tab}${cmd.name}: ${newValue}`);
      } else if (hasProperty(defaultInitCompilerOptions, cmd.name)) {
        result.push(`${tab}${cmd.name}: ${defaultValue}`);
      }
    });
    return result.join(newLine) + newLine;
  }
}
function getSerializedCompilerOption(options) {
  const compilerOptions = extend(options, defaultInitCompilerOptions);
  return serializeCompilerOptions(compilerOptions);
}
function generateTSConfig(options, fileNames, newLine) {
  const compilerOptionsMap = getSerializedCompilerOption(options);
  return writeConfigurations();
  function makePadding(paddingLength) {
    return Array(paddingLength + 1).join(" ");
  }
  function isAllowedOptionForOutput({ category, name, isCommandLineOnly }) {
    const categoriesToSkip = [Diagnostics.Command_line_Options, Diagnostics.Editor_Support, Diagnostics.Compiler_Diagnostics, Diagnostics.Backwards_Compatibility, Diagnostics.Watch_and_Build_Modes, Diagnostics.Output_Formatting];
    return !isCommandLineOnly && category !== void 0 && (!categoriesToSkip.includes(category) || compilerOptionsMap.has(name));
  }
  function writeConfigurations() {
    const categorizedOptions = /* @__PURE__ */ new Map();
    categorizedOptions.set(Diagnostics.Projects, []);
    categorizedOptions.set(Diagnostics.Language_and_Environment, []);
    categorizedOptions.set(Diagnostics.Modules, []);
    categorizedOptions.set(Diagnostics.JavaScript_Support, []);
    categorizedOptions.set(Diagnostics.Emit, []);
    categorizedOptions.set(Diagnostics.Interop_Constraints, []);
    categorizedOptions.set(Diagnostics.Type_Checking, []);
    categorizedOptions.set(Diagnostics.Completeness, []);
    for (const option of optionDeclarations) {
      if (isAllowedOptionForOutput(option)) {
        let listForCategory = categorizedOptions.get(option.category);
        if (!listForCategory) categorizedOptions.set(option.category, listForCategory = []);
        listForCategory.push(option);
      }
    }
    let marginLength = 0;
    let seenKnownKeys = 0;
    const entries = [];
    categorizedOptions.forEach((options2, category) => {
      if (entries.length !== 0) {
        entries.push({ value: "" });
      }
      entries.push({ value: `/* ${getLocaleSpecificMessage(category)} */` });
      for (const option of options2) {
        let optionName;
        if (compilerOptionsMap.has(option.name)) {
          optionName = `"${option.name}": ${JSON.stringify(compilerOptionsMap.get(option.name))}${(seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","}`;
        } else {
          optionName = `// "${option.name}": ${JSON.stringify(getDefaultValueForOption(option))},`;
        }
        entries.push({
          value: optionName,
          description: `/* ${option.description && getLocaleSpecificMessage(option.description) || option.name} */`
        });
        marginLength = Math.max(optionName.length, marginLength);
      }
    });
    const tab = makePadding(2);
    const result = [];
    result.push(`{`);
    result.push(`${tab}"compilerOptions": {`);
    result.push(`${tab}${tab}/* ${getLocaleSpecificMessage(Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file)} */`);
    result.push("");
    for (const entry of entries) {
      const { value, description = "" } = entry;
      result.push(value && `${tab}${tab}${value}${description && makePadding(marginLength - value.length + 2) + description}`);
    }
    if (fileNames.length) {
      result.push(`${tab}},`);
      result.push(`${tab}"files": [`);
      for (let i = 0; i < fileNames.length; i++) {
        result.push(`${tab}${tab}${JSON.stringify(fileNames[i])}${i === fileNames.length - 1 ? "" : ","}`);
      }
      result.push(`${tab}]`);
    } else {
      result.push(`${tab}}`);
    }
    result.push(`}`);
    return result.join(newLine) + newLine;
  }
}
function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
  const result = {};
  const optionsNameMap = getOptionsNameMap().optionsNameMap;
  for (const name in options) {
    if (hasProperty(options, name)) {
      result[name] = convertToOptionValueWithAbsolutePaths(
        optionsNameMap.get(name.toLowerCase()),
        options[name],
        toAbsolutePath
      );
    }
  }
  if (result.configFilePath) {
    result.configFilePath = toAbsolutePath(result.configFilePath);
  }
  return result;
}
function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
  if (option && !isNullOrUndefined(value)) {
    if (option.type === "list") {
      const values = value;
      if (option.element.isFilePath && values.length) {
        return values.map(toAbsolutePath);
      }
    } else if (option.isFilePath) {
      return toAbsolutePath(value);
    }
    Debug.assert(option.type !== "listOrElement");
  }
  return value;
}
function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
  var _a, _b;
  (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { path: sourceFile.fileName });
  const result = parseJsonConfigFileContentWorker(
    /*json*/
    void 0,
    sourceFile,
    host,
    basePath,
    existingOptions,
    existingWatchOptions,
    configFileName,
    resolutionStack,
    extraFileExtensions,
    extendedConfigCache
  );
  (_b = tracing) == null ? void 0 : _b.pop();
  return result;
}
function setConfigFileInOptions(options, configFile) {
  if (configFile) {
    Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
  }
}
function isNullOrUndefined(x) {
  return x === void 0 || x === null;
}
function directoryOfCombinedPath(fileName, basePath) {
  return getDirectoryPath(getNormalizedAbsolutePath(fileName, basePath));
}
var defaultIncludeSpec = "**/*";
function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions = {}, existingWatchOptions, configFileName, resolutionStack = [], extraFileExtensions = [], extendedConfigCache) {
  Debug.assert(json === void 0 && sourceFile !== void 0 || json !== void 0 && sourceFile === void 0);
  const errors = [];
  const parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
  const { raw } = parsedConfig;
  const options = handleOptionConfigDirTemplateSubstitution(
    extend(existingOptions, parsedConfig.options || {}),
    configDirTemplateSubstitutionOptions,
    basePath
  );
  const watchOptions = handleWatchOptionsConfigDirTemplateSubstitution(
    existingWatchOptions && parsedConfig.watchOptions ? extend(existingWatchOptions, parsedConfig.watchOptions) : parsedConfig.watchOptions || existingWatchOptions,
    basePath
  );
  options.configFilePath = configFileName && normalizeSlashes(configFileName);
  const basePathForFileNames = normalizePath(configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath);
  const configFileSpecs = getConfigFileSpecs();
  if (sourceFile) sourceFile.configFileSpecs = configFileSpecs;
  setConfigFileInOptions(options, sourceFile);
  return {
    options,
    watchOptions,
    fileNames: getFileNames(basePathForFileNames),
    projectReferences: getProjectReferences(basePathForFileNames),
    typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
    raw,
    errors,
    // Wildcard directories (provided as part of a wildcard path) are stored in a
    // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
    // or a recursive directory. This information is used by filesystem watchers to monitor for
    // new entries in these paths.
    wildcardDirectories: getWildcardDirectories(configFileSpecs, basePathForFileNames, host.useCaseSensitiveFileNames),
    compileOnSave: !!raw.compileOnSave
  };
  function getConfigFileSpecs() {
    const referencesOfRaw = getPropFromRaw("references", (element) => typeof element === "object", "object");
    const filesSpecs = toPropValue(getSpecsFromRaw("files"));
    if (filesSpecs) {
      const hasZeroOrNoReferences = referencesOfRaw === "no-prop" || isArray(referencesOfRaw) && referencesOfRaw.length === 0;
      const hasExtends = hasProperty(raw, "extends");
      if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
        if (sourceFile) {
          const fileName = configFileName || "tsconfig.json";
          const diagnosticMessage = Diagnostics.The_files_list_in_config_file_0_is_empty;
          const nodeValue = forEachTsConfigPropArray(sourceFile, "files", (property) => property.initializer);
          const error = createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, nodeValue, diagnosticMessage, fileName);
          errors.push(error);
        } else {
          createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
        }
      }
    }
    let includeSpecs = toPropValue(getSpecsFromRaw("include"));
    const excludeOfRaw = getSpecsFromRaw("exclude");
    let isDefaultIncludeSpec = false;
    let excludeSpecs = toPropValue(excludeOfRaw);
    if (excludeOfRaw === "no-prop") {
      const outDir = options.outDir;
      const declarationDir = options.declarationDir;
      if (outDir || declarationDir) {
        excludeSpecs = filter([outDir, declarationDir], (d) => !!d);
      }
    }
    if (filesSpecs === void 0 && includeSpecs === void 0) {
      includeSpecs = [defaultIncludeSpec];
      isDefaultIncludeSpec = true;
    }
    let validatedIncludeSpecsBeforeSubstitution, validatedExcludeSpecsBeforeSubstitution;
    let validatedIncludeSpecs, validatedExcludeSpecs;
    if (includeSpecs) {
      validatedIncludeSpecsBeforeSubstitution = validateSpecs(
        includeSpecs,
        errors,
        /*disallowTrailingRecursion*/
        true,
        sourceFile,
        "include"
      );
      validatedIncludeSpecs = getSubstitutedStringArrayWithConfigDirTemplate(
        validatedIncludeSpecsBeforeSubstitution,
        basePathForFileNames
      ) || validatedIncludeSpecsBeforeSubstitution;
    }
    if (excludeSpecs) {
      validatedExcludeSpecsBeforeSubstitution = validateSpecs(
        excludeSpecs,
        errors,
        /*disallowTrailingRecursion*/
        false,
        sourceFile,
        "exclude"
      );
      validatedExcludeSpecs = getSubstitutedStringArrayWithConfigDirTemplate(
        validatedExcludeSpecsBeforeSubstitution,
        basePathForFileNames
      ) || validatedExcludeSpecsBeforeSubstitution;
    }
    const validatedFilesSpecBeforeSubstitution = filter(filesSpecs, isString);
    const validatedFilesSpec = getSubstitutedStringArrayWithConfigDirTemplate(
      validatedFilesSpecBeforeSubstitution,
      basePathForFileNames
    ) || validatedFilesSpecBeforeSubstitution;
    return {
      filesSpecs,
      includeSpecs,
      excludeSpecs,
      validatedFilesSpec,
      validatedIncludeSpecs,
      validatedExcludeSpecs,
      validatedFilesSpecBeforeSubstitution,
      validatedIncludeSpecsBeforeSubstitution,
      validatedExcludeSpecsBeforeSubstitution,
      isDefaultIncludeSpec
    };
  }
  function getFileNames(basePath2) {
    const fileNames = getFileNamesFromConfigSpecs(configFileSpecs, basePath2, options, host, extraFileExtensions);
    if (shouldReportNoInputFiles(fileNames, canJsonReportNoInputFiles(raw), resolutionStack)) {
      errors.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
    }
    return fileNames;
  }
  function getProjectReferences(basePath2) {
    let projectReferences;
    const referencesOfRaw = getPropFromRaw("references", (element) => typeof element === "object", "object");
    if (isArray(referencesOfRaw)) {
      for (const ref of referencesOfRaw) {
        if (typeof ref.path !== "string") {
          createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
        } else {
          (projectReferences || (projectReferences = [])).push({
            path: getNormalizedAbsolutePath(ref.path, basePath2),
            originalPath: ref.path,
            prepend: ref.prepend,
            circular: ref.circular
          });
        }
      }
    }
    return projectReferences;
  }
  function toPropValue(specResult) {
    return isArray(specResult) ? specResult : void 0;
  }
  function getSpecsFromRaw(prop) {
    return getPropFromRaw(prop, isString, "string");
  }
  function getPropFromRaw(prop, validateElement, elementTypeName) {
    if (hasProperty(raw, prop) && !isNullOrUndefined(raw[prop])) {
      if (isArray(raw[prop])) {
        const result = raw[prop];
        if (!sourceFile && !every(result, validateElement)) {
          errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, elementTypeName));
        }
        return result;
      } else {
        createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, "Array");
        return "not-array";
      }
    }
    return "no-prop";
  }
  function createCompilerDiagnosticOnlyIfJson(message, ...args) {
    if (!sourceFile) {
      errors.push(createCompilerDiagnostic(message, ...args));
    }
  }
}
function handleWatchOptionsConfigDirTemplateSubstitution(watchOptions, basePath) {
  return handleOptionConfigDirTemplateSubstitution(watchOptions, configDirTemplateSubstitutionWatchOptions, basePath);
}
function handleOptionConfigDirTemplateSubstitution(options, optionDeclarations2, basePath) {
  if (!options) return options;
  let result;
  for (const option of optionDeclarations2) {
    if (options[option.name] !== void 0) {
      const value = options[option.name];
      switch (option.type) {
        case "string":
          Debug.assert(option.isFilePath);
          if (startsWithConfigDirTemplate(value)) {
            setOptionValue(option, getSubstitutedPathWithConfigDirTemplate(value, basePath));
          }
          break;
        case "list":
          Debug.assert(option.element.isFilePath);
          const listResult = getSubstitutedStringArrayWithConfigDirTemplate(value, basePath);
          if (listResult) setOptionValue(option, listResult);
          break;
        case "object":
          Debug.assert(option.name === "paths");
          const objectResult = getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(value, basePath);
          if (objectResult) setOptionValue(option, objectResult);
          break;
        default:
          Debug.fail("option type not supported");
      }
    }
  }
  return result || options;
  function setOptionValue(option, value) {
    (result ?? (result = assign({}, options)))[option.name] = value;
  }
}
var configDirTemplate = `\${configDir}`;
function startsWithConfigDirTemplate(value) {
  return isString(value) && startsWith(
    value,
    configDirTemplate,
    /*ignoreCase*/
    true
  );
}
function getSubstitutedPathWithConfigDirTemplate(value, basePath) {
  return getNormalizedAbsolutePath(value.replace(configDirTemplate, "./"), basePath);
}
function getSubstitutedStringArrayWithConfigDirTemplate(list, basePath) {
  if (!list) return list;
  let result;
  list.forEach((element, index) => {
    if (!startsWithConfigDirTemplate(element)) return;
    (result ?? (result = list.slice()))[index] = getSubstitutedPathWithConfigDirTemplate(element, basePath);
  });
  return result;
}
function getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(mapLike, basePath) {
  let result;
  const ownKeys = getOwnKeys(mapLike);
  ownKeys.forEach((key) => {
    if (!isArray(mapLike[key])) return;
    const subStitution = getSubstitutedStringArrayWithConfigDirTemplate(mapLike[key], basePath);
    if (!subStitution) return;
    (result ?? (result = assign({}, mapLike)))[key] = subStitution;
  });
  return result;
}
function isErrorNoInputFiles(error) {
  return error.code === Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
}
function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }, configFileName) {
  return createCompilerDiagnostic(
    Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
    configFileName || "tsconfig.json",
    JSON.stringify(includeSpecs || []),
    JSON.stringify(excludeSpecs || [])
  );
}
function shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles, resolutionStack) {
  return fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
}
function isSolutionConfig(config) {
  return !config.fileNames.length && hasProperty(config.raw, "references");
}
function canJsonReportNoInputFiles(raw) {
  return !hasProperty(raw, "files") && !hasProperty(raw, "references");
}
function updateErrorForNoInputFiles(fileNames, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
  const existingErrors = configParseDiagnostics.length;
  if (shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles)) {
    configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
  } else {
    filterMutate(configParseDiagnostics, (error) => !isErrorNoInputFiles(error));
  }
  return existingErrors !== configParseDiagnostics.length;
}
function isSuccessfulParsedTsconfig(value) {
  return !!value.options;
}
function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
  var _a;
  basePath = normalizeSlashes(basePath);
  const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath);
  if (resolutionStack.includes(resolvedPath)) {
    errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> ")));
    return { raw: json || convertToObject(sourceFile, errors) };
  }
  const ownConfig = json ? parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
  if ((_a = ownConfig.options) == null ? void 0 : _a.paths) {
    ownConfig.options.pathsBasePath = basePath;
  }
  if (ownConfig.extendedConfigPath) {
    resolutionStack = resolutionStack.concat([resolvedPath]);
    const result = { options: {} };
    if (isString(ownConfig.extendedConfigPath)) {
      applyExtendedConfig(result, ownConfig.extendedConfigPath);
    } else {
      ownConfig.extendedConfigPath.forEach((extendedConfigPath) => applyExtendedConfig(result, extendedConfigPath));
    }
    if (result.include) ownConfig.raw.include = result.include;
    if (result.exclude) ownConfig.raw.exclude = result.exclude;
    if (result.files) ownConfig.raw.files = result.files;
    if (ownConfig.raw.compileOnSave === void 0 && result.compileOnSave) ownConfig.raw.compileOnSave = result.compileOnSave;
    if (sourceFile && result.extendedSourceFiles) sourceFile.extendedSourceFiles = arrayFrom(result.extendedSourceFiles.keys());
    ownConfig.options = assign(result.options, ownConfig.options);
    ownConfig.watchOptions = ownConfig.watchOptions && result.watchOptions ? assignWatchOptions(result, ownConfig.watchOptions) : ownConfig.watchOptions || result.watchOptions;
  }
  return ownConfig;
  function applyExtendedConfig(result, extendedConfigPath) {
    const extendedConfig = getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache, result);
    if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
      const extendsRaw = extendedConfig.raw;
      let relativeDifference;
      const setPropertyInResultIfNotUndefined = (propertyName) => {
        if (ownConfig.raw[propertyName]) return;
        if (extendsRaw[propertyName]) {
          result[propertyName] = map(extendsRaw[propertyName], (path) => startsWithConfigDirTemplate(path) || isRootedDiskPath(path) ? path : combinePaths(
            relativeDifference || (relativeDifference = convertToRelativePath(getDirectoryPath(extendedConfigPath), basePath, createGetCanonicalFileName(host.useCaseSensitiveFileNames))),
            path
          ));
        }
      };
      setPropertyInResultIfNotUndefined("include");
      setPropertyInResultIfNotUndefined("exclude");
      setPropertyInResultIfNotUndefined("files");
      if (extendsRaw.compileOnSave !== void 0) {
        result.compileOnSave = extendsRaw.compileOnSave;
      }
      assign(result.options, extendedConfig.options);
      result.watchOptions = result.watchOptions && extendedConfig.watchOptions ? assignWatchOptions(result, extendedConfig.watchOptions) : result.watchOptions || extendedConfig.watchOptions;
    }
  }
  function assignWatchOptions(result, watchOptions) {
    if (result.watchOptionsCopied) return assign(result.watchOptions, watchOptions);
    result.watchOptionsCopied = true;
    return assign({}, result.watchOptions, watchOptions);
  }
}
function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
  if (hasProperty(json, "excludes")) {
    errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
  }
  const options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
  const typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition, basePath, errors, configFileName);
  const watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
  json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
  const extendedConfigPath = json.extends || json.extends === "" ? getExtendsConfigPathOrArray(json.extends, host, basePath, configFileName, errors) : void 0;
  return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath };
}
function getExtendsConfigPathOrArray(value, host, basePath, configFileName, errors, propertyAssignment, valueExpression, sourceFile) {
  let extendedConfigPath;
  const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
  if (isString(value)) {
    extendedConfigPath = getExtendsConfigPath(
      value,
      host,
      newBase,
      errors,
      valueExpression,
      sourceFile
    );
  } else if (isArray(value)) {
    extendedConfigPath = [];
    for (let index = 0; index < value.length; index++) {
      const fileName = value[index];
      if (isString(fileName)) {
        extendedConfigPath = append(
          extendedConfigPath,
          getExtendsConfigPath(
            fileName,
            host,
            newBase,
            errors,
            valueExpression == null ? void 0 : valueExpression.elements[index],
            sourceFile
          )
        );
      } else {
        convertJsonOption(extendsOptionDeclaration.element, value, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile);
      }
    }
  } else {
    convertJsonOption(extendsOptionDeclaration, value, basePath, errors, propertyAssignment, valueExpression, sourceFile);
  }
  return extendedConfigPath;
}
function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
  const options = getDefaultCompilerOptions(configFileName);
  let typeAcquisition;
  let watchOptions;
  let extendedConfigPath;
  let rootCompilerOptions;
  const rootOptions = getTsconfigRootOptionsMap();
  const json = convertConfigFileToObject(
    sourceFile,
    errors,
    { rootOptions, onPropertySet }
  );
  if (!typeAcquisition) {
    typeAcquisition = getDefaultTypeAcquisition(configFileName);
  }
  if (rootCompilerOptions && json && json.compilerOptions === void 0) {
    errors.push(createDiagnosticForNodeInSourceFile(sourceFile, rootCompilerOptions[0], Diagnostics._0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file, getTextOfPropertyName(rootCompilerOptions[0])));
  }
  return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath };
  function onPropertySet(keyText, value, propertyAssignment, parentOption, option) {
    if (option && option !== extendsOptionDeclaration) value = convertJsonOption(option, value, basePath, errors, propertyAssignment, propertyAssignment.initializer, sourceFile);
    if (parentOption == null ? void 0 : parentOption.name) {
      if (option) {
        let currentOption;
        if (parentOption === compilerOptionsDeclaration) currentOption = options;
        else if (parentOption === watchOptionsDeclaration) currentOption = watchOptions ?? (watchOptions = {});
        else if (parentOption === typeAcquisitionDeclaration) currentOption = typeAcquisition ?? (typeAcquisition = getDefaultTypeAcquisition(configFileName));
        else Debug.fail("Unknown option");
        currentOption[option.name] = value;
      } else if (keyText && (parentOption == null ? void 0 : parentOption.extraKeyDiagnostics)) {
        if (parentOption.elementOptions) {
          errors.push(createUnknownOptionError(
            keyText,
            parentOption.extraKeyDiagnostics,
            /*unknownOptionErrorText*/
            void 0,
            propertyAssignment.name,
            sourceFile
          ));
        } else {
          errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, parentOption.extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
        }
      }
    } else if (parentOption === rootOptions) {
      if (option === extendsOptionDeclaration) {
        extendedConfigPath = getExtendsConfigPathOrArray(value, host, basePath, configFileName, errors, propertyAssignment, propertyAssignment.initializer, sourceFile);
      } else if (!option) {
        if (keyText === "excludes") {
          errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
        }
        if (find(commandOptionsWithoutBuild, (opt) => opt.name === keyText)) {
          rootCompilerOptions = append(rootCompilerOptions, propertyAssignment.name);
        }
      }
    }
  }
}
function getExtendsConfigPath(extendedConfig, host, basePath, errors, valueExpression, sourceFile) {
  extendedConfig = normalizeSlashes(extendedConfig);
  if (isRootedDiskPath(extendedConfig) || startsWith(extendedConfig, "./") || startsWith(extendedConfig, "../")) {
    let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath);
    if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ".json" /* Json */)) {
      extendedConfigPath = `${extendedConfigPath}.json`;
      if (!host.fileExists(extendedConfigPath)) {
        errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.File_0_not_found, extendedConfig));
        return void 0;
      }
    }
    return extendedConfigPath;
  }
  const resolved = nodeNextJsonConfigResolver(extendedConfig, combinePaths(basePath, "tsconfig.json"), host);
  if (resolved.resolvedModule) {
    return resolved.resolvedModule.resolvedFileName;
  }
  if (extendedConfig === "") {
    errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.Compiler_option_0_cannot_be_given_an_empty_string, "extends"));
  } else {
    errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.File_0_not_found, extendedConfig));
  }
  return void 0;
}
function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache, result) {
  const path = host.useCaseSensitiveFileNames ? extendedConfigPath : toFileNameLowerCase(extendedConfigPath);
  let value;
  let extendedResult;
  let extendedConfig;
  if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
    ({ extendedResult, extendedConfig } = value);
  } else {
    extendedResult = readJsonConfigFile(extendedConfigPath, (path2) => host.readFile(path2));
    if (!extendedResult.parseDiagnostics.length) {
      extendedConfig = parseConfig(
        /*json*/
        void 0,
        extendedResult,
        host,
        getDirectoryPath(extendedConfigPath),
        getBaseFileName(extendedConfigPath),
        resolutionStack,
        errors,
        extendedConfigCache
      );
    }
    if (extendedConfigCache) {
      extendedConfigCache.set(path, { extendedResult, extendedConfig });
    }
  }
  if (sourceFile) {
    (result.extendedSourceFiles ?? (result.extendedSourceFiles = /* @__PURE__ */ new Set())).add(extendedResult.fileName);
    if (extendedResult.extendedSourceFiles) {
      for (const extenedSourceFile of extendedResult.extendedSourceFiles) {
        result.extendedSourceFiles.add(extenedSourceFile);
      }
    }
  }
  if (extendedResult.parseDiagnostics.length) {
    errors.push(...extendedResult.parseDiagnostics);
    return void 0;
  }
  return extendedConfig;
}
function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
  if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) {
    return false;
  }
  const result = convertJsonOption(compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
  return typeof result === "boolean" && result;
}
function getDefaultCompilerOptions(configFileName) {
  const options = configFileName && getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } : {};
  return options;
}
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
  const options = getDefaultCompilerOptions(configFileName);
  convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, compilerOptionsDidYouMeanDiagnostics, errors);
  if (configFileName) {
    options.configFilePath = normalizeSlashes(configFileName);
  }
  return options;
}
function getDefaultTypeAcquisition(configFileName) {
  return { enable: !!configFileName && getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
}
function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
  const options = getDefaultTypeAcquisition(configFileName);
  convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), jsonOptions, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
  return options;
}
function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
  return convertOptionsFromJson(
    getCommandLineWatchOptionsMap(),
    jsonOptions,
    basePath,
    /*defaultOptions*/
    void 0,
    watchOptionsDidYouMeanDiagnostics,
    errors
  );
}
function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
  if (!jsonOptions) {
    return;
  }
  for (const id in jsonOptions) {
    const opt = optionsNameMap.get(id);
    if (opt) {
      (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
    } else {
      errors.push(createUnknownOptionError(id, diagnostics));
    }
  }
  return defaultOptions;
}
function createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, message, ...args) {
  return sourceFile && node ? createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args) : createCompilerDiagnostic(message, ...args);
}
function convertJsonOption(opt, value, basePath, errors, propertyAssignment, valueExpression, sourceFile) {
  if (opt.isCommandLineOnly) {
    errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, propertyAssignment == null ? void 0 : propertyAssignment.name, Diagnostics.Option_0_can_only_be_specified_on_command_line, opt.name));
    return void 0;
  }
  if (isCompilerOptionsValue(opt, value)) {
    const optType = opt.type;
    if (optType === "list" && isArray(value)) {
      return convertJsonOptionOfListType(opt, value, basePath, errors, propertyAssignment, valueExpression, sourceFile);
    } else if (optType === "listOrElement") {
      return isArray(value) ? convertJsonOptionOfListType(opt, value, basePath, errors, propertyAssignment, valueExpression, sourceFile) : convertJsonOption(opt.element, value, basePath, errors, propertyAssignment, valueExpression, sourceFile);
    } else if (!isString(opt.type)) {
      return convertJsonOptionOfCustomType(opt, value, errors, valueExpression, sourceFile);
    }
    const validatedValue = validateJsonOptionValue(opt, value, errors, valueExpression, sourceFile);
    return isNullOrUndefined(validatedValue) ? validatedValue : normalizeNonListOptionValue(opt, basePath, validatedValue);
  } else {
    errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
  }
}
function normalizeNonListOptionValue(option, basePath, value) {
  if (option.isFilePath) {
    value = normalizeSlashes(value);
    value = !startsWithConfigDirTemplate(value) ? getNormalizedAbsolutePath(value, basePath) : value;
    if (value === "") {
      value = ".";
    }
  }
  return value;
}
function validateJsonOptionValue(opt, value, errors, valueExpression, sourceFile) {
  var _a;
  if (isNullOrUndefined(value)) return void 0;
  const d = (_a = opt.extraValidation) == null ? void 0 : _a.call(opt, value);
  if (!d) return value;
  errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, ...d));
  return void 0;
}
function convertJsonOptionOfCustomType(opt, value, errors, valueExpression, sourceFile) {
  if (isNullOrUndefined(value)) return void 0;
  const key = value.toLowerCase();
  const val = opt.type.get(key);
  if (val !== void 0) {
    return validateJsonOptionValue(opt, val, errors, valueExpression, sourceFile);
  } else {
    errors.push(createDiagnosticForInvalidCustomType(opt, (message, ...args) => createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, message, ...args)));
  }
}
function convertJsonOptionOfListType(option, values, basePath, errors, propertyAssignment, valueExpression, sourceFile) {
  return filter(map(values, (v, index) => convertJsonOption(option.element, v, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile)), (v) => option.listPreserveFalsyValues ? true : !!v);
}
var invalidTrailingRecursionPattern = /(?:^|\/)\*\*\/?$/;
var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions = emptyArray) {
  basePath = normalizePath(basePath);
  const keyMapper = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
  const literalFileMap = /* @__PURE__ */ new Map();
  const wildcardFileMap = /* @__PURE__ */ new Map();
  const wildCardJsonFileMap = /* @__PURE__ */ new Map();
  const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = configFileSpecs;
  const supportedExtensions = getSupportedExtensions(options, extraFileExtensions);
  const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
  if (validatedFilesSpec) {
    for (const fileName of validatedFilesSpec) {
      const file = getNormalizedAbsolutePath(fileName, basePath);
      literalFileMap.set(keyMapper(file), file);
    }
  }
  let jsonOnlyIncludeRegexes;
  if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
    for (const file of host.readDirectory(
      basePath,
      flatten(supportedExtensionsWithJsonIfResolveJsonModule),
      validatedExcludeSpecs,
      validatedIncludeSpecs,
      /*depth*/
      void 0
    )) {
      if (fileExtensionIs(file, ".json" /* Json */)) {
        if (!jsonOnlyIncludeRegexes) {
          const includes = validatedIncludeSpecs.filter((s) => endsWith(s, ".json" /* Json */));
          const includeFilePatterns = map(getRegularExpressionsForWildcards(includes, basePath, "files"), (pattern) => `^${pattern}$`);
          jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, host.useCaseSensitiveFileNames)) : emptyArray;
        }
        const includeIndex = findIndex(jsonOnlyIncludeRegexes, (re) => re.test(file));
        if (includeIndex !== -1) {
          const key2 = keyMapper(file);
          if (!literalFileMap.has(key2) && !wildCardJsonFileMap.has(key2)) {
            wildCardJsonFileMap.set(key2, file);
          }
        }
        continue;
      }
      if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
        continue;
      }
      removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
      const key = keyMapper(file);
      if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
        wildcardFileMap.set(key, file);
      }
    }
  }
  const literalFiles = arrayFrom(literalFileMap.values());
  const wildcardFiles = arrayFrom(wildcardFileMap.values());
  return literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values()));
}
function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames2, currentDirectory) {
  const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec;
  if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false;
  basePath = normalizePath(basePath);
  const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames2);
  if (validatedFilesSpec) {
    for (const fileName of validatedFilesSpec) {
      if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) return false;
    }
  }
  return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath);
}
function invalidDotDotAfterRecursiveWildcard(s) {
  const wildcardIndex = startsWith(s, "**/") ? 0 : s.indexOf("/**/");
  if (wildcardIndex === -1) {
    return false;
  }
  const lastDotIndex = endsWith(s, "/..") ? s.length : s.lastIndexOf("/../");
  return lastDotIndex > wildcardIndex;
}
function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory) {
  return matchesExcludeWorker(
    pathToCheck,
    filter(excludeSpecs, (spec) => !invalidDotDotAfterRecursiveWildcard(spec)),
    useCaseSensitiveFileNames2,
    currentDirectory
  );
}
function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath) {
  const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude");
  const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames2);
  if (!excludeRegex) return false;
  if (excludeRegex.test(pathToCheck)) return true;
  return !hasExtension(pathToCheck) && excludeRegex.test(ensureTrailingDirectorySeparator(pathToCheck));
}
function validateSpecs(specs, errors, disallowTrailingRecursion, jsonSourceFile, specKey) {
  return specs.filter((spec) => {
    if (!isString(spec)) return false;
    const diag2 = specToDiagnostic(spec, disallowTrailingRecursion);
    if (diag2 !== void 0) {
      errors.push(createDiagnostic(...diag2));
    }
    return diag2 === void 0;
  });
  function createDiagnostic(message, spec) {
    const element = getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
    return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(jsonSourceFile, element, message, spec);
  }
}
function specToDiagnostic(spec, disallowTrailingRecursion) {
  Debug.assert(typeof spec === "string");
  if (disallowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
    return [Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
  } else if (invalidDotDotAfterRecursiveWildcard(spec)) {
    return [Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
  }
}
function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, basePath, useCaseSensitiveFileNames2) {
  const rawExcludeRegex = getRegularExpressionForWildcard(exclude, basePath, "exclude");
  const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames2 ? "" : "i");
  const wildcardDirectories = {};
  const wildCardKeyToPath = /* @__PURE__ */ new Map();
  if (include !== void 0) {
    const recursiveKeys = [];
    for (const file of include) {
      const spec = normalizePath(combinePaths(basePath, file));
      if (excludeRegex && excludeRegex.test(spec)) {
        continue;
      }
      const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2);
      if (match) {
        const { key, path, flags } = match;
        const existingPath = wildCardKeyToPath.get(key);
        const existingFlags = existingPath !== void 0 ? wildcardDirectories[existingPath] : void 0;
        if (existingFlags === void 0 || existingFlags < flags) {
          wildcardDirectories[existingPath !== void 0 ? existingPath : path] = flags;
          if (existingPath === void 0) wildCardKeyToPath.set(key, path);
          if (flags === 1 /* Recursive */) {
            recursiveKeys.push(key);
          }
        }
      }
    }
    for (const path in wildcardDirectories) {
      if (hasProperty(wildcardDirectories, path)) {
        for (const recursiveKey of recursiveKeys) {
          const key = toCanonicalKey(path, useCaseSensitiveFileNames2);
          if (key !== recursiveKey && containsPath(recursiveKey, key, basePath, !useCaseSensitiveFileNames2)) {
            delete wildcardDirectories[path];
          }
        }
      }
    }
  }
  return wildcardDirectories;
}
function toCanonicalKey(path, useCaseSensitiveFileNames2) {
  return useCaseSensitiveFileNames2 ? path : toFileNameLowerCase(path);
}
function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2) {
  const match = wildcardDirectoryPattern.exec(spec);
  if (match) {
    const questionWildcardIndex = spec.indexOf("?");
    const starWildcardIndex = spec.indexOf("*");
    const lastDirectorySeperatorIndex = spec.lastIndexOf(directorySeparator);
    return {
      key: toCanonicalKey(match[0], useCaseSensitiveFileNames2),
      path: match[0],
      flags: questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex || starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex ? 1 /* Recursive */ : 0 /* None */
    };
  }
  if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) {
    const path = removeTrailingDirectorySeparator(spec);
    return {
      key: toCanonicalKey(path, useCaseSensitiveFileNames2),
      path,
      flags: 1 /* Recursive */
    };
  }
  return void 0;
}
function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
  const extensionGroup = forEach(extensions, (group2) => fileExtensionIsOneOf(file, group2) ? group2 : void 0);
  if (!extensionGroup) {
    return false;
  }
  for (const ext of extensionGroup) {
    if (fileExtensionIs(file, ext) && (ext !== ".ts" /* Ts */ || !fileExtensionIs(file, ".d.ts" /* Dts */))) {
      return false;
    }
    const higherPriorityPath = keyMapper(changeExtension(file, ext));
    if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
      if (ext === ".d.ts" /* Dts */ && (fileExtensionIs(file, ".js" /* Js */) || fileExtensionIs(file, ".jsx" /* Jsx */))) {
        continue;
      }
      return true;
    }
  }
  return false;
}
function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
  const extensionGroup = forEach(extensions, (group2) => fileExtensionIsOneOf(file, group2) ? group2 : void 0);
  if (!extensionGroup) {
    return;
  }
  for (let i = extensionGroup.length - 1; i >= 0; i--) {
    const ext = extensionGroup[i];
    if (fileExtensionIs(file, ext)) {
      return;
    }
    const lowerPriorityPath = keyMapper(changeExtension(file, ext));
    wildcardFiles.delete(lowerPriorityPath);
  }
}
function getDefaultValueForOption(option) {
  switch (option.type) {
    case "number":
      return 1;
    case "boolean":
      return true;
    case "string":
      const defaultValue = option.defaultValueDescription;
      return option.isFilePath ? `./${defaultValue && typeof defaultValue === "string" ? defaultValue : ""}` : "";
    case "list":
      return [];
    case "listOrElement":
      return getDefaultValueForOption(option.element);
    case "object":
      return {};
    default:
      const value = firstOrUndefinedIterator(option.type.keys());
      if (value !== void 0) return value;
      return Debug.fail("Expected 'option.type' to have entries.");
  }
}

// src/compiler/moduleNameResolver.ts
function trace(host, message, ...args) {
  host.trace(formatMessage(message, ...args));
}
function isTraceEnabled(compilerOptions, host) {
  return !!compilerOptions.traceResolution && host.trace !== void 0;
}
function withPackageId(packageInfo, r, state) {
  let packageId;
  if (r && packageInfo) {
    const packageJsonContent = packageInfo.contents.packageJsonContent;
    if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
      packageId = {
        name: packageJsonContent.name,
        subModuleName: r.path.slice(packageInfo.packageDirectory.length + directorySeparator.length),
        version: packageJsonContent.version,
        peerDependencies: getPeerDependenciesOfPackageJsonInfo(packageInfo, state)
      };
    }
  }
  return r && { path: r.path, extension: r.ext, packageId, resolvedUsingTsExtension: r.resolvedUsingTsExtension };
}
function noPackageId(r) {
  return withPackageId(
    /*packageInfo*/
    void 0,
    r,
    /*state*/
    void 0
  );
}
function removeIgnoredPackageId(r) {
  if (r) {
    Debug.assert(r.packageId === void 0);
    return { path: r.path, ext: r.extension, resolvedUsingTsExtension: r.resolvedUsingTsExtension };
  }
}
function formatExtensions(extensions) {
  const result = [];
  if (extensions & 1 /* TypeScript */) result.push("TypeScript");
  if (extensions & 2 /* JavaScript */) result.push("JavaScript");
  if (extensions & 4 /* Declaration */) result.push("Declaration");
  if (extensions & 8 /* Json */) result.push("JSON");
  return result.join(", ");
}
function resolvedTypeScriptOnly(resolved) {
  if (!resolved) {
    return void 0;
  }
  Debug.assert(extensionIsTS(resolved.extension));
  return { fileName: resolved.path, packageId: resolved.packageId };
}
function createResolvedModuleWithFailedLookupLocationsHandlingSymlink(moduleName, resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state, cache, alternateResult) {
  if (!state.resultFromCache && !state.compilerOptions.preserveSymlinks && resolved && isExternalLibraryImport && !resolved.originalPath && !isExternalModuleNameRelative(moduleName)) {
    const { resolvedFileName, originalPath } = getOriginalAndResolvedFileName(resolved.path, state.host, state.traceEnabled);
    if (originalPath) resolved = { ...resolved, path: resolvedFileName, originalPath };
  }
  return createResolvedModuleWithFailedLookupLocations(
    resolved,
    isExternalLibraryImport,
    failedLookupLocations,
    affectingLocations,
    diagnostics,
    state.resultFromCache,
    cache,
    alternateResult
  );
}
function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache, cache, alternateResult) {
  if (resultFromCache) {
    if (!(cache == null ? void 0 : cache.isReadonly)) {
      resultFromCache.failedLookupLocations = updateResolutionField(resultFromCache.failedLookupLocations, failedLookupLocations);
      resultFromCache.affectingLocations = updateResolutionField(resultFromCache.affectingLocations, affectingLocations);
      resultFromCache.resolutionDiagnostics = updateResolutionField(resultFromCache.resolutionDiagnostics, diagnostics);
      return resultFromCache;
    } else {
      return {
        ...resultFromCache,
        failedLookupLocations: initializeResolutionFieldForReadonlyCache(resultFromCache.failedLookupLocations, failedLookupLocations),
        affectingLocations: initializeResolutionFieldForReadonlyCache(resultFromCache.affectingLocations, affectingLocations),
        resolutionDiagnostics: initializeResolutionFieldForReadonlyCache(resultFromCache.resolutionDiagnostics, diagnostics)
      };
    }
  }
  return {
    resolvedModule: resolved && {
      resolvedFileName: resolved.path,
      originalPath: resolved.originalPath === true ? void 0 : resolved.originalPath,
      extension: resolved.extension,
      isExternalLibraryImport,
      packageId: resolved.packageId,
      resolvedUsingTsExtension: !!resolved.resolvedUsingTsExtension
    },
    failedLookupLocations: initializeResolutionField(failedLookupLocations),
    affectingLocations: initializeResolutionField(affectingLocations),
    resolutionDiagnostics: initializeResolutionField(diagnostics),
    alternateResult
  };
}
function initializeResolutionField(value) {
  return value.length ? value : void 0;
}
function updateResolutionField(to, value) {
  if (!(value == null ? void 0 : value.length)) return to;
  if (!(to == null ? void 0 : to.length)) return value;
  to.push(...value);
  return to;
}
function initializeResolutionFieldForReadonlyCache(fromCache, value) {
  if (!(fromCache == null ? void 0 : fromCache.length)) return initializeResolutionField(value);
  if (!value.length) return fromCache.slice();
  return [...fromCache, ...value];
}
function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
  if (!hasProperty(jsonContent, fieldName)) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName);
    }
    return;
  }
  const value = jsonContent[fieldName];
  if (typeof value !== typeOfTag || value === null) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value);
    }
    return;
  }
  return value;
}
function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
  const fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
  if (fileName === void 0) {
    return;
  }
  if (!fileName) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_had_a_falsy_0_field, fieldName);
    }
    return;
  }
  const path = normalizePath(combinePaths(baseDirectory, fileName));
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
  }
  return path;
}
function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
  return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
}
function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
  return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
}
function readPackageJsonMainField(jsonContent, baseDirectory, state) {
  return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
}
function readPackageJsonTypesVersionsField(jsonContent, state) {
  const typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
  if (typesVersions === void 0) return;
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
  }
  return typesVersions;
}
function readPackageJsonTypesVersionPaths(jsonContent, state) {
  const typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
  if (typesVersions === void 0) return;
  if (state.traceEnabled) {
    for (const key in typesVersions) {
      if (hasProperty(typesVersions, key) && !VersionRange.tryParse(key)) {
        trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
      }
    }
  }
  const result = getPackageJsonTypesVersionsPaths(typesVersions);
  if (!result) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, versionMajorMinor);
    }
    return;
  }
  const { version: bestVersionKey, paths: bestVersionPaths } = result;
  if (typeof bestVersionPaths !== "object") {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "object", typeof bestVersionPaths);
    }
    return;
  }
  return result;
}
var typeScriptVersion;
function getPackageJsonTypesVersionsPaths(typesVersions) {
  if (!typeScriptVersion) typeScriptVersion = new Version(version);
  for (const key in typesVersions) {
    if (!hasProperty(typesVersions, key)) continue;
    const keyRange = VersionRange.tryParse(key);
    if (keyRange === void 0) {
      continue;
    }
    if (keyRange.test(typeScriptVersion)) {
      return { version: key, paths: typesVersions[key] };
    }
  }
}
function getEffectiveTypeRoots(options, host) {
  if (options.typeRoots) {
    return options.typeRoots;
  }
  let currentDirectory;
  if (options.configFilePath) {
    currentDirectory = getDirectoryPath(options.configFilePath);
  } else if (host.getCurrentDirectory) {
    currentDirectory = host.getCurrentDirectory();
  }
  if (currentDirectory !== void 0) {
    return getDefaultTypeRoots(currentDirectory);
  }
}
function getDefaultTypeRoots(currentDirectory) {
  let typeRoots;
  forEachAncestorDirectory(normalizePath(currentDirectory), (directory) => {
    const atTypes = combinePaths(directory, nodeModulesAtTypes);
    (typeRoots ?? (typeRoots = [])).push(atTypes);
  });
  return typeRoots;
}
var nodeModulesAtTypes = combinePaths("node_modules", "@types");
function arePathsEqual(path1, path2, host) {
  const useCaseSensitiveFileNames2 = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames;
  return comparePaths(path1, path2, !useCaseSensitiveFileNames2) === 0 /* EqualTo */;
}
function getOriginalAndResolvedFileName(fileName, host, traceEnabled) {
  const resolvedFileName = realPath(fileName, host, traceEnabled);
  const pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host);
  return {
    // If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames
    resolvedFileName: pathsAreEqual ? fileName : resolvedFileName,
    originalPath: pathsAreEqual ? void 0 : fileName
  };
}
function getCandidateFromTypeRoot(typeRoot, typeReferenceDirectiveName, moduleResolutionState) {
  const nameForLookup = endsWith(typeRoot, "/node_modules/@types") || endsWith(typeRoot, "/node_modules/@types/") ? mangleScopedPackageNameWithTrace(typeReferenceDirectiveName, moduleResolutionState) : typeReferenceDirectiveName;
  return combinePaths(typeRoot, nameForLookup);
}
function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache, resolutionMode) {
  Debug.assert(typeof typeReferenceDirectiveName === "string", "Non-string value passed to `ts.resolveTypeReferenceDirective`, likely by a wrapping package working with an outdated `resolveTypeReferenceDirectives` signature. This is probably not a problem in TS itself.");
  const traceEnabled = isTraceEnabled(options, host);
  if (redirectedReference) {
    options = redirectedReference.commandLine.options;
  }
  const containingDirectory = containingFile ? getDirectoryPath(containingFile) : void 0;
  let result = containingDirectory ? cache == null ? void 0 : cache.getFromDirectoryCache(typeReferenceDirectiveName, resolutionMode, containingDirectory, redirectedReference) : void 0;
  if (!result && containingDirectory && !isExternalModuleNameRelative(typeReferenceDirectiveName)) {
    result = cache == null ? void 0 : cache.getFromNonRelativeNameCache(typeReferenceDirectiveName, resolutionMode, containingDirectory, redirectedReference);
  }
  if (result) {
    if (traceEnabled) {
      trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile);
      if (redirectedReference) trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
      trace(host, Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory);
      traceResult(result);
    }
    return result;
  }
  const typeRoots = getEffectiveTypeRoots(options, host);
  if (traceEnabled) {
    if (containingFile === void 0) {
      if (typeRoots === void 0) {
        trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
      } else {
        trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
      }
    } else {
      if (typeRoots === void 0) {
        trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
      } else {
        trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
      }
    }
    if (redirectedReference) {
      trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
    }
  }
  const failedLookupLocations = [];
  const affectingLocations = [];
  let features = getNodeResolutionFeatures(options);
  if (resolutionMode !== void 0) {
    features |= 30 /* AllFeatures */;
  }
  const moduleResolution = getEmitModuleResolutionKind(options);
  if (resolutionMode === 99 /* ESNext */ && (3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */)) {
    features |= 32 /* EsmMode */;
  }
  const conditions = features & 8 /* Exports */ ? getConditions(options, resolutionMode) : [];
  const diagnostics = [];
  const moduleResolutionState = {
    compilerOptions: options,
    host,
    traceEnabled,
    failedLookupLocations,
    affectingLocations,
    packageJsonInfoCache: cache,
    features,
    conditions,
    requestContainingDirectory: containingDirectory,
    reportDiagnostic: (diag2) => void diagnostics.push(diag2),
    isConfigLookup: false,
    candidateIsFromPackageJsonField: false,
    resolvedPackageDirectory: false
  };
  let resolved = primaryLookup();
  let primary = true;
  if (!resolved) {
    resolved = secondaryLookup();
    primary = false;
  }
  let resolvedTypeReferenceDirective;
  if (resolved) {
    const { fileName, packageId } = resolved;
    let resolvedFileName = fileName, originalPath;
    if (!options.preserveSymlinks) ({ resolvedFileName, originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled));
    resolvedTypeReferenceDirective = {
      primary,
      resolvedFileName,
      originalPath,
      packageId,
      isExternalLibraryImport: pathContainsNodeModules(fileName)
    };
  }
  result = {
    resolvedTypeReferenceDirective,
    failedLookupLocations: initializeResolutionField(failedLookupLocations),
    affectingLocations: initializeResolutionField(affectingLocations),
    resolutionDiagnostics: initializeResolutionField(diagnostics)
  };
  if (containingDirectory && cache && !cache.isReadonly) {
    cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(
      typeReferenceDirectiveName,
      /*mode*/
      resolutionMode,
      result
    );
    if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) {
      cache.getOrCreateCacheForNonRelativeName(typeReferenceDirectiveName, resolutionMode, redirectedReference).set(containingDirectory, result);
    }
  }
  if (traceEnabled) traceResult(result);
  return result;
  function traceResult(result2) {
    var _a;
    if (!((_a = result2.resolvedTypeReferenceDirective) == null ? void 0 : _a.resolvedFileName)) {
      trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
    } else if (result2.resolvedTypeReferenceDirective.packageId) {
      trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result2.resolvedTypeReferenceDirective.resolvedFileName, packageIdToString(result2.resolvedTypeReferenceDirective.packageId), result2.resolvedTypeReferenceDirective.primary);
    } else {
      trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result2.resolvedTypeReferenceDirective.resolvedFileName, result2.resolvedTypeReferenceDirective.primary);
    }
  }
  function primaryLookup() {
    if (typeRoots && typeRoots.length) {
      if (traceEnabled) {
        trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
      }
      return firstDefined(typeRoots, (typeRoot) => {
        const candidate = getCandidateFromTypeRoot(typeRoot, typeReferenceDirectiveName, moduleResolutionState);
        const directoryExists = directoryProbablyExists(typeRoot, host);
        if (!directoryExists && traceEnabled) {
          trace(host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, typeRoot);
        }
        if (options.typeRoots) {
          const resolvedFromFile = loadModuleFromFile(4 /* Declaration */, candidate, !directoryExists, moduleResolutionState);
          if (resolvedFromFile) {
            const packageDirectory = parseNodeModuleFromPath(resolvedFromFile.path);
            const packageInfo = packageDirectory ? getPackageJsonInfo(
              packageDirectory,
              /*onlyRecordFailures*/
              false,
              moduleResolutionState
            ) : void 0;
            return resolvedTypeScriptOnly(withPackageId(packageInfo, resolvedFromFile, moduleResolutionState));
          }
        }
        return resolvedTypeScriptOnly(
          loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, moduleResolutionState)
        );
      });
    } else {
      if (traceEnabled) {
        trace(host, Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
      }
    }
  }
  function secondaryLookup() {
    const initialLocationForSecondaryLookup = containingFile && getDirectoryPath(containingFile);
    if (initialLocationForSecondaryLookup !== void 0) {
      let result2;
      if (!options.typeRoots || !endsWith(containingFile, inferredTypesContainingFile)) {
        if (traceEnabled) {
          trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
        }
        if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) {
          const searchResult = loadModuleFromNearestNodeModulesDirectory(
            4 /* Declaration */,
            typeReferenceDirectiveName,
            initialLocationForSecondaryLookup,
            moduleResolutionState,
            /*cache*/
            void 0,
            /*redirectedReference*/
            void 0
          );
          result2 = searchResult && searchResult.value;
        } else {
          const { path: candidate } = normalizePathForCJSResolution(initialLocationForSecondaryLookup, typeReferenceDirectiveName);
          result2 = nodeLoadModuleByRelativeName(
            4 /* Declaration */,
            candidate,
            /*onlyRecordFailures*/
            false,
            moduleResolutionState,
            /*considerPackageJson*/
            true
          );
        }
      } else if (traceEnabled) {
        trace(host, Diagnostics.Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_node_modules_folder);
      }
      return resolvedTypeScriptOnly(result2);
    } else {
      if (traceEnabled) {
        trace(host, Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
      }
    }
  }
}
function getNodeResolutionFeatures(options) {
  let features = 0 /* None */;
  switch (getEmitModuleResolutionKind(options)) {
    case 3 /* Node16 */:
      features = 30 /* Node16Default */;
      break;
    case 99 /* NodeNext */:
      features = 30 /* NodeNextDefault */;
      break;
    case 100 /* Bundler */:
      features = 30 /* BundlerDefault */;
      break;
  }
  if (options.resolvePackageJsonExports) {
    features |= 8 /* Exports */;
  } else if (options.resolvePackageJsonExports === false) {
    features &= ~8 /* Exports */;
  }
  if (options.resolvePackageJsonImports) {
    features |= 2 /* Imports */;
  } else if (options.resolvePackageJsonImports === false) {
    features &= ~2 /* Imports */;
  }
  return features;
}
function getConditions(options, resolutionMode) {
  const moduleResolution = getEmitModuleResolutionKind(options);
  if (resolutionMode === void 0) {
    if (moduleResolution === 100 /* Bundler */) {
      resolutionMode = 99 /* ESNext */;
    } else if (moduleResolution === 2 /* Node10 */) {
      return [];
    }
  }
  const conditions = resolutionMode === 99 /* ESNext */ ? ["import"] : ["require"];
  if (!options.noDtsResolution) {
    conditions.push("types");
  }
  if (moduleResolution !== 100 /* Bundler */) {
    conditions.push("node");
  }
  return concatenate(conditions, options.customConditions);
}
function getAutomaticTypeDirectiveNames(options, host) {
  if (options.types) {
    return options.types;
  }
  const result = [];
  if (host.directoryExists && host.getDirectories) {
    const typeRoots = getEffectiveTypeRoots(options, host);
    if (typeRoots) {
      for (const root of typeRoots) {
        if (host.directoryExists(root)) {
          for (const typeDirectivePath of host.getDirectories(root)) {
            const normalized = normalizePath(typeDirectivePath);
            const packageJsonPath = combinePaths(root, normalized, "package.json");
            const isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
            if (!isNotNeededPackage) {
              const baseFileName = getBaseFileName(normalized);
              if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
                result.push(baseFileName);
              }
            }
          }
        }
      }
    }
  }
  return result;
}
function isPackageJsonInfo(entry) {
  return !!(entry == null ? void 0 : entry.contents);
}
function isMissingPackageJsonInfo(entry) {
  return !!entry && !entry.contents;
}
function compilerOptionValueToString(value) {
  var _a;
  if (value === null || typeof value !== "object") {
    return "" + value;
  }
  if (isArray(value)) {
    return `[${(_a = value.map((e) => compilerOptionValueToString(e))) == null ? void 0 : _a.join(",")}]`;
  }
  let str = "{";
  for (const key in value) {
    if (hasProperty(value, key)) {
      str += `${key}: ${compilerOptionValueToString(value[key])}`;
    }
  }
  return str + "}";
}
function getKeyForCompilerOptions(options, affectingOptionDeclarations) {
  return affectingOptionDeclarations.map((option) => compilerOptionValueToString(getCompilerOptionValue(options, option))).join("|") + `|${options.pathsBasePath}`;
}
function createCacheWithRedirects(ownOptions, optionsToRedirectsKey) {
  const redirectsMap = /* @__PURE__ */ new Map();
  const redirectsKeyToMap = /* @__PURE__ */ new Map();
  let ownMap = /* @__PURE__ */ new Map();
  if (ownOptions) redirectsMap.set(ownOptions, ownMap);
  return {
    getMapOfCacheRedirects,
    getOrCreateMapOfCacheRedirects,
    update,
    clear: clear2,
    getOwnMap: () => ownMap
  };
  function getMapOfCacheRedirects(redirectedReference) {
    return redirectedReference ? getOrCreateMap(
      redirectedReference.commandLine.options,
      /*create*/
      false
    ) : ownMap;
  }
  function getOrCreateMapOfCacheRedirects(redirectedReference) {
    return redirectedReference ? getOrCreateMap(
      redirectedReference.commandLine.options,
      /*create*/
      true
    ) : ownMap;
  }
  function update(newOptions) {
    if (ownOptions !== newOptions) {
      if (ownOptions) ownMap = getOrCreateMap(
        newOptions,
        /*create*/
        true
      );
      else redirectsMap.set(newOptions, ownMap);
      ownOptions = newOptions;
    }
  }
  function getOrCreateMap(redirectOptions, create) {
    let result = redirectsMap.get(redirectOptions);
    if (result) return result;
    const key = getRedirectsCacheKey(redirectOptions);
    result = redirectsKeyToMap.get(key);
    if (!result) {
      if (ownOptions) {
        const ownKey = getRedirectsCacheKey(ownOptions);
        if (ownKey === key) result = ownMap;
        else if (!redirectsKeyToMap.has(ownKey)) redirectsKeyToMap.set(ownKey, ownMap);
      }
      if (create) result ?? (result = /* @__PURE__ */ new Map());
      if (result) redirectsKeyToMap.set(key, result);
    }
    if (result) redirectsMap.set(redirectOptions, result);
    return result;
  }
  function clear2() {
    const ownKey = ownOptions && optionsToRedirectsKey.get(ownOptions);
    ownMap.clear();
    redirectsMap.clear();
    optionsToRedirectsKey.clear();
    redirectsKeyToMap.clear();
    if (ownOptions) {
      if (ownKey) optionsToRedirectsKey.set(ownOptions, ownKey);
      redirectsMap.set(ownOptions, ownMap);
    }
  }
  function getRedirectsCacheKey(options) {
    let result = optionsToRedirectsKey.get(options);
    if (!result) {
      optionsToRedirectsKey.set(options, result = getKeyForCompilerOptions(options, moduleResolutionOptionDeclarations));
    }
    return result;
  }
}
function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) {
  let cache;
  return { getPackageJsonInfo: getPackageJsonInfo2, setPackageJsonInfo, clear: clear2, getInternalMap };
  function getPackageJsonInfo2(packageJsonPath) {
    return cache == null ? void 0 : cache.get(toPath(packageJsonPath, currentDirectory, getCanonicalFileName));
  }
  function setPackageJsonInfo(packageJsonPath, info) {
    (cache || (cache = /* @__PURE__ */ new Map())).set(toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info);
  }
  function clear2() {
    cache = void 0;
  }
  function getInternalMap() {
    return cache;
  }
}
function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
  const cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
  let result = cache.get(key);
  if (!result) {
    result = create();
    cache.set(key, result);
  }
  return result;
}
function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, options, optionsToRedirectsKey) {
  const directoryToModuleNameMap = createCacheWithRedirects(options, optionsToRedirectsKey);
  return {
    getFromDirectoryCache,
    getOrCreateCacheForDirectory,
    clear: clear2,
    update,
    directoryToModuleNameMap
  };
  function clear2() {
    directoryToModuleNameMap.clear();
  }
  function update(options2) {
    directoryToModuleNameMap.update(options2);
  }
  function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
    const path = toPath(directoryName, currentDirectory, getCanonicalFileName);
    return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, () => createModeAwareCache());
  }
  function getFromDirectoryCache(name, mode, directoryName, redirectedReference) {
    var _a, _b;
    const path = toPath(directoryName, currentDirectory, getCanonicalFileName);
    return (_b = (_a = directoryToModuleNameMap.getMapOfCacheRedirects(redirectedReference)) == null ? void 0 : _a.get(path)) == null ? void 0 : _b.get(name, mode);
  }
}
function createModeAwareCacheKey(specifier, mode) {
  return mode === void 0 ? specifier : `${mode}|${specifier}`;
}
function createModeAwareCache() {
  const underlying = /* @__PURE__ */ new Map();
  const memoizedReverseKeys = /* @__PURE__ */ new Map();
  const cache = {
    get(specifier, mode) {
      return underlying.get(getUnderlyingCacheKey(specifier, mode));
    },
    set(specifier, mode, value) {
      underlying.set(getUnderlyingCacheKey(specifier, mode), value);
      return cache;
    },
    delete(specifier, mode) {
      underlying.delete(getUnderlyingCacheKey(specifier, mode));
      return cache;
    },
    has(specifier, mode) {
      return underlying.has(getUnderlyingCacheKey(specifier, mode));
    },
    forEach(cb) {
      return underlying.forEach((elem, key) => {
        const [specifier, mode] = memoizedReverseKeys.get(key);
        return cb(elem, specifier, mode);
      });
    },
    size() {
      return underlying.size;
    }
  };
  return cache;
  function getUnderlyingCacheKey(specifier, mode) {
    const result = createModeAwareCacheKey(specifier, mode);
    memoizedReverseKeys.set(result, [specifier, mode]);
    return result;
  }
}
function getOriginalOrResolvedModuleFileName(result) {
  return result.resolvedModule && (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
}
function getOriginalOrResolvedTypeReferenceFileName(result) {
  return result.resolvedTypeReferenceDirective && (result.resolvedTypeReferenceDirective.originalPath || result.resolvedTypeReferenceDirective.resolvedFileName);
}
function createNonRelativeNameResolutionCache(currentDirectory, getCanonicalFileName, options, getResolvedFileName, optionsToRedirectsKey) {
  const moduleNameToDirectoryMap = createCacheWithRedirects(options, optionsToRedirectsKey);
  return {
    getFromNonRelativeNameCache,
    getOrCreateCacheForNonRelativeName,
    clear: clear2,
    update
  };
  function clear2() {
    moduleNameToDirectoryMap.clear();
  }
  function update(options2) {
    moduleNameToDirectoryMap.update(options2);
  }
  function getFromNonRelativeNameCache(nonRelativeModuleName, mode, directoryName, redirectedReference) {
    var _a, _b;
    Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName));
    return (_b = (_a = moduleNameToDirectoryMap.getMapOfCacheRedirects(redirectedReference)) == null ? void 0 : _a.get(createModeAwareCacheKey(nonRelativeModuleName, mode))) == null ? void 0 : _b.get(directoryName);
  }
  function getOrCreateCacheForNonRelativeName(nonRelativeModuleName, mode, redirectedReference) {
    Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName));
    return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, createModeAwareCacheKey(nonRelativeModuleName, mode), createPerModuleNameCache);
  }
  function createPerModuleNameCache() {
    const directoryPathMap = /* @__PURE__ */ new Map();
    return { get, set };
    function get(directory) {
      return directoryPathMap.get(toPath(directory, currentDirectory, getCanonicalFileName));
    }
    function set(directory, result) {
      const path = toPath(directory, currentDirectory, getCanonicalFileName);
      if (directoryPathMap.has(path)) {
        return;
      }
      directoryPathMap.set(path, result);
      const resolvedFileName = getResolvedFileName(result);
      const commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
      let current = path;
      while (current !== commonPrefix) {
        const parent = getDirectoryPath(current);
        if (parent === current || directoryPathMap.has(parent)) {
          break;
        }
        directoryPathMap.set(parent, result);
        current = parent;
      }
    }
    function getCommonPrefix(directory, resolution) {
      const resolutionDirectory = toPath(getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
      let i = 0;
      const limit = Math.min(directory.length, resolutionDirectory.length);
      while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
        i++;
      }
      if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === directorySeparator)) {
        return directory;
      }
      const rootLength = getRootLength(directory);
      if (i < rootLength) {
        return void 0;
      }
      const sep = directory.lastIndexOf(directorySeparator, i - 1);
      if (sep === -1) {
        return void 0;
      }
      return directory.substr(0, Math.max(sep, rootLength));
    }
  }
}
function createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, getResolvedFileName, optionsToRedirectsKey) {
  optionsToRedirectsKey ?? (optionsToRedirectsKey = /* @__PURE__ */ new Map());
  const perDirectoryResolutionCache = createPerDirectoryResolutionCache(
    currentDirectory,
    getCanonicalFileName,
    options,
    optionsToRedirectsKey
  );
  const nonRelativeNameResolutionCache = createNonRelativeNameResolutionCache(
    currentDirectory,
    getCanonicalFileName,
    options,
    getResolvedFileName,
    optionsToRedirectsKey
  );
  packageJsonInfoCache ?? (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName));
  return {
    ...packageJsonInfoCache,
    ...perDirectoryResolutionCache,
    ...nonRelativeNameResolutionCache,
    clear: clear2,
    update,
    getPackageJsonInfoCache: () => packageJsonInfoCache,
    clearAllExceptPackageJsonInfoCache,
    optionsToRedirectsKey
  };
  function clear2() {
    clearAllExceptPackageJsonInfoCache();
    packageJsonInfoCache.clear();
  }
  function clearAllExceptPackageJsonInfoCache() {
    perDirectoryResolutionCache.clear();
    nonRelativeNameResolutionCache.clear();
  }
  function update(options2) {
    perDirectoryResolutionCache.update(options2);
    nonRelativeNameResolutionCache.update(options2);
  }
}
function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, optionsToRedirectsKey) {
  const result = createModuleOrTypeReferenceResolutionCache(
    currentDirectory,
    getCanonicalFileName,
    options,
    packageJsonInfoCache,
    getOriginalOrResolvedModuleFileName,
    optionsToRedirectsKey
  );
  result.getOrCreateCacheForModuleName = (nonRelativeName, mode, redirectedReference) => result.getOrCreateCacheForNonRelativeName(nonRelativeName, mode, redirectedReference);
  return result;
}
function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, optionsToRedirectsKey) {
  return createModuleOrTypeReferenceResolutionCache(
    currentDirectory,
    getCanonicalFileName,
    options,
    packageJsonInfoCache,
    getOriginalOrResolvedTypeReferenceFileName,
    optionsToRedirectsKey
  );
}
function getOptionsForLibraryResolution(options) {
  return { moduleResolution: 2 /* Node10 */, traceResolution: options.traceResolution };
}
function resolveLibrary(libraryName, resolveFrom, compilerOptions, host, cache) {
  return resolveModuleName(libraryName, resolveFrom, getOptionsForLibraryResolution(compilerOptions), host, cache);
}
function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
  const traceEnabled = isTraceEnabled(compilerOptions, host);
  if (redirectedReference) {
    compilerOptions = redirectedReference.commandLine.options;
  }
  if (traceEnabled) {
    trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
    if (redirectedReference) {
      trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
    }
  }
  const containingDirectory = getDirectoryPath(containingFile);
  let result = cache == null ? void 0 : cache.getFromDirectoryCache(moduleName, resolutionMode, containingDirectory, redirectedReference);
  if (result) {
    if (traceEnabled) {
      trace(host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
    }
  } else {
    let moduleResolution = compilerOptions.moduleResolution;
    if (moduleResolution === void 0) {
      moduleResolution = getEmitModuleResolutionKind(compilerOptions);
      if (traceEnabled) {
        trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]);
      }
    } else {
      if (traceEnabled) {
        trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]);
      }
    }
    switch (moduleResolution) {
      case 3 /* Node16 */:
        result = node16ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
        break;
      case 99 /* NodeNext */:
        result = nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
        break;
      case 2 /* Node10 */:
        result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode ? getConditions(compilerOptions, resolutionMode) : void 0);
        break;
      case 1 /* Classic */:
        result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
        break;
      case 100 /* Bundler */:
        result = bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode ? getConditions(compilerOptions, resolutionMode) : void 0);
        break;
      default:
        return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`);
    }
    if (cache && !cache.isReadonly) {
      cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(moduleName, resolutionMode, result);
      if (!isExternalModuleNameRelative(moduleName)) {
        cache.getOrCreateCacheForNonRelativeName(moduleName, resolutionMode, redirectedReference).set(containingDirectory, result);
      }
    }
  }
  if (traceEnabled) {
    if (result.resolvedModule) {
      if (result.resolvedModule.packageId) {
        trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2, moduleName, result.resolvedModule.resolvedFileName, packageIdToString(result.resolvedModule.packageId));
      } else {
        trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
      }
    } else {
      trace(host, Diagnostics.Module_name_0_was_not_resolved, moduleName);
    }
  }
  return result;
}
function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
  const resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
  if (resolved) return resolved.value;
  if (!isExternalModuleNameRelative(moduleName)) {
    return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
  } else {
    return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
  }
}
function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
  const { baseUrl, paths } = state.compilerOptions;
  if (paths && !pathIsRelative(moduleName)) {
    if (state.traceEnabled) {
      if (baseUrl) {
        trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
      }
      trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
    }
    const baseDirectory = getPathsBasePath(state.compilerOptions, state.host);
    const pathPatterns = tryParsePatterns(paths);
    return tryLoadModuleUsingPaths(
      extensions,
      moduleName,
      baseDirectory,
      paths,
      pathPatterns,
      loader,
      /*onlyRecordFailures*/
      false,
      state
    );
  }
}
function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
  if (!state.compilerOptions.rootDirs) {
    return void 0;
  }
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
  }
  const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
  let matchedRootDir;
  let matchedNormalizedPrefix;
  for (const rootDir of state.compilerOptions.rootDirs) {
    let normalizedRoot = normalizePath(rootDir);
    if (!endsWith(normalizedRoot, directorySeparator)) {
      normalizedRoot += directorySeparator;
    }
    const isLongestMatchingPrefix = startsWith(candidate, normalizedRoot) && (matchedNormalizedPrefix === void 0 || matchedNormalizedPrefix.length < normalizedRoot.length);
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
    }
    if (isLongestMatchingPrefix) {
      matchedNormalizedPrefix = normalizedRoot;
      matchedRootDir = rootDir;
    }
  }
  if (matchedNormalizedPrefix) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
    }
    const suffix = candidate.substr(matchedNormalizedPrefix.length);
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
    }
    const resolvedFileName = loader(extensions, candidate, !directoryProbablyExists(containingDirectory, state.host), state);
    if (resolvedFileName) {
      return resolvedFileName;
    }
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Trying_other_entries_in_rootDirs);
    }
    for (const rootDir of state.compilerOptions.rootDirs) {
      if (rootDir === matchedRootDir) {
        continue;
      }
      const candidate2 = combinePaths(normalizePath(rootDir), suffix);
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate2);
      }
      const baseDirectory = getDirectoryPath(candidate2);
      const resolvedFileName2 = loader(extensions, candidate2, !directoryProbablyExists(baseDirectory, state.host), state);
      if (resolvedFileName2) {
        return resolvedFileName2;
      }
    }
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Module_resolution_using_rootDirs_has_failed);
    }
  }
  return void 0;
}
function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
  const { baseUrl } = state.compilerOptions;
  if (!baseUrl) {
    return void 0;
  }
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
  }
  const candidate = normalizePath(combinePaths(baseUrl, moduleName));
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
  }
  return loader(extensions, candidate, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
}
function resolveJSModule(moduleName, initialDir, host) {
  const { resolvedModule, failedLookupLocations } = tryResolveJSModuleWorker(moduleName, initialDir, host);
  if (!resolvedModule) {
    throw new Error(`Could not resolve JS module '${moduleName}' starting at '${initialDir}'. Looked in: ${failedLookupLocations == null ? void 0 : failedLookupLocations.join(", ")}`);
  }
  return resolvedModule.resolvedFileName;
}
function node16ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
  return nodeNextModuleNameResolverWorker(
    30 /* Node16Default */,
    moduleName,
    containingFile,
    compilerOptions,
    host,
    cache,
    redirectedReference,
    resolutionMode
  );
}
function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
  return nodeNextModuleNameResolverWorker(
    30 /* NodeNextDefault */,
    moduleName,
    containingFile,
    compilerOptions,
    host,
    cache,
    redirectedReference,
    resolutionMode
  );
}
function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode, conditions) {
  const containingDirectory = getDirectoryPath(containingFile);
  const esmMode = resolutionMode === 99 /* ESNext */ ? 32 /* EsmMode */ : 0;
  let extensions = compilerOptions.noDtsResolution ? 3 /* ImplementationFiles */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */;
  if (getResolveJsonModule(compilerOptions)) {
    extensions |= 8 /* Json */;
  }
  return nodeModuleNameResolverWorker(
    features | esmMode,
    moduleName,
    containingDirectory,
    compilerOptions,
    host,
    cache,
    extensions,
    /*isConfigLookup*/
    false,
    redirectedReference,
    conditions
  );
}
function tryResolveJSModuleWorker(moduleName, initialDir, host) {
  return nodeModuleNameResolverWorker(
    0 /* None */,
    moduleName,
    initialDir,
    { moduleResolution: 2 /* Node10 */, allowJs: true },
    host,
    /*cache*/
    void 0,
    2 /* JavaScript */,
    /*isConfigLookup*/
    false,
    /*redirectedReference*/
    void 0,
    /*conditions*/
    void 0
  );
}
function bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, conditions) {
  const containingDirectory = getDirectoryPath(containingFile);
  let extensions = compilerOptions.noDtsResolution ? 3 /* ImplementationFiles */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */;
  if (getResolveJsonModule(compilerOptions)) {
    extensions |= 8 /* Json */;
  }
  return nodeModuleNameResolverWorker(
    getNodeResolutionFeatures(compilerOptions),
    moduleName,
    containingDirectory,
    compilerOptions,
    host,
    cache,
    extensions,
    /*isConfigLookup*/
    false,
    redirectedReference,
    conditions
  );
}
function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, conditions, isConfigLookup) {
  let extensions;
  if (isConfigLookup) {
    extensions = 8 /* Json */;
  } else if (compilerOptions.noDtsResolution) {
    extensions = 3 /* ImplementationFiles */;
    if (getResolveJsonModule(compilerOptions)) extensions |= 8 /* Json */;
  } else {
    extensions = getResolveJsonModule(compilerOptions) ? 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */ | 8 /* Json */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */;
  }
  return nodeModuleNameResolverWorker(conditions ? 30 /* AllFeatures */ : 0 /* None */, moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, extensions, !!isConfigLookup, redirectedReference, conditions);
}
function nodeNextJsonConfigResolver(moduleName, containingFile, host) {
  return nodeModuleNameResolverWorker(
    30 /* NodeNextDefault */,
    moduleName,
    getDirectoryPath(containingFile),
    { moduleResolution: 99 /* NodeNext */ },
    host,
    /*cache*/
    void 0,
    8 /* Json */,
    /*isConfigLookup*/
    true,
    /*redirectedReference*/
    void 0,
    /*conditions*/
    void 0
  );
}
function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, compilerOptions, host, cache, extensions, isConfigLookup, redirectedReference, conditions) {
  var _a, _b, _c, _d, _e;
  const traceEnabled = isTraceEnabled(compilerOptions, host);
  const failedLookupLocations = [];
  const affectingLocations = [];
  const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
  conditions ?? (conditions = getConditions(
    compilerOptions,
    moduleResolution === 100 /* Bundler */ || moduleResolution === 2 /* Node10 */ ? void 0 : features & 32 /* EsmMode */ ? 99 /* ESNext */ : 1 /* CommonJS */
  ));
  const diagnostics = [];
  const state = {
    compilerOptions,
    host,
    traceEnabled,
    failedLookupLocations,
    affectingLocations,
    packageJsonInfoCache: cache,
    features,
    conditions: conditions ?? emptyArray,
    requestContainingDirectory: containingDirectory,
    reportDiagnostic: (diag2) => void diagnostics.push(diag2),
    isConfigLookup,
    candidateIsFromPackageJsonField: false,
    resolvedPackageDirectory: false
  };
  if (traceEnabled && moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) {
    trace(host, Diagnostics.Resolving_in_0_mode_with_conditions_1, features & 32 /* EsmMode */ ? "ESM" : "CJS", state.conditions.map((c) => `'${c}'`).join(", "));
  }
  let result;
  if (moduleResolution === 2 /* Node10 */) {
    const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */);
    const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */);
    result = priorityExtensions && tryResolve(priorityExtensions, state) || secondaryExtensions && tryResolve(secondaryExtensions, state) || void 0;
  } else {
    result = tryResolve(extensions, state);
  }
  let alternateResult;
  if (state.resolvedPackageDirectory && !isConfigLookup && !isExternalModuleNameRelative(moduleName)) {
    const wantedTypesButGotJs = (result == null ? void 0 : result.value) && extensions & (1 /* TypeScript */ | 4 /* Declaration */) && !extensionIsOk(1 /* TypeScript */ | 4 /* Declaration */, result.value.resolved.extension);
    if (((_a = result == null ? void 0 : result.value) == null ? void 0 : _a.isExternalLibraryImport) && wantedTypesButGotJs && features & 8 /* Exports */ && (conditions == null ? void 0 : conditions.includes("import"))) {
      traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_if_npm_library_needs_configuration_update);
      const diagnosticState = {
        ...state,
        features: state.features & ~8 /* Exports */,
        reportDiagnostic: noop
      };
      const diagnosticResult = tryResolve(extensions & (1 /* TypeScript */ | 4 /* Declaration */), diagnosticState);
      if ((_b = diagnosticResult == null ? void 0 : diagnosticResult.value) == null ? void 0 : _b.isExternalLibraryImport) {
        alternateResult = diagnosticResult.value.resolved.path;
      }
    } else if ((!(result == null ? void 0 : result.value) || wantedTypesButGotJs) && moduleResolution === 2 /* Node10 */) {
      traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_need_configuration_update);
      const diagnosticsCompilerOptions = { ...state.compilerOptions, moduleResolution: 100 /* Bundler */ };
      const diagnosticState = {
        ...state,
        compilerOptions: diagnosticsCompilerOptions,
        features: 30 /* BundlerDefault */,
        conditions: getConditions(diagnosticsCompilerOptions),
        reportDiagnostic: noop
      };
      const diagnosticResult = tryResolve(extensions & (1 /* TypeScript */ | 4 /* Declaration */), diagnosticState);
      if ((_c = diagnosticResult == null ? void 0 : diagnosticResult.value) == null ? void 0 : _c.isExternalLibraryImport) {
        alternateResult = diagnosticResult.value.resolved.path;
      }
    }
  }
  return createResolvedModuleWithFailedLookupLocationsHandlingSymlink(
    moduleName,
    (_d = result == null ? void 0 : result.value) == null ? void 0 : _d.resolved,
    (_e = result == null ? void 0 : result.value) == null ? void 0 : _e.isExternalLibraryImport,
    failedLookupLocations,
    affectingLocations,
    diagnostics,
    state,
    cache,
    alternateResult
  );
  function tryResolve(extensions2, state2) {
    const loader = (extensions3, candidate, onlyRecordFailures, state3) => nodeLoadModuleByRelativeName(
      extensions3,
      candidate,
      onlyRecordFailures,
      state3,
      /*considerPackageJson*/
      true
    );
    const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions2, moduleName, containingDirectory, loader, state2);
    if (resolved) {
      return toSearchResult({ resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
    }
    if (!isExternalModuleNameRelative(moduleName)) {
      if (features & 2 /* Imports */ && startsWith(moduleName, "#")) {
        const resolved3 = loadModuleFromImports(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference);
        if (resolved3) {
          return resolved3.value && { value: { resolved: resolved3.value, isExternalLibraryImport: false } };
        }
      }
      if (features & 4 /* SelfName */) {
        const resolved3 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference);
        if (resolved3) {
          return resolved3.value && { value: { resolved: resolved3.value, isExternalLibraryImport: false } };
        }
      }
      if (moduleName.includes(":")) {
        if (traceEnabled) {
          trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions2));
        }
        return void 0;
      }
      if (traceEnabled) {
        trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_types_Colon_1, moduleName, formatExtensions(extensions2));
      }
      let resolved2 = loadModuleFromNearestNodeModulesDirectory(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference);
      if (extensions2 & 4 /* Declaration */) {
        resolved2 ?? (resolved2 = resolveFromTypeRoot(moduleName, state2));
      }
      return resolved2 && { value: resolved2.value && { resolved: resolved2.value, isExternalLibraryImport: true } };
    } else {
      const { path: candidate, parts } = normalizePathForCJSResolution(containingDirectory, moduleName);
      const resolved2 = nodeLoadModuleByRelativeName(
        extensions2,
        candidate,
        /*onlyRecordFailures*/
        false,
        state2,
        /*considerPackageJson*/
        true
      );
      return resolved2 && toSearchResult({ resolved: resolved2, isExternalLibraryImport: contains(parts, "node_modules") });
    }
  }
}
function normalizePathForCJSResolution(containingDirectory, moduleName) {
  const combined = combinePaths(containingDirectory, moduleName);
  const parts = getPathComponents(combined);
  const lastPart = lastOrUndefined(parts);
  const path = lastPart === "." || lastPart === ".." ? ensureTrailingDirectorySeparator(normalizePath(combined)) : normalizePath(combined);
  return { path, parts };
}
function realPath(path, host, traceEnabled) {
  if (!host.realpath) {
    return path;
  }
  const real = normalizePath(host.realpath(path));
  if (traceEnabled) {
    trace(host, Diagnostics.Resolving_real_path_for_0_result_1, path, real);
  }
  return real;
}
function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1, candidate, formatExtensions(extensions));
  }
  if (!hasTrailingDirectorySeparator(candidate)) {
    if (!onlyRecordFailures) {
      const parentOfCandidate = getDirectoryPath(candidate);
      if (!directoryProbablyExists(parentOfCandidate, state.host)) {
        if (state.traceEnabled) {
          trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
        }
        onlyRecordFailures = true;
      }
    }
    const resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
    if (resolvedFromFile) {
      const packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : void 0;
      const packageInfo = packageDirectory ? getPackageJsonInfo(
        packageDirectory,
        /*onlyRecordFailures*/
        false,
        state
      ) : void 0;
      return withPackageId(packageInfo, resolvedFromFile, state);
    }
  }
  if (!onlyRecordFailures) {
    const candidateExists = directoryProbablyExists(candidate, state.host);
    if (!candidateExists) {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
      }
      onlyRecordFailures = true;
    }
  }
  if (!(state.features & 32 /* EsmMode */)) {
    return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
  }
  return void 0;
}
var nodeModulesPathPart = "/node_modules/";
function pathContainsNodeModules(path) {
  return path.includes(nodeModulesPathPart);
}
function parseNodeModuleFromPath(resolved, isFolder) {
  const path = normalizePath(resolved);
  const idx = path.lastIndexOf(nodeModulesPathPart);
  if (idx === -1) {
    return void 0;
  }
  const indexAfterNodeModules = idx + nodeModulesPathPart.length;
  let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules, isFolder);
  if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
    indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName, isFolder);
  }
  return path.slice(0, indexAfterPackageName);
}
function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex, isFolder) {
  const nextSeparatorIndex = path.indexOf(directorySeparator, prevSeparatorIndex + 1);
  return nextSeparatorIndex === -1 ? isFolder ? path.length : prevSeparatorIndex : nextSeparatorIndex;
}
function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
  return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
}
function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
  const resolvedByReplacingExtension = loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state);
  if (resolvedByReplacingExtension) {
    return resolvedByReplacingExtension;
  }
  if (!(state.features & 32 /* EsmMode */)) {
    const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, "", onlyRecordFailures, state);
    if (resolvedByAddingExtension) {
      return resolvedByAddingExtension;
    }
  }
}
function loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state) {
  const filename = getBaseFileName(candidate);
  if (!filename.includes(".")) {
    return void 0;
  }
  let extensionless = removeFileExtension(candidate);
  if (extensionless === candidate) {
    extensionless = candidate.substring(0, candidate.lastIndexOf("."));
  }
  const extension = candidate.substring(extensionless.length);
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
  }
  return tryAddingExtensions(extensionless, extensions, extension, onlyRecordFailures, state);
}
function loadFileNameFromPackageJsonField(extensions, candidate, packageJsonValue, onlyRecordFailures, state) {
  if (extensions & 1 /* TypeScript */ && fileExtensionIsOneOf(candidate, supportedTSImplementationExtensions) || extensions & 4 /* Declaration */ && fileExtensionIsOneOf(candidate, supportedDeclarationExtensions)) {
    const result = tryFile(candidate, onlyRecordFailures, state);
    const ext = tryExtractTSExtension(candidate);
    return result !== void 0 ? { path: candidate, ext, resolvedUsingTsExtension: packageJsonValue ? !endsWith(packageJsonValue, ext) : void 0 } : void 0;
  }
  if (state.isConfigLookup && extensions === 8 /* Json */ && fileExtensionIs(candidate, ".json" /* Json */)) {
    const result = tryFile(candidate, onlyRecordFailures, state);
    return result !== void 0 ? { path: candidate, ext: ".json" /* Json */, resolvedUsingTsExtension: void 0 } : void 0;
  }
  return loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state);
}
function tryAddingExtensions(candidate, extensions, originalExtension, onlyRecordFailures, state) {
  if (!onlyRecordFailures) {
    const directory = getDirectoryPath(candidate);
    if (directory) {
      onlyRecordFailures = !directoryProbablyExists(directory, state.host);
    }
  }
  switch (originalExtension) {
    case ".mjs" /* Mjs */:
    case ".mts" /* Mts */:
    case ".d.mts" /* Dmts */:
      return extensions & 1 /* TypeScript */ && tryExtension(".mts" /* Mts */, originalExtension === ".mts" /* Mts */ || originalExtension === ".d.mts" /* Dmts */) || extensions & 4 /* Declaration */ && tryExtension(".d.mts" /* Dmts */, originalExtension === ".mts" /* Mts */ || originalExtension === ".d.mts" /* Dmts */) || extensions & 2 /* JavaScript */ && tryExtension(".mjs" /* Mjs */) || void 0;
    case ".cjs" /* Cjs */:
    case ".cts" /* Cts */:
    case ".d.cts" /* Dcts */:
      return extensions & 1 /* TypeScript */ && tryExtension(".cts" /* Cts */, originalExtension === ".cts" /* Cts */ || originalExtension === ".d.cts" /* Dcts */) || extensions & 4 /* Declaration */ && tryExtension(".d.cts" /* Dcts */, originalExtension === ".cts" /* Cts */ || originalExtension === ".d.cts" /* Dcts */) || extensions & 2 /* JavaScript */ && tryExtension(".cjs" /* Cjs */) || void 0;
    case ".json" /* Json */:
      return extensions & 4 /* Declaration */ && tryExtension(".d.json.ts") || extensions & 8 /* Json */ && tryExtension(".json" /* Json */) || void 0;
    case ".tsx" /* Tsx */:
    case ".jsx" /* Jsx */:
      return extensions & 1 /* TypeScript */ && (tryExtension(".tsx" /* Tsx */, originalExtension === ".tsx" /* Tsx */) || tryExtension(".ts" /* Ts */, originalExtension === ".tsx" /* Tsx */)) || extensions & 4 /* Declaration */ && tryExtension(".d.ts" /* Dts */, originalExtension === ".tsx" /* Tsx */) || extensions & 2 /* JavaScript */ && (tryExtension(".jsx" /* Jsx */) || tryExtension(".js" /* Js */)) || void 0;
    case ".ts" /* Ts */:
    case ".d.ts" /* Dts */:
    case ".js" /* Js */:
    case "":
      return extensions & 1 /* TypeScript */ && (tryExtension(".ts" /* Ts */, originalExtension === ".ts" /* Ts */ || originalExtension === ".d.ts" /* Dts */) || tryExtension(".tsx" /* Tsx */, originalExtension === ".ts" /* Ts */ || originalExtension === ".d.ts" /* Dts */)) || extensions & 4 /* Declaration */ && tryExtension(".d.ts" /* Dts */, originalExtension === ".ts" /* Ts */ || originalExtension === ".d.ts" /* Dts */) || extensions & 2 /* JavaScript */ && (tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */)) || state.isConfigLookup && tryExtension(".json" /* Json */) || void 0;
    default:
      return extensions & 4 /* Declaration */ && !isDeclarationFileName(candidate + originalExtension) && tryExtension(`.d${originalExtension}.ts`) || void 0;
  }
  function tryExtension(ext, resolvedUsingTsExtension) {
    const path = tryFile(candidate + ext, onlyRecordFailures, state);
    return path === void 0 ? void 0 : { path, ext, resolvedUsingTsExtension: !state.candidateIsFromPackageJsonField && resolvedUsingTsExtension };
  }
}
function tryFile(fileName, onlyRecordFailures, state) {
  var _a;
  if (!((_a = state.compilerOptions.moduleSuffixes) == null ? void 0 : _a.length)) {
    return tryFileLookup(fileName, onlyRecordFailures, state);
  }
  const ext = tryGetExtensionFromPath2(fileName) ?? "";
  const fileNameNoExtension = ext ? removeExtension(fileName, ext) : fileName;
  return forEach(state.compilerOptions.moduleSuffixes, (suffix) => tryFileLookup(fileNameNoExtension + suffix + ext, onlyRecordFailures, state));
}
function tryFileLookup(fileName, onlyRecordFailures, state) {
  var _a;
  if (!onlyRecordFailures) {
    if (state.host.fileExists(fileName)) {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.File_0_exists_use_it_as_a_name_resolution_result, fileName);
      }
      return fileName;
    } else {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.File_0_does_not_exist, fileName);
      }
    }
  }
  (_a = state.failedLookupLocations) == null ? void 0 : _a.push(fileName);
  return void 0;
}
function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson = true) {
  const packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : void 0;
  const packageJsonContent = packageInfo && packageInfo.contents.packageJsonContent;
  const versionPaths = packageInfo && getVersionPathsOfPackageJsonInfo(packageInfo, state);
  return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths), state);
}
function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) {
  return {
    host,
    compilerOptions: options,
    traceEnabled: isTraceEnabled(options, host),
    failedLookupLocations: void 0,
    affectingLocations: void 0,
    packageJsonInfoCache,
    features: 0 /* None */,
    conditions: emptyArray,
    requestContainingDirectory: void 0,
    reportDiagnostic: noop,
    isConfigLookup: false,
    candidateIsFromPackageJsonField: false,
    resolvedPackageDirectory: false
  };
}
function getPackageScopeForPath(directory, state) {
  return forEachAncestorDirectoryStoppingAtGlobalCache(
    state.host,
    directory,
    (dir) => getPackageJsonInfo(
      dir,
      /*onlyRecordFailures*/
      false,
      state
    )
  );
}
function getVersionPathsOfPackageJsonInfo(packageJsonInfo, state) {
  if (packageJsonInfo.contents.versionPaths === void 0) {
    packageJsonInfo.contents.versionPaths = readPackageJsonTypesVersionPaths(packageJsonInfo.contents.packageJsonContent, state) || false;
  }
  return packageJsonInfo.contents.versionPaths || void 0;
}
function getPeerDependenciesOfPackageJsonInfo(packageJsonInfo, state) {
  if (packageJsonInfo.contents.peerDependencies === void 0) {
    packageJsonInfo.contents.peerDependencies = readPackageJsonPeerDependencies(packageJsonInfo, state) || false;
  }
  return packageJsonInfo.contents.peerDependencies || void 0;
}
function readPackageJsonPeerDependencies(packageJsonInfo, state) {
  const peerDependencies = readPackageJsonField(packageJsonInfo.contents.packageJsonContent, "peerDependencies", "object", state);
  if (peerDependencies === void 0) return void 0;
  if (state.traceEnabled) trace(state.host, Diagnostics.package_json_has_a_peerDependencies_field);
  const packageDirectory = realPath(packageJsonInfo.packageDirectory, state.host, state.traceEnabled);
  const nodeModules = packageDirectory.substring(0, packageDirectory.lastIndexOf("node_modules") + "node_modules".length) + directorySeparator;
  let result = "";
  for (const key in peerDependencies) {
    if (hasProperty(peerDependencies, key)) {
      const peerPackageJson = getPackageJsonInfo(
        nodeModules + key,
        /*onlyRecordFailures*/
        false,
        state
      );
      if (peerPackageJson) {
        const version2 = peerPackageJson.contents.packageJsonContent.version;
        result += `+${key}@${version2}`;
        if (state.traceEnabled) trace(state.host, Diagnostics.Found_peerDependency_0_with_1_version, key, version2);
      } else {
        if (state.traceEnabled) trace(state.host, Diagnostics.Failed_to_find_peerDependency_0, key);
      }
    }
  }
  return result;
}
function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
  var _a, _b, _c, _d, _e, _f;
  const { host, traceEnabled } = state;
  const packageJsonPath = combinePaths(packageDirectory, "package.json");
  if (onlyRecordFailures) {
    (_a = state.failedLookupLocations) == null ? void 0 : _a.push(packageJsonPath);
    return void 0;
  }
  const existing = (_b = state.packageJsonInfoCache) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
  if (existing !== void 0) {
    if (isPackageJsonInfo(existing)) {
      if (traceEnabled) trace(host, Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath);
      (_c = state.affectingLocations) == null ? void 0 : _c.push(packageJsonPath);
      return existing.packageDirectory === packageDirectory ? existing : { packageDirectory, contents: existing.contents };
    } else {
      if (existing.directoryExists && traceEnabled) trace(host, Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath);
      (_d = state.failedLookupLocations) == null ? void 0 : _d.push(packageJsonPath);
      return void 0;
    }
  }
  const directoryExists = directoryProbablyExists(packageDirectory, host);
  if (directoryExists && host.fileExists(packageJsonPath)) {
    const packageJsonContent = readJson(packageJsonPath, host);
    if (traceEnabled) {
      trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath);
    }
    const result = { packageDirectory, contents: { packageJsonContent, versionPaths: void 0, resolvedEntrypoints: void 0, peerDependencies: void 0 } };
    if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, result);
    (_e = state.affectingLocations) == null ? void 0 : _e.push(packageJsonPath);
    return result;
  } else {
    if (directoryExists && traceEnabled) {
      trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath);
    }
    if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, { packageDirectory, directoryExists });
    (_f = state.failedLookupLocations) == null ? void 0 : _f.push(packageJsonPath);
  }
}
function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
  let packageFile;
  if (jsonContent) {
    if (state.isConfigLookup) {
      packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
    } else {
      packageFile = extensions & 4 /* Declaration */ && readPackageJsonTypesFields(jsonContent, candidate, state) || extensions & (3 /* ImplementationFiles */ | 4 /* Declaration */) && readPackageJsonMainField(jsonContent, candidate, state) || void 0;
    }
  }
  const loader = (extensions2, candidate2, onlyRecordFailures2, state2) => {
    const fromFile = loadFileNameFromPackageJsonField(
      extensions2,
      candidate2,
      /*packageJsonValue*/
      void 0,
      onlyRecordFailures2,
      state2
    );
    if (fromFile) {
      return noPackageId(fromFile);
    }
    const expandedExtensions = extensions2 === 4 /* Declaration */ ? 1 /* TypeScript */ | 4 /* Declaration */ : extensions2;
    const features = state2.features;
    const candidateIsFromPackageJsonField = state2.candidateIsFromPackageJsonField;
    state2.candidateIsFromPackageJsonField = true;
    if ((jsonContent == null ? void 0 : jsonContent.type) !== "module") {
      state2.features &= ~32 /* EsmMode */;
    }
    const result = nodeLoadModuleByRelativeName(
      expandedExtensions,
      candidate2,
      onlyRecordFailures2,
      state2,
      /*considerPackageJson*/
      false
    );
    state2.features = features;
    state2.candidateIsFromPackageJsonField = candidateIsFromPackageJsonField;
    return result;
  };
  const onlyRecordFailuresForPackageFile = packageFile ? !directoryProbablyExists(getDirectoryPath(packageFile), state.host) : void 0;
  const onlyRecordFailuresForIndex = onlyRecordFailures || !directoryProbablyExists(candidate, state.host);
  const indexPath = combinePaths(candidate, state.isConfigLookup ? "tsconfig" : "index");
  if (versionPaths && (!packageFile || containsPath(candidate, packageFile))) {
    const moduleName = getRelativePathFromDirectory(
      candidate,
      packageFile || indexPath,
      /*ignoreCase*/
      false
    );
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, moduleName);
    }
    const pathPatterns = tryParsePatterns(versionPaths.paths);
    const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, pathPatterns, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
    if (result) {
      return removeIgnoredPackageId(result.value);
    }
  }
  const packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
  if (packageFileResult) return packageFileResult;
  if (!(state.features & 32 /* EsmMode */)) {
    return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
  }
}
function extensionIsOk(extensions, extension) {
  return extensions & 2 /* JavaScript */ && (extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */ || extension === ".mjs" /* Mjs */ || extension === ".cjs" /* Cjs */) || extensions & 1 /* TypeScript */ && (extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".mts" /* Mts */ || extension === ".cts" /* Cts */) || extensions & 4 /* Declaration */ && (extension === ".d.ts" /* Dts */ || extension === ".d.mts" /* Dmts */ || extension === ".d.cts" /* Dcts */) || extensions & 8 /* Json */ && extension === ".json" /* Json */ || false;
}
function parsePackageName(moduleName) {
  let idx = moduleName.indexOf(directorySeparator);
  if (moduleName[0] === "@") {
    idx = moduleName.indexOf(directorySeparator, idx + 1);
  }
  return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
}
function allKeysStartWithDot(obj) {
  return every(getOwnKeys(obj), (k) => startsWith(k, "."));
}
function noKeyStartsWithDot(obj) {
  return !some(getOwnKeys(obj), (k) => startsWith(k, "."));
}
function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) {
  var _a, _b;
  const directoryPath = getNormalizedAbsolutePath(directory, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a));
  const scope = getPackageScopeForPath(directoryPath, state);
  if (!scope || !scope.contents.packageJsonContent.exports) {
    return void 0;
  }
  if (typeof scope.contents.packageJsonContent.name !== "string") {
    return void 0;
  }
  const parts = getPathComponents(moduleName);
  const nameParts = getPathComponents(scope.contents.packageJsonContent.name);
  if (!every(nameParts, (p, i) => parts[i] === p)) {
    return void 0;
  }
  const trailingParts = parts.slice(nameParts.length);
  const subpath = !length(trailingParts) ? "." : `.${directorySeparator}${trailingParts.join(directorySeparator)}`;
  if (getAllowJSCompilerOption(state.compilerOptions) && !pathContainsNodeModules(directory)) {
    return loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference);
  }
  const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */);
  const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */);
  return loadModuleFromExports(scope, priorityExtensions, subpath, state, cache, redirectedReference) || loadModuleFromExports(scope, secondaryExtensions, subpath, state, cache, redirectedReference);
}
function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) {
  if (!scope.contents.packageJsonContent.exports) {
    return void 0;
  }
  if (subpath === ".") {
    let mainExport;
    if (typeof scope.contents.packageJsonContent.exports === "string" || Array.isArray(scope.contents.packageJsonContent.exports) || typeof scope.contents.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.contents.packageJsonContent.exports)) {
      mainExport = scope.contents.packageJsonContent.exports;
    } else if (hasProperty(scope.contents.packageJsonContent.exports, ".")) {
      mainExport = scope.contents.packageJsonContent.exports["."];
    }
    if (mainExport) {
      const loadModuleFromTargetExportOrImport = getLoadModuleFromTargetExportOrImport(
        extensions,
        state,
        cache,
        redirectedReference,
        subpath,
        scope,
        /*isImports*/
        false
      );
      return loadModuleFromTargetExportOrImport(
        mainExport,
        "",
        /*pattern*/
        false,
        "."
      );
    }
  } else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) {
    if (typeof scope.contents.packageJsonContent.exports !== "object") {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
      }
      return toSearchResult(
        /*value*/
        void 0
      );
    }
    const result = loadModuleFromExportsOrImports(
      extensions,
      state,
      cache,
      redirectedReference,
      subpath,
      scope.contents.packageJsonContent.exports,
      scope,
      /*isImports*/
      false
    );
    if (result) {
      return result;
    }
  }
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
  }
  return toSearchResult(
    /*value*/
    void 0
  );
}
function loadModuleFromImports(extensions, moduleName, directory, state, cache, redirectedReference) {
  var _a, _b;
  if (moduleName === "#" || startsWith(moduleName, "#/")) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Invalid_import_specifier_0_has_no_possible_resolutions, moduleName);
    }
    return toSearchResult(
      /*value*/
      void 0
    );
  }
  const directoryPath = getNormalizedAbsolutePath(directory, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a));
  const scope = getPackageScopeForPath(directoryPath, state);
  if (!scope) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath);
    }
    return toSearchResult(
      /*value*/
      void 0
    );
  }
  if (!scope.contents.packageJsonContent.imports) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory);
    }
    return toSearchResult(
      /*value*/
      void 0
    );
  }
  const result = loadModuleFromExportsOrImports(
    extensions,
    state,
    cache,
    redirectedReference,
    moduleName,
    scope.contents.packageJsonContent.imports,
    scope,
    /*isImports*/
    true
  );
  if (result) {
    return result;
  }
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1, moduleName, scope.packageDirectory);
  }
  return toSearchResult(
    /*value*/
    void 0
  );
}
function comparePatternKeys(a, b) {
  const aPatternIndex = a.indexOf("*");
  const bPatternIndex = b.indexOf("*");
  const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
  const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
  if (baseLenA > baseLenB) return -1 /* LessThan */;
  if (baseLenB > baseLenA) return 1 /* GreaterThan */;
  if (aPatternIndex === -1) return 1 /* GreaterThan */;
  if (bPatternIndex === -1) return -1 /* LessThan */;
  if (a.length > b.length) return -1 /* LessThan */;
  if (b.length > a.length) return 1 /* GreaterThan */;
  return 0 /* EqualTo */;
}
function loadModuleFromExportsOrImports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) {
  const loadModuleFromTargetExportOrImport = getLoadModuleFromTargetExportOrImport(extensions, state, cache, redirectedReference, moduleName, scope, isImports);
  if (!endsWith(moduleName, directorySeparator) && !moduleName.includes("*") && hasProperty(lookupTable, moduleName)) {
    const target = lookupTable[moduleName];
    return loadModuleFromTargetExportOrImport(
      target,
      /*subpath*/
      "",
      /*pattern*/
      false,
      moduleName
    );
  }
  const expandingKeys = toSorted(filter(getOwnKeys(lookupTable), (k) => hasOneAsterisk(k) || endsWith(k, "/")), comparePatternKeys);
  for (const potentialTarget of expandingKeys) {
    if (state.features & 16 /* ExportsPatternTrailers */ && matchesPatternWithTrailer(potentialTarget, moduleName)) {
      const target = lookupTable[potentialTarget];
      const starPos = potentialTarget.indexOf("*");
      const subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos));
      return loadModuleFromTargetExportOrImport(
        target,
        subpath,
        /*pattern*/
        true,
        potentialTarget
      );
    } else if (endsWith(potentialTarget, "*") && startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) {
      const target = lookupTable[potentialTarget];
      const subpath = moduleName.substring(potentialTarget.length - 1);
      return loadModuleFromTargetExportOrImport(
        target,
        subpath,
        /*pattern*/
        true,
        potentialTarget
      );
    } else if (startsWith(moduleName, potentialTarget)) {
      const target = lookupTable[potentialTarget];
      const subpath = moduleName.substring(potentialTarget.length);
      return loadModuleFromTargetExportOrImport(
        target,
        subpath,
        /*pattern*/
        false,
        potentialTarget
      );
    }
  }
  function matchesPatternWithTrailer(target, name) {
    if (endsWith(target, "*")) return false;
    const starPos = target.indexOf("*");
    if (starPos === -1) return false;
    return startsWith(name, target.substring(0, starPos)) && endsWith(name, target.substring(starPos + 1));
  }
}
function hasOneAsterisk(patternKey) {
  const firstStar = patternKey.indexOf("*");
  return firstStar !== -1 && firstStar === patternKey.lastIndexOf("*");
}
function getLoadModuleFromTargetExportOrImport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) {
  return loadModuleFromTargetExportOrImport;
  function loadModuleFromTargetExportOrImport(target, subpath, pattern, key) {
    if (typeof target === "string") {
      if (!pattern && subpath.length > 0 && !endsWith(target, "/")) {
        if (state.traceEnabled) {
          trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
        }
        return toSearchResult(
          /*value*/
          void 0
        );
      }
      if (!startsWith(target, "./")) {
        if (isImports && !startsWith(target, "../") && !startsWith(target, "/") && !isRootedDiskPath(target)) {
          const combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath;
          traceIfEnabled(state, Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup);
          traceIfEnabled(state, Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/");
          const result = nodeModuleNameResolverWorker(
            state.features,
            combinedLookup,
            scope.packageDirectory + "/",
            state.compilerOptions,
            state.host,
            cache,
            extensions,
            /*isConfigLookup*/
            false,
            redirectedReference,
            state.conditions
          );
          return toSearchResult(
            result.resolvedModule ? {
              path: result.resolvedModule.resolvedFileName,
              extension: result.resolvedModule.extension,
              packageId: result.resolvedModule.packageId,
              originalPath: result.resolvedModule.originalPath,
              resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension
            } : void 0
          );
        }
        if (state.traceEnabled) {
          trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
        }
        return toSearchResult(
          /*value*/
          void 0
        );
      }
      const parts = pathIsRelative(target) ? getPathComponents(target).slice(1) : getPathComponents(target);
      const partsAfterFirst = parts.slice(1);
      if (partsAfterFirst.includes("..") || partsAfterFirst.includes(".") || partsAfterFirst.includes("node_modules")) {
        if (state.traceEnabled) {
          trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
        }
        return toSearchResult(
          /*value*/
          void 0
        );
      }
      const resolvedTarget = combinePaths(scope.packageDirectory, target);
      const subpathParts = getPathComponents(subpath);
      if (subpathParts.includes("..") || subpathParts.includes(".") || subpathParts.includes("node_modules")) {
        if (state.traceEnabled) {
          trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
        }
        return toSearchResult(
          /*value*/
          void 0
        );
      }
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath);
      }
      const finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath);
      const inputLink = tryLoadInputFileForPath(finalPath, subpath, combinePaths(scope.packageDirectory, "package.json"), isImports);
      if (inputLink) return inputLink;
      return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField(
        extensions,
        finalPath,
        target,
        /*onlyRecordFailures*/
        false,
        state
      ), state));
    } else if (typeof target === "object" && target !== null) {
      if (!Array.isArray(target)) {
        traceIfEnabled(state, Diagnostics.Entering_conditional_exports);
        for (const condition of getOwnKeys(target)) {
          if (condition === "default" || state.conditions.includes(condition) || isApplicableVersionedTypesKey(state.conditions, condition)) {
            traceIfEnabled(state, Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition);
            const subTarget = target[condition];
            const result = loadModuleFromTargetExportOrImport(subTarget, subpath, pattern, key);
            if (result) {
              traceIfEnabled(state, Diagnostics.Resolved_under_condition_0, condition);
              traceIfEnabled(state, Diagnostics.Exiting_conditional_exports);
              return result;
            } else {
              traceIfEnabled(state, Diagnostics.Failed_to_resolve_under_condition_0, condition);
            }
          } else {
            traceIfEnabled(state, Diagnostics.Saw_non_matching_condition_0, condition);
          }
        }
        traceIfEnabled(state, Diagnostics.Exiting_conditional_exports);
        return void 0;
      } else {
        if (!length(target)) {
          if (state.traceEnabled) {
            trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
          }
          return toSearchResult(
            /*value*/
            void 0
          );
        }
        for (const elem of target) {
          const result = loadModuleFromTargetExportOrImport(elem, subpath, pattern, key);
          if (result) {
            return result;
          }
        }
      }
    } else if (target === null) {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.package_json_scope_0_explicitly_maps_specifier_1_to_null, scope.packageDirectory, moduleName);
      }
      return toSearchResult(
        /*value*/
        void 0
      );
    }
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
    }
    return toSearchResult(
      /*value*/
      void 0
    );
    function toAbsolutePath(path) {
      var _a, _b;
      if (path === void 0) return path;
      return getNormalizedAbsolutePath(path, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a));
    }
    function combineDirectoryPath(root, dir) {
      return ensureTrailingDirectorySeparator(combinePaths(root, dir));
    }
    function tryLoadInputFileForPath(finalPath, entry, packagePath, isImports2) {
      var _a, _b, _c, _d;
      if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && !finalPath.includes("/node_modules/") && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)) {
        const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames: () => useCaseSensitiveFileNames(state) });
        const commonSourceDirGuesses = [];
        if (state.compilerOptions.rootDir || state.compilerOptions.composite && state.compilerOptions.configFilePath) {
          const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [], ((_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)) || "", getCanonicalFileName));
          commonSourceDirGuesses.push(commonDir);
        } else if (state.requestContainingDirectory) {
          const requestingFile = toAbsolutePath(combinePaths(state.requestContainingDirectory, "index.ts"));
          const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [requestingFile, toAbsolutePath(packagePath)], ((_d = (_c = state.host).getCurrentDirectory) == null ? void 0 : _d.call(_c)) || "", getCanonicalFileName));
          commonSourceDirGuesses.push(commonDir);
          let fragment = ensureTrailingDirectorySeparator(commonDir);
          while (fragment && fragment.length > 1) {
            const parts = getPathComponents(fragment);
            parts.pop();
            const commonDir2 = getPathFromPathComponents(parts);
            commonSourceDirGuesses.unshift(commonDir2);
            fragment = ensureTrailingDirectorySeparator(commonDir2);
          }
        }
        if (commonSourceDirGuesses.length > 1) {
          state.reportDiagnostic(createCompilerDiagnostic(
            isImports2 ? Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate : Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate,
            entry === "" ? "." : entry,
            // replace empty string with `.` - the reverse of the operation done when entries are built - so main entrypoint errors don't look weird
            packagePath
          ));
        }
        for (const commonSourceDirGuess of commonSourceDirGuesses) {
          const candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess);
          for (const candidateDir of candidateDirectories) {
            if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames(state))) {
              const pathFragment = finalPath.slice(candidateDir.length + 1);
              const possibleInputBase = combinePaths(commonSourceDirGuess, pathFragment);
              const jsAndDtsExtensions = [".mjs" /* Mjs */, ".cjs" /* Cjs */, ".js" /* Js */, ".json" /* Json */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */, ".d.ts" /* Dts */];
              for (const ext of jsAndDtsExtensions) {
                if (fileExtensionIs(possibleInputBase, ext)) {
                  const inputExts = getPossibleOriginalInputExtensionForExtension(possibleInputBase);
                  for (const possibleExt of inputExts) {
                    if (!extensionIsOk(extensions, possibleExt)) continue;
                    const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state));
                    if (state.host.fileExists(possibleInputWithInputExtension)) {
                      return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField(
                        extensions,
                        possibleInputWithInputExtension,
                        /*packageJsonValue*/
                        void 0,
                        /*onlyRecordFailures*/
                        false,
                        state
                      ), state));
                    }
                  }
                }
              }
            }
          }
        }
      }
      return void 0;
      function getOutputDirectoriesForBaseDirectory(commonSourceDirGuess) {
        var _a2, _b2;
        const currentDir = state.compilerOptions.configFile ? ((_b2 = (_a2 = state.host).getCurrentDirectory) == null ? void 0 : _b2.call(_a2)) || "" : commonSourceDirGuess;
        const candidateDirectories = [];
        if (state.compilerOptions.declarationDir) {
          candidateDirectories.push(toAbsolutePath(combineDirectoryPath(currentDir, state.compilerOptions.declarationDir)));
        }
        if (state.compilerOptions.outDir && state.compilerOptions.outDir !== state.compilerOptions.declarationDir) {
          candidateDirectories.push(toAbsolutePath(combineDirectoryPath(currentDir, state.compilerOptions.outDir)));
        }
        return candidateDirectories;
      }
    }
  }
}
function isApplicableVersionedTypesKey(conditions, key) {
  if (!conditions.includes("types")) return false;
  if (!startsWith(key, "types@")) return false;
  const range = VersionRange.tryParse(key.substring("types@".length));
  if (!range) return false;
  return range.test(version);
}
function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
  return loadModuleFromNearestNodeModulesDirectoryWorker(
    extensions,
    moduleName,
    directory,
    state,
    /*typesScopeOnly*/
    false,
    cache,
    redirectedReference
  );
}
function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
  return loadModuleFromNearestNodeModulesDirectoryWorker(
    4 /* Declaration */,
    moduleName,
    directory,
    state,
    /*typesScopeOnly*/
    true,
    /*cache*/
    void 0,
    /*redirectedReference*/
    void 0
  );
}
function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
  const mode = state.features === 0 ? void 0 : state.features & 32 /* EsmMode */ ? 99 /* ESNext */ : 1 /* CommonJS */;
  const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */);
  const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */);
  if (priorityExtensions) {
    traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0, formatExtensions(priorityExtensions));
    const result = lookup(priorityExtensions);
    if (result) return result;
  }
  if (secondaryExtensions && !typesScopeOnly) {
    traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0, formatExtensions(secondaryExtensions));
    return lookup(secondaryExtensions);
  }
  function lookup(extensions2) {
    return forEachAncestorDirectoryStoppingAtGlobalCache(
      state.host,
      normalizeSlashes(directory),
      (ancestorDirectory) => {
        if (getBaseFileName(ancestorDirectory) !== "node_modules") {
          const resolutionFromCache = tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, ancestorDirectory, redirectedReference, state);
          if (resolutionFromCache) {
            return resolutionFromCache;
          }
          return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions2, moduleName, ancestorDirectory, state, typesScopeOnly, cache, redirectedReference));
        }
      }
    );
  }
}
function forEachAncestorDirectoryStoppingAtGlobalCache(host, directory, callback) {
  var _a;
  const globalCache = (_a = host == null ? void 0 : host.getGlobalTypingsCacheLocation) == null ? void 0 : _a.call(host);
  return forEachAncestorDirectory(directory, (ancestorDirectory) => {
    const result = callback(ancestorDirectory);
    if (result !== void 0) return result;
    if (ancestorDirectory === globalCache) return false;
  }) || void 0;
}
function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
  const nodeModulesFolder = combinePaths(directory, "node_modules");
  const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
  if (!nodeModulesFolderExists && state.traceEnabled) {
    trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
  }
  if (!typesScopeOnly) {
    const packageResult = loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state, cache, redirectedReference);
    if (packageResult) {
      return packageResult;
    }
  }
  if (extensions & 4 /* Declaration */) {
    const nodeModulesAtTypes2 = combinePaths(nodeModulesFolder, "@types");
    let nodeModulesAtTypesExists = nodeModulesFolderExists;
    if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes2, state.host)) {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes2);
      }
      nodeModulesAtTypesExists = false;
    }
    return loadModuleFromSpecificNodeModulesDirectory(4 /* Declaration */, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes2, nodeModulesAtTypesExists, state, cache, redirectedReference);
  }
}
function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state, cache, redirectedReference) {
  var _a, _b;
  const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName));
  const { packageName, rest } = parsePackageName(moduleName);
  const packageDirectory = combinePaths(nodeModulesDirectory, packageName);
  let rootPackageInfo;
  let packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
  if (rest !== "" && packageInfo && (!(state.features & 8 /* Exports */) || !hasProperty(((_a = rootPackageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state)) == null ? void 0 : _a.contents.packageJsonContent) ?? emptyArray, "exports"))) {
    const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
    if (fromFile) {
      return noPackageId(fromFile);
    }
    const fromDirectory = loadNodeModuleFromDirectoryWorker(
      extensions,
      candidate,
      !nodeModulesDirectoryExists,
      state,
      packageInfo.contents.packageJsonContent,
      getVersionPathsOfPackageJsonInfo(packageInfo, state)
    );
    return withPackageId(packageInfo, fromDirectory, state);
  }
  const loader = (extensions2, candidate2, onlyRecordFailures, state2) => {
    let pathAndExtension = (rest || !(state2.features & 32 /* EsmMode */)) && loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker(
      extensions2,
      candidate2,
      onlyRecordFailures,
      state2,
      packageInfo && packageInfo.contents.packageJsonContent,
      packageInfo && getVersionPathsOfPackageJsonInfo(packageInfo, state2)
    );
    if (!pathAndExtension && packageInfo && (packageInfo.contents.packageJsonContent.exports === void 0 || packageInfo.contents.packageJsonContent.exports === null) && state2.features & 32 /* EsmMode */) {
      pathAndExtension = loadModuleFromFile(extensions2, combinePaths(candidate2, "index.js"), onlyRecordFailures, state2);
    }
    return withPackageId(packageInfo, pathAndExtension, state2);
  };
  if (rest !== "") {
    packageInfo = rootPackageInfo ?? getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
  }
  if (packageInfo) {
    state.resolvedPackageDirectory = true;
  }
  if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & 8 /* Exports */) {
    return (_b = loadModuleFromExports(packageInfo, extensions, combinePaths(".", rest), state, cache, redirectedReference)) == null ? void 0 : _b.value;
  }
  const versionPaths = rest !== "" && packageInfo ? getVersionPathsOfPackageJsonInfo(packageInfo, state) : void 0;
  if (versionPaths) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, rest);
    }
    const packageDirectoryExists = nodeModulesDirectoryExists && directoryProbablyExists(packageDirectory, state.host);
    const pathPatterns = tryParsePatterns(versionPaths.paths);
    const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, pathPatterns, loader, !packageDirectoryExists, state);
    if (fromPaths) {
      return fromPaths.value;
    }
  }
  return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
}
function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, pathPatterns, loader, onlyRecordFailures, state) {
  const matchedPattern = matchPatternOrExact(pathPatterns, moduleName);
  if (matchedPattern) {
    const matchedStar = isString(matchedPattern) ? void 0 : matchedText(matchedPattern, moduleName);
    const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern);
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
    }
    const resolved = forEach(paths[matchedPatternText], (subst) => {
      const path = matchedStar ? replaceFirstStar(subst, matchedStar) : subst;
      const candidate = normalizePath(combinePaths(baseDirectory, path));
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
      }
      const extension = tryGetExtensionFromPath2(subst);
      if (extension !== void 0) {
        const path2 = tryFile(candidate, onlyRecordFailures, state);
        if (path2 !== void 0) {
          return noPackageId({ path: path2, ext: extension, resolvedUsingTsExtension: void 0 });
        }
      }
      return loader(extensions, candidate, onlyRecordFailures || !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
    });
    return { value: resolved };
  }
}
var mangledScopedPackageSeparator = "__";
function mangleScopedPackageNameWithTrace(packageName, state) {
  const mangled = mangleScopedPackageName(packageName);
  if (state.traceEnabled && mangled !== packageName) {
    trace(state.host, Diagnostics.Scoped_package_detected_looking_in_0, mangled);
  }
  return mangled;
}
function getTypesPackageName(packageName) {
  return `@types/${mangleScopedPackageName(packageName)}`;
}
function mangleScopedPackageName(packageName) {
  if (startsWith(packageName, "@")) {
    const replaceSlash = packageName.replace(directorySeparator, mangledScopedPackageSeparator);
    if (replaceSlash !== packageName) {
      return replaceSlash.slice(1);
    }
  }
  return packageName;
}
function getPackageNameFromTypesPackageName(mangledName) {
  const withoutAtTypePrefix = removePrefix(mangledName, "@types/");
  if (withoutAtTypePrefix !== mangledName) {
    return unmangleScopedPackageName(withoutAtTypePrefix);
  }
  return mangledName;
}
function unmangleScopedPackageName(typesPackageName) {
  return typesPackageName.includes(mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) : typesPackageName;
}
function tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, containingDirectory, redirectedReference, state) {
  const result = cache && cache.getFromNonRelativeNameCache(moduleName, mode, containingDirectory, redirectedReference);
  if (result) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
    }
    state.resultFromCache = result;
    return {
      value: result.resolvedModule && {
        path: result.resolvedModule.resolvedFileName,
        originalPath: result.resolvedModule.originalPath || true,
        extension: result.resolvedModule.extension,
        packageId: result.resolvedModule.packageId,
        resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension
      }
    };
  }
}
function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
  const traceEnabled = isTraceEnabled(compilerOptions, host);
  const failedLookupLocations = [];
  const affectingLocations = [];
  const containingDirectory = getDirectoryPath(containingFile);
  const diagnostics = [];
  const state = {
    compilerOptions,
    host,
    traceEnabled,
    failedLookupLocations,
    affectingLocations,
    packageJsonInfoCache: cache,
    features: 0 /* None */,
    conditions: [],
    requestContainingDirectory: containingDirectory,
    reportDiagnostic: (diag2) => void diagnostics.push(diag2),
    isConfigLookup: false,
    candidateIsFromPackageJsonField: false,
    resolvedPackageDirectory: false
  };
  const resolved = tryResolve(1 /* TypeScript */ | 4 /* Declaration */) || tryResolve(2 /* JavaScript */ | (compilerOptions.resolveJsonModule ? 8 /* Json */ : 0));
  return createResolvedModuleWithFailedLookupLocationsHandlingSymlink(
    moduleName,
    resolved && resolved.value,
    (resolved == null ? void 0 : resolved.value) && pathContainsNodeModules(resolved.value.path),
    failedLookupLocations,
    affectingLocations,
    diagnostics,
    state,
    cache
  );
  function tryResolve(extensions) {
    const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
    if (resolvedUsingSettings) {
      return { value: resolvedUsingSettings };
    }
    if (!isExternalModuleNameRelative(moduleName)) {
      const resolved2 = forEachAncestorDirectoryStoppingAtGlobalCache(
        state.host,
        containingDirectory,
        (directory) => {
          const resolutionFromCache = tryFindNonRelativeModuleNameInCache(
            cache,
            moduleName,
            /*mode*/
            void 0,
            directory,
            redirectedReference,
            state
          );
          if (resolutionFromCache) {
            return resolutionFromCache;
          }
          const searchName = normalizePath(combinePaths(directory, moduleName));
          return toSearchResult(loadModuleFromFileNoPackageId(
            extensions,
            searchName,
            /*onlyRecordFailures*/
            false,
            state
          ));
        }
      );
      if (resolved2) return resolved2;
      if (extensions & (1 /* TypeScript */ | 4 /* Declaration */)) {
        let resolved3 = loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
        if (extensions & 4 /* Declaration */) resolved3 ?? (resolved3 = resolveFromTypeRoot(moduleName, state));
        return resolved3;
      }
    } else {
      const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
      return toSearchResult(loadModuleFromFileNoPackageId(
        extensions,
        candidate,
        /*onlyRecordFailures*/
        false,
        state
      ));
    }
  }
}
function resolveFromTypeRoot(moduleName, state) {
  if (!state.compilerOptions.typeRoots) return;
  for (const typeRoot of state.compilerOptions.typeRoots) {
    const candidate = getCandidateFromTypeRoot(typeRoot, moduleName, state);
    const directoryExists = directoryProbablyExists(typeRoot, state.host);
    if (!directoryExists && state.traceEnabled) {
      trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, typeRoot);
    }
    const resolvedFromFile = loadModuleFromFile(4 /* Declaration */, candidate, !directoryExists, state);
    if (resolvedFromFile) {
      const packageDirectory = parseNodeModuleFromPath(resolvedFromFile.path);
      const packageInfo = packageDirectory ? getPackageJsonInfo(
        packageDirectory,
        /*onlyRecordFailures*/
        false,
        state
      ) : void 0;
      return toSearchResult(withPackageId(packageInfo, resolvedFromFile, state));
    }
    const resolved = loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, state);
    if (resolved) return toSearchResult(resolved);
  }
}
function shouldAllowImportingTsExtension(compilerOptions, fromFileName) {
  return getAllowImportingTsExtensions(compilerOptions) || !!fromFileName && isDeclarationFileName(fromFileName);
}
function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) {
  const traceEnabled = isTraceEnabled(compilerOptions, host);
  if (traceEnabled) {
    trace(host, Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache);
  }
  const failedLookupLocations = [];
  const affectingLocations = [];
  const diagnostics = [];
  const state = {
    compilerOptions,
    host,
    traceEnabled,
    failedLookupLocations,
    affectingLocations,
    packageJsonInfoCache,
    features: 0 /* None */,
    conditions: [],
    requestContainingDirectory: void 0,
    reportDiagnostic: (diag2) => void diagnostics.push(diag2),
    isConfigLookup: false,
    candidateIsFromPackageJsonField: false,
    resolvedPackageDirectory: false
  };
  const resolved = loadModuleFromImmediateNodeModulesDirectory(
    4 /* Declaration */,
    moduleName,
    globalCache,
    state,
    /*typesScopeOnly*/
    false,
    /*cache*/
    void 0,
    /*redirectedReference*/
    void 0
  );
  return createResolvedModuleWithFailedLookupLocations(
    resolved,
    /*isExternalLibraryImport*/
    true,
    failedLookupLocations,
    affectingLocations,
    diagnostics,
    state.resultFromCache,
    /*cache*/
    void 0
  );
}
function toSearchResult(value) {
  return value !== void 0 ? { value } : void 0;
}
function traceIfEnabled(state, diagnostic, ...args) {
  if (state.traceEnabled) {
    trace(state.host, diagnostic, ...args);
  }
}
function useCaseSensitiveFileNames(state) {
  return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames();
}

// src/compiler/binder.ts
function getModuleInstanceState(node, visited) {
  if (node.body && !node.body.parent) {
    setParent(node.body, node);
    setParentRecursive(
      node.body,
      /*incremental*/
      false
    );
  }
  return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
}
function getModuleInstanceStateCached(node, visited = /* @__PURE__ */ new Map()) {
  const nodeId = getNodeId(node);
  if (visited.has(nodeId)) {
    return visited.get(nodeId) || 0 /* NonInstantiated */;
  }
  visited.set(nodeId, void 0);
  const result = getModuleInstanceStateWorker(node, visited);
  visited.set(nodeId, result);
  return result;
}
function getModuleInstanceStateWorker(node, visited) {
  switch (node.kind) {
    // 1. interface declarations, type alias declarations
    case 264 /* InterfaceDeclaration */:
    case 265 /* TypeAliasDeclaration */:
      return 0 /* NonInstantiated */;
    // 2. const enum declarations
    case 266 /* EnumDeclaration */:
      if (isEnumConst(node)) {
        return 2 /* ConstEnumOnly */;
      }
      break;
    // 3. non-exported import declarations
    case 272 /* ImportDeclaration */:
    case 271 /* ImportEqualsDeclaration */:
      if (!hasSyntacticModifier(node, 32 /* Export */)) {
        return 0 /* NonInstantiated */;
      }
      break;
    // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
    case 278 /* ExportDeclaration */:
      const exportDeclaration = node;
      if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 279 /* NamedExports */) {
        let state = 0 /* NonInstantiated */;
        for (const specifier of exportDeclaration.exportClause.elements) {
          const specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
          if (specifierState > state) {
            state = specifierState;
          }
          if (state === 1 /* Instantiated */) {
            return state;
          }
        }
        return state;
      }
      break;
    // 5. other uninstantiated module declarations.
    case 268 /* ModuleBlock */: {
      let state = 0 /* NonInstantiated */;
      forEachChild(node, (n) => {
        const childState = getModuleInstanceStateCached(n, visited);
        switch (childState) {
          case 0 /* NonInstantiated */:
            return;
          case 2 /* ConstEnumOnly */:
            state = 2 /* ConstEnumOnly */;
            return;
          case 1 /* Instantiated */:
            state = 1 /* Instantiated */;
            return true;
          default:
            Debug.assertNever(childState);
        }
      });
      return state;
    }
    case 267 /* ModuleDeclaration */:
      return getModuleInstanceState(node, visited);
    case 80 /* Identifier */:
      if (node.flags & 4096 /* IdentifierIsInJSDocNamespace */) {
        return 0 /* NonInstantiated */;
      }
  }
  return 1 /* Instantiated */;
}
function getModuleInstanceStateForAliasTarget(specifier, visited) {
  const name = specifier.propertyName || specifier.name;
  if (name.kind !== 80 /* Identifier */) {
    return 1 /* Instantiated */;
  }
  let p = specifier.parent;
  while (p) {
    if (isBlock(p) || isModuleBlock(p) || isSourceFile(p)) {
      const statements = p.statements;
      let found;
      for (const statement of statements) {
        if (nodeHasName(statement, name)) {
          if (!statement.parent) {
            setParent(statement, p);
            setParentRecursive(
              statement,
              /*incremental*/
              false
            );
          }
          const state = getModuleInstanceStateCached(statement, visited);
          if (found === void 0 || state > found) {
            found = state;
          }
          if (found === 1 /* Instantiated */) {
            return found;
          }
          if (statement.kind === 271 /* ImportEqualsDeclaration */) {
            found = 1 /* Instantiated */;
          }
        }
      }
      if (found !== void 0) {
        return found;
      }
    }
    p = p.parent;
  }
  return 1 /* Instantiated */;
}
function createFlowNode(flags, node, antecedent) {
  return Debug.attachFlowNodeDebugInfo({ flags, id: 0, node, antecedent });
}
var binder = /* @__PURE__ */ createBinder();
function bindSourceFile(file, options) {
  mark("beforeBind");
  binder(file, options);
  mark("afterBind");
  measure("Bind", "beforeBind", "afterBind");
}
function createBinder() {
  var file;
  var options;
  var languageVersion;
  var parent;
  var container;
  var thisParentContainer;
  var blockScopeContainer;
  var lastContainer;
  var delayedTypeAliases;
  var seenThisKeyword;
  var jsDocImports;
  var currentFlow;
  var currentBreakTarget;
  var currentContinueTarget;
  var currentReturnTarget;
  var currentTrueTarget;
  var currentFalseTarget;
  var currentExceptionTarget;
  var preSwitchCaseFlow;
  var activeLabelList;
  var hasExplicitReturn;
  var hasFlowEffects;
  var emitFlags;
  var inStrictMode;
  var inAssignmentPattern = false;
  var symbolCount = 0;
  var Symbol13;
  var classifiableNames;
  var unreachableFlow = createFlowNode(
    1 /* Unreachable */,
    /*node*/
    void 0,
    /*antecedent*/
    void 0
  );
  var reportedUnreachableFlow = createFlowNode(
    1 /* Unreachable */,
    /*node*/
    void 0,
    /*antecedent*/
    void 0
  );
  var bindBinaryExpressionFlow = createBindBinaryExpressionFlow();
  return bindSourceFile2;
  function createDiagnosticForNode2(node, message, ...args) {
    return createDiagnosticForNodeInSourceFile(getSourceFileOfNode(node) || file, node, message, ...args);
  }
  function bindSourceFile2(f, opts) {
    var _a, _b;
    file = f;
    options = opts;
    languageVersion = getEmitScriptTarget(options);
    inStrictMode = bindInStrictMode(file, opts);
    classifiableNames = /* @__PURE__ */ new Set();
    symbolCount = 0;
    Symbol13 = objectAllocator.getSymbolConstructor();
    Debug.attachFlowNodeDebugInfo(unreachableFlow);
    Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
    if (!file.locals) {
      (_a = tracing) == null ? void 0 : _a.push(
        tracing.Phase.Bind,
        "bindSourceFile",
        { path: file.path },
        /*separateBeginAndEnd*/
        true
      );
      bind(file);
      (_b = tracing) == null ? void 0 : _b.pop();
      file.symbolCount = symbolCount;
      file.classifiableNames = classifiableNames;
      delayedBindJSDocTypedefTag();
      bindJSDocImports();
    }
    file = void 0;
    options = void 0;
    languageVersion = void 0;
    parent = void 0;
    container = void 0;
    thisParentContainer = void 0;
    blockScopeContainer = void 0;
    lastContainer = void 0;
    delayedTypeAliases = void 0;
    jsDocImports = void 0;
    seenThisKeyword = false;
    currentFlow = void 0;
    currentBreakTarget = void 0;
    currentContinueTarget = void 0;
    currentReturnTarget = void 0;
    currentTrueTarget = void 0;
    currentFalseTarget = void 0;
    currentExceptionTarget = void 0;
    activeLabelList = void 0;
    hasExplicitReturn = false;
    hasFlowEffects = false;
    inAssignmentPattern = false;
    emitFlags = 0 /* None */;
  }
  function bindInStrictMode(file2, opts) {
    if (getStrictOptionValue(opts, "alwaysStrict") && !file2.isDeclarationFile) {
      return true;
    } else {
      return !!file2.externalModuleIndicator;
    }
  }
  function createSymbol(flags, name) {
    symbolCount++;
    return new Symbol13(flags, name);
  }
  function addDeclarationToSymbol(symbol, node, symbolFlags) {
    symbol.flags |= symbolFlags;
    node.symbol = symbol;
    symbol.declarations = appendIfUnique(symbol.declarations, node);
    if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
      symbol.exports = createSymbolTable();
    }
    if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
      symbol.members = createSymbolTable();
    }
    if (symbol.constEnumOnlyModule && symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) {
      symbol.constEnumOnlyModule = false;
    }
    if (symbolFlags & 111551 /* Value */) {
      setValueDeclaration(symbol, node);
    }
  }
  function getDeclarationName(node) {
    if (node.kind === 277 /* ExportAssignment */) {
      return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
    }
    const name = getNameOfDeclaration(node);
    if (name) {
      if (isAmbientModule(node)) {
        const moduleName = getTextOfIdentifierOrLiteral(name);
        return isGlobalScopeAugmentation(node) ? "__global" : `"${moduleName}"`;
      }
      if (name.kind === 167 /* ComputedPropertyName */) {
        const nameExpression = name.expression;
        if (isStringOrNumericLiteralLike(nameExpression)) {
          return escapeLeadingUnderscores(nameExpression.text);
        }
        if (isSignedNumericLiteral(nameExpression)) {
          return tokenToString(nameExpression.operator) + nameExpression.operand.text;
        } else {
          Debug.fail("Only computed properties with literal names have declaration names");
        }
      }
      if (isPrivateIdentifier(name)) {
        const containingClass = getContainingClass(node);
        if (!containingClass) {
          return void 0;
        }
        const containingClassSymbol = containingClass.symbol;
        return getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
      }
      if (isJsxNamespacedName(name)) {
        return getEscapedTextOfJsxNamespacedName(name);
      }
      return isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0;
    }
    switch (node.kind) {
      case 176 /* Constructor */:
        return "__constructor" /* Constructor */;
      case 184 /* FunctionType */:
      case 179 /* CallSignature */:
      case 323 /* JSDocSignature */:
        return "__call" /* Call */;
      case 185 /* ConstructorType */:
      case 180 /* ConstructSignature */:
        return "__new" /* New */;
      case 181 /* IndexSignature */:
        return "__index" /* Index */;
      case 278 /* ExportDeclaration */:
        return "__export" /* ExportStar */;
      case 307 /* SourceFile */:
        return "export=" /* ExportEquals */;
      case 226 /* BinaryExpression */:
        if (getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
          return "export=" /* ExportEquals */;
        }
        Debug.fail("Unknown binary declaration kind");
        break;
      case 317 /* JSDocFunctionType */:
        return isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */;
      case 169 /* Parameter */:
        Debug.assert(node.parent.kind === 317 /* JSDocFunctionType */, "Impossible parameter parent kind", () => `parent is: ${Debug.formatSyntaxKind(node.parent.kind)}, expected JSDocFunctionType`);
        const functionType = node.parent;
        const index = functionType.parameters.indexOf(node);
        return "arg" + index;
    }
  }
  function getDisplayName(node) {
    return isNamedDeclaration(node) ? declarationNameToString(node.name) : unescapeLeadingUnderscores(Debug.checkDefined(getDeclarationName(node)));
  }
  function declareSymbol(symbolTable, parent2, node, includes, excludes, isReplaceableByMethod, isComputedName) {
    Debug.assert(isComputedName || !hasDynamicName(node));
    const isDefaultExport = hasSyntacticModifier(node, 2048 /* Default */) || isExportSpecifier(node) && moduleExportNameIsDefault(node.name);
    const name = isComputedName ? "__computed" /* Computed */ : isDefaultExport && parent2 ? "default" /* Default */ : getDeclarationName(node);
    let symbol;
    if (name === void 0) {
      symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
    } else {
      symbol = symbolTable.get(name);
      if (includes & 2885600 /* Classifiable */) {
        classifiableNames.add(name);
      }
      if (!symbol) {
        symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
        if (isReplaceableByMethod) symbol.isReplaceableByMethod = true;
      } else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
        return symbol;
      } else if (symbol.flags & excludes) {
        if (symbol.isReplaceableByMethod) {
          symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
        } else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
          if (isNamedDeclaration(node)) {
            setParent(node.name, node);
          }
          let message = symbol.flags & 2 /* BlockScopedVariable */ ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0;
          let messageNeedsName = true;
          if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
            message = Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
            messageNeedsName = false;
          }
          let multipleDefaultExports = false;
          if (length(symbol.declarations)) {
            if (isDefaultExport) {
              message = Diagnostics.A_module_cannot_have_multiple_default_exports;
              messageNeedsName = false;
              multipleDefaultExports = true;
            } else {
              if (symbol.declarations && symbol.declarations.length && (node.kind === 277 /* ExportAssignment */ && !node.isExportEquals)) {
                message = Diagnostics.A_module_cannot_have_multiple_default_exports;
                messageNeedsName = false;
                multipleDefaultExports = true;
              }
            }
          }
          const relatedInformation = [];
          if (isTypeAliasDeclaration(node) && nodeIsMissing(node.type) && hasSyntacticModifier(node, 32 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
            relatedInformation.push(createDiagnosticForNode2(node, Diagnostics.Did_you_mean_0, `export type { ${unescapeLeadingUnderscores(node.name.escapedText)} }`));
          }
          const declarationName = getNameOfDeclaration(node) || node;
          forEach(symbol.declarations, (declaration, index) => {
            const decl = getNameOfDeclaration(declaration) || declaration;
            const diag3 = messageNeedsName ? createDiagnosticForNode2(decl, message, getDisplayName(declaration)) : createDiagnosticForNode2(decl, message);
            file.bindDiagnostics.push(
              multipleDefaultExports ? addRelatedInfo(diag3, createDiagnosticForNode2(declarationName, index === 0 ? Diagnostics.Another_export_default_is_here : Diagnostics.and_here)) : diag3
            );
            if (multipleDefaultExports) {
              relatedInformation.push(createDiagnosticForNode2(decl, Diagnostics.The_first_export_default_is_here));
            }
          });
          const diag2 = messageNeedsName ? createDiagnosticForNode2(declarationName, message, getDisplayName(node)) : createDiagnosticForNode2(declarationName, message);
          file.bindDiagnostics.push(addRelatedInfo(diag2, ...relatedInformation));
          symbol = createSymbol(0 /* None */, name);
        }
      }
    }
    addDeclarationToSymbol(symbol, node, includes);
    if (symbol.parent) {
      Debug.assert(symbol.parent === parent2, "Existing symbol parent should match new one");
    } else {
      symbol.parent = parent2;
    }
    return symbol;
  }
  function declareModuleMember(node, symbolFlags, symbolExcludes) {
    const hasExportModifier = !!(getCombinedModifierFlags(node) & 32 /* Export */) || jsdocTreatAsExported(node);
    if (symbolFlags & 2097152 /* Alias */) {
      if (node.kind === 281 /* ExportSpecifier */ || node.kind === 271 /* ImportEqualsDeclaration */ && hasExportModifier) {
        return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
      } else {
        Debug.assertNode(container, canHaveLocals);
        return declareSymbol(
          container.locals,
          /*parent*/
          void 0,
          node,
          symbolFlags,
          symbolExcludes
        );
      }
    } else {
      if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node));
      if (!isAmbientModule(node) && (hasExportModifier || container.flags & 128 /* ExportContext */)) {
        if (!canHaveLocals(container) || !container.locals || hasSyntacticModifier(node, 2048 /* Default */) && !getDeclarationName(node)) {
          return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
        }
        const exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
        const local = declareSymbol(
          container.locals,
          /*parent*/
          void 0,
          node,
          exportKind,
          symbolExcludes
        );
        local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
        node.localSymbol = local;
        return local;
      } else {
        Debug.assertNode(container, canHaveLocals);
        return declareSymbol(
          container.locals,
          /*parent*/
          void 0,
          node,
          symbolFlags,
          symbolExcludes
        );
      }
    }
  }
  function jsdocTreatAsExported(node) {
    if (node.parent && isModuleDeclaration(node)) {
      node = node.parent;
    }
    if (!isJSDocTypeAlias(node)) return false;
    if (!isJSDocEnumTag(node) && !!node.fullName) return true;
    const declName = getNameOfDeclaration(node);
    if (!declName) return false;
    if (isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent)) return true;
    if (isDeclaration(declName.parent) && getCombinedModifierFlags(declName.parent) & 32 /* Export */) return true;
    return false;
  }
  function bindContainer(node, containerFlags) {
    const saveContainer = container;
    const saveThisParentContainer = thisParentContainer;
    const savedBlockScopeContainer = blockScopeContainer;
    if (containerFlags & 1 /* IsContainer */) {
      if (node.kind !== 219 /* ArrowFunction */) {
        thisParentContainer = container;
      }
      container = blockScopeContainer = node;
      if (containerFlags & 32 /* HasLocals */) {
        container.locals = createSymbolTable();
        addToContainerChain(container);
      }
    } else if (containerFlags & 2 /* IsBlockScopedContainer */) {
      blockScopeContainer = node;
      if (containerFlags & 32 /* HasLocals */) {
        blockScopeContainer.locals = void 0;
      }
    }
    if (containerFlags & 4 /* IsControlFlowContainer */) {
      const saveCurrentFlow = currentFlow;
      const saveBreakTarget = currentBreakTarget;
      const saveContinueTarget = currentContinueTarget;
      const saveReturnTarget = currentReturnTarget;
      const saveExceptionTarget = currentExceptionTarget;
      const saveActiveLabelList = activeLabelList;
      const saveHasExplicitReturn = hasExplicitReturn;
      const isImmediatelyInvoked = containerFlags & 16 /* IsFunctionExpression */ && !hasSyntacticModifier(node, 1024 /* Async */) && !node.asteriskToken && !!getImmediatelyInvokedFunctionExpression(node) || node.kind === 175 /* ClassStaticBlockDeclaration */;
      if (!isImmediatelyInvoked) {
        currentFlow = createFlowNode(
          2 /* Start */,
          /*node*/
          void 0,
          /*antecedent*/
          void 0
        );
        if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */)) {
          currentFlow.node = node;
        }
      }
      currentReturnTarget = isImmediatelyInvoked || node.kind === 176 /* Constructor */ || isInJSFile(node) && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */) ? createBranchLabel() : void 0;
      currentExceptionTarget = void 0;
      currentBreakTarget = void 0;
      currentContinueTarget = void 0;
      activeLabelList = void 0;
      hasExplicitReturn = false;
      bindChildren(node);
      node.flags &= ~5632 /* ReachabilityAndEmitFlags */;
      if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && nodeIsPresent(node.body)) {
        node.flags |= 512 /* HasImplicitReturn */;
        if (hasExplicitReturn) node.flags |= 1024 /* HasExplicitReturn */;
        node.endFlowNode = currentFlow;
      }
      if (node.kind === 307 /* SourceFile */) {
        node.flags |= emitFlags;
        node.endFlowNode = currentFlow;
      }
      if (currentReturnTarget) {
        addAntecedent(currentReturnTarget, currentFlow);
        currentFlow = finishFlowLabel(currentReturnTarget);
        if (node.kind === 176 /* Constructor */ || node.kind === 175 /* ClassStaticBlockDeclaration */ || isInJSFile(node) && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */)) {
          node.returnFlowNode = currentFlow;
        }
      }
      if (!isImmediatelyInvoked) {
        currentFlow = saveCurrentFlow;
      }
      currentBreakTarget = saveBreakTarget;
      currentContinueTarget = saveContinueTarget;
      currentReturnTarget = saveReturnTarget;
      currentExceptionTarget = saveExceptionTarget;
      activeLabelList = saveActiveLabelList;
      hasExplicitReturn = saveHasExplicitReturn;
    } else if (containerFlags & 64 /* IsInterface */) {
      seenThisKeyword = false;
      bindChildren(node);
      Debug.assertNotNode(node, isIdentifier);
      node.flags = seenThisKeyword ? node.flags | 256 /* ContainsThis */ : node.flags & ~256 /* ContainsThis */;
    } else {
      bindChildren(node);
    }
    container = saveContainer;
    thisParentContainer = saveThisParentContainer;
    blockScopeContainer = savedBlockScopeContainer;
  }
  function bindEachFunctionsFirst(nodes) {
    bindEach(nodes, (n) => n.kind === 262 /* FunctionDeclaration */ ? bind(n) : void 0);
    bindEach(nodes, (n) => n.kind !== 262 /* FunctionDeclaration */ ? bind(n) : void 0);
  }
  function bindEach(nodes, bindFunction = bind) {
    if (nodes === void 0) {
      return;
    }
    forEach(nodes, bindFunction);
  }
  function bindEachChild(node) {
    forEachChild(node, bind, bindEach);
  }
  function bindChildren(node) {
    const saveInAssignmentPattern = inAssignmentPattern;
    inAssignmentPattern = false;
    if (checkUnreachable(node)) {
      bindEachChild(node);
      bindJSDoc(node);
      inAssignmentPattern = saveInAssignmentPattern;
      return;
    }
    if (node.kind >= 243 /* FirstStatement */ && node.kind <= 259 /* LastStatement */ && (!options.allowUnreachableCode || node.kind === 253 /* ReturnStatement */)) {
      node.flowNode = currentFlow;
    }
    switch (node.kind) {
      case 247 /* WhileStatement */:
        bindWhileStatement(node);
        break;
      case 246 /* DoStatement */:
        bindDoStatement(node);
        break;
      case 248 /* ForStatement */:
        bindForStatement(node);
        break;
      case 249 /* ForInStatement */:
      case 250 /* ForOfStatement */:
        bindForInOrForOfStatement(node);
        break;
      case 245 /* IfStatement */:
        bindIfStatement(node);
        break;
      case 253 /* ReturnStatement */:
      case 257 /* ThrowStatement */:
        bindReturnOrThrow(node);
        break;
      case 252 /* BreakStatement */:
      case 251 /* ContinueStatement */:
        bindBreakOrContinueStatement(node);
        break;
      case 258 /* TryStatement */:
        bindTryStatement(node);
        break;
      case 255 /* SwitchStatement */:
        bindSwitchStatement(node);
        break;
      case 269 /* CaseBlock */:
        bindCaseBlock(node);
        break;
      case 296 /* CaseClause */:
        bindCaseClause(node);
        break;
      case 244 /* ExpressionStatement */:
        bindExpressionStatement(node);
        break;
      case 256 /* LabeledStatement */:
        bindLabeledStatement(node);
        break;
      case 224 /* PrefixUnaryExpression */:
        bindPrefixUnaryExpressionFlow(node);
        break;
      case 225 /* PostfixUnaryExpression */:
        bindPostfixUnaryExpressionFlow(node);
        break;
      case 226 /* BinaryExpression */:
        if (isDestructuringAssignment(node)) {
          inAssignmentPattern = saveInAssignmentPattern;
          bindDestructuringAssignmentFlow(node);
          return;
        }
        bindBinaryExpressionFlow(node);
        break;
      case 220 /* DeleteExpression */:
        bindDeleteExpressionFlow(node);
        break;
      case 227 /* ConditionalExpression */:
        bindConditionalExpressionFlow(node);
        break;
      case 260 /* VariableDeclaration */:
        bindVariableDeclarationFlow(node);
        break;
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        bindAccessExpressionFlow(node);
        break;
      case 213 /* CallExpression */:
        bindCallExpressionFlow(node);
        break;
      case 235 /* NonNullExpression */:
        bindNonNullExpressionFlow(node);
        break;
      case 346 /* JSDocTypedefTag */:
      case 338 /* JSDocCallbackTag */:
      case 340 /* JSDocEnumTag */:
        bindJSDocTypeAlias(node);
        break;
      case 351 /* JSDocImportTag */:
        bindJSDocImportTag(node);
        break;
      // In source files and blocks, bind functions first to match hoisting that occurs at runtime
      case 307 /* SourceFile */: {
        bindEachFunctionsFirst(node.statements);
        bind(node.endOfFileToken);
        break;
      }
      case 241 /* Block */:
      case 268 /* ModuleBlock */:
        bindEachFunctionsFirst(node.statements);
        break;
      case 208 /* BindingElement */:
        bindBindingElementFlow(node);
        break;
      case 169 /* Parameter */:
        bindParameterFlow(node);
        break;
      case 210 /* ObjectLiteralExpression */:
      case 209 /* ArrayLiteralExpression */:
      case 303 /* PropertyAssignment */:
      case 230 /* SpreadElement */:
        inAssignmentPattern = saveInAssignmentPattern;
      // falls through
      default:
        bindEachChild(node);
        break;
    }
    bindJSDoc(node);
    inAssignmentPattern = saveInAssignmentPattern;
  }
  function isNarrowingExpression(expr) {
    switch (expr.kind) {
      case 80 /* Identifier */:
      case 110 /* ThisKeyword */:
        return true;
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        return containsNarrowableReference(expr);
      case 213 /* CallExpression */:
        return hasNarrowableArgument(expr);
      case 217 /* ParenthesizedExpression */:
        if (isJSDocTypeAssertion(expr)) {
          return false;
        }
      // fallthrough
      case 235 /* NonNullExpression */:
        return isNarrowingExpression(expr.expression);
      case 226 /* BinaryExpression */:
        return isNarrowingBinaryExpression(expr);
      case 224 /* PrefixUnaryExpression */:
        return expr.operator === 54 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
      case 221 /* TypeOfExpression */:
        return isNarrowingExpression(expr.expression);
    }
    return false;
  }
  function isNarrowableReference(expr) {
    switch (expr.kind) {
      case 80 /* Identifier */:
      case 110 /* ThisKeyword */:
      case 108 /* SuperKeyword */:
      case 236 /* MetaProperty */:
        return true;
      case 211 /* PropertyAccessExpression */:
      case 217 /* ParenthesizedExpression */:
      case 235 /* NonNullExpression */:
        return isNarrowableReference(expr.expression);
      case 212 /* ElementAccessExpression */:
        return (isStringOrNumericLiteralLike(expr.argumentExpression) || isEntityNameExpression(expr.argumentExpression)) && isNarrowableReference(expr.expression);
      case 226 /* BinaryExpression */:
        return expr.operatorToken.kind === 28 /* CommaToken */ && isNarrowableReference(expr.right) || isAssignmentOperator(expr.operatorToken.kind) && isLeftHandSideExpression(expr.left);
    }
    return false;
  }
  function containsNarrowableReference(expr) {
    return isNarrowableReference(expr) || isOptionalChain(expr) && containsNarrowableReference(expr.expression);
  }
  function hasNarrowableArgument(expr) {
    if (expr.arguments) {
      for (const argument of expr.arguments) {
        if (containsNarrowableReference(argument)) {
          return true;
        }
      }
    }
    if (expr.expression.kind === 211 /* PropertyAccessExpression */ && containsNarrowableReference(expr.expression.expression)) {
      return true;
    }
    return false;
  }
  function isNarrowingTypeofOperands(expr1, expr2) {
    return isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && isStringLiteralLike(expr2);
  }
  function isNarrowingBinaryExpression(expr) {
    switch (expr.operatorToken.kind) {
      case 64 /* EqualsToken */:
      case 76 /* BarBarEqualsToken */:
      case 77 /* AmpersandAmpersandEqualsToken */:
      case 78 /* QuestionQuestionEqualsToken */:
        return containsNarrowableReference(expr.left);
      case 35 /* EqualsEqualsToken */:
      case 36 /* ExclamationEqualsToken */:
      case 37 /* EqualsEqualsEqualsToken */:
      case 38 /* ExclamationEqualsEqualsToken */:
        return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || (isBooleanLiteral(expr.right) && isNarrowingExpression(expr.left) || isBooleanLiteral(expr.left) && isNarrowingExpression(expr.right));
      case 104 /* InstanceOfKeyword */:
        return isNarrowableOperand(expr.left);
      case 103 /* InKeyword */:
        return isNarrowingExpression(expr.right);
      case 28 /* CommaToken */:
        return isNarrowingExpression(expr.right);
    }
    return false;
  }
  function isNarrowableOperand(expr) {
    switch (expr.kind) {
      case 217 /* ParenthesizedExpression */:
        return isNarrowableOperand(expr.expression);
      case 226 /* BinaryExpression */:
        switch (expr.operatorToken.kind) {
          case 64 /* EqualsToken */:
            return isNarrowableOperand(expr.left);
          case 28 /* CommaToken */:
            return isNarrowableOperand(expr.right);
        }
    }
    return containsNarrowableReference(expr);
  }
  function createBranchLabel() {
    return createFlowNode(
      4 /* BranchLabel */,
      /*node*/
      void 0,
      /*antecedent*/
      void 0
    );
  }
  function createLoopLabel() {
    return createFlowNode(
      8 /* LoopLabel */,
      /*node*/
      void 0,
      /*antecedent*/
      void 0
    );
  }
  function createReduceLabel(target, antecedents, antecedent) {
    return createFlowNode(1024 /* ReduceLabel */, { target, antecedents }, antecedent);
  }
  function setFlowNodeReferenced(flow) {
    flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
  }
  function addAntecedent(label, antecedent) {
    if (!(antecedent.flags & 1 /* Unreachable */) && !contains(label.antecedent, antecedent)) {
      (label.antecedent || (label.antecedent = [])).push(antecedent);
      setFlowNodeReferenced(antecedent);
    }
  }
  function createFlowCondition(flags, antecedent, expression) {
    if (antecedent.flags & 1 /* Unreachable */) {
      return antecedent;
    }
    if (!expression) {
      return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
    }
    if ((expression.kind === 112 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || expression.kind === 97 /* FalseKeyword */ && flags & 32 /* TrueCondition */) && !isExpressionOfOptionalChainRoot(expression) && !isNullishCoalesce(expression.parent)) {
      return unreachableFlow;
    }
    if (!isNarrowingExpression(expression)) {
      return antecedent;
    }
    setFlowNodeReferenced(antecedent);
    return createFlowNode(flags, expression, antecedent);
  }
  function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
    setFlowNodeReferenced(antecedent);
    return createFlowNode(128 /* SwitchClause */, { switchStatement, clauseStart, clauseEnd }, antecedent);
  }
  function createFlowMutation(flags, antecedent, node) {
    setFlowNodeReferenced(antecedent);
    hasFlowEffects = true;
    const result = createFlowNode(flags, node, antecedent);
    if (currentExceptionTarget) {
      addAntecedent(currentExceptionTarget, result);
    }
    return result;
  }
  function createFlowCall(antecedent, node) {
    setFlowNodeReferenced(antecedent);
    hasFlowEffects = true;
    return createFlowNode(512 /* Call */, node, antecedent);
  }
  function finishFlowLabel(flow) {
    const antecedents = flow.antecedent;
    if (!antecedents) {
      return unreachableFlow;
    }
    if (antecedents.length === 1) {
      return antecedents[0];
    }
    return flow;
  }
  function isStatementCondition(node) {
    const parent2 = node.parent;
    switch (parent2.kind) {
      case 245 /* IfStatement */:
      case 247 /* WhileStatement */:
      case 246 /* DoStatement */:
        return parent2.expression === node;
      case 248 /* ForStatement */:
      case 227 /* ConditionalExpression */:
        return parent2.condition === node;
    }
    return false;
  }
  function isLogicalExpression(node) {
    while (true) {
      if (node.kind === 217 /* ParenthesizedExpression */) {
        node = node.expression;
      } else if (node.kind === 224 /* PrefixUnaryExpression */ && node.operator === 54 /* ExclamationToken */) {
        node = node.operand;
      } else {
        return isLogicalOrCoalescingBinaryExpression(node);
      }
    }
  }
  function isLogicalAssignmentExpression(node) {
    return isLogicalOrCoalescingAssignmentExpression(skipParentheses(node));
  }
  function isTopLevelLogicalExpression(node) {
    while (isParenthesizedExpression(node.parent) || isPrefixUnaryExpression(node.parent) && node.parent.operator === 54 /* ExclamationToken */) {
      node = node.parent;
    }
    return !isStatementCondition(node) && !isLogicalExpression(node.parent) && !(isOptionalChain(node.parent) && node.parent.expression === node);
  }
  function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
    const savedTrueTarget = currentTrueTarget;
    const savedFalseTarget = currentFalseTarget;
    currentTrueTarget = trueTarget;
    currentFalseTarget = falseTarget;
    action(value);
    currentTrueTarget = savedTrueTarget;
    currentFalseTarget = savedFalseTarget;
  }
  function bindCondition(node, trueTarget, falseTarget) {
    doWithConditionalBranches(bind, node, trueTarget, falseTarget);
    if (!node || !isLogicalAssignmentExpression(node) && !isLogicalExpression(node) && !(isOptionalChain(node) && isOutermostOptionalChain(node))) {
      addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
      addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
    }
  }
  function bindIterativeStatement(node, breakTarget, continueTarget) {
    const saveBreakTarget = currentBreakTarget;
    const saveContinueTarget = currentContinueTarget;
    currentBreakTarget = breakTarget;
    currentContinueTarget = continueTarget;
    bind(node);
    currentBreakTarget = saveBreakTarget;
    currentContinueTarget = saveContinueTarget;
  }
  function setContinueTarget(node, target) {
    let label = activeLabelList;
    while (label && node.parent.kind === 256 /* LabeledStatement */) {
      label.continueTarget = target;
      label = label.next;
      node = node.parent;
    }
    return target;
  }
  function bindWhileStatement(node) {
    const preWhileLabel = setContinueTarget(node, createLoopLabel());
    const preBodyLabel = createBranchLabel();
    const postWhileLabel = createBranchLabel();
    addAntecedent(preWhileLabel, currentFlow);
    currentFlow = preWhileLabel;
    bindCondition(node.expression, preBodyLabel, postWhileLabel);
    currentFlow = finishFlowLabel(preBodyLabel);
    bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
    addAntecedent(preWhileLabel, currentFlow);
    currentFlow = finishFlowLabel(postWhileLabel);
  }
  function bindDoStatement(node) {
    const preDoLabel = createLoopLabel();
    const preConditionLabel = setContinueTarget(node, createBranchLabel());
    const postDoLabel = createBranchLabel();
    addAntecedent(preDoLabel, currentFlow);
    currentFlow = preDoLabel;
    bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
    addAntecedent(preConditionLabel, currentFlow);
    currentFlow = finishFlowLabel(preConditionLabel);
    bindCondition(node.expression, preDoLabel, postDoLabel);
    currentFlow = finishFlowLabel(postDoLabel);
  }
  function bindForStatement(node) {
    const preLoopLabel = setContinueTarget(node, createLoopLabel());
    const preBodyLabel = createBranchLabel();
    const postLoopLabel = createBranchLabel();
    bind(node.initializer);
    addAntecedent(preLoopLabel, currentFlow);
    currentFlow = preLoopLabel;
    bindCondition(node.condition, preBodyLabel, postLoopLabel);
    currentFlow = finishFlowLabel(preBodyLabel);
    bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
    bind(node.incrementor);
    addAntecedent(preLoopLabel, currentFlow);
    currentFlow = finishFlowLabel(postLoopLabel);
  }
  function bindForInOrForOfStatement(node) {
    const preLoopLabel = setContinueTarget(node, createLoopLabel());
    const postLoopLabel = createBranchLabel();
    bind(node.expression);
    addAntecedent(preLoopLabel, currentFlow);
    currentFlow = preLoopLabel;
    if (node.kind === 250 /* ForOfStatement */) {
      bind(node.awaitModifier);
    }
    addAntecedent(postLoopLabel, currentFlow);
    bind(node.initializer);
    if (node.initializer.kind !== 261 /* VariableDeclarationList */) {
      bindAssignmentTargetFlow(node.initializer);
    }
    bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
    addAntecedent(preLoopLabel, currentFlow);
    currentFlow = finishFlowLabel(postLoopLabel);
  }
  function bindIfStatement(node) {
    const thenLabel = createBranchLabel();
    const elseLabel = createBranchLabel();
    const postIfLabel = createBranchLabel();
    bindCondition(node.expression, thenLabel, elseLabel);
    currentFlow = finishFlowLabel(thenLabel);
    bind(node.thenStatement);
    addAntecedent(postIfLabel, currentFlow);
    currentFlow = finishFlowLabel(elseLabel);
    bind(node.elseStatement);
    addAntecedent(postIfLabel, currentFlow);
    currentFlow = finishFlowLabel(postIfLabel);
  }
  function bindReturnOrThrow(node) {
    bind(node.expression);
    if (node.kind === 253 /* ReturnStatement */) {
      hasExplicitReturn = true;
      if (currentReturnTarget) {
        addAntecedent(currentReturnTarget, currentFlow);
      }
    }
    currentFlow = unreachableFlow;
    hasFlowEffects = true;
  }
  function findActiveLabel(name) {
    for (let label = activeLabelList; label; label = label.next) {
      if (label.name === name) {
        return label;
      }
    }
    return void 0;
  }
  function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
    const flowLabel = node.kind === 252 /* BreakStatement */ ? breakTarget : continueTarget;
    if (flowLabel) {
      addAntecedent(flowLabel, currentFlow);
      currentFlow = unreachableFlow;
      hasFlowEffects = true;
    }
  }
  function bindBreakOrContinueStatement(node) {
    bind(node.label);
    if (node.label) {
      const activeLabel = findActiveLabel(node.label.escapedText);
      if (activeLabel) {
        activeLabel.referenced = true;
        bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
      }
    } else {
      bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
    }
  }
  function bindTryStatement(node) {
    const saveReturnTarget = currentReturnTarget;
    const saveExceptionTarget = currentExceptionTarget;
    const normalExitLabel = createBranchLabel();
    const returnLabel = createBranchLabel();
    let exceptionLabel = createBranchLabel();
    if (node.finallyBlock) {
      currentReturnTarget = returnLabel;
    }
    addAntecedent(exceptionLabel, currentFlow);
    currentExceptionTarget = exceptionLabel;
    bind(node.tryBlock);
    addAntecedent(normalExitLabel, currentFlow);
    if (node.catchClause) {
      currentFlow = finishFlowLabel(exceptionLabel);
      exceptionLabel = createBranchLabel();
      addAntecedent(exceptionLabel, currentFlow);
      currentExceptionTarget = exceptionLabel;
      bind(node.catchClause);
      addAntecedent(normalExitLabel, currentFlow);
    }
    currentReturnTarget = saveReturnTarget;
    currentExceptionTarget = saveExceptionTarget;
    if (node.finallyBlock) {
      const finallyLabel = createBranchLabel();
      finallyLabel.antecedent = concatenate(concatenate(normalExitLabel.antecedent, exceptionLabel.antecedent), returnLabel.antecedent);
      currentFlow = finallyLabel;
      bind(node.finallyBlock);
      if (currentFlow.flags & 1 /* Unreachable */) {
        currentFlow = unreachableFlow;
      } else {
        if (currentReturnTarget && returnLabel.antecedent) {
          addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedent, currentFlow));
        }
        if (currentExceptionTarget && exceptionLabel.antecedent) {
          addAntecedent(currentExceptionTarget, createReduceLabel(finallyLabel, exceptionLabel.antecedent, currentFlow));
        }
        currentFlow = normalExitLabel.antecedent ? createReduceLabel(finallyLabel, normalExitLabel.antecedent, currentFlow) : unreachableFlow;
      }
    } else {
      currentFlow = finishFlowLabel(normalExitLabel);
    }
  }
  function bindSwitchStatement(node) {
    const postSwitchLabel = createBranchLabel();
    bind(node.expression);
    const saveBreakTarget = currentBreakTarget;
    const savePreSwitchCaseFlow = preSwitchCaseFlow;
    currentBreakTarget = postSwitchLabel;
    preSwitchCaseFlow = currentFlow;
    bind(node.caseBlock);
    addAntecedent(postSwitchLabel, currentFlow);
    const hasDefault = forEach(node.caseBlock.clauses, (c) => c.kind === 297 /* DefaultClause */);
    node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedent;
    if (!hasDefault) {
      addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
    }
    currentBreakTarget = saveBreakTarget;
    preSwitchCaseFlow = savePreSwitchCaseFlow;
    currentFlow = finishFlowLabel(postSwitchLabel);
  }
  function bindCaseBlock(node) {
    const clauses = node.clauses;
    const isNarrowingSwitch = node.parent.expression.kind === 112 /* TrueKeyword */ || isNarrowingExpression(node.parent.expression);
    let fallthroughFlow = unreachableFlow;
    for (let i = 0; i < clauses.length; i++) {
      const clauseStart = i;
      while (!clauses[i].statements.length && i + 1 < clauses.length) {
        if (fallthroughFlow === unreachableFlow) {
          currentFlow = preSwitchCaseFlow;
        }
        bind(clauses[i]);
        i++;
      }
      const preCaseLabel = createBranchLabel();
      addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
      addAntecedent(preCaseLabel, fallthroughFlow);
      currentFlow = finishFlowLabel(preCaseLabel);
      const clause = clauses[i];
      bind(clause);
      fallthroughFlow = currentFlow;
      if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
        clause.fallthroughFlowNode = currentFlow;
      }
    }
  }
  function bindCaseClause(node) {
    const saveCurrentFlow = currentFlow;
    currentFlow = preSwitchCaseFlow;
    bind(node.expression);
    currentFlow = saveCurrentFlow;
    bindEach(node.statements);
  }
  function bindExpressionStatement(node) {
    bind(node.expression);
    maybeBindExpressionFlowIfCall(node.expression);
  }
  function maybeBindExpressionFlowIfCall(node) {
    if (node.kind === 213 /* CallExpression */) {
      const call = node;
      if (call.expression.kind !== 108 /* SuperKeyword */ && isDottedName(call.expression)) {
        currentFlow = createFlowCall(currentFlow, call);
      }
    }
  }
  function bindLabeledStatement(node) {
    const postStatementLabel = createBranchLabel();
    activeLabelList = {
      next: activeLabelList,
      name: node.label.escapedText,
      breakTarget: postStatementLabel,
      continueTarget: void 0,
      referenced: false
    };
    bind(node.label);
    bind(node.statement);
    if (!activeLabelList.referenced && !options.allowUnusedLabels) {
      errorOrSuggestionOnNode(unusedLabelIsError(options), node.label, Diagnostics.Unused_label);
    }
    activeLabelList = activeLabelList.next;
    addAntecedent(postStatementLabel, currentFlow);
    currentFlow = finishFlowLabel(postStatementLabel);
  }
  function bindDestructuringTargetFlow(node) {
    if (node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */) {
      bindAssignmentTargetFlow(node.left);
    } else {
      bindAssignmentTargetFlow(node);
    }
  }
  function bindAssignmentTargetFlow(node) {
    if (isNarrowableReference(node)) {
      currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
    } else if (node.kind === 209 /* ArrayLiteralExpression */) {
      for (const e of node.elements) {
        if (e.kind === 230 /* SpreadElement */) {
          bindAssignmentTargetFlow(e.expression);
        } else {
          bindDestructuringTargetFlow(e);
        }
      }
    } else if (node.kind === 210 /* ObjectLiteralExpression */) {
      for (const p of node.properties) {
        if (p.kind === 303 /* PropertyAssignment */) {
          bindDestructuringTargetFlow(p.initializer);
        } else if (p.kind === 304 /* ShorthandPropertyAssignment */) {
          bindAssignmentTargetFlow(p.name);
        } else if (p.kind === 305 /* SpreadAssignment */) {
          bindAssignmentTargetFlow(p.expression);
        }
      }
    }
  }
  function bindLogicalLikeExpression(node, trueTarget, falseTarget) {
    const preRightLabel = createBranchLabel();
    if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 77 /* AmpersandAmpersandEqualsToken */) {
      bindCondition(node.left, preRightLabel, falseTarget);
    } else {
      bindCondition(node.left, trueTarget, preRightLabel);
    }
    currentFlow = finishFlowLabel(preRightLabel);
    bind(node.operatorToken);
    if (isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind)) {
      doWithConditionalBranches(bind, node.right, trueTarget, falseTarget);
      bindAssignmentTargetFlow(node.left);
      addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
      addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
    } else {
      bindCondition(node.right, trueTarget, falseTarget);
    }
  }
  function bindPrefixUnaryExpressionFlow(node) {
    if (node.operator === 54 /* ExclamationToken */) {
      const saveTrueTarget = currentTrueTarget;
      currentTrueTarget = currentFalseTarget;
      currentFalseTarget = saveTrueTarget;
      bindEachChild(node);
      currentFalseTarget = currentTrueTarget;
      currentTrueTarget = saveTrueTarget;
    } else {
      bindEachChild(node);
      if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) {
        bindAssignmentTargetFlow(node.operand);
      }
    }
  }
  function bindPostfixUnaryExpressionFlow(node) {
    bindEachChild(node);
    if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) {
      bindAssignmentTargetFlow(node.operand);
    }
  }
  function bindDestructuringAssignmentFlow(node) {
    if (inAssignmentPattern) {
      inAssignmentPattern = false;
      bind(node.operatorToken);
      bind(node.right);
      inAssignmentPattern = true;
      bind(node.left);
    } else {
      inAssignmentPattern = true;
      bind(node.left);
      inAssignmentPattern = false;
      bind(node.operatorToken);
      bind(node.right);
    }
    bindAssignmentTargetFlow(node.left);
  }
  function createBindBinaryExpressionFlow() {
    return createBinaryExpressionTrampoline(
      onEnter,
      onLeft,
      onOperator,
      onRight,
      onExit,
      /*foldState*/
      void 0
    );
    function onEnter(node, state) {
      if (state) {
        state.stackIndex++;
        setParent(node, parent);
        const saveInStrictMode = inStrictMode;
        bindWorker(node);
        const saveParent = parent;
        parent = node;
        state.skip = false;
        state.inStrictModeStack[state.stackIndex] = saveInStrictMode;
        state.parentStack[state.stackIndex] = saveParent;
      } else {
        state = {
          stackIndex: 0,
          skip: false,
          inStrictModeStack: [void 0],
          parentStack: [void 0]
        };
      }
      const operator = node.operatorToken.kind;
      if (isLogicalOrCoalescingBinaryOperator(operator) || isLogicalOrCoalescingAssignmentOperator(operator)) {
        if (isTopLevelLogicalExpression(node)) {
          const postExpressionLabel = createBranchLabel();
          const saveCurrentFlow = currentFlow;
          const saveHasFlowEffects = hasFlowEffects;
          hasFlowEffects = false;
          bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel);
          currentFlow = hasFlowEffects ? finishFlowLabel(postExpressionLabel) : saveCurrentFlow;
          hasFlowEffects || (hasFlowEffects = saveHasFlowEffects);
        } else {
          bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget);
        }
        state.skip = true;
      }
      return state;
    }
    function onLeft(left, state, node) {
      if (!state.skip) {
        const maybeBound = maybeBind2(left);
        if (node.operatorToken.kind === 28 /* CommaToken */) {
          maybeBindExpressionFlowIfCall(left);
        }
        return maybeBound;
      }
    }
    function onOperator(operatorToken, state, _node) {
      if (!state.skip) {
        bind(operatorToken);
      }
    }
    function onRight(right, state, node) {
      if (!state.skip) {
        const maybeBound = maybeBind2(right);
        if (node.operatorToken.kind === 28 /* CommaToken */) {
          maybeBindExpressionFlowIfCall(right);
        }
        return maybeBound;
      }
    }
    function onExit(node, state) {
      if (!state.skip) {
        const operator = node.operatorToken.kind;
        if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) {
          bindAssignmentTargetFlow(node.left);
          if (operator === 64 /* EqualsToken */ && node.left.kind === 212 /* ElementAccessExpression */) {
            const elementAccess = node.left;
            if (isNarrowableOperand(elementAccess.expression)) {
              currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
            }
          }
        }
      }
      const savedInStrictMode = state.inStrictModeStack[state.stackIndex];
      const savedParent = state.parentStack[state.stackIndex];
      if (savedInStrictMode !== void 0) {
        inStrictMode = savedInStrictMode;
      }
      if (savedParent !== void 0) {
        parent = savedParent;
      }
      state.skip = false;
      state.stackIndex--;
    }
    function maybeBind2(node) {
      if (node && isBinaryExpression(node) && !isDestructuringAssignment(node)) {
        return node;
      }
      bind(node);
    }
  }
  function bindDeleteExpressionFlow(node) {
    bindEachChild(node);
    if (node.expression.kind === 211 /* PropertyAccessExpression */) {
      bindAssignmentTargetFlow(node.expression);
    }
  }
  function bindConditionalExpressionFlow(node) {
    const trueLabel = createBranchLabel();
    const falseLabel = createBranchLabel();
    const postExpressionLabel = createBranchLabel();
    const saveCurrentFlow = currentFlow;
    const saveHasFlowEffects = hasFlowEffects;
    hasFlowEffects = false;
    bindCondition(node.condition, trueLabel, falseLabel);
    currentFlow = finishFlowLabel(trueLabel);
    bind(node.questionToken);
    bind(node.whenTrue);
    addAntecedent(postExpressionLabel, currentFlow);
    currentFlow = finishFlowLabel(falseLabel);
    bind(node.colonToken);
    bind(node.whenFalse);
    addAntecedent(postExpressionLabel, currentFlow);
    currentFlow = hasFlowEffects ? finishFlowLabel(postExpressionLabel) : saveCurrentFlow;
    hasFlowEffects || (hasFlowEffects = saveHasFlowEffects);
  }
  function bindInitializedVariableFlow(node) {
    const name = !isOmittedExpression(node) ? node.name : void 0;
    if (isBindingPattern(name)) {
      for (const child of name.elements) {
        bindInitializedVariableFlow(child);
      }
    } else {
      currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
    }
  }
  function bindVariableDeclarationFlow(node) {
    bindEachChild(node);
    if (node.initializer || isForInOrOfStatement(node.parent.parent)) {
      bindInitializedVariableFlow(node);
    }
  }
  function bindBindingElementFlow(node) {
    bind(node.dotDotDotToken);
    bind(node.propertyName);
    bindInitializer(node.initializer);
    bind(node.name);
  }
  function bindParameterFlow(node) {
    bindEach(node.modifiers);
    bind(node.dotDotDotToken);
    bind(node.questionToken);
    bind(node.type);
    bindInitializer(node.initializer);
    bind(node.name);
  }
  function bindInitializer(node) {
    if (!node) {
      return;
    }
    const entryFlow = currentFlow;
    bind(node);
    if (entryFlow === unreachableFlow || entryFlow === currentFlow) {
      return;
    }
    const exitFlow = createBranchLabel();
    addAntecedent(exitFlow, entryFlow);
    addAntecedent(exitFlow, currentFlow);
    currentFlow = finishFlowLabel(exitFlow);
  }
  function bindJSDocTypeAlias(node) {
    bind(node.tagName);
    if (node.kind !== 340 /* JSDocEnumTag */ && node.fullName) {
      setParent(node.fullName, node);
      setParentRecursive(
        node.fullName,
        /*incremental*/
        false
      );
    }
    if (typeof node.comment !== "string") {
      bindEach(node.comment);
    }
  }
  function bindJSDocClassTag(node) {
    bindEachChild(node);
    const host = getHostSignatureFromJSDoc(node);
    if (host && host.kind !== 174 /* MethodDeclaration */) {
      addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
    }
  }
  function bindJSDocImportTag(node) {
    bind(node.tagName);
    bind(node.moduleSpecifier);
    bind(node.attributes);
    if (typeof node.comment !== "string") {
      bindEach(node.comment);
    }
  }
  function bindOptionalExpression(node, trueTarget, falseTarget) {
    doWithConditionalBranches(bind, node, trueTarget, falseTarget);
    if (!isOptionalChain(node) || isOutermostOptionalChain(node)) {
      addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
      addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
    }
  }
  function bindOptionalChainRest(node) {
    switch (node.kind) {
      case 211 /* PropertyAccessExpression */:
        bind(node.questionDotToken);
        bind(node.name);
        break;
      case 212 /* ElementAccessExpression */:
        bind(node.questionDotToken);
        bind(node.argumentExpression);
        break;
      case 213 /* CallExpression */:
        bind(node.questionDotToken);
        bindEach(node.typeArguments);
        bindEach(node.arguments);
        break;
    }
  }
  function bindOptionalChain(node, trueTarget, falseTarget) {
    const preChainLabel = isOptionalChainRoot(node) ? createBranchLabel() : void 0;
    bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
    if (preChainLabel) {
      currentFlow = finishFlowLabel(preChainLabel);
    }
    doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
    if (isOutermostOptionalChain(node)) {
      addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
      addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
    }
  }
  function bindOptionalChainFlow(node) {
    if (isTopLevelLogicalExpression(node)) {
      const postExpressionLabel = createBranchLabel();
      const saveCurrentFlow = currentFlow;
      const saveHasFlowEffects = hasFlowEffects;
      bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
      currentFlow = hasFlowEffects ? finishFlowLabel(postExpressionLabel) : saveCurrentFlow;
      hasFlowEffects || (hasFlowEffects = saveHasFlowEffects);
    } else {
      bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
    }
  }
  function bindNonNullExpressionFlow(node) {
    if (isOptionalChain(node)) {
      bindOptionalChainFlow(node);
    } else {
      bindEachChild(node);
    }
  }
  function bindAccessExpressionFlow(node) {
    if (isOptionalChain(node)) {
      bindOptionalChainFlow(node);
    } else {
      bindEachChild(node);
    }
  }
  function bindCallExpressionFlow(node) {
    if (isOptionalChain(node)) {
      bindOptionalChainFlow(node);
    } else {
      const expr = skipParentheses(node.expression);
      if (expr.kind === 218 /* FunctionExpression */ || expr.kind === 219 /* ArrowFunction */) {
        bindEach(node.typeArguments);
        bindEach(node.arguments);
        bind(node.expression);
      } else {
        bindEachChild(node);
        if (node.expression.kind === 108 /* SuperKeyword */) {
          currentFlow = createFlowCall(currentFlow, node);
        }
      }
    }
    if (node.expression.kind === 211 /* PropertyAccessExpression */) {
      const propertyAccess = node.expression;
      if (isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && isPushOrUnshiftIdentifier(propertyAccess.name)) {
        currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
      }
    }
  }
  function addToContainerChain(next) {
    if (lastContainer) {
      lastContainer.nextContainer = next;
    }
    lastContainer = next;
  }
  function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
    switch (container.kind) {
      // Modules, source files, and classes need specialized handling for how their
      // members are declared (for example, a member of a class will go into a specific
      // symbol table depending on if it is static or not). We defer to specialized
      // handlers to take care of declaring these child members.
      case 267 /* ModuleDeclaration */:
        return declareModuleMember(node, symbolFlags, symbolExcludes);
      case 307 /* SourceFile */:
        return declareSourceFileMember(node, symbolFlags, symbolExcludes);
      case 231 /* ClassExpression */:
      case 263 /* ClassDeclaration */:
        return declareClassMember(node, symbolFlags, symbolExcludes);
      case 266 /* EnumDeclaration */:
        return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
      case 187 /* TypeLiteral */:
      case 322 /* JSDocTypeLiteral */:
      case 210 /* ObjectLiteralExpression */:
      case 264 /* InterfaceDeclaration */:
      case 292 /* JsxAttributes */:
        return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
      case 184 /* FunctionType */:
      case 185 /* ConstructorType */:
      case 179 /* CallSignature */:
      case 180 /* ConstructSignature */:
      case 323 /* JSDocSignature */:
      case 181 /* IndexSignature */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
      case 176 /* Constructor */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 317 /* JSDocFunctionType */:
      case 175 /* ClassStaticBlockDeclaration */:
      case 265 /* TypeAliasDeclaration */:
      case 200 /* MappedType */:
        if (container.locals) Debug.assertNode(container, canHaveLocals);
        return declareSymbol(
          container.locals,
          /*parent*/
          void 0,
          node,
          symbolFlags,
          symbolExcludes
        );
    }
  }
  function declareClassMember(node, symbolFlags, symbolExcludes) {
    return isStatic(node) ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
  }
  function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
    return isExternalModule(file) ? declareModuleMember(node, symbolFlags, symbolExcludes) : declareSymbol(
      file.locals,
      /*parent*/
      void 0,
      node,
      symbolFlags,
      symbolExcludes
    );
  }
  function hasExportDeclarations(node) {
    const body = isSourceFile(node) ? node : tryCast(node.body, isModuleBlock);
    return !!body && body.statements.some((s) => isExportDeclaration(s) || isExportAssignment(s));
  }
  function setExportContextFlag(node) {
    if (node.flags & 33554432 /* Ambient */ && !hasExportDeclarations(node)) {
      node.flags |= 128 /* ExportContext */;
    } else {
      node.flags &= ~128 /* ExportContext */;
    }
  }
  function bindModuleDeclaration(node) {
    setExportContextFlag(node);
    if (isAmbientModule(node)) {
      if (hasSyntacticModifier(node, 32 /* Export */)) {
        errorOnFirstToken(node, Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
      }
      if (isModuleAugmentationExternal(node)) {
        declareModuleSymbol(node);
      } else {
        let pattern;
        if (node.name.kind === 11 /* StringLiteral */) {
          const { text } = node.name;
          pattern = tryParsePattern(text);
          if (pattern === void 0) {
            errorOnFirstToken(node.name, Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
          }
        }
        const symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
        file.patternAmbientModules = append(file.patternAmbientModules, pattern && !isString(pattern) ? { pattern, symbol } : void 0);
      }
    } else {
      const state = declareModuleSymbol(node);
      if (state !== 0 /* NonInstantiated */) {
        const { symbol } = node;
        symbol.constEnumOnlyModule = !(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) && state === 2 /* ConstEnumOnly */ && symbol.constEnumOnlyModule !== false;
      }
    }
  }
  function declareModuleSymbol(node) {
    const state = getModuleInstanceState(node);
    const instantiated = state !== 0 /* NonInstantiated */;
    declareSymbolAndAddToSymbolTable(
      node,
      instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */,
      instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */
    );
    return state;
  }
  function bindFunctionOrConstructorType(node) {
    const symbol = createSymbol(131072 /* Signature */, getDeclarationName(node));
    addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
    const typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
    addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
    typeLiteralSymbol.members = createSymbolTable();
    typeLiteralSymbol.members.set(symbol.escapedName, symbol);
  }
  function bindObjectLiteralExpression(node) {
    return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
  }
  function bindJsxAttributes(node) {
    return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
  }
  function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
    return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
  }
  function bindAnonymousDeclaration(node, symbolFlags, name) {
    const symbol = createSymbol(symbolFlags, name);
    if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
      symbol.parent = container.symbol;
    }
    addDeclarationToSymbol(symbol, node, symbolFlags);
    return symbol;
  }
  function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
    switch (blockScopeContainer.kind) {
      case 267 /* ModuleDeclaration */:
        declareModuleMember(node, symbolFlags, symbolExcludes);
        break;
      case 307 /* SourceFile */:
        if (isExternalOrCommonJsModule(container)) {
          declareModuleMember(node, symbolFlags, symbolExcludes);
          break;
        }
      // falls through
      default:
        Debug.assertNode(blockScopeContainer, canHaveLocals);
        if (!blockScopeContainer.locals) {
          blockScopeContainer.locals = createSymbolTable();
          addToContainerChain(blockScopeContainer);
        }
        declareSymbol(
          blockScopeContainer.locals,
          /*parent*/
          void 0,
          node,
          symbolFlags,
          symbolExcludes
        );
    }
  }
  function delayedBindJSDocTypedefTag() {
    if (!delayedTypeAliases) {
      return;
    }
    const saveContainer = container;
    const saveLastContainer = lastContainer;
    const saveBlockScopeContainer = blockScopeContainer;
    const saveParent = parent;
    const saveCurrentFlow = currentFlow;
    for (const typeAlias of delayedTypeAliases) {
      const host = typeAlias.parent.parent;
      container = getEnclosingContainer(host) || file;
      blockScopeContainer = getEnclosingBlockScopeContainer(host) || file;
      currentFlow = createFlowNode(
        2 /* Start */,
        /*node*/
        void 0,
        /*antecedent*/
        void 0
      );
      parent = typeAlias;
      bind(typeAlias.typeExpression);
      const declName = getNameOfDeclaration(typeAlias);
      if ((isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && isPropertyAccessEntityNameExpression(declName.parent)) {
        const isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
        if (isTopLevel) {
          bindPotentiallyMissingNamespaces(
            file.symbol,
            declName.parent,
            isTopLevel,
            !!findAncestor(declName, (d) => isPropertyAccessExpression(d) && d.name.escapedText === "prototype"),
            /*containerIsClass*/
            false
          );
          const oldContainer = container;
          switch (getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
            case 1 /* ExportsProperty */:
            case 2 /* ModuleExports */:
              if (!isExternalOrCommonJsModule(file)) {
                container = void 0;
              } else {
                container = file;
              }
              break;
            case 4 /* ThisProperty */:
              container = declName.parent.expression;
              break;
            case 3 /* PrototypeProperty */:
              container = declName.parent.expression.name;
              break;
            case 5 /* Property */:
              container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file : isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name : declName.parent.expression;
              break;
            case 0 /* None */:
              return Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
          }
          if (container) {
            declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
          }
          container = oldContainer;
        }
      } else if (isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 80 /* Identifier */) {
        parent = typeAlias.parent;
        bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
      } else {
        bind(typeAlias.fullName);
      }
    }
    container = saveContainer;
    lastContainer = saveLastContainer;
    blockScopeContainer = saveBlockScopeContainer;
    parent = saveParent;
    currentFlow = saveCurrentFlow;
  }
  function bindJSDocImports() {
    if (jsDocImports === void 0) {
      return;
    }
    const saveContainer = container;
    const saveLastContainer = lastContainer;
    const saveBlockScopeContainer = blockScopeContainer;
    const saveParent = parent;
    const saveCurrentFlow = currentFlow;
    for (const jsDocImportTag of jsDocImports) {
      const host = getJSDocHost(jsDocImportTag);
      const enclosingContainer = host ? getEnclosingContainer(host) : void 0;
      const enclosingBlockScopeContainer = host ? getEnclosingBlockScopeContainer(host) : void 0;
      container = enclosingContainer || file;
      blockScopeContainer = enclosingBlockScopeContainer || file;
      currentFlow = createFlowNode(
        2 /* Start */,
        /*node*/
        void 0,
        /*antecedent*/
        void 0
      );
      parent = jsDocImportTag;
      bind(jsDocImportTag.importClause);
    }
    container = saveContainer;
    lastContainer = saveLastContainer;
    blockScopeContainer = saveBlockScopeContainer;
    parent = saveParent;
    currentFlow = saveCurrentFlow;
  }
  function checkContextualIdentifier(node) {
    if (!file.parseDiagnostics.length && !(node.flags & 33554432 /* Ambient */) && !(node.flags & 16777216 /* JSDoc */) && !isIdentifierName(node)) {
      const originalKeywordKind = identifierToKeywordKind(node);
      if (originalKeywordKind === void 0) {
        return;
      }
      if (inStrictMode && originalKeywordKind >= 119 /* FirstFutureReservedWord */ && originalKeywordKind <= 127 /* LastFutureReservedWord */) {
        file.bindDiagnostics.push(createDiagnosticForNode2(node, getStrictModeIdentifierMessage(node), declarationNameToString(node)));
      } else if (originalKeywordKind === 135 /* AwaitKeyword */) {
        if (isExternalModule(file) && isInTopLevelContext(node)) {
          file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, declarationNameToString(node)));
        } else if (node.flags & 65536 /* AwaitContext */) {
          file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node)));
        }
      } else if (originalKeywordKind === 127 /* YieldKeyword */ && node.flags & 16384 /* YieldContext */) {
        file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node)));
      }
    }
  }
  function getStrictModeIdentifierMessage(node) {
    if (getContainingClass(node)) {
      return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
    }
    if (file.externalModuleIndicator) {
      return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
    }
    return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
  }
  function checkPrivateIdentifier(node) {
    if (node.escapedText === "#constructor") {
      if (!file.parseDiagnostics.length) {
        file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.constructor_is_a_reserved_word, declarationNameToString(node)));
      }
    }
  }
  function checkStrictModeBinaryExpression(node) {
    if (inStrictMode && isLeftHandSideExpression(node.left) && isAssignmentOperator(node.operatorToken.kind)) {
      checkStrictModeEvalOrArguments(node, node.left);
    }
  }
  function checkStrictModeCatchClause(node) {
    if (inStrictMode && node.variableDeclaration) {
      checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
    }
  }
  function checkStrictModeDeleteExpression(node) {
    if (inStrictMode && node.expression.kind === 80 /* Identifier */) {
      const span = getErrorSpanForNode(file, node.expression);
      file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
    }
  }
  function isEvalOrArgumentsIdentifier(node) {
    return isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
  }
  function checkStrictModeEvalOrArguments(contextNode, name) {
    if (name && name.kind === 80 /* Identifier */) {
      const identifier = name;
      if (isEvalOrArgumentsIdentifier(identifier)) {
        const span = getErrorSpanForNode(file, name);
        file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), idText(identifier)));
      }
    }
  }
  function getStrictModeEvalOrArgumentsMessage(node) {
    if (getContainingClass(node)) {
      return Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode;
    }
    if (file.externalModuleIndicator) {
      return Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
    }
    return Diagnostics.Invalid_use_of_0_in_strict_mode;
  }
  function checkStrictModeFunctionName(node) {
    if (inStrictMode && !(node.flags & 33554432 /* Ambient */)) {
      checkStrictModeEvalOrArguments(node, node.name);
    }
  }
  function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
    if (getContainingClass(node)) {
      return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definitions_are_automatically_in_strict_mode;
    }
    if (file.externalModuleIndicator) {
      return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_automatically_in_strict_mode;
    }
    return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5;
  }
  function checkStrictModeFunctionDeclaration(node) {
    if (languageVersion < 2 /* ES2015 */) {
      if (blockScopeContainer.kind !== 307 /* SourceFile */ && blockScopeContainer.kind !== 267 /* ModuleDeclaration */ && !isFunctionLikeOrClassStaticBlockDeclaration(blockScopeContainer)) {
        const errorSpan = getErrorSpanForNode(file, node);
        file.bindDiagnostics.push(createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
      }
    }
  }
  function checkStrictModePostfixUnaryExpression(node) {
    if (inStrictMode) {
      checkStrictModeEvalOrArguments(node, node.operand);
    }
  }
  function checkStrictModePrefixUnaryExpression(node) {
    if (inStrictMode) {
      if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) {
        checkStrictModeEvalOrArguments(node, node.operand);
      }
    }
  }
  function checkStrictModeWithStatement(node) {
    if (inStrictMode) {
      errorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_strict_mode);
    }
  }
  function checkStrictModeLabeledStatement(node) {
    if (inStrictMode && getEmitScriptTarget(options) >= 2 /* ES2015 */) {
      if (isDeclarationStatement(node.statement) || isVariableStatement(node.statement)) {
        errorOnFirstToken(node.label, Diagnostics.A_label_is_not_allowed_here);
      }
    }
  }
  function errorOnFirstToken(node, message, ...args) {
    const span = getSpanOfTokenAtPosition(file, node.pos);
    file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, ...args));
  }
  function errorOrSuggestionOnNode(isError, node, message) {
    errorOrSuggestionOnRange(isError, node, node, message);
  }
  function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
    addErrorOrSuggestionDiagnostic(isError, { pos: getTokenPosOfNode(startNode, file), end: endNode.end }, message);
  }
  function addErrorOrSuggestionDiagnostic(isError, range, message) {
    const diag2 = createFileDiagnostic(file, range.pos, range.end - range.pos, message);
    if (isError) {
      file.bindDiagnostics.push(diag2);
    } else {
      file.bindSuggestionDiagnostics = append(file.bindSuggestionDiagnostics, { ...diag2, category: 2 /* Suggestion */ });
    }
  }
  function bind(node) {
    if (!node) {
      return;
    }
    setParent(node, parent);
    if (tracing) node.tracingPath = file.path;
    const saveInStrictMode = inStrictMode;
    bindWorker(node);
    if (node.kind > 165 /* LastToken */) {
      const saveParent = parent;
      parent = node;
      const containerFlags = getContainerFlags(node);
      if (containerFlags === 0 /* None */) {
        bindChildren(node);
      } else {
        bindContainer(node, containerFlags);
      }
      parent = saveParent;
    } else {
      const saveParent = parent;
      if (node.kind === 1 /* EndOfFileToken */) parent = node;
      bindJSDoc(node);
      parent = saveParent;
    }
    inStrictMode = saveInStrictMode;
  }
  function bindJSDoc(node) {
    if (hasJSDocNodes(node)) {
      if (isInJSFile(node)) {
        for (const j of node.jsDoc) {
          bind(j);
        }
      } else {
        for (const j of node.jsDoc) {
          setParent(j, node);
          setParentRecursive(
            j,
            /*incremental*/
            false
          );
        }
      }
    }
  }
  function updateStrictModeStatementList(statements) {
    if (!inStrictMode) {
      for (const statement of statements) {
        if (!isPrologueDirective(statement)) {
          return;
        }
        if (isUseStrictPrologueDirective(statement)) {
          inStrictMode = true;
          return;
        }
      }
    }
  }
  function isUseStrictPrologueDirective(node) {
    const nodeText = getSourceTextOfNodeFromSourceFile(file, node.expression);
    return nodeText === '"use strict"' || nodeText === "'use strict'";
  }
  function bindWorker(node) {
    switch (node.kind) {
      /* Strict mode checks */
      case 80 /* Identifier */:
        if (node.flags & 4096 /* IdentifierIsInJSDocNamespace */) {
          let parentNode = node.parent;
          while (parentNode && !isJSDocTypeAlias(parentNode)) {
            parentNode = parentNode.parent;
          }
          bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
          break;
        }
      // falls through
      case 110 /* ThisKeyword */:
        if (currentFlow && (isExpression(node) || parent.kind === 304 /* ShorthandPropertyAssignment */)) {
          node.flowNode = currentFlow;
        }
        return checkContextualIdentifier(node);
      case 166 /* QualifiedName */:
        if (currentFlow && isPartOfTypeQuery(node)) {
          node.flowNode = currentFlow;
        }
        break;
      case 236 /* MetaProperty */:
      case 108 /* SuperKeyword */:
        node.flowNode = currentFlow;
        break;
      case 81 /* PrivateIdentifier */:
        return checkPrivateIdentifier(node);
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        const expr = node;
        if (currentFlow && isNarrowableReference(expr)) {
          expr.flowNode = currentFlow;
        }
        if (isSpecialPropertyDeclaration(expr)) {
          bindSpecialPropertyDeclaration(expr);
        }
        if (isInJSFile(expr) && file.commonJsModuleIndicator && isModuleExportsAccessExpression(expr) && !lookupSymbolForName(blockScopeContainer, "module")) {
          declareSymbol(
            file.locals,
            /*parent*/
            void 0,
            expr.expression,
            1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */,
            111550 /* FunctionScopedVariableExcludes */
          );
        }
        break;
      case 226 /* BinaryExpression */:
        const specialKind = getAssignmentDeclarationKind(node);
        switch (specialKind) {
          case 1 /* ExportsProperty */:
            bindExportsPropertyAssignment(node);
            break;
          case 2 /* ModuleExports */:
            bindModuleExportsAssignment(node);
            break;
          case 3 /* PrototypeProperty */:
            bindPrototypePropertyAssignment(node.left, node);
            break;
          case 6 /* Prototype */:
            bindPrototypeAssignment(node);
            break;
          case 4 /* ThisProperty */:
            bindThisPropertyAssignment(node);
            break;
          case 5 /* Property */:
            const expression = node.left.expression;
            if (isInJSFile(node) && isIdentifier(expression)) {
              const symbol = lookupSymbolForName(blockScopeContainer, expression.escapedText);
              if (isThisInitializedDeclaration(symbol == null ? void 0 : symbol.valueDeclaration)) {
                bindThisPropertyAssignment(node);
                break;
              }
            }
            bindSpecialPropertyAssignment(node);
            break;
          case 0 /* None */:
            break;
          default:
            Debug.fail("Unknown binary expression special property assignment kind");
        }
        return checkStrictModeBinaryExpression(node);
      case 299 /* CatchClause */:
        return checkStrictModeCatchClause(node);
      case 220 /* DeleteExpression */:
        return checkStrictModeDeleteExpression(node);
      case 225 /* PostfixUnaryExpression */:
        return checkStrictModePostfixUnaryExpression(node);
      case 224 /* PrefixUnaryExpression */:
        return checkStrictModePrefixUnaryExpression(node);
      case 254 /* WithStatement */:
        return checkStrictModeWithStatement(node);
      case 256 /* LabeledStatement */:
        return checkStrictModeLabeledStatement(node);
      case 197 /* ThisType */:
        seenThisKeyword = true;
        return;
      case 182 /* TypePredicate */:
        break;
      // Binding the children will handle everything
      case 168 /* TypeParameter */:
        return bindTypeParameter(node);
      case 169 /* Parameter */:
        return bindParameter(node);
      case 260 /* VariableDeclaration */:
        return bindVariableDeclarationOrBindingElement(node);
      case 208 /* BindingElement */:
        node.flowNode = currentFlow;
        return bindVariableDeclarationOrBindingElement(node);
      case 172 /* PropertyDeclaration */:
      case 171 /* PropertySignature */:
        return bindPropertyWorker(node);
      case 303 /* PropertyAssignment */:
      case 304 /* ShorthandPropertyAssignment */:
        return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
      case 306 /* EnumMember */:
        return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
      case 179 /* CallSignature */:
      case 180 /* ConstructSignature */:
      case 181 /* IndexSignature */:
        return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
      case 262 /* FunctionDeclaration */:
        return bindFunctionDeclaration(node);
      case 176 /* Constructor */:
        return declareSymbolAndAddToSymbolTable(
          node,
          16384 /* Constructor */,
          /*symbolExcludes:*/
          0 /* None */
        );
      case 177 /* GetAccessor */:
        return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
      case 178 /* SetAccessor */:
        return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
      case 184 /* FunctionType */:
      case 317 /* JSDocFunctionType */:
      case 323 /* JSDocSignature */:
      case 185 /* ConstructorType */:
        return bindFunctionOrConstructorType(node);
      case 187 /* TypeLiteral */:
      case 322 /* JSDocTypeLiteral */:
      case 200 /* MappedType */:
        return bindAnonymousTypeWorker(node);
      case 332 /* JSDocClassTag */:
        return bindJSDocClassTag(node);
      case 210 /* ObjectLiteralExpression */:
        return bindObjectLiteralExpression(node);
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
        return bindFunctionExpression(node);
      case 213 /* CallExpression */:
        const assignmentKind = getAssignmentDeclarationKind(node);
        switch (assignmentKind) {
          case 7 /* ObjectDefinePropertyValue */:
            return bindObjectDefinePropertyAssignment(node);
          case 8 /* ObjectDefinePropertyExports */:
            return bindObjectDefinePropertyExport(node);
          case 9 /* ObjectDefinePrototypeProperty */:
            return bindObjectDefinePrototypeProperty(node);
          case 0 /* None */:
            break;
          // Nothing to do
          default:
            return Debug.fail("Unknown call expression assignment declaration kind");
        }
        if (isInJSFile(node)) {
          bindCallExpression(node);
        }
        break;
      // Members of classes, interfaces, and modules
      case 231 /* ClassExpression */:
      case 263 /* ClassDeclaration */:
        inStrictMode = true;
        return bindClassLikeDeclarat