 getDirectoryPath(entry.path))) : void 0;
  entry.latestChangedDtsTime = latestChangedDtsTime || false;
  return latestChangedDtsTime;
}
function updateOutputTimestamps(state, proj, resolvedPath) {
  if (state.options.dry) {
    return reportStatus(state, Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
  }
  updateOutputTimestampsWorker(state, proj, resolvedPath, Diagnostics.Updating_output_timestamps_of_project_0);
  state.projectStatus.set(resolvedPath, {
    type: 1 /* UpToDate */,
    oldestOutputFileName: getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
  });
}
function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
  if (state.options.stopBuildOnErrors && buildResult & 4 /* AnyErrors */) return;
  if (!config.options.composite) return;
  for (let index = projectIndex + 1; index < buildOrder.length; index++) {
    const nextProject = buildOrder[index];
    const nextProjectPath = toResolvedConfigFilePath(state, nextProject);
    if (state.projectPendingBuild.has(nextProjectPath)) continue;
    const nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
    if (!nextProjectConfig || !nextProjectConfig.projectReferences) continue;
    for (const ref of nextProjectConfig.projectReferences) {
      const resolvedRefPath = resolveProjectName(state, ref.path);
      if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath) continue;
      const status = state.projectStatus.get(nextProjectPath);
      if (status) {
        switch (status.type) {
          case 1 /* UpToDate */:
            if (buildResult & 2 /* DeclarationOutputUnchanged */) {
              status.type = 2 /* UpToDateWithUpstreamTypes */;
              break;
            }
          // falls through
          case 15 /* UpToDateWithInputFileText */:
          case 2 /* UpToDateWithUpstreamTypes */:
            if (!(buildResult & 2 /* DeclarationOutputUnchanged */)) {
              state.projectStatus.set(nextProjectPath, {
                type: 6 /* OutOfDateWithUpstream */,
                outOfDateOutputFileName: status.oldestOutputFileName,
                newerProjectName: project
              });
            }
            break;
          case 12 /* UpstreamBlocked */:
            if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
              clearProjectStatus(state, nextProjectPath);
            }
            break;
        }
      }
      addProjToQueue(state, nextProjectPath, 0 /* Update */);
      break;
    }
  }
}
function build(state, project, cancellationToken, writeFile2, getCustomTransformers, onlyReferences) {
  mark("SolutionBuilder::beforeBuild");
  const result = buildWorker(state, project, cancellationToken, writeFile2, getCustomTransformers, onlyReferences);
  mark("SolutionBuilder::afterBuild");
  measure("SolutionBuilder::Build", "SolutionBuilder::beforeBuild", "SolutionBuilder::afterBuild");
  return result;
}
function buildWorker(state, project, cancellationToken, writeFile2, getCustomTransformers, onlyReferences) {
  const buildOrder = getBuildOrderFor(state, project, onlyReferences);
  if (!buildOrder) return 3 /* InvalidProject_OutputsSkipped */;
  setupInitialBuild(state, cancellationToken);
  let reportQueue = true;
  let successfulProjects = 0;
  while (true) {
    const invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
    if (!invalidatedProject) break;
    reportQueue = false;
    invalidatedProject.done(cancellationToken, writeFile2, getCustomTransformers == null ? void 0 : getCustomTransformers(invalidatedProject.project));
    if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++;
  }
  disableCache(state);
  reportErrorSummary(state, buildOrder);
  startWatching(state, buildOrder);
  return isCircularBuildOrder(buildOrder) ? 4 /* ProjectReferenceCycle_OutputsSkipped */ : !buildOrder.some((p) => state.diagnostics.has(toResolvedConfigFilePath(state, p))) ? 0 /* Success */ : successfulProjects ? 2 /* DiagnosticsPresent_OutputsGenerated */ : 1 /* DiagnosticsPresent_OutputsSkipped */;
}
function clean(state, project, onlyReferences) {
  mark("SolutionBuilder::beforeClean");
  const result = cleanWorker(state, project, onlyReferences);
  mark("SolutionBuilder::afterClean");
  measure("SolutionBuilder::Clean", "SolutionBuilder::beforeClean", "SolutionBuilder::afterClean");
  return result;
}
function cleanWorker(state, project, onlyReferences) {
  const buildOrder = getBuildOrderFor(state, project, onlyReferences);
  if (!buildOrder) return 3 /* InvalidProject_OutputsSkipped */;
  if (isCircularBuildOrder(buildOrder)) {
    reportErrors(state, buildOrder.circularDiagnostics);
    return 4 /* ProjectReferenceCycle_OutputsSkipped */;
  }
  const { options, host } = state;
  const filesToDelete = options.dry ? [] : void 0;
  for (const proj of buildOrder) {
    const resolvedPath = toResolvedConfigFilePath(state, proj);
    const parsed = parseConfigFile(state, proj, resolvedPath);
    if (parsed === void 0) {
      reportParseConfigFileDiagnostic(state, resolvedPath);
      continue;
    }
    const outputs = getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
    if (!outputs.length) continue;
    const inputFileNames = new Set(parsed.fileNames.map((f) => toPath2(state, f)));
    for (const output of outputs) {
      if (inputFileNames.has(toPath2(state, output))) continue;
      if (host.fileExists(output)) {
        if (filesToDelete) {
          filesToDelete.push(output);
        } else {
          host.deleteFile(output);
          invalidateProject(state, resolvedPath, 0 /* Update */);
        }
      }
    }
  }
  if (filesToDelete) {
    reportStatus(state, Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map((f) => `\r
 * ${f}`).join(""));
  }
  return 0 /* Success */;
}
function invalidateProject(state, resolved, updateLevel) {
  if (state.host.getParsedCommandLine && updateLevel === 1 /* RootNamesAndUpdate */) {
    updateLevel = 2 /* Full */;
  }
  if (updateLevel === 2 /* Full */) {
    state.configFileCache.delete(resolved);
    state.buildOrder = void 0;
  }
  state.needsSummary = true;
  clearProjectStatus(state, resolved);
  addProjToQueue(state, resolved, updateLevel);
  enableCache(state);
}
function invalidateProjectAndScheduleBuilds(state, resolvedPath, updateLevel) {
  state.reportFileChangeDetected = true;
  invalidateProject(state, resolvedPath, updateLevel);
  scheduleBuildInvalidatedProject(
    state,
    250,
    /*changeDetected*/
    true
  );
}
function scheduleBuildInvalidatedProject(state, time, changeDetected) {
  const { hostWithWatch } = state;
  if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
    return;
  }
  if (state.timerToBuildInvalidatedProject) {
    hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
  }
  state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, "timerToBuildInvalidatedProject", state, changeDetected);
}
function buildNextInvalidatedProject(_timeoutType, state, changeDetected) {
  mark("SolutionBuilder::beforeBuild");
  const buildOrder = buildNextInvalidatedProjectWorker(state, changeDetected);
  mark("SolutionBuilder::afterBuild");
  measure("SolutionBuilder::Build", "SolutionBuilder::beforeBuild", "SolutionBuilder::afterBuild");
  if (buildOrder) reportErrorSummary(state, buildOrder);
}
function buildNextInvalidatedProjectWorker(state, changeDetected) {
  state.timerToBuildInvalidatedProject = void 0;
  if (state.reportFileChangeDetected) {
    state.reportFileChangeDetected = false;
    state.projectErrorsReported.clear();
    reportWatchStatus(state, Diagnostics.File_change_detected_Starting_incremental_compilation);
  }
  let projectsBuilt = 0;
  const buildOrder = getBuildOrder(state);
  const invalidatedProject = getNextInvalidatedProject(
    state,
    buildOrder,
    /*reportQueue*/
    false
  );
  if (invalidatedProject) {
    invalidatedProject.done();
    projectsBuilt++;
    while (state.projectPendingBuild.size) {
      if (state.timerToBuildInvalidatedProject) return;
      const info = getNextInvalidatedProjectCreateInfo(
        state,
        buildOrder,
        /*reportQueue*/
        false
      );
      if (!info) break;
      if (info.kind !== 1 /* UpdateOutputFileStamps */ && (changeDetected || projectsBuilt === 5)) {
        scheduleBuildInvalidatedProject(
          state,
          100,
          /*changeDetected*/
          false
        );
        return;
      }
      const project = createInvalidatedProjectWithInfo(state, info, buildOrder);
      project.done();
      if (info.kind !== 1 /* UpdateOutputFileStamps */) projectsBuilt++;
    }
  }
  disableCache(state);
  return buildOrder;
}
function watchConfigFile(state, resolved, resolvedPath, parsed) {
  if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return;
  state.allWatchedConfigFiles.set(
    resolvedPath,
    watchFile(
      state,
      resolved,
      () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 2 /* Full */),
      2e3 /* High */,
      parsed == null ? void 0 : parsed.watchOptions,
      WatchType.ConfigFile,
      resolved
    )
  );
}
function watchExtendedConfigFiles(state, resolvedPath, parsed) {
  updateSharedExtendedConfigFileWatcher(
    resolvedPath,
    parsed == null ? void 0 : parsed.options,
    state.allWatchedExtendedConfigFiles,
    (extendedConfigFileName, extendedConfigFilePath) => watchFile(
      state,
      extendedConfigFileName,
      () => {
        var _a;
        return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) == null ? void 0 : _a.projects.forEach((projectConfigFilePath) => invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, 2 /* Full */));
      },
      2e3 /* High */,
      parsed == null ? void 0 : parsed.watchOptions,
      WatchType.ExtendedConfigFile
    ),
    (fileName) => toPath2(state, fileName)
  );
}
function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
  if (!state.watch) return;
  updateWatchingWildcardDirectories(
    getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath),
    parsed.wildcardDirectories,
    (dir, flags) => state.watchDirectory(
      dir,
      (fileOrDirectory) => {
        var _a;
        if (isIgnoredFileFromWildCardWatching({
          watchedDirPath: toPath2(state, dir),
          fileOrDirectory,
          fileOrDirectoryPath: toPath2(state, fileOrDirectory),
          configFileName: resolved,
          currentDirectory: state.compilerHost.getCurrentDirectory(),
          options: parsed.options,
          program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) == null ? void 0 : _a.fileNames),
          useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames,
          writeLog: (s) => state.writeLog(s),
          toPath: (fileName) => toPath2(state, fileName)
        })) return;
        invalidateProjectAndScheduleBuilds(state, resolvedPath, 1 /* RootNamesAndUpdate */);
      },
      flags,
      parsed == null ? void 0 : parsed.watchOptions,
      WatchType.WildcardDirectory,
      resolved
    )
  );
}
function watchInputFiles(state, resolved, resolvedPath, parsed) {
  if (!state.watch) return;
  mutateMap(
    getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath),
    new Set(parsed.fileNames),
    {
      createNewValue: (input) => watchFile(
        state,
        input,
        () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* Update */),
        250 /* Low */,
        parsed == null ? void 0 : parsed.watchOptions,
        WatchType.SourceFile,
        resolved
      ),
      onDeleteValue: closeFileWatcher
    }
  );
}
function watchPackageJsonFiles(state, resolved, resolvedPath, parsed) {
  if (!state.watch || !state.lastCachedPackageJsonLookups) return;
  mutateMap(
    getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath),
    state.lastCachedPackageJsonLookups.get(resolvedPath),
    {
      createNewValue: (input) => watchFile(
        state,
        input,
        () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* Update */),
        2e3 /* High */,
        parsed == null ? void 0 : parsed.watchOptions,
        WatchType.PackageJson,
        resolved
      ),
      onDeleteValue: closeFileWatcher
    }
  );
}
function startWatching(state, buildOrder) {
  if (!state.watchAllProjectsPending) return;
  mark("SolutionBuilder::beforeWatcherCreation");
  state.watchAllProjectsPending = false;
  for (const resolved of getBuildOrderFromAnyBuildOrder(buildOrder)) {
    const resolvedPath = toResolvedConfigFilePath(state, resolved);
    const cfg = parseConfigFile(state, resolved, resolvedPath);
    watchConfigFile(state, resolved, resolvedPath, cfg);
    watchExtendedConfigFiles(state, resolvedPath, cfg);
    if (cfg) {
      watchWildCardDirectories(state, resolved, resolvedPath, cfg);
      watchInputFiles(state, resolved, resolvedPath, cfg);
      watchPackageJsonFiles(state, resolved, resolvedPath, cfg);
    }
  }
  mark("SolutionBuilder::afterWatcherCreation");
  measure("SolutionBuilder::Watcher creation", "SolutionBuilder::beforeWatcherCreation", "SolutionBuilder::afterWatcherCreation");
}
function stopWatching(state) {
  clearMap(state.allWatchedConfigFiles, closeFileWatcher);
  clearMap(state.allWatchedExtendedConfigFiles, closeFileWatcherOf);
  clearMap(state.allWatchedWildcardDirectories, (watchedWildcardDirectories) => clearMap(watchedWildcardDirectories, closeFileWatcherOf));
  clearMap(state.allWatchedInputFiles, (watchedWildcardDirectories) => clearMap(watchedWildcardDirectories, closeFileWatcher));
  clearMap(state.allWatchedPackageJsonFiles, (watchedPacageJsonFiles) => clearMap(watchedPacageJsonFiles, closeFileWatcher));
}
function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
  const state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
  return {
    build: (project, cancellationToken, writeFile2, getCustomTransformers) => build(state, project, cancellationToken, writeFile2, getCustomTransformers),
    clean: (project) => clean(state, project),
    buildReferences: (project, cancellationToken, writeFile2, getCustomTransformers) => build(
      state,
      project,
      cancellationToken,
      writeFile2,
      getCustomTransformers,
      /*onlyReferences*/
      true
    ),
    cleanReferences: (project) => clean(
      state,
      project,
      /*onlyReferences*/
      true
    ),
    getNextInvalidatedProject: (cancellationToken) => {
      setupInitialBuild(state, cancellationToken);
      return getNextInvalidatedProject(
        state,
        getBuildOrder(state),
        /*reportQueue*/
        false
      );
    },
    getBuildOrder: () => getBuildOrder(state),
    getUpToDateStatusOfProject: (project) => {
      const configFileName = resolveProjectName(state, project);
      const configFilePath = toResolvedConfigFilePath(state, configFileName);
      return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
    },
    invalidateProject: (configFilePath, updateLevel) => invalidateProject(state, configFilePath, updateLevel || 0 /* Update */),
    close: () => stopWatching(state)
  };
}
function relName(state, path) {
  return convertToRelativePath(path, state.compilerHost.getCurrentDirectory(), state.compilerHost.getCanonicalFileName);
}
function reportStatus(state, message, ...args) {
  state.host.reportSolutionBuilderStatus(createCompilerDiagnostic(message, ...args));
}
function reportWatchStatus(state, message, ...args) {
  var _a, _b;
  (_b = (_a = state.hostWithWatch).onWatchStatusChange) == null ? void 0 : _b.call(_a, createCompilerDiagnostic(message, ...args), state.host.getNewLine(), state.baseCompilerOptions);
}
function reportErrors({ host }, errors) {
  errors.forEach((err) => host.reportDiagnostic(err));
}
function reportAndStoreErrors(state, proj, errors) {
  reportErrors(state, errors);
  state.projectErrorsReported.set(proj, true);
  if (errors.length) {
    state.diagnostics.set(proj, errors);
  }
}
function reportParseConfigFileDiagnostic(state, proj) {
  reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
}
function reportErrorSummary(state, buildOrder) {
  if (!state.needsSummary) return;
  state.needsSummary = false;
  const canReportSummary = state.watch || !!state.host.reportErrorSummary;
  const { diagnostics } = state;
  let totalErrors = 0;
  let filesInError = [];
  if (isCircularBuildOrder(buildOrder)) {
    reportBuildQueue(state, buildOrder.buildOrder);
    reportErrors(state, buildOrder.circularDiagnostics);
    if (canReportSummary) totalErrors += getErrorCountForSummary(buildOrder.circularDiagnostics);
    if (canReportSummary) filesInError = [...filesInError, ...getFilesInErrorForSummary(buildOrder.circularDiagnostics)];
  } else {
    buildOrder.forEach((project) => {
      const projectPath = toResolvedConfigFilePath(state, project);
      if (!state.projectErrorsReported.has(projectPath)) {
        reportErrors(state, diagnostics.get(projectPath) || emptyArray);
      }
    });
    if (canReportSummary) diagnostics.forEach((singleProjectErrors) => totalErrors += getErrorCountForSummary(singleProjectErrors));
    if (canReportSummary) diagnostics.forEach((singleProjectErrors) => [...filesInError, ...getFilesInErrorForSummary(singleProjectErrors)]);
  }
  if (state.watch) {
    reportWatchStatus(state, getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
  } else if (state.host.reportErrorSummary) {
    state.host.reportErrorSummary(totalErrors, filesInError);
  }
}
function reportBuildQueue(state, buildQueue) {
  if (state.options.verbose) {
    reportStatus(state, Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map((s) => "\r\n    * " + relName(state, s)).join(""));
  }
}
function reportUpToDateStatus(state, configFileName, status) {
  switch (status.type) {
    case 5 /* OutOfDateWithSelf */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2,
        relName(state, configFileName),
        relName(state, status.outOfDateOutputFileName),
        relName(state, status.newerInputFileName)
      );
    case 6 /* OutOfDateWithUpstream */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2,
        relName(state, configFileName),
        relName(state, status.outOfDateOutputFileName),
        relName(state, status.newerProjectName)
      );
    case 3 /* OutputMissing */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist,
        relName(state, configFileName),
        relName(state, status.missingOutputFileName)
      );
    case 4 /* ErrorReadingFile */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_there_was_error_reading_file_1,
        relName(state, configFileName),
        relName(state, status.fileName)
      );
    case 7 /* OutOfDateBuildInfoWithPendingEmit */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted,
        relName(state, configFileName),
        relName(state, status.buildInfoFile)
      );
    case 8 /* OutOfDateBuildInfoWithErrors */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors,
        relName(state, configFileName),
        relName(state, status.buildInfoFile)
      );
    case 9 /* OutOfDateOptions */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions,
        relName(state, configFileName),
        relName(state, status.buildInfoFile)
      );
    case 10 /* OutOfDateRoots */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_but_not_any_more,
        relName(state, configFileName),
        relName(state, status.buildInfoFile),
        relName(state, status.inputFile)
      );
    case 1 /* UpToDate */:
      if (status.newestInputFileTime !== void 0) {
        return reportStatus(
          state,
          Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2,
          relName(state, configFileName),
          relName(state, status.newestInputFileName || ""),
          relName(state, status.oldestOutputFileName || "")
        );
      }
      break;
    case 2 /* UpToDateWithUpstreamTypes */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies,
        relName(state, configFileName)
      );
    case 15 /* UpToDateWithInputFileText */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files,
        relName(state, configFileName)
      );
    case 11 /* UpstreamOutOfDate */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date,
        relName(state, configFileName),
        relName(state, status.upstreamProjectName)
      );
    case 12 /* UpstreamBlocked */:
      return reportStatus(
        state,
        status.upstreamProjectBlocked ? Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built : Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors,
        relName(state, configFileName),
        relName(state, status.upstreamProjectName)
      );
    case 0 /* Unbuildable */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_1,
        relName(state, configFileName),
        status.reason
      );
    case 14 /* TsVersionOutputOfDate */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2,
        relName(state, configFileName),
        status.version,
        version
      );
    case 17 /* ForceBuild */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_being_forcibly_rebuilt,
        relName(state, configFileName)
      );
    case 16 /* ContainerOnly */:
    // Don't report status on "solution" projects
    // falls through
    case 13 /* ComputingUpstream */:
      break;
    default:
      assertType(status);
  }
}
function verboseReportProjectStatus(state, configFileName, status) {
  if (state.options.verbose) {
    reportUpToDateStatus(state, configFileName, status);
  }
}

// src/compiler/executeCommandLine.ts
var StatisticType = /* @__PURE__ */ ((StatisticType2) => {
  StatisticType2[StatisticType2["time"] = 0] = "time";
  StatisticType2[StatisticType2["count"] = 1] = "count";
  StatisticType2[StatisticType2["memory"] = 2] = "memory";
  return StatisticType2;
})(StatisticType || {});
function countLines(program) {
  const counts2 = getCountsMap();
  forEach(program.getSourceFiles(), (file) => {
    const key = getCountKey(program, file);
    const lineCount = getLineStarts(file).length;
    counts2.set(key, counts2.get(key) + lineCount);
  });
  return counts2;
}
function getCountsMap() {
  const counts2 = /* @__PURE__ */ new Map();
  counts2.set("Library", 0);
  counts2.set("Definitions", 0);
  counts2.set("TypeScript", 0);
  counts2.set("JavaScript", 0);
  counts2.set("JSON", 0);
  counts2.set("Other", 0);
  return counts2;
}
function getCountKey(program, file) {
  if (program.isSourceFileDefaultLibrary(file)) {
    return "Library";
  } else if (file.isDeclarationFile) {
    return "Definitions";
  }
  const path = file.path;
  if (fileExtensionIsOneOf(path, supportedTSExtensionsFlat)) {
    return "TypeScript";
  } else if (fileExtensionIsOneOf(path, supportedJSExtensionsFlat)) {
    return "JavaScript";
  } else if (fileExtensionIs(path, ".json" /* Json */)) {
    return "JSON";
  } else {
    return "Other";
  }
}
function updateReportDiagnostic(sys2, existing, options) {
  return shouldBePretty(sys2, options) ? createDiagnosticReporter(
    sys2,
    /*pretty*/
    true
  ) : existing;
}
function defaultIsPretty(sys2) {
  return !!sys2.writeOutputIsTTY && sys2.writeOutputIsTTY() && !sys2.getEnvironmentVariable("NO_COLOR");
}
function shouldBePretty(sys2, options) {
  if (!options || typeof options.pretty === "undefined") {
    return defaultIsPretty(sys2);
  }
  return options.pretty;
}
function getOptionsForHelp(commandLine) {
  return !!commandLine.options.all ? toSorted(optionDeclarations.concat(tscBuildOption), (a, b) => compareStringsCaseInsensitive(a.name, b.name)) : filter(optionDeclarations.concat(tscBuildOption), (v) => !!v.showInSimplifiedHelpView);
}
function printVersion(sys2) {
  sys2.write(getDiagnosticText(Diagnostics.Version_0, version) + sys2.newLine);
}
function createColors(sys2) {
  const showColors = defaultIsPretty(sys2);
  if (!showColors) {
    return {
      bold: (str) => str,
      blue: (str) => str,
      blueBackground: (str) => str,
      brightWhite: (str) => str
    };
  }
  function bold(str) {
    return `\x1B[1m${str}\x1B[22m`;
  }
  const isWindows = sys2.getEnvironmentVariable("OS") && sys2.getEnvironmentVariable("OS").toLowerCase().includes("windows");
  const isWindowsTerminal = sys2.getEnvironmentVariable("WT_SESSION");
  const isVSCode = sys2.getEnvironmentVariable("TERM_PROGRAM") && sys2.getEnvironmentVariable("TERM_PROGRAM") === "vscode";
  function blue(str) {
    if (isWindows && !isWindowsTerminal && !isVSCode) {
      return brightWhite(str);
    }
    return `\x1B[94m${str}\x1B[39m`;
  }
  const supportsRicherColors = sys2.getEnvironmentVariable("COLORTERM") === "truecolor" || sys2.getEnvironmentVariable("TERM") === "xterm-256color";
  function blueBackground(str) {
    if (supportsRicherColors) {
      return `\x1B[48;5;68m${str}\x1B[39;49m`;
    } else {
      return `\x1B[44m${str}\x1B[39;49m`;
    }
  }
  function brightWhite(str) {
    return `\x1B[97m${str}\x1B[39m`;
  }
  return {
    bold,
    blue,
    brightWhite,
    blueBackground
  };
}
function getDisplayNameTextOfOption(option) {
  return `--${option.name}${option.shortName ? `, -${option.shortName}` : ""}`;
}
function generateOptionOutput(sys2, option, rightAlignOfLeft, leftAlignOfRight) {
  var _a;
  const text = [];
  const colors = createColors(sys2);
  const name = getDisplayNameTextOfOption(option);
  const valueCandidates = getValueCandidate(option);
  const defaultValueDescription = typeof option.defaultValueDescription === "object" ? getDiagnosticText(option.defaultValueDescription) : formatDefaultValue(
    option.defaultValueDescription,
    option.type === "list" || option.type === "listOrElement" ? option.element.type : option.type
  );
  const terminalWidth = ((_a = sys2.getWidthOfTerminal) == null ? void 0 : _a.call(sys2)) ?? 0;
  if (terminalWidth >= 80) {
    let description3 = "";
    if (option.description) {
      description3 = getDiagnosticText(option.description);
    }
    text.push(...getPrettyOutput(
      name,
      description3,
      rightAlignOfLeft,
      leftAlignOfRight,
      terminalWidth,
      /*colorLeft*/
      true
    ), sys2.newLine);
    if (showAdditionalInfoOutput(valueCandidates, option)) {
      if (valueCandidates) {
        text.push(...getPrettyOutput(
          valueCandidates.valueType,
          valueCandidates.possibleValues,
          rightAlignOfLeft,
          leftAlignOfRight,
          terminalWidth,
          /*colorLeft*/
          false
        ), sys2.newLine);
      }
      if (defaultValueDescription) {
        text.push(...getPrettyOutput(
          getDiagnosticText(Diagnostics.default_Colon),
          defaultValueDescription,
          rightAlignOfLeft,
          leftAlignOfRight,
          terminalWidth,
          /*colorLeft*/
          false
        ), sys2.newLine);
      }
    }
    text.push(sys2.newLine);
  } else {
    text.push(colors.blue(name), sys2.newLine);
    if (option.description) {
      const description3 = getDiagnosticText(option.description);
      text.push(description3);
    }
    text.push(sys2.newLine);
    if (showAdditionalInfoOutput(valueCandidates, option)) {
      if (valueCandidates) {
        text.push(`${valueCandidates.valueType} ${valueCandidates.possibleValues}`);
      }
      if (defaultValueDescription) {
        if (valueCandidates) text.push(sys2.newLine);
        const diagType = getDiagnosticText(Diagnostics.default_Colon);
        text.push(`${diagType} ${defaultValueDescription}`);
      }
      text.push(sys2.newLine);
    }
    text.push(sys2.newLine);
  }
  return text;
  function formatDefaultValue(defaultValue, type) {
    return defaultValue !== void 0 && typeof type === "object" ? arrayFrom(type.entries()).filter(([, value]) => value === defaultValue).map(([name2]) => name2).join("/") : String(defaultValue);
  }
  function showAdditionalInfoOutput(valueCandidates2, option2) {
    const ignoreValues = ["string"];
    const ignoredDescriptions = [void 0, "false", "n/a"];
    const defaultValueDescription2 = option2.defaultValueDescription;
    if (option2.category === Diagnostics.Command_line_Options) return false;
    if (contains(ignoreValues, valueCandidates2 == null ? void 0 : valueCandidates2.possibleValues) && contains(ignoredDescriptions, defaultValueDescription2)) {
      return false;
    }
    return true;
  }
  function getPrettyOutput(left, right, rightAlignOfLeft2, leftAlignOfRight2, terminalWidth2, colorLeft) {
    const res = [];
    let isFirstLine = true;
    let remainRight = right;
    const rightCharacterNumber = terminalWidth2 - leftAlignOfRight2;
    while (remainRight.length > 0) {
      let curLeft = "";
      if (isFirstLine) {
        curLeft = left.padStart(rightAlignOfLeft2);
        curLeft = curLeft.padEnd(leftAlignOfRight2);
        curLeft = colorLeft ? colors.blue(curLeft) : curLeft;
      } else {
        curLeft = "".padStart(leftAlignOfRight2);
      }
      const curRight = remainRight.substr(0, rightCharacterNumber);
      remainRight = remainRight.slice(rightCharacterNumber);
      res.push(`${curLeft}${curRight}`);
      isFirstLine = false;
    }
    return res;
  }
  function getValueCandidate(option2) {
    if (option2.type === "object") {
      return void 0;
    }
    return {
      valueType: getValueType(option2),
      possibleValues: getPossibleValues(option2)
    };
    function getValueType(option3) {
      Debug.assert(option3.type !== "listOrElement");
      switch (option3.type) {
        case "string":
        case "number":
        case "boolean":
          return getDiagnosticText(Diagnostics.type_Colon);
        case "list":
          return getDiagnosticText(Diagnostics.one_or_more_Colon);
        default:
          return getDiagnosticText(Diagnostics.one_of_Colon);
      }
    }
    function getPossibleValues(option3) {
      let possibleValues;
      switch (option3.type) {
        case "string":
        case "number":
        case "boolean":
          possibleValues = option3.type;
          break;
        case "list":
        case "listOrElement":
          possibleValues = getPossibleValues(option3.element);
          break;
        case "object":
          possibleValues = "";
          break;
        default:
          const inverted = {};
          option3.type.forEach((value, name2) => {
            var _a2;
            if (!((_a2 = option3.deprecatedKeys) == null ? void 0 : _a2.has(name2))) {
              (inverted[value] || (inverted[value] = [])).push(name2);
            }
          });
          return Object.entries(inverted).map(([, synonyms]) => synonyms.join("/")).join(", ");
      }
      return possibleValues;
    }
  }
}
function generateGroupOptionOutput(sys2, optionsList) {
  let maxLength2 = 0;
  for (const option of optionsList) {
    const curLength = getDisplayNameTextOfOption(option).length;
    maxLength2 = maxLength2 > curLength ? maxLength2 : curLength;
  }
  const rightAlignOfLeftPart = maxLength2 + 2;
  const leftAlignOfRightPart = rightAlignOfLeftPart + 2;
  let lines = [];
  for (const option of optionsList) {
    const tmp = generateOptionOutput(sys2, option, rightAlignOfLeftPart, leftAlignOfRightPart);
    lines = [...lines, ...tmp];
  }
  if (lines[lines.length - 2] !== sys2.newLine) {
    lines.push(sys2.newLine);
  }
  return lines;
}
function generateSectionOptionsOutput(sys2, sectionName, options, subCategory, beforeOptionsDescription, afterOptionsDescription) {
  let res = [];
  res.push(createColors(sys2).bold(sectionName) + sys2.newLine + sys2.newLine);
  if (beforeOptionsDescription) {
    res.push(beforeOptionsDescription + sys2.newLine + sys2.newLine);
  }
  if (!subCategory) {
    res = [...res, ...generateGroupOptionOutput(sys2, options)];
    if (afterOptionsDescription) {
      res.push(afterOptionsDescription + sys2.newLine + sys2.newLine);
    }
    return res;
  }
  const categoryMap = /* @__PURE__ */ new Map();
  for (const option of options) {
    if (!option.category) {
      continue;
    }
    const curCategory = getDiagnosticText(option.category);
    const optionsOfCurCategory = categoryMap.get(curCategory) ?? [];
    optionsOfCurCategory.push(option);
    categoryMap.set(curCategory, optionsOfCurCategory);
  }
  categoryMap.forEach((value, key) => {
    res.push(`### ${key}${sys2.newLine}${sys2.newLine}`);
    res = [...res, ...generateGroupOptionOutput(sys2, value)];
  });
  if (afterOptionsDescription) {
    res.push(afterOptionsDescription + sys2.newLine + sys2.newLine);
  }
  return res;
}
function printEasyHelp(sys2, simpleOptions) {
  const colors = createColors(sys2);
  let output = [...getHeader(sys2, `${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)];
  output.push(colors.bold(getDiagnosticText(Diagnostics.COMMON_COMMANDS)) + sys2.newLine + sys2.newLine);
  example("tsc", Diagnostics.Compiles_the_current_project_tsconfig_json_in_the_working_directory);
  example("tsc app.ts util.ts", Diagnostics.Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options);
  example("tsc -b", Diagnostics.Build_a_composite_project_in_the_working_directory);
  example("tsc --init", Diagnostics.Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory);
  example("tsc -p ./path/to/tsconfig.json", Diagnostics.Compiles_the_TypeScript_project_located_at_the_specified_path);
  example("tsc --help --all", Diagnostics.An_expanded_version_of_this_information_showing_all_possible_compiler_options);
  example(["tsc --noEmit", "tsc --target esnext"], Diagnostics.Compiles_the_current_project_with_additional_settings);
  const cliCommands = simpleOptions.filter((opt) => opt.isCommandLineOnly || opt.category === Diagnostics.Command_line_Options);
  const configOpts = simpleOptions.filter((opt) => !contains(cliCommands, opt));
  output = [
    ...output,
    ...generateSectionOptionsOutput(
      sys2,
      getDiagnosticText(Diagnostics.COMMAND_LINE_FLAGS),
      cliCommands,
      /*subCategory*/
      false,
      /*beforeOptionsDescription*/
      void 0,
      /*afterOptionsDescription*/
      void 0
    ),
    ...generateSectionOptionsOutput(
      sys2,
      getDiagnosticText(Diagnostics.COMMON_COMPILER_OPTIONS),
      configOpts,
      /*subCategory*/
      false,
      /*beforeOptionsDescription*/
      void 0,
      formatMessage(Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsc")
    )
  ];
  for (const line of output) {
    sys2.write(line);
  }
  function example(ex, desc) {
    const examples = typeof ex === "string" ? [ex] : ex;
    for (const example2 of examples) {
      output.push("  " + colors.blue(example2) + sys2.newLine);
    }
    output.push("  " + getDiagnosticText(desc) + sys2.newLine + sys2.newLine);
  }
}
function printAllHelp(sys2, compilerOptions, buildOptions, watchOptions) {
  let output = [...getHeader(sys2, `${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)];
  output = [...output, ...generateSectionOptionsOutput(
    sys2,
    getDiagnosticText(Diagnostics.ALL_COMPILER_OPTIONS),
    compilerOptions,
    /*subCategory*/
    true,
    /*beforeOptionsDescription*/
    void 0,
    formatMessage(Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsc")
  )];
  output = [...output, ...generateSectionOptionsOutput(
    sys2,
    getDiagnosticText(Diagnostics.WATCH_OPTIONS),
    watchOptions,
    /*subCategory*/
    false,
    getDiagnosticText(Diagnostics.Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_config_watch_mode_with_Colon)
  )];
  output = [...output, ...generateSectionOptionsOutput(
    sys2,
    getDiagnosticText(Diagnostics.BUILD_OPTIONS),
    filter(buildOptions, (option) => option !== tscBuildOption),
    /*subCategory*/
    false,
    formatMessage(Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds")
  )];
  for (const line of output) {
    sys2.write(line);
  }
}
function printBuildHelp(sys2, buildOptions) {
  let output = [...getHeader(sys2, `${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)];
  output = [...output, ...generateSectionOptionsOutput(
    sys2,
    getDiagnosticText(Diagnostics.BUILD_OPTIONS),
    filter(buildOptions, (option) => option !== tscBuildOption),
    /*subCategory*/
    false,
    formatMessage(Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds")
  )];
  for (const line of output) {
    sys2.write(line);
  }
}
function getHeader(sys2, message) {
  var _a;
  const colors = createColors(sys2);
  const header = [];
  const terminalWidth = ((_a = sys2.getWidthOfTerminal) == null ? void 0 : _a.call(sys2)) ?? 0;
  const tsIconLength = 5;
  const tsIconFirstLine = colors.blueBackground("".padStart(tsIconLength));
  const tsIconSecondLine = colors.blueBackground(colors.brightWhite("TS ".padStart(tsIconLength)));
  if (terminalWidth >= message.length + tsIconLength) {
    const rightAlign = terminalWidth > 120 ? 120 : terminalWidth;
    const leftAlign = rightAlign - tsIconLength;
    header.push(message.padEnd(leftAlign) + tsIconFirstLine + sys2.newLine);
    header.push("".padStart(leftAlign) + tsIconSecondLine + sys2.newLine);
  } else {
    header.push(message + sys2.newLine);
    header.push(sys2.newLine);
  }
  return header;
}
function printHelp(sys2, commandLine) {
  if (!commandLine.options.all) {
    printEasyHelp(sys2, getOptionsForHelp(commandLine));
  } else {
    printAllHelp(sys2, getOptionsForHelp(commandLine), optionsForBuild, optionsForWatch);
  }
}
function executeCommandLineWorker(sys2, cb, commandLine) {
  let reportDiagnostic = createDiagnosticReporter(sys2);
  let configFileName;
  if (commandLine.options.locale) {
    validateLocaleAndSetLanguage(commandLine.options.locale, sys2, commandLine.errors);
  }
  if (commandLine.errors.length > 0) {
    commandLine.errors.forEach(reportDiagnostic);
    return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */);
  }
  if (commandLine.options.init) {
    writeConfigFile(sys2, reportDiagnostic, commandLine.options, commandLine.fileNames);
    return sys2.exit(0 /* Success */);
  }
  if (commandLine.options.version) {
    printVersion(sys2);
    return sys2.exit(0 /* Success */);
  }
  if (commandLine.options.help || commandLine.options.all) {
    printHelp(sys2, commandLine);
    return sys2.exit(0 /* Success */);
  }
  if (commandLine.options.watch && commandLine.options.listFilesOnly) {
    reportDiagnostic(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "listFilesOnly"));
    return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */);
  }
  if (commandLine.options.project) {
    if (commandLine.fileNames.length !== 0) {
      reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line));
      return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */);
    }
    const fileOrDirectory = normalizePath(commandLine.options.project);
    if (!fileOrDirectory || sys2.directoryExists(fileOrDirectory)) {
      configFileName = combinePaths(fileOrDirectory, "tsconfig.json");
      if (!sys2.fileExists(configFileName)) {
        reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project));
        return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */);
      }
    } else {
      configFileName = fileOrDirectory;
      if (!sys2.fileExists(configFileName)) {
        reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project));
        return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */);
      }
    }
  } else if (commandLine.fileNames.length === 0) {
    const searchPath = normalizePath(sys2.getCurrentDirectory());
    configFileName = findConfigFile(searchPath, (fileName) => sys2.fileExists(fileName));
  }
  if (commandLine.fileNames.length === 0 && !configFileName) {
    if (commandLine.options.showConfig) {
      reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0, normalizePath(sys2.getCurrentDirectory())));
    } else {
      printVersion(sys2);
      printHelp(sys2, commandLine);
    }
    return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */);
  }
  const currentDirectory = sys2.getCurrentDirectory();
  const commandLineOptions = convertToOptionsWithAbsolutePaths(
    commandLine.options,
    (fileName) => getNormalizedAbsolutePath(fileName, currentDirectory)
  );
  if (configFileName) {
    const extendedConfigCache = /* @__PURE__ */ new Map();
    const configParseResult = parseConfigFileWithSystem(configFileName, commandLineOptions, extendedConfigCache, commandLine.watchOptions, sys2, reportDiagnostic);
    if (commandLineOptions.showConfig) {
      if (configParseResult.errors.length !== 0) {
        reportDiagnostic = updateReportDiagnostic(
          sys2,
          reportDiagnostic,
          configParseResult.options
        );
        configParseResult.errors.forEach(reportDiagnostic);
        return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */);
      }
      sys2.write(JSON.stringify(convertToTSConfig(configParseResult, configFileName, sys2), null, 4) + sys2.newLine);
      return sys2.exit(0 /* Success */);
    }
    reportDiagnostic = updateReportDiagnostic(
      sys2,
      reportDiagnostic,
      configParseResult.options
    );
    if (isWatchSet(configParseResult.options)) {
      if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return;
      return createWatchOfConfigFile(
        sys2,
        cb,
        reportDiagnostic,
        configParseResult,
        commandLineOptions,
        commandLine.watchOptions,
        extendedConfigCache
      );
    } else if (isIncrementalCompilation(configParseResult.options)) {
      performIncrementalCompilation2(
        sys2,
        cb,
        reportDiagnostic,
        configParseResult
      );
    } else {
      performCompilation(
        sys2,
        cb,
        reportDiagnostic,
        configParseResult
      );
    }
  } else {
    if (commandLineOptions.showConfig) {
      sys2.write(JSON.stringify(convertToTSConfig(commandLine, combinePaths(currentDirectory, "tsconfig.json"), sys2), null, 4) + sys2.newLine);
      return sys2.exit(0 /* Success */);
    }
    reportDiagnostic = updateReportDiagnostic(
      sys2,
      reportDiagnostic,
      commandLineOptions
    );
    if (isWatchSet(commandLineOptions)) {
      if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return;
      return createWatchOfFilesAndCompilerOptions(
        sys2,
        cb,
        reportDiagnostic,
        commandLine.fileNames,
        commandLineOptions,
        commandLine.watchOptions
      );
    } else if (isIncrementalCompilation(commandLineOptions)) {
      performIncrementalCompilation2(
        sys2,
        cb,
        reportDiagnostic,
        { ...commandLine, options: commandLineOptions }
      );
    } else {
      performCompilation(
        sys2,
        cb,
        reportDiagnostic,
        { ...commandLine, options: commandLineOptions }
      );
    }
  }
}
function isBuildCommand(commandLineArgs) {
  if (commandLineArgs.length > 0 && commandLineArgs[0].charCodeAt(0) === 45 /* minus */) {
    const firstOption = commandLineArgs[0].slice(commandLineArgs[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase();
    return firstOption === tscBuildOption.name || firstOption === tscBuildOption.shortName;
  }
  return false;
}
function executeCommandLine(system, cb, commandLineArgs) {
  if (isBuildCommand(commandLineArgs)) {
    const { buildOptions, watchOptions, projects, errors } = parseBuildCommand(commandLineArgs);
    if (buildOptions.generateCpuProfile && system.enableCPUProfiler) {
      system.enableCPUProfiler(buildOptions.generateCpuProfile, () => performBuild(
        system,
        cb,
        buildOptions,
        watchOptions,
        projects,
        errors
      ));
    } else {
      return performBuild(
        system,
        cb,
        buildOptions,
        watchOptions,
        projects,
        errors
      );
    }
  }
  const commandLine = parseCommandLine(commandLineArgs, (path) => system.readFile(path));
  if (commandLine.options.generateCpuProfile && system.enableCPUProfiler) {
    system.enableCPUProfiler(commandLine.options.generateCpuProfile, () => executeCommandLineWorker(
      system,
      cb,
      commandLine
    ));
  } else {
    return executeCommandLineWorker(system, cb, commandLine);
  }
}
function reportWatchModeWithoutSysSupport(sys2, reportDiagnostic) {
  if (!sys2.watchFile || !sys2.watchDirectory) {
    reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"));
    sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */);
    return true;
  }
  return false;
}
var defaultJSDocParsingMode = 2 /* ParseForTypeErrors */;
function performBuild(sys2, cb, buildOptions, watchOptions, projects, errors) {
  const reportDiagnostic = updateReportDiagnostic(
    sys2,
    createDiagnosticReporter(sys2),
    buildOptions
  );
  if (buildOptions.locale) {
    validateLocaleAndSetLanguage(buildOptions.locale, sys2, errors);
  }
  if (errors.length > 0) {
    errors.forEach(reportDiagnostic);
    return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */);
  }
  if (buildOptions.help) {
    printVersion(sys2);
    printBuildHelp(sys2, buildOpts);
    return sys2.exit(0 /* Success */);
  }
  if (projects.length === 0) {
    printVersion(sys2);
    printBuildHelp(sys2, buildOpts);
    return sys2.exit(0 /* Success */);
  }
  if (!sys2.getModifiedTime || !sys2.setModifiedTime || buildOptions.clean && !sys2.deleteFile) {
    reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--build"));
    return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */);
  }
  if (buildOptions.watch) {
    if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return;
    const buildHost2 = createSolutionBuilderWithWatchHost(
      sys2,
      /*createProgram*/
      void 0,
      reportDiagnostic,
      createBuilderStatusReporter(sys2, shouldBePretty(sys2, buildOptions)),
      createWatchStatusReporter2(sys2, buildOptions)
    );
    buildHost2.jsDocParsingMode = defaultJSDocParsingMode;
    const solutionPerformance2 = enableSolutionPerformance(sys2, buildOptions);
    updateSolutionBuilderHost(sys2, cb, buildHost2, solutionPerformance2);
    const onWatchStatusChange = buildHost2.onWatchStatusChange;
    let reportBuildStatistics = false;
    buildHost2.onWatchStatusChange = (d, newLine, options, errorCount) => {
      onWatchStatusChange == null ? void 0 : onWatchStatusChange(d, newLine, options, errorCount);
      if (reportBuildStatistics && (d.code === Diagnostics.Found_0_errors_Watching_for_file_changes.code || d.code === Diagnostics.Found_1_error_Watching_for_file_changes.code)) {
        reportSolutionBuilderTimes(builder2, solutionPerformance2);
      }
    };
    const builder2 = createSolutionBuilderWithWatch(buildHost2, projects, buildOptions, watchOptions);
    builder2.build();
    reportSolutionBuilderTimes(builder2, solutionPerformance2);
    reportBuildStatistics = true;
    return builder2;
  }
  const buildHost = createSolutionBuilderHost(
    sys2,
    /*createProgram*/
    void 0,
    reportDiagnostic,
    createBuilderStatusReporter(sys2, shouldBePretty(sys2, buildOptions)),
    createReportErrorSummary(sys2, buildOptions)
  );
  buildHost.jsDocParsingMode = defaultJSDocParsingMode;
  const solutionPerformance = enableSolutionPerformance(sys2, buildOptions);
  updateSolutionBuilderHost(sys2, cb, buildHost, solutionPerformance);
  const builder = createSolutionBuilder(buildHost, projects, buildOptions);
  const exitStatus = buildOptions.clean ? builder.clean() : builder.build();
  reportSolutionBuilderTimes(builder, solutionPerformance);
  dumpTracingLegend();
  return sys2.exit(exitStatus);
}
function createReportErrorSummary(sys2, options) {
  return shouldBePretty(sys2, options) ? (errorCount, filesInError) => sys2.write(getErrorSummaryText(errorCount, filesInError, sys2.newLine, sys2)) : void 0;
}
function performCompilation(sys2, cb, reportDiagnostic, config) {
  const { fileNames, options, projectReferences } = config;
  const host = createCompilerHostWorker(
    options,
    /*setParentNodes*/
    void 0,
    sys2
  );
  host.jsDocParsingMode = defaultJSDocParsingMode;
  const currentDirectory = host.getCurrentDirectory();
  const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
  changeCompilerHostLikeToUseCache(host, (fileName) => toPath(fileName, currentDirectory, getCanonicalFileName));
  enableStatisticsAndTracing(
    sys2,
    options,
    /*isBuildMode*/
    false
  );
  const programOptions = {
    rootNames: fileNames,
    options,
    projectReferences,
    host,
    configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config)
  };
  const program = createProgram(programOptions);
  const exitStatus = emitFilesAndReportErrorsAndGetExitStatus(
    program,
    reportDiagnostic,
    (s) => sys2.write(s + sys2.newLine),
    createReportErrorSummary(sys2, options)
  );
  reportStatistics(
    sys2,
    program,
    /*solutionPerformance*/
    void 0
  );
  cb(program);
  return sys2.exit(exitStatus);
}
function performIncrementalCompilation2(sys2, cb, reportDiagnostic, config) {
  const { options, fileNames, projectReferences } = config;
  enableStatisticsAndTracing(
    sys2,
    options,
    /*isBuildMode*/
    false
  );
  const host = createIncrementalCompilerHost(options, sys2);
  host.jsDocParsingMode = defaultJSDocParsingMode;
  const exitStatus = performIncrementalCompilation({
    host,
    system: sys2,
    rootNames: fileNames,
    options,
    configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config),
    projectReferences,
    reportDiagnostic,
    reportErrorSummary: createReportErrorSummary(sys2, options),
    afterProgramEmitAndDiagnostics: (builderProgram) => {
      reportStatistics(
        sys2,
        builderProgram.getProgram(),
        /*solutionPerformance*/
        void 0
      );
      cb(builderProgram);
    }
  });
  return sys2.exit(exitStatus);
}
function updateSolutionBuilderHost(sys2, cb, buildHost, solutionPerformance) {
  updateCreateProgram(
    sys2,
    buildHost,
    /*isBuildMode*/
    true
  );
  buildHost.afterProgramEmitAndDiagnostics = (program) => {
    reportStatistics(sys2, program.getProgram(), solutionPerformance);
    cb(program);
  };
}
function updateCreateProgram(sys2, host, isBuildMode) {
  const compileUsingBuilder = host.createProgram;
  host.createProgram = (rootNames, options, host2, oldProgram, configFileParsingDiagnostics, projectReferences) => {
    Debug.assert(rootNames !== void 0 || options === void 0 && !!oldProgram);
    if (options !== void 0) {
      enableStatisticsAndTracing(sys2, options, isBuildMode);
    }
    return compileUsingBuilder(rootNames, options, host2, oldProgram, configFileParsingDiagnostics, projectReferences);
  };
}
function updateWatchCompilationHost(sys2, cb, watchCompilerHost) {
  watchCompilerHost.jsDocParsingMode = defaultJSDocParsingMode;
  updateCreateProgram(
    sys2,
    watchCompilerHost,
    /*isBuildMode*/
    false
  );
  const emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate;
  watchCompilerHost.afterProgramCreate = (builderProgram) => {
    emitFilesUsingBuilder(builderProgram);
    reportStatistics(
      sys2,
      builderProgram.getProgram(),
      /*solutionPerformance*/
      void 0
    );
    cb(builderProgram);
  };
}
function createWatchStatusReporter2(sys2, options) {
  return createWatchStatusReporter(sys2, shouldBePretty(sys2, options));
}
function createWatchOfConfigFile(system, cb, reportDiagnostic, configParseResult, optionsToExtend, watchOptionsToExtend, extendedConfigCache) {
  const watchCompilerHost = createWatchCompilerHostOfConfigFile({
    configFileName: configParseResult.options.configFilePath,
    optionsToExtend,
    watchOptionsToExtend,
    system,
    reportDiagnostic,
    reportWatchStatus: createWatchStatusReporter2(system, configParseResult.options)
  });
  updateWatchCompilationHost(system, cb, watchCompilerHost);
  watchCompilerHost.configFileParsingResult = configParseResult;
  watchCompilerHost.extendedConfigCache = extendedConfigCache;
  return createWatchProgram(watchCompilerHost);
}
function createWatchOfFilesAndCompilerOptions(system, cb, reportDiagnostic, rootFiles, options, watchOptions) {
  const watchCompilerHost = createWatchCompilerHostOfFilesAndCompilerOptions({
    rootFiles,
    options,
    watchOptions,
    system,
    reportDiagnostic,
    reportWatchStatus: createWatchStatusReporter2(system, options)
  });
  updateWatchCompilationHost(system, cb, watchCompilerHost);
  return createWatchProgram(watchCompilerHost);
}
function enableSolutionPerformance(system, options) {
  if (system === sys && options.extendedDiagnostics) {
    enable();
    return createSolutionPerfomrance();
  }
}
function createSolutionPerfomrance() {
  let statistics;
  return {
    addAggregateStatistic,
    forEachAggregateStatistics: forEachAggreateStatistics,
    clear: clear2
  };
  function addAggregateStatistic(s) {
    const existing = statistics == null ? void 0 : statistics.get(s.name);
    if (existing) {
      if (existing.type === 2 /* memory */) existing.value = Math.max(existing.value, s.value);
      else existing.value += s.value;
    } else {
      (statistics ?? (statistics = /* @__PURE__ */ new Map())).set(s.name, s);
    }
  }
  function forEachAggreateStatistics(cb) {
    statistics == null ? void 0 : statistics.forEach(cb);
  }
  function clear2() {
    statistics = void 0;
  }
}
function reportSolutionBuilderTimes(builder, solutionPerformance) {
  if (!solutionPerformance) return;
  if (!isEnabled()) {
    sys.write(Diagnostics.Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found.message + "\n");
    return;
  }
  const statistics = [];
  statistics.push(
    { name: "Projects in scope", value: getBuildOrderFromAnyBuildOrder(builder.getBuildOrder()).length, type: 1 /* count */ }
  );
  reportSolutionBuilderCountStatistic("SolutionBuilder::Projects built");
  reportSolutionBuilderCountStatistic("SolutionBuilder::Timestamps only updates");
  reportSolutionBuilderCountStatistic("SolutionBuilder::Bundles updated");
  solutionPerformance.forEachAggregateStatistics((s) => {
    s.name = `Aggregate ${s.name}`;
    statistics.push(s);
  });
  forEachMeasure((name, duration) => {
    if (isSolutionMarkOrMeasure(name)) statistics.push({ name: `${getNameFromSolutionBuilderMarkOrMeasure(name)} time`, value: duration, type: 0 /* time */ });
  });
  disable();
  enable();
  solutionPerformance.clear();
  reportAllStatistics(sys, statistics);
  function reportSolutionBuilderCountStatistic(name) {
    const value = getCount(name);
    if (value) {
      statistics.push({ name: getNameFromSolutionBuilderMarkOrMeasure(name), value, type: 1 /* count */ });
    }
  }
  function getNameFromSolutionBuilderMarkOrMeasure(name) {
    return name.replace("SolutionBuilder::", "");
  }
}
function canReportDiagnostics(system, compilerOptions) {
  return system === sys && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics);
}
function canTrace(system, compilerOptions) {
  return system === sys && compilerOptions.generateTrace;
}
function enableStatisticsAndTracing(system, compilerOptions, isBuildMode) {
  if (canReportDiagnostics(system, compilerOptions)) {
    enable(system);
  }
  if (canTrace(system, compilerOptions)) {
    startTracing(isBuildMode ? "build" : "project", compilerOptions.generateTrace, compilerOptions.configFilePath);
  }
}
function isSolutionMarkOrMeasure(name) {
  return startsWith(name, "SolutionBuilder::");
}
function reportStatistics(sys2, program, solutionPerformance) {
  var _a;
  const compilerOptions = program.getCompilerOptions();
  if (canTrace(sys2, compilerOptions)) {
    (_a = tracing) == null ? void 0 : _a.stopTracing();
  }
  let statistics;
  if (canReportDiagnostics(sys2, compilerOptions)) {
    statistics = [];
    const memoryUsed = sys2.getMemoryUsage ? sys2.getMemoryUsage() : -1;
    reportCountStatistic("Files", program.getSourceFiles().length);
    const lineCounts = countLines(program);
    if (compilerOptions.extendedDiagnostics) {
      for (const [key, value] of lineCounts.entries()) {
        reportCountStatistic("Lines of " + key, value);
      }
    } else {
      reportCountStatistic("Lines", reduceLeftIterator(lineCounts.values(), (sum, count) => sum + count, 0));
    }
    reportCountStatistic("Identifiers", program.getIdentifierCount());
    reportCountStatistic("Symbols", program.getSymbolCount());
    reportCountStatistic("Types", program.getTypeCount());
    reportCountStatistic("Instantiations", program.getInstantiationCount());
    if (memoryUsed >= 0) {
      reportStatisticalValue(
        { name: "Memory used", value: memoryUsed, type: 2 /* memory */ },
        /*aggregate*/
        true
      );
    }
    const isPerformanceEnabled = isEnabled();
    const programTime = isPerformanceEnabled ? getDuration("Program") : 0;
    const bindTime = isPerformanceEnabled ? getDuration("Bind") : 0;
    const checkTime = isPerformanceEnabled ? getDuration("Check") : 0;
    const emitTime = isPerformanceEnabled ? getDuration("Emit") : 0;
    if (compilerOptions.extendedDiagnostics) {
      const caches = program.getRelationCacheSizes();
      reportCountStatistic("Assignability cache size", caches.assignable);
      reportCountStatistic("Identity cache size", caches.identity);
      reportCountStatistic("Subtype cache size", caches.subtype);
      reportCountStatistic("Strict subtype cache size", caches.strictSubtype);
      if (isPerformanceEnabled) {
        forEachMeasure((name, duration) => {
          if (!isSolutionMarkOrMeasure(name)) reportTimeStatistic(
            `${name} time`,
            duration,
            /*aggregate*/
            true
          );
        });
      }
    } else if (isPerformanceEnabled) {
      reportTimeStatistic(
        "I/O read",
        getDuration("I/O Read"),
        /*aggregate*/
        true
      );
      reportTimeStatistic(
        "I/O write",
        getDuration("I/O Write"),
        /*aggregate*/
        true
      );
      reportTimeStatistic(
        "Parse time",
        programTime,
        /*aggregate*/
        true
      );
      reportTimeStatistic(
        "Bind time",
        bindTime,
        /*aggregate*/
        true
      );
      reportTimeStatistic(
        "Check time",
        checkTime,
        /*aggregate*/
        true
      );
      reportTimeStatistic(
        "Emit time",
        emitTime,
        /*aggregate*/
        true
      );
    }
    if (isPerformanceEnabled) {
      reportTimeStatistic(
        "Total time",
        programTime + bindTime + checkTime + emitTime,
        /*aggregate*/
        false
      );
    }
    reportAllStatistics(sys2, statistics);
    if (!isPerformanceEnabled) {
      sys2.write(Diagnostics.Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found.message + "\n");
    } else {
      if (solutionPerformance) {
        forEachMeasure((name) => {
          if (!isSolutionMarkOrMeasure(name)) clearMeasures(name);
        });
        forEachMark((name) => {
          if (!isSolutionMarkOrMeasure(name)) clearMarks(name);
        });
      } else {
        disable();
      }
    }
  }
  function reportStatisticalValue(s, aggregate) {
    statistics.push(s);
    if (aggregate) solutionPerformance == null ? void 0 : solutionPerformance.addAggregateStatistic(s);
  }
  function reportCountStatistic(name, count) {
    reportStatisticalValue(
      { name, value: count, type: 1 /* count */ },
      /*aggregate*/
      true
    );
  }
  function reportTimeStatistic(name, time, aggregate) {
    reportStatisticalValue({ name, value: time, type: 0 /* time */ }, aggregate);
  }
}
function reportAllStatistics(sys2, statistics) {
  let nameSize = 0;
  let valueSize = 0;
  for (const s of statistics) {
    if (s.name.length > nameSize) {
      nameSize = s.name.length;
    }
    const value = statisticValue(s);
    if (value.length > valueSize) {
      valueSize = value.length;
    }
  }
  for (const s of statistics) {
    sys2.write(`${s.name}:`.padEnd(nameSize + 2) + statisticValue(s).toString().padStart(valueSize) + sys2.newLine);
  }
}
function statisticValue(s) {
  switch (s.type) {
    case 1 /* count */:
      return "" + s.value;
    case 0 /* time */:
      return (s.value / 1e3).toFixed(2) + "s";
    case 2 /* memory */:
      return Math.round(s.value / 1e3) + "K";
    default:
      Debug.assertNever(s.type);
  }
}
function writeConfigFile(sys2, reportDiagnostic, options, fileNames) {
  const currentDirectory = sys2.getCurrentDirectory();
  const file = normalizePath(combinePaths(currentDirectory, "tsconfig.json"));
  if (sys2.fileExists(file)) {
    reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file));
  } else {
    sys2.writeFile(file, generateTSConfig(options, fileNames, sys2.newLine));
    const output = [sys2.newLine, ...getHeader(sys2, "Created a new tsconfig.json with:")];
    output.push(getCompilerOptionsDiffValue(options, sys2.newLine) + sys2.newLine + sys2.newLine);
    output.push(`You can learn more at https://aka.ms/tsconfig` + sys2.newLine);
    for (const line of output) {
      sys2.write(line);
    }
  }
  return;
}

// src/compiler/expressionToTypeNode.ts
function syntacticResult(type, reportFallback = true) {
  return { type, reportFallback };
}
var notImplemented2 = syntacticResult(
  /*type*/
  void 0,
  /*reportFallback*/
  false
);
var alreadyReported = syntacticResult(
  /*type*/
  void 0,
  /*reportFallback*/
  false
);
var failed = syntacticResult(
  /*type*/
  void 0,
  /*reportFallback*/
  true
);
function createSyntacticTypeNodeBuilder(options, resolver) {
  const strictNullChecks = getStrictOptionValue(options, "strictNullChecks");
  return {
    serializeTypeOfDeclaration,
    serializeReturnTypeForSignature,
    serializeTypeOfExpression,
    serializeTypeOfAccessor,
    tryReuseExistingTypeNode(context, existing) {
      if (!resolver.canReuseTypeNode(context, existing)) {
        return void 0;
      }
      return tryReuseExistingTypeNode(context, existing);
    }
  };
  function reuseNode(context, node, range = node) {
    return node === void 0 ? void 0 : resolver.markNodeReuse(context, node.flags & 16 /* Synthesized */ ? node : factory.cloneNode(node), range ?? node);
  }
  function tryReuseExistingTypeNode(context, existing) {
    const { finalizeBoundary, startRecoveryScope, hadError, markError } = resolver.createRecoveryBoundary(context);
    const transformed = visitNode(existing, visitExistingNodeTreeSymbols, isTypeNode);
    if (!finalizeBoundary()) {
      return void 0;
    }
    context.approximateLength += existing.end - existing.pos;
    return transformed;
    function visitExistingNodeTreeSymbols(node) {
      if (hadError()) return node;
      const recover = startRecoveryScope();
      const onExitNewScope = isNewScopeNode(node) ? resolver.enterNewScope(context, node) : void 0;
      const result = visitExistingNodeTreeSymbolsWorker(node);
      onExitNewScope == null ? void 0 : onExitNewScope();
      if (hadError()) {
        if (isTypeNode(node) && !isTypePredicateNode(node)) {
          recover();
          return resolver.serializeExistingTypeNode(context, node);
        }
        return node;
      }
      return result ? resolver.markNodeReuse(context, result, node) : void 0;
    }
    function tryVisitSimpleTypeNode(node) {
      const innerNode = skipTypeParentheses(node);
      switch (innerNode.kind) {
        case 183 /* TypeReference */:
          return tryVisitTypeReference(innerNode);
        case 186 /* TypeQuery */:
          return tryVisitTypeQuery(innerNode);
        case 199 /* IndexedAccessType */:
          return tryVisitIndexedAccess(innerNode);
        case 198 /* TypeOperator */:
          const typeOperatorNode = innerNode;
          if (typeOperatorNode.operator === 143 /* KeyOfKeyword */) {
            return tryVisitKeyOf(typeOperatorNode);
          }
      }
      return visitNode(node, visitExistingNodeTreeSymbols, isTypeNode);
    }
    function tryVisitIndexedAccess(node) {
      const resultObjectType = tryVisitSimpleTypeNode(node.objectType);
      if (resultObjectType === void 0) {
        return void 0;
      }
      return factory.updateIndexedAccessTypeNode(node, resultObjectType, visitNode(node.indexType, visitExistingNodeTreeSymbols, isTypeNode));
    }
    function tryVisitKeyOf(node) {
      Debug.assertEqual(node.operator, 143 /* KeyOfKeyword */);
      const type = tryVisitSimpleTypeNode(node.type);
      if (type === void 0) {
        return void 0;
      }
      return factory.updateTypeOperatorNode(node, type);
    }
    function tryVisitTypeQuery(node) {
      const { introducesError, node: exprName } = resolver.trackExistingEntityName(context, node.exprName);
      if (!introducesError) {
        return factory.updateTypeQueryNode(
          node,
          exprName,
          visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode)
        );
      }
      const serializedName = resolver.serializeTypeName(
        context,
        node.exprName,
        /*isTypeOf*/
        true
      );
      if (serializedName) {
        return resolver.markNodeReuse(context, serializedName, node.exprName);
      }
    }
    function tryVisitTypeReference(node) {
      if (resolver.canReuseTypeNode(context, node)) {
        const { introducesError, node: newName } = resolver.trackExistingEntityName(context, node.typeName);
        const typeArguments = visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode);
        if (!introducesError) {
          const updated = factory.updateTypeReferenceNode(
            node,
            newName,
            typeArguments
          );
          return resolver.markNodeReuse(context, updated, node);
        } else {
          const serializedName = resolver.serializeTypeName(
            context,
            node.typeName,
            /*isTypeOf*/
            false,
            typeArguments
          );
          if (serializedName) {
            return resolver.markNodeReuse(context, serializedName, node.typeName);
          }
        }
      }
    }
    function visitExistingNodeTreeSymbolsWorker(node) {
      var _a;
      if (isJSDocTypeExpression(node)) {
        return visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode);
      }
      if (isJSDocAllType(node) || node.kind === 319 /* JSDocNamepathType */) {
        return factory.createKeywordTypeNode(133 /* AnyKeyword */);
      }
      if (isJSDocUnknownType(node)) {
        return factory.createKeywordTypeNode(159 /* UnknownKeyword */);
      }
      if (isJSDocNullableType(node)) {
        return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createLiteralTypeNode(factory.createNull())]);
      }
      if (isJSDocOptionalType(node)) {
        return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]);
      }
      if (isJSDocNonNullableType(node)) {
        return visitNode(node.type, visitExistingNodeTreeSymbols);
      }
      if (isJSDocVariadicType(node)) {
        return factory.createArrayTypeNode(visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode));
      }
      if (isJSDocTypeLiteral(node)) {
        return factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (t) => {
          const name = visitNode(isIdentifier(t.name) ? t.name : t.name.right, visitExistingNodeTreeSymbols, isIdentifier);
          const overrideTypeNode = resolver.getJsDocPropertyOverride(context, node, t);
          return factory.createPropertySignature(
            /*modifiers*/
            void 0,
            name,
            t.isBracketed || t.typeExpression && isJSDocOptionalType(t.typeExpression.type) ? factory.createToken(58 /* QuestionToken */) : void 0,
            overrideTypeNode || t.typeExpression && visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */)
          );
        }));
      }
      if (isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "") {
        return setOriginalNode(factory.createKeywordTypeNode(133 /* AnyKeyword */), node);
      }
      if ((isExpressionWithTypeArguments(node) || isTypeReferenceNode(node)) && isJSDocIndexSignature(node)) {
        return factory.createTypeLiteralNode([factory.createIndexSignature(
          /*modifiers*/
          void 0,
          [factory.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            "x",
            /*questionToken*/
            void 0,
            visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols, isTypeNode)
          )],
          visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols, isTypeNode)
        )]);
      }
      if (isJSDocFunctionType(node)) {
        if (isJSDocConstructSignature(node)) {
          let newTypeNode;
          return factory.createConstructorTypeNode(
            /*modifiers*/
            void 0,
            visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration),
            mapDefined(node.parameters, (p, i) => p.name && isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode = p.type, void 0) : factory.createParameterDeclaration(
              /*modifiers*/
              void 0,
              getEffectiveDotDotDotForParameter(p),
              resolver.markNodeReuse(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p),
              factory.cloneNode(p.questionToken),
              visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode),
              /*initializer*/
              void 0
            )),
            visitNode(newTypeNode || node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */)
          );
        } else {
          return factory.createFunctionTypeNode(
            visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration),
            map(node.parameters, (p, i) => factory.createParameterDeclaration(
              /*modifiers*/
              void 0,
              getEffectiveDotDotDotForParameter(p),
              resolver.markNodeReuse(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p),
              factory.cloneNode(p.questionToken),
              visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode),
              /*initializer*/
              void 0
            )),
            visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */)
          );
        }
      }
      if (isThisTypeNode(node)) {
        if (resolver.canReuseTypeNode(context, node)) {
          return node;
        }
        markError();
        return node;
      }
      if (isTypeParameterDeclaration(node)) {
        const { node: newName } = resolver.trackExistingEntityName(context, node.name);
        return factory.updateTypeParameterDeclaration(
          node,
          visitNodes2(node.modifiers, visitExistingNodeTreeSymbols, isModifier),
          // resolver.markNodeReuse(context, typeParameterToName(getDeclaredTypeOfSymbol(getSymbolOfDeclaration(node)), context), node),
          newName,
          visitNode(node.constraint, visitExistingNodeTreeSymbols, isTypeNode),
          visitNode(node.default, visitExistingNodeTreeSymbols, isTypeNode)
        );
      }
      if (isIndexedAccessTypeNode(node)) {
        const result = tryVisitIndexedAccess(node);
        if (!result) {
          markError();
          return node;
        }
        return result;
      }
      if (isTypeReferenceNode(node)) {
        const result = tryVisitTypeReference(node);
        if (result) {
          return result;
        }
        markError();
        return node;
      }
      if (isLiteralImportTypeNode(node)) {
        if (((_a = node.attributes) == null ? void 0 : _a.token) === 132 /* AssertKeyword */) {
          markError();
          return node;
        }
        if (!resolver.canReuseTypeNode(context, node)) {
          return resolver.serializeExistingTypeNode(context, node);
        }
        return factory.updateImportTypeNode(
          node,
          factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier2(node, node.argument.literal)),
          visitNode(node.attributes, visitExistingNodeTreeSymbols, isImportAttributes),
          visitNode(node.qualifier, visitExistingNodeTreeSymbols, isEntityName),
          visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode),
          node.isTypeOf
        );
      }
      if (isNamedDeclaration(node) && node.name.kind === 167 /* ComputedPropertyName */ && !resolver.hasLateBindableName(node)) {
        if (!hasDynamicName(node)) {
          return visitEachChild2(node, visitExistingNodeTreeSymbols);
        }
        if (resolver.shouldRemoveDeclaration(context, node)) {
          return void 0;
        }
      }
      if (isFunctionLike(node) && !node.type || isPropertyDeclaration(node) && !node.type && !node.initializer || isPropertySignature(node) && !node.type && !node.initializer || isParameter(node) && !node.type && !node.initializer) {
        let visited = visitEachChild2(node, visitExistingNodeTreeSymbols);
        if (visited === node) {
          visited = resolver.markNodeReuse(context, factory.cloneNode(node), node);
        }
        visited.type = factory.createKeywordTypeNode(133 /* AnyKeyword */);
        if (isParameter(node)) {
          visited.modifiers = void 0;
        }
        return visited;
      }
      if (isTypeQueryNode(node)) {
        const result = tryVisitTypeQuery(node);
        if (!result) {
          markError();
          return node;
        }
        return result;
      }
      if (isComputedPropertyName(node) && isEntityNameExpression(node.expression)) {
        const { node: result, introducesError } = resolver.trackExistingEntityName(context, node.expression);
        if (!introducesError) {
          return factory.updateComputedPropertyName(node, result);
        } else {
          const computedPropertyNameType = resolver.serializeTypeOfExpression(context, node.expression);
          let literal;
          if (isLiteralTypeNode(computedPropertyNameType)) {
            literal = computedPropertyNameType.literal;
          } else {
            const evaluated = resolver.evaluateEntityNameExpression(node.expression);
            const literalNode = typeof evaluated.value === "string" ? factory.createStringLiteral(
              evaluated.value,
              /*isSingleQuote*/
              void 0
            ) : typeof evaluated.value === "number" ? factory.createNumericLiteral(
              evaluated.value,
              /*numericLiteralFlags*/
              0
            ) : void 0;
            if (!literalNode) {
              if (isImportTypeNode(computedPropertyNameType)) {
                resolver.trackComputedName(context, node.expression);
              }
              return node;
            }
            literal = literalNode;
          }
          if (literal.kind === 11 /* StringLiteral */ && isIdentifierText(literal.text, getEmitScriptTarget(options))) {
            return factory.createIdentifier(literal.text);
          }
          if (literal.kind === 9 /* NumericLiteral */ && !literal.text.startsWith("-")) {
            return literal;
          }
          return factory.updateComputedPropertyName(node, literal);
        }
      }
      if (isTypePredicateNode(node)) {
        let parameterName;
        if (isIdentifier(node.parameterName)) {
          const { node: result, introducesError } = resolver.trackExistingEntityName(context, node.parameterName);
          if (introducesError) markError();
          parameterName = result;
        } else {
          parameterName = factory.cloneNode(node.parameterName);
        }
        return factory.updateTypePredicateNode(node, factory.cloneNode(node.assertsModifier), parameterName, visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode));
      }
      if (isTupleTypeNode(node) || isTypeLiteralNode(node) || isMappedTypeNode(node)) {
        const visited = visitEachChild2(node, visitExistingNodeTreeSymbols);
        const clone2 = resolver.markNodeReuse(context, visited === node ? factory.cloneNode(node) : visited, node);
        const flags = getEmitFlags(clone2);
        setEmitFlags(clone2, flags | (context.flags & 1024 /* MultilineObjectLiterals */ && isTypeLiteralNode(node) ? 0 : 1 /* SingleLine */));
        return clone2;
      }
      if (isStringLiteral(node) && !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */) && !node.singleQuote) {
        const clone2 = factory.cloneNode(node);
        clone2.singleQuote = true;
        return clone2;
      }
      if (isConditionalTypeNode(node)) {
        const checkType = visitNode(node.checkType, visitExistingNodeTreeSymbols, isTypeNode);
        const disposeScope = resolver.enterNewScope(context, node);
        const extendType = visitNode(node.extendsType, visitExistingNodeTreeSymbols, isTypeNode);
        const trueType = visitNode(node.trueType, visitExistingNodeTreeSymbols, isTypeNode);
        disposeScope();
        const falseType = visitNode(node.falseType, visitExistingNodeTreeSymbols, isTypeNode);
        return factory.updateConditionalTypeNode(
          node,
          checkType,
          extendType,
          trueType,
          falseType
        );
      }
      if (isTypeOperatorNode(node)) {
        if (node.operator === 158 /* UniqueKeyword */ && node.type.kind === 155 /* SymbolKeyword */) {
          if (!resolver.canReuseTypeNode(context, node)) {
            markError();
            return node;
          }
        } else if (node.operator === 143 /* KeyOfKeyword */) {
          const result = tryVisitKeyOf(node);
          if (!result) {
            markError();
            return node;
          }
          return result;
        }
      }
      return visitEachChild2(node, visitExistingNodeTreeSymbols);
      function visitEachChild2(node2, visitor) {
        const nonlocalNode = !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(node2);
        return visitEachChild(
          node2,
          visitor,
          /*context*/
          void 0,
          nonlocalNode ? visitNodesWithoutCopyingPositions : void 0
        );
      }
      function visitNodesWithoutCopyingPositions(nodes, visitor, test, start, count) {
        let result = visitNodes2(nodes, visitor, test, start, count);
        if (result) {
          if (result.pos !== -1 || result.end !== -1) {
            if (result === nodes) {
              result = factory.createNodeArray(nodes.slice(), nodes.hasTrailingComma);
            }
            setTextRangePosEnd(result, -1, -1);
          }
        }
        return result;
      }
      function getEffectiveDotDotDotForParameter(p) {
        return p.dotDotDotToken || (p.type && isJSDocVariadicType(p.type) ? factory.createToken(26 /* DotDotDotToken */) : void 0);
      }
      function getNameForJSDocFunctionParameter(p, index) {
        return p.name && isIdentifier(p.name) && p.name.escapedText === "this" ? "this" : getEffectiveDotDotDotForParameter(p) ? `args` : `arg${index}`;
      }
      function rewriteModuleSpecifier2(parent2, lit) {
        const newName = resolver.getModuleSpecifierOverride(context, parent2, lit);
        if (newName) {
          return setOriginalNode(factory.createStringLiteral(newName), lit);
        }
        return visitNode(lit, visitExistingNodeTreeSymbols, isStringLiteral);
      }
    }
  }
  function serializeExistingTypeNode(typeNode, context, addUndefined) {
    if (!typeNode) return void 0;
    let result;
    if ((!addUndefined || canAddUndefined(typeNode)) && resolver.canReuseTypeNode(context, typeNode)) {
      result = tryReuseExistingTypeNode(context, typeNode);
      if (result !== void 0) {
        result = addUndefinedIfNeeded(
          result,
          addUndefined,
          /*owner*/
          void 0,
          context
        );
      }
    }
    return result;
  }
  function serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol, requiresAddingUndefined, useFallback = requiresAddingUndefined !== void 0) {
    if (!declaredType) return void 0;
    if (!resolver.canReuseTypeNodeAnnotation(context, node, declaredType, symbol, requiresAddingUndefined)) {
      if (!requiresAddingUndefined || !resolver.canReuseTypeNodeAnnotation(
        context,
        node,
        declaredType,
        symbol,
        /*requiresAddingUndefined*/
        false
      )) {
        return void 0;
      }
    }
    let result;
    if (!requiresAddingUndefined || canAddUndefined(declaredType)) {
      result = serializeExistingTypeNode(declaredType, context, requiresAddingUndefined);
    }
    if (result !== void 0 || !useFallback) {
      return result;
    }
    context.tracker.reportInferenceFallback(node);
    return resolver.serializeExistingTypeNode(context, declaredType, requiresAddingUndefined) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */);
  }
  function serializeExistingTypeNodeWithFallback(typeNode, context, addUndefined, targetNode) {
    if (!typeNode) return void 0;
    const result = serializeExistingTypeNode(typeNode, context, addUndefined);
    if (result !== void 0) {
      return result;
    }
    context.tracker.reportInferenceFallback(targetNode ?? typeNode);
    return resolver.serializeExistingTypeNode(context, typeNode, addUndefined) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */);
  }
  function serializeTypeOfAccessor(accessor, symbol, context) {
    return typeFromAccessor(accessor, symbol, context) ?? inferAccessorType(accessor, resolver.getAllAccessorDeclarations(accessor), context, symbol);
  }
  function serializeTypeOfExpression(expr, context, addUndefined, preserveLiterals) {
    const result = typeFromExpression(
      expr,
      context,
      /*isConstContext*/
      false,
      addUndefined,
      preserveLiterals
    );
    return result.type !== void 0 ? result.type : inferExpressionType(expr, context, result.reportFallback);
  }
  function serializeTypeOfDeclaration(node, symbol, context) {
    switch (node.kind) {
      case 169 /* Parameter */:
      case 341 /* JSDocParameterTag */:
        return typeFromParameter(node, symbol, context);
      case 260 /* VariableDeclaration */:
        return typeFromVariable(node, symbol, context);
      case 171 /* PropertySignature */:
      case 348 /* JSDocPropertyTag */:
      case 172 /* PropertyDeclaration */:
        return typeFromProperty(node, symbol, context);
      case 208 /* BindingElement */:
        return inferTypeOfDeclaration(node, symbol, context);
      case 277 /* ExportAssignment */:
        return serializeTypeOfExpression(
          node.expression,
          context,
          /*addUndefined*/
          void 0,
          /*preserveLiterals*/
          true
        );
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
      case 226 /* BinaryExpression */:
        return typeFromExpandoProperty(node, symbol, context);
      case 303 /* PropertyAssignment */:
      case 304 /* ShorthandPropertyAssignment */:
        return typeFromPropertyAssignment(node, symbol, context);
      default:
        Debug.assertNever(node, `Node needs to be an inferrable node, found ${Debug.formatSyntaxKind(node.kind)}`);
    }
  }
  function typeFromPropertyAssignment(node, symbol, context) {
    const typeAnnotation = getEffectiveTypeAnnotationNode(node);
    let result;
    if (typeAnnotation && resolver.canReuseTypeNodeAnnotation(context, node, typeAnnotation, symbol)) {
      result = serializeExistingTypeNode(typeAnnotation, context);
    }
    if (!result && node.kind === 303 /* PropertyAssignment */) {
      const initializer = node.initializer;
      const assertionNode = isJSDocTypeAssertion(initializer) ? getJSDocTypeAssertionType(initializer) : initializer.kind === 234 /* AsExpression */ || initializer.kind === 216 /* TypeAssertionExpression */ ? initializer.type : void 0;
      if (assertionNode && !isConstTypeReference(assertionNode) && resolver.canReuseTypeNodeAnnotation(context, node, assertionNode, symbol)) {
        result = serializeExistingTypeNode(assertionNode, context);
      }
    }
    return result ?? inferTypeOfDeclaration(
      node,
      symbol,
      context,
      /*reportFallback*/
      false
    );
  }
  function serializeReturnTypeForSignature(node, symbol, context) {
    switch (node.kind) {
      case 177 /* GetAccessor */:
        return serializeTypeOfAccessor(node, symbol, context);
      case 174 /* MethodDeclaration */:
      case 262 /* FunctionDeclaration */:
      case 180 /* ConstructSignature */:
      case 173 /* MethodSignature */:
      case 179 /* CallSignature */:
      case 176 /* Constructor */:
      case 178 /* SetAccessor */:
      case 181 /* IndexSignature */:
      case 184 /* FunctionType */:
      case 185 /* ConstructorType */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 317 /* JSDocFunctionType */:
      case 323 /* JSDocSignature */:
        return createReturnFromSignature(node, symbol, context);
      default:
        Debug.assertNever(node, `Node needs to be an inferrable node, found ${Debug.formatSyntaxKind(node.kind)}`);
    }
  }
  function getTypeAnnotationFromAccessor(accessor) {
    if (accessor) {
      return accessor.kind === 177 /* GetAccessor */ ? isInJSFile(accessor) && getJSDocType(accessor) || getEffectiveReturnTypeNode(accessor) : getEffectiveSetAccessorTypeAnnotationNode(accessor);
    }
  }
  function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
    let accessorType = getTypeAnnotationFromAccessor(node);
    if (!accessorType && node !== accessors.firstAccessor) {
      accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
    }
    if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
      accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
    }
    return accessorType;
  }
  function typeFromAccessor(node, symbol, context) {
    const accessorDeclarations = resolver.getAllAccessorDeclarations(node);
    const accessorType = getTypeAnnotationFromAllAccessorDeclarations(node, accessorDeclarations);
    if (accessorType && !isTypePredicateNode(accessorType)) {
      return withNewScope(context, node, () => serializeTypeAnnotationOfDeclaration(accessorType, context, node, symbol) ?? inferTypeOfDeclaration(node, symbol, context));
    }
    if (accessorDeclarations.getAccessor) {
      return withNewScope(context, accessorDeclarations.getAccessor, () => createReturnFromSignature(
        accessorDeclarations.getAccessor,
        /*symbol*/
        void 0,
        context
      ));
    }
    return void 0;
  }
  function typeFromVariable(node, symbol, context) {
    var _a;
    const declaredType = getEffectiveTypeAnnotationNode(node);
    let resultType = failed;
    if (declaredType) {
      resultType = syntacticResult(serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol));
    } else if (node.initializer && (((_a = symbol.declarations) == null ? void 0 : _a.length) === 1 || countWhere(symbol.declarations, isVariableDeclaration) === 1)) {
      if (!resolver.isExpandoFunctionDeclaration(node) && !isContextuallyTyped(node)) {
        resultType = typeFromExpression(
          node.initializer,
          context,
          /*isConstContext*/
          void 0,
          /*requiresAddingUndefined*/
          void 0,
          isVarConstLike(node)
        );
      }
    }
    return resultType.type !== void 0 ? resultType.type : inferTypeOfDeclaration(node, symbol, context, resultType.reportFallback);
  }
  function typeFromParameter(node, symbol, context) {
    const parent2 = node.parent;
    if (parent2.kind === 178 /* SetAccessor */) {
      return serializeTypeOfAccessor(
        parent2,
        /*symbol*/
        void 0,
        context
      );
    }
    const declaredType = getEffectiveTypeAnnotationNode(node);
    const addUndefined = resolver.requiresAddingImplicitUndefined(node, symbol, context.enclosingDeclaration);
    let resultType = failed;
    if (declaredType) {
      resultType = syntacticResult(serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol, addUndefined));
    } else if (isParameter(node) && node.initializer && isIdentifier(node.name) && !isContextuallyTyped(node)) {
      resultType = typeFromExpression(
        node.initializer,
        context,
        /*isConstContext*/
        void 0,
        addUndefined
      );
    }
    return resultType.type !== void 0 ? resultType.type : inferTypeOfDeclaration(node, symbol, context, resultType.reportFallback);
  }
  function typeFromExpandoProperty(node, symbol, context) {
    const declaredType = getEffectiveTypeAnnotationNode(node);
    let result;
    if (declaredType) {
      result = serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol);
    }
    const oldSuppressReportInferenceFallback = context.suppressReportInferenceFallback;
    context.suppressReportInferenceFallback = true;
    const resultType = result ?? inferTypeOfDeclaration(
      node,
      symbol,
      context,
      /*reportFallback*/
      false
    );
    context.suppressReportInferenceFallback = oldSuppressReportInferenceFallback;
    return resultType;
  }
  function typeFromProperty(node, symbol, context) {
    const declaredType = getEffectiveTypeAnnotationNode(node);
    const requiresAddingUndefined = resolver.requiresAddingImplicitUndefined(node, symbol, context.enclosingDeclaration);
    let resultType = failed;
    if (declaredType) {
      resultType = syntacticResult(serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol, requiresAddingUndefined));
    } else {
      const initializer = isPropertyDeclaration(node) ? node.initializer : void 0;
      if (initializer && !isContextuallyTyped(node)) {
        const isReadonly = isDeclarationReadonly(node);
        resultType = typeFromExpression(
          initializer,
          context,
          /*isConstContext*/
          void 0,
          requiresAddingUndefined,
          isReadonly
        );
      }
    }
    return resultType.type !== void 0 ? resultType.type : inferTypeOfDeclaration(node, symbol, context, resultType.reportFallback);
  }
  function inferTypeOfDeclaration(node, symbol, context, reportFallback = true) {
    if (reportFallback) {
      context.tracker.reportInferenceFallback(node);
    }
    if (context.noInferenceFallback === true) {
      return factory.createKeywordTypeNode(133 /* AnyKeyword */);
    }
    return resolver.serializeTypeOfDeclaration(context, node, symbol);
  }
  function inferExpressionType(node, context, reportFallback = true, requiresAddingUndefined) {
    Debug.assert(!requiresAddingUndefined);
    if (reportFallback) {
      context.tracker.reportInferenceFallback(node);
    }
    if (context.noInferenceFallback === true) {
      return factory.createKeywordTypeNode(133 /* AnyKeyword */);
    }
    return resolver.serializeTypeOfExpression(context, node) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */);
  }
  function inferReturnTypeOfSignatureSignature(node, context, reportFallback) {
    if (reportFallback) {
      context.tracker.reportInferenceFallback(node);
    }
    if (context.noInferenceFallback === true) {
      return factory.createKeywordTypeNode(133 /* AnyKeyword */);
    }
    return resolver.serializeReturnTypeForSignature(context, node) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */);
  }
  function inferAccessorType(node, allAccessors, context, symbol, reportFallback = true) {
    if (node.kind === 177 /* GetAccessor */) {
      return createReturnFromSignature(node, symbol, context, reportFallback);
    } else {
      if (reportFallback) {
        context.tracker.reportInferenceFallback(node);
      }
      const result = allAccessors.getAccessor && createReturnFromSignature(allAccessors.getAccessor, symbol, context, reportFallback);
      return result ?? resolver.serializeTypeOfDeclaration(context, node, symbol) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */);
    }
  }
  function withNewScope(context, node, fn) {
    const cleanup = resolver.enterNewScope(context, node);
    const result = fn();
    cleanup();
    return result;
  }
  function typeFromTypeAssertion(expression, type, context, requiresAddingUndefined) {
    if (isConstTypeReference(type)) {
      return typeFromExpression(
        expression,
        context,
        /*isConstContext*/
        true,
        requiresAddingUndefined
      );
    }
    return syntacticResult(serializeExistingTypeNodeWithFallback(type, context, requiresAddingUndefined));
  }
  function typeFromExpression(node, context, isConstContext = false, requiresAddingUndefined = false, preserveLiterals = false) {
    switch (node.kind) {
      case 217 /* ParenthesizedExpression */:
        if (isJSDocTypeAssertion(node)) {
          return typeFromTypeAssertion(node.expression, getJSDocTypeAssertionType(node), context, requiresAddingUndefined);
        }
        return typeFromExpression(node.expression, context, isConstContext, requiresAddingUndefined);
      case 80 /* Identifier */:
        if (resolver.isUndefinedIdentifierExpression(node)) {
          return syntacticResult(createUndefinedTypeNode());
        }
        break;
      case 106 /* NullKeyword */:
        if (strictNullChecks) {
          return syntacticResult(addUndefinedIfNeeded(factory.createLiteralTypeNode(factory.createNull()), requiresAddingUndefined, node, context));
        } else {
          return syntacticResult(factory.createKeywordTypeNode(133 /* AnyKeyword */));
        }
      case 219 /* ArrowFunction */:
      case 218 /* FunctionExpression */:
        Debug.type(node);
        return withNewScope(context, node, () => typeFromFunctionLikeExpression(node, context));
      case 216 /* TypeAssertionExpression */:
      case 234 /* AsExpression */:
        const asExpression = node;
        return typeFromTypeAssertion(asExpression.expression, asExpression.type, context, requiresAddingUndefined);
      case 224 /* PrefixUnaryExpression */:
        const unaryExpression = node;
        if (isPrimitiveLiteralValue(unaryExpression)) {
          return typeFromPrimitiveLiteral(
            unaryExpression.operator === 40 /* PlusToken */ ? unaryExpression.operand : unaryExpression,
            unaryExpression.operand.kind === 10 /* BigIntLiteral */ ? 163 /* BigIntKeyword */ : 150 /* NumberKeyword */,
            context,
            isConstContext || preserveLiterals,
            requiresAddingUndefined
          );
        }
        break;
      case 209 /* ArrayLiteralExpression */:
        return typeFromArrayLiteral(node, context, isConstContext, requiresAddingUndefined);
      case 210 /* ObjectLiteralExpression */:
        return typeFromObjectLiteral(node, context, isConstContext, requiresAddingUndefined);
      case 231 /* ClassExpression */:
        return syntacticResult(inferExpressionType(
          node,
          context,
          /*reportFallback*/
          true,
          requiresAddingUndefined
        ));
      case 228 /* TemplateExpression */:
        if (!isConstContext && !preserveLiterals) {
          return syntacticResult(factory.createKeywordTypeNode(154 /* StringKeyword */));
        }
        break;
      default:
        let typeKind;
        let primitiveNode = node;
        switch (node.kind) {
          case 9 /* NumericLiteral */:
            typeKind = 150 /* NumberKeyword */;
            break;
          case 15 /* NoSubstitutionTemplateLiteral */:
            primitiveNode = factory.createStringLiteral(node.text);
            typeKind = 154 /* StringKeyword */;
            break;
          case 11 /* StringLiteral */:
            typeKind = 154 /* StringKeyword */;
            break;
          case 10 /* BigIntLiteral */:
            typeKind = 163 /* BigIntKeyword */;
            break;
          case 112 /* TrueKeyword */:
          case 97 /* FalseKeyword */:
            typeKind = 136 /* BooleanKeyword */;
            break;
        }
        if (typeKind) {
          return typeFromPrimitiveLiteral(primitiveNode, typeKind, context, isConstContext || preserveLiterals, requiresAddingUndefined);
        }
    }
    return failed;
  }
  function typeFromFunctionLikeExpression(fnNode, context) {
    const oldNoInferenceFallback = context.noInferenceFallback;
    context.noInferenceFallback = true;
    createReturnFromSignature(
      fnNode,
      /*symbol*/
      void 0,
      context
    );
    reuseTypeParameters(fnNode.typeParameters, context);
    fnNode.parameters.map((p) => ensureParameter(p, context));
    context.noInferenceFallback = oldNoInferenceFallback;
    return notImplemented2;
  }
  function canGetTypeFromArrayLiteral(arrayLiteral, context, isConstContext) {
    if (!isConstContext) {
      context.tracker.reportInferenceFallback(arrayLiteral);
      return false;
    }
    for (const element of arrayLiteral.elements) {
      if (element.kind === 230 /* SpreadElement */) {
        context.tracker.reportInferenceFallback(element);
        return false;
      }
    }
    return true;
  }
  function typeFromArrayLiteral(arrayLiteral, context, isConstContext, requiresAddingUndefined) {
    if (!canGetTypeFromArrayLiteral(arrayLiteral, context, isConstContext)) {
      if (requiresAddingUndefined || isDeclaration(walkUpParenthesizedExpressions(arrayLiteral).parent)) {
        return alreadyReported;
      }
      return syntacticResult(inferExpressionType(
        arrayLiteral,
        context,
        /*reportFallback*/
        false,
        requiresAddingUndefined
      ));
    }
    const oldNoInferenceFallback = context.noInferenceFallback;
    context.noInferenceFallback = true;
    const elementTypesInfo = [];
    for (const element of arrayLiteral.elements) {
      Debug.assert(element.kind !== 230 /* SpreadElement */);
      if (element.kind === 232 /* OmittedExpression */) {
        elementTypesInfo.push(
          createUndefinedTypeNode()
        );
      } else {
        const expressionType = typeFromExpression(element, context, isConstContext);
        const elementType = expressionType.type !== void 0 ? expressionType.type : inferExpressionType(element, context, expressionType.reportFallback);
        elementTypesInfo.push(elementType);
      }
    }
    const tupleType = factory.createTupleTypeNode(elementTypesInfo);
    tupleType.emitNode = { flags: 1, autoGenerate: void 0, internalFlags: 0 };
    context.noInferenceFallback = oldNoInferenceFallback;
    return notImplemented2;
  }
  function canGetTypeFromObjectLiteral(objectLiteral, context) {
    let result = true;
    for (const prop of objectLiteral.properties) {
      if (prop.flags & 262144 /* ThisNodeHasError */) {
        result = false;
        break;
      }
      if (prop.kind === 304 /* ShorthandPropertyAssignment */ || prop.kind === 305 /* SpreadAssignment */) {
        context.tracker.reportInferenceFallback(prop);
        result = false;
      } else if (prop.name.flags & 262144 /* ThisNodeHasError */) {
        result = false;
        break;
      } else if (prop.name.kind === 81 /* PrivateIdentifier */) {
        result = false;
      } else if (prop.name.kind === 167 /* ComputedPropertyName */) {
        const expression = prop.name.expression;
        if (!isPrimitiveLiteralValue(
          expression,
          /*includeBigInt*/
          false
        ) && !resolver.isDefinitelyReferenceToGlobalSymbolObject(expression)) {
          context.tracker.reportInferenceFallback(prop.name);
          result = false;
        }
      }
    }
    return result;
  }
  function typeFromObjectLiteral(objectLiteral, context, isConstContext, requiresAddingUndefined) {
    if (!canGetTypeFromObjectLiteral(objectLiteral, context)) {
      if (requiresAddingUndefined || isDeclaration(walkUpParenthesizedExpressions(objectLiteral).parent)) {
        return alreadyReported;
      }
      return syntacticResult(inferExpressionType(
        objectLiteral,
        context,
        /*reportFallback*/
        false,
        requiresAddingUndefined
      ));
    }
    const oldNoInferenceFallback = context.noInferenceFallback;
    context.noInferenceFallback = true;
    const properties = [];
    const oldFlags = context.flags;
    context.flags |= 4194304 /* InObjectTypeLiteral */;
    for (const prop of objectLiteral.properties) {
      Debug.assert(!isShorthandPropertyAssignment(prop) && !isSpreadAssignment(prop));
      const name = prop.name;
      let newProp;
      switch (prop.kind) {
        case 174 /* MethodDeclaration */:
          newProp = withNewScope(context, prop, () => typeFromObjectLiteralMethod(prop, name, context, isConstContext));
          break;
        case 303 /* PropertyAssignment */:
          newProp = typeFromObjectLiteralPropertyAssignment(prop, name, context, isConstContext);
          break;
        case 178 /* SetAccessor */:
        case 177 /* GetAccessor */:
          newProp = typeFromObjectLiteralAccessor(prop, name, context);
          break;
      }
      if (newProp) {
        setCommentRange(newProp, prop);
        properties.push(newProp);
      }
    }
    context.flags = oldFlags;
    const typeNode = factory.createTypeLiteralNode(properties);
    if (!(context.flags & 1024 /* MultilineObjectLiterals */)) {
      setEmitFlags(typeNode, 1 /* SingleLine */);
    }
    context.noInferenceFallback = oldNoInferenceFallback;
    return notImplemented2;
  }
  function typeFromObjectLiteralPropertyAssignment(prop, name, context, isConstContext) {
    const modifiers = isConstContext ? [factory.createModifier(148 /* ReadonlyKeyword */)] : [];
    const expressionResult = typeFromExpression(prop.initializer, context, isConstContext);
    const typeNode = expressionResult.type !== void 0 ? expressionResult.type : inferTypeOfDeclaration(
      prop,
      /*symbol*/
      void 0,
      context,
      expressionResult.reportFallback
    );
    return factory.createPropertySignature(
      modifiers,
      reuseNode(context, name),
      /*questionToken*/
      void 0,
      typeNode
    );
  }
  function ensureParameter(p, context) {
    return factory.updateParameterDeclaration(
      p,
      [],
      reuseNode(context, p.dotDotDotToken),
      resolver.serializeNameOfParameter(context, p),
      resolver.isOptionalParameter(p) ? factory.createToken(58 /* QuestionToken */) : void 0,
      typeFromParameter(
        p,
        /*symbol*/
        void 0,
        context
      ),
      // Ignore private param props, since this type is going straight back into a param
      /*initializer*/
      void 0
    );
  }
  function reuseTypeParameters(typeParameters, context) {
    return typeParameters == null ? void 0 : typeParameters.map(
      (tp) => {
        var _a;
        return factory.updateTypeParameterDeclaration(
          tp,
          (_a = tp.modifiers) == null ? void 0 : _a.map((m) => reuseNode(context, m)),
          reuseNode(context, tp.name),
          serializeExistingTypeNodeWithFallback(tp.constraint, context),
          serializeExistingTypeNodeWithFallback(tp.default, context)
        );
      }
    );
  }
  function typeFromObjectLiteralMethod(method, name, context, isConstContext) {
    const returnType = createReturnFromSignature(
      method,
      /*symbol*/
      void 0,
      context
    );
    const typeParameters = reuseTypeParameters(method.typeParameters, context);
    const parameters = method.parameters.map((p) => ensureParameter(p, context));
    if (isConstContext) {
      return factory.createPropertySignature(
        [factory.createModifier(148 /* ReadonlyKeyword */)],
        reuseNode(context, name),
        reuseNode(context, method.questionToken),
        factory.createFunctionTypeNode(
          typeParameters,
          parameters,
          returnType
        )
      );
    } else {
      if (isIdentifier(name) && name.escapedText === "new") {
        name = factory.createStringLiteral("new");
      }
      return factory.createMethodSignature(
        [],
        reuseNode(context, name),
        reuseNode(context, method.questionToken),
        typeParameters,
        parameters,
        returnType
      );
    }
  }
  function typeFromObjectLiteralAccessor(accessor, name, context) {
    const allAccessors = resolver.getAllAccessorDeclarations(accessor);
    const getAccessorType = allAccessors.getAccessor && getTypeAnnotationFromAccessor(allAccessors.getAccessor);
    const setAccessorType = allAccessors.setAccessor && getTypeAnnotationFromAccessor(allAccessors.setAccessor);
    if (getAccessorType !== void 0 && setAccessorType !== void 0) {
      return withNewScope(context, accessor, () => {
        const parameters = accessor.parameters.map((p) => ensureParameter(p, context));
        if (isGetAccessor(accessor)) {
          return factory.updateGetAccessorDeclaration(
            accessor,
            [],
            reuseNode(context, name),
            parameters,
            serializeExistingTypeNodeWithFallback(getAccessorType, context),
            /*body*/
            void 0
          );
        } else {
          return factory.updateSetAccessorDeclaration(
            accessor,
            [],
            reuseNode(context, name),
            parameters,
            /*body*/
            void 0
          );
        }
      });
    } else if (allAccessors.firstAccessor === accessor) {
      const foundType = getAccessorType ? withNewScope(context, allAccessors.getAccessor, () => serializeExistingTypeNodeWithFallback(getAccessorType, context)) : setAccessorType ? withNewScope(context, allAccessors.setAccessor, () => serializeExistingTypeNodeWithFallback(setAccessorType, context)) : void 0;
      const propertyType = foundType ?? inferAccessorType(
        accessor,
        allAccessors,
        context,
        /*symbol*/
        void 0
      );
      const propertySignature = factory.createPropertySignature(
        allAccessors.setAccessor === void 0 ? [factory.createModifier(148 /* ReadonlyKeyword */)] : [],
        reuseNode(context, name),
        /*questionToken*/
        void 0,
        propertyType
      );
      return propertySignature;
    }
  }
  function createUndefinedTypeNode() {
    if (strictNullChecks) {
      return factory.createKeywordTypeNode(157 /* UndefinedKeyword */);
    } else {
      return factory.createKeywordTypeNode(133 /* AnyKeyword */);
    }
  }
  function typeFromPrimitiveLiteral(node, baseType, context, preserveLiterals, requiresAddingUndefined) {
    let result;
    if (preserveLiterals) {
      if (node.kind === 224 /* PrefixUnaryExpression */ && node.operator === 40 /* PlusToken */) {
        result = factory.createLiteralTypeNode(reuseNode(context, node.operand));
      }
      result = factory.createLiteralTypeNode(reuseNode(context, node));
    } else {
      result = factory.createKeywordTypeNode(baseType);
    }
    return syntacticResult(addUndefinedIfNeeded(result, requiresAddingUndefined, node, context));
  }
  function addUndefinedIfNeeded(node, addUndefined, owner, context) {
    const parentDeclaration = owner && walkUpParenthesizedExpressions(owner).parent;
    const optionalDeclaration = parentDeclaration && isDeclaration(parentDeclaration) && isOptionalDeclaration(parentDeclaration);
    if (!strictNullChecks || !(addUndefined || optionalDeclaration)) return node;
    if (!canAddUndefined(node)) {
      context.tracker.reportInferenceFallback(node);
    }
    if (isUnionTypeNode(node)) {
      return factory.createUnionTypeNode([...node.types, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]);
    }
    return factory.createUnionTypeNode([node, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]);
  }
  function canAddUndefined(node) {
    if (!strictNullChecks) return true;
    if (isKeyword(node.kind) || node.kind === 201 /* LiteralType */ || node.kind === 184 /* FunctionType */ || node.kind === 185 /* ConstructorType */ || node.kind === 188 /* ArrayType */ || node.kind === 189 /* TupleType */ || node.kind === 187 /* TypeLiteral */ || node.kind === 203 /* TemplateLiteralType */ || node.kind === 197 /* ThisType */) {
      return true;
    }
    if (node.kind === 196 /* ParenthesizedType */) {
      return canAddUndefined(node.type);
    }
    if (node.kind === 192 /* UnionType */ || node.kind === 193 /* IntersectionType */) {
      return node.types.every(canAddUndefined);
    }
    return false;
  }
  function createReturnFromSignature(fn, symbol, context, reportFallback = true) {
    let returnType = failed;
    const returnTypeNode = isJSDocConstructSignature(fn) ? getEffectiveTypeAnnotationNode(fn.parameters[0]) : getEffectiveReturnTypeNode(fn);
    if (returnTypeNode) {
      returnType = syntacticResult(serializeTypeAnnotationOfDeclaration(returnTypeNode, context, fn, symbol));
    } else if (isValueSignatureDeclaration(fn)) {
      returnType = typeFromSingleReturnExpression(fn, context);
    }
    return returnType.type !== void 0 ? returnType.type : inferReturnTypeOfSignatureSignature(fn, context, reportFallback && returnType.reportFallback && !returnTypeNode);
  }
  function typeFromSingleReturnExpression(declaration, context) {
    let candidateExpr;
    if (declaration && !nodeIsMissing(declaration.body)) {
      const flags = getFunctionFlags(declaration);
      if (flags & 3 /* AsyncGenerator */) return failed;
      const body = declaration.body;
      if (body && isBlock(body)) {
        forEachReturnStatement(body, (s) => {
          if (s.parent !== body) {
            candidateExpr = void 0;
            return true;
          }
          if (!candidateExpr) {
            candidateExpr = s.expression;
          } else {
            candidateExpr = void 0;
            return true;
          }
        });
      } else {
        candidateExpr = body;
      }
    }
    if (candidateExpr) {
      if (isContextuallyTyped(candidateExpr)) {
        const type = isJSDocTypeAssertion(candidateExpr) ? getJSDocTypeAssertionType(candidateExpr) : isAsExpression(candidateExpr) || isTypeAssertionExpression(candidateExpr) ? candidateExpr.type : void 0;
        if (type && !isConstTypeReference(type)) {
          return syntacticResult(serializeExistingTypeNode(type, context));
        }
      } else {
        return typeFromExpression(candidateExpr, context);
      }
    }
    return failed;
  }
  function isContextuallyTyped(node) {
    return findAncestor(node.parent, (n) => {
      return isCallExpression(n) || !isFunctionLikeDeclaration(n) && !!getEffectiveTypeAnnotationNode(n) || isJsxElement(n) || isJsxExpression(n);
    });
  }
}

// src/jsTyping/_namespaces/ts.JsTyping.ts
var ts_JsTyping_exports = {};
__export(ts_JsTyping_exports, {
  NameValidationResult: () => NameValidationResult,
  discoverTypings: () => discoverTypings,
  isTypingUpToDate: () => isTypingUpToDate,
  loadSafeList: () => loadSafeList,
  loadTypesMap: () => loadTypesMap,
  nonRelativeModuleNameForTypingCache: () => nonRelativeModuleNameForTypingCache,
  renderPackageNameValidationFailure: () => renderPackageNameValidationFailure,
  validatePackageName: () => validatePackageName
});

// src/jsTyping/shared.ts
var ActionSet = "action::set";
var ActionInvalidate = "action::invalidate";
var ActionPackageInstalled = "action::packageInstalled";
var EventTypesRegistry = "event::typesRegistry";
var EventBeginInstallTypes = "event::beginInstallTypes";
var EventEndInstallTypes = "event::endInstallTypes";
var EventInitializationFailed = "event::initializationFailed";
var ActionWatchTypingLocations = "action::watchTypingLocations";
var Arguments;
((Arguments2) => {
  Arguments2.GlobalCacheLocation = "--globalTypingsCacheLocation";
  Arguments2.LogFile = "--logFile";
  Arguments2.EnableTelemetry = "--enableTelemetry";
  Arguments2.TypingSafeListLocation = "--typingSafeListLocation";
  Arguments2.TypesMapLocation = "--typesMapLocation";
  Arguments2.NpmLocation = "--npmLocation";
  Arguments2.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
})(Arguments || (Arguments = {}));
function hasArgument(argumentName) {
  return sys.args.includes(argumentName);
}
function findArgument(argumentName) {
  const index = sys.args.indexOf(argumentName);
  return index >= 0 && index < sys.args.length - 1 ? sys.args[index + 1] : void 0;
}
function nowString() {
  const d = /* @__PURE__ */ new Date();
  return `${d.getHours().toString().padStart(2, "0")}:${d.getMinutes().toString().padStart(2, "0")}:${d.getSeconds().toString().padStart(2, "0")}.${d.getMilliseconds().toString().padStart(3, "0")}`;
}
var indentStr = "\n    ";
function indent2(str) {
  return indentStr + str.replace(/\n/g, indentStr);
}
function stringifyIndented(json) {
  return indent2(JSON.stringify(json, void 0, 2));
}

// src/jsTyping/jsTyping.ts
function isTypingUpToDate(cachedTyping, availableTypingVersions) {
  const availableVersion = new Version(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest"));
  return availableVersion.compareTo(cachedTyping.version) <= 0;
}
function nonRelativeModuleNameForTypingCache(moduleName) {
  return nodeCoreModules.has(moduleName) ? "node" : moduleName;
}
function loadSafeList(host, safeListPath) {
  const result = readConfigFile(safeListPath, (path) => host.readFile(path));
  return new Map(Object.entries(result.config));
}
function loadTypesMap(host, typesMapPath) {
  var _a;
  const result = readConfigFile(typesMapPath, (path) => host.readFile(path));
  if ((_a = result.config) == null ? void 0 : _a.simpleMap) {
    return new Map(Object.entries(result.config.simpleMap));
  }
  return void 0;
}
function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry, compilerOptions) {
  if (!typeAcquisition || !typeAcquisition.enable) {
    return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
  }
  const inferredTypings = /* @__PURE__ */ new Map();
  fileNames = mapDefined(fileNames, (fileName) => {
    const path = normalizePath(fileName);
    if (hasJSFileExtension(path)) {
      return path;
    }
  });
  const filesToWatch = [];
  if (typeAcquisition.include) addInferredTypings(typeAcquisition.include, "Explicitly included types");
  const exclude = typeAcquisition.exclude || [];
  if (!compilerOptions.types) {
    const possibleSearchDirs = new Set(fileNames.map(getDirectoryPath));
    possibleSearchDirs.add(projectRootPath);
    possibleSearchDirs.forEach((searchDir) => {
      getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch);
      getTypingNames(searchDir, "package.json", "node_modules", filesToWatch);
    });
  }
  if (!typeAcquisition.disableFilenameBasedTypeAcquisition) {
    getTypingNamesFromSourceFileNames(fileNames);
  }
  if (unresolvedImports) {
    const module2 = deduplicate(
      unresolvedImports.map(nonRelativeModuleNameForTypingCache),
      equateStringsCaseSensitive,
      compareStringsCaseSensitive
    );
    addInferredTypings(module2, "Inferred typings from unresolved imports");
  }
  for (const excludeTypingName of exclude) {
    const didDelete = inferredTypings.delete(excludeTypingName);
    if (didDelete && log) log(`Typing for ${excludeTypingName} is in exclude list, will be ignored.`);
  }
  packageNameToTypingLocation.forEach((typing, name) => {
    const registryEntry = typesRegistry.get(name);
    if (inferredTypings.get(name) === false && registryEntry !== void 0 && isTypingUpToDate(typing, registryEntry)) {
      inferredTypings.set(name, typing.typingLocation);
    }
  });
  const newTypingNames = [];
  const cachedTypingPaths = [];
  inferredTypings.forEach((inferred, typing) => {
    if (inferred) {
      cachedTypingPaths.push(inferred);
    } else {
      newTypingNames.push(typing);
    }
  });
  const result = { cachedTypingPaths, newTypingNames, filesToWatch };
  if (log) log(`Finished typings discovery:${stringifyIndented(result)}`);
  return result;
  function addInferredTyping(typingName) {
    if (!inferredTypings.has(typingName)) {
      inferredTypings.set(typingName, false);
    }
  }
  function addInferredTypings(typingNames, message) {
    if (log) log(`${message}: ${JSON.stringify(typingNames)}`);
    forEach(typingNames, addInferredTyping);
  }
  function getTypingNames(projectRootPath2, manifestName, modulesDirName, filesToWatch2) {
    const manifestPath = combinePaths(projectRootPath2, manifestName);
    let manifest;
    let manifestTypingNames;
    if (host.fileExists(manifestPath)) {
      filesToWatch2.push(manifestPath);
      manifest = readConfigFile(manifestPath, (path) => host.readFile(path)).config;
      manifestTypingNames = flatMap([manifest.dependencies, manifest.devDependencies, manifest.optionalDependencies, manifest.peerDependencies], getOwnKeys);
      addInferredTypings(manifestTypingNames, `Typing names in '${manifestPath}' dependencies`);
    }
    const packagesFolderPath = combinePaths(projectRootPath2, modulesDirName);
    filesToWatch2.push(packagesFolderPath);
    if (!host.directoryExists(packagesFolderPath)) {
      return;
    }
    const packageNames = [];
    const dependencyManifestNames = manifestTypingNames ? manifestTypingNames.map((typingName) => combinePaths(packagesFolderPath, typingName, manifestName)) : host.readDirectory(
      packagesFolderPath,
      [".json" /* Json */],
      /*excludes*/
      void 0,
      /*includes*/
      void 0,
      /*depth*/
      3
    ).filter((manifestPath2) => {
      if (getBaseFileName(manifestPath2) !== manifestName) {
        return false;
      }
      const pathComponents2 = getPathComponents(normalizePath(manifestPath2));
      const isScoped = pathComponents2[pathComponents2.length - 3][0] === "@";
      return isScoped && toFileNameLowerCase(pathComponents2[pathComponents2.length - 4]) === modulesDirName || // `node_modules/@foo/bar`
      !isScoped && toFileNameLowerCase(pathComponents2[pathComponents2.length - 3]) === modulesDirName;
    });
    if (log) log(`Searching for typing names in ${packagesFolderPath}; all files: ${JSON.stringify(dependencyManifestNames)}`);
    for (const manifestPath2 of dependencyManifestNames) {
      const normalizedFileName = normalizePath(manifestPath2);
      const result2 = readConfigFile(normalizedFileName, (path) => host.readFile(path));
      const manifest2 = result2.config;
      if (!manifest2.name) {
        continue;
      }
      const ownTypes = manifest2.types || manifest2.typings;
      if (ownTypes) {
        const absolutePath = getNormalizedAbsolutePath(ownTypes, getDirectoryPath(normalizedFileName));
        if (host.fileExists(absolutePath)) {
          if (log) log(`    Package '${manifest2.name}' provides its own types.`);
          inferredTypings.set(manifest2.name, absolutePath);
        } else {
          if (log) log(`    Package '${manifest2.name}' provides its own types but they are missing.`);
        }
      } else {
        packageNames.push(manifest2.name);
      }
    }
    addInferredTypings(packageNames, "    Found package names");
  }
  function getTypingNamesFromSourceFileNames(fileNames2) {
    const fromFileNames = mapDefined(fileNames2, (j) => {
      if (!hasJSFileExtension(j)) return void 0;
      const inferredTypingName = removeFileExtension(toFileNameLowerCase(getBaseFileName(j)));
      const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName);
      return safeList.get(cleanedTypingName);
    });
    if (fromFileNames.length) {
      addInferredTypings(fromFileNames, "Inferred typings from file names");
    }
    const hasJsxFile = some(fileNames2, (f) => fileExtensionIs(f, ".jsx" /* Jsx */));
    if (hasJsxFile) {
      if (log) log(`Inferred 'react' typings due to presence of '.jsx' extension`);
      addInferredTyping("react");
    }
  }
}
var NameValidationResult = /* @__PURE__ */ ((NameValidationResult2) => {
  NameValidationResult2[NameValidationResult2["Ok"] = 0] = "Ok";
  NameValidationResult2[NameValidationResult2["EmptyName"] = 1] = "EmptyName";
  NameValidationResult2[NameValidationResult2["NameTooLong"] = 2] = "NameTooLong";
  NameValidationResult2[NameValidationResult2["NameStartsWithDot"] = 3] = "NameStartsWithDot";
  NameValidationResult2[NameValidationResult2["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
  NameValidationResult2[NameValidationResult2["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
  return NameValidationResult2;
})(NameValidationResult || {});
var maxPackageNameLength = 214;
function validatePackageName(packageName) {
  return validatePackageNameWorker(
    packageName,
    /*supportScopedPackage*/
    true
  );
}
function validatePackageNameWorker(packageName, supportScopedPackage) {
  if (!packageName) {
    return 1 /* EmptyName */;
  }
  if (packageName.length > maxPackageNameLength) {
    return 2 /* NameTooLong */;
  }
  if (packageName.charCodeAt(0) === 46 /* dot */) {
    return 3 /* NameStartsWithDot */;
  }
  if (packageName.charCodeAt(0) === 95 /* _ */) {
    return 4 /* NameStartsWithUnderscore */;
  }
  if (supportScopedPackage) {
    const matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
    if (matches) {
      const scopeResult = validatePackageNameWorker(
        matches[1],
        /*supportScopedPackage*/
        false
      );
      if (scopeResult !== 0 /* Ok */) {
        return { name: matches[1], isScopeName: true, result: scopeResult };
      }
      const packageResult = validatePackageNameWorker(
        matches[2],
        /*supportScopedPackage*/
        false
      );
      if (packageResult !== 0 /* Ok */) {
        return { name: matches[2], isScopeName: false, result: packageResult };
      }
      return 0 /* Ok */;
    }
  }
  if (encodeURIComponent(packageName) !== packageName) {
    return 5 /* NameContainsNonURISafeCharacters */;
  }
  return 0 /* Ok */;
}
function renderPackageNameValidationFailure(result, typing) {
  return typeof result === "object" ? renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) : renderPackageNameValidationFailureWorker(
    typing,
    result,
    typing,
    /*isScopeName*/
    false
  );
}
function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
  const kind = isScopeName ? "Scope" : "Package";
  switch (result) {
    case 1 /* EmptyName */:
      return `'${typing}':: ${kind} name '${name}' cannot be empty`;
    case 2 /* NameTooLong */:
      return `'${typing}':: ${kind} name '${name}' should be less than ${maxPackageNameLength} characters`;
    case 3 /* NameStartsWithDot */:
      return `'${typing}':: ${kind} name '${name}' cannot start with '.'`;
    case 4 /* NameStartsWithUnderscore */:
      return `'${typing}':: ${kind} name '${name}' cannot start with '_'`;
    case 5 /* NameContainsNonURISafeCharacters */:
      return `'${typing}':: ${kind} name '${name}' contains non URI safe characters`;
    case 0 /* Ok */:
      return Debug.fail();
    // Shouldn't have called this.
    default:
      Debug.assertNever(result);
  }
}

// src/services/types.ts
var ScriptSnapshot;
((ScriptSnapshot2) => {
  class StringScriptSnapshot {
    constructor(text) {
      this.text = text;
    }
    getText(start, end) {
      return start === 0 && end === this.text.length ? this.text : this.text.substring(start, end);
    }
    getLength() {
      return this.text.length;
    }
    getChangeRange() {
      return void 0;
    }
  }
  function fromString(text) {
    return new StringScriptSnapshot(text);
  }
  ScriptSnapshot2.fromString = fromString;
})(ScriptSnapshot || (ScriptSnapshot = {}));
var PackageJsonDependencyGroup = /* @__PURE__ */ ((PackageJsonDependencyGroup2) => {
  PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["Dependencies"] = 1] = "Dependencies";
  PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["DevDependencies"] = 2] = "DevDependencies";
  PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["PeerDependencies"] = 4] = "PeerDependencies";
  PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["OptionalDependencies"] = 8] = "OptionalDependencies";
  PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["All"] = 15] = "All";
  return PackageJsonDependencyGroup2;
})(PackageJsonDependencyGroup || {});
var PackageJsonAutoImportPreference = /* @__PURE__ */ ((PackageJsonAutoImportPreference2) => {
  PackageJsonAutoImportPreference2[PackageJsonAutoImportPreference2["Off"] = 0] = "Off";
  PackageJsonAutoImportPreference2[PackageJsonAutoImportPreference2["On"] = 1] = "On";
  PackageJsonAutoImportPreference2[PackageJsonAutoImportPreference2["Auto"] = 2] = "Auto";
  return PackageJsonAutoImportPreference2;
})(PackageJsonAutoImportPreference || {});
var LanguageServiceMode = /* @__PURE__ */ ((LanguageServiceMode2) => {
  LanguageServiceMode2[LanguageServiceMode2["Semantic"] = 0] = "Semantic";
  LanguageServiceMode2[LanguageServiceMode2["PartialSemantic"] = 1] = "PartialSemantic";
  LanguageServiceMode2[LanguageServiceMode2["Syntactic"] = 2] = "Syntactic";
  return LanguageServiceMode2;
})(LanguageServiceMode || {});
var emptyOptions = {};
var SemanticClassificationFormat = /* @__PURE__ */ ((SemanticClassificationFormat2) => {
  SemanticClassificationFormat2["Original"] = "original";
  SemanticClassificationFormat2["TwentyTwenty"] = "2020";
  return SemanticClassificationFormat2;
})(SemanticClassificationFormat || {});
var OrganizeImportsMode = /* @__PURE__ */ ((OrganizeImportsMode2) => {
  OrganizeImportsMode2["All"] = "All";
  OrganizeImportsMode2["SortAndCombine"] = "SortAndCombine";
  OrganizeImportsMode2["RemoveUnused"] = "RemoveUnused";
  return OrganizeImportsMode2;
})(OrganizeImportsMode || {});
var CompletionTriggerKind = /* @__PURE__ */ ((CompletionTriggerKind2) => {
  CompletionTriggerKind2[CompletionTriggerKind2["Invoked"] = 1] = "Invoked";
  CompletionTriggerKind2[CompletionTriggerKind2["TriggerCharacter"] = 2] = "TriggerCharacter";
  CompletionTriggerKind2[CompletionTriggerKind2["TriggerForIncompleteCompletions"] = 3] = "TriggerForIncompleteCompletions";
  return CompletionTriggerKind2;
})(CompletionTriggerKind || {});
var InlayHintKind2 = /* @__PURE__ */ ((InlayHintKind3) => {
  InlayHintKind3["Type"] = "Type";
  InlayHintKind3["Parameter"] = "Parameter";
  InlayHintKind3["Enum"] = "Enum";
  return InlayHintKind3;
})(InlayHintKind2 || {});
var HighlightSpanKind = /* @__PURE__ */ ((HighlightSpanKind2) => {
  HighlightSpanKind2["none"] = "none";
  HighlightSpanKind2["definition"] = "definition";
  HighlightSpanKind2["reference"] = "reference";
  HighlightSpanKind2["writtenReference"] = "writtenReference";
  return HighlightSpanKind2;
})(HighlightSpanKind || {});
var IndentStyle = /* @__PURE__ */ ((IndentStyle3) => {
  IndentStyle3[IndentStyle3["None"] = 0] = "None";
  IndentStyle3[IndentStyle3["Block"] = 1] = "Block";
  IndentStyle3[IndentStyle3["Smart"] = 2] = "Smart";
  return IndentStyle3;
})(IndentStyle || {});
var SemicolonPreference = /* @__PURE__ */ ((SemicolonPreference2) => {
  SemicolonPreference2["Ignore"] = "ignore";
  SemicolonPreference2["Insert"] = "insert";
  SemicolonPreference2["Remove"] = "remove";
  return SemicolonPreference2;
})(SemicolonPreference || {});
function getDefaultFormatCodeSettings(newLineCharacter) {
  return {
    indentSize: 4,
    tabSize: 4,
    newLineCharacter: newLineCharacter || "\n",
    convertTabsToSpaces: true,
    indentStyle: 2 /* Smart */,
    insertSpaceAfterConstructor: false,
    insertSpaceAfterCommaDelimiter: true,
    insertSpaceAfterSemicolonInForStatements: true,
    insertSpaceBeforeAndAfterBinaryOperators: true,
    insertSpaceAfterKeywordsInControlFlowStatements: true,
    insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
    insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
    insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
    insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
    insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
    insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
    insertSpaceBeforeFunctionParenthesis: false,
    placeOpenBraceOnNewLineForFunctions: false,
    placeOpenBraceOnNewLineForControlBlocks: false,
    semicolons: "ignore" /* Ignore */,
    trimTrailingWhitespace: true,
    indentSwitchCase: true
  };
}
var testFormatSettings = getDefaultFormatCodeSettings("\n");
var SymbolDisplayPartKind = /* @__PURE__ */ ((SymbolDisplayPartKind2) => {
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["aliasName"] = 0] = "aliasName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["className"] = 1] = "className";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["enumName"] = 2] = "enumName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["fieldName"] = 3] = "fieldName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["interfaceName"] = 4] = "interfaceName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["keyword"] = 5] = "keyword";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["lineBreak"] = 6] = "lineBreak";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["numericLiteral"] = 7] = "numericLiteral";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["stringLiteral"] = 8] = "stringLiteral";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["localName"] = 9] = "localName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["methodName"] = 10] = "methodName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["moduleName"] = 11] = "moduleName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["operator"] = 12] = "operator";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["parameterName"] = 13] = "parameterName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["propertyName"] = 14] = "propertyName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["punctuation"] = 15] = "punctuation";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["space"] = 16] = "space";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["text"] = 17] = "text";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["typeParameterName"] = 18] = "typeParameterName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["enumMemberName"] = 19] = "enumMemberName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["functionName"] = 20] = "functionName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["regularExpressionLiteral"] = 21] = "regularExpressionLiteral";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["link"] = 22] = "link";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["linkName"] = 23] = "linkName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["linkText"] = 24] = "linkText";
  return SymbolDisplayPartKind2;
})(SymbolDisplayPartKind || {});
var CompletionInfoFlags = /* @__PURE__ */ ((CompletionInfoFlags2) => {
  CompletionInfoFlags2[CompletionInfoFlags2["None"] = 0] = "None";
  CompletionInfoFlags2[CompletionInfoFlags2["MayIncludeAutoImports"] = 1] = "MayIncludeAutoImports";
  CompletionInfoFlags2[CompletionInfoFlags2["IsImportStatementCompletion"] = 2] = "IsImportStatementCompletion";
  CompletionInfoFlags2[CompletionInfoFlags2["IsContinuation"] = 4] = "IsContinuation";
  CompletionInfoFlags2[CompletionInfoFlags2["ResolvedModuleSpecifiers"] = 8] = "ResolvedModuleSpecifiers";
  CompletionInfoFlags2[CompletionInfoFlags2["ResolvedModuleSpecifiersBeyondLimit"] = 16] = "ResolvedModuleSpecifiersBeyondLimit";
  CompletionInfoFlags2[CompletionInfoFlags2["MayIncludeMethodSnippets"] = 32] = "MayIncludeMethodSnippets";
  return CompletionInfoFlags2;
})(CompletionInfoFlags || {});
var OutliningSpanKind = /* @__PURE__ */ ((OutliningSpanKind2) => {
  OutliningSpanKind2["Comment"] = "comment";
  OutliningSpanKind2["Region"] = "region";
  OutliningSpanKind2["Code"] = "code";
  OutliningSpanKind2["Imports"] = "imports";
  return OutliningSpanKind2;
})(OutliningSpanKind || {});
var OutputFileType = /* @__PURE__ */ ((OutputFileType2) => {
  OutputFileType2[OutputFileType2["JavaScript"] = 0] = "JavaScript";
  OutputFileType2[OutputFileType2["SourceMap"] = 1] = "SourceMap";
  OutputFileType2[OutputFileType2["Declaration"] = 2] = "Declaration";
  return OutputFileType2;
})(OutputFileType || {});
var EndOfLineState = /* @__PURE__ */ ((EndOfLineState2) => {
  EndOfLineState2[EndOfLineState2["None"] = 0] = "None";
  EndOfLineState2[EndOfLineState2["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia";
  EndOfLineState2[EndOfLineState2["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral";
  EndOfLineState2[EndOfLineState2["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral";
  EndOfLineState2[EndOfLineState2["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate";
  EndOfLineState2[EndOfLineState2["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail";
  EndOfLineState2[EndOfLineState2["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition";
  return EndOfLineState2;
})(EndOfLineState || {});
var TokenClass = /* @__PURE__ */ ((TokenClass2) => {
  TokenClass2[TokenClass2["Punctuation"] = 0] = "Punctuation";
  TokenClass2[TokenClass2["Keyword"] = 1] = "Keyword";
  TokenClass2[TokenClass2["Operator"] = 2] = "Operator";
  TokenClass2[TokenClass2["Comment"] = 3] = "Comment";
  TokenClass2[TokenClass2["Whitespace"] = 4] = "Whitespace";
  TokenClass2[TokenClass2["Identifier"] = 5] = "Identifier";
  TokenClass2[TokenClass2["NumberLiteral"] = 6] = "NumberLiteral";
  TokenClass2[TokenClass2["BigIntLiteral"] = 7] = "BigIntLiteral";
  TokenClass2[TokenClass2["StringLiteral"] = 8] = "StringLiteral";
  TokenClass2[TokenClass2["RegExpLiteral"] = 9] = "RegExpLiteral";
  return TokenClass2;
})(TokenClass || {});
var ScriptElementKind = /* @__PURE__ */ ((ScriptElementKind2) => {
  ScriptElementKind2["unknown"] = "";
  ScriptElementKind2["warning"] = "warning";
  ScriptElementKind2["keyword"] = "keyword";
  ScriptElementKind2["scriptElement"] = "script";
  ScriptElementKind2["moduleElement"] = "module";
  ScriptElementKind2["classElement"] = "class";
  ScriptElementKind2["localClassElement"] = "local class";
  ScriptElementKind2["interfaceElement"] = "interface";
  ScriptElementKind2["typeElement"] = "type";
  ScriptElementKind2["enumElement"] = "enum";
  ScriptElementKind2["enumMemberElement"] = "enum member";
  ScriptElementKind2["variableElement"] = "var";
  ScriptElementKind2["localVariableElement"] = "local var";
  ScriptElementKind2["variableUsingElement"] = "using";
  ScriptElementKind2["variableAwaitUsingElement"] = "await using";
  ScriptElementKind2["functionElement"] = "function";
  ScriptElementKind2["localFunctionElement"] = "local function";
  ScriptElementKind2["memberFunctionElement"] = "method";
  ScriptElementKind2["memberGetAccessorElement"] = "getter";
  ScriptElementKind2["memberSetAccessorElement"] = "setter";
  ScriptElementKind2["memberVariableElement"] = "property";
  ScriptElementKind2["memberAccessorVariableElement"] = "accessor";
  ScriptElementKind2["constructorImplementationElement"] = "constructor";
  ScriptElementKind2["callSignatureElement"] = "call";
  ScriptElementKind2["indexSignatureElement"] = "index";
  ScriptElementKind2["constructSignatureElement"] = "construct";
  ScriptElementKind2["parameterElement"] = "parameter";
  ScriptElementKind2["typeParameterElement"] = "type parameter";
  ScriptElementKind2["primitiveType"] = "primitive type";
  ScriptElementKind2["label"] = "label";
  ScriptElementKind2["alias"] = "alias";
  ScriptElementKind2["constElement"] = "const";
  ScriptElementKind2["letElement"] = "let";
  ScriptElementKind2["directory"] = "directory";
  ScriptElementKind2["externalModuleName"] = "external module name";
  ScriptElementKind2["jsxAttribute"] = "JSX attribute";
  ScriptElementKind2["string"] = "string";
  ScriptElementKind2["link"] = "link";
  ScriptElementKind2["linkName"] = "link name";
  ScriptElementKind2["linkText"] = "link text";
  return ScriptElementKind2;
})(ScriptElementKind || {});
var ScriptElementKindModifier = /* @__PURE__ */ ((ScriptElementKindModifier2) => {
  ScriptElementKindModifier2["none"] = "";
  ScriptElementKindModifier2["publicMemberModifier"] = "public";
  ScriptElementKindModifier2["privateMemberModifier"] = "private";
  ScriptElementKindModifier2["protectedMemberModifier"] = "protected";
  ScriptElementKindModifier2["exportedModifier"] = "export";
  ScriptElementKindModifier2["ambientModifier"] = "declare";
  ScriptElementKindModifier2["staticModifier"] = "static";
  ScriptElementKindModifier2["abstractModifier"] = "abstract";
  ScriptElementKindModifier2["optionalModifier"] = "optional";
  ScriptElementKindModifier2["deprecatedModifier"] = "deprecated";
  ScriptElementKindModifier2["dtsModifier"] = ".d.ts";
  ScriptElementKindModifier2["tsModifier"] = ".ts";
  ScriptElementKindModifier2["tsxModifier"] = ".tsx";
  ScriptElementKindModifier2["jsModifier"] = ".js";
  ScriptElementKindModifier2["jsxModifier"] = ".jsx";
  ScriptElementKindModifier2["jsonModifier"] = ".json";
  ScriptElementKindModifier2["dmtsModifier"] = ".d.mts";
  ScriptElementKindModifier2["mtsModifier"] = ".mts";
  ScriptElementKindModifier2["mjsModifier"] = ".mjs";
  ScriptElementKindModifier2["dctsModifier"] = ".d.cts";
  ScriptElementKindModifier2["ctsModifier"] = ".cts";
  ScriptElementKindModifier2["cjsModifier"] = ".cjs";
  return ScriptElementKindModifier2;
})(ScriptElementKindModifier || {});
var ClassificationTypeNames = /* @__PURE__ */ ((ClassificationTypeNames2) => {
  ClassificationTypeNames2["comment"] = "comment";
  ClassificationTypeNames2["identifier"] = "identifier";
  ClassificationTypeNames2["keyword"] = "keyword";
  ClassificationTypeNames2["numericLiteral"] = "number";
  ClassificationTypeNames2["bigintLiteral"] = "bigint";
  ClassificationTypeNames2["operator"] = "operator";
  ClassificationTypeNames2["stringLiteral"] = "string";
  ClassificationTypeNames2["whiteSpace"] = "whitespace";
  ClassificationTypeNames2["text"] = "text";
  ClassificationTypeNames2["punctuation"] = "punctuation";
  ClassificationTypeNames2["className"] = "class name";
  ClassificationTypeNames2["enumName"] = "enum name";
  ClassificationTypeNames2["interfaceName"] = "interface name";
  ClassificationTypeNames2["moduleName"] = "module name";
  ClassificationTypeNames2["typeParameterName"] = "type parameter name";
  ClassificationTypeNames2["typeAliasName"] = "type alias name";
  ClassificationTypeNames2["parameterName"] = "parameter name";
  ClassificationTypeNames2["docCommentTagName"] = "doc comment tag name";
  ClassificationTypeNames2["jsxOpenTagName"] = "jsx open tag name";
  ClassificationTypeNames2["jsxCloseTagName"] = "jsx close tag name";
  ClassificationTypeNames2["jsxSelfClosingTagName"] = "jsx self closing tag name";
  ClassificationTypeNames2["jsxAttribute"] = "jsx attribute";
  ClassificationTypeNames2["jsxText"] = "jsx text";
  ClassificationTypeNames2["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value";
  return ClassificationTypeNames2;
})(ClassificationTypeNames || {});
var ClassificationType = /* @__PURE__ */ ((ClassificationType2) => {
  ClassificationType2[ClassificationType2["comment"] = 1] = "comment";
  ClassificationType2[ClassificationType2["identifier"] = 2] = "identifier";
  ClassificationType2[ClassificationType2["keyword"] = 3] = "keyword";
  ClassificationType2[ClassificationType2["numericLiteral"] = 4] = "numericLiteral";
  ClassificationType2[ClassificationType2["operator"] = 5] = "operator";
  ClassificationType2[ClassificationType2["stringLiteral"] = 6] = "stringLiteral";
  ClassificationType2[ClassificationType2["regularExpressionLiteral"] = 7] = "regularExpressionLiteral";
  ClassificationType2[ClassificationType2["whiteSpace"] = 8] = "whiteSpace";
  ClassificationType2[ClassificationType2["text"] = 9] = "text";
  ClassificationType2[ClassificationType2["punctuation"] = 10] = "punctuation";
  ClassificationType2[ClassificationType2["className"] = 11] = "className";
  ClassificationType2[ClassificationType2["enumName"] = 12] = "enumName";
  ClassificationType2[ClassificationType2["interfaceName"] = 13] = "interfaceName";
  ClassificationType2[ClassificationType2["moduleName"] = 14] = "moduleName";
  ClassificationType2[ClassificationType2["typeParameterName"] = 15] = "typeParameterName";
  ClassificationType2[ClassificationType2["typeAliasName"] = 16] = "typeAliasName";
  ClassificationType2[ClassificationType2["parameterName"] = 17] = "parameterName";
  ClassificationType2[ClassificationType2["docCommentTagName"] = 18] = "docCommentTagName";
  ClassificationType2[ClassificationType2["jsxOpenTagName"] = 19] = "jsxOpenTagName";
  ClassificationType2[ClassificationType2["jsxCloseTagName"] = 20] = "jsxCloseTagName";
  ClassificationType2[ClassificationType2["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName";
  ClassificationType2[ClassificationType2["jsxAttribute"] = 22] = "jsxAttribute";
  ClassificationType2[ClassificationType2["jsxText"] = 23] = "jsxText";
  ClassificationType2[ClassificationType2["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue";
  ClassificationType2[ClassificationType2["bigintLiteral"] = 25] = "bigintLiteral";
  return ClassificationType2;
})(ClassificationType || {});

// src/services/utilities.ts
var scanner = createScanner(
  99 /* Latest */,
  /*skipTrivia*/
  true
);
var SemanticMeaning = /* @__PURE__ */ ((SemanticMeaning2) => {
  SemanticMeaning2[SemanticMeaning2["None"] = 0] = "None";
  SemanticMeaning2[SemanticMeaning2["Value"] = 1] = "Value";
  SemanticMeaning2[SemanticMeaning2["Type"] = 2] = "Type";
  SemanticMeaning2[SemanticMeaning2["Namespace"] = 4] = "Namespace";
  SemanticMeaning2[SemanticMeaning2["All"] = 7] = "All";
  return SemanticMeaning2;
})(SemanticMeaning || {});
function getMeaningFromDeclaration(node) {
  switch (node.kind) {
    case 260 /* VariableDeclaration */:
      return isInJSFile(node) && getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */;
    case 169 /* Parameter */:
    case 208 /* BindingElement */:
    case 172 /* PropertyDeclaration */:
    case 171 /* PropertySignature */:
    case 303 /* PropertyAssignment */:
    case 304 /* ShorthandPropertyAssignment */:
    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 299 /* CatchClause */:
    case 291 /* JsxAttribute */:
      return 1 /* Value */;
    case 168 /* TypeParameter */:
    case 264 /* InterfaceDeclaration */:
    case 265 /* TypeAliasDeclaration */:
    case 187 /* TypeLiteral */:
      return 2 /* Type */;
    case 346 /* JSDocTypedefTag */:
      return node.name === void 0 ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
    case 306 /* EnumMember */:
    case 263 /* ClassDeclaration */:
      return 1 /* Value */ | 2 /* Type */;
    case 267 /* ModuleDeclaration */:
      if (isAmbientModule(node)) {
        return 4 /* Namespace */ | 1 /* Value */;
      } else if (getModuleInstanceState(node) === 1 /* Instantiated */) {
        return 4 /* Namespace */ | 1 /* Value */;
      } else {
        return 4 /* Namespace */;
      }
    case 266 /* EnumDeclaration */:
    case 275 /* NamedImports */:
    case 276 /* ImportSpecifier */:
    case 271 /* ImportEqualsDeclaration */:
    case 272 /* ImportDeclaration */:
    case 277 /* ExportAssignment */:
    case 278 /* ExportDeclaration */:
      return 7 /* All */;
    // An external module can be a Value
    case 307 /* SourceFile */:
      return 4 /* Namespace */ | 1 /* Value */;
  }
  return 7 /* All */;
}
function getMeaningFromLocation(node) {
  node = getAdjustedReferenceLocation(node);
  const parent2 = node.parent;
  if (node.kind === 307 /* SourceFile */) {
    return 1 /* Value */;
  } else if (isExportAssignment(parent2) || isExportSpecifier(parent2) || isExternalModuleReference(parent2) || isImportSpecifier(parent2) || isImportClause(parent2) || isImportEqualsDeclaration(parent2) && node === parent2.name) {
    return 7 /* All */;
  } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) {
    return getMeaningFromRightHandSideOfImportEquals(node);
  } else if (isDeclarationName(node)) {
    return getMeaningFromDeclaration(parent2);
  } else if (isEntityName(node) && findAncestor(node, or(isJSDocNameReference, isJSDocLinkLike, isJSDocMemberName))) {
    return 7 /* All */;
  } else if (isTypeReference(node)) {
    return 2 /* Type */;
  } else if (isNamespaceReference(node)) {
    return 4 /* Namespace */;
  } else if (isTypeParameterDeclaration(parent2)) {
    Debug.assert(isJSDocTemplateTag(parent2.parent));
    return 2 /* Type */;
  } else if (isLiteralTypeNode(parent2)) {
    return 2 /* Type */ | 1 /* Value */;
  } else {
    return 1 /* Value */;
  }
}
function getMeaningFromRightHandSideOfImportEquals(node) {
  const name = node.kind === 166 /* QualifiedName */ ? node : isQualifiedName(node.parent) && node.parent.right === node ? node.parent : void 0;
  return name && name.parent.kind === 271 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */;
}
function isInRightSideOfInternalImportEqualsDeclaration(node) {
  while (node.parent.kind === 166 /* QualifiedName */) {
    node = node.parent;
  }
  return isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node;
}
function isNamespaceReference(node) {
  return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node);
}
function isQualifiedNameNamespaceReference(node) {
  let root = node;
  let isLastClause = true;
  if (root.parent.kind === 166 /* QualifiedName */) {
    while (root.parent && root.parent.kind === 166 /* QualifiedName */) {
      root = root.parent;
    }
    isLastClause = root.right === node;
  }
  return root.parent.kind === 183 /* TypeReference */ && !isLastClause;
}
function isPropertyAccessNamespaceReference(node) {
  let root = node;
  let isLastClause = true;
  if (root.parent.kind === 211 /* PropertyAccessExpression */) {
    while (root.parent && root.parent.kind === 211 /* PropertyAccessExpression */) {
      root = root.parent;
    }
    isLastClause = root.name === node;
  }
  if (!isLastClause && root.parent.kind === 233 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 298 /* HeritageClause */) {
    const decl = root.parent.parent.parent;
    return decl.kind === 263 /* ClassDeclaration */ && root.parent.parent.token === 119 /* ImplementsKeyword */ || decl.kind === 264 /* InterfaceDeclaration */ && root.parent.parent.token === 96 /* ExtendsKeyword */;
  }
  return false;
}
function isTypeReference(node) {
  if (isRightSideOfQualifiedNameOrPropertyAccess(node)) {
    node = node.parent;
  }
  switch (node.kind) {
    case 110 /* ThisKeyword */:
      return !isExpressionNode(node);
    case 197 /* ThisType */:
      return true;
  }
  switch (node.parent.kind) {
    case 183 /* TypeReference */:
      return true;
    case 205 /* ImportType */:
      return !node.parent.isTypeOf;
    case 233 /* ExpressionWithTypeArguments */:
      return isPartOfTypeNode(node.parent);
  }
  return false;
}
function isCallExpressionTarget(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isCallExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
function isNewExpressionTarget(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
function isCallOrNewExpressionTarget(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isCallOrNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
function isTaggedTemplateTag(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isTaggedTemplateExpression, selectTagOfTaggedTemplateExpression, includeElementAccess, skipPastOuterExpressions);
}
function isDecoratorTarget(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isDecorator, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
function isJsxOpeningLikeElementTagName(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isJsxOpeningLikeElement, selectTagNameOfJsxOpeningLikeElement, includeElementAccess, skipPastOuterExpressions);
}
function selectExpressionOfCallOrNewExpressionOrDecorator(node) {
  return node.expression;
}
function selectTagOfTaggedTemplateExpression(node) {
  return node.tag;
}
function selectTagNameOfJsxOpeningLikeElement(node) {
  return node.tagName;
}
function isCalleeWorker(node, pred, calleeSelector, includeElementAccess, skipPastOuterExpressions) {
  let target = includeElementAccess ? climbPastPropertyOrElementAccess(node) : climbPastPropertyAccess(node);
  if (skipPastOuterExpressions) {
    target = skipOuterExpressions(target);
  }
  return !!target && !!target.parent && pred(target.parent) && calleeSelector(target.parent) === target;
}
function climbPastPropertyAccess(node) {
  return isRightSideOfPropertyAccess(node) ? node.parent : node;
}
function climbPastPropertyOrElementAccess(node) {
  return isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node) ? node.parent : node;
}
function getTargetLabel(referenceNode, labelName) {
  while (referenceNode) {
    if (referenceNode.kind === 256 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) {
      return referenceNode.label;
    }
    referenceNode = referenceNode.parent;
  }
  return void 0;
}
function hasPropertyAccessExpressionWithName(node, funcName) {
  if (!isPropertyAccessExpression(node.expression)) {
    return false;
  }
  return node.expression.name.text === funcName;
}
function isJumpStatementTarget(node) {
  var _a;
  return isIdentifier(node) && ((_a = tryCast(node.parent, isBreakOrContinueStatement)) == null ? void 0 : _a.label) === node;
}
function isLabelOfLabeledStatement(node) {
  var _a;
  return isIdentifier(node) && ((_a = tryCast(node.parent, isLabeledStatement)) == null ? void 0 : _a.label) === node;
}
function isLabelName(node) {
  return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}
function isTagName(node) {
  var _a;
  return ((_a = tryCast(node.parent, isJSDocTag)) == null ? void 0 : _a.tagName) === node;
}
function isRightSideOfQualifiedName(node) {
  var _a;
  return ((_a = tryCast(node.parent, isQualifiedName)) == null ? void 0 : _a.right) === node;
}
function isRightSideOfPropertyAccess(node) {
  var _a;
  return ((_a = tryCast(node.parent, isPropertyAccessExpression)) == null ? void 0 : _a.name) === node;
}
function isArgumentExpressionOfElementAccess(node) {
  var _a;
  return ((_a = tryCast(node.parent, isElementAccessExpression)) == null ? void 0 : _a.argumentExpression) === node;
}
function isNameOfModuleDeclaration(node) {
  var _a;
  return ((_a = tryCast(node.parent, isModuleDeclaration)) == null ? void 0 : _a.name) === node;
}
function isNameOfFunctionDeclaration(node) {
  var _a;
  return isIdentifier(node) && ((_a = tryCast(node.parent, isFunctionLike)) == null ? void 0 : _a.name) === node;
}
function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) {
  switch (node.parent.kind) {
    case 172 /* PropertyDeclaration */:
    case 171 /* PropertySignature */:
    case 303 /* PropertyAssignment */:
    case 306 /* EnumMember */:
    case 174 /* MethodDeclaration */:
    case 173 /* MethodSignature */:
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
    case 267 /* ModuleDeclaration */:
      return getNameOfDeclaration(node.parent) === node;
    case 212 /* ElementAccessExpression */:
      return node.parent.argumentExpression === node;
    case 167 /* ComputedPropertyName */:
      return true;
    case 201 /* LiteralType */:
      return node.parent.parent.kind === 199 /* IndexedAccessType */;
    default:
      return false;
  }
}
function isExpressionOfExternalModuleImportEqualsDeclaration(node) {
  return isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node;
}
function getContainerNode(node) {
  if (isJSDocTypeAlias(node)) {
    node = node.parent.parent;
  }
  while (true) {
    node = node.parent;
    if (!node) {
      return void 0;
    }
    switch (node.kind) {
      case 307 /* SourceFile */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 263 /* ClassDeclaration */:
      case 264 /* InterfaceDeclaration */:
      case 266 /* EnumDeclaration */:
      case 267 /* ModuleDeclaration */:
        return node;
    }
  }
}
function getNodeKind(node) {
  switch (node.kind) {
    case 307 /* SourceFile */:
      return isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
    case 267 /* ModuleDeclaration */:
      return "module" /* moduleElement */;
    case 263 /* ClassDeclaration */:
    case 231 /* ClassExpression */:
      return "class" /* classElement */;
    case 264 /* InterfaceDeclaration */:
      return "interface" /* interfaceElement */;
    case 265 /* TypeAliasDeclaration */:
    case 338 /* JSDocCallbackTag */:
    case 346 /* JSDocTypedefTag */:
      return "type" /* typeElement */;
    case 266 /* EnumDeclaration */:
      return "enum" /* enumElement */;
    case 260 /* VariableDeclaration */:
      return getKindOfVariableDeclaration(node);
    case 208 /* BindingElement */:
      return getKindOfVariableDeclaration(getRootDeclaration(node));
    case 219 /* ArrowFunction */:
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
      return "function" /* functionElement */;
    case 177 /* GetAccessor */:
      return "getter" /* memberGetAccessorElement */;
    case 178 /* SetAccessor */:
      return "setter" /* memberSetAccessorElement */;
    case 174 /* MethodDeclaration */:
    case 173 /* MethodSignature */:
      return "method" /* memberFunctionElement */;
    case 303 /* PropertyAssignment */:
      const { initializer } = node;
      return isFunctionLike(initializer) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
    case 172 /* PropertyDeclaration */:
    case 171 /* PropertySignature */:
    case 304 /* ShorthandPropertyAssignment */:
    case 305 /* SpreadAssignment */:
      return "property" /* memberVariableElement */;
    case 181 /* IndexSignature */:
      return "index" /* indexSignatureElement */;
    case 180 /* ConstructSignature */:
      return "construct" /* constructSignatureElement */;
    case 179 /* CallSignature */:
      return "call" /* callSignatureElement */;
    case 176 /* Constructor */:
    case 175 /* ClassStaticBlockDeclaration */:
      return "constructor" /* constructorImplementationElement */;
    case 168 /* TypeParameter */:
      return "type parameter" /* typeParameterElement */;
    case 306 /* EnumMember */:
      return "enum member" /* enumMemberElement */;
    case 169 /* Parameter */:
      return hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */;
    case 271 /* ImportEqualsDeclaration */:
    case 276 /* ImportSpecifier */:
    case 281 /* ExportSpecifier */:
    case 274 /* NamespaceImport */:
    case 280 /* NamespaceExport */:
      return "alias" /* alias */;
    case 226 /* BinaryExpression */:
      const kind = getAssignmentDeclarationKind(node);
      const { right } = node;
      switch (kind) {
        case 7 /* ObjectDefinePropertyValue */:
        case 8 /* ObjectDefinePropertyExports */:
        case 9 /* ObjectDefinePrototypeProperty */:
        case 0 /* None */:
          return "" /* unknown */;
        case 1 /* ExportsProperty */:
        case 2 /* ModuleExports */:
          const rightKind = getNodeKind(right);
          return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind;
        case 3 /* PrototypeProperty */:
          return isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
        case 4 /* ThisProperty */:
          return "property" /* memberVariableElement */;
        // property
        case 5 /* Property */:
          return isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
        case 6 /* Prototype */:
          return "local class" /* localClassElement */;
        default: {
          assertType(kind);
          return "" /* unknown */;
        }
      }
    case 80 /* Identifier */:
      return isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */;
    case 277 /* ExportAssignment */:
      const scriptKind = getNodeKind(node.expression);
      return scriptKind === "" /* unknown */ ? "const" /* constElement */ : scriptKind;
    default:
      return "" /* unknown */;
  }
  function getKindOfVariableDeclaration(v) {
    return isVarConst(v) ? "const" /* constElement */ : isLet(v) ? "let" /* letElement */ : "var" /* variableElement */;
  }
}
function isThis(node) {
  switch (node.kind) {
    case 110 /* ThisKeyword */:
      return true;
    case 80 /* Identifier */:
      return identifierIsThisKeyword(node) && node.parent.kind === 169 /* Parameter */;
    default:
      return false;
  }
}
var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</;
function getLineStartPositionForPosition(position, sourceFile) {
  const lineStarts = getLineStarts(sourceFile);
  const line = sourceFile.getLineAndCharacterOfPosition(position).line;
  return lineStarts[line];
}
function rangeContainsRangeExclusive(r1, r2) {
  return rangeContainsPositionExclusive(r1, r2.pos) && rangeContainsPositionExclusive(r1, r2.end);
}
function rangeContainsPosition(r, pos) {
  return r.pos <= pos && pos <= r.end;
}
function rangeContainsPositionExclusive(r, pos) {
  return r.pos < pos && pos < r.end;
}
function rangeContainsStartEnd(range, start, end) {
  return range.pos <= start && range.end >= end;
}
function rangeOverlapsWithStartEnd(r1, start, end) {
  return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end);
}
function nodeOverlapsWithStartEnd(node, sourceFile, start, end) {
  return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end);
}
function startEndOverlapsWithStartEnd(start1, end1, start2, end2) {
  const start = Math.max(start1, start2);
  const end = Math.min(end1, end2);
  return start < end;
}
function positionBelongsToNode(candidate, position, sourceFile) {
  Debug.assert(candidate.pos <= position);
  return position < candidate.end || !isCompletedNode(candidate, sourceFile);
}
function isCompletedNode(n, sourceFile) {
  if (n === void 0 || nodeIsMissing(n)) {
    return false;
  }
  switch (n.kind) {
    case 263 /* ClassDeclaration */:
    case 264 /* InterfaceDeclaration */:
    case 266 /* EnumDeclaration */:
    case 210 /* ObjectLiteralExpression */:
    case 206 /* ObjectBindingPattern */:
    case 187 /* TypeLiteral */:
    case 241 /* Block */:
    case 268 /* ModuleBlock */:
    case 269 /* CaseBlock */:
    case 275 /* NamedImports */:
    case 279 /* NamedExports */:
      return nodeEndsWith(n, 20 /* CloseBraceToken */, sourceFile);
    case 299 /* CatchClause */:
      return isCompletedNode(n.block, sourceFile);
    case 214 /* NewExpression */:
      if (!n.arguments) {
        return true;
      }
    // falls through
    case 213 /* CallExpression */:
    case 217 /* ParenthesizedExpression */:
    case 196 /* ParenthesizedType */:
      return nodeEndsWith(n, 22 /* CloseParenToken */, sourceFile);
    case 184 /* FunctionType */:
    case 185 /* ConstructorType */:
      return isCompletedNode(n.type, sourceFile);
    case 176 /* Constructor */:
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
    case 174 /* MethodDeclaration */:
    case 173 /* MethodSignature */:
    case 180 /* ConstructSignature */:
    case 179 /* CallSignature */:
    case 219 /* ArrowFunction */:
      if (n.body) {
        return isCompletedNode(n.body, sourceFile);
      }
      if (n.type) {
        return isCompletedNode(n.type, sourceFile);
      }
      return hasChildOfKind(n, 22 /* CloseParenToken */, sourceFile);
    case 267 /* ModuleDeclaration */:
      return !!n.body && isCompletedNode(n.body, sourceFile);
    case 245 /* IfStatement */:
      if (n.elseStatement) {
        return isCompletedNode(n.elseStatement, sourceFile);
      }
      return isCompletedNode(n.thenStatement, sourceFile);
    case 244 /* ExpressionStatement */:
      return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 27 /* SemicolonToken */, sourceFile);
    case 209 /* ArrayLiteralExpression */:
    case 207 /* ArrayBindingPattern */:
    case 212 /* ElementAccessExpression */:
    case 167 /* ComputedPropertyName */:
    case 189 /* TupleType */:
      return nodeEndsWith(n, 24 /* CloseBracketToken */, sourceFile);
    case 181 /* IndexSignature */:
      if (n.type) {
        return isCompletedNode(n.type, sourceFile);
      }
      return hasChildOfKind(n, 24 /* CloseBracketToken */, sourceFile);
    case 296 /* CaseClause */:
    case 297 /* DefaultClause */:
      return false;
    case 248 /* ForStatement */:
    case 249 /* ForInStatement */:
    case 250 /* ForOfStatement */:
    case 247 /* WhileStatement */:
      return isCompletedNode(n.statement, sourceFile);
    case 246 /* DoStatement */:
      return hasChildOfKind(n, 117 /* WhileKeyword */, sourceFile) ? nodeEndsWith(n, 22 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile);
    case 186 /* TypeQuery */:
      return isCompletedNode(n.exprName, sourceFile);
    case 221 /* TypeOfExpression */:
    case 220 /* DeleteExpression */:
    case 222 /* VoidExpression */:
    case 229 /* YieldExpression */:
    case 230 /* SpreadElement */:
      const unaryWordExpression = n;
      return isCompletedNode(unaryWordExpression.expression, sourceFile);
    case 215 /* TaggedTemplateExpression */:
      return isCompletedNode(n.template, sourceFile);
    case 228 /* TemplateExpression */:
      const lastSpan = lastOrUndefined(n.templateSpans);
      return isCompletedNode(lastSpan, sourceFile);
    case 239 /* TemplateSpan */:
      return nodeIsPresent(n.literal);
    case 278 /* ExportDeclaration */:
    case 272 /* ImportDeclaration */:
      return nodeIsPresent(n.moduleSpecifier);
    case 224 /* PrefixUnaryExpression */:
      return isCompletedNode(n.operand, sourceFile);
    case 226 /* BinaryExpression */:
      return isCompletedNode(n.right, sourceFile);
    case 227 /* ConditionalExpression */:
      return isCompletedNode(n.whenFalse, sourceFile);
    default:
      return true;
  }
}
function nodeEndsWith(n, expectedLastToken, sourceFile) {
  const children = n.getChildren(sourceFile);
  if (children.length) {
    const lastChild = last(children);
    if (lastChild.kind === expectedLastToken) {
      return true;
    } else if (lastChild.kind === 27 /* SemicolonToken */ && children.length !== 1) {
      return children[children.length - 2].kind === expectedLastToken;
    }
  }
  return false;
}
function findListItemInfo(node) {
  const list = findContainingList(node);
  if (!list) {
    return void 0;
  }
  const children = list.getChildren();
  const listItemIndex = indexOfNode(children, node);
  return {
    listItemIndex,
    list
  };
}
function hasChildOfKind(n, kind, sourceFile) {
  return !!findChildOfKind(n, kind, sourceFile);
}
function findChildOfKind(n, kind, sourceFile) {
  return find(n.getChildren(sourceFile), (c) => c.kind === kind);
}
function findContainingList(node) {
  const syntaxList = find(node.parent.getChildren(), (c) => isSyntaxList(c) && rangeContainsRange(c, node));
  Debug.assert(!syntaxList || contains(syntaxList.getChildren(), node));
  return syntaxList;
}
function isDefaultModifier2(node) {
  return node.kind === 90 /* DefaultKeyword */;
}
function isClassKeyword(node) {
  return node.kind === 86 /* ClassKeyword */;
}
function isFunctionKeyword(node) {
  return node.kind === 100 /* FunctionKeyword */;
}
function getAdjustedLocationForClass(node) {
  if (isNamedDeclaration(node)) {
    return node.name;
  }
  if (isClassDeclaration(node)) {
    const defaultModifier = node.modifiers && find(node.modifiers, isDefaultModifier2);
    if (defaultModifier) return defaultModifier;
  }
  if (isClassExpression(node)) {
    const classKeyword = find(node.getChildren(), isClassKeyword);
    if (classKeyword) return classKeyword;
  }
}
function getAdjustedLocationForFunction(node) {
  if (isNamedDeclaration(node)) {
    return node.name;
  }
  if (isFunctionDeclaration(node)) {
    const defaultModifier = find(node.modifiers, isDefaultModifier2);
    if (defaultModifier) return defaultModifier;
  }
  if (isFunctionExpression(node)) {
    const functionKeyword = find(node.getChildren(), isFunctionKeyword);
    if (functionKeyword) return functionKeyword;
  }
}
function getAncestorTypeNode(node) {
  let lastTypeNode;
  findAncestor(node, (a) => {
    if (isTypeNode(a)) {
      lastTypeNode = a;
    }
    return !isQualifiedName(a.parent) && !isTypeNode(a.parent) && !isTypeElement(a.parent);
  });
  return lastTypeNode;
}
function getContextualTypeFromParentOrAncestorTypeNode(node, checker) {
  if (node.flags & (16777216 /* JSDoc */ & ~524288 /* JavaScriptFile */)) return void 0;
  const contextualType = getContextualTypeFromParent(node, checker);
  if (contextualType) return contextualType;
  const ancestorTypeNode = getAncestorTypeNode(node);
  return ancestorTypeNode && checker.getTypeAtLocation(ancestorTypeNode);
}
function getAdjustedLocationForDeclaration(node, forRename) {
  if (!forRename) {
    switch (node.kind) {
      case 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
        return getAdjustedLocationForClass(node);
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
        return getAdjustedLocationForFunction(node);
      case 176 /* Constructor */:
        return node;
    }
  }
  if (isNamedDeclaration(node)) {
    return node.name;
  }
}
function getAdjustedLocationForImportDeclaration(node, forRename) {
  if (node.importClause) {
    if (node.importClause.name && node.importClause.namedBindings) {
      return;
    }
    if (node.importClause.name) {
      return node.importClause.name;
    }
    if (node.importClause.namedBindings) {
      if (isNamedImports(node.importClause.namedBindings)) {
        const onlyBinding = singleOrUndefined(node.importClause.namedBindings.elements);
        if (!onlyBinding) {
          return;
        }
        return onlyBinding.name;
      } else if (isNamespaceImport(node.importClause.namedBindings)) {
        return node.importClause.namedBindings.name;
      }
    }
  }
  if (!forRename) {
    return node.moduleSpecifier;
  }
}
function getAdjustedLocationForExportDeclaration(node, forRename) {
  if (node.exportClause) {
    if (isNamedExports(node.exportClause)) {
      const onlyBinding = singleOrUndefined(node.exportClause.elements);
      if (!onlyBinding) {
        return;
      }
      return node.exportClause.elements[0].name;
    } else if (isNamespaceExport(node.exportClause)) {
      return node.exportClause.name;
    }
  }
  if (!forRename) {
    return node.moduleSpecifier;
  }
}
function getAdjustedLocationForHeritageClause(node) {
  if (node.types.length === 1) {
    return node.types[0].expression;
  }
}
function getAdjustedLocation(node, forRename) {
  const { parent: parent2 } = node;
  if (isModifier(node) && (forRename || node.kind !== 90 /* DefaultKeyword */) ? canHaveModifiers(parent2) && contains(parent2.modifiers, node) : node.kind === 86 /* ClassKeyword */ ? isClassDeclaration(parent2) || isClassExpression(node) : node.kind === 100 /* FunctionKeyword */ ? isFunctionDeclaration(parent2) || isFunctionExpression(node) : node.kind === 120 /* InterfaceKeyword */ ? isInterfaceDeclaration(parent2) : node.kind === 94 /* EnumKeyword */ ? isEnumDeclaration(parent2) : node.kind === 156 /* TypeKeyword */ ? isTypeAliasDeclaration(parent2) : node.kind === 145 /* NamespaceKeyword */ || node.kind === 144 /* ModuleKeyword */ ? isModuleDeclaration(parent2) : node.kind === 102 /* ImportKeyword */ ? isImportEqualsDeclaration(parent2) : node.kind === 139 /* GetKeyword */ ? isGetAccessorDeclaration(parent2) : node.kind === 153 /* SetKeyword */ && isSetAccessorDeclaration(parent2)) {
    const location = getAdjustedLocationForDeclaration(parent2, forRename);
    if (location) {
      return location;
    }
  }
  if ((node.kind === 115 /* VarKeyword */ || node.kind === 87 /* ConstKeyword */ || node.kind === 121 /* LetKeyword */) && isVariableDeclarationList(parent2) && parent2.declarations.length === 1) {
    const decl = parent2.declarations[0];
    if (isIdentifier(decl.name)) {
      return decl.name;
    }
  }
  if (node.kind === 156 /* TypeKeyword */) {
    if (isImportClause(parent2) && parent2.isTypeOnly) {
      const location = getAdjustedLocationForImportDeclaration(parent2.parent, forRename);
      if (location) {
        return location;
      }
    }
    if (isExportDeclaration(parent2) && parent2.isTypeOnly) {
      const location = getAdjustedLocationForExportDeclaration(parent2, forRename);
      if (location) {
        return location;
      }
    }
  }
  if (node.kind === 130 /* AsKeyword */) {
    if (isImportSpecifier(parent2) && parent2.propertyName || isExportSpecifier(parent2) && parent2.propertyName || isNamespaceImport(parent2) || isNamespaceExport(parent2)) {
      return parent2.name;
    }
    if (isExportDeclaration(parent2) && parent2.exportClause && isNamespaceExport(parent2.exportClause)) {
      return parent2.exportClause.name;
    }
  }
  if (node.kind === 102 /* ImportKeyword */ && isImportDeclaration(parent2)) {
    const location = getAdjustedLocationForImportDeclaration(parent2, forRename);
    if (location) {
      return location;
    }
  }
  if (node.kind === 95 /* ExportKeyword */) {
    if (isExportDeclaration(parent2)) {
      const location = getAdjustedLocationForExportDeclaration(parent2, forRename);
      if (location) {
        return location;
      }
    }
    if (isExportAssignment(parent2)) {
      return skipOuterExpressions(parent2.expression);
    }
  }
  if (node.kind === 149 /* RequireKeyword */ && isExternalModuleReference(parent2)) {
    return parent2.expression;
  }
  if (node.kind === 161 /* FromKeyword */ && (isImportDeclaration(parent2) || isExportDeclaration(parent2)) && parent2.moduleSpecifier) {
    return parent2.moduleSpecifier;
  }
  if ((node.kind === 96 /* ExtendsKeyword */ || node.kind === 119 /* ImplementsKeyword */) && isHeritageClause(parent2) && parent2.token === node.kind) {
    const location = getAdjustedLocationForHeritageClause(parent2);
    if (location) {
      return location;
    }
  }
  if (node.kind === 96 /* ExtendsKeyword */) {
    if (isTypeParameterDeclaration(parent2) && parent2.constraint && isTypeReferenceNode(parent2.constraint)) {
      return parent2.constraint.typeName;
    }
    if (isConditionalTypeNode(parent2) && isTypeReferenceNode(parent2.extendsType)) {
      return parent2.extendsType.typeName;
    }
  }
  if (node.kind === 140 /* InferKeyword */ && isInferTypeNode(parent2)) {
    return parent2.typeParameter.name;
  }
  if (node.kind === 103 /* InKeyword */ && isTypeParameterDeclaration(parent2) && isMappedTypeNode(parent2.parent)) {
    return parent2.name;
  }
  if (node.kind === 143 /* KeyOfKeyword */ && isTypeOperatorNode(parent2) && parent2.operator === 143 /* KeyOfKeyword */ && isTypeReferenceNode(parent2.type)) {
    return parent2.type.typeName;
  }
  if (node.kind === 148 /* ReadonlyKeyword */ && isTypeOperatorNode(parent2) && parent2.operator === 148 /* ReadonlyKeyword */ && isArrayTypeNode(parent2.type) && isTypeReferenceNode(parent2.type.elementType)) {
    return parent2.type.elementType.typeName;
  }
  if (!forRename) {
    if (node.kind === 105 /* NewKeyword */ && isNewExpression(parent2) || node.kind === 116 /* VoidKeyword */ && isVoidExpression(parent2) || node.kind === 114 /* TypeOfKeyword */ && isTypeOfExpression(parent2) || node.kind === 135 /* AwaitKeyword */ && isAwaitExpression(parent2) || node.kind === 127 /* YieldKeyword */ && isYieldExpression(parent2) || node.kind === 91 /* DeleteKeyword */ && isDeleteExpression(parent2)) {
      if (parent2.expression) {
        return skipOuterExpressions(parent2.expression);
      }
    }
    if ((node.kind === 103 /* InKeyword */ || node.kind === 104 /* InstanceOfKeyword */) && isBinaryExpression(parent2) && parent2.operatorToken === node) {
      return skipOuterExpressions(parent2.right);
    }
    if (node.kind === 130 /* AsKeyword */ && isAsExpression(parent2) && isTypeReferenceNode(parent2.type)) {
      return parent2.type.typeName;
    }
    if (node.kind === 103 /* InKeyword */ && isForInStatement(parent2) || node.kind === 165 /* OfKeyword */ && isForOfStatement(parent2)) {
      return skipOuterExpressions(parent2.expression);
    }
  }
  return node;
}
function getAdjustedReferenceLocation(node) {
  return getAdjustedLocation(
    node,
    /*forRename*/
    false
  );
}
function getAdjustedRenameLocation(node) {
  return getAdjustedLocation(
    node,
    /*forRename*/
    true
  );
}
function getTouchingPropertyName(sourceFile, position) {
  return getTouchingToken(sourceFile, position, (n) => isPropertyNameLiteral(n) || isKeyword(n.kind) || isPrivateIdentifier(n));
}
function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) {
  return getTokenAtPositionWorker(
    sourceFile,
    position,
    /*allowPositionInLeadingTrivia*/
    false,
    includePrecedingTokenAtEndPosition,
    /*includeEndPosition*/
    false
  );
}
function getTokenAtPosition(sourceFile, position) {
  return getTokenAtPositionWorker(
    sourceFile,
    position,
    /*allowPositionInLeadingTrivia*/
    true,
    /*includePrecedingTokenAtEndPosition*/
    void 0,
    /*includeEndPosition*/
    false
  );
}
function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) {
  let current = sourceFile;
  let foundToken;
  outer:
    while (true) {
      const children = current.getChildren(sourceFile);
      const i = binarySearchKey(children, position, (_, i2) => i2, (middle, _) => {
        const end = children[middle].getEnd();
        if (end < position) {
          return -1 /* LessThan */;
        }
        const start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(
          sourceFile,
          /*includeJsDocComment*/
          true
        );
        if (start > position) {
          return 1 /* GreaterThan */;
        }
        if (nodeContainsPosition(children[middle], start, end)) {
          if (children[middle - 1]) {
            if (nodeContainsPosition(children[middle - 1])) {
              return 1 /* GreaterThan */;
            }
          }
          return 0 /* EqualTo */;
        }
        if (includePrecedingTokenAtEndPosition && start === position && children[middle - 1] && children[middle - 1].getEnd() === position && nodeContainsPosition(children[middle - 1])) {
          return 1 /* GreaterThan */;
        }
        return -1 /* LessThan */;
      });
      if (foundToken) {
        return foundToken;
      }
      if (i >= 0 && children[i]) {
        current = children[i];
        continue outer;
      }
      return current;
    }
  function nodeContainsPosition(node, start, end) {
    end ?? (end = node.getEnd());
    if (end < position) {
      return false;
    }
    start ?? (start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(
      sourceFile,
      /*includeJsDocComment*/
      true
    ));
    if (start > position) {
      return false;
    }
    if (position < end || position === end && (node.kind === 1 /* EndOfFileToken */ || includeEndPosition)) {
      return true;
    } else if (includePrecedingTokenAtEndPosition && end === position) {
      const previousToken = findPrecedingToken(position, sourceFile, node);
      if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) {
        foundToken = previousToken;
        return true;
      }
    }
    return false;
  }
}
function findFirstNonJsxWhitespaceToken(sourceFile, position) {
  let tokenAtPosition = getTokenAtPosition(sourceFile, position);
  while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) {
    const nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile);
    if (!nextToken) return;
    tokenAtPosition = nextToken;
  }
  return tokenAtPosition;
}
function findTokenOnLeftOfPosition(file, position) {
  const tokenAtPosition = getTokenAtPosition(file, position);
  if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {
    return tokenAtPosition;
  }
  return findPrecedingToken(position, file);
}
function findNextToken(previousToken, parent2, sourceFile) {
  return find2(parent2);
  function find2(n) {
    if (isToken(n) && n.pos === previousToken.end) {
      return n;
    }
    return firstDefined(n.getChildren(sourceFile), (child) => {
      const shouldDiveInChildNode = (
        // previous token is enclosed somewhere in the child
        child.pos <= previousToken.pos && child.end > previousToken.end || // previous token ends exactly at the beginning of child
        child.pos === previousToken.end
      );
      return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find2(child) : void 0;
    });
  }
}
function findPrecedingToken(position, sourceFile, startNode2, excludeJsdoc) {
  const result = find2(startNode2 || sourceFile);
  Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result)));
  return result;
  function find2(n) {
    if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) {
      return n;
    }
    const children = n.getChildren(sourceFile);
    const i = binarySearchKey(children, position, (_, i2) => i2, (middle, _) => {
      if (position < children[middle].end) {
        if (!children[middle - 1] || position >= children[middle - 1].end) {
          return 0 /* EqualTo */;
        }
        return 1 /* GreaterThan */;
      }
      return -1 /* LessThan */;
    });
    if (i >= 0 && children[i]) {
      const child = children[i];
      if (position < child.end) {
        const start = child.getStart(
          sourceFile,
          /*includeJsDoc*/
          !excludeJsdoc
        );
        const lookInPreviousChild = start >= position || // cursor in the leading trivia
        !nodeHasTokens(child, sourceFile) || isWhiteSpaceOnlyJsxText(child);
        if (lookInPreviousChild) {
          const candidate2 = findRightmostChildNodeWithTokens(
            children,
            /*exclusiveStartPosition*/
            i,
            sourceFile,
            n.kind
          );
          if (candidate2) {
            if (!excludeJsdoc && isJSDocCommentContainingNode(candidate2) && candidate2.getChildren(sourceFile).length) {
              return find2(candidate2);
            }
            return findRightmostToken(candidate2, sourceFile);
          }
          return void 0;
        } else {
          return find2(child);
        }
      }
    }
    Debug.assert(startNode2 !== void 0 || n.kind === 307 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || isJSDocCommentContainingNode(n));
    const candidate = findRightmostChildNodeWithTokens(
      children,
      /*exclusiveStartPosition*/
      children.length,
      sourceFile,
      n.kind
    );
    return candidate && findRightmostToken(candidate, sourceFile);
  }
}
function isNonWhitespaceToken(n) {
  return isToken(n) && !isWhiteSpaceOnlyJsxText(n);
}
function findRightmostToken(n, sourceFile) {
  if (isNonWhitespaceToken(n)) {
    return n;
  }
  const children = n.getChildren(sourceFile);
  if (children.length === 0) {
    return n;
  }
  const candidate = findRightmostChildNodeWithTokens(
    children,
    /*exclusiveStartPosition*/
    children.length,
    sourceFile,
    n.kind
  );
  return candidate && findRightmostToken(candidate, sourceFile);
}
function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile, parentKind) {
  for (let i = exclusiveStartPosition - 1; i >= 0; i--) {
    const child = children[i];
    if (isWhiteSpaceOnlyJsxText(child)) {
      if (i === 0 && (parentKind === 12 /* JsxText */ || parentKind === 285 /* JsxSelfClosingElement */)) {
        Debug.fail("`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`");
      }
    } else if (nodeHasTokens(children[i], sourceFile)) {
      return children[i];
    }
  }
}
function isInString(sourceFile, position, previousToken = findPrecedingToken(position, sourceFile)) {
  if (previousToken && isStringTextContainingNode(previousToken)) {
    const start = previousToken.getStart(sourceFile);
    const end = previousToken.getEnd();
    if (start < position && position < end) {
      return true;
    }
    if (position === end) {
      return !!previousToken.isUnterminated;
    }
  }
  return false;
}
function isInsideJsxElementOrAttribute(sourceFile, position) {
  const token = getTokenAtPosition(sourceFile, position);
  if (!token) {
    return false;
  }
  if (token.kind === 12 /* JsxText */) {
    return true;
  }
  if (token.kind === 30 /* LessThanToken */ && token.parent.kind === 12 /* JsxText */) {
    return true;
  }
  if (token.kind === 30 /* LessThanToken */ && token.parent.kind === 294 /* JsxExpression */) {
    return true;
  }
  if (token && token.kind === 20 /* CloseBraceToken */ && token.parent.kind === 294 /* JsxExpression */) {
    return true;
  }
  if (token.kind === 30 /* LessThanToken */ && token.parent.kind === 287 /* JsxClosingElement */) {
    return true;
  }
  return false;
}
function isWhiteSpaceOnlyJsxText(node) {
  return isJsxText(node) && node.containsOnlyTriviaWhiteSpaces;
}
function isInTemplateString(sourceFile, position) {
  const token = getTokenAtPosition(sourceFile, position);
  return isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile);
}
function isInJSXText(sourceFile, position) {
  const token = getTokenAtPosition(sourceFile, position);
  if (isJsxText(token)) {
    return true;
  }
  if (token.kind === 19 /* OpenBraceToken */ && isJsxExpression(token.parent) && isJsxElement(token.parent.parent)) {
    return true;
  }
  if (token.kind === 30 /* LessThanToken */ && isJsxOpeningLikeElement(token.parent) && isJsxElement(token.parent.parent)) {
    return true;
  }
  return false;
}
function isInsideJsxElement(sourceFile, position) {
  function isInsideJsxElementTraversal(node) {
    while (node) {
      if (node.kind >= 285 /* JsxSelfClosingElement */ && node.kind <= 294 /* JsxExpression */ || node.kind === 12 /* JsxText */ || node.kind === 30 /* LessThanToken */ || node.kind === 32 /* GreaterThanToken */ || node.kind === 80 /* Identifier */ || node.kind === 20 /* CloseBraceToken */ || node.kind === 19 /* OpenBraceToken */ || node.kind === 44 /* SlashToken */) {
        node = node.parent;
      } else if (node.kind === 284 /* JsxElement */) {
        if (position > node.getStart(sourceFile)) return true;
        node = node.parent;
      } else {
        return false;
      }
    }
    return false;
  }
  return isInsideJsxElementTraversal(getTokenAtPosition(sourceFile, position));
}
function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) {
  const closeTokenText = tokenToString(token.kind);
  const matchingTokenText = tokenToString(matchingTokenKind);
  const tokenFullStart = token.getFullStart();
  const bestGuessIndex = sourceFile.text.lastIndexOf(matchingTokenText, tokenFullStart);
  if (bestGuessIndex === -1) {
    return void 0;
  }
  if (sourceFile.text.lastIndexOf(closeTokenText, tokenFullStart - 1) < bestGuessIndex) {
    const nodeAtGuess = findPrecedingToken(bestGuessIndex + 1, sourceFile);
    if (nodeAtGuess && nodeAtGuess.kind === matchingTokenKind) {
      return nodeAtGuess;
    }
  }
  const tokenKind = token.kind;
  let remainingMatchingTokens = 0;
  while (true) {
    const preceding = findPrecedingToken(token.getFullStart(), sourceFile);
    if (!preceding) {
      return void 0;
    }
    token = preceding;
    if (token.kind === matchingTokenKind) {
      if (remainingMatchingTokens === 0) {
        return token;
      }
      remainingMatchingTokens--;
    } else if (token.kind === tokenKind) {
      remainingMatchingTokens++;
    }
  }
}
function removeOptionality(type, isOptionalExpression, isOptionalChain2) {
  return isOptionalExpression ? type.getNonNullableType() : isOptionalChain2 ? type.getNonOptionalType() : type;
}
function isPossiblyTypeArgumentPosition(token, sourceFile, checker) {
  const info = getPossibleTypeArgumentsInfo(token, sourceFile);
  return info !== void 0 && (isPartOfTypeNode(info.called) || getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || isPossiblyTypeArgumentPosition(info.called, sourceFile, checker));
}
function getPossibleGenericSignatures(called, typeArgumentCount, checker) {
  let type = checker.getTypeAtLocation(called);
  if (isOptionalChain(called.parent)) {
    type = removeOptionality(
      type,
      isOptionalChainRoot(called.parent),
      /*isOptionalChain*/
      true
    );
  }
  const signatures = isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures();
  return signatures.filter((candidate) => !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount);
}
function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) {
  if (sourceFile.text.lastIndexOf("<", tokenIn ? tokenIn.pos : sourceFile.text.length) === -1) {
    return void 0;
  }
  let token = tokenIn;
  let remainingLessThanTokens = 0;
  let nTypeArguments = 0;
  while (token) {
    switch (token.kind) {
      case 30 /* LessThanToken */:
        token = findPrecedingToken(token.getFullStart(), sourceFile);
        if (token && token.kind === 29 /* QuestionDotToken */) {
          token = findPrecedingToken(token.getFullStart(), sourceFile);
        }
        if (!token || !isIdentifier(token)) return void 0;
        if (!remainingLessThanTokens) {
          return isDeclarationName(token) ? void 0 : { called: token, nTypeArguments };
        }
        remainingLessThanTokens--;
        break;
      case 50 /* GreaterThanGreaterThanGreaterThanToken */:
        remainingLessThanTokens = 3;
        break;
      case 49 /* GreaterThanGreaterThanToken */:
        remainingLessThanTokens = 2;
        break;
      case 32 /* GreaterThanToken */:
        remainingLessThanTokens++;
        break;
      case 20 /* CloseBraceToken */:
        token = findPrecedingMatchingToken(token, 19 /* OpenBraceToken */, sourceFile);
        if (!token) return void 0;
        break;
      case 22 /* CloseParenToken */:
        token = findPrecedingMatchingToken(token, 21 /* OpenParenToken */, sourceFile);
        if (!token) return void 0;
        break;
      case 24 /* CloseBracketToken */:
        token = findPrecedingMatchingToken(token, 23 /* OpenBracketToken */, sourceFile);
        if (!token) return void 0;
        break;
      // Valid tokens in a type name. Skip.
      case 28 /* CommaToken */:
        nTypeArguments++;
        break;
      case 39 /* EqualsGreaterThanToken */:
      // falls through
      case 80 /* Identifier */:
      case 11 /* StringLiteral */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      // falls through
      case 114 /* TypeOfKeyword */:
      case 96 /* ExtendsKeyword */:
      case 143 /* KeyOfKeyword */:
      case 25 /* DotToken */:
      case 52 /* BarToken */:
      case 58 /* QuestionToken */:
      case 59 /* ColonToken */:
        break;
      default:
        if (isTypeNode(token)) {
          break;
        }
        return void 0;
    }
    token = findPrecedingToken(token.getFullStart(), sourceFile);
  }
  return void 0;
}
function isInComment(sourceFile, position, tokenAtPosition) {
  return ts_formatting_exports.getRangeOfEnclosingComment(
    sourceFile,
    position,
    /*precedingToken*/
    void 0,
    tokenAtPosition
  );
}
function hasDocComment(sourceFile, position) {
  const token = getTokenAtPosition(sourceFile, position);
  return !!findAncestor(token, isJSDoc);
}
function nodeHasTokens(n, sourceFile) {
  return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0;
}
function getNodeModifiers(node, excludeFlags = 0 /* None */) {
  const result = [];
  const flags = isDeclaration(node) ? getCombinedNodeFlagsAlwaysIncludeJSDoc(node) & ~excludeFlags : 0 /* None */;
  if (flags & 2 /* Private */) result.push("private" /* privateMemberModifier */);
  if (flags & 4 /* Protected */) result.push("protected" /* protectedMemberModifier */);
  if (flags & 1 /* Public */) result.push("public" /* publicMemberModifier */);
  if (flags & 256 /* Static */ || isClassStaticBlockDeclaration(node)) result.push("static" /* staticModifier */);
  if (flags & 64 /* Abstract */) result.push("abstract" /* abstractModifier */);
  if (flags & 32 /* Export */) result.push("export" /* exportedModifier */);
  if (flags & 65536 /* Deprecated */) result.push("deprecated" /* deprecatedModifier */);
  if (node.flags & 33554432 /* Ambient */) result.push("declare" /* ambientModifier */);
  if (node.kind === 277 /* ExportAssignment */) result.push("export" /* exportedModifier */);
  return result.length > 0 ? result.join(",") : "" /* none */;
}
function getTypeArgumentOrTypeParameterList(node) {
  if (node.kind === 183 /* TypeReference */ || node.kind === 213 /* CallExpression */) {
    return node.typeArguments;
  }
  if (isFunctionLike(node) || node.kind === 263 /* ClassDeclaration */ || node.kind === 264 /* InterfaceDeclaration */) {
    return node.typeParameters;
  }
  return void 0;
}
function isComment(kind) {
  return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */;
}
function isStringOrRegularExpressionOrTemplateLiteral(kind) {
  if (kind === 11 /* StringLiteral */ || kind === 14 /* RegularExpressionLiteral */ || isTemplateLiteralKind(kind)) {
    return true;
  }
  return false;
}
function areIntersectedTypesAvoidingStringReduction(checker, t1, t2) {
  return !!(t1.flags & 4 /* String */) && checker.isEmptyAnonymousObjectType(t2);
}
function isStringAndEmptyAnonymousObjectIntersection(type) {
  if (!type.isIntersection()) {
    return false;
  }
  const { types, checker } = type;
  return types.length === 2 && (areIntersectedTypesAvoidingStringReduction(checker, types[0], types[1]) || areIntersectedTypesAvoidingStringReduction(checker, types[1], types[0]));
}
function isInsideTemplateLiteral(node, position, sourceFile) {
  return isTemplateLiteralKind(node.kind) && (node.getStart(sourceFile) < position && position < node.end) || !!node.isUnterminated && position === node.end;
}
function isAccessibilityModifier(kind) {
  switch (kind) {
    case 125 /* PublicKeyword */:
    case 123 /* PrivateKeyword */:
    case 124 /* ProtectedKeyword */:
      return true;
  }
  return false;
}
function cloneCompilerOptions(options) {
  const result = clone(options);
  setConfigFileInOptions(result, options && options.configFile);
  return result;
}
function isArrayLiteralOrObjectLiteralDestructuringPattern(node) {
  if (node.kind === 209 /* ArrayLiteralExpression */ || node.kind === 210 /* ObjectLiteralExpression */) {
    if (node.parent.kind === 226 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */) {
      return true;
    }
    if (node.parent.kind === 250 /* ForOfStatement */ && node.parent.initializer === node) {
      return true;
    }
    if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 303 /* PropertyAssignment */ ? node.parent.parent : node.parent)) {
      return true;
    }
  }
  return false;
}
function isInReferenceComment(sourceFile, position) {
  return isInReferenceCommentWorker(
    sourceFile,
    position,
    /*shouldBeReference*/
    true
  );
}
function isInNonReferenceComment(sourceFile, position) {
  return isInReferenceCommentWorker(
    sourceFile,
    position,
    /*shouldBeReference*/
    false
  );
}
function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) {
  const range = isInComment(
    sourceFile,
    position,
    /*tokenAtPosition*/
    void 0
  );
  return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end));
}
function getReplacementSpanForContextToken(contextToken, position) {
  if (!contextToken) return void 0;
  switch (contextToken.kind) {
    case 11 /* StringLiteral */:
    case 15 /* NoSubstitutionTemplateLiteral */:
      return createTextSpanFromStringLiteralLikeContent(contextToken, position);
    default:
      return createTextSpanFromNode(contextToken);
  }
}
function createTextSpanFromNode(node, sourceFile, endNode2) {
  return createTextSpanFromBounds(node.getStart(sourceFile), (endNode2 || node).getEnd());
}
function createTextSpanFromStringLiteralLikeContent(node, position) {
  let replacementEnd = node.getEnd() - 1;
  if (node.isUnterminated) {
    if (node.getStart() === replacementEnd) return void 0;
    replacementEnd = Math.min(position, node.getEnd());
  }
  return createTextSpanFromBounds(node.getStart() + 1, replacementEnd);
}
function createTextRangeFromNode(node, sourceFile) {
  return createRange(node.getStart(sourceFile), node.end);
}
function createTextSpanFromRange(range) {
  return createTextSpanFromBounds(range.pos, range.end);
}
function createTextRangeFromSpan(span) {
  return createRange(span.start, span.start + span.length);
}
function createTextChangeFromStartLength(start, length2, newText) {
  return createTextChange(createTextSpan(start, length2), newText);
}
function createTextChange(span, newText) {
  return { span, newText };
}
var typeKeywords = [
  133 /* AnyKeyword */,
  131 /* AssertsKeyword */,
  163 /* BigIntKeyword */,
  136 /* BooleanKeyword */,
  97 /* FalseKeyword */,
  140 /* InferKeyword */,
  143 /* KeyOfKeyword */,
  146 /* NeverKeyword */,
  106 /* NullKeyword */,
  150 /* NumberKeyword */,
  151 /* ObjectKeyword */,
  148 /* ReadonlyKeyword */,
  154 /* StringKeyword */,
  155 /* SymbolKeyword */,
  114 /* TypeOfKeyword */,
  112 /* TrueKeyword */,
  116 /* VoidKeyword */,
  157 /* UndefinedKeyword */,
  158 /* UniqueKeyword */,
  159 /* UnknownKeyword */
];
function isTypeKeyword(kind) {
  return contains(typeKeywords, kind);
}
function isTypeKeywordToken(node) {
  return node.kind === 156 /* TypeKeyword */;
}
function isTypeKeywordTokenOrIdentifier(node) {
  return isTypeKeywordToken(node) || isIdentifier(node) && node.text === "type";
}
function nodeSeenTracker() {
  const seen = [];
  return (node) => {
    const id = getNodeId(node);
    return !seen[id] && (seen[id] = true);
  };
}
function getSnapshotText(snap) {
  return snap.getText(0, snap.getLength());
}
function repeatString(str, count) {
  let result = "";
  for (let i = 0; i < count; i++) {
    result += str;
  }
  return result;
}
function skipConstraint(type) {
  return type.isTypeParameter() ? type.getConstraint() || type : type;
}
function getNameFromPropertyName(name) {
  return name.kind === 167 /* ComputedPropertyName */ ? isStringOrNumericLiteralLike(name.expression) ? name.expression.text : void 0 : isPrivateIdentifier(name) ? idText(name) : getTextOfIdentifierOrLiteral(name);
}
function programContainsModules(program) {
  return program.getSourceFiles().some((s) => !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator));
}
function programContainsEsModules(program) {
  return program.getSourceFiles().some((s) => !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator);
}
function compilerOptionsIndicateEsModules(compilerOptions) {
  return !!compilerOptions.module || getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ || !!compilerOptions.noEmit;
}
function createModuleSpecifierResolutionHost(program, host) {
  return {
    fileExists: (fileName) => program.fileExists(fileName),
    getCurrentDirectory: () => host.getCurrentDirectory(),
    readFile: maybeBind(host, host.readFile),
    useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames) || program.useCaseSensitiveFileNames,
    getSymlinkCache: maybeBind(host, host.getSymlinkCache) || program.getSymlinkCache,
    getModuleSpecifierCache: maybeBind(host, host.getModuleSpecifierCache),
    getPackageJsonInfoCache: () => {
      var _a;
      return (_a = program.getModuleResolutionCache()) == null ? void 0 : _a.getPackageJsonInfoCache();
    },
    getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation),
    redirectTargetsMap: program.redirectTargetsMap,
    getProjectReferenceRedirect: (fileName) => program.getProjectReferenceRedirect(fileName),
    isSourceOfProjectReferenceRedirect: (fileName) => program.isSourceOfProjectReferenceRedirect(fileName),
    getNearestAncestorDirectoryWithPackageJson: maybeBind(host, host.getNearestAncestorDirectoryWithPackageJson),
    getFileIncludeReasons: () => program.getFileIncludeReasons(),
    getCommonSourceDirectory: () => program.getCommonSourceDirectory(),
    getDefaultResolutionModeForFile: (file) => program.getDefaultResolutionModeForFile(file),
    getModeForResolutionAtIndex: (file, index) => program.getModeForResolutionAtIndex(file, index)
  };
}
function getModuleSpecifierResolverHost(program, host) {
  return {
    ...createModuleSpecifierResolutionHost(program, host),
    getCommonSourceDirectory: () => program.getCommonSourceDirectory()
  };
}
function moduleResolutionUsesNodeModules(moduleResolution) {
  return moduleResolution === 2 /* Node10 */ || moduleResolution >= 3 /* Node16 */ && moduleResolution <= 99 /* NodeNext */ || moduleResolution === 100 /* Bundler */;
}
function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference, isTypeOnly) {
  return factory.createImportDeclaration(
    /*modifiers*/
    void 0,
    defaultImport || namedImports ? factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? factory.createNamedImports(namedImports) : void 0) : void 0,
    typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier,
    /*attributes*/
    void 0
  );
}
function makeStringLiteral(text, quotePreference) {
  return factory.createStringLiteral(text, quotePreference === 0 /* Single */);
}
var QuotePreference = /* @__PURE__ */ ((QuotePreference6) => {
  QuotePreference6[QuotePreference6["Single"] = 0] = "Single";
  QuotePreference6[QuotePreference6["Double"] = 1] = "Double";
  return QuotePreference6;
})(QuotePreference || {});
function quotePreferenceFromString(str, sourceFile) {
  return isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */;
}
function getQuotePreference(sourceFile, preferences) {
  if (preferences.quotePreference && preferences.quotePreference !== "auto") {
    return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */;
  } else {
    const firstModuleSpecifier = isFullSourceFile(sourceFile) && sourceFile.imports && find(sourceFile.imports, (n) => isStringLiteral(n) && !nodeIsSynthesized(n.parent));
    return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */;
  }
}
function getQuoteFromPreference(qp) {
  switch (qp) {
    case 0 /* Single */:
      return "'";
    case 1 /* Double */:
      return '"';
    default:
      return Debug.assertNever(qp);
  }
}
function symbolNameNoDefault(symbol) {
  const escaped = symbolEscapedNameNoDefault(symbol);
  return escaped === void 0 ? void 0 : unescapeLeadingUnderscores(escaped);
}
function symbolEscapedNameNoDefault(symbol) {
  if (symbol.escapedName !== "default" /* Default */) {
    return symbol.escapedName;
  }
  return firstDefined(symbol.declarations, (decl) => {
    const name = getNameOfDeclaration(decl);
    return name && name.kind === 80 /* Identifier */ ? name.escapedText : void 0;
  });
}
function isModuleSpecifierLike(node) {
  return isStringLiteralLike(node) && (isExternalModuleReference(node.parent) || isImportDeclaration(node.parent) || isJSDocImportTag(node.parent) || isRequireCall(
    node.parent,
    /*requireStringLiteralLikeArgument*/
    false
  ) && node.parent.arguments[0] === node || isImportCall(node.parent) && node.parent.arguments[0] === node);
}
function isObjectBindingElementWithoutPropertyName(bindingElement) {
  return isBindingElement(bindingElement) && isObjectBindingPattern(bindingElement.parent) && isIdentifier(bindingElement.name) && !bindingElement.propertyName;
}
function getPropertySymbolFromBindingElement(checker, bindingElement) {
  const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
  return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
}
function getParentNodeInSpan(node, file, span) {
  if (!node) return void 0;
  while (node.parent) {
    if (isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) {
      return node;
    }
    node = node.parent;
  }
}
function spanContainsNode(span, node, file) {
  return textSpanContainsPosition(span, node.getStart(file)) && node.getEnd() <= textSpanEnd(span);
}
function findModifier(node, kind) {
  return canHaveModifiers(node) ? find(node.modifiers, (m) => m.kind === kind) : void 0;
}
function insertImports(changes, sourceFile, imports, blankLineBetween, preferences) {
  var _a;
  const decl = isArray(imports) ? imports[0] : imports;
  const importKindPredicate = decl.kind === 243 /* VariableStatement */ ? isRequireVariableStatement : isAnyImportSyntax;
  const existingImportStatements = filter(sourceFile.statements, importKindPredicate);
  const { comparer, isSorted } = ts_OrganizeImports_exports.getOrganizeImportsStringComparerWithDetection(existingImportStatements, preferences);
  const sortedNewImports = isArray(imports) ? toSorted(imports, (a, b) => ts_OrganizeImports_exports.compareImportsOrRequireStatements(a, b, comparer)) : [imports];
  if (!(existingImportStatements == null ? void 0 : existingImportStatements.length)) {
    if (isFullSourceFile(sourceFile)) {
      changes.insertNodesAtTopOfFile(sourceFile, sortedNewImports, blankLineBetween);
    } else {
      for (const newImport of sortedNewImports) {
        changes.insertStatementsInNewFile(sourceFile.fileName, [newImport], (_a = getOriginalNode(newImport)) == null ? void 0 : _a.getSourceFile());
      }
    }
    return;
  }
  Debug.assert(isFullSourceFile(sourceFile));
  if (existingImportStatements && isSorted) {
    for (const newImport of sortedNewImports) {
      const insertionIndex = ts_OrganizeImports_exports.getImportDeclarationInsertionIndex(existingImportStatements, newImport, comparer);
      if (insertionIndex === 0) {
        const options = existingImportStatements[0] === sourceFile.statements[0] ? { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude } : {};
        changes.insertNodeBefore(
          sourceFile,
          existingImportStatements[0],
          newImport,
          /*blankLineBetween*/
          false,
          options
        );
      } else {
        const prevImport = existingImportStatements[insertionIndex - 1];
        changes.insertNodeAfter(sourceFile, prevImport, newImport);
      }
    }
  } else {
    const lastExistingImport = lastOrUndefined(existingImportStatements);
    if (lastExistingImport) {
      changes.insertNodesAfter(sourceFile, lastExistingImport, sortedNewImports);
    } else {
      changes.insertNodesAtTopOfFile(sourceFile, sortedNewImports, blankLineBetween);
    }
  }
}
function getTypeKeywordOfTypeOnlyImport(importClause, sourceFile) {
  Debug.assert(importClause.isTypeOnly);
  return cast(importClause.getChildAt(0, sourceFile), isTypeKeywordToken);
}
function textSpansEqual(a, b) {
  return !!a && !!b && a.start === b.start && a.length === b.length;
}
function documentSpansEqual(a, b, useCaseSensitiveFileNames2) {
  return (useCaseSensitiveFileNames2 ? equateStringsCaseSensitive : equateStringsCaseInsensitive)(a.fileName, b.fileName) && textSpansEqual(a.textSpan, b.textSpan);
}
function getDocumentSpansEqualityComparer(useCaseSensitiveFileNames2) {
  return (a, b) => documentSpansEqual(a, b, useCaseSensitiveFileNames2);
}
function forEachUnique(array, callback) {
  if (array) {
    for (let i = 0; i < array.length; i++) {
      if (array.indexOf(array[i]) === i) {
        const result = callback(array[i], i);
        if (result) {
          return result;
        }
      }
    }
  }
  return void 0;
}
function isTextWhiteSpaceLike(text, startPos, endPos) {
  for (let i = startPos; i < endPos; i++) {
    if (!isWhiteSpaceLike(text.charCodeAt(i))) {
      return false;
    }
  }
  return true;
}
function getMappedLocation(location, sourceMapper, fileExists) {
  const mapsTo = sourceMapper.tryGetSourcePosition(location);
  return mapsTo && (!fileExists || fileExists(normalizePath(mapsTo.fileName)) ? mapsTo : void 0);
}
function getMappedDocumentSpan(documentSpan, sourceMapper, fileExists) {
  const { fileName, textSpan } = documentSpan;
  const newPosition = getMappedLocation({ fileName, pos: textSpan.start }, sourceMapper, fileExists);
  if (!newPosition) return void 0;
  const newEndPosition = getMappedLocation({ fileName, pos: textSpan.start + textSpan.length }, sourceMapper, fileExists);
  const newLength = newEndPosition ? newEndPosition.pos - newPosition.pos : textSpan.length;
  return {
    fileName: newPosition.fileName,
    textSpan: {
      start: newPosition.pos,
      length: newLength
    },
    originalFileName: documentSpan.fileName,
    originalTextSpan: documentSpan.textSpan,
    contextSpan: getMappedContextSpan(documentSpan, sourceMapper, fileExists),
    originalContextSpan: documentSpan.contextSpan
  };
}
function getMappedContextSpan(documentSpan, sourceMapper, fileExists) {
  const contextSpanStart = documentSpan.contextSpan && getMappedLocation(
    { fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start },
    sourceMapper,
    fileExists
  );
  const contextSpanEnd = documentSpan.contextSpan && getMappedLocation(
    { fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length },
    sourceMapper,
    fileExists
  );
  return contextSpanStart && contextSpanEnd ? { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } : void 0;
}
function isFirstDeclarationOfSymbolParameter(symbol) {
  const declaration = symbol.declarations ? firstOrUndefined(symbol.declarations) : void 0;
  return !!findAncestor(declaration, (n) => isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit");
}
var displayPartWriter = getDisplayPartWriter();
function getDisplayPartWriter() {
  const absoluteMaximumLength = defaultMaximumTruncationLength * 10;
  let displayParts;
  let lineStart;
  let indent3;
  let length2;
  resetWriter();
  const unknownWrite = (text) => writeKind(text, 17 /* text */);
  return {
    displayParts: () => {
      const finalText = displayParts.length && displayParts[displayParts.length - 1].text;
      if (length2 > absoluteMaximumLength && finalText && finalText !== "...") {
        if (!isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) {
          displayParts.push(displayPart(" ", 16 /* space */));
        }
        displayParts.push(displayPart("...", 15 /* punctuation */));
      }
      return displayParts;
    },
    writeKeyword: (text) => writeKind(text, 5 /* keyword */),
    writeOperator: (text) => writeKind(text, 12 /* operator */),
    writePunctuation: (text) => writeKind(text, 15 /* punctuation */),
    writeTrailingSemicolon: (text) => writeKind(text, 15 /* punctuation */),
    writeSpace: (text) => writeKind(text, 16 /* space */),
    writeStringLiteral: (text) => writeKind(text, 8 /* stringLiteral */),
    writeParameter: (text) => writeKind(text, 13 /* parameterName */),
    writeProperty: (text) => writeKind(text, 14 /* propertyName */),
    writeLiteral: (text) => writeKind(text, 8 /* stringLiteral */),
    writeSymbol,
    writeLine,
    write: unknownWrite,
    writeComment: unknownWrite,
    getText: () => "",
    getTextPos: () => 0,
    getColumn: () => 0,
    getLine: () => 0,
    isAtStartOfLine: () => false,
    hasTrailingWhitespace: () => false,
    hasTrailingComment: () => false,
    rawWrite: notImplemented,
    getIndent: () => indent3,
    increaseIndent: () => {
      indent3++;
    },
    decreaseIndent: () => {
      indent3--;
    },
    clear: resetWriter
  };
  function writeIndent() {
    if (length2 > absoluteMaximumLength) return;
    if (lineStart) {
      const indentString = getIndentString(indent3);
      if (indentString) {
        length2 += indentString.length;
        displayParts.push(displayPart(indentString, 16 /* space */));
      }
      lineStart = false;
    }
  }
  function writeKind(text, kind) {
    if (length2 > absoluteMaximumLength) return;
    writeIndent();
    length2 += text.length;
    displayParts.push(displayPart(text, kind));
  }
  function writeSymbol(text, symbol) {
    if (length2 > absoluteMaximumLength) return;
    writeIndent();
    length2 += text.length;
    displayParts.push(symbolPart(text, symbol));
  }
  function writeLine() {
    if (length2 > absoluteMaximumLength) return;
    length2 += 1;
    displayParts.push(lineBreakPart());
    lineStart = true;
  }
  function resetWriter() {
    displayParts = [];
    lineStart = true;
    indent3 = 0;
    length2 = 0;
  }
}
function symbolPart(text, symbol) {
  return displayPart(text, displayPartKind(symbol));
  function displayPartKind(symbol2) {
    const flags = symbol2.flags;
    if (flags & 3 /* Variable */) {
      return isFirstDeclarationOfSymbolParameter(symbol2) ? 13 /* parameterName */ : 9 /* localName */;
    }
    if (flags & 4 /* Property */) return 14 /* propertyName */;
    if (flags & 32768 /* GetAccessor */) return 14 /* propertyName */;
    if (flags & 65536 /* SetAccessor */) return 14 /* propertyName */;
    if (flags & 8 /* EnumMember */) return 19 /* enumMemberName */;
    if (flags & 16 /* Function */) return 20 /* functionName */;
    if (flags & 32 /* Class */) return 1 /* className */;
    if (flags & 64 /* Interface */) return 4 /* interfaceName */;
    if (flags & 384 /* Enum */) return 2 /* enumName */;
    if (flags & 1536 /* Module */) return 11 /* moduleName */;
    if (flags & 8192 /* Method */) return 10 /* methodName */;
    if (flags & 262144 /* TypeParameter */) return 18 /* typeParameterName */;
    if (flags & 524288 /* TypeAlias */) return 0 /* aliasName */;
    if (flags & 2097152 /* Alias */) return 0 /* aliasName */;
    return 17 /* text */;
  }
}
function displayPart(text, kind) {
  return { text, kind: SymbolDisplayPartKind[kind] };
}
function spacePart() {
  return displayPart(" ", 16 /* space */);
}
function keywordPart(kind) {
  return displayPart(tokenToString(kind), 5 /* keyword */);
}
function punctuationPart(kind) {
  return displayPart(tokenToString(kind), 15 /* punctuation */);
}
function operatorPart(kind) {
  return displayPart(tokenToString(kind), 12 /* operator */);
}
function parameterNamePart(text) {
  return displayPart(text, 13 /* parameterName */);
}
function propertyNamePart(text) {
  return displayPart(text, 14 /* propertyName */);
}
function textOrKeywordPart(text) {
  const kind = stringToToken(text);
  return kind === void 0 ? textPart(text) : keywordPart(kind);
}
function textPart(text) {
  return displayPart(text, 17 /* text */);
}
function typeAliasNamePart(text) {
  return displayPart(text, 0 /* aliasName */);
}
function typeParameterNamePart(text) {
  return displayPart(text, 18 /* typeParameterName */);
}
function linkTextPart(text) {
  return displayPart(text, 24 /* linkText */);
}
function linkNamePart(text, target) {
  return {
    text,
    kind: SymbolDisplayPartKind[23 /* linkName */],
    target: {
      fileName: getSourceFileOfNode(target).fileName,
      textSpan: createTextSpanFromNode(target)
    }
  };
}
function linkPart(text) {
  return displayPart(text, 22 /* link */);
}
function buildLinkParts(link, checker) {
  var _a;
  const prefix = isJSDocLink(link) ? "link" : isJSDocLinkCode(link) ? "linkcode" : "linkplain";
  const parts = [linkPart(`{@${prefix} `)];
  if (!link.name) {
    if (link.text) {
      parts.push(linkTextPart(link.text));
    }
  } else {
    const symbol = checker == null ? void 0 : checker.getSymbolAtLocation(link.name);
    const targetSymbol = symbol && checker ? getSymbolTarget(symbol, checker) : void 0;
    const suffix = findLinkNameEnd(link.text);
    const name = getTextOfNode(link.name) + link.text.slice(0, suffix);
    const text = skipSeparatorFromLinkText(link.text.slice(suffix));
    const decl = (targetSymbol == null ? void 0 : targetSymbol.valueDeclaration) || ((_a = targetSymbol == null ? void 0 : targetSymbol.declarations) == null ? void 0 : _a[0]);
    if (decl) {
      parts.push(linkNamePart(name, decl));
      if (text) parts.push(linkTextPart(text));
    } else {
      const separator = suffix === 0 || link.text.charCodeAt(suffix) === 124 /* bar */ && name.charCodeAt(name.length - 1) !== 32 /* space */ ? " " : "";
      parts.push(linkTextPart(name + separator + text));
    }
  }
  parts.push(linkPart("}"));
  return parts;
}
function skipSeparatorFromLinkText(text) {
  let pos = 0;
  if (text.charCodeAt(pos++) === 124 /* bar */) {
    while (pos < text.length && text.charCodeAt(pos) === 32 /* space */) pos++;
    return text.slice(pos);
  }
  return text;
}
function findLinkNameEnd(text) {
  let pos = text.indexOf("://");
  if (pos === 0) {
    while (pos < text.length && text.charCodeAt(pos) !== 124 /* bar */) pos++;
    return pos;
  }
  if (text.indexOf("()") === 0) return 2;
  if (text.charAt(0) === "<") {
    let brackets2 = 0;
    let i = 0;
    while (i < text.length) {
      if (text[i] === "<") brackets2++;
      if (text[i] === ">") brackets2--;
      i++;
      if (!brackets2) return i;
    }
  }
  return 0;
}
var lineFeed2 = "\n";
function getNewLineOrDefaultFromHost(host, formatSettings) {
  var _a;
  return (formatSettings == null ? void 0 : formatSettings.newLineCharacter) || ((_a = host.getNewLine) == null ? void 0 : _a.call(host)) || lineFeed2;
}
function lineBreakPart() {
  return displayPart("\n", 6 /* lineBreak */);
}
function mapToDisplayParts(writeDisplayParts) {
  try {
    writeDisplayParts(displayPartWriter);
    return displayPartWriter.displayParts();
  } finally {
    displayPartWriter.clear();
  }
}
function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags = 0 /* None */) {
  return mapToDisplayParts((writer) => {
    typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer);
  });
}
function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags = 0 /* None */) {
  return mapToDisplayParts((writer) => {
    typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer);
  });
}
function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags = 0 /* None */) {
  flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */;
  return mapToDisplayParts((writer) => {
    typechecker.writeSignature(
      signature,
      enclosingDeclaration,
      flags,
      /*kind*/
      void 0,
      writer
    );
  });
}
function isImportOrExportSpecifierName(location) {
  return !!location.parent && isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location;
}
function getScriptKind(fileName, host) {
  return ensureScriptKind(fileName, host.getScriptKind && host.getScriptKind(fileName));
}
function getSymbolTarget(symbol, checker) {
  let next = symbol;
  while (isAliasSymbol(next) || isTransientSymbol(next) && next.links.target) {
    if (isTransientSymbol(next) && next.links.target) {
      next = next.links.target;
    } else {
      next = skipAlias(next, checker);
    }
  }
  return next;
}
function isAliasSymbol(symbol) {
  return (symbol.flags & 2097152 /* Alias */) !== 0;
}
function getUniqueSymbolId(symbol, checker) {
  return getSymbolId(skipAlias(symbol, checker));
}
function getFirstNonSpaceCharacterPosition(text, position) {
  while (isWhiteSpaceLike(text.charCodeAt(position))) {
    position += 1;
  }
  return position;
}
function getPrecedingNonSpaceCharacterPosition(text, position) {
  while (position > -1 && isWhiteSpaceSingleLine(text.charCodeAt(position))) {
    position -= 1;
  }
  return position + 1;
}
function getSynthesizedDeepClone(node, includeTrivia = true) {
  const clone2 = node && getSynthesizedDeepCloneWorker(node);
  if (clone2 && !includeTrivia) suppressLeadingAndTrailingTrivia(clone2);
  return setParentRecursive(
    clone2,
    /*incremental*/
    false
  );
}
function getSynthesizedDeepCloneWithReplacements(node, includeTrivia, replaceNode) {
  let clone2 = replaceNode(node);
  if (clone2) {
    setOriginalNode(clone2, node);
  } else {
    clone2 = getSynthesizedDeepCloneWorker(node, replaceNode);
  }
  if (clone2 && !includeTrivia) suppressLeadingAndTrailingTrivia(clone2);
  return clone2;
}
function getSynthesizedDeepCloneWorker(node, replaceNode) {
  const nodeClone = replaceNode ? (n) => getSynthesizedDeepCloneWithReplacements(
    n,
    /*includeTrivia*/
    true,
    replaceNode
  ) : getSynthesizedDeepClone;
  const nodesClone = replaceNode ? (ns) => ns && getSynthesizedDeepClonesWithReplacements(
    ns,
    /*includeTrivia*/
    true,
    replaceNode
  ) : (ns) => ns && getSynthesizedDeepClones(ns);
  const visited = visitEachChild(
    node,
    nodeClone,
    /*context*/
    void 0,
    nodesClone,
    nodeClone
  );
  if (visited === node) {
    const clone2 = isStringLiteral(node) ? setOriginalNode(factory.createStringLiteralFromNode(node), node) : isNumericLiteral(node) ? setOriginalNode(factory.createNumericLiteral(node.text, node.numericLiteralFlags), node) : factory.cloneNode(node);
    return setTextRange(clone2, node);
  }
  visited.parent = void 0;
  return visited;
}
function getSynthesizedDeepClones(nodes, includeTrivia = true) {
  if (nodes) {
    const cloned = factory.createNodeArray(nodes.map((n) => getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma);
    setTextRange(cloned, nodes);
    return cloned;
  }
  return nodes;
}
function getSynthesizedDeepClonesWithReplacements(nodes, includeTrivia, replaceNode) {
  return factory.createNodeArray(nodes.map((n) => getSynthesizedDeepCloneWithReplacements(n, includeTrivia, replaceNode)), nodes.hasTrailingComma);
}
function suppressLeadingAndTrailingTrivia(node) {
  suppressLeadingTrivia(node);
  suppressTrailingTrivia(node);
}
function suppressLeadingTrivia(node) {
  addEmitFlagsRecursively(node, 1024 /* NoLeadingComments */, getFirstChild);
}
function suppressTrailingTrivia(node) {
  addEmitFlagsRecursively(node, 2048 /* NoTrailingComments */, getLastChild);
}
function copyComments(sourceNode, targetNode) {
  const sourceFile = sourceNode.getSourceFile();
  const text = sourceFile.text;
  if (hasLeadingLineBreak(sourceNode, text)) {
    copyLeadingComments(sourceNode, targetNode, sourceFile);
  } else {
    copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
  }
  copyTrailingComments(sourceNode, targetNode, sourceFile);
}
function hasLeadingLineBreak(node, text) {
  const start = node.getFullStart();
  const end = node.getStart();
  for (let i = start; i < end; i++) {
    if (text.charCodeAt(i) === 10 /* lineFeed */) return true;
  }
  return false;
}
function addEmitFlagsRecursively(node, flag, getChild) {
  addEmitFlags(node, flag);
  const child = getChild(node);
  if (child) addEmitFlagsRecursively(child, flag, getChild);
}
function getFirstChild(node) {
  return node.forEachChild((child) => child);
}
function getUniqueName(baseName, sourceFile) {
  let nameText = baseName;
  for (let i = 1; !isFileLevelUniqueName(sourceFile, nameText); i++) {
    nameText = `${baseName}_${i}`;
  }
  return nameText;
}
function getRenameLocation(edits, renameFilename, name, preferLastLocation) {
  let delta = 0;
  let lastPos = -1;
  for (const { fileName, textChanges: textChanges2 } of edits) {
    Debug.assert(fileName === renameFilename);
    for (const change of textChanges2) {
      const { span, newText } = change;
      const index = indexInTextChange(newText, escapeString(name));
      if (index !== -1) {
        lastPos = span.start + delta + index;
        if (!preferLastLocation) {
          return lastPos;
        }
      }
      delta += newText.length - span.length;
    }
  }
  Debug.assert(preferLastLocation);
  Debug.assert(lastPos >= 0);
  return lastPos;
}
function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
  forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticLeadingComment));
}
function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
  forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticTrailingComment));
}
function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
  forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticLeadingComment));
}
function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
  return (pos, end, kind, htnl) => {
    if (kind === 3 /* MultiLineCommentTrivia */) {
      pos += 2;
      end -= 2;
    } else {
      pos += 2;
    }
    cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== void 0 ? hasTrailingNewLine : htnl);
  };
}
function indexInTextChange(change, name) {
  if (startsWith(change, name)) return 0;
  let idx = change.indexOf(" " + name);
  if (idx === -1) idx = change.indexOf("." + name);
  if (idx === -1) idx = change.indexOf('"' + name);
  return idx === -1 ? -1 : idx + 1;
}
function needsParentheses(expression) {
  return isBinaryExpression(expression) && expression.operatorToken.kind === 28 /* CommaToken */ || isObjectLiteralExpression(expression) || (isAsExpression(expression) || isSatisfiesExpression(expression)) && isObjectLiteralExpression(expression.expression);
}
function getContextualTypeFromParent(node, checker, contextFlags) {
  const parent2 = walkUpParenthesizedExpressions(node.parent);
  switch (parent2.kind) {
    case 214 /* NewExpression */:
      return checker.getContextualType(parent2, contextFlags);
    case 226 /* BinaryExpression */: {
      const { left, operatorToken, right } = parent2;
      return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node, contextFlags);
    }
    case 296 /* CaseClause */:
      return getSwitchedType(parent2, checker);
    default:
      return checker.getContextualType(node, contextFlags);
  }
}
function quote(sourceFile, preferences, text) {
  const quotePreference = getQuotePreference(sourceFile, preferences);
  const quoted = JSON.stringify(text);
  return quotePreference === 0 /* Single */ ? `'${stripQuotes(quoted).replace(/'/g, () => "\\'").replace(/\\"/g, '"')}'` : quoted;
}
function isEqualityOperatorKind(kind) {
  switch (kind) {
    case 37 /* EqualsEqualsEqualsToken */:
    case 35 /* EqualsEqualsToken */:
    case 38 /* ExclamationEqualsEqualsToken */:
    case 36 /* ExclamationEqualsToken */:
      return true;
    default:
      return false;
  }
}
function isStringLiteralOrTemplate(node) {
  switch (node.kind) {
    case 11 /* StringLiteral */:
    case 15 /* NoSubstitutionTemplateLiteral */:
    case 228 /* TemplateExpression */:
    case 215 /* TaggedTemplateExpression */:
      return true;
    default:
      return false;
  }
}
function hasIndexSignature(type) {
  return !!type.getStringIndexType() || !!type.getNumberIndexType();
}
function getSwitchedType(caseClause, checker) {
  return checker.getTypeAtLocation(caseClause.parent.parent.expression);
}
var ANONYMOUS = "anonymous function";
function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
  const checker = program.getTypeChecker();
  let typeIsAccessible = true;
  const notAccessible = () => typeIsAccessible = false;
  const res = checker.typeToTypeNode(type, enclosingScope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */, {
    trackSymbol: (symbol, declaration, meaning) => {
      typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(
        symbol,
        declaration,
        meaning,
        /*shouldComputeAliasToMarkVisible*/
        false
      ).accessibility === 0 /* Accessible */;
      return !typeIsAccessible;
    },
    reportInaccessibleThisError: notAccessible,
    reportPrivateInBaseOfClassExpression: notAccessible,
    reportInaccessibleUniqueSymbolError: notAccessible,
    moduleResolverHost: getModuleSpecifierResolverHost(program, host)
  });
  return typeIsAccessible ? res : void 0;
}
function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) {
  return kind === 179 /* CallSignature */ || kind === 180 /* ConstructSignature */ || kind === 181 /* IndexSignature */ || kind === 171 /* PropertySignature */ || kind === 173 /* MethodSignature */;
}
function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) {
  return kind === 262 /* FunctionDeclaration */ || kind === 176 /* Constructor */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */;
}
function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) {
  return kind === 267 /* ModuleDeclaration */;
}
function syntaxRequiresTrailingSemicolonOrASI(kind) {
  return kind === 243 /* VariableStatement */ || kind === 244 /* ExpressionStatement */ || kind === 246 /* DoStatement */ || kind === 251 /* ContinueStatement */ || kind === 252 /* BreakStatement */ || kind === 253 /* ReturnStatement */ || kind === 257 /* ThrowStatement */ || kind === 259 /* DebuggerStatement */ || kind === 172 /* PropertyDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 278 /* ExportDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 277 /* ExportAssignment */;
}
var syntaxMayBeASICandidate = or(
  syntaxRequiresTrailingCommaOrSemicolonOrASI,
  syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI,
  syntaxRequiresTrailingModuleBlockOrSemicolonOrASI,
  syntaxRequiresTrailingSemicolonOrASI
);
function nodeIsASICandidate(node, sourceFile) {
  const lastToken = node.getLastToken(sourceFile);
  if (lastToken && lastToken.kind === 27 /* SemicolonToken */) {
    return false;
  }
  if (syntaxRequiresTrailingCommaOrSemicolonOrASI(node.kind)) {
    if (lastToken && lastToken.kind === 28 /* CommaToken */) {
      return false;
    }
  } else if (syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(node.kind)) {
    const lastChild = last(node.getChildren(sourceFile));
    if (lastChild && isModuleBlock(lastChild)) {
      return false;
    }
  } else if (syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(node.kind)) {
    const lastChild = last(node.getChildren(sourceFile));
    if (lastChild && isFunctionBlock(lastChild)) {
      return false;
    }
  } else if (!syntaxRequiresTrailingSemicolonOrASI(node.kind)) {
    return false;
  }
  if (node.kind === 246 /* DoStatement */) {
    return true;
  }
  const topNode = findAncestor(node, (ancestor) => !ancestor.parent);
  const nextToken = findNextToken(node, topNode, sourceFile);
  if (!nextToken || nextToken.kind === 20 /* CloseBraceToken */) {
    return true;
  }
  const startLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
  const endLine = sourceFile.getLineAndCharacterOfPosition(nextToken.getStart(sourceFile)).line;
  return startLine !== endLine;
}
function positionIsASICandidate(pos, context, sourceFile) {
  const contextAncestor = findAncestor(context, (ancestor) => {
    if (ancestor.end !== pos) {
      return "quit";
    }
    return syntaxMayBeASICandidate(ancestor.kind);
  });
  return !!contextAncestor && nodeIsASICandidate(contextAncestor, sourceFile);
}
function probablyUsesSemicolons(sourceFile) {
  let withSemicolon = 0;
  let withoutSemicolon = 0;
  const nStatementsToObserve = 5;
  forEachChild(sourceFile, function visit(node) {
    if (syntaxRequiresTrailingSemicolonOrASI(node.kind)) {
      const lastToken = node.getLastToken(sourceFile);
      if ((lastToken == null ? void 0 : lastToken.kind) === 27 /* SemicolonToken */) {
        withSemicolon++;
      } else {
        withoutSemicolon++;
      }
    } else if (syntaxRequiresTrailingCommaOrSemicolonOrASI(node.kind)) {
      const lastToken = node.getLastToken(sourceFile);
      if ((lastToken == null ? void 0 : lastToken.kind) === 27 /* SemicolonToken */) {
        withSemicolon++;
      } else if (lastToken && lastToken.kind !== 28 /* CommaToken */) {
        const lastTokenLine = getLineAndCharacterOfPosition(sourceFile, lastToken.getStart(sourceFile)).line;
        const nextTokenLine = getLineAndCharacterOfPosition(sourceFile, getSpanOfTokenAtPosition(sourceFile, lastToken.end).start).line;
        if (lastTokenLine !== nextTokenLine) {
          withoutSemicolon++;
        }
      }
    }
    if (withSemicolon + withoutSemicolon >= nStatementsToObserve) {
      return true;
    }
    return forEachChild(node, visit);
  });
  if (withSemicolon === 0 && withoutSemicolon <= 1) {
    return true;
  }
  return withSemicolon / withoutSemicolon > 1 / nStatementsToObserve;
}
function tryGetDirectories(host, directoryName) {
  return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || [];
}
function tryReadDirectory(host, path, extensions, exclude, include) {
  return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || emptyArray;
}
function tryFileExists(host, path) {
  return tryIOAndConsumeErrors(host, host.fileExists, path);
}
function tryDirectoryExists(host, path) {
  return tryAndIgnoreErrors(() => directoryProbablyExists(path, host)) || false;
}
function tryAndIgnoreErrors(cb) {
  try {
    return cb();
  } catch {
    return void 0;
  }
}
function tryIOAndConsumeErrors(host, toApply, ...args) {
  return tryAndIgnoreErrors(() => toApply && toApply.apply(host, args));
}
function findPackageJsons(startDirectory, host) {
  const paths = [];
  forEachAncestorDirectoryStoppingAtGlobalCache(
    host,
    startDirectory,
    (ancestor) => {
      const currentConfigPath = combinePaths(ancestor, "package.json");
      if (tryFileExists(host, currentConfigPath)) {
        paths.push(currentConfigPath);
      }
    }
  );
  return paths;
}
function findPackageJson(directory, host) {
  let packageJson;
  forEachAncestorDirectoryStoppingAtGlobalCache(
    host,
    directory,
    (ancestor) => {
      if (ancestor === "node_modules") return true;
      packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json");
      if (packageJson) {
        return true;
      }
    }
  );
  return packageJson;
}
function getPackageJsonsVisibleToFile(fileName, host) {
  if (!host.fileExists) {
    return [];
  }
  const packageJsons = [];
  forEachAncestorDirectoryStoppingAtGlobalCache(
    host,
    getDirectoryPath(fileName),
    (ancestor) => {
      const packageJsonFileName = combinePaths(ancestor, "package.json");
      if (host.fileExists(packageJsonFileName)) {
        const info = createPackageJsonInfo(packageJsonFileName, host);
        if (info) {
          packageJsons.push(info);
        }
      }
    }
  );
  return packageJsons;
}
function createPackageJsonInfo(fileName, host) {
  if (!host.readFile) {
    return void 0;
  }
  const dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
  const stringContent = host.readFile(fileName) || "";
  const content = tryParseJson(stringContent);
  const info = {};
  if (content) {
    for (const key of dependencyKeys) {
      const dependencies = content[key];
      if (!dependencies) {
        continue;
      }
      const dependencyMap = /* @__PURE__ */ new Map();
      for (const packageName in dependencies) {
        dependencyMap.set(packageName, dependencies[packageName]);
      }
      info[key] = dependencyMap;
    }
  }
  const dependencyGroups = [
    [1 /* Dependencies */, info.dependencies],
    [2 /* DevDependencies */, info.devDependencies],
    [8 /* OptionalDependencies */, info.optionalDependencies],
    [4 /* PeerDependencies */, info.peerDependencies]
  ];
  return {
    ...info,
    parseable: !!content,
    fileName,
    get,
    has(dependencyName, inGroups) {
      return !!get(dependencyName, inGroups);
    }
  };
  function get(dependencyName, inGroups = 15 /* All */) {
    for (const [group2, deps] of dependencyGroups) {
      if (deps && inGroups & group2) {
        const dep = deps.get(dependencyName);
        if (dep !== void 0) {
          return dep;
        }
      }
    }
  }
}
function createPackageJsonImportFilter(fromFile, preferences, host) {
  const packageJsons = (host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName) || getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter((p) => p.parseable);
  let usesNodeCoreModules;
  let ambientModuleCache;
  let sourceFileCache;
  return {
    allowsImportingAmbientModule,
    getSourceFileInfo,
    allowsImportingSpecifier
  };
  function moduleSpecifierIsCoveredByPackageJson(specifier) {
    const packageName = getNodeModuleRootSpecifier(specifier);
    for (const packageJson of packageJsons) {
      if (packageJson.has(packageName) || packageJson.has(getTypesPackageName(packageName))) {
        return true;
      }
    }
    return false;
  }
  function allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost) {
    if (!packageJsons.length || !moduleSymbol.valueDeclaration) {
      return true;
    }
    if (!ambientModuleCache) {
      ambientModuleCache = /* @__PURE__ */ new Map();
    } else {
      const cached = ambientModuleCache.get(moduleSymbol);
      if (cached !== void 0) {
        return cached;
      }
    }
    const declaredModuleSpecifier = stripQuotes(moduleSymbol.getName());
    if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) {
      ambientModuleCache.set(moduleSymbol, true);
      return true;
    }
    const declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile();
    const declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName, moduleSpecifierResolutionHost);
    if (typeof declaringNodeModuleName === "undefined") {
      ambientModuleCache.set(moduleSymbol, true);
      return true;
    }
    const result = moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier);
    ambientModuleCache.set(moduleSymbol, result);
    return result;
  }
  function getSourceFileInfo(sourceFile, moduleSpecifierResolutionHost) {
    if (!packageJsons.length) {
      return { importable: true, packageName: void 0 };
    }
    if (!sourceFileCache) {
      sourceFileCache = /* @__PURE__ */ new Map();
    } else {
      const cached = sourceFileCache.get(sourceFile);
      if (cached !== void 0) {
        return cached;
      }
    }
    const packageName = getNodeModulesPackageNameFromFileName(sourceFile.fileName, moduleSpecifierResolutionHost);
    if (!packageName) {
      const result2 = { importable: true, packageName };
      sourceFileCache.set(sourceFile, result2);
      return result2;
    }
    const importable = moduleSpecifierIsCoveredByPackageJson(packageName);
    const result = { importable, packageName };
    sourceFileCache.set(sourceFile, result);
    return result;
  }
  function allowsImportingSpecifier(moduleSpecifier) {
    if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) {
      return true;
    }
    if (pathIsRelative(moduleSpecifier) || isRootedDiskPath(moduleSpecifier)) {
      return true;
    }
    return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier);
  }
  function isAllowedCoreNodeModulesImport(moduleSpecifier) {
    if (isFullSourceFile(fromFile) && isSourceFileJS(fromFile) && nodeCoreModules.has(moduleSpecifier)) {
      if (usesNodeCoreModules === void 0) {
        usesNodeCoreModules = consumesNodeCoreModules(fromFile);
      }
      if (usesNodeCoreModules) {
        return true;
      }
    }
    return false;
  }
  function getNodeModulesPackageNameFromFileName(importedFileName, moduleSpecifierResolutionHost) {
    if (!importedFileName.includes("node_modules")) {
      return void 0;
    }
    const specifier = ts_moduleSpecifiers_exports.getNodeModulesPackageName(
      host.getCompilationSettings(),
      fromFile,
      importedFileName,
      moduleSpecifierResolutionHost,
      preferences
    );
    if (!specifier) {
      return void 0;
    }
    if (!pathIsRelative(specifier) && !isRootedDiskPath(specifier)) {
      return getNodeModuleRootSpecifier(specifier);
    }
  }
  function getNodeModuleRootSpecifier(fullSpecifier) {
    const components = getPathComponents(getPackageNameFromTypesPackageName(fullSpecifier)).slice(1);
    if (startsWith(components[0], "@")) {
      return `${components[0]}/${components[1]}`;
    }
    return components[0];
  }
}
function consumesNodeCoreModules(sourceFile) {
  return some(sourceFile.imports, ({ text }) => nodeCoreModules.has(text));
}
function isInsideNodeModules(fileOrDirectory) {
  return contains(getPathComponents(fileOrDirectory), "node_modules");
}
function isDiagnosticWithLocation(diagnostic) {
  return diagnostic.file !== void 0 && diagnostic.start !== void 0 && diagnostic.length !== void 0;
}
function findDiagnosticForNode(node, sortedFileDiagnostics) {
  const span = createTextSpanFromNode(node);
  const index = binarySearchKey(sortedFileDiagnostics, span, identity, compareTextSpans);
  if (index >= 0) {
    const diagnostic = sortedFileDiagnostics[index];
    Debug.assertEqual(diagnostic.file, node.getSourceFile(), "Diagnostics proided to 'findDiagnosticForNode' must be from a single SourceFile");
    return cast(diagnostic, isDiagnosticWithLocation);
  }
}
function getDiagnosticsWithinSpan(span, sortedFileDiagnostics) {
  var _a;
  let index = binarySearchKey(sortedFileDiagnostics, span.start, (diag2) => diag2.start, compareValues);
  if (index < 0) {
    index = ~index;
  }
  while (((_a = sortedFileDiagnostics[index - 1]) == null ? void 0 : _a.start) === span.start) {
    index--;
  }
  const result = [];
  const end = textSpanEnd(span);
  while (true) {
    const diagnostic = tryCast(sortedFileDiagnostics[index], isDiagnosticWithLocation);
    if (!diagnostic || diagnostic.start > end) {
      break;
    }
    if (textSpanContainsTextSpan(span, diagnostic)) {
      result.push(diagnostic);
    }
    index++;
  }
  return result;
}
function getRefactorContextSpan({ startPosition, endPosition }) {
  return createTextSpanFromBounds(startPosition, endPosition === void 0 ? startPosition : endPosition);
}
function getFixableErrorSpanExpression(sourceFile, span) {
  const token = getTokenAtPosition(sourceFile, span.start);
  const expression = findAncestor(token, (node) => {
    if (node.getStart(sourceFile) < span.start || node.getEnd() > textSpanEnd(span)) {
      return "quit";
    }
    return isExpression(node) && textSpansEqual(span, createTextSpanFromNode(node, sourceFile));
  });
  return expression;
}
function mapOneOrMany(valueOrArray, f, resultSelector = identity) {
  return valueOrArray ? isArray(valueOrArray) ? resultSelector(map(valueOrArray, f)) : f(valueOrArray, 0) : void 0;
}
function firstOrOnly(valueOrArray) {
  return isArray(valueOrArray) ? first(valueOrArray) : valueOrArray;
}
function getNameForExportedSymbol(symbol, scriptTarget, preferCapitalized) {
  if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) {
    return getDefaultLikeExportNameFromDeclaration(symbol) || moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, !!preferCapitalized);
  }
  return symbol.name;
}
function getDefaultLikeExportNameFromDeclaration(symbol) {
  return firstDefined(symbol.declarations, (d) => {
    var _a, _b, _c;
    if (isExportAssignment(d)) {
      return (_a = tryCast(skipOuterExpressions(d.expression), isIdentifier)) == null ? void 0 : _a.text;
    }
    if (isExportSpecifier(d) && d.symbol.flags === 2097152 /* Alias */) {
      return (_b = tryCast(d.propertyName, isIdentifier)) == null ? void 0 : _b.text;
    }
    const name = (_c = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _c.text;
    if (name) {
      return name;
    }
    if (symbol.parent && !isExternalModuleSymbol(symbol.parent)) {
      return symbol.parent.getName();
    }
  });
}
function getSymbolParentOrFail(symbol) {
  var _a;
  return Debug.checkDefined(
    symbol.parent,
    `Symbol parent was undefined. Flags: ${Debug.formatSymbolFlags(symbol.flags)}. Declarations: ${(_a = symbol.declarations) == null ? void 0 : _a.map((d) => {
      const kind = Debug.formatSyntaxKind(d.kind);
      const inJS = isInJSFile(d);
      const { expression } = d;
      return (inJS ? "[JS]" : "") + kind + (expression ? ` (expression: ${Debug.formatSyntaxKind(expression.kind)})` : "");
    }).join(", ")}.`
  );
}
function moduleSymbolToValidIdentifier(moduleSymbol, target, forceCapitalize) {
  return moduleSpecifierToValidIdentifier(removeFileExtension(stripQuotes(moduleSymbol.name)), target, forceCapitalize);
}
function moduleSpecifierToValidIdentifier(moduleSpecifier, target, forceCapitalize) {
  const baseName = getBaseFileName(removeSuffix(moduleSpecifier, "/index"));
  let res = "";
  let lastCharWasValid = true;
  const firstCharCode = baseName.charCodeAt(0);
  if (isIdentifierStart(firstCharCode, target)) {
    res += String.fromCharCode(firstCharCode);
    if (forceCapitalize) {
      res = res.toUpperCase();
    }
  } else {
    lastCharWasValid = false;
  }
  for (let i = 1; i < baseName.length; i++) {
    const ch = baseName.charCodeAt(i);
    const isValid = isIdentifierPart(ch, target);
    if (isValid) {
      let char = String.fromCharCode(ch);
      if (!lastCharWasValid) {
        char = char.toUpperCase();
      }
      res += char;
    }
    lastCharWasValid = isValid;
  }
  return !isStringANonContextualKeyword(res) ? res || "_" : `_${res}`;
}
function stringContainsAt(haystack, needle, startIndex) {
  const needleLength = needle.length;
  if (needleLength + startIndex > haystack.length) {
    return false;
  }
  for (let i = 0; i < needleLength; i++) {
    if (needle.charCodeAt(i) !== haystack.charCodeAt(i + startIndex)) return false;
  }
  return true;
}
function startsWithUnderscore(name) {
  return name.charCodeAt(0) === 95 /* _ */;
}
function isDeprecatedDeclaration(decl) {
  return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & 65536 /* Deprecated */);
}
function shouldUseUriStyleNodeCoreModules(file, program) {
  let decisionFromFile;
  for (const node of file.imports) {
    if (nodeCoreModules.has(node.text) && !exclusivelyPrefixedNodeCoreModules.has(node.text)) {
      if (startsWith(node.text, "node:")) {
        return true;
      } else {
        decisionFromFile = false;
      }
    }
  }
  return decisionFromFile ?? program.usesUriStyleNodeCoreModules;
}
function getNewLineKind(newLineCharacter) {
  return newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */;
}
function diagnosticToString(diag2) {
  return isArray(diag2) ? formatStringFromArgs(getLocaleSpecificMessage(diag2[0]), diag2.slice(1)) : getLocaleSpecificMessage(diag2);
}
function getFormatCodeSettingsForWriting({ options }, sourceFile) {
  const shouldAutoDetectSemicolonPreference = !options.semicolons || options.semicolons === "ignore" /* Ignore */;
  const shouldRemoveSemicolons = options.semicolons === "remove" /* Remove */ || shouldAutoDetectSemicolonPreference && !probablyUsesSemicolons(sourceFile);
  return {
    ...options,
    semicolons: shouldRemoveSemicolons ? "remove" /* Remove */ : "ignore" /* Ignore */
  };
}
function jsxModeNeedsExplicitImport(jsx) {
  return jsx === 2 /* React */ || jsx === 3 /* ReactNative */;
}
function isSourceFileFromLibrary(program, node) {
  return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node);
}
function newCaseClauseTracker(checker, clauses) {
  const existingStrings = /* @__PURE__ */ new Set();
  const existingNumbers = /* @__PURE__ */ new Set();
  const existingBigInts = /* @__PURE__ */ new Set();
  for (const clause of clauses) {
    if (!isDefaultClause(clause)) {
      const expression = skipParentheses(clause.expression);
      if (isLiteralExpression(expression)) {
        switch (expression.kind) {
          case 15 /* NoSubstitutionTemplateLiteral */:
          case 11 /* StringLiteral */:
            existingStrings.add(expression.text);
            break;
          case 9 /* NumericLiteral */:
            existingNumbers.add(parseInt(expression.text));
            break;
          case 10 /* BigIntLiteral */:
            const parsedBigInt = parseBigInt(endsWith(expression.text, "n") ? expression.text.slice(0, -1) : expression.text);
            if (parsedBigInt) {
              existingBigInts.add(pseudoBigIntToString(parsedBigInt));
            }
            break;
        }
      } else {
        const symbol = checker.getSymbolAtLocation(clause.expression);
        if (symbol && symbol.valueDeclaration && isEnumMember(symbol.valueDeclaration)) {
          const enumValue = checker.getConstantValue(symbol.valueDeclaration);
          if (enumValue !== void 0) {
            addValue(enumValue);
          }
        }
      }
    }
  }
  return {
    addValue,
    hasValue
  };
  function addValue(value) {
    switch (typeof value) {
      case "string":
        existingStrings.add(value);
        break;
      case "number":
        existingNumbers.add(value);
    }
  }
  function hasValue(value) {
    switch (typeof value) {
      case "string":
        return existingStrings.has(value);
      case "number":
        return existingNumbers.has(value);
      case "object":
        return existingBigInts.has(pseudoBigIntToString(value));
    }
  }
}
function fileShouldUseJavaScriptRequire(file, program, host, preferRequire) {
  var _a;
  const fileName = typeof file === "string" ? file : file.fileName;
  if (!hasJSFileExtension(fileName)) {
    return false;
  }
  const compilerOptions = typeof file === "string" ? program.getCompilerOptions() : program.getCompilerOptionsForFile(file);
  const moduleKind = getEmitModuleKind(compilerOptions);
  const sourceFileLike = typeof file === "string" ? {
    fileName: file,
    impliedNodeFormat: getImpliedNodeFormatForFile(toPath(file, host.getCurrentDirectory(), hostGetCanonicalFileName(host)), (_a = program.getPackageJsonInfoCache) == null ? void 0 : _a.call(program), host, compilerOptions)
  } : file;
  const impliedNodeFormat = getImpliedNodeFormatForEmitWorker(sourceFileLike, compilerOptions);
  if (impliedNodeFormat === 99 /* ESNext */) {
    return false;
  }
  if (impliedNodeFormat === 1 /* CommonJS */) {
    return true;
  }
  if (compilerOptions.verbatimModuleSyntax && moduleKind === 1 /* CommonJS */) {
    return true;
  }
  if (compilerOptions.verbatimModuleSyntax && emitModuleKindIsNonNodeESM(moduleKind)) {
    return false;
  }
  if (typeof file === "object") {
    if (file.commonJsModuleIndicator) {
      return true;
    }
    if (file.externalModuleIndicator) {
      return false;
    }
  }
  return preferRequire;
}
function isBlockLike(node) {
  switch (node.kind) {
    case 241 /* Block */:
    case 307 /* SourceFile */:
    case 268 /* ModuleBlock */:
    case 296 /* CaseClause */:
      return true;
    default:
      return false;
  }
}
function createFutureSourceFile(fileName, syntaxModuleIndicator, program, moduleResolutionHost) {
  var _a;
  const result = getImpliedNodeFormatForFileWorker(fileName, (_a = program.getPackageJsonInfoCache) == null ? void 0 : _a.call(program), moduleResolutionHost, program.getCompilerOptions());
  let impliedNodeFormat, packageJsonScope;
  if (typeof result === "object") {
    impliedNodeFormat = result.impliedNodeFormat;
    packageJsonScope = result.packageJsonScope;
  }
  return {
    path: toPath(fileName, program.getCurrentDirectory(), program.getCanonicalFileName),
    fileName,
    externalModuleIndicator: syntaxModuleIndicator === 99 /* ESNext */ ? true : void 0,
    commonJsModuleIndicator: syntaxModuleIndicator === 1 /* CommonJS */ ? true : void 0,
    impliedNodeFormat,
    packageJsonScope,
    statements: emptyArray,
    imports: emptyArray
  };
}

// src/services/exportInfoMap.ts
var ImportKind = /* @__PURE__ */ ((ImportKind2) => {
  ImportKind2[ImportKind2["Named"] = 0] = "Named";
  ImportKind2[ImportKind2["Default"] = 1] = "Default";
  ImportKind2[ImportKind2["Namespace"] = 2] = "Namespace";
  ImportKind2[ImportKind2["CommonJS"] = 3] = "CommonJS";
  return ImportKind2;
})(ImportKind || {});
var ExportKind = /* @__PURE__ */ ((ExportKind3) => {
  ExportKind3[ExportKind3["Named"] = 0] = "Named";
  ExportKind3[ExportKind3["Default"] = 1] = "Default";
  ExportKind3[ExportKind3["ExportEquals"] = 2] = "ExportEquals";
  ExportKind3[ExportKind3["UMD"] = 3] = "UMD";
  ExportKind3[ExportKind3["Module"] = 4] = "Module";
  return ExportKind3;
})(ExportKind || {});
function createCacheableExportInfoMap(host) {
  let exportInfoId = 1;
  const exportInfo = createMultiMap();
  const symbols = /* @__PURE__ */ new Map();
  const packages = /* @__PURE__ */ new Map();
  let usableByFileName;
  const cache = {
    isUsableByFile: (importingFile) => importingFile === usableByFileName,
    isEmpty: () => !exportInfo.size,
    clear: () => {
      exportInfo.clear();
      symbols.clear();
      usableByFileName = void 0;
    },
    add: (importingFile, symbol, symbolTableKey, moduleSymbol, moduleFile, exportKind, isFromPackageJson, checker) => {
      if (importingFile !== usableByFileName) {
        cache.clear();
        usableByFileName = importingFile;
      }
      let packageName;
      if (moduleFile) {
        const nodeModulesPathParts = getNodeModulePathParts(moduleFile.fileName);
        if (nodeModulesPathParts) {
          const { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex } = nodeModulesPathParts;
          packageName = unmangleScopedPackageName(getPackageNameFromTypesPackageName(moduleFile.fileName.substring(topLevelPackageNameIndex + 1, packageRootIndex)));
          if (startsWith(importingFile, moduleFile.path.substring(0, topLevelNodeModulesIndex))) {
            const prevDeepestNodeModulesPath = packages.get(packageName);
            const nodeModulesPath = moduleFile.fileName.substring(0, topLevelPackageNameIndex + 1);
            if (prevDeepestNodeModulesPath) {
              const prevDeepestNodeModulesIndex = prevDeepestNodeModulesPath.indexOf(nodeModulesPathPart);
              if (topLevelNodeModulesIndex > prevDeepestNodeModulesIndex) {
                packages.set(packageName, nodeModulesPath);
              }
            } else {
              packages.set(packageName, nodeModulesPath);
            }
          }
        }
      }
      const isDefault = exportKind === 1 /* Default */;
      const namedSymbol = isDefault && getLocalSymbolForExportDefault(symbol) || symbol;
      const names = exportKind === 0 /* Named */ || isExternalModuleSymbol(namedSymbol) ? unescapeLeadingUnderscores(symbolTableKey) : getNamesForExportedSymbol(
        namedSymbol,
        checker,
        /*scriptTarget*/
        void 0
      );
      const symbolName2 = typeof names === "string" ? names : names[0];
      const capitalizedSymbolName = typeof names === "string" ? void 0 : names[1];
      const moduleName = stripQuotes(moduleSymbol.name);
      const id = exportInfoId++;
      const target = skipAlias(symbol, checker);
      const storedSymbol = symbol.flags & 33554432 /* Transient */ ? void 0 : symbol;
      const storedModuleSymbol = moduleSymbol.flags & 33554432 /* Transient */ ? void 0 : moduleSymbol;
      if (!storedSymbol || !storedModuleSymbol) symbols.set(id, [symbol, moduleSymbol]);
      exportInfo.add(key(symbolName2, symbol, isExternalModuleNameRelative(moduleName) ? void 0 : moduleName, checker), {
        id,
        symbolTableKey,
        symbolName: symbolName2,
        capitalizedSymbolName,
        moduleName,
        moduleFile,
        moduleFileName: moduleFile == null ? void 0 : moduleFile.fileName,
        packageName,
        exportKind,
        targetFlags: target.flags,
        isFromPackageJson,
        symbol: storedSymbol,
        moduleSymbol: storedModuleSymbol
      });
    },
    get: (importingFile, key2) => {
      if (importingFile !== usableByFileName) return;
      const result = exportInfo.get(key2);
      return result == null ? void 0 : result.map(rehydrateCachedInfo);
    },
    search: (importingFile, preferCapitalized, matches, action) => {
      if (importingFile !== usableByFileName) return;
      return forEachEntry(exportInfo, (info, key2) => {
        const { symbolName: symbolName2, ambientModuleName } = parseKey(key2);
        const name = preferCapitalized && info[0].capitalizedSymbolName || symbolName2;
        if (matches(name, info[0].targetFlags)) {
          const rehydrated = info.map(rehydrateCachedInfo);
          const filtered = rehydrated.filter((r, i) => isNotShadowedByDeeperNodeModulesPackage(r, info[i].packageName));
          if (filtered.length) {
            const res = action(filtered, name, !!ambientModuleName, key2);
            if (res !== void 0) return res;
          }
        }
      });
    },
    releaseSymbols: () => {
      symbols.clear();
    },
    onFileChanged: (oldSourceFile, newSourceFile, typeAcquisitionEnabled) => {
      if (fileIsGlobalOnly(oldSourceFile) && fileIsGlobalOnly(newSourceFile)) {
        return false;
      }
      if (usableByFileName && usableByFileName !== newSourceFile.path || // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node.
      // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list.
      typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) || // Module agumentation and ambient module changes can add or remove exports available to be auto-imported.
      // Changes elsewhere in the file can change the *type* of an export in a module augmentation,
      // but type info is gathered in getCompletionEntryDetails, which doesn't use the cache.
      !arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || !ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)) {
        cache.clear();
        return true;
      }
      usableByFileName = newSourceFile.path;
      return false;
    }
  };
  if (Debug.isDebugging) {
    Object.defineProperty(cache, "__cache", { value: exportInfo });
  }
  return cache;
  function rehydrateCachedInfo(info) {
    if (info.symbol && info.moduleSymbol) return info;
    const { id, exportKind, targetFlags, isFromPackageJson, moduleFileName } = info;
    const [cachedSymbol, cachedModuleSymbol] = symbols.get(id) || emptyArray;
    if (cachedSymbol && cachedModuleSymbol) {
      return {
        symbol: cachedSymbol,
        moduleSymbol: cachedModuleSymbol,
        moduleFileName,
        exportKind,
        targetFlags,
        isFromPackageJson
      };
    }
    const checker = (isFromPackageJson ? host.getPackageJsonAutoImportProvider() : host.getCurrentProgram()).getTypeChecker();
    const moduleSymbol = info.moduleSymbol || cachedModuleSymbol || Debug.checkDefined(
      info.moduleFile ? checker.getMergedSymbol(info.moduleFile.symbol) : checker.tryFindAmbientModule(info.moduleName)
    );
    const symbol = info.symbol || cachedSymbol || Debug.checkDefined(
      exportKind === 2 /* ExportEquals */ ? checker.resolveExternalModuleSymbol(moduleSymbol) : checker.tryGetMemberInModuleExportsAndProperties(unescapeLeadingUnderscores(info.symbolTableKey), moduleSymbol),
      `Could not find symbol '${info.symbolName}' by key '${info.symbolTableKey}' in module ${moduleSymbol.name}`
    );
    symbols.set(id, [symbol, moduleSymbol]);
    return {
      symbol,
      moduleSymbol,
      moduleFileName,
      exportKind,
      targetFlags,
      isFromPackageJson
    };
  }
  function key(importedName, symbol, ambientModuleName, checker) {
    const moduleKey = ambientModuleName || "";
    return `${importedName.length} ${getSymbolId(skipAlias(symbol, checker))} ${importedName} ${moduleKey}`;
  }
  function parseKey(key2) {
    const firstSpace = key2.indexOf(" ");
    const secondSpace = key2.indexOf(" ", firstSpace + 1);
    const symbolNameLength = parseInt(key2.substring(0, firstSpace), 10);
    const data = key2.substring(secondSpace + 1);
    const symbolName2 = data.substring(0, symbolNameLength);
    const moduleKey = data.substring(symbolNameLength + 1);
    const ambientModuleName = moduleKey === "" ? void 0 : moduleKey;
    return { symbolName: symbolName2, ambientModuleName };
  }
  function fileIsGlobalOnly(file) {
    return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames;
  }
  function ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile) {
    if (!arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) {
      return false;
    }
    let oldFileStatementIndex = -1;
    let newFileStatementIndex = -1;
    for (const ambientModuleName of newSourceFile.ambientModuleNames) {
      const isMatchingModuleDeclaration = (node) => isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName;
      oldFileStatementIndex = findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1);
      newFileStatementIndex = findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1);
      if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) {
        return false;
      }
    }
    return true;
  }
  function isNotShadowedByDeeperNodeModulesPackage(info, packageName) {
    if (!packageName || !info.moduleFileName) return true;
    const typingsCacheLocation = host.getGlobalTypingsCacheLocation();
    if (typingsCacheLocation && startsWith(info.moduleFileName, typingsCacheLocation)) return true;
    const packageDeepestNodeModulesPath = packages.get(packageName);
    return !packageDeepestNodeModulesPath || startsWith(info.moduleFileName, packageDeepestNodeModulesPath);
  }
}
function isImportable(program, fromFile, toFile, toModule, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) {
  var _a;
  if (!toFile) {
    let useNodePrefix;
    const moduleName = stripQuotes(toModule.name);
    if (nodeCoreModules.has(moduleName) && (useNodePrefix = shouldUseUriStyleNodeCoreModules(fromFile, program)) !== void 0) {
      return useNodePrefix === startsWith(moduleName, "node:");
    }
    return !packageJsonFilter || packageJsonFilter.allowsImportingAmbientModule(toModule, moduleSpecifierResolutionHost) || fileContainsPackageImport(fromFile, moduleName);
  }
  Debug.assertIsDefined(toFile);
  if (fromFile === toFile) return false;
  const cachedResult = moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.get(fromFile.path, toFile.path, preferences, {});
  if ((cachedResult == null ? void 0 : cachedResult.isBlockedByPackageJsonDependencies) !== void 0) {
    return !cachedResult.isBlockedByPackageJsonDependencies || !!cachedResult.packageName && fileContainsPackageImport(fromFile, cachedResult.packageName);
  }
  const getCanonicalFileName = hostGetCanonicalFileName(moduleSpecifierResolutionHost);
  const globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) == null ? void 0 : _a.call(moduleSpecifierResolutionHost);
  const hasImportablePath = !!ts_moduleSpecifiers_exports.forEachFileNameOfModule(
    fromFile.fileName,
    toFile.fileName,
    moduleSpecifierResolutionHost,
    /*preferSymlinks*/
    false,
    (toPath3) => {
      const file = program.getSourceFile(toPath3);
      return (file === toFile || !file) && isImportablePath(
        fromFile.fileName,
        toPath3,
        getCanonicalFileName,
        globalTypingsCache,
        moduleSpecifierResolutionHost
      );
    }
  );
  if (packageJsonFilter) {
    const importInfo = hasImportablePath ? packageJsonFilter.getSourceFileInfo(toFile, moduleSpecifierResolutionHost) : void 0;
    moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.setBlockedByPackageJsonDependencies(fromFile.path, toFile.path, preferences, {}, importInfo == null ? void 0 : importInfo.packageName, !(importInfo == null ? void 0 : importInfo.importable));
    return !!(importInfo == null ? void 0 : importInfo.importable) || hasImportablePath && !!(importInfo == null ? void 0 : importInfo.packageName) && fileContainsPackageImport(fromFile, importInfo.packageName);
  }
  return hasImportablePath;
}
function fileContainsPackageImport(sourceFile, packageName) {
  return sourceFile.imports && sourceFile.imports.some((i) => i.text === packageName || i.text.startsWith(packageName + "/"));
}
function isImportablePath(fromPath, toPath3, getCanonicalFileName, globalCachePath, host) {
  const toNodeModules = forEachAncestorDirectoryStoppingAtGlobalCache(
    host,
    toPath3,
    (ancestor) => getBaseFileName(ancestor) === "node_modules" ? ancestor : void 0
  );
  const toNodeModulesParent = toNodeModules && getDirectoryPath(getCanonicalFileName(toNodeModules));
  return toNodeModulesParent === void 0 || startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || !!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent);
}
function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) {
  var _a, _b;
  const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host);
  const excludePatterns = preferences.autoImportFileExcludePatterns && getIsExcludedPatterns(preferences, useCaseSensitiveFileNames2);
  forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, host, (module2, file) => cb(
    module2,
    file,
    program,
    /*isFromPackageJson*/
    false
  ));
  const autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a.call(host));
  if (autoImportProvider) {
    const start = timestamp();
    const checker = program.getTypeChecker();
    forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, host, (module2, file) => {
      if (file && !program.getSourceFile(file.fileName) || !file && !checker.resolveName(
        module2.name,
        /*location*/
        void 0,
        1536 /* Module */,
        /*excludeGlobals*/
        false
      )) {
        cb(
          module2,
          file,
          autoImportProvider,
          /*isFromPackageJson*/
          true
        );
      }
    });
    (_b = host.log) == null ? void 0 : _b.call(host, `forEachExternalModuleToImportFrom autoImportProvider: ${timestamp() - start}`);
  }
}
function getIsExcludedPatterns(preferences, useCaseSensitiveFileNames2) {
  return mapDefined(preferences.autoImportFileExcludePatterns, (spec) => {
    const pattern = getSubPatternFromSpec(spec, "", "exclude");
    return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames2) : void 0;
  });
}
function forEachExternalModule(checker, allSourceFiles, excludePatterns, host, cb) {
  var _a;
  const isExcluded = excludePatterns && getIsExcluded(excludePatterns, host);
  for (const ambient of checker.getAmbientModules()) {
    if (!ambient.name.includes("*") && !(excludePatterns && ((_a = ambient.declarations) == null ? void 0 : _a.every((d) => isExcluded(d.getSourceFile()))))) {
      cb(
        ambient,
        /*sourceFile*/
        void 0
      );
    }
  }
  for (const sourceFile of allSourceFiles) {
    if (isExternalOrCommonJsModule(sourceFile) && !(isExcluded == null ? void 0 : isExcluded(sourceFile))) {
      cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile);
    }
  }
}
function getIsExcluded(excludePatterns, host) {
  var _a;
  const realpathsWithSymlinks = (_a = host.getSymlinkCache) == null ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath();
  return ({ fileName, path }) => {
    if (excludePatterns.some((p) => p.test(fileName))) return true;
    if ((realpathsWithSymlinks == null ? void 0 : realpathsWithSymlinks.size) && pathContainsNodeModules(fileName)) {
      let dir = getDirectoryPath(fileName);
      return forEachAncestorDirectoryStoppingAtGlobalCache(
        host,
        getDirectoryPath(path),
        (dirPath) => {
          const symlinks = realpathsWithSymlinks.get(ensureTrailingDirectorySeparator(dirPath));
          if (symlinks) {
            return symlinks.some((s) => excludePatterns.some((p) => p.test(fileName.replace(dir, s))));
          }
          dir = getDirectoryPath(dir);
        }
      ) ?? false;
    }
    return false;
  };
}
function getIsFileExcluded(host, preferences) {
  if (!preferences.autoImportFileExcludePatterns) return () => false;
  return getIsExcluded(getIsExcludedPatterns(preferences, hostUsesCaseSensitiveFileNames(host)), host);
}
function getExportInfoMap(importingFile, host, program, preferences, cancellationToken) {
  var _a, _b, _c, _d, _e;
  const start = timestamp();
  (_a = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a.call(host);
  const cache = ((_b = host.getCachedExportInfoMap) == null ? void 0 : _b.call(host)) || createCacheableExportInfoMap({
    getCurrentProgram: () => program,
    getPackageJsonAutoImportProvider: () => {
      var _a2;
      return (_a2 = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a2.call(host);
    },
    getGlobalTypingsCacheLocation: () => {
      var _a2;
      return (_a2 = host.getGlobalTypingsCacheLocation) == null ? void 0 : _a2.call(host);
    }
  });
  if (cache.isUsableByFile(importingFile.path)) {
    (_c = host.log) == null ? void 0 : _c.call(host, "getExportInfoMap: cache hit");
    return cache;
  }
  (_d = host.log) == null ? void 0 : _d.call(host, "getExportInfoMap: cache miss or empty; calculating new results");
  let moduleCount = 0;
  try {
    forEachExternalModuleToImportFrom(
      program,
      host,
      preferences,
      /*useAutoImportProvider*/
      true,
      (moduleSymbol, moduleFile, program2, isFromPackageJson) => {
        if (++moduleCount % 100 === 0) cancellationToken == null ? void 0 : cancellationToken.throwIfCancellationRequested();
        const seenExports = /* @__PURE__ */ new Set();
        const checker = program2.getTypeChecker();
        const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker);
        if (defaultInfo && isImportableSymbol(defaultInfo.symbol, checker)) {
          cache.add(
            importingFile.path,
            defaultInfo.symbol,
            defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */,
            moduleSymbol,
            moduleFile,
            defaultInfo.exportKind,
            isFromPackageJson,
            checker
          );
        }
        checker.forEachExportAndPropertyOfModule(moduleSymbol, (exported, key) => {
          if (exported !== (defaultInfo == null ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && addToSeen(seenExports, key)) {
            cache.add(
              importingFile.path,
              exported,
              key,
              moduleSymbol,
              moduleFile,
              0 /* Named */,
              isFromPackageJson,
              checker
            );
          }
        });
      }
    );
  } catch (err) {
    cache.clear();
    throw err;
  }
  (_e = host.log) == null ? void 0 : _e.call(host, `getExportInfoMap: done in ${timestamp() - start} ms`);
  return cache;
}
function getDefaultLikeExportInfo(moduleSymbol, checker) {
  const exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol);
  if (exportEquals !== moduleSymbol) {
    const defaultExport2 = checker.tryGetMemberInModuleExports("default" /* Default */, exportEquals);
    if (defaultExport2) return { symbol: defaultExport2, exportKind: 1 /* Default */ };
    return { symbol: exportEquals, exportKind: 2 /* ExportEquals */ };
  }
  const defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol);
  if (defaultExport) return { symbol: defaultExport, exportKind: 1 /* Default */ };
}
function isImportableSymbol(symbol, checker) {
  return !checker.isUndefinedSymbol(symbol) && !checker.isUnknownSymbol(symbol) && !isKnownSymbol(symbol) && !isPrivateIdentifierSymbol(symbol);
}
function getNamesForExportedSymbol(defaultExport, checker, scriptTarget) {
  let names;
  forEachNameOfDefaultExport(defaultExport, checker, scriptTarget, (name, capitalizedName) => {
    names = capitalizedName ? [name, capitalizedName] : name;
    return true;
  });
  return Debug.checkDefined(names);
}
function forEachNameOfDefaultExport(defaultExport, checker, scriptTarget, cb) {
  let chain;
  let current = defaultExport;
  const seen = /* @__PURE__ */ new Set();
  while (current) {
    const fromDeclaration = getDefaultLikeExportNameFromDeclaration(current);
    if (fromDeclaration) {
      const final = cb(fromDeclaration);
      if (final) return final;
    }
    if (current.escapedName !== "default" /* Default */ && current.escapedName !== "export=" /* ExportEquals */) {
      const final = cb(current.name);
      if (final) return final;
    }
    chain = append(chain, current);
    if (!addToSeen(seen, current)) break;
    current = current.flags & 2097152 /* Alias */ ? checker.getImmediateAliasedSymbol(current) : void 0;
  }
  for (const symbol of chain ?? emptyArray) {
    if (symbol.parent && isExternalModuleSymbol(symbol.parent)) {
      const final = cb(
        moduleSymbolToValidIdentifier(
          symbol.parent,
          scriptTarget,
          /*forceCapitalize*/
          false
        ),
        moduleSymbolToValidIdentifier(
          symbol.parent,
          scriptTarget,
          /*forceCapitalize*/
          true
        )
      );
      if (final) return final;
    }
  }
}

// src/services/classifier.ts
function createClassifier() {
  const scanner2 = createScanner(
    99 /* Latest */,
    /*skipTrivia*/
    false
  );
  function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) {
    return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
  }
  function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) {
    let token = 0 /* Unknown */;
    let lastNonTriviaToken = 0 /* Unknown */;
    const templateStack = [];
    const { prefix, pushTemplate } = getPrefixFromLexState(lexState);
    text = prefix + text;
    const offset = prefix.length;
    if (pushTemplate) {
      templateStack.push(16 /* TemplateHead */);
    }
    scanner2.setText(text);
    let endOfLineState = 0 /* None */;
    const spans = [];
    let angleBracketStack = 0;
    do {
      token = scanner2.scan();
      if (!isTrivia(token)) {
        handleToken();
        lastNonTriviaToken = token;
      }
      const end = scanner2.getTokenEnd();
      pushEncodedClassification(scanner2.getTokenStart(), end, offset, classFromKind(token), spans);
      if (end >= text.length) {
        const end2 = getNewEndOfLineState(scanner2, token, lastOrUndefined(templateStack));
        if (end2 !== void 0) {
          endOfLineState = end2;
        }
      }
    } while (token !== 1 /* EndOfFileToken */);
    function handleToken() {
      switch (token) {
        case 44 /* SlashToken */:
        case 69 /* SlashEqualsToken */:
          if (!noRegexTable[lastNonTriviaToken] && scanner2.reScanSlashToken() === 14 /* RegularExpressionLiteral */) {
            token = 14 /* RegularExpressionLiteral */;
          }
          break;
        case 30 /* LessThanToken */:
          if (lastNonTriviaToken === 80 /* Identifier */) {
            angleBracketStack++;
          }
          break;
        case 32 /* GreaterThanToken */:
          if (angleBracketStack > 0) {
            angleBracketStack--;
          }
          break;
        case 133 /* AnyKeyword */:
        case 154 /* StringKeyword */:
        case 150 /* NumberKeyword */:
        case 136 /* BooleanKeyword */:
        case 155 /* SymbolKeyword */:
          if (angleBracketStack > 0 && !syntacticClassifierAbsent) {
            token = 80 /* Identifier */;
          }
          break;
        case 16 /* TemplateHead */:
          templateStack.push(token);
          break;
        case 19 /* OpenBraceToken */:
          if (templateStack.length > 0) {
            templateStack.push(token);
          }
          break;
        case 20 /* CloseBraceToken */:
          if (templateStack.length > 0) {
            const lastTemplateStackToken = lastOrUndefined(templateStack);
            if (lastTemplateStackToken === 16 /* TemplateHead */) {
              token = scanner2.reScanTemplateToken(
                /*isTaggedTemplate*/
                false
              );
              if (token === 18 /* TemplateTail */) {
                templateStack.pop();
              } else {
                Debug.assertEqual(token, 17 /* TemplateMiddle */, "Should have been a template middle.");
              }
            } else {
              Debug.assertEqual(lastTemplateStackToken, 19 /* OpenBraceToken */, "Should have been an open brace");
              templateStack.pop();
            }
          }
          break;
        default:
          if (!isKeyword(token)) {
            break;
          }
          if (lastNonTriviaToken === 25 /* DotToken */) {
            token = 80 /* Identifier */;
          } else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) {
            token = 80 /* Identifier */;
          }
      }
    }
    return { endOfLineState, spans };
  }
  return { getClassificationsForLine, getEncodedLexicalClassifications };
}
var noRegexTable = arrayToNumericMap(
  [
    80 /* Identifier */,
    11 /* StringLiteral */,
    9 /* NumericLiteral */,
    10 /* BigIntLiteral */,
    14 /* RegularExpressionLiteral */,
    110 /* ThisKeyword */,
    46 /* PlusPlusToken */,
    47 /* MinusMinusToken */,
    22 /* CloseParenToken */,
    24 /* CloseBracketToken */,
    20 /* CloseBraceToken */,
    112 /* TrueKeyword */,
    97 /* FalseKeyword */
  ],
  (token) => token,
  () => true
);
function getNewEndOfLineState(scanner2, token, lastOnTemplateStack) {
  switch (token) {
    case 11 /* StringLiteral */: {
      if (!scanner2.isUnterminated()) return void 0;
      const tokenText = scanner2.getTokenText();
      const lastCharIndex = tokenText.length - 1;
      let numBackslashes = 0;
      while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) {
        numBackslashes++;
      }
      if ((numBackslashes & 1) === 0) return void 0;
      return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */;
    }
    case 3 /* MultiLineCommentTrivia */:
      return scanner2.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : void 0;
    default:
      if (isTemplateLiteralKind(token)) {
        if (!scanner2.isUnterminated()) {
          return void 0;
        }
        switch (token) {
          case 18 /* TemplateTail */:
            return 5 /* InTemplateMiddleOrTail */;
          case 15 /* NoSubstitutionTemplateLiteral */:
            return 4 /* InTemplateHeadOrNoSubstitutionTemplate */;
          default:
            return Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
        }
      }
      return lastOnTemplateStack === 16 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : void 0;
  }
}
function pushEncodedClassification(start, end, offset, classification, result) {
  if (classification === 8 /* whiteSpace */) {
    return;
  }
  if (start === 0 && offset > 0) {
    start += offset;
  }
  const length2 = end - start;
  if (length2 > 0) {
    result.push(start - offset, length2, classification);
  }
}
function convertClassificationsToResult(classifications, text) {
  const entries = [];
  const dense = classifications.spans;
  let lastEnd = 0;
  for (let i = 0; i < dense.length; i += 3) {
    const start = dense[i];
    const length2 = dense[i + 1];
    const type = dense[i + 2];
    if (lastEnd >= 0) {
      const whitespaceLength2 = start - lastEnd;
      if (whitespaceLength2 > 0) {
        entries.push({ length: whitespaceLength2, classification: 4 /* Whitespace */ });
      }
    }
    entries.push({ length: length2, classification: convertClassification(type) });
    lastEnd = start + length2;
  }
  const whitespaceLength = text.length - lastEnd;
  if (whitespaceLength > 0) {
    entries.push({ length: whitespaceLength, classification: 4 /* Whitespace */ });
  }
  return { entries, finalLexState: classifications.endOfLineState };
}
function convertClassification(type) {
  switch (type) {
    case 1 /* comment */:
      return 3 /* Comment */;
    case 3 /* keyword */:
      return 1 /* Keyword */;
    case 4 /* numericLiteral */:
      return 6 /* NumberLiteral */;
    case 25 /* bigintLiteral */:
      return 7 /* BigIntLiteral */;
    case 5 /* operator */:
      return 2 /* Operator */;
    case 6 /* stringLiteral */:
      return 8 /* StringLiteral */;
    case 8 /* whiteSpace */:
      return 4 /* Whitespace */;
    case 10 /* punctuation */:
      return 0 /* Punctuation */;
    case 2 /* identifier */:
    case 11 /* className */:
    case 12 /* enumName */:
    case 13 /* interfaceName */:
    case 14 /* moduleName */:
    case 15 /* typeParameterName */:
    case 16 /* typeAliasName */:
    case 9 /* text */:
    case 17 /* parameterName */:
      return 5 /* Identifier */;
    default:
      return void 0;
  }
}
function canFollow(keyword1, keyword2) {
  if (!isAccessibilityModifier(keyword1)) {
    return true;
  }
  switch (keyword2) {
    case 139 /* GetKeyword */:
    case 153 /* SetKeyword */:
    case 137 /* ConstructorKeyword */:
    case 126 /* StaticKeyword */:
    case 129 /* AccessorKeyword */:
      return true;
    // Allow things like "public get", "public constructor" and "public static".
    default:
      return false;
  }
}
function getPrefixFromLexState(lexState) {
  switch (lexState) {
    case 3 /* InDoubleQuoteStringLiteral */:
      return { prefix: '"\\\n' };
    case 2 /* InSingleQuoteStringLiteral */:
      return { prefix: "'\\\n" };
    case 1 /* InMultiLineCommentTrivia */:
      return { prefix: "/*\n" };
    case 4 /* InTemplateHeadOrNoSubstitutionTemplate */:
      return { prefix: "`\n" };
    case 5 /* InTemplateMiddleOrTail */:
      return { prefix: "}\n", pushTemplate: true };
    case 6 /* InTemplateSubstitutionPosition */:
      return { prefix: "", pushTemplate: true };
    case 0 /* None */:
      return { prefix: "" };
    default:
      return Debug.assertNever(lexState);
  }
}
function isBinaryExpressionOperatorToken(token) {
  switch (token) {
    case 42 /* AsteriskToken */:
    case 44 /* SlashToken */:
    case 45 /* PercentToken */:
    case 40 /* PlusToken */:
    case 41 /* MinusToken */:
    case 48 /* LessThanLessThanToken */:
    case 49 /* GreaterThanGreaterThanToken */:
    case 50 /* GreaterThanGreaterThanGreaterThanToken */:
    case 30 /* LessThanToken */:
    case 32 /* GreaterThanToken */:
    case 33 /* LessThanEqualsToken */:
    case 34 /* GreaterThanEqualsToken */:
    case 104 /* InstanceOfKeyword */:
    case 103 /* InKeyword */:
    case 130 /* AsKeyword */:
    case 152 /* SatisfiesKeyword */:
    case 35 /* EqualsEqualsToken */:
    case 36 /* ExclamationEqualsToken */:
    case 37 /* EqualsEqualsEqualsToken */:
    case 38 /* ExclamationEqualsEqualsToken */:
    case 51 /* AmpersandToken */:
    case 53 /* CaretToken */:
    case 52 /* BarToken */:
    case 56 /* AmpersandAmpersandToken */:
    case 57 /* BarBarToken */:
    case 75 /* BarEqualsToken */:
    case 74 /* AmpersandEqualsToken */:
    case 79 /* CaretEqualsToken */:
    case 71 /* LessThanLessThanEqualsToken */:
    case 72 /* GreaterThanGreaterThanEqualsToken */:
    case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
    case 65 /* PlusEqualsToken */:
    case 66 /* MinusEqualsToken */:
    case 67 /* AsteriskEqualsToken */:
    case 69 /* SlashEqualsToken */:
    case 70 /* PercentEqualsToken */:
    case 64 /* EqualsToken */:
    case 28 /* CommaToken */:
    case 61 /* QuestionQuestionToken */:
    case 76 /* BarBarEqualsToken */:
    case 77 /* AmpersandAmpersandEqualsToken */:
    case 78 /* QuestionQuestionEqualsToken */:
      return true;
    default:
      return false;
  }
}
function isPrefixUnaryExpressionOperatorToken(token) {
  switch (token) {
    case 40 /* PlusToken */:
    case 41 /* MinusToken */:
    case 55 /* TildeToken */:
    case 54 /* ExclamationToken */:
    case 46 /* PlusPlusToken */:
    case 47 /* MinusMinusToken */:
      return true;
    default:
      return false;
  }
}
function classFromKind(token) {
  if (isKeyword(token)) {
    return 3 /* keyword */;
  } else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) {
    return 5 /* operator */;
  } else if (token >= 19 /* FirstPunctuation */ && token <= 79 /* LastPunctuation */) {
    return 10 /* punctuation */;
  }
  switch (token) {
    case 9 /* NumericLiteral */:
      return 4 /* numericLiteral */;
    case 10 /* BigIntLiteral */:
      return 25 /* bigintLiteral */;
    case 11 /* StringLiteral */:
      return 6 /* stringLiteral */;
    case 14 /* RegularExpressionLiteral */:
      return 7 /* regularExpressionLiteral */;
    case 7 /* ConflictMarkerTrivia */:
    case 3 /* MultiLineCommentTrivia */:
    case 2 /* SingleLineCommentTrivia */:
      return 1 /* comment */;
    case 5 /* WhitespaceTrivia */:
    case 4 /* NewLineTrivia */:
      return 8 /* whiteSpace */;
    case 80 /* Identifier */:
    default:
      if (isTemplateLiteralKind(token)) {
        return 6 /* stringLiteral */;
      }
      return 2 /* identifier */;
  }
}
function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
  return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span));
}
function checkForClassificationCancellation(cancellationToken, kind) {
  switch (kind) {
    case 267 /* ModuleDeclaration */:
    case 263 /* ClassDeclaration */:
    case 264 /* InterfaceDeclaration */:
    case 262 /* FunctionDeclaration */:
    case 231 /* ClassExpression */:
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
      cancellationToken.throwIfCancellationRequested();
  }
}
function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
  const spans = [];
  sourceFile.forEachChild(function cb(node) {
    if (!node || !textSpanIntersectsWith(span, node.pos, node.getFullWidth())) {
      return;
    }
    checkForClassificationCancellation(cancellationToken, node.kind);
    if (isIdentifier(node) && !nodeIsMissing(node) && classifiableNames.has(node.escapedText)) {
      const symbol = typeChecker.getSymbolAtLocation(node);
      const type = symbol && classifySymbol(symbol, getMeaningFromLocation(node), typeChecker);
      if (type) {
        pushClassification(node.getStart(sourceFile), node.getEnd(), type);
      }
    }
    node.forEachChild(cb);
  });
  return { spans, endOfLineState: 0 /* None */ };
  function pushClassification(start, end, type) {
    const length2 = end - start;
    Debug.assert(length2 > 0, `Classification had non-positive length of ${length2}`);
    spans.push(start);
    spans.push(length2);
    spans.push(type);
  }
}
function classifySymbol(symbol, meaningAtPosition, checker) {
  const flags = symbol.getFlags();
  if ((flags & 2885600 /* Classifiable */) === 0 /* None */) {
    return void 0;
  } else if (flags & 32 /* Class */) {
    return 11 /* className */;
  } else if (flags & 384 /* Enum */) {
    return 12 /* enumName */;
  } else if (flags & 524288 /* TypeAlias */) {
    return 16 /* typeAliasName */;
  } else if (flags & 1536 /* Module */) {
    return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : void 0;
  } else if (flags & 2097152 /* Alias */) {
    return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker);
  } else if (meaningAtPosition & 2 /* Type */) {
    return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : void 0;
  } else {
    return void 0;
  }
}
function hasValueSideModule(symbol) {
  return some(symbol.declarations, (declaration) => isModuleDeclaration(declaration) && getModuleInstanceState(declaration) === 1 /* Instantiated */);
}
function getClassificationTypeName(type) {
  switch (type) {
    case 1 /* comment */:
      return "comment" /* comment */;
    case 2 /* identifier */:
      return "identifier" /* identifier */;
    case 3 /* keyword */:
      return "keyword" /* keyword */;
    case 4 /* numericLiteral */:
      return "number" /* numericLiteral */;
    case 25 /* bigintLiteral */:
      return "bigint" /* bigintLiteral */;
    case 5 /* operator */:
      return "operator" /* operator */;
    case 6 /* stringLiteral */:
      return "string" /* stringLiteral */;
    case 8 /* whiteSpace */:
      return "whitespace" /* whiteSpace */;
    case 9 /* text */:
      return "text" /* text */;
    case 10 /* punctuation */:
      return "punctuation" /* punctuation */;
    case 11 /* className */:
      return "class name" /* className */;
    case 12 /* enumName */:
      return "enum name" /* enumName */;
    case 13 /* interfaceName */:
      return "interface name" /* interfaceName */;
    case 14 /* moduleName */:
      return "module name" /* moduleName */;
    case 15 /* typeParameterName */:
      return "type parameter name" /* typeParameterName */;
    case 16 /* typeAliasName */:
      return "type alias name" /* typeAliasName */;
    case 17 /* parameterName */:
      return "parameter name" /* parameterName */;
    case 18 /* docCommentTagName */:
      return "doc comment tag name" /* docCommentTagName */;
    case 19 /* jsxOpenTagName */:
      return "jsx open tag name" /* jsxOpenTagName */;
    case 20 /* jsxCloseTagName */:
      return "jsx close tag name" /* jsxCloseTagName */;
    case 21 /* jsxSelfClosingTagName */:
      return "jsx self closing tag name" /* jsxSelfClosingTagName */;
    case 22 /* jsxAttribute */:
      return "jsx attribute" /* jsxAttribute */;
    case 23 /* jsxText */:
      return "jsx text" /* jsxText */;
    case 24 /* jsxAttributeStringLiteralValue */:
      return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */;
    default:
      return void 0;
  }
}
function convertClassificationsToSpans(classifications) {
  Debug.assert(classifications.spans.length % 3 === 0);
  const dense = classifications.spans;
  const result = [];
  for (let i = 0; i < dense.length; i += 3) {
    result.push({
      textSpan: createTextSpan(dense[i], dense[i + 1]),
      classificationType: getClassificationTypeName(dense[i + 2])
    });
  }
  return result;
}
function getSyntacticClassifications(cancellationToken, sourceFile, span) {
  return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span));
}
function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) {
  const spanStart = span.start;
  const spanLength = span.length;
  const triviaScanner = createScanner(
    99 /* Latest */,
    /*skipTrivia*/
    false,
    sourceFile.languageVariant,
    sourceFile.text
  );
  const mergeConflictScanner = createScanner(
    99 /* Latest */,
    /*skipTrivia*/
    false,
    sourceFile.languageVariant,
    sourceFile.text
  );
  const result = [];
  processElement(sourceFile);
  return { spans: result, endOfLineState: 0 /* None */ };
  function pushClassification(start, length2, type) {
    result.push(start);
    result.push(length2);
    result.push(type);
  }
  function classifyLeadingTriviaAndGetTokenStart(token) {
    triviaScanner.resetTokenState(token.pos);
    while (true) {
      const start = triviaScanner.getTokenEnd();
      if (!couldStartTrivia(sourceFile.text, start)) {
        return start;
      }
      const kind = triviaScanner.scan();
      const end = triviaScanner.getTokenEnd();
      const width = end - start;
      if (!isTrivia(kind)) {
        return start;
      }
      switch (kind) {
        case 4 /* NewLineTrivia */:
        case 5 /* WhitespaceTrivia */:
          continue;
        case 2 /* SingleLineCommentTrivia */:
        case 3 /* MultiLineCommentTrivia */:
          classifyComment(token, kind, start, width);
          triviaScanner.resetTokenState(end);
          continue;
        case 7 /* ConflictMarkerTrivia */:
          const text = sourceFile.text;
          const ch = text.charCodeAt(start);
          if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
            pushClassification(start, width, 1 /* comment */);
            continue;
          }
          Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
          classifyDisabledMergeCode(text, start, end);
          break;
        case 6 /* ShebangTrivia */:
          break;
        default:
          Debug.assertNever(kind);
      }
    }
  }
  function classifyComment(token, kind, start, width) {
    if (kind === 3 /* MultiLineCommentTrivia */) {
      const docCommentAndDiagnostics = parseIsolatedJSDocComment(sourceFile.text, start, width);
      if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) {
        setParent(docCommentAndDiagnostics.jsDoc, token);
        classifyJSDocComment(docCommentAndDiagnostics.jsDoc);
        return;
      }
    } else if (kind === 2 /* SingleLineCommentTrivia */) {
      if (tryClassifyTripleSlashComment(start, width)) {
        return;
      }
    }
    pushCommentRange(start, width);
  }
  function pushCommentRange(start, width) {
    pushClassification(start, width, 1 /* comment */);
  }
  function classifyJSDocComment(docComment) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    let pos = docComment.pos;
    if (docComment.tags) {
      for (const tag of docComment.tags) {
        if (tag.pos !== pos) {
          pushCommentRange(pos, tag.pos - pos);
        }
        pushClassification(tag.pos, 1, 10 /* punctuation */);
        pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */);
        pos = tag.tagName.end;
        let commentStart = tag.tagName.end;
        switch (tag.kind) {
          case 341 /* JSDocParameterTag */:
            const param = tag;
            processJSDocParameterTag(param);
            commentStart = param.isNameFirst && ((_a = param.typeExpression) == null ? void 0 : _a.end) || param.name.end;
            break;
          case 348 /* JSDocPropertyTag */:
            const prop = tag;
            commentStart = prop.isNameFirst && ((_b = prop.typeExpression) == null ? void 0 : _b.end) || prop.name.end;
            break;
          case 345 /* JSDocTemplateTag */:
            processJSDocTemplateTag(tag);
            pos = tag.end;
            commentStart = tag.typeParameters.end;
            break;
          case 346 /* JSDocTypedefTag */:
            const type = tag;
            commentStart = ((_c = type.typeExpression) == null ? void 0 : _c.kind) === 309 /* JSDocTypeExpression */ && ((_d = type.fullName) == null ? void 0 : _d.end) || ((_e = type.typeExpression) == null ? void 0 : _e.end) || commentStart;
            break;
          case 338 /* JSDocCallbackTag */:
            commentStart = tag.typeExpression.end;
            break;
          case 344 /* JSDocTypeTag */:
            processElement(tag.typeExpression);
            pos = tag.end;
            commentStart = tag.typeExpression.end;
            break;
          case 343 /* JSDocThisTag */:
          case 340 /* JSDocEnumTag */:
            commentStart = tag.typeExpression.end;
            break;
          case 342 /* JSDocReturnTag */:
            processElement(tag.typeExpression);
            pos = tag.end;
            commentStart = ((_f = tag.typeExpression) == null ? void 0 : _f.end) || commentStart;
            break;
          case 347 /* JSDocSeeTag */:
            commentStart = ((_g = tag.name) == null ? void 0 : _g.end) || commentStart;
            break;
          case 328 /* JSDocAugmentsTag */:
          case 329 /* JSDocImplementsTag */:
            commentStart = tag.class.end;
            break;
          case 349 /* JSDocThrowsTag */:
            processElement(tag.typeExpression);
            pos = tag.end;
            commentStart = ((_h = tag.typeExpression) == null ? void 0 : _h.end) || commentStart;
            break;
        }
        if (typeof tag.comment === "object") {
          pushCommentRange(tag.comment.pos, tag.comment.end - tag.comment.pos);
        } else if (typeof tag.comment === "string") {
          pushCommentRange(commentStart, tag.end - commentStart);
        }
      }
    }
    if (pos !== docComment.end) {
      pushCommentRange(pos, docComment.end - pos);
    }
    return;
    function processJSDocParameterTag(tag) {
      if (tag.isNameFirst) {
        pushCommentRange(pos, tag.name.pos - pos);
        pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
        pos = tag.name.end;
      }
      if (tag.typeExpression) {
        pushCommentRange(pos, tag.typeExpression.pos - pos);
        processElement(tag.typeExpression);
        pos = tag.typeExpression.end;
      }
      if (!tag.isNameFirst) {
        pushCommentRange(pos, tag.name.pos - pos);
        pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
        pos = tag.name.end;
      }
    }
  }
  function tryClassifyTripleSlashComment(start, width) {
    const tripleSlashXMLCommentRegEx = /^(\/\/\/\s*)(<)(?:(\S+)((?:[^/]|\/[^>])*)(\/>)?)?/m;
    const attributeRegex = /(\s)(\S+)(\s*)(=)(\s*)('[^']+'|"[^"]+")/g;
    const text = sourceFile.text.substr(start, width);
    const match = tripleSlashXMLCommentRegEx.exec(text);
    if (!match) {
      return false;
    }
    if (!match[3] || !(match[3] in commentPragmas)) {
      return false;
    }
    let pos = start;
    pushCommentRange(pos, match[1].length);
    pos += match[1].length;
    pushClassification(pos, match[2].length, 10 /* punctuation */);
    pos += match[2].length;
    pushClassification(pos, match[3].length, 21 /* jsxSelfClosingTagName */);
    pos += match[3].length;
    const attrText = match[4];
    let attrPos = pos;
    while (true) {
      const attrMatch = attributeRegex.exec(attrText);
      if (!attrMatch) {
        break;
      }
      const newAttrPos = pos + attrMatch.index + attrMatch[1].length;
      if (newAttrPos > attrPos) {
        pushCommentRange(attrPos, newAttrPos - attrPos);
        attrPos = newAttrPos;
      }
      pushClassification(attrPos, attrMatch[2].length, 22 /* jsxAttribute */);
      attrPos += attrMatch[2].length;
      if (attrMatch[3].length) {
        pushCommentRange(attrPos, attrMatch[3].length);
        attrPos += attrMatch[3].length;
      }
      pushClassification(attrPos, attrMatch[4].length, 5 /* operator */);
      attrPos += attrMatch[4].length;
      if (attrMatch[5].length) {
        pushCommentRange(attrPos, attrMatch[5].length);
        attrPos += attrMatch[5].length;
      }
      pushClassification(attrPos, attrMatch[6].length, 24 /* jsxAttributeStringLiteralValue */);
      attrPos += attrMatch[6].length;
    }
    pos += match[4].length;
    if (pos > attrPos) {
      pushCommentRange(attrPos, pos - attrPos);
    }
    if (match[5]) {
      pushClassification(pos, match[5].length, 10 /* punctuation */);
      pos += match[5].length;
    }
    const end = start + width;
    if (pos < end) {
      pushCommentRange(pos, end - pos);
    }
    return true;
  }
  function processJSDocTemplateTag(tag) {
    for (const child of tag.getChildren()) {
      processElement(child);
    }
  }
  function classifyDisabledMergeCode(text, start, end) {
    let i;
    for (i = start; i < end; i++) {
      if (isLineBreak(text.charCodeAt(i))) {
        break;
      }
    }
    pushClassification(start, i - start, 1 /* comment */);
    mergeConflictScanner.resetTokenState(i);
    while (mergeConflictScanner.getTokenEnd() < end) {
      classifyDisabledCodeToken();
    }
  }
  function classifyDisabledCodeToken() {
    const start = mergeConflictScanner.getTokenEnd();
    const tokenKind = mergeConflictScanner.scan();
    const end = mergeConflictScanner.getTokenEnd();
    const type = classifyTokenType(tokenKind);
    if (type) {
      pushClassification(start, end - start, type);
    }
  }
  function tryClassifyNode(node) {
    if (isJSDoc(node)) {
      return true;
    }
    if (nodeIsMissing(node)) {
      return true;
    }
    const classifiedElementName = tryClassifyJsxElementName(node);
    if (!isToken(node) && node.kind !== 12 /* JsxText */ && classifiedElementName === void 0) {
      return false;
    }
    const tokenStart = node.kind === 12 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node);
    const tokenWidth = node.end - tokenStart;
    Debug.assert(tokenWidth >= 0);
    if (tokenWidth > 0) {
      const type = classifiedElementName || classifyTokenType(node.kind, node);
      if (type) {
        pushClassification(tokenStart, tokenWidth, type);
      }
    }
    return true;
  }
  function tryClassifyJsxElementName(token) {
    switch (token.parent && token.parent.kind) {
      case 286 /* JsxOpeningElement */:
        if (token.parent.tagName === token) {
          return 19 /* jsxOpenTagName */;
        }
        break;
      case 287 /* JsxClosingElement */:
        if (token.parent.tagName === token) {
          return 20 /* jsxCloseTagName */;
        }
        break;
      case 285 /* JsxSelfClosingElement */:
        if (token.parent.tagName === token) {
          return 21 /* jsxSelfClosingTagName */;
        }
        break;
      case 291 /* JsxAttribute */:
        if (token.parent.name === token) {
          return 22 /* jsxAttribute */;
        }
        break;
    }
    return void 0;
  }
  function classifyTokenType(tokenKind, token) {
    if (isKeyword(tokenKind)) {
      return 3 /* keyword */;
    }
    if (tokenKind === 30 /* LessThanToken */ || tokenKind === 32 /* GreaterThanToken */) {
      if (token && getTypeArgumentOrTypeParameterList(token.parent)) {
        return 10 /* punctuation */;
      }
    }
    if (isPunctuation(tokenKind)) {
      if (token) {
        const parent2 = token.parent;
        if (tokenKind === 64 /* EqualsToken */) {
          if (parent2.kind === 260 /* VariableDeclaration */ || parent2.kind === 172 /* PropertyDeclaration */ || parent2.kind === 169 /* Parameter */ || parent2.kind === 291 /* JsxAttribute */) {
            return 5 /* operator */;
          }
        }
        if (parent2.kind === 226 /* BinaryExpression */ || parent2.kind === 224 /* PrefixUnaryExpression */ || parent2.kind === 225 /* PostfixUnaryExpression */ || parent2.kind === 227 /* ConditionalExpression */) {
          return 5 /* operator */;
        }
      }
      return 10 /* punctuation */;
    } else if (tokenKind === 9 /* NumericLiteral */) {
      return 4 /* numericLiteral */;
    } else if (tokenKind === 10 /* BigIntLiteral */) {
      return 25 /* bigintLiteral */;
    } else if (tokenKind === 11 /* StringLiteral */) {
      return token && token.parent.kind === 291 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */;
    } else if (tokenKind === 14 /* RegularExpressionLiteral */) {
      return 6 /* stringLiteral */;
    } else if (isTemplateLiteralKind(tokenKind)) {
      return 6 /* stringLiteral */;
    } else if (tokenKind === 12 /* JsxText */) {
      return 23 /* jsxText */;
    } else if (tokenKind === 80 /* Identifier */) {
      if (token) {
        switch (token.parent.kind) {
          case 263 /* ClassDeclaration */:
            if (token.parent.name === token) {
              return 11 /* className */;
            }
            return;
          case 168 /* TypeParameter */:
            if (token.parent.name === token) {
              return 15 /* typeParameterName */;
            }
            return;
          case 264 /* InterfaceDeclaration */:
            if (token.parent.name === token) {
              return 13 /* interfaceName */;
            }
            return;
          case 266 /* EnumDeclaration */:
            if (token.parent.name === token) {
              return 12 /* enumName */;
            }
            return;
          case 267 /* ModuleDeclaration */:
            if (token.parent.name === token) {
              return 14 /* moduleName */;
            }
            return;
          case 169 /* Parameter */:
            if (token.parent.name === token) {
              return isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */;
            }
            return;
        }
        if (isConstTypeReference(token.parent)) {
          return 3 /* keyword */;
        }
      }
      return 2 /* identifier */;
    }
  }
  function processElement(element) {
    if (!element) {
      return;
    }
    if (decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) {
      checkForClassificationCancellation(cancellationToken, element.kind);
      for (const child of element.getChildren(sourceFile)) {
        if (!tryClassifyNode(child)) {
          processElement(child);
        }
      }
    }
  }
}

// src/services/documentHighlights.ts
var DocumentHighlights;
((DocumentHighlights3) => {
  function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) {
    const node = getTouchingPropertyName(sourceFile, position);
    if (node.parent && (isJsxOpeningElement(node.parent) && node.parent.tagName === node || isJsxClosingElement(node.parent))) {
      const { openingElement, closingElement } = node.parent.parent;
      const highlightSpans = [openingElement, closingElement].map(({ tagName }) => getHighlightSpanForNode(tagName, sourceFile));
      return [{ fileName: sourceFile.fileName, highlightSpans }];
    }
    return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile);
  }
  DocumentHighlights3.getDocumentHighlights = getDocumentHighlights;
  function getHighlightSpanForNode(node, sourceFile) {
    return {
      fileName: sourceFile.fileName,
      textSpan: createTextSpanFromNode(node, sourceFile),
      kind: "none" /* none */
    };
  }
  function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) {
    const sourceFilesSet = new Set(sourceFilesToSearch.map((f) => f.fileName));
    const referenceEntries = ts_FindAllReferences_exports.getReferenceEntriesForNode(
      position,
      node,
      program,
      sourceFilesToSearch,
      cancellationToken,
      /*options*/
      void 0,
      sourceFilesSet
    );
    if (!referenceEntries) return void 0;
    const map2 = arrayToMultiMap(referenceEntries.map(ts_FindAllReferences_exports.toHighlightSpan), (e) => e.fileName, (e) => e.span);
    const getCanonicalFileName = createGetCanonicalFileName(program.useCaseSensitiveFileNames());
    return arrayFrom(mapDefinedIterator(map2.entries(), ([fileName, highlightSpans]) => {
      if (!sourceFilesSet.has(fileName)) {
        if (!program.redirectTargetsMap.has(toPath(fileName, program.getCurrentDirectory(), getCanonicalFileName))) {
          return void 0;
        }
        const redirectTarget = program.getSourceFile(fileName);
        const redirect = find(sourceFilesToSearch, (f) => !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget);
        fileName = redirect.fileName;
        Debug.assert(sourceFilesSet.has(fileName));
      }
      return { fileName, highlightSpans };
    }));
  }
  function getSyntacticDocumentHighlights(node, sourceFile) {
    const highlightSpans = getHighlightSpans(node, sourceFile);
    return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans }];
  }
  function getHighlightSpans(node, sourceFile) {
    switch (node.kind) {
      case 101 /* IfKeyword */:
      case 93 /* ElseKeyword */:
        return isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : void 0;
      case 107 /* ReturnKeyword */:
        return useParent(node.parent, isReturnStatement, getReturnOccurrences);
      case 111 /* ThrowKeyword */:
        return useParent(node.parent, isThrowStatement, getThrowOccurrences);
      case 113 /* TryKeyword */:
      case 85 /* CatchKeyword */:
      case 98 /* FinallyKeyword */:
        const tryStatement = node.kind === 85 /* CatchKeyword */ ? node.parent.parent : node.parent;
        return useParent(tryStatement, isTryStatement, getTryCatchFinallyOccurrences);
      case 109 /* SwitchKeyword */:
        return useParent(node.parent, isSwitchStatement, getSwitchCaseDefaultOccurrences);
      case 84 /* CaseKeyword */:
      case 90 /* DefaultKeyword */: {
        if (isDefaultClause(node.parent) || isCaseClause(node.parent)) {
          return useParent(node.parent.parent.parent, isSwitchStatement, getSwitchCaseDefaultOccurrences);
        }
        return void 0;
      }
      case 83 /* BreakKeyword */:
      case 88 /* ContinueKeyword */:
        return useParent(node.parent, isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences);
      case 99 /* ForKeyword */:
      case 117 /* WhileKeyword */:
      case 92 /* DoKeyword */:
        return useParent(node.parent, (n) => isIterationStatement(
          n,
          /*lookInLabeledStatements*/
          true
        ), getLoopBreakContinueOccurrences);
      case 137 /* ConstructorKeyword */:
        return getFromAllDeclarations(isConstructorDeclaration, [137 /* ConstructorKeyword */]);
      case 139 /* GetKeyword */:
      case 153 /* SetKeyword */:
        return getFromAllDeclarations(isAccessor, [139 /* GetKeyword */, 153 /* SetKeyword */]);
      case 135 /* AwaitKeyword */:
        return useParent(node.parent, isAwaitExpression, getAsyncAndAwaitOccurrences);
      case 134 /* AsyncKeyword */:
        return highlightSpans(getAsyncAndAwaitOccurrences(node));
      case 127 /* YieldKeyword */:
        return highlightSpans(getYieldOccurrences(node));
      case 103 /* InKeyword */:
      case 147 /* OutKeyword */:
        return void 0;
      default:
        return isModifierKind(node.kind) && (isDeclaration(node.parent) || isVariableStatement(node.parent)) ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) : void 0;
    }
    function getFromAllDeclarations(nodeTest, keywords) {
      return useParent(node.parent, nodeTest, (decl) => {
        var _a;
        return mapDefined((_a = tryCast(decl, canHaveSymbol)) == null ? void 0 : _a.symbol.declarations, (d) => nodeTest(d) ? find(d.getChildren(sourceFile), (c) => contains(keywords, c.kind)) : void 0);
      });
    }
    function useParent(node2, nodeTest, getNodes4) {
      return nodeTest(node2) ? highlightSpans(getNodes4(node2, sourceFile)) : void 0;
    }
    function highlightSpans(nodes) {
      return nodes && nodes.map((node2) => getHighlightSpanForNode(node2, sourceFile));
    }
  }
  function aggregateOwnedThrowStatements(node) {
    if (isThrowStatement(node)) {
      return [node];
    } else if (isTryStatement(node)) {
      return concatenate(
        node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock),
        node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)
      );
    }
    return isFunctionLike(node) ? void 0 : flatMapChildren(node, aggregateOwnedThrowStatements);
  }
  function getThrowStatementOwner(throwStatement) {
    let child = throwStatement;
    while (child.parent) {
      const parent2 = child.parent;
      if (isFunctionBlock(parent2) || parent2.kind === 307 /* SourceFile */) {
        return parent2;
      }
      if (isTryStatement(parent2) && parent2.tryBlock === child && parent2.catchClause) {
        return child;
      }
      child = parent2;
    }
    return void 0;
  }
  function aggregateAllBreakAndContinueStatements(node) {
    return isBreakOrContinueStatement(node) ? [node] : isFunctionLike(node) ? void 0 : flatMapChildren(node, aggregateAllBreakAndContinueStatements);
  }
  function flatMapChildren(node, cb) {
    const result = [];
    node.forEachChild((child) => {
      const value = cb(child);
      if (value !== void 0) {
        result.push(...toArray(value));
      }
    });
    return result;
  }
  function ownsBreakOrContinueStatement(owner, statement) {
    const actualOwner = getBreakOrContinueOwner(statement);
    return !!actualOwner && actualOwner === owner;
  }
  function getBreakOrContinueOwner(statement) {
    return findAncestor(statement, (node) => {
      switch (node.kind) {
        case 255 /* SwitchStatement */:
          if (statement.kind === 251 /* ContinueStatement */) {
            return false;
          }
        // falls through
        case 248 /* ForStatement */:
        case 249 /* ForInStatement */:
        case 250 /* ForOfStatement */:
        case 247 /* WhileStatement */:
        case 246 /* DoStatement */:
          return !statement.label || isLabeledBy(node, statement.label.escapedText);
        default:
          return isFunctionLike(node) && "quit";
      }
    });
  }
  function getModifierOccurrences(modifier, declaration) {
    return mapDefined(getNodesToSearchForModifier(declaration, modifierToFlag(modifier)), (node) => findModifier(node, modifier));
  }
  function getNodesToSearchForModifier(declaration, modifierFlag) {
    const container = declaration.parent;
    switch (container.kind) {
      case 268 /* ModuleBlock */:
      case 307 /* SourceFile */:
      case 241 /* Block */:
      case 296 /* CaseClause */:
      case 297 /* DefaultClause */:
        if (modifierFlag & 64 /* Abstract */ && isClassDeclaration(declaration)) {
          return [...declaration.members, declaration];
        } else {
          return container.statements;
        }
      case 176 /* Constructor */:
      case 174 /* MethodDeclaration */:
      case 262 /* FunctionDeclaration */:
        return [...container.parameters, ...isClassLike(container.parent) ? container.parent.members : []];
      case 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
      case 264 /* InterfaceDeclaration */:
      case 187 /* TypeLiteral */:
        const nodes = container.members;
        if (modifierFlag & (7 /* AccessibilityModifier */ | 8 /* Readonly */)) {
          const constructor = find(container.members, isConstructorDeclaration);
          if (constructor) {
            return [...nodes, ...constructor.parameters];
          }
        } else if (modifierFlag & 64 /* Abstract */) {
          return [...nodes, container];
        }
        return nodes;
      // Syntactically invalid positions that the parser might produce anyway
      default:
        return void 0;
    }
  }
  function pushKeywordIf(keywordList, token, ...expected) {
    if (token && contains(expected, token.kind)) {
      keywordList.push(token);
      return true;
    }
    return false;
  }
  function getLoopBreakContinueOccurrences(loopNode) {
    const keywords = [];
    if (pushKeywordIf(keywords, loopNode.getFirstToken(), 99 /* ForKeyword */, 117 /* WhileKeyword */, 92 /* DoKeyword */)) {
      if (loopNode.kind === 246 /* DoStatement */) {
        const loopTokens = loopNode.getChildren();
        for (let i = loopTokens.length - 1; i >= 0; i--) {
          if (pushKeywordIf(keywords, loopTokens[i], 117 /* WhileKeyword */)) {
            break;
          }
        }
      }
    }
    forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), (statement) => {
      if (ownsBreakOrContinueStatement(loopNode, statement)) {
        pushKeywordIf(keywords, statement.getFirstToken(), 83 /* BreakKeyword */, 88 /* ContinueKeyword */);
      }
    });
    return keywords;
  }
  function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) {
    const owner = getBreakOrContinueOwner(breakOrContinueStatement);
    if (owner) {
      switch (owner.kind) {
        case 248 /* ForStatement */:
        case 249 /* ForInStatement */:
        case 250 /* ForOfStatement */:
        case 246 /* DoStatement */:
        case 247 /* WhileStatement */:
          return getLoopBreakContinueOccurrences(owner);
        case 255 /* SwitchStatement */:
          return getSwitchCaseDefaultOccurrences(owner);
      }
    }
    return void 0;
  }
  function getSwitchCaseDefaultOccurrences(switchStatement) {
    const keywords = [];
    pushKeywordIf(keywords, switchStatement.getFirstToken(), 109 /* SwitchKeyword */);
    forEach(switchStatement.caseBlock.clauses, (clause) => {
      pushKeywordIf(keywords, clause.getFirstToken(), 84 /* CaseKeyword */, 90 /* DefaultKeyword */);
      forEach(aggregateAllBreakAndContinueStatements(clause), (statement) => {
        if (ownsBreakOrContinueStatement(switchStatement, statement)) {
          pushKeywordIf(keywords, statement.getFirstToken(), 83 /* BreakKeyword */);
        }
      });
    });
    return keywords;
  }
  function getTryCatchFinallyOccurrences(tryStatement, sourceFile) {
    const keywords = [];
    pushKeywordIf(keywords, tryStatement.getFirstToken(), 113 /* TryKeyword */);
    if (tryStatement.catchClause) {
      pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 85 /* CatchKeyword */);
    }
    if (tryStatement.finallyBlock) {
      const finallyKeyword = findChildOfKind(tryStatement, 98 /* FinallyKeyword */, sourceFile);
      pushKeywordIf(keywords, finallyKeyword, 98 /* FinallyKeyword */);
    }
    return keywords;
  }
  function getThrowOccurrences(throwStatement, sourceFile) {
    const owner = getThrowStatementOwner(throwStatement);
    if (!owner) {
      return void 0;
    }
    const keywords = [];
    forEach(aggregateOwnedThrowStatements(owner), (throwStatement2) => {
      keywords.push(findChildOfKind(throwStatement2, 111 /* ThrowKeyword */, sourceFile));
    });
    if (isFunctionBlock(owner)) {
      forEachReturnStatement(owner, (returnStatement) => {
        keywords.push(findChildOfKind(returnStatement, 107 /* ReturnKeyword */, sourceFile));
      });
    }
    return keywords;
  }
  function getReturnOccurrences(returnStatement, sourceFile) {
    const func = getContainingFunction(returnStatement);
    if (!func) {
      return void 0;
    }
    const keywords = [];
    forEachReturnStatement(cast(func.body, isBlock), (returnStatement2) => {
      keywords.push(findChildOfKind(returnStatement2, 107 /* ReturnKeyword */, sourceFile));
    });
    forEach(aggregateOwnedThrowStatements(func.body), (throwStatement) => {
      keywords.push(findChildOfKind(throwStatement, 111 /* ThrowKeyword */, sourceFile));
    });
    return keywords;
  }
  function getAsyncAndAwaitOccurrences(node) {
    const func = getContainingFunction(node);
    if (!func) {
      return void 0;
    }
    const keywords = [];
    if (func.modifiers) {
      func.modifiers.forEach((modifier) => {
        pushKeywordIf(keywords, modifier, 134 /* AsyncKeyword */);
      });
    }
    forEachChild(func, (child) => {
      traverseWithoutCrossingFunction(child, (node2) => {
        if (isAwaitExpression(node2)) {
          pushKeywordIf(keywords, node2.getFirstToken(), 135 /* AwaitKeyword */);
        }
      });
    });
    return keywords;
  }
  function getYieldOccurrences(node) {
    const func = getContainingFunction(node);
    if (!func) {
      return void 0;
    }
    const keywords = [];
    forEachChild(func, (child) => {
      traverseWithoutCrossingFunction(child, (node2) => {
        if (isYieldExpression(node2)) {
          pushKeywordIf(keywords, node2.getFirstToken(), 127 /* YieldKeyword */);
        }
      });
    });
    return keywords;
  }
  function traverseWithoutCrossingFunction(node, cb) {
    cb(node);
    if (!isFunctionLike(node) && !isClassLike(node) && !isInterfaceDeclaration(node) && !isModuleDeclaration(node) && !isTypeAliasDeclaration(node) && !isTypeNode(node)) {
      forEachChild(node, (child) => traverseWithoutCrossingFunction(child, cb));
    }
  }
  function getIfElseOccurrences(ifStatement, sourceFile) {
    const keywords = getIfElseKeywords(ifStatement, sourceFile);
    const result = [];
    for (let i = 0; i < keywords.length; i++) {
      if (keywords[i].kind === 93 /* ElseKeyword */ && i < keywords.length - 1) {
        const elseKeyword = keywords[i];
        const ifKeyword = keywords[i + 1];
        let shouldCombineElseAndIf = true;
        for (let j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) {
          if (!isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) {
            shouldCombineElseAndIf = false;
            break;
          }
        }
        if (shouldCombineElseAndIf) {
          result.push({
            fileName: sourceFile.fileName,
            textSpan: createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end),
            kind: "reference" /* reference */
          });
          i++;
          continue;
        }
      }
      result.push(getHighlightSpanForNode(keywords[i], sourceFile));
    }
    return result;
  }
  function getIfElseKeywords(ifStatement, sourceFile) {
    const keywords = [];
    while (isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) {
      ifStatement = ifStatement.parent;
    }
    while (true) {
      const children = ifStatement.getChildren(sourceFile);
      pushKeywordIf(keywords, children[0], 101 /* IfKeyword */);
      for (let i = children.length - 1; i >= 0; i--) {
        if (pushKeywordIf(keywords, children[i], 93 /* ElseKeyword */)) {
          break;
        }
      }
      if (!ifStatement.elseStatement || !isIfStatement(ifStatement.elseStatement)) {
        break;
      }
      ifStatement = ifStatement.elseStatement;
    }
    return keywords;
  }
  function isLabeledBy(node, labelName) {
    return !!findAncestor(node.parent, (owner) => !isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName);
  }
})(DocumentHighlights || (DocumentHighlights = {}));

// src/services/documentRegistry.ts
function isDocumentRegistryEntry(entry) {
  return !!entry.sourceFile;
}
function createDocumentRegistry(useCaseSensitiveFileNames2, currentDirectory, jsDocParsingMode) {
  return createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory, jsDocParsingMode);
}
function createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory = "", jsDocParsingMode, externalCache) {
  const buckets = /* @__PURE__ */ new Map();
  const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames2);
  function reportStats() {
    const bucketInfoArray = arrayFrom(buckets.keys()).filter((name) => name && name.charAt(0) === "_").map((name) => {
      const entries = buckets.get(name);
      const sourceFiles = [];
      entries.forEach((entry, name2) => {
        if (isDocumentRegistryEntry(entry)) {
          sourceFiles.push({
            name: name2,
            scriptKind: entry.sourceFile.scriptKind,
            refCount: entry.languageServiceRefCount
          });
        } else {
          entry.forEach((value, scriptKind) => sourceFiles.push({ name: name2, scriptKind, refCount: value.languageServiceRefCount }));
        }
      });
      sourceFiles.sort((x, y) => y.refCount - x.refCount);
      return {
        bucket: name,
        sourceFiles
      };
    });
    return JSON.stringify(bucketInfoArray, void 0, 2);
  }
  function getCompilationSettings(settingsOrHost) {
    if (typeof settingsOrHost.getCompilationSettings === "function") {
      return settingsOrHost.getCompilationSettings();
    }
    return settingsOrHost;
  }
  function acquireDocument(fileName, compilationSettings, scriptSnapshot, version2, scriptKind, languageVersionOrOptions) {
    const path = toPath(fileName, currentDirectory, getCanonicalFileName);
    const key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings));
    return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions);
  }
  function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions) {
    return acquireOrUpdateDocument(
      fileName,
      path,
      compilationSettings,
      key,
      scriptSnapshot,
      version2,
      /*acquiring*/
      true,
      scriptKind,
      languageVersionOrOptions
    );
  }
  function updateDocument(fileName, compilationSettings, scriptSnapshot, version2, scriptKind, languageVersionOrOptions) {
    const path = toPath(fileName, currentDirectory, getCanonicalFileName);
    const key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings));
    return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions);
  }
  function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions) {
    return acquireOrUpdateDocument(
      fileName,
      path,
      getCompilationSettings(compilationSettings),
      key,
      scriptSnapshot,
      version2,
      /*acquiring*/
      false,
      scriptKind,
      languageVersionOrOptions
    );
  }
  function getDocumentRegistryEntry(bucketEntry, scriptKind) {
    const entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided"));
    Debug.assert(scriptKind === void 0 || !entry || entry.sourceFile.scriptKind === scriptKind, `Script kind should match provided ScriptKind:${scriptKind} and sourceFile.scriptKind: ${entry == null ? void 0 : entry.sourceFile.scriptKind}, !entry: ${!entry}`);
    return entry;
  }
  function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version2, acquiring, scriptKind, languageVersionOrOptions) {
    var _a, _b, _c, _d;
    scriptKind = ensureScriptKind(fileName, scriptKind);
    const compilationSettings = getCompilationSettings(compilationSettingsOrHost);
    const host = compilationSettingsOrHost === compilationSettings ? void 0 : compilationSettingsOrHost;
    const scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : getEmitScriptTarget(compilationSettings);
    const sourceFileOptions = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : {
      languageVersion: scriptTarget,
      impliedNodeFormat: host && getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getModuleResolutionCache) == null ? void 0 : _c.call(_b)) == null ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings),
      setExternalModuleIndicator: getSetExternalModuleIndicator(compilationSettings),
      jsDocParsingMode
    };
    sourceFileOptions.languageVersion = scriptTarget;
    Debug.assertEqual(jsDocParsingMode, sourceFileOptions.jsDocParsingMode);
    const oldBucketCount = buckets.size;
    const keyWithMode = getDocumentRegistryBucketKeyWithMode(key, sourceFileOptions.impliedNodeFormat);
    const bucket = getOrUpdate(buckets, keyWithMode, () => /* @__PURE__ */ new Map());
    if (tracing) {
      if (buckets.size > oldBucketCount) {
        tracing.instant(tracing.Phase.Session, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: keyWithMode });
      }
      const otherBucketKey = !isDeclarationFileName(path) && forEachEntry(buckets, (bucket2, bucketKey) => bucketKey !== keyWithMode && bucket2.has(path) && bucketKey);
      if (otherBucketKey) {
        tracing.instant(tracing.Phase.Session, "documentRegistryBucketOverlap", { path, key1: otherBucketKey, key2: keyWithMode });
      }
    }
    const bucketEntry = bucket.get(path);
    let entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind);
    if (!entry && externalCache) {
      const sourceFile = externalCache.getDocument(keyWithMode, path);
      if (sourceFile && sourceFile.scriptKind === scriptKind && sourceFile.text === getSnapshotText(scriptSnapshot)) {
        Debug.assert(acquiring);
        entry = {
          sourceFile,
          languageServiceRefCount: 0
        };
        setBucketEntry();
      }
    }
    if (!entry) {
      const sourceFile = createLanguageServiceSourceFile(
        fileName,
        scriptSnapshot,
        sourceFileOptions,
        version2,
        /*setNodeParents*/
        false,
        scriptKind
      );
      if (externalCache) {
        externalCache.setDocument(keyWithMode, path, sourceFile);
      }
      entry = {
        sourceFile,
        languageServiceRefCount: 1
      };
      setBucketEntry();
    } else {
      if (entry.sourceFile.version !== version2) {
        entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version2, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot));
        if (externalCache) {
          externalCache.setDocument(keyWithMode, path, entry.sourceFile);
        }
      }
      if (acquiring) {
        entry.languageServiceRefCount++;
      }
    }
    Debug.assert(entry.languageServiceRefCount !== 0);
    return entry.sourceFile;
    function setBucketEntry() {
      if (!bucketEntry) {
        bucket.set(path, entry);
      } else if (isDocumentRegistryEntry(bucketEntry)) {
        const scriptKindMap = /* @__PURE__ */ new Map();
        scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry);
        scriptKindMap.set(scriptKind, entry);
        bucket.set(path, scriptKindMap);
      } else {
        bucketEntry.set(scriptKind, entry);
      }
    }
  }
  function releaseDocument(fileName, compilationSettings, scriptKind, impliedNodeFormat) {
    const path = toPath(fileName, currentDirectory, getCanonicalFileName);
    const key = getKeyForCompilationSettings(compilationSettings);
    return releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat);
  }
  function releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat) {
    const bucket = Debug.checkDefined(buckets.get(getDocumentRegistryBucketKeyWithMode(key, impliedNodeFormat)));
    const bucketEntry = bucket.get(path);
    const entry = getDocumentRegistryEntry(bucketEntry, scriptKind);
    entry.languageServiceRefCount--;
    Debug.assert(entry.languageServiceRefCount >= 0);
    if (entry.languageServiceRefCount === 0) {
      if (isDocumentRegistryEntry(bucketEntry)) {
        bucket.delete(path);
      } else {
        bucketEntry.delete(scriptKind);
        if (bucketEntry.size === 1) {
          bucket.set(path, firstDefinedIterator(bucketEntry.values(), identity));
        }
      }
    }
  }
  return {
    acquireDocument,
    acquireDocumentWithKey,
    updateDocument,
    updateDocumentWithKey,
    releaseDocument,
    releaseDocumentWithKey,
    getKeyForCompilationSettings,
    getDocumentRegistryBucketKeyWithMode,
    reportStats,
    getBuckets: () => buckets
  };
}
function getKeyForCompilationSettings(settings) {
  return getKeyForCompilerOptions(settings, sourceFileAffectingCompilerOptions);
}
function getDocumentRegistryBucketKeyWithMode(key, mode) {
  return mode ? `${key}|${mode}` : key;
}

// src/services/getEditsForFileRename.ts
function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) {
  const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host);
  const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2);
  const oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper);
  const newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper);
  return ts_textChanges_exports.ChangeTracker.with({ host, formatContext, preferences }, (changeTracker) => {
    updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames2);
    updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName);
  });
}
function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) {
  const canonicalOldPath = getCanonicalFileName(oldFileOrDirPath);
  return (path) => {
    const originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 });
    const updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path);
    return originalPath ? updatedPath === void 0 ? void 0 : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) : updatedPath;
  };
  function getUpdatedPath(pathToUpdate) {
    if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) return newFileOrDirPath;
    const suffix = tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName);
    return suffix === void 0 ? void 0 : newFileOrDirPath + "/" + suffix;
  }
}
function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) {
  const rel = getRelativePathFromFile(a0, b0, getCanonicalFileName);
  return combinePathsSafe(getDirectoryPath(a1), rel);
}
function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames2) {
  const { configFile } = program.getCompilerOptions();
  if (!configFile) return;
  const configDir = getDirectoryPath(configFile.fileName);
  const jsonObjectLiteral = getTsConfigObjectLiteralExpression(configFile);
  if (!jsonObjectLiteral) return;
  forEachProperty(jsonObjectLiteral, (property, propertyName) => {
    switch (propertyName) {
      case "files":
      case "include":
      case "exclude": {
        const foundExactMatch = updatePaths(property);
        if (foundExactMatch || propertyName !== "include" || !isArrayLiteralExpression(property.initializer)) return;
        const includes = mapDefined(property.initializer.elements, (e) => isStringLiteral(e) ? e.text : void 0);
        if (includes.length === 0) return;
        const matchers = getFileMatcherPatterns(
          configDir,
          /*excludes*/
          [],
          includes,
          useCaseSensitiveFileNames2,
          currentDirectory
        );
        if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(newFileOrDirPath)) {
          changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), factory.createStringLiteral(relativePath(newFileOrDirPath)));
        }
        return;
      }
      case "compilerOptions":
        forEachProperty(property.initializer, (property2, propertyName2) => {
          const option = getOptionFromName(propertyName2);
          Debug.assert((option == null ? void 0 : option.type) !== "listOrElement");
          if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) {
            updatePaths(property2);
          } else if (propertyName2 === "paths") {
            forEachProperty(property2.initializer, (pathsProperty) => {
              if (!isArrayLiteralExpression(pathsProperty.initializer)) return;
              for (const e of pathsProperty.initializer.elements) {
                tryUpdateString(e);
              }
            });
          }
        });
        return;
    }
  });
  function updatePaths(property) {
    const elements = isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer];
    let foundExactMatch = false;
    for (const element of elements) {
      foundExactMatch = tryUpdateString(element) || foundExactMatch;
    }
    return foundExactMatch;
  }
  function tryUpdateString(element) {
    if (!isStringLiteral(element)) return false;
    const elementFileName = combinePathsSafe(configDir, element.text);
    const updated = oldToNew(elementFileName);
    if (updated !== void 0) {
      changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated));
      return true;
    }
    return false;
  }
  function relativePath(path) {
    return getRelativePathFromDirectory(
      configDir,
      path,
      /*ignoreCase*/
      !useCaseSensitiveFileNames2
    );
  }
}
function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
  const allFiles = program.getSourceFiles();
  for (const sourceFile of allFiles) {
    const newFromOld = oldToNew(sourceFile.fileName);
    const newImportFromPath = newFromOld ?? sourceFile.fileName;
    const newImportFromDirectory = getDirectoryPath(newImportFromPath);
    const oldFromNew = newToOld(sourceFile.fileName);
    const oldImportFromPath = oldFromNew || sourceFile.fileName;
    const oldImportFromDirectory = getDirectoryPath(oldImportFromPath);
    const importingSourceFileMoved = newFromOld !== void 0 || oldFromNew !== void 0;
    updateImportsWorker(sourceFile, changeTracker, (referenceText) => {
      if (!pathIsRelative(referenceText)) return void 0;
      const oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText);
      const newAbsolute = oldToNew(oldAbsolute);
      return newAbsolute === void 0 ? void 0 : ensurePathIsNonModuleName(getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName));
    }, (importLiteral) => {
      const importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral);
      if ((importedModuleSymbol == null ? void 0 : importedModuleSymbol.declarations) && importedModuleSymbol.declarations.some((d) => isAmbientModule(d))) return void 0;
      const toImport = oldFromNew !== void 0 ? getSourceFileToImportFromResolved(importLiteral, resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, allFiles) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew);
      return toImport !== void 0 && (toImport.updated || importingSourceFileMoved && pathIsRelative(importLiteral.text)) ? ts_moduleSpecifiers_exports.updateModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, createModuleSpecifierResolutionHost(program, host), importLiteral.text) : void 0;
    });
  }
}
function combineNormal(pathA, pathB) {
  return normalizePath(combinePaths(pathA, pathB));
}
function combinePathsSafe(pathA, pathB) {
  return ensurePathIsNonModuleName(combineNormal(pathA, pathB));
}
function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) {
  if (importedModuleSymbol) {
    const oldFileName = find(importedModuleSymbol.declarations, isSourceFile).fileName;
    const newFileName = oldToNew(oldFileName);
    return newFileName === void 0 ? { newFileName: oldFileName, updated: false } : { newFileName, updated: true };
  } else {
    const mode = program.getModeForUsageLocation(importingSourceFile, importLiteral);
    const resolved = host.resolveModuleNameLiterals || !host.resolveModuleNames ? program.getResolvedModuleFromModuleSpecifier(importLiteral, importingSourceFile) : host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName, mode);
    return getSourceFileToImportFromResolved(importLiteral, resolved, oldToNew, program.getSourceFiles());
  }
}
function getSourceFileToImportFromResolved(importLiteral, resolved, oldToNew, sourceFiles) {
  if (!resolved) return void 0;
  if (resolved.resolvedModule) {
    const result2 = tryChange(resolved.resolvedModule.resolvedFileName);
    if (result2) return result2;
  }
  const result = forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJsonExisting) || pathIsRelative(importLiteral.text) && forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
  if (result) return result;
  return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false };
  function tryChangeWithIgnoringPackageJsonExisting(oldFileName) {
    const newFileName = oldToNew(oldFileName);
    return newFileName && find(sourceFiles, (src) => src.fileName === newFileName) ? tryChangeWithIgnoringPackageJson(oldFileName) : void 0;
  }
  function tryChangeWithIgnoringPackageJson(oldFileName) {
    return !endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : void 0;
  }
  function tryChange(oldFileName) {
    const newFileName = oldToNew(oldFileName);
    return newFileName && { newFileName, updated: true };
  }
}
function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) {
  for (const ref of sourceFile.referencedFiles || emptyArray) {
    const updated = updateRef(ref.fileName);
    if (updated !== void 0 && updated !== sourceFile.text.slice(ref.pos, ref.end)) changeTracker.replaceRangeWithText(sourceFile, ref, updated);
  }
  for (const importStringLiteral of sourceFile.imports) {
    const updated = updateImport(importStringLiteral);
    if (updated !== void 0 && updated !== importStringLiteral.text) changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated);
  }
}
function createStringRange(node, sourceFile) {
  return createRange(node.getStart(sourceFile) + 1, node.end - 1);
}
function forEachProperty(objectLiteral, cb) {
  if (!isObjectLiteralExpression(objectLiteral)) return;
  for (const property of objectLiteral.properties) {
    if (isPropertyAssignment(property) && isStringLiteral(property.name)) {
      cb(property, property.name.text);
    }
  }
}

// src/services/patternMatcher.ts
var PatternMatchKind = /* @__PURE__ */ ((PatternMatchKind2) => {
  PatternMatchKind2[PatternMatchKind2["exact"] = 0] = "exact";
  PatternMatchKind2[PatternMatchKind2["prefix"] = 1] = "prefix";
  PatternMatchKind2[PatternMatchKind2["substring"] = 2] = "substring";
  PatternMatchKind2[PatternMatchKind2["camelCase"] = 3] = "camelCase";
  return PatternMatchKind2;
})(PatternMatchKind || {});
function createPatternMatch(kind, isCaseSensitive) {
  return {
    kind,
    isCaseSensitive
  };
}
function createPatternMatcher(pattern) {
  const stringToWordSpans = /* @__PURE__ */ new Map();
  const dotSeparatedSegments = pattern.trim().split(".").map((p) => createSegment(p.trim()));
  if (dotSeparatedSegments.length === 1 && dotSeparatedSegments[0].totalTextChunk.text === "") {
    return {
      getMatchForLastSegmentOfPattern: () => createPatternMatch(
        2 /* substring */,
        /*isCaseSensitive*/
        true
      ),
      getFullMatch: () => createPatternMatch(
        2 /* substring */,
        /*isCaseSensitive*/
        true
      ),
      patternContainsDots: false
    };
  }
  if (dotSeparatedSegments.some((segment) => !segment.subWordTextChunks.length)) return void 0;
  return {
    getFullMatch: (containers, candidate) => getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans),
    getMatchForLastSegmentOfPattern: (candidate) => matchSegment(candidate, last(dotSeparatedSegments), stringToWordSpans),
    patternContainsDots: dotSeparatedSegments.length > 1
  };
}
function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) {
  const candidateMatch = matchSegment(candidate, last(dotSeparatedSegments), stringToWordSpans);
  if (!candidateMatch) {
    return void 0;
  }
  if (dotSeparatedSegments.length - 1 > candidateContainers.length) {
    return void 0;
  }
  let bestMatch;
  for (let i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) {
    bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans));
  }
  return bestMatch;
}
function getWordSpans(word, stringToWordSpans) {
  let spans = stringToWordSpans.get(word);
  if (!spans) {
    stringToWordSpans.set(word, spans = breakIntoWordSpans(word));
  }
  return spans;
}
function matchTextChunk(candidate, chunk, stringToWordSpans) {
  const index = indexOfIgnoringCase(candidate, chunk.textLowerCase);
  if (index === 0) {
    return createPatternMatch(
      chunk.text.length === candidate.length ? 0 /* exact */ : 1 /* prefix */,
      /*isCaseSensitive:*/
      startsWith(candidate, chunk.text)
    );
  }
  if (chunk.isLowerCase) {
    if (index === -1) return void 0;
    const wordSpans = getWordSpans(candidate, stringToWordSpans);
    for (const span of wordSpans) {
      if (partStartsWith(
        candidate,
        span,
        chunk.text,
        /*ignoreCase*/
        true
      )) {
        return createPatternMatch(
          2 /* substring */,
          /*isCaseSensitive:*/
          partStartsWith(
            candidate,
            span,
            chunk.text,
            /*ignoreCase*/
            false
          )
        );
      }
    }
    if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) {
      return createPatternMatch(
        2 /* substring */,
        /*isCaseSensitive*/
        false
      );
    }
  } else {
    if (candidate.indexOf(chunk.text) > 0) {
      return createPatternMatch(
        2 /* substring */,
        /*isCaseSensitive*/
        true
      );
    }
    if (chunk.characterSpans.length > 0) {
      const candidateParts = getWordSpans(candidate, stringToWordSpans);
      const isCaseSensitive = tryCamelCaseMatch(
        candidate,
        candidateParts,
        chunk,
        /*ignoreCase*/
        false
      ) ? true : tryCamelCaseMatch(
        candidate,
        candidateParts,
        chunk,
        /*ignoreCase*/
        true
      ) ? false : void 0;
      if (isCaseSensitive !== void 0) {
        return createPatternMatch(3 /* camelCase */, isCaseSensitive);
      }
    }
  }
}
function matchSegment(candidate, segment, stringToWordSpans) {
  if (every2(segment.totalTextChunk.text, (ch) => ch !== 32 /* space */ && ch !== 42 /* asterisk */)) {
    const match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans);
    if (match) return match;
  }
  const subWordTextChunks = segment.subWordTextChunks;
  let bestMatch;
  for (const subWordTextChunk of subWordTextChunks) {
    bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans));
  }
  return bestMatch;
}
function betterMatch(a, b) {
  return min([a, b], compareMatches);
}
function compareMatches(a, b) {
  return a === void 0 ? 1 /* GreaterThan */ : b === void 0 ? -1 /* LessThan */ : compareValues(a.kind, b.kind) || compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive);
}
function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan = { start: 0, length: pattern.length }) {
  return patternSpan.length <= candidateSpan.length && everyInRange(0, patternSpan.length, (i) => equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase));
}
function equalChars(ch1, ch2, ignoreCase) {
  return ignoreCase ? toLowerCase2(ch1) === toLowerCase2(ch2) : ch1 === ch2;
}
function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) {
  const chunkCharacterSpans = chunk.characterSpans;
  let currentCandidate = 0;
  let currentChunkSpan = 0;
  let firstMatch;
  let contiguous;
  while (true) {
    if (currentChunkSpan === chunkCharacterSpans.length) {
      return true;
    } else if (currentCandidate === candidateParts.length) {
      return false;
    }
    let candidatePart = candidateParts[currentCandidate];
    let gotOneMatchThisCandidate = false;
    for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) {
      const chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan];
      if (gotOneMatchThisCandidate) {
        if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) {
          break;
        }
      }
      if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) {
        break;
      }
      gotOneMatchThisCandidate = true;
      firstMatch = firstMatch === void 0 ? currentCandidate : firstMatch;
      contiguous = contiguous === void 0 ? true : contiguous;
      candidatePart = createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length);
    }
    if (!gotOneMatchThisCandidate && contiguous !== void 0) {
      contiguous = false;
    }
    currentCandidate++;
  }
}
function createSegment(text) {
  return {
    totalTextChunk: createTextChunk(text),
    subWordTextChunks: breakPatternIntoTextChunks(text)
  };
}
function isUpperCaseLetter(ch) {
  if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
    return true;
  }
  if (ch < 127 /* maxAsciiCharacter */ || !isUnicodeIdentifierStart(ch, 99 /* Latest */)) {
    return false;
  }
  const str = String.fromCharCode(ch);
  return str === str.toUpperCase();
}
function isLowerCaseLetter(ch) {
  if (ch >= 97 /* a */ && ch <= 122 /* z */) {
    return true;
  }
  if (ch < 127 /* maxAsciiCharacter */ || !isUnicodeIdentifierStart(ch, 99 /* Latest */)) {
    return false;
  }
  const str = String.fromCharCode(ch);
  return str === str.toLowerCase();
}
function indexOfIgnoringCase(str, value) {
  const n = str.length - value.length;
  for (let start = 0; start <= n; start++) {
    if (every2(value, (valueChar, i) => toLowerCase2(str.charCodeAt(i + start)) === valueChar)) {
      return start;
    }
  }
  return -1;
}
function toLowerCase2(ch) {
  if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
    return 97 /* a */ + (ch - 65 /* A */);
  }
  if (ch < 127 /* maxAsciiCharacter */) {
    return ch;
  }
  return String.fromCharCode(ch).toLowerCase().charCodeAt(0);
}
function isDigit2(ch) {
  return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
}
function isWordChar(ch) {
  return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit2(ch) || ch === 95 /* _ */ || ch === 36 /* $ */;
}
function breakPatternIntoTextChunks(pattern) {
  const result = [];
  let wordStart = 0;
  let wordLength = 0;
  for (let i = 0; i < pattern.length; i++) {
    const ch = pattern.charCodeAt(i);
    if (isWordChar(ch)) {
      if (wordLength === 0) {
        wordStart = i;
      }
      wordLength++;
    } else {
      if (wordLength > 0) {
        result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
        wordLength = 0;
      }
    }
  }
  if (wordLength > 0) {
    result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
  }
  return result;
}
function createTextChunk(text) {
  const textLowerCase = text.toLowerCase();
  return {
    text,
    textLowerCase,
    isLowerCase: text === textLowerCase,
    characterSpans: breakIntoCharacterSpans(text)
  };
}
function breakIntoCharacterSpans(identifier) {
  return breakIntoSpans(
    identifier,
    /*word*/
    false
  );
}
function breakIntoWordSpans(identifier) {
  return breakIntoSpans(
    identifier,
    /*word*/
    true
  );
}
function breakIntoSpans(identifier, word) {
  const result = [];
  let wordStart = 0;
  for (let i = 1; i < identifier.length; i++) {
    const lastIsDigit = isDigit2(identifier.charCodeAt(i - 1));
    const currentIsDigit = isDigit2(identifier.charCodeAt(i));
    const hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i);
    const hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart);
    if (charIsPunctuation(identifier.charCodeAt(i - 1)) || charIsPunctuation(identifier.charCodeAt(i)) || lastIsDigit !== currentIsDigit || hasTransitionFromLowerToUpper || hasTransitionFromUpperToLower) {
      if (!isAllPunctuation(identifier, wordStart, i)) {
        result.push(createTextSpan(wordStart, i - wordStart));
      }
      wordStart = i;
    }
  }
  if (!isAllPunctuation(identifier, wordStart, identifier.length)) {
    result.push(createTextSpan(wordStart, identifier.length - wordStart));
  }
  return result;
}
function charIsPunctuation(ch) {
  switch (ch) {
    case 33 /* exclamation */:
    case 34 /* doubleQuote */:
    case 35 /* hash */:
    case 37 /* percent */:
    case 38 /* ampersand */:
    case 39 /* singleQuote */:
    case 40 /* openParen */:
    case 41 /* closeParen */:
    case 42 /* asterisk */:
    case 44 /* comma */:
    case 45 /* minus */:
    case 46 /* dot */:
    case 47 /* slash */:
    case 58 /* colon */:
    case 59 /* semicolon */:
    case 63 /* question */:
    case 64 /* at */:
    case 91 /* openBracket */:
    case 92 /* backslash */:
    case 93 /* closeBracket */:
    case 95 /* _ */:
    case 123 /* openBrace */:
    case 125 /* closeBrace */:
      return true;
  }
  return false;
}
function isAllPunctuation(identifier, start, end) {
  return every2(identifier, (ch) => charIsPunctuation(ch) && ch !== 95 /* _ */, start, end);
}
function transitionFromUpperToLower(identifier, index, wordStart) {
  return index !== wordStart && index + 1 < identifier.length && isUpperCaseLetter(identifier.charCodeAt(index)) && isLowerCaseLetter(identifier.charCodeAt(index + 1)) && every2(identifier, isUpperCaseLetter, wordStart, index);
}
function transitionFromLowerToUpper(identifier, word, index) {
  const lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1));
  const currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index));
  return currentIsUpper && (!word || !lastIsUpper);
}
function everyInRange(start, end, pred) {
  for (let i = start; i < end; i++) {
    if (!pred(i)) {
      return false;
    }
  }
  return true;
}
function every2(s, pred, start = 0, end = s.length) {
  return everyInRange(start, end, (i) => pred(s.charCodeAt(i), i));
}

// src/services/preProcess.ts
function preProcessFile(sourceText, readImportFiles = true, detectJavaScriptImports = false) {
  const pragmaContext = {
    languageVersion: 1 /* ES5 */,
    // controls whether the token scanner considers unicode identifiers or not - shouldn't matter, since we're only using it for trivia
    pragmas: void 0,
    checkJsDirective: void 0,
    referencedFiles: [],
    typeReferenceDirectives: [],
    libReferenceDirectives: [],
    amdDependencies: [],
    hasNoDefaultLib: void 0,
    moduleName: void 0
  };
  const importedFiles = [];
  let ambientExternalModules;
  let lastToken;
  let currentToken;
  let braceNesting = 0;
  let externalModule = false;
  function nextToken() {
    lastToken = currentToken;
    currentToken = scanner.scan();
    if (currentToken === 19 /* OpenBraceToken */) {
      braceNesting++;
    } else if (currentToken === 20 /* CloseBraceToken */) {
      braceNesting--;
    }
    return currentToken;
  }
  function getFileReference() {
    const fileName = scanner.getTokenValue();
    const pos = scanner.getTokenStart();
    return { fileName, pos, end: pos + fileName.length };
  }
  function recordAmbientExternalModule() {
    if (!ambientExternalModules) {
      ambientExternalModules = [];
    }
    ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting });
  }
  function recordModuleName() {
    importedFiles.push(getFileReference());
    markAsExternalModuleIfTopLevel();
  }
  function markAsExternalModuleIfTopLevel() {
    if (braceNesting === 0) {
      externalModule = true;
    }
  }
  function tryConsumeDeclare() {
    let token = scanner.getToken();
    if (token === 138 /* DeclareKeyword */) {
      token = nextToken();
      if (token === 144 /* ModuleKeyword */) {
        token = nextToken();
        if (token === 11 /* StringLiteral */) {
          recordAmbientExternalModule();
        }
      }
      return true;
    }
    return false;
  }
  function tryConsumeImport() {
    if (lastToken === 25 /* DotToken */) {
      return false;
    }
    let token = scanner.getToken();
    if (token === 102 /* ImportKeyword */) {
      token = nextToken();
      if (token === 21 /* OpenParenToken */) {
        token = nextToken();
        if (token === 11 /* StringLiteral */ || token === 15 /* NoSubstitutionTemplateLiteral */) {
          recordModuleName();
          return true;
        }
      } else if (token === 11 /* StringLiteral */) {
        recordModuleName();
        return true;
      } else {
        if (token === 156 /* TypeKeyword */) {
          const skipTypeKeyword = scanner.lookAhead(() => {
            const token2 = scanner.scan();
            return token2 !== 161 /* FromKeyword */ && (token2 === 42 /* AsteriskToken */ || token2 === 19 /* OpenBraceToken */ || token2 === 80 /* Identifier */ || isKeyword(token2));
          });
          if (skipTypeKeyword) {
            token = nextToken();
          }
        }
        if (token === 80 /* Identifier */ || isKeyword(token)) {
          token = nextToken();
          if (token === 161 /* FromKeyword */) {
            token = nextToken();
            if (token === 11 /* StringLiteral */) {
              recordModuleName();
              return true;
            }
          } else if (token === 64 /* EqualsToken */) {
            if (tryConsumeRequireCall(
              /*skipCurrentToken*/
              true
            )) {
              return true;
            }
          } else if (token === 28 /* CommaToken */) {
            token = nextToken();
          } else {
            return true;
          }
        }
        if (token === 19 /* OpenBraceToken */) {
          token = nextToken();
          while (token !== 20 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
            token = nextToken();
          }
          if (token === 20 /* CloseBraceToken */) {
            token = nextToken();
            if (token === 161 /* FromKeyword */) {
              token = nextToken();
              if (token === 11 /* StringLiteral */) {
                recordModuleName();
              }
            }
          }
        } else if (token === 42 /* AsteriskToken */) {
          token = nextToken();
          if (token === 130 /* AsKeyword */) {
            token = nextToken();
            if (token === 80 /* Identifier */ || isKeyword(token)) {
              token = nextToken();
              if (token === 161 /* FromKeyword */) {
                token = nextToken();
                if (token === 11 /* StringLiteral */) {
                  recordModuleName();
                }
              }
            }
          }
        }
      }
      return true;
    }
    return false;
  }
  function tryConsumeExport() {
    let token = scanner.getToken();
    if (token === 95 /* ExportKeyword */) {
      markAsExternalModuleIfTopLevel();
      token = nextToken();
      if (token === 156 /* TypeKeyword */) {
        const skipTypeKeyword = scanner.lookAhead(() => {
          const token2 = scanner.scan();
          return token2 === 42 /* AsteriskToken */ || token2 === 19 /* OpenBraceToken */;
        });
        if (skipTypeKeyword) {
          token = nextToken();
        }
      }
      if (token === 19 /* OpenBraceToken */) {
        token = nextToken();
        while (token !== 20 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
          token = nextToken();
        }
        if (token === 20 /* CloseBraceToken */) {
          token = nextToken();
          if (token === 161 /* FromKeyword */) {
            token = nextToken();
            if (token === 11 /* StringLiteral */) {
              recordModuleName();
            }
          }
        }
      } else if (token === 42 /* AsteriskToken */) {
        token = nextToken();
        if (token === 161 /* FromKeyword */) {
          token = nextToken();
          if (token === 11 /* StringLiteral */) {
            recordModuleName();
          }
        }
      } else if (token === 102 /* ImportKeyword */) {
        token = nextToken();
        if (token === 156 /* TypeKeyword */) {
          const skipTypeKeyword = scanner.lookAhead(() => {
            const token2 = scanner.scan();
            return token2 === 80 /* Identifier */ || isKeyword(token2);
          });
          if (skipTypeKeyword) {
            token = nextToken();
          }
        }
        if (token === 80 /* Identifier */ || isKeyword(token)) {
          token = nextToken();
          if (token === 64 /* EqualsToken */) {
            if (tryConsumeRequireCall(
              /*skipCurrentToken*/
              true
            )) {
              return true;
            }
          }
        }
      }
      return true;
    }
    return false;
  }
  function tryConsumeRequireCall(skipCurrentToken, allowTemplateLiterals = false) {
    let token = skipCurrentToken ? nextToken() : scanner.getToken();
    if (token === 149 /* RequireKeyword */) {
      token = nextToken();
      if (token === 21 /* OpenParenToken */) {
        token = nextToken();
        if (token === 11 /* StringLiteral */ || allowTemplateLiterals && token === 15 /* NoSubstitutionTemplateLiteral */) {
          recordModuleName();
        }
      }
      return true;
    }
    return false;
  }
  function tryConsumeDefine() {
    let token = scanner.getToken();
    if (token === 80 /* Identifier */ && scanner.getTokenValue() === "define") {
      token = nextToken();
      if (token !== 21 /* OpenParenToken */) {
        return true;
      }
      token = nextToken();
      if (token === 11 /* StringLiteral */ || token === 15 /* NoSubstitutionTemplateLiteral */) {
        token = nextToken();
        if (token === 28 /* CommaToken */) {
          token = nextToken();
        } else {
          return true;
        }
      }
      if (token !== 23 /* OpenBracketToken */) {
        return true;
      }
      token = nextToken();
      while (token !== 24 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) {
        if (token === 11 /* StringLiteral */ || token === 15 /* NoSubstitutionTemplateLiteral */) {
          recordModuleName();
        }
        token = nextToken();
      }
      return true;
    }
    return false;
  }
  function processImports() {
    scanner.setText(sourceText);
    nextToken();
    while (true) {
      if (scanner.getToken() === 1 /* EndOfFileToken */) {
        break;
      }
      if (scanner.getToken() === 16 /* TemplateHead */) {
        const stack = [scanner.getToken()];
        loop:
          while (length(stack)) {
            const token = scanner.scan();
            switch (token) {
              case 1 /* EndOfFileToken */:
                break loop;
              case 102 /* ImportKeyword */:
                tryConsumeImport();
                break;
              case 16 /* TemplateHead */:
                stack.push(token);
                break;
              case 19 /* OpenBraceToken */:
                if (length(stack)) {
                  stack.push(token);
                }
                break;
              case 20 /* CloseBraceToken */:
                if (length(stack)) {
                  if (lastOrUndefined(stack) === 16 /* TemplateHead */) {
                    if (scanner.reScanTemplateToken(
                      /*isTaggedTemplate*/
                      false
                    ) === 18 /* TemplateTail */) {
                      stack.pop();
                    }
                  } else {
                    stack.pop();
                  }
                }
                break;
            }
          }
        nextToken();
      }
      if (tryConsumeDeclare() || tryConsumeImport() || tryConsumeExport() || detectJavaScriptImports && (tryConsumeRequireCall(
        /*skipCurrentToken*/
        false,
        /*allowTemplateLiterals*/
        true
      ) || tryConsumeDefine())) {
        continue;
      } else {
        nextToken();
      }
    }
    scanner.setText(void 0);
  }
  if (readImportFiles) {
    processImports();
  }
  processCommentPragmas(pragmaContext, sourceText);
  processPragmasIntoFields(pragmaContext, noop);
  if (externalModule) {
    if (ambientExternalModules) {
      for (const decl of ambientExternalModules) {
        importedFiles.push(decl.ref);
      }
    }
    return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: void 0 };
  } else {
    let ambientModuleNames;
    if (ambientExternalModules) {
      for (const decl of ambientExternalModules) {
        if (decl.depth === 0) {
          if (!ambientModuleNames) {
            ambientModuleNames = [];
          }
          ambientModuleNames.push(decl.ref.fileName);
        } else {
          importedFiles.push(decl.ref);
        }
      }
    }
    return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames };
  }
}

// src/services/sourcemaps.ts
var base64UrlRegExp = /^data:(?:application\/json;charset=[uU][tT][fF]-8;base64,([A-Za-z0-9+/=]+)$)?/;
function getSourceMapper(host) {
  const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
  const currentDirectory = host.getCurrentDirectory();
  const sourceFileLike = /* @__PURE__ */ new Map();
  const documentPositionMappers = /* @__PURE__ */ new Map();
  return {
    tryGetSourcePosition,
    tryGetGeneratedPosition,
    toLineColumnOffset,
    clearCache,
    documentPositionMappers
  };
  function toPath3(fileName) {
    return toPath(fileName, currentDirectory, getCanonicalFileName);
  }
  function getDocumentPositionMapper2(generatedFileName, sourceFileName) {
    const path = toPath3(generatedFileName);
    const value = documentPositionMappers.get(path);
    if (value) return value;
    let mapper;
    if (host.getDocumentPositionMapper) {
      mapper = host.getDocumentPositionMapper(generatedFileName, sourceFileName);
    } else if (host.readFile) {
      const file = getSourceFileLike(generatedFileName);
      mapper = file && getDocumentPositionMapper(
        { getSourceFileLike, getCanonicalFileName, log: (s) => host.log(s) },
        generatedFileName,
        getLineInfo(file.text, getLineStarts(file)),
        (f) => !host.fileExists || host.fileExists(f) ? host.readFile(f) : void 0
      );
    }
    documentPositionMappers.set(path, mapper || identitySourceMapConsumer);
    return mapper || identitySourceMapConsumer;
  }
  function tryGetSourcePosition(info) {
    if (!isDeclarationFileName(info.fileName)) return void 0;
    const file = getSourceFile(info.fileName);
    if (!file) return void 0;
    const newLoc = getDocumentPositionMapper2(info.fileName).getSourcePosition(info);
    return !newLoc || newLoc === info ? void 0 : tryGetSourcePosition(newLoc) || newLoc;
  }
  function tryGetGeneratedPosition(info) {
    if (isDeclarationFileName(info.fileName)) return void 0;
    const sourceFile = getSourceFile(info.fileName);
    if (!sourceFile) return void 0;
    const program = host.getProgram();
    if (program.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) {
      return void 0;
    }
    const options = program.getCompilerOptions();
    const outPath = options.outFile;
    const declarationPath = outPath ? removeFileExtension(outPath) + ".d.ts" /* Dts */ : getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), program);
    if (declarationPath === void 0) return void 0;
    const newLoc = getDocumentPositionMapper2(declarationPath, info.fileName).getGeneratedPosition(info);
    return newLoc === info ? void 0 : newLoc;
  }
  function getSourceFile(fileName) {
    const program = host.getProgram();
    if (!program) return void 0;
    const path = toPath3(fileName);
    const file = program.getSourceFileByPath(path);
    return file && file.resolvedPath === path ? file : void 0;
  }
  function getOrCreateSourceFileLike(fileName) {
    const path = toPath3(fileName);
    const fileFromCache = sourceFileLike.get(path);
    if (fileFromCache !== void 0) return fileFromCache ? fileFromCache : void 0;
    if (!host.readFile || host.fileExists && !host.fileExists(fileName)) {
      sourceFileLike.set(path, false);
      return void 0;
    }
    const text = host.readFile(fileName);
    const file = text ? createSourceFileLike(text) : false;
    sourceFileLike.set(path, file);
    return file ? file : void 0;
  }
  function getSourceFileLike(fileName) {
    return !host.getSourceFileLike ? getSourceFile(fileName) || getOrCreateSourceFileLike(fileName) : host.getSourceFileLike(fileName);
  }
  function toLineColumnOffset(fileName, position) {
    const file = getSourceFileLike(fileName);
    return file.getLineAndCharacterOfPosition(position);
  }
  function clearCache() {
    sourceFileLike.clear();
    documentPositionMappers.clear();
  }
}
function getDocumentPositionMapper(host, generatedFileName, generatedFileLineInfo, readMapFile) {
  let mapFileName = tryGetSourceMappingURL(generatedFileLineInfo);
  if (mapFileName) {
    const match = base64UrlRegExp.exec(mapFileName);
    if (match) {
      if (match[1]) {
        const base64Object = match[1];
        return convertDocumentToSourceMapper(host, base64decode(sys, base64Object), generatedFileName);
      }
      mapFileName = void 0;
    }
  }
  const possibleMapLocations = [];
  if (mapFileName) {
    possibleMapLocations.push(mapFileName);
  }
  possibleMapLocations.push(generatedFileName + ".map");
  const originalMapFileName = mapFileName && getNormalizedAbsolutePath(mapFileName, getDirectoryPath(generatedFileName));
  for (const location of possibleMapLocations) {
    const mapFileName2 = getNormalizedAbsolutePath(location, getDirectoryPath(generatedFileName));
    const mapFileContents = readMapFile(mapFileName2, originalMapFileName);
    if (isString(mapFileContents)) {
      return convertDocumentToSourceMapper(host, mapFileContents, mapFileName2);
    }
    if (mapFileContents !== void 0) {
      return mapFileContents || void 0;
    }
  }
  return void 0;
}
function convertDocumentToSourceMapper(host, contents, mapFileName) {
  const map2 = tryParseRawSourceMap(contents);
  if (!map2 || !map2.sources || !map2.file || !map2.mappings) {
    return void 0;
  }
  if (map2.sourcesContent && map2.sourcesContent.some(isString)) return void 0;
  return createDocumentPositionMapper(host, map2, mapFileName);
}
function createSourceFileLike(text, lineMap) {
  return {
    text,
    lineMap,
    getLineAndCharacterOfPosition(pos) {
      return computeLineAndCharacterOfPosition(getLineStarts(this), pos);
    }
  };
}

// src/services/suggestionDiagnostics.ts
var visitedNestedConvertibleFunctions = /* @__PURE__ */ new Map();
function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) {
  var _a;
  program.getSemanticDiagnostics(sourceFile, cancellationToken);
  const diags = [];
  const checker = program.getTypeChecker();
  const isCommonJSFile = program.getImpliedNodeFormatForEmit(sourceFile) === 1 /* CommonJS */ || fileExtensionIsOneOf(sourceFile.fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]);
  if (!isCommonJSFile && sourceFile.commonJsModuleIndicator && (programContainsEsModules(program) || compilerOptionsIndicateEsModules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) {
    diags.push(createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module));
  }
  const isJsFile = isSourceFileJS(sourceFile);
  visitedNestedConvertibleFunctions.clear();
  check(sourceFile);
  if (getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
    for (const moduleSpecifier of sourceFile.imports) {
      const importNode = importFromModuleSpecifier(moduleSpecifier);
      const name = importNameForConvertToDefaultImport(importNode);
      if (!name) continue;
      const module2 = (_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier, sourceFile)) == null ? void 0 : _a.resolvedModule;
      const resolvedFile = module2 && program.getSourceFile(module2.resolvedFileName);
      if (resolvedFile && resolvedFile.externalModuleIndicator && resolvedFile.externalModuleIndicator !== true && isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
        diags.push(createDiagnosticForNode(name, Diagnostics.Import_may_be_converted_to_a_default_import));
      }
    }
  }
  addRange(diags, sourceFile.bindSuggestionDiagnostics);
  addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken));
  diags.sort((d1, d2) => d1.start - d2.start);
  return diags;
  function check(node) {
    if (isJsFile) {
      if (canBeConvertedToClass(node, checker)) {
        diags.push(createDiagnosticForNode(isVariableDeclaration(node.parent) ? node.parent.name : node, Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
      }
    } else {
      if (isVariableStatement(node) && node.parent === sourceFile && node.declarationList.flags & 2 /* Const */ && node.declarationList.declarations.length === 1) {
        const init = node.declarationList.declarations[0].initializer;
        if (init && isRequireCall(
          init,
          /*requireStringLiteralLikeArgument*/
          true
        )) {
          diags.push(createDiagnosticForNode(init, Diagnostics.require_call_may_be_converted_to_an_import));
        }
      }
      const jsdocTypedefNodes = ts_codefix_exports.getJSDocTypedefNodes(node);
      for (const jsdocTypedefNode of jsdocTypedefNodes) {
        diags.push(createDiagnosticForNode(jsdocTypedefNode, Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type));
      }
      if (ts_codefix_exports.parameterShouldGetTypeFromJSDoc(node)) {
        diags.push(createDiagnosticForNode(node.name || node, Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types));
      }
    }
    if (canBeConvertedToAsync(node)) {
      addConvertToAsyncFunctionDiagnostics(node, checker, diags);
    }
    node.forEachChild(check);
  }
}
function containsTopLevelCommonjs(sourceFile) {
  return sourceFile.statements.some((statement) => {
    switch (statement.kind) {
      case 243 /* VariableStatement */:
        return statement.declarationList.declarations.some((decl) => !!decl.initializer && isRequireCall(
          propertyAccessLeftHandSide(decl.initializer),
          /*requireStringLiteralLikeArgument*/
          true
        ));
      case 244 /* ExpressionStatement */: {
        const { expression } = statement;
        if (!isBinaryExpression(expression)) return isRequireCall(
          expression,
          /*requireStringLiteralLikeArgument*/
          true
        );
        const kind = getAssignmentDeclarationKind(expression);
        return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */;
      }
      default:
        return false;
    }
  });
}
function propertyAccessLeftHandSide(node) {
  return isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node;
}
function importNameForConvertToDefaultImport(node) {
  switch (node.kind) {
    case 272 /* ImportDeclaration */:
      const { importClause, moduleSpecifier } = node;
      return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 274 /* NamespaceImport */ && isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : void 0;
    case 271 /* ImportEqualsDeclaration */:
      return node.name;
    default:
      return void 0;
  }
}
function addConvertToAsyncFunctionDiagnostics(node, checker, diags) {
  if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) {
    diags.push(createDiagnosticForNode(
      !node.name && isVariableDeclaration(node.parent) && isIdentifier(node.parent.name) ? node.parent.name : node,
      Diagnostics.This_may_be_converted_to_an_async_function
    ));
  }
}
function isConvertibleFunction(node, checker) {
  return !isAsyncFunction(node) && node.body && isBlock(node.body) && hasReturnStatementWithPromiseHandler(node.body, checker) && returnsPromise(node, checker);
}
function returnsPromise(node, checker) {
  const signature = checker.getSignatureFromDeclaration(node);
  const returnType = signature ? checker.getReturnTypeOfSignature(signature) : void 0;
  return !!returnType && !!checker.getPromisedTypeOfPromise(returnType);
}
function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) {
  return isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator;
}
function hasReturnStatementWithPromiseHandler(body, checker) {
  return !!forEachReturnStatement(body, (statement) => isReturnStatementWithFixablePromiseHandler(statement, checker));
}
function isReturnStatementWithFixablePromiseHandler(node, checker) {
  return isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker);
}
function isFixablePromiseHandler(node, checker) {
  if (!isPromiseHandler(node) || !hasSupportedNumberOfArguments(node) || !node.arguments.every((arg) => isFixablePromiseArgument(arg, checker))) {
    return false;
  }
  let currentNode = node.expression.expression;
  while (isPromiseHandler(currentNode) || isPropertyAccessExpression(currentNode)) {
    if (isCallExpression(currentNode)) {
      if (!hasSupportedNumberOfArguments(currentNode) || !currentNode.arguments.every((arg) => isFixablePromiseArgument(arg, checker))) {
        return false;
      }
      currentNode = currentNode.expression.expression;
    } else {
      currentNode = currentNode.expression;
    }
  }
  return true;
}
function isPromiseHandler(node) {
  return isCallExpression(node) && (hasPropertyAccessExpressionWithName(node, "then") || hasPropertyAccessExpressionWithName(node, "catch") || hasPropertyAccessExpressionWithName(node, "finally"));
}
function hasSupportedNumberOfArguments(node) {
  const name = node.expression.name.text;
  const maxArguments = name === "then" ? 2 : name === "catch" ? 1 : name === "finally" ? 1 : 0;
  if (node.arguments.length > maxArguments) return false;
  if (node.arguments.length < maxArguments) return true;
  return maxArguments === 1 || some(node.arguments, (arg) => {
    return arg.kind === 106 /* NullKeyword */ || isIdentifier(arg) && arg.text === "undefined";
  });
}
function isFixablePromiseArgument(arg, checker) {
  switch (arg.kind) {
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
      const functionFlags = getFunctionFlags(arg);
      if (functionFlags & 1 /* Generator */) {
        return false;
      }
    // falls through
    case 219 /* ArrowFunction */:
      visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true);
    // falls through
    case 106 /* NullKeyword */:
      return true;
    case 80 /* Identifier */:
    case 211 /* PropertyAccessExpression */: {
      const symbol = checker.getSymbolAtLocation(arg);
      if (!symbol) {
        return false;
      }
      return checker.isUndefinedSymbol(symbol) || some(skipAlias(symbol, checker).declarations, (d) => isFunctionLike(d) || hasInitializer(d) && !!d.initializer && isFunctionLike(d.initializer));
    }
    default:
      return false;
  }
}
function getKeyFromNode(exp) {
  return `${exp.pos.toString()}:${exp.end.toString()}`;
}
function canBeConvertedToClass(node, checker) {
  var _a, _b, _c, _d;
  if (isFunctionExpression(node)) {
    if (isVariableDeclaration(node.parent) && ((_a = node.symbol.members) == null ? void 0 : _a.size)) {
      return true;
    }
    const symbol = checker.getSymbolOfExpando(
      node,
      /*allowDeclaration*/
      false
    );
    return !!(symbol && (((_b = symbol.exports) == null ? void 0 : _b.size) || ((_c = symbol.members) == null ? void 0 : _c.size)));
  }
  if (isFunctionDeclaration(node)) {
    return !!((_d = node.symbol.members) == null ? void 0 : _d.size);
  }
  return false;
}
function canBeConvertedToAsync(node) {
  switch (node.kind) {
    case 262 /* FunctionDeclaration */:
    case 174 /* MethodDeclaration */:
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
      return true;
    default:
      return false;
  }
}

// src/services/transpile.ts
var optionsRedundantWithVerbatimModuleSyntax = /* @__PURE__ */ new Set([
  "isolatedModules"
]);
function transpileModule(input, transpileOptions) {
  return transpileWorker(
    input,
    transpileOptions,
    /*declaration*/
    false
  );
}
function transpileDeclaration(input, transpileOptions) {
  return transpileWorker(
    input,
    transpileOptions,
    /*declaration*/
    true
  );
}
var barebonesLibContent = `/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number {}
interface Object {}
interface RegExp {}
interface String {}
interface Array<T> { length: number; [n: number]: T; }
interface SymbolConstructor {
    (desc?: string | number): symbol;
    for(name: string): symbol;
    readonly toStringTag: symbol;
}
declare var Symbol: SymbolConstructor;
interface Symbol {
    readonly [Symbol.toStringTag]: string;
}`;
var barebonesLibName = "lib.d.ts";
var barebonesLibSourceFile;
function transpileWorker(input, transpileOptions, declaration) {
  barebonesLibSourceFile ?? (barebonesLibSourceFile = createSourceFile(barebonesLibName, barebonesLibContent, { languageVersion: 99 /* Latest */ }));
  const diagnostics = [];
  const options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : {};
  const defaultOptions = getDefaultCompilerOptions2();
  for (const key in defaultOptions) {
    if (hasProperty(defaultOptions, key) && options[key] === void 0) {
      options[key] = defaultOptions[key];
    }
  }
  for (const option of transpileOptionValueCompilerOptions) {
    if (options.verbatimModuleSyntax && optionsRedundantWithVerbatimModuleSyntax.has(option.name)) {
      continue;
    }
    options[option.name] = option.transpileOptionValue;
  }
  options.suppressOutputPathCheck = true;
  options.allowNonTsExtensions = true;
  if (declaration) {
    options.declaration = true;
    options.emitDeclarationOnly = true;
    options.isolatedDeclarations = true;
  } else {
    options.declaration = false;
    options.declarationMap = false;
  }
  const newLine = getNewLineCharacter(options);
  const compilerHost = {
    getSourceFile: (fileName) => fileName === normalizePath(inputFileName) ? sourceFile : fileName === normalizePath(barebonesLibName) ? barebonesLibSourceFile : void 0,
    writeFile: (name, text) => {
      if (fileExtensionIs(name, ".map")) {
        Debug.assertEqual(sourceMapText, void 0, "Unexpected multiple source map outputs, file:", name);
        sourceMapText = text;
      } else {
        Debug.assertEqual(outputText, void 0, "Unexpected multiple outputs, file:", name);
        outputText = text;
      }
    },
    getDefaultLibFileName: () => barebonesLibName,
    useCaseSensitiveFileNames: () => false,
    getCanonicalFileName: (fileName) => fileName,
    getCurrentDirectory: () => "",
    getNewLine: () => newLine,
    fileExists: (fileName) => fileName === inputFileName || !!declaration && fileName === barebonesLibName,
    readFile: () => "",
    directoryExists: () => true,
    getDirectories: () => []
  };
  const inputFileName = transpileOptions.fileName || (transpileOptions.compilerOptions && transpileOptions.compilerOptions.jsx ? "module.tsx" : "module.ts");
  const sourceFile = createSourceFile(
    inputFileName,
    input,
    {
      languageVersion: getEmitScriptTarget(options),
      impliedNodeFormat: getImpliedNodeFormatForFile(
        toPath(inputFileName, "", compilerHost.getCanonicalFileName),
        /*packageJsonInfoCache*/
        void 0,
        compilerHost,
        options
      ),
      setExternalModuleIndicator: getSetExternalModuleIndicator(options),
      jsDocParsingMode: transpileOptions.jsDocParsingMode ?? 0 /* ParseAll */
    }
  );
  if (transpileOptions.moduleName) {
    sourceFile.moduleName = transpileOptions.moduleName;
  }
  if (transpileOptions.renamedDependencies) {
    sourceFile.renamedDependencies = new Map(Object.entries(transpileOptions.renamedDependencies));
  }
  let outputText;
  let sourceMapText;
  const inputs = declaration ? [inputFileName, barebonesLibName] : [inputFileName];
  const program = createProgram(inputs, options, compilerHost);
  if (transpileOptions.reportDiagnostics) {
    addRange(
      /*to*/
      diagnostics,
      /*from*/
      program.getSyntacticDiagnostics(sourceFile)
    );
    addRange(
      /*to*/
      diagnostics,
      /*from*/
      program.getOptionsDiagnostics()
    );
  }
  const result = program.emit(
    /*targetSourceFile*/
    void 0,
    /*writeFile*/
    void 0,
    /*cancellationToken*/
    void 0,
    /*emitOnlyDtsFiles*/
    declaration,
    transpileOptions.transformers,
    /*forceDtsEmit*/
    declaration
  );
  addRange(
    /*to*/
    diagnostics,
    /*from*/
    result.diagnostics
  );
  if (outputText === void 0) return Debug.fail("Output generation failed");
  return { outputText, diagnostics, sourceMapText };
}
function transpile(input, compilerOptions, fileName, diagnostics, moduleName) {
  const output = transpileModule(input, { compilerOptions, fileName, reportDiagnostics: !!diagnostics, moduleName });
  addRange(diagnostics, output.diagnostics);
  return output.outputText;
}
var commandLineOptionsStringToEnum;
function fixupCompilerOptions(options, diagnostics) {
  commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || filter(optionDeclarations, (o) => typeof o.type === "object" && !forEachEntry(o.type, (v) => typeof v !== "number"));
  options = cloneCompilerOptions(options);
  for (const opt of commandLineOptionsStringToEnum) {
    if (!hasProperty(options, opt.name)) {
      continue;
    }
    const value = options[opt.name];
    if (isString(value)) {
      options[opt.name] = parseCustomTypeOption(opt, value, diagnostics);
    } else {
      if (!forEachEntry(opt.type, (v) => v === value)) {
        diagnostics.push(createCompilerDiagnosticForInvalidCustomType(opt));
      }
    }
  }
  return options;
}

// src/services/_namespaces/ts.NavigateTo.ts
var ts_NavigateTo_exports = {};
__export(ts_NavigateTo_exports, {
  getNavigateToItems: () => getNavigateToItems
});

// src/services/navigateTo.ts
function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles, excludeLibFiles) {
  const patternMatcher = createPatternMatcher(searchValue);
  if (!patternMatcher) return emptyArray;
  const rawItems = [];
  const singleCurrentFile = sourceFiles.length === 1 ? sourceFiles[0] : void 0;
  for (const sourceFile of sourceFiles) {
    cancellationToken.throwIfCancellationRequested();
    if (excludeDtsFiles && sourceFile.isDeclarationFile) {
      continue;
    }
    if (shouldExcludeFile(sourceFile, !!excludeLibFiles, singleCurrentFile)) {
      continue;
    }
    sourceFile.getNamedDeclarations().forEach((declarations, name) => {
      getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, !!excludeLibFiles, singleCurrentFile, rawItems);
    });
  }
  rawItems.sort(compareNavigateToItems);
  return (maxResultCount === void 0 ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
}
function shouldExcludeFile(file, excludeLibFiles, singleCurrentFile) {
  return file !== singleCurrentFile && excludeLibFiles && (isInsideNodeModules(file.path) || file.hasNoDefaultLib);
}
function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, excludeLibFiles, singleCurrentFile, rawItems) {
  const match = patternMatcher.getMatchForLastSegmentOfPattern(name);
  if (!match) {
    return;
  }
  for (const declaration of declarations) {
    if (!shouldKeepItem(declaration, checker, excludeLibFiles, singleCurrentFile)) continue;
    if (patternMatcher.patternContainsDots) {
      const fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name);
      if (fullMatch) {
        rawItems.push({ name, fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration });
      }
    } else {
      rawItems.push({ name, fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration });
    }
  }
}
function shouldKeepItem(declaration, checker, excludeLibFiles, singleCurrentFile) {
  var _a;
  switch (declaration.kind) {
    case 273 /* ImportClause */:
    case 276 /* ImportSpecifier */:
    case 271 /* ImportEqualsDeclaration */:
      const importer = checker.getSymbolAtLocation(declaration.name);
      const imported = checker.getAliasedSymbol(importer);
      return importer.escapedName !== imported.escapedName && !((_a = imported.declarations) == null ? void 0 : _a.every((d) => shouldExcludeFile(d.getSourceFile(), excludeLibFiles, singleCurrentFile)));
    default:
      return true;
  }
}
function tryAddSingleDeclarationName(declaration, containers) {
  const name = getNameOfDeclaration(declaration);
  return !!name && (pushLiteral(name, containers) || name.kind === 167 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers));
}
function tryAddComputedPropertyName(expression, containers) {
  return pushLiteral(expression, containers) || isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers);
}
function pushLiteral(node, containers) {
  return isPropertyNameLiteral(node) && (containers.push(getTextOfIdentifierOrLiteral(node)), true);
}
function getContainers(declaration) {
  const containers = [];
  const name = getNameOfDeclaration(declaration);
  if (name && name.kind === 167 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) {
    return emptyArray;
  }
  containers.shift();
  let container = getContainerNode(declaration);
  while (container) {
    if (!tryAddSingleDeclarationName(container, containers)) {
      return emptyArray;
    }
    container = getContainerNode(container);
  }
  containers.reverse();
  return containers;
}
function compareNavigateToItems(i1, i2) {
  return compareValues(i1.matchKind, i2.matchKind) || compareStringsCaseSensitiveUI(i1.name, i2.name);
}
function createNavigateToItem(rawItem) {
  const declaration = rawItem.declaration;
  const container = getContainerNode(declaration);
  const containerName = container && getNameOfDeclaration(container);
  return {
    name: rawItem.name,
    kind: getNodeKind(declaration),
    kindModifiers: getNodeModifiers(declaration),
    matchKind: PatternMatchKind[rawItem.matchKind],
    isCaseSensitive: rawItem.isCaseSensitive,
    fileName: rawItem.fileName,
    textSpan: createTextSpanFromNode(declaration),
    // TODO(jfreeman): What should be the containerName when the container has a computed name?
    containerName: containerName ? containerName.text : "",
    containerKind: containerName ? getNodeKind(container) : "" /* unknown */
  };
}

// src/services/_namespaces/ts.NavigationBar.ts
var ts_NavigationBar_exports = {};
__export(ts_NavigationBar_exports, {
  getNavigationBarItems: () => getNavigationBarItems,
  getNavigationTree: () => getNavigationTree
});

// src/services/navigationBar.ts
var whiteSpaceRegex = /\s+/g;
var maxLength = 150;
var curCancellationToken;
var curSourceFile;
var parentsStack = [];
var parent;
var trackedEs5ClassesStack = [];
var trackedEs5Classes;
var emptyChildItemArray = [];
function getNavigationBarItems(sourceFile, cancellationToken) {
  curCancellationToken = cancellationToken;
  curSourceFile = sourceFile;
  try {
    return map(primaryNavBarMenuItems(rootNavigationBarNode(sourceFile)), convertToPrimaryNavBarMenuItem);
  } finally {
    reset();
  }
}
function getNavigationTree(sourceFile, cancellationToken) {
  curCancellationToken = cancellationToken;
  curSourceFile = sourceFile;
  try {
    return convertToTree(rootNavigationBarNode(sourceFile));
  } finally {
    reset();
  }
}
function reset() {
  curSourceFile = void 0;
  curCancellationToken = void 0;
  parentsStack = [];
  parent = void 0;
  emptyChildItemArray = [];
}
function nodeText(node) {
  return cleanText(node.getText(curSourceFile));
}
function navigationBarNodeKind(n) {
  return n.node.kind;
}
function pushChild(parent2, child) {
  if (parent2.children) {
    parent2.children.push(child);
  } else {
    parent2.children = [child];
  }
}
function rootNavigationBarNode(sourceFile) {
  Debug.assert(!parentsStack.length);
  const root = { node: sourceFile, name: void 0, additionalNodes: void 0, parent: void 0, children: void 0, indent: 0 };
  parent = root;
  for (const statement of sourceFile.statements) {
    addChildrenRecursively(statement);
  }
  endNode();
  Debug.assert(!parent && !parentsStack.length);
  return root;
}
function addLeafNode(node, name) {
  pushChild(parent, emptyNavigationBarNode(node, name));
}
function emptyNavigationBarNode(node, name) {
  return {
    node,
    name: name || (isDeclaration(node) || isExpression(node) ? getNameOfDeclaration(node) : void 0),
    additionalNodes: void 0,
    parent,
    children: void 0,
    indent: parent.indent + 1
  };
}
function addTrackedEs5Class(name) {
  if (!trackedEs5Classes) {
    trackedEs5Classes = /* @__PURE__ */ new Map();
  }
  trackedEs5Classes.set(name, true);
}
function endNestedNodes(depth) {
  for (let i = 0; i < depth; i++) endNode();
}
function startNestedNodes(targetNode, entityName) {
  const names = [];
  while (!isPropertyNameLiteral(entityName)) {
    const name = getNameOrArgument(entityName);
    const nameText = getElementOrPropertyAccessName(entityName);
    entityName = entityName.expression;
    if (nameText === "prototype" || isPrivateIdentifier(name)) continue;
    names.push(name);
  }
  names.push(entityName);
  for (let i = names.length - 1; i > 0; i--) {
    const name = names[i];
    startNode(targetNode, name);
  }
  return [names.length - 1, names[0]];
}
function startNode(node, name) {
  const navNode = emptyNavigationBarNode(node, name);
  pushChild(parent, navNode);
  parentsStack.push(parent);
  trackedEs5ClassesStack.push(trackedEs5Classes);
  trackedEs5Classes = void 0;
  parent = navNode;
}
function endNode() {
  if (parent.children) {
    mergeChildren(parent.children, parent);
    sortChildren(parent.children);
  }
  parent = parentsStack.pop();
  trackedEs5Classes = trackedEs5ClassesStack.pop();
}
function addNodeWithRecursiveChild(node, child, name) {
  startNode(node, name);
  addChildrenRecursively(child);
  endNode();
}
function addNodeWithRecursiveInitializer(node) {
  if (node.initializer && isFunctionOrClassExpression(node.initializer)) {
    startNode(node);
    forEachChild(node.initializer, addChildrenRecursively);
    endNode();
  } else {
    addNodeWithRecursiveChild(node, node.initializer);
  }
}
function hasNavigationBarName(node) {
  const name = getNameOfDeclaration(node);
  if (name === void 0) return false;
  if (isComputedPropertyName(name)) {
    const expression = name.expression;
    return isEntityNameExpression(expression) || isNumericLiteral(expression) || isStringOrNumericLiteralLike(expression);
  }
  return !!name;
}
function addChildrenRecursively(node) {
  curCancellationToken.throwIfCancellationRequested();
  if (!node || isToken(node)) {
    return;
  }
  switch (node.kind) {
    case 176 /* Constructor */:
      const ctr = node;
      addNodeWithRecursiveChild(ctr, ctr.body);
      for (const param of ctr.parameters) {
        if (isParameterPropertyDeclaration(param, ctr)) {
          addLeafNode(param);
        }
      }
      break;
    case 174 /* MethodDeclaration */:
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
    case 173 /* MethodSignature */:
      if (hasNavigationBarName(node)) {
        addNodeWithRecursiveChild(node, node.body);
      }
      break;
    case 172 /* PropertyDeclaration */:
      if (hasNavigationBarName(node)) {
        addNodeWithRecursiveInitializer(node);
      }
      break;
    case 171 /* PropertySignature */:
      if (hasNavigationBarName(node)) {
        addLeafNode(node);
      }
      break;
    case 273 /* ImportClause */:
      const importClause = node;
      if (importClause.name) {
        addLeafNode(importClause.name);
      }
      const { namedBindings } = importClause;
      if (namedBindings) {
        if (namedBindings.kind === 274 /* NamespaceImport */) {
          addLeafNode(namedBindings);
        } else {
          for (const element of namedBindings.elements) {
            addLeafNode(element);
          }
        }
      }
      break;
    case 304 /* ShorthandPropertyAssignment */:
      addNodeWithRecursiveChild(node, node.name);
      break;
    case 305 /* SpreadAssignment */:
      const { expression } = node;
      isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node);
      break;
    case 208 /* BindingElement */:
    case 303 /* PropertyAssignment */:
    case 260 /* VariableDeclaration */: {
      const child = node;
      if (isBindingPattern(child.name)) {
        addChildrenRecursively(child.name);
      } else {
        addNodeWithRecursiveInitializer(child);
      }
      break;
    }
    case 262 /* FunctionDeclaration */:
      const nameNode = node.name;
      if (nameNode && isIdentifier(nameNode)) {
        addTrackedEs5Class(nameNode.text);
      }
      addNodeWithRecursiveChild(node, node.body);
      break;
    case 219 /* ArrowFunction */:
    case 218 /* FunctionExpression */:
      addNodeWithRecursiveChild(node, node.body);
      break;
    case 266 /* EnumDeclaration */:
      startNode(node);
      for (const member of node.members) {
        if (!isComputedProperty(member)) {
          addLeafNode(member);
        }
      }
      endNode();
      break;
    case 263 /* ClassDeclaration */:
    case 231 /* ClassExpression */:
    case 264 /* InterfaceDeclaration */:
      startNode(node);
      for (const member of node.members) {
        addChildrenRecursively(member);
      }
      endNode();
      break;
    case 267 /* ModuleDeclaration */:
      addNodeWithRecursiveChild(node, getInteriorModule(node).body);
      break;
    case 277 /* ExportAssignment */: {
      const expression2 = node.expression;
      const child = isObjectLiteralExpression(expression2) || isCallExpression(expression2) ? expression2 : isArrowFunction(expression2) || isFunctionExpression(expression2) ? expression2.body : void 0;
      if (child) {
        startNode(node);
        addChildrenRecursively(child);
        endNode();
      } else {
        addLeafNode(node);
      }
      break;
    }
    case 281 /* ExportSpecifier */:
    case 271 /* ImportEqualsDeclaration */:
    case 181 /* IndexSignature */:
    case 179 /* CallSignature */:
    case 180 /* ConstructSignature */:
    case 265 /* TypeAliasDeclaration */:
      addLeafNode(node);
      break;
    case 213 /* CallExpression */:
    case 226 /* BinaryExpression */: {
      const special = getAssignmentDeclarationKind(node);
      switch (special) {
        case 1 /* ExportsProperty */:
        case 2 /* ModuleExports */:
          addNodeWithRecursiveChild(node, node.right);
          return;
        case 6 /* Prototype */:
        case 3 /* PrototypeProperty */: {
          const binaryExpression = node;
          const assignmentTarget = binaryExpression.left;
          const prototypeAccess = special === 3 /* PrototypeProperty */ ? assignmentTarget.expression : assignmentTarget;
          let depth = 0;
          let className;
          if (isIdentifier(prototypeAccess.expression)) {
            addTrackedEs5Class(prototypeAccess.expression.text);
            className = prototypeAccess.expression;
          } else {
            [depth, className] = startNestedNodes(binaryExpression, prototypeAccess.expression);
          }
          if (special === 6 /* Prototype */) {
            if (isObjectLiteralExpression(binaryExpression.right)) {
              if (binaryExpression.right.properties.length > 0) {
                startNode(binaryExpression, className);
                forEachChild(binaryExpression.right, addChildrenRecursively);
                endNode();
              }
            }
          } else if (isFunctionExpression(binaryExpression.right) || isArrowFunction(binaryExpression.right)) {
            addNodeWithRecursiveChild(node, binaryExpression.right, className);
          } else {
            startNode(binaryExpression, className);
            addNodeWithRecursiveChild(node, binaryExpression.right, assignmentTarget.name);
            endNode();
          }
          endNestedNodes(depth);
          return;
        }
        case 7 /* ObjectDefinePropertyValue */:
        case 9 /* ObjectDefinePrototypeProperty */: {
          const defineCall = node;
          const className = special === 7 /* ObjectDefinePropertyValue */ ? defineCall.arguments[0] : defineCall.arguments[0].expression;
          const memberName = defineCall.arguments[1];
          const [depth, classNameIdentifier] = startNestedNodes(node, className);
          startNode(node, classNameIdentifier);
          startNode(node, setTextRange(factory.createIdentifier(memberName.text), memberName));
          addChildrenRecursively(node.arguments[2]);
          endNode();
          endNode();
          endNestedNodes(depth);
          return;
        }
        case 5 /* Property */: {
          const binaryExpression = node;
          const assignmentTarget = binaryExpression.left;
          const targetFunction = assignmentTarget.expression;
          if (isIdentifier(targetFunction) && getElementOrPropertyAccessName(assignmentTarget) !== "prototype" && trackedEs5Classes && trackedEs5Classes.has(targetFunction.text)) {
            if (isFunctionExpression(binaryExpression.right) || isArrowFunction(binaryExpression.right)) {
              addNodeWithRecursiveChild(node, binaryExpression.right, targetFunction);
            } else if (isBindableStaticAccessExpression(assignmentTarget)) {
              startNode(binaryExpression, targetFunction);
              addNodeWithRecursiveChild(binaryExpression.left, binaryExpression.right, getNameOrArgument(assignmentTarget));
              endNode();
            }
            return;
          }
          break;
        }
        case 4 /* ThisProperty */:
        case 0 /* None */:
        case 8 /* ObjectDefinePropertyExports */:
          break;
        default:
          Debug.assertNever(special);
      }
    }
    // falls through
    default:
      if (hasJSDocNodes(node)) {
        forEach(node.jsDoc, (jsDoc) => {
          forEach(jsDoc.tags, (tag) => {
            if (isJSDocTypeAlias(tag)) {
              addLeafNode(tag);
            }
          });
        });
      }
      forEachChild(node, addChildrenRecursively);
  }
}
function mergeChildren(children, node) {
  const nameToItems = /* @__PURE__ */ new Map();
  filterMutate(children, (child, index) => {
    const declName = child.name || getNameOfDeclaration(child.node);
    const name = declName && nodeText(declName);
    if (!name) {
      return true;
    }
    const itemsWithSameName = nameToItems.get(name);
    if (!itemsWithSameName) {
      nameToItems.set(name, child);
      return true;
    }
    if (itemsWithSameName instanceof Array) {
      for (const itemWithSameName of itemsWithSameName) {
        if (tryMerge(itemWithSameName, child, index, node)) {
          return false;
        }
      }
      itemsWithSameName.push(child);
      return true;
    } else {
      const itemWithSameName = itemsWithSameName;
      if (tryMerge(itemWithSameName, child, index, node)) {
        return false;
      }
      nameToItems.set(name, [itemWithSameName, child]);
      return true;
    }
  });
}
var isEs5ClassMember = {
  [5 /* Property */]: true,
  [3 /* PrototypeProperty */]: true,
  [7 /* ObjectDefinePropertyValue */]: true,
  [9 /* ObjectDefinePrototypeProperty */]: true,
  [0 /* None */]: false,
  [1 /* ExportsProperty */]: false,
  [2 /* ModuleExports */]: false,
  [8 /* ObjectDefinePropertyExports */]: false,
  [6 /* Prototype */]: true,
  [4 /* ThisProperty */]: false
};
function tryMergeEs5Class(a, b, bIndex, parent2) {
  function isPossibleConstructor(node) {
    return isFunctionExpression(node) || isFunctionDeclaration(node) || isVariableDeclaration(node);
  }
  const bAssignmentDeclarationKind = isBinaryExpression(b.node) || isCallExpression(b.node) ? getAssignmentDeclarationKind(b.node) : 0 /* None */;
  const aAssignmentDeclarationKind = isBinaryExpression(a.node) || isCallExpression(a.node) ? getAssignmentDeclarationKind(a.node) : 0 /* None */;
  if (isEs5ClassMember[bAssignmentDeclarationKind] && isEs5ClassMember[aAssignmentDeclarationKind] || isPossibleConstructor(a.node) && isEs5ClassMember[bAssignmentDeclarationKind] || isPossibleConstructor(b.node) && isEs5ClassMember[aAssignmentDeclarationKind] || isClassDeclaration(a.node) && isSynthesized(a.node) && isEs5ClassMember[bAssignmentDeclarationKind] || isClassDeclaration(b.node) && isEs5ClassMember[aAssignmentDeclarationKind] || isClassDeclaration(a.node) && isSynthesized(a.node) && isPossibleConstructor(b.node) || isClassDeclaration(b.node) && isPossibleConstructor(a.node) && isSynthesized(a.node)) {
    let lastANode = a.additionalNodes && lastOrUndefined(a.additionalNodes) || a.node;
    if (!isClassDeclaration(a.node) && !isClassDeclaration(b.node) || isPossibleConstructor(a.node) || isPossibleConstructor(b.node)) {
      const ctorFunction = isPossibleConstructor(a.node) ? a.node : isPossibleConstructor(b.node) ? b.node : void 0;
      if (ctorFunction !== void 0) {
        const ctorNode = setTextRange(
          factory.createConstructorDeclaration(
            /*modifiers*/
            void 0,
            [],
            /*body*/
            void 0
          ),
          ctorFunction
        );
        const ctor = emptyNavigationBarNode(ctorNode);
        ctor.indent = a.indent + 1;
        ctor.children = a.node === ctorFunction ? a.children : b.children;
        a.children = a.node === ctorFunction ? concatenate([ctor], b.children || [b]) : concatenate(a.children || [{ ...a }], [ctor]);
      } else {
        if (a.children || b.children) {
          a.children = concatenate(a.children || [{ ...a }], b.children || [b]);
          if (a.children) {
            mergeChildren(a.children, a);
            sortChildren(a.children);
          }
        }
      }
      lastANode = a.node = setTextRange(
        factory.createClassDeclaration(
          /*modifiers*/
          void 0,
          a.name || factory.createIdentifier("__class__"),
          /*typeParameters*/
          void 0,
          /*heritageClauses*/
          void 0,
          []
        ),
        a.node
      );
    } else {
      a.children = concatenate(a.children, b.children);
      if (a.children) {
        mergeChildren(a.children, a);
      }
    }
    const bNode = b.node;
    if (parent2.children[bIndex - 1].node.end === lastANode.end) {
      setTextRange(lastANode, { pos: lastANode.pos, end: bNode.end });
    } else {
      if (!a.additionalNodes) a.additionalNodes = [];
      a.additionalNodes.push(setTextRange(
        factory.createClassDeclaration(
          /*modifiers*/
          void 0,
          a.name || factory.createIdentifier("__class__"),
          /*typeParameters*/
          void 0,
          /*heritageClauses*/
          void 0,
          []
        ),
        b.node
      ));
    }
    return true;
  }
  return bAssignmentDeclarationKind === 0 /* None */ ? false : true;
}
function tryMerge(a, b, bIndex, parent2) {
  if (tryMergeEs5Class(a, b, bIndex, parent2)) {
    return true;
  }
  if (shouldReallyMerge(a.node, b.node, parent2)) {
    merge(a, b);
    return true;
  }
  return false;
}
function shouldReallyMerge(a, b, parent2) {
  if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent2) && isOwnChild(b, parent2))) {
    return false;
  }
  switch (a.kind) {
    case 172 /* PropertyDeclaration */:
    case 174 /* MethodDeclaration */:
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
      return isStatic(a) === isStatic(b);
    case 267 /* ModuleDeclaration */:
      return areSameModule(a, b) && getFullyQualifiedModuleName(a) === getFullyQualifiedModuleName(b);
    default:
      return true;
  }
}
function isSynthesized(node) {
  return !!(node.flags & 16 /* Synthesized */);
}
function isOwnChild(n, parent2) {
  if (n.parent === void 0) return false;
  const par = isModuleBlock(n.parent) ? n.parent.parent : n.parent;
  return par === parent2.node || contains(parent2.additionalNodes, par);
}
function areSameModule(a, b) {
  if (!a.body || !b.body) {
    return a.body === b.body;
  }
  return a.body.kind === b.body.kind && (a.body.kind !== 267 /* ModuleDeclaration */ || areSameModule(a.body, b.body));
}
function merge(target, source) {
  target.additionalNodes = target.additionalNodes || [];
  target.additionalNodes.push(source.node);
  if (source.additionalNodes) {
    target.additionalNodes.push(...source.additionalNodes);
  }
  target.children = concatenate(target.children, source.children);
  if (target.children) {
    mergeChildren(target.children, target);
    sortChildren(target.children);
  }
}
function sortChildren(children) {
  children.sort(compareChildren);
}
function compareChildren(child1, child2) {
  return compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) || compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2));
}
function tryGetName(node) {
  if (node.kind === 267 /* ModuleDeclaration */) {
    return getModuleName(node);
  }
  const declName = getNameOfDeclaration(node);
  if (declName && isPropertyName(declName)) {
    const propertyName = getPropertyNameForPropertyNameNode(declName);
    return propertyName && unescapeLeadingUnderscores(propertyName);
  }
  switch (node.kind) {
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
    case 231 /* ClassExpression */:
      return getFunctionOrClassName(node);
    default:
      return void 0;
  }
}
function getItemName(node, name) {
  if (node.kind === 267 /* ModuleDeclaration */) {
    return cleanText(getModuleName(node));
  }
  if (name) {
    const text = isIdentifier(name) ? name.text : isElementAccessExpression(name) ? `[${nodeText(name.argumentExpression)}]` : nodeText(name);
    if (text.length > 0) {
      return cleanText(text);
    }
  }
  switch (node.kind) {
    case 307 /* SourceFile */:
      const sourceFile = node;
      return isExternalModule(sourceFile) ? `"${escapeString(getBaseFileName(removeFileExtension(normalizePath(sourceFile.fileName))))}"` : "<global>";
    case 277 /* ExportAssignment */:
      return isExportAssignment(node) && node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
    case 219 /* ArrowFunction */:
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
    case 263 /* ClassDeclaration */:
    case 231 /* ClassExpression */:
      if (getSyntacticModifierFlags(node) & 2048 /* Default */) {
        return "default";
      }
      return getFunctionOrClassName(node);
    case 176 /* Constructor */:
      return "constructor";
    case 180 /* ConstructSignature */:
      return "new()";
    case 179 /* CallSignature */:
      return "()";
    case 181 /* IndexSignature */:
      return "[]";
    default:
      return "<unknown>";
  }
}
function primaryNavBarMenuItems(root) {
  const primaryNavBarMenuItems2 = [];
  function recur(item) {
    if (shouldAppearInPrimaryNavBarMenu(item)) {
      primaryNavBarMenuItems2.push(item);
      if (item.children) {
        for (const child of item.children) {
          recur(child);
        }
      }
    }
  }
  recur(root);
  return primaryNavBarMenuItems2;
  function shouldAppearInPrimaryNavBarMenu(item) {
    if (item.children) {
      return true;
    }
    switch (navigationBarNodeKind(item)) {
      case 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
      case 266 /* EnumDeclaration */:
      case 264 /* InterfaceDeclaration */:
      case 267 /* ModuleDeclaration */:
      case 307 /* SourceFile */:
      case 265 /* TypeAliasDeclaration */:
      case 346 /* JSDocTypedefTag */:
      case 338 /* JSDocCallbackTag */:
        return true;
      case 219 /* ArrowFunction */:
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
        return isTopLevelFunctionDeclaration(item);
      default:
        return false;
    }
    function isTopLevelFunctionDeclaration(item2) {
      if (!item2.node.body) {
        return false;
      }
      switch (navigationBarNodeKind(item2.parent)) {
        case 268 /* ModuleBlock */:
        case 307 /* SourceFile */:
        case 174 /* MethodDeclaration */:
        case 176 /* Constructor */:
          return true;
        default:
          return false;
      }
    }
  }
}
function convertToTree(n) {
  return {
    text: getItemName(n.node, n.name),
    kind: getNodeKind(n.node),
    kindModifiers: getModifiers2(n.node),
    spans: getSpans(n),
    nameSpan: n.name && getNodeSpan(n.name),
    childItems: map(n.children, convertToTree)
  };
}
function convertToPrimaryNavBarMenuItem(n) {
  return {
    text: getItemName(n.node, n.name),
    kind: getNodeKind(n.node),
    kindModifiers: getModifiers2(n.node),
    spans: getSpans(n),
    childItems: map(n.children, convertToSecondaryNavBarMenuItem) || emptyChildItemArray,
    indent: n.indent,
    bolded: false,
    grayed: false
  };
  function convertToSecondaryNavBarMenuItem(n2) {
    return {
      text: getItemName(n2.node, n2.name),
      kind: getNodeKind(n2.node),
      kindModifiers: getNodeModifiers(n2.node),
      spans: getSpans(n2),
      childItems: emptyChildItemArray,
      indent: 0,
      bolded: false,
      grayed: false
    };
  }
}
function getSpans(n) {
  const spans = [getNodeSpan(n.node)];
  if (n.additionalNodes) {
    for (const node of n.additionalNodes) {
      spans.push(getNodeSpan(node));
    }
  }
  return spans;
}
function getModuleName(moduleDeclaration) {
  if (isAmbientModule(moduleDeclaration)) {
    return getTextOfNode(moduleDeclaration.name);
  }
  return getFullyQualifiedModuleName(moduleDeclaration);
}
function getFullyQualifiedModuleName(moduleDeclaration) {
  const result = [getTextOfIdentifierOrLiteral(moduleDeclaration.name)];
  while (moduleDeclaration.body && moduleDeclaration.body.kind === 267 /* ModuleDeclaration */) {
    moduleDeclaration = moduleDeclaration.body;
    result.push(getTextOfIdentifierOrLiteral(moduleDeclaration.name));
  }
  return result.join(".");
}
function getInteriorModule(decl) {
  return decl.body && isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl;
}
function isComputedProperty(member) {
  return !member.name || member.name.kind === 167 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
  return node.kind === 307 /* SourceFile */ ? createTextSpanFromRange(node) : createTextSpanFromNode(node, curSourceFile);
}
function getModifiers2(node) {
  if (node.parent && node.parent.kind === 260 /* VariableDeclaration */) {
    node = node.parent;
  }
  return getNodeModifiers(node);
}
function getFunctionOrClassName(node) {
  const { parent: parent2 } = node;
  if (node.name && getFullWidth(node.name) > 0) {
    return cleanText(declarationNameToString(node.name));
  } else if (isVariableDeclaration(parent2)) {
    return cleanText(declarationNameToString(parent2.name));
  } else if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */) {
    return nodeText(parent2.left).replace(whiteSpaceRegex, "");
  } else if (isPropertyAssignment(parent2)) {
    return nodeText(parent2.name);
  } else if (getSyntacticModifierFlags(node) & 2048 /* Default */) {
    return "default";
  } else if (isClassLike(node)) {
    return "<class>";
  } else if (isCallExpression(parent2)) {
    let name = getCalledExpressionName(parent2.expression);
    if (name !== void 0) {
      name = cleanText(name);
      if (name.length > maxLength) {
        return `${name} callback`;
      }
      const args = cleanText(mapDefined(parent2.arguments, (a) => isStringLiteralLike(a) || isTemplateLiteral(a) ? a.getText(curSourceFile) : void 0).join(", "));
      return `${name}(${args}) callback`;
    }
  }
  return "<function>";
}
function getCalledExpressionName(expr) {
  if (isIdentifier(expr)) {
    return expr.text;
  } else if (isPropertyAccessExpression(expr)) {
    const left = getCalledExpressionName(expr.expression);
    const right = expr.name.text;
    return left === void 0 ? right : `${left}.${right}`;
  } else {
    return void 0;
  }
}
function isFunctionOrClassExpression(node) {
  switch (node.kind) {
    case 219 /* ArrowFunction */:
    case 218 /* FunctionExpression */:
    case 231 /* ClassExpression */:
      return true;
    default:
      return false;
  }
}
function cleanText(text) {
  text = text.length > maxLength ? text.substring(0, maxLength) + "..." : text;
  return text.replace(/\\?(?:\r?\n|[\r\u2028\u2029])/g, "");
}

// src/services/_namespaces/ts.refactor.ts
var ts_refactor_exports = {};
__export(ts_refactor_exports, {
  addExportsInOldFile: () => addExportsInOldFile,
  addImportsForMovedSymbols: () => addImportsForMovedSymbols,
  addNewFileToTsconfig: () => addNewFileToTsconfig,
  addOrRemoveBracesToArrowFunction: () => ts_refactor_addOrRemoveBracesToArrowFunction_exports,
  addTargetFileImports: () => addTargetFileImports,
  containsJsx: () => containsJsx,
  convertArrowFunctionOrFunctionExpression: () => ts_refactor_convertArrowFunctionOrFunctionExpression_exports,
  convertParamsToDestructuredObject: () => ts_refactor_convertParamsToDestructuredObject_exports,
  convertStringOrTemplateLiteral: () => ts_refactor_convertStringOrTemplateLiteral_exports,
  convertToOptionalChainExpression: () => ts_refactor_convertToOptionalChainExpression_exports,
  createNewFileName: () => createNewFileName,
  doChangeNamedToNamespaceOrDefault: () => doChangeNamedToNamespaceOrDefault,
  extractSymbol: () => ts_refactor_extractSymbol_exports,
  generateGetAccessorAndSetAccessor: () => ts_refactor_generateGetAccessorAndSetAccessor_exports,
  getApplicableRefactors: () => getApplicableRefactors,
  getEditsForRefactor: () => getEditsForRefactor,
  getExistingLocals: () => getExistingLocals,
  getIdentifierForNode: () => getIdentifierForNode,
  getNewStatementsAndRemoveFromOldFile: () => getNewStatementsAndRemoveFromOldFile,
  getStatementsToMove: () => getStatementsToMove,
  getUsageInfo: () => getUsageInfo,
  inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports,
  isInImport: () => isInImport,
  isRefactorErrorInfo: () => isRefactorErrorInfo,
  refactorKindBeginsWith: () => refactorKindBeginsWith,
  registerRefactor: () => registerRefactor
});

// src/services/refactorProvider.ts
var refactors = /* @__PURE__ */ new Map();
function registerRefactor(name, refactor) {
  refactors.set(name, refactor);
}
function getApplicableRefactors(context, includeInteractiveActions) {
  return arrayFrom(flatMapIterator(refactors.values(), (refactor) => {
    var _a;
    return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a = refactor.kinds) == null ? void 0 : _a.some((kind) => refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context, includeInteractiveActions);
  }));
}
function getEditsForRefactor(context, refactorName14, actionName2, interactiveRefactorArguments) {
  const refactor = refactors.get(refactorName14);
  return refactor && refactor.getEditsForAction(context, actionName2, interactiveRefactorArguments);
}

// src/services/refactors/convertExport.ts
var refactorName = "Convert export";
var defaultToNamedAction = {
  name: "Convert default export to named export",
  description: getLocaleSpecificMessage(Diagnostics.Convert_default_export_to_named_export),
  kind: "refactor.rewrite.export.named"
};
var namedToDefaultAction = {
  name: "Convert named export to default export",
  description: getLocaleSpecificMessage(Diagnostics.Convert_named_export_to_default_export),
  kind: "refactor.rewrite.export.default"
};
registerRefactor(refactorName, {
  kinds: [
    defaultToNamedAction.kind,
    namedToDefaultAction.kind
  ],
  getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) {
    const info = getInfo2(context, context.triggerReason === "invoked");
    if (!info) return emptyArray;
    if (!isRefactorErrorInfo(info)) {
      const action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction;
      return [{ name: refactorName, description: action.description, actions: [action] }];
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return [
        {
          name: refactorName,
          description: getLocaleSpecificMessage(Diagnostics.Convert_default_export_to_named_export),
          actions: [
            { ...defaultToNamedAction, notApplicableReason: info.error },
            { ...namedToDefaultAction, notApplicableReason: info.error }
          ]
        }
      ];
    }
    return emptyArray;
  },
  getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName2) {
    Debug.assert(actionName2 === defaultToNamedAction.name || actionName2 === namedToDefaultAction.name, "Unexpected action name");
    const info = getInfo2(context);
    Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info");
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange(context.file, context.program, info, t, context.cancellationToken));
    return { edits, renameFilename: void 0, renameLocation: void 0 };
  }
});
function getInfo2(context, considerPartialSpans = true) {
  const { file, program } = context;
  const span = getRefactorContextSpan(context);
  const token = getTokenAtPosition(file, span.start);
  const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 32 /* Export */) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span);
  if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) {
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) };
  }
  const checker = program.getTypeChecker();
  const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker);
  const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 2080 /* ExportDefault */ : 0 /* None */);
  const wasDefault = !!(flags & 2048 /* Default */);
  if (!(flags & 32 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) {
    return { error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) };
  }
  const noSymbolError = (id) => isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) };
  switch (exportNode.kind) {
    case 262 /* FunctionDeclaration */:
    case 263 /* ClassDeclaration */:
    case 264 /* InterfaceDeclaration */:
    case 266 /* EnumDeclaration */:
    case 265 /* TypeAliasDeclaration */:
    case 267 /* ModuleDeclaration */: {
      const node = exportNode;
      if (!node.name) return void 0;
      return noSymbolError(node.name) || { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol };
    }
    case 243 /* VariableStatement */: {
      const vs = exportNode;
      if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) {
        return void 0;
      }
      const decl = first(vs.declarationList.declarations);
      if (!decl.initializer) return void 0;
      Debug.assert(!wasDefault, "Can't have a default flag here");
      return noSymbolError(decl.name) || { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol };
    }
    case 277 /* ExportAssignment */: {
      const node = exportNode;
      if (node.isExportEquals) return void 0;
      return noSymbolError(node.expression) || { exportNode: node, exportName: node.expression, wasDefault, exportingModuleSymbol };
    }
    default:
      return void 0;
  }
}
function doChange(exportingSourceFile, program, info, changes, cancellationToken) {
  changeExport(exportingSourceFile, info, changes, program.getTypeChecker());
  changeImports(program, info, changes, cancellationToken);
}
function changeExport(exportingSourceFile, { wasDefault, exportNode, exportName }, changes, checker) {
  if (wasDefault) {
    if (isExportAssignment(exportNode) && !exportNode.isExportEquals) {
      const exp = exportNode.expression;
      const spec = makeExportSpecifier(exp.text, exp.text);
      changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration(
        /*modifiers*/
        void 0,
        /*isTypeOnly*/
        false,
        factory.createNamedExports([spec])
      ));
    } else {
      changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, 90 /* DefaultKeyword */), "Should find a default keyword in modifier list"));
    }
  } else {
    const exportKeyword = Debug.checkDefined(findModifier(exportNode, 95 /* ExportKeyword */), "Should find an export keyword in modifier list");
    switch (exportNode.kind) {
      case 262 /* FunctionDeclaration */:
      case 263 /* ClassDeclaration */:
      case 264 /* InterfaceDeclaration */:
        changes.insertNodeAfter(exportingSourceFile, exportKeyword, factory.createToken(90 /* DefaultKeyword */));
        break;
      case 243 /* VariableStatement */:
        const decl = first(exportNode.declarationList.declarations);
        if (!ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) {
          changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDefault(Debug.checkDefined(decl.initializer, "Initializer was previously known to be present")));
          break;
        }
      // falls through
      case 266 /* EnumDeclaration */:
      case 265 /* TypeAliasDeclaration */:
      case 267 /* ModuleDeclaration */:
        changes.deleteModifier(exportingSourceFile, exportKeyword);
        changes.insertNodeAfter(exportingSourceFile, exportNode, factory.createExportDefault(factory.createIdentifier(exportName.text)));
        break;
      default:
        Debug.fail(`Unexpected exportNode kind ${exportNode.kind}`);
    }
  }
}
function changeImports(program, { wasDefault, exportName, exportingModuleSymbol }, changes, cancellationToken) {
  const checker = program.getTypeChecker();
  const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol");
  ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref) => {
    if (exportName === ref) return;
    const importingSourceFile = ref.getSourceFile();
    if (wasDefault) {
      changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text);
    } else {
      changeNamedToDefaultImport(importingSourceFile, ref, changes);
    }
  });
}
function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) {
  const { parent: parent2 } = ref;
  switch (parent2.kind) {
    case 211 /* PropertyAccessExpression */:
      changes.replaceNode(importingSourceFile, ref, factory.createIdentifier(exportName));
      break;
    case 276 /* ImportSpecifier */:
    case 281 /* ExportSpecifier */: {
      const spec = parent2;
      changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text));
      break;
    }
    case 273 /* ImportClause */: {
      const clause = parent2;
      Debug.assert(clause.name === ref, "Import clause name should match provided ref");
      const spec = makeImportSpecifier(exportName, ref.text);
      const { namedBindings } = clause;
      if (!namedBindings) {
        changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([spec]));
      } else if (namedBindings.kind === 274 /* NamespaceImport */) {
        changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) });
        const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */;
        const newImport = makeImport(
          /*defaultImport*/
          void 0,
          [makeImportSpecifier(exportName, ref.text)],
          clause.parent.moduleSpecifier,
          quotePreference
        );
        changes.insertNodeAfter(importingSourceFile, clause.parent, newImport);
      } else {
        changes.delete(importingSourceFile, ref);
        changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec);
      }
      break;
    }
    case 205 /* ImportType */:
      const importTypeNode = parent2;
      changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.attributes, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf));
      break;
    default:
      Debug.failBadSyntaxKind(parent2);
  }
}
function changeNamedToDefaultImport(importingSourceFile, ref, changes) {
  const parent2 = ref.parent;
  switch (parent2.kind) {
    case 211 /* PropertyAccessExpression */:
      changes.replaceNode(importingSourceFile, ref, factory.createIdentifier("default"));
      break;
    case 276 /* ImportSpecifier */: {
      const defaultImport = factory.createIdentifier(parent2.name.text);
      if (parent2.parent.elements.length === 1) {
        changes.replaceNode(importingSourceFile, parent2.parent, defaultImport);
      } else {
        changes.delete(importingSourceFile, parent2);
        changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport);
      }
      break;
    }
    case 281 /* ExportSpecifier */: {
      changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text));
      break;
    }
    default:
      Debug.assertNever(parent2, `Unexpected parent kind ${parent2.kind}`);
  }
}
function makeImportSpecifier(propertyName, name) {
  return factory.createImportSpecifier(
    /*isTypeOnly*/
    false,
    propertyName === name ? void 0 : factory.createIdentifier(propertyName),
    factory.createIdentifier(name)
  );
}
function makeExportSpecifier(propertyName, name) {
  return factory.createExportSpecifier(
    /*isTypeOnly*/
    false,
    propertyName === name ? void 0 : factory.createIdentifier(propertyName),
    factory.createIdentifier(name)
  );
}
function getExportingModuleSymbol(parent2, checker) {
  if (isSourceFile(parent2)) {
    return parent2.symbol;
  }
  const symbol = parent2.parent.symbol;
  if (symbol.valueDeclaration && isExternalModuleAugmentation(symbol.valueDeclaration)) {
    return checker.getMergedSymbol(symbol);
  }
  return symbol;
}

// src/services/refactors/convertImport.ts
var refactorName2 = "Convert import";
var actions = {
  [0 /* Named */]: {
    name: "Convert namespace import to named imports",
    description: getLocaleSpecificMessage(Diagnostics.Convert_namespace_import_to_named_imports),
    kind: "refactor.rewrite.import.named"
  },
  [2 /* Namespace */]: {
    name: "Convert named imports to namespace import",
    description: getLocaleSpecificMessage(Diagnostics.Convert_named_imports_to_namespace_import),
    kind: "refactor.rewrite.import.namespace"
  },
  [1 /* Default */]: {
    name: "Convert named imports to default import",
    description: getLocaleSpecificMessage(Diagnostics.Convert_named_imports_to_default_import),
    kind: "refactor.rewrite.import.default"
  }
};
registerRefactor(refactorName2, {
  kinds: getOwnValues(actions).map((a) => a.kind),
  getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) {
    const info = getImportConversionInfo(context, context.triggerReason === "invoked");
    if (!info) return emptyArray;
    if (!isRefactorErrorInfo(info)) {
      const action = actions[info.convertTo];
      return [{ name: refactorName2, description: action.description, actions: [action] }];
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return getOwnValues(actions).map((action) => ({
        name: refactorName2,
        description: action.description,
        actions: [{ ...action, notApplicableReason: info.error }]
      }));
    }
    return emptyArray;
  },
  getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName2) {
    Debug.assert(some(getOwnValues(actions), (action) => action.name === actionName2), "Unexpected action name");
    const info = getImportConversionInfo(context);
    Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info");
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange2(context.file, context.program, t, info));
    return { edits, renameFilename: void 0, renameLocation: void 0 };
  }
});
function getImportConversionInfo(context, considerPartialSpans = true) {
  const { file } = context;
  const span = getRefactorContextSpan(context);
  const token = getTokenAtPosition(file, span.start);
  const importDecl = considerPartialSpans ? findAncestor(token, or(isImportDeclaration, isJSDocImportTag)) : getParentNodeInSpan(token, file, span);
  if (importDecl === void 0 || !(isImportDeclaration(importDecl) || isJSDocImportTag(importDecl))) return { error: "Selection is not an import declaration." };
  const end = span.start + span.length;
  const nextToken = findNextToken(importDecl, importDecl.parent, file);
  if (nextToken && end > nextToken.getStart()) return void 0;
  const { importClause } = importDecl;
  if (!importClause) {
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) };
  }
  if (!importClause.namedBindings) {
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) };
  }
  if (importClause.namedBindings.kind === 274 /* NamespaceImport */) {
    return { convertTo: 0 /* Named */, import: importClause.namedBindings };
  }
  const shouldUseDefault = getShouldUseDefault(context.program, importClause);
  return shouldUseDefault ? { convertTo: 1 /* Default */, import: importClause.namedBindings } : { convertTo: 2 /* Namespace */, import: importClause.namedBindings };
}
function getShouldUseDefault(program, importClause) {
  return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker());
}
function doChange2(sourceFile, program, changes, info) {
  const checker = program.getTypeChecker();
  if (info.convertTo === 0 /* Named */) {
    doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions()));
  } else {
    doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === 1 /* Default */);
  }
}
function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) {
  let usedAsNamespaceOrDefault = false;
  const nodesToReplace = [];
  const conflictingNames = /* @__PURE__ */ new Map();
  ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, (id) => {
    if (!isPropertyAccessOrQualifiedName(id.parent)) {
      usedAsNamespaceOrDefault = true;
    } else {
      const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text;
      if (checker.resolveName(
        exportName,
        id,
        -1 /* All */,
        /*excludeGlobals*/
        true
      )) {
        conflictingNames.set(exportName, true);
      }
      Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id");
      nodesToReplace.push(id.parent);
    }
  });
  const exportNameToImportName = /* @__PURE__ */ new Map();
  for (const propertyAccessOrQualifiedName of nodesToReplace) {
    const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text;
    let importName = exportNameToImportName.get(exportName);
    if (importName === void 0) {
      exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? getUniqueName(exportName, sourceFile) : exportName);
    }
    changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, factory.createIdentifier(importName));
  }
  const importSpecifiers = [];
  exportNameToImportName.forEach((name, propertyName) => {
    importSpecifiers.push(factory.createImportSpecifier(
      /*isTypeOnly*/
      false,
      name === propertyName ? void 0 : factory.createIdentifier(propertyName),
      factory.createIdentifier(name)
    ));
  });
  const importDecl = toConvert.parent.parent;
  if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports && isImportDeclaration(importDecl)) {
    changes.insertNodeAfter(sourceFile, importDecl, createImport(
      importDecl,
      /*defaultImportName*/
      void 0,
      importSpecifiers
    ));
  } else {
    const defaultImportName = usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : void 0;
    changes.replaceNode(sourceFile, toConvert.parent, createImportClause(defaultImportName, importSpecifiers));
  }
}
function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) {
  return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right;
}
function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) {
  return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left;
}
function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConvert, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)) {
  const checker = program.getTypeChecker();
  const importDecl = toConvert.parent.parent;
  const { moduleSpecifier } = importDecl;
  const toConvertSymbols = /* @__PURE__ */ new Set();
  toConvert.elements.forEach((namedImport) => {
    const symbol = checker.getSymbolAtLocation(namedImport.name);
    if (symbol) {
      toConvertSymbols.add(symbol);
    }
  });
  const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module";
  function hasNamespaceNameConflict(namedImport) {
    return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id) => {
      const symbol = checker.resolveName(
        preferredName,
        id,
        -1 /* All */,
        /*excludeGlobals*/
        true
      );
      if (symbol) {
        if (toConvertSymbols.has(symbol)) {
          return isExportSpecifier(id.parent);
        }
        return true;
      }
      return false;
    });
  }
  const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict);
  const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName;
  const neededNamedImports = /* @__PURE__ */ new Set();
  for (const element of toConvert.elements) {
    const propertyName = element.propertyName || element.name;
    ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id) => {
      const access = propertyName.kind === 11 /* StringLiteral */ ? factory.createElementAccessExpression(factory.createIdentifier(namespaceImportName), factory.cloneNode(propertyName)) : factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), factory.cloneNode(propertyName));
      if (isShorthandPropertyAssignment(id.parent)) {
        changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access));
      } else if (isExportSpecifier(id.parent)) {
        neededNamedImports.add(element);
      } else {
        changes.replaceNode(sourceFile, id, access);
      }
    });
  }
  changes.replaceNode(
    sourceFile,
    toConvert,
    shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))
  );
  if (neededNamedImports.size && isImportDeclaration(importDecl)) {
    const newNamedImports = arrayFrom(neededNamedImports.values(), (element) => factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.cloneNode(element.propertyName), factory.cloneNode(element.name)));
    changes.insertNodeAfter(sourceFile, toConvert.parent.parent, createImport(
      importDecl,
      /*defaultImportName*/
      void 0,
      newNamedImports
    ));
  }
}
function isExportEqualsModule(moduleSpecifier, checker) {
  const externalModule = checker.resolveExternalModuleName(moduleSpecifier);
  if (!externalModule) return false;
  const exportEquals = checker.resolveExternalModuleSymbol(externalModule);
  return externalModule !== exportEquals;
}
function createImport(node, defaultImportName, elements) {
  return factory.createImportDeclaration(
    /*modifiers*/
    void 0,
    createImportClause(defaultImportName, elements),
    node.moduleSpecifier,
    /*attributes*/
    void 0
  );
}
function createImportClause(defaultImportName, elements) {
  return factory.createImportClause(
    /*isTypeOnly*/
    false,
    defaultImportName,
    elements && elements.length ? factory.createNamedImports(elements) : void 0
  );
}

// src/services/refactors/extractType.ts
var refactorName3 = "Extract type";
var extractToTypeAliasAction = {
  name: "Extract to type alias",
  description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias),
  kind: "refactor.extract.type"
};
var extractToInterfaceAction = {
  name: "Extract to interface",
  description: getLocaleSpecificMessage(Diagnostics.Extract_to_interface),
  kind: "refactor.extract.interface"
};
var extractToTypeDefAction = {
  name: "Extract to typedef",
  description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef),
  kind: "refactor.extract.typedef"
};
registerRefactor(refactorName3, {
  kinds: [
    extractToTypeAliasAction.kind,
    extractToInterfaceAction.kind,
    extractToTypeDefAction.kind
  ],
  getAvailableActions: function getRefactorActionsToExtractType(context) {
    const { info, affectedTextRange } = getRangeToExtract(context, context.triggerReason === "invoked");
    if (!info) return emptyArray;
    if (!isRefactorErrorInfo(info)) {
      const refactorInfo = [{
        name: refactorName3,
        description: getLocaleSpecificMessage(Diagnostics.Extract_type),
        actions: info.isJS ? [extractToTypeDefAction] : append([extractToTypeAliasAction], info.typeElements && extractToInterfaceAction)
      }];
      return refactorInfo.map((info2) => ({
        ...info2,
        actions: info2.actions.map((action) => ({
          ...action,
          range: affectedTextRange ? {
            start: { line: getLineAndCharacterOfPosition(context.file, affectedTextRange.pos).line, offset: getLineAndCharacterOfPosition(context.file, affectedTextRange.pos).character },
            end: { line: getLineAndCharacterOfPosition(context.file, affectedTextRange.end).line, offset: getLineAndCharacterOfPosition(context.file, affectedTextRange.end).character }
          } : void 0
        }))
      }));
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return [{
        name: refactorName3,
        description: getLocaleSpecificMessage(Diagnostics.Extract_type),
        actions: [
          { ...extractToTypeDefAction, notApplicableReason: info.error },
          { ...extractToTypeAliasAction, notApplicableReason: info.error },
          { ...extractToInterfaceAction, notApplicableReason: info.error }
        ]
      }];
    }
    return emptyArray;
  },
  getEditsForAction: function getRefactorEditsToExtractType(context, actionName2) {
    const { file } = context;
    const { info } = getRangeToExtract(context);
    Debug.assert(info && !isRefactorErrorInfo(info), "Expected to find a range to extract");
    const name = getUniqueName("NewType", file);
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      switch (actionName2) {
        case extractToTypeAliasAction.name:
          Debug.assert(!info.isJS, "Invalid actionName/JS combo");
          return doTypeAliasChange(changes, file, name, info);
        case extractToTypeDefAction.name:
          Debug.assert(info.isJS, "Invalid actionName/JS combo");
          return doTypedefChange(changes, context, file, name, info);
        case extractToInterfaceAction.name:
          Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo");
          return doInterfaceChange(changes, file, name, info);
        default:
          Debug.fail("Unexpected action name");
      }
    });
    const renameFilename = file.fileName;
    const renameLocation = getRenameLocation(
      edits,
      renameFilename,
      name,
      /*preferLastLocation*/
      false
    );
    return { edits, renameFilename, renameLocation };
  }
});
function getRangeToExtract(context, considerEmptySpans = true) {
  const { file, startPosition } = context;
  const isJS = isSourceFileJS(file);
  const range = createTextRangeFromSpan(getRefactorContextSpan(context));
  const isCursorRequest = range.pos === range.end && considerEmptySpans;
  const firstType = getFirstTypeAt(file, startPosition, range, isCursorRequest);
  if (!firstType || !isTypeNode(firstType)) return { info: { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }, affectedTextRange: void 0 };
  const checker = context.program.getTypeChecker();
  const enclosingNode = getEnclosingNode(firstType, isJS);
  if (enclosingNode === void 0) return { info: { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }, affectedTextRange: void 0 };
  const expandedFirstType = getExpandedSelectionNode(firstType, enclosingNode);
  if (!isTypeNode(expandedFirstType)) return { info: { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }, affectedTextRange: void 0 };
  const typeList = [];
  if ((isUnionTypeNode(expandedFirstType.parent) || isIntersectionTypeNode(expandedFirstType.parent)) && range.end > firstType.end) {
    addRange(
      typeList,
      expandedFirstType.parent.types.filter((type) => {
        return nodeOverlapsWithStartEnd(type, file, range.pos, range.end);
      })
    );
  }
  const selection = typeList.length > 1 ? typeList : expandedFirstType;
  const { typeParameters, affectedTextRange } = collectTypeParameters(checker, selection, enclosingNode, file);
  if (!typeParameters) return { info: { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }, affectedTextRange: void 0 };
  const typeElements = flattenTypeLiteralNodeReference(checker, selection);
  return { info: { isJS, selection, enclosingNode, typeParameters, typeElements }, affectedTextRange };
}
function getFirstTypeAt(file, startPosition, range, isCursorRequest) {
  const currentNodes = [
    () => getTokenAtPosition(file, startPosition),
    () => getTouchingToken(file, startPosition, () => true)
  ];
  for (const f of currentNodes) {
    const current = f();
    const overlappingRange = nodeOverlapsWithStartEnd(current, file, range.pos, range.end);
    const firstType = findAncestor(current, (node) => node.parent && isTypeNode(node) && !rangeContainsSkipTrivia(range, node.parent, file) && (isCursorRequest || overlappingRange));
    if (firstType) {
      return firstType;
    }
  }
  return void 0;
}
function flattenTypeLiteralNodeReference(checker, selection) {
  if (!selection) return void 0;
  if (isArray(selection)) {
    const result = [];
    for (const type of selection) {
      const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type);
      if (!flattenedTypeMembers) return void 0;
      addRange(result, flattenedTypeMembers);
    }
    return result;
  }
  if (isIntersectionTypeNode(selection)) {
    const result = [];
    const seen = /* @__PURE__ */ new Set();
    for (const type of selection.types) {
      const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type);
      if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2) => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) {
        return void 0;
      }
      addRange(result, flattenedTypeMembers);
    }
    return result;
  } else if (isParenthesizedTypeNode(selection)) {
    return flattenTypeLiteralNodeReference(checker, selection.type);
  } else if (isTypeLiteralNode(selection)) {
    return selection.members;
  }
  return void 0;
}
function rangeContainsSkipTrivia(r1, node, file) {
  return rangeContainsStartEnd(r1, skipTrivia(file.text, node.pos), node.end);
}
function collectTypeParameters(checker, selection, enclosingNode, file) {
  const result = [];
  const selectionArray = toArray(selection);
  const selectionRange = { pos: selectionArray[0].getStart(file), end: selectionArray[selectionArray.length - 1].end };
  for (const t of selectionArray) {
    if (visitor(t)) return { typeParameters: void 0, affectedTextRange: void 0 };
  }
  return { typeParameters: result, affectedTextRange: selectionRange };
  function visitor(node) {
    if (isTypeReferenceNode(node)) {
      if (isIdentifier(node.typeName)) {
        const typeName = node.typeName;
        const symbol = checker.resolveName(
          typeName.text,
          typeName,
          262144 /* TypeParameter */,
          /*excludeGlobals*/
          true
        );
        for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray) {
          if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) {
            if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selectionRange, file)) {
              return true;
            }
            if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selectionRange, decl, file)) {
              pushIfUnique(result, decl);
              break;
            }
          }
        }
      }
    } else if (isInferTypeNode(node)) {
      const conditionalTypeNode = findAncestor(node, (n) => isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file));
      if (!conditionalTypeNode || !rangeContainsSkipTrivia(selectionRange, conditionalTypeNode, file)) {
        return true;
      }
    } else if (isTypePredicateNode(node) || isThisTypeNode(node)) {
      const functionLikeNode = findAncestor(node.parent, isFunctionLike);
      if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selectionRange, functionLikeNode, file)) {
        return true;
      }
    } else if (isTypeQueryNode(node)) {
      if (isIdentifier(node.exprName)) {
        const symbol = checker.resolveName(
          node.exprName.text,
          node.exprName,
          111551 /* Value */,
          /*excludeGlobals*/
          false
        );
        if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selectionRange, symbol.valueDeclaration, file)) {
          return true;
        }
      } else {
        if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selectionRange, node.parent, file)) {
          return true;
        }
      }
    }
    if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) {
      setEmitFlags(node, 1 /* SingleLine */);
    }
    return forEachChild(node, visitor);
  }
}
function doTypeAliasChange(changes, file, name, info) {
  const { enclosingNode, typeParameters } = info;
  const { firstTypeNode, lastTypeNode, newTypeNode } = getNodesToEdit(info);
  const newTypeDeclaration = factory.createTypeAliasDeclaration(
    /*modifiers*/
    void 0,
    name,
    typeParameters.map((id) => factory.updateTypeParameterDeclaration(
      id,
      id.modifiers,
      id.name,
      id.constraint,
      /*defaultType*/
      void 0
    )),
    newTypeNode
  );
  changes.insertNodeBefore(
    file,
    enclosingNode,
    ignoreSourceNewlines(newTypeDeclaration),
    /*blankLineBetween*/
    true
  );
  changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode(
    id.name,
    /*typeArguments*/
    void 0
  ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace });
}
function doInterfaceChange(changes, file, name, info) {
  var _a;
  const { enclosingNode, typeParameters, typeElements } = info;
  const newTypeNode = factory.createInterfaceDeclaration(
    /*modifiers*/
    void 0,
    name,
    typeParameters,
    /*heritageClauses*/
    void 0,
    typeElements
  );
  setTextRange(newTypeNode, (_a = typeElements[0]) == null ? void 0 : _a.parent);
  changes.insertNodeBefore(
    file,
    enclosingNode,
    ignoreSourceNewlines(newTypeNode),
    /*blankLineBetween*/
    true
  );
  const { firstTypeNode, lastTypeNode } = getNodesToEdit(info);
  changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode(
    id.name,
    /*typeArguments*/
    void 0
  ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace });
}
function doTypedefChange(changes, context, file, name, info) {
  var _a;
  toArray(info.selection).forEach((typeNode) => {
    setEmitFlags(typeNode, 3072 /* NoComments */ | 4096 /* NoNestedComments */);
  });
  const { enclosingNode, typeParameters } = info;
  const { firstTypeNode, lastTypeNode, newTypeNode } = getNodesToEdit(info);
  const node = factory.createJSDocTypedefTag(
    factory.createIdentifier("typedef"),
    factory.createJSDocTypeExpression(newTypeNode),
    factory.createIdentifier(name)
  );
  const templates = [];
  forEach(typeParameters, (typeParameter) => {
    const constraint = getEffectiveConstraintOfTypeParameter(typeParameter);
    const parameter = factory.createTypeParameterDeclaration(
      /*modifiers*/
      void 0,
      typeParameter.name
    );
    const template = factory.createJSDocTemplateTag(
      factory.createIdentifier("template"),
      constraint && cast(constraint, isJSDocTypeExpression),
      [parameter]
    );
    templates.push(template);
  });
  const jsDoc = factory.createJSDocComment(
    /*comment*/
    void 0,
    factory.createNodeArray(concatenate(templates, [node]))
  );
  if (isJSDoc(enclosingNode)) {
    const pos = enclosingNode.getStart(file);
    const newLineCharacter = getNewLineOrDefaultFromHost(context.host, (_a = context.formatContext) == null ? void 0 : _a.options);
    changes.insertNodeAt(file, enclosingNode.getStart(file), jsDoc, {
      suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos)
    });
  } else {
    changes.insertNodeBefore(
      file,
      enclosingNode,
      jsDoc,
      /*blankLineBetween*/
      true
    );
  }
  changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode(
    id.name,
    /*typeArguments*/
    void 0
  ))));
}
function getNodesToEdit(info) {
  if (isArray(info.selection)) {
    return {
      firstTypeNode: info.selection[0],
      lastTypeNode: info.selection[info.selection.length - 1],
      newTypeNode: isUnionTypeNode(info.selection[0].parent) ? factory.createUnionTypeNode(info.selection) : factory.createIntersectionTypeNode(info.selection)
    };
  }
  return {
    firstTypeNode: info.selection,
    lastTypeNode: info.selection,
    newTypeNode: info.selection
  };
}
function getEnclosingNode(node, isJS) {
  return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0);
}
function getExpandedSelectionNode(firstType, enclosingNode) {
  return findAncestor(firstType, (node) => {
    if (node === enclosingNode) return "quit";
    if (isUnionTypeNode(node.parent) || isIntersectionTypeNode(node.parent)) {
      return true;
    }
    return false;
  }) ?? firstType;
}

// src/services/refactors/moveToFile.ts
var refactorNameForMoveToFile = "Move to file";
var description = getLocaleSpecificMessage(Diagnostics.Move_to_file);
var moveToFileAction = {
  name: "Move to file",
  description,
  kind: "refactor.move.file"
};
registerRefactor(refactorNameForMoveToFile, {
  kinds: [moveToFileAction.kind],
  getAvailableActions: function getRefactorActionsToMoveToFile(context, interactiveRefactorArguments) {
    const file = context.file;
    const statements = getStatementsToMove(context);
    if (!interactiveRefactorArguments) {
      return emptyArray;
    }
    if (context.triggerReason === "implicit" && context.endPosition !== void 0) {
      const startNodeAncestor = findAncestor(getTokenAtPosition(file, context.startPosition), isBlockLike);
      const endNodeAncestor = findAncestor(getTokenAtPosition(file, context.endPosition), isBlockLike);
      if (startNodeAncestor && !isSourceFile(startNodeAncestor) && endNodeAncestor && !isSourceFile(endNodeAncestor)) {
        return emptyArray;
      }
    }
    if (context.preferences.allowTextChangesInNewFiles && statements) {
      const affectedTextRange = {
        start: { line: getLineAndCharacterOfPosition(file, statements.all[0].getStart(file)).line, offset: getLineAndCharacterOfPosition(file, statements.all[0].getStart(file)).character },
        end: { line: getLineAndCharacterOfPosition(file, last(statements.all).end).line, offset: getLineAndCharacterOfPosition(file, last(statements.all).end).character }
      };
      return [{ name: refactorNameForMoveToFile, description, actions: [{ ...moveToFileAction, range: affectedTextRange }] }];
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return [{ name: refactorNameForMoveToFile, description, actions: [{ ...moveToFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] }];
    }
    return emptyArray;
  },
  getEditsForAction: function getRefactorEditsToMoveToFile(context, actionName2, interactiveRefactorArguments) {
    Debug.assert(actionName2 === refactorNameForMoveToFile, "Wrong refactor invoked");
    const statements = Debug.checkDefined(getStatementsToMove(context));
    const { host, program } = context;
    Debug.assert(interactiveRefactorArguments, "No interactive refactor arguments available");
    const targetFile = interactiveRefactorArguments.targetFile;
    if (hasJSFileExtension(targetFile) || hasTSFileExtension(targetFile)) {
      if (host.fileExists(targetFile) && program.getSourceFile(targetFile) === void 0) {
        return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_statements_to_the_selected_file));
      }
      const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange3(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences));
      return { edits, renameFilename: void 0, renameLocation: void 0 };
    }
    return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_to_file_selected_file_is_invalid));
  }
});
function error(notApplicableReason) {
  return { edits: [], renameFilename: void 0, renameLocation: void 0, notApplicableReason };
}
function doChange3(context, oldFile, targetFile, program, toMove, changes, host, preferences) {
  const checker = program.getTypeChecker();
  const isForNewFile = !host.fileExists(targetFile);
  const targetSourceFile = isForNewFile ? createFutureSourceFile(targetFile, oldFile.externalModuleIndicator ? 99 /* ESNext */ : oldFile.commonJsModuleIndicator ? 1 /* CommonJS */ : void 0, program, host) : Debug.checkDefined(program.getSourceFile(targetFile));
  const importAdderForOldFile = ts_codefix_exports.createImportAdder(oldFile, context.program, context.preferences, context.host);
  const importAdderForNewFile = ts_codefix_exports.createImportAdder(targetSourceFile, context.program, context.preferences, context.host);
  getNewStatementsAndRemoveFromOldFile(oldFile, targetSourceFile, getUsageInfo(oldFile, toMove.all, checker, isForNewFile ? void 0 : getExistingLocals(targetSourceFile, toMove.all, checker)), changes, toMove, program, host, preferences, importAdderForNewFile, importAdderForOldFile);
  if (isForNewFile) {
    addNewFileToTsconfig(program, changes, oldFile.fileName, targetFile, hostGetCanonicalFileName(host));
  }
}
function getNewStatementsAndRemoveFromOldFile(oldFile, targetFile, usage, changes, toMove, program, host, preferences, importAdderForNewFile, importAdderForOldFile) {
  const checker = program.getTypeChecker();
  const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective);
  const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFile.fileName, program, host, !!oldFile.commonJsModuleIndicator);
  const quotePreference = getQuotePreference(oldFile, preferences);
  addImportsForMovedSymbols(usage.oldFileImportsFromTargetFile, targetFile.fileName, importAdderForOldFile, program);
  deleteUnusedOldImports(oldFile, toMove.all, usage.unusedImportsFromOldFile, importAdderForOldFile);
  importAdderForOldFile.writeFixes(changes, quotePreference);
  deleteMovedStatements(oldFile, toMove.ranges, changes);
  updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, targetFile.fileName, quotePreference);
  addExportsInOldFile(oldFile, usage.targetFileImportsFromOldFile, changes, useEsModuleSyntax);
  addTargetFileImports(oldFile, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, checker, program, importAdderForNewFile);
  if (!isFullSourceFile(targetFile) && prologueDirectives.length) {
    changes.insertStatementsInNewFile(targetFile.fileName, prologueDirectives, oldFile);
  }
  importAdderForNewFile.writeFixes(changes, quotePreference);
  const body = addExports(oldFile, toMove.all, arrayFrom(usage.oldFileImportsFromTargetFile.keys()), useEsModuleSyntax);
  if (isFullSourceFile(targetFile) && targetFile.statements.length > 0) {
    moveStatementsToTargetFile(changes, program, body, targetFile, toMove);
  } else if (isFullSourceFile(targetFile)) {
    changes.insertNodesAtEndOfFile(
      targetFile,
      body,
      /*blankLineBetween*/
      false
    );
  } else {
    changes.insertStatementsInNewFile(targetFile.fileName, importAdderForNewFile.hasFixes() ? [4 /* NewLineTrivia */, ...body] : body, oldFile);
  }
}
function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
  const cfg = program.getCompilerOptions().configFile;
  if (!cfg) return;
  const newFileAbsolutePath = normalizePath(combinePaths(oldFileName, "..", newFileNameWithExtension));
  const newFilePath = getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
  const cfgObject = cfg.statements[0] && tryCast(cfg.statements[0].expression, isObjectLiteralExpression);
  const filesProp = cfgObject && find(cfgObject.properties, (prop) => isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "files");
  if (filesProp && isArrayLiteralExpression(filesProp.initializer)) {
    changes.insertNodeInListAfter(cfg, last(filesProp.initializer.elements), factory.createStringLiteral(newFilePath), filesProp.initializer.elements);
  }
}
function deleteMovedStatements(sourceFile, moved, changes) {
  for (const { first: first2, afterLast } of moved) {
    changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast);
  }
}
function deleteUnusedOldImports(oldFile, toMove, toDelete, importAdder) {
  for (const statement of oldFile.statements) {
    if (contains(toMove, statement)) continue;
    forEachImportInStatement(statement, (i) => {
      forEachAliasDeclarationInImportOrRequire(i, (decl) => {
        if (toDelete.has(decl.symbol)) {
          importAdder.removeExistingImport(decl);
        }
      });
    });
  }
}
function addExportsInOldFile(oldFile, targetFileImportsFromOldFile, changes, useEsModuleSyntax) {
  const markSeenTop = nodeSeenTracker();
  targetFileImportsFromOldFile.forEach((_, symbol) => {
    if (!symbol.declarations) {
      return;
    }
    for (const decl of symbol.declarations) {
      if (!isTopLevelDeclaration(decl)) continue;
      const name = nameOfTopLevelDeclaration(decl);
      if (!name) continue;
      const top = getTopLevelDeclarationStatement(decl);
      if (markSeenTop(top)) {
        addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax);
      }
    }
  });
}
function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols, targetFileName, quotePreference) {
  const checker = program.getTypeChecker();
  for (const sourceFile of program.getSourceFiles()) {
    if (sourceFile === oldFile) continue;
    for (const statement of sourceFile.statements) {
      forEachImportInStatement(statement, (importNode) => {
        if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return;
        const shouldMove = (name) => {
          const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker);
          return !!symbol && movedSymbols.has(symbol);
        };
        deleteUnusedImports(sourceFile, importNode, changes, shouldMove);
        const pathToTargetFileWithExtension = resolvePath(getDirectoryPath(getNormalizedAbsolutePath(oldFile.fileName, program.getCurrentDirectory())), targetFileName);
        if (getStringComparer(!program.useCaseSensitiveFileNames())(pathToTargetFileWithExtension, sourceFile.fileName) === 0 /* EqualTo */) return;
        const newModuleSpecifier = ts_moduleSpecifiers_exports.getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.fileName, pathToTargetFileWithExtension, createModuleSpecifierResolutionHost(program, host));
        const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove);
        if (newImportDeclaration) changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
        const ns = getNamespaceLikeImport(importNode);
        if (ns) updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode, quotePreference);
      });
    }
  }
}
function getNamespaceLikeImport(node) {
  switch (node.kind) {
    case 272 /* ImportDeclaration */:
      return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 274 /* NamespaceImport */ ? node.importClause.namedBindings.name : void 0;
    case 271 /* ImportEqualsDeclaration */:
      return node.name;
    case 260 /* VariableDeclaration */:
      return tryCast(node.name, isIdentifier);
    default:
      return Debug.assertNever(node, `Unexpected node kind ${node.kind}`);
  }
}
function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, oldImportId, oldImportNode, quotePreference) {
  const preferredNewNamespaceName = moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */);
  let needUniqueName = false;
  const toChange = [];
  ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref) => {
    if (!isPropertyAccessExpression(ref.parent)) return;
    needUniqueName = needUniqueName || !!checker.resolveName(
      preferredNewNamespaceName,
      ref,
      -1 /* All */,
      /*excludeGlobals*/
      true
    );
    if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) {
      toChange.push(ref);
    }
  });
  if (toChange.length) {
    const newNamespaceName = needUniqueName ? getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName;
    for (const ref of toChange) {
      changes.replaceNode(sourceFile, ref, factory.createIdentifier(newNamespaceName));
    }
    changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, preferredNewNamespaceName, newModuleSpecifier, quotePreference));
  }
}
function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier, quotePreference) {
  const newNamespaceId = factory.createIdentifier(newNamespaceName);
  const newModuleString = makeStringLiteral(newModuleSpecifier, quotePreference);
  switch (node.kind) {
    case 272 /* ImportDeclaration */:
      return factory.createImportDeclaration(
        /*modifiers*/
        void 0,
        factory.createImportClause(
          /*isTypeOnly*/
          false,
          /*name*/
          void 0,
          factory.createNamespaceImport(newNamespaceId)
        ),
        newModuleString,
        /*attributes*/
        void 0
      );
    case 271 /* ImportEqualsDeclaration */:
      return factory.createImportEqualsDeclaration(
        /*modifiers*/
        void 0,
        /*isTypeOnly*/
        false,
        newNamespaceId,
        factory.createExternalModuleReference(newModuleString)
      );
    case 260 /* VariableDeclaration */:
      return factory.createVariableDeclaration(
        newNamespaceId,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        createRequireCall(newModuleString)
      );
    default:
      return Debug.assertNever(node, `Unexpected node kind ${node.kind}`);
  }
}
function createRequireCall(moduleSpecifier) {
  return factory.createCallExpression(
    factory.createIdentifier("require"),
    /*typeArguments*/
    void 0,
    [moduleSpecifier]
  );
}
function moduleSpecifierFromImport(i) {
  return i.kind === 272 /* ImportDeclaration */ ? i.moduleSpecifier : i.kind === 271 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0];
}
function forEachImportInStatement(statement, cb) {
  if (isImportDeclaration(statement)) {
    if (isStringLiteral(statement.moduleSpecifier)) cb(statement);
  } else if (isImportEqualsDeclaration(statement)) {
    if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) {
      cb(statement);
    }
  } else if (isVariableStatement(statement)) {
    for (const decl of statement.declarationList.declarations) {
      if (decl.initializer && isRequireCall(
        decl.initializer,
        /*requireStringLiteralLikeArgument*/
        true
      )) {
        cb(decl);
      }
    }
  }
}
function forEachAliasDeclarationInImportOrRequire(importOrRequire, cb) {
  var _a, _b, _c, _d, _e;
  if (importOrRequire.kind === 272 /* ImportDeclaration */) {
    if ((_a = importOrRequire.importClause) == null ? void 0 : _a.name) {
      cb(importOrRequire.importClause);
    }
    if (((_c = (_b = importOrRequire.importClause) == null ? void 0 : _b.namedBindings) == null ? void 0 : _c.kind) === 274 /* NamespaceImport */) {
      cb(importOrRequire.importClause.namedBindings);
    }
    if (((_e = (_d = importOrRequire.importClause) == null ? void 0 : _d.namedBindings) == null ? void 0 : _e.kind) === 275 /* NamedImports */) {
      for (const element of importOrRequire.importClause.namedBindings.elements) {
        cb(element);
      }
    }
  } else if (importOrRequire.kind === 271 /* ImportEqualsDeclaration */) {
    cb(importOrRequire);
  } else if (importOrRequire.kind === 260 /* VariableDeclaration */) {
    if (importOrRequire.name.kind === 80 /* Identifier */) {
      cb(importOrRequire);
    } else if (importOrRequire.name.kind === 206 /* ObjectBindingPattern */) {
      for (const element of importOrRequire.name.elements) {
        if (isIdentifier(element.name)) {
          cb(element);
        }
      }
    }
  }
}
function addImportsForMovedSymbols(symbols, targetFileName, importAdder, program) {
  for (const [symbol, isValidTypeOnlyUseSite] of symbols) {
    const symbolName2 = getNameForExportedSymbol(symbol, getEmitScriptTarget(program.getCompilerOptions()));
    const exportKind = symbol.name === "default" && symbol.parent ? 1 /* Default */ : 0 /* Named */;
    importAdder.addImportForNonExistentExport(symbolName2, targetFileName, exportKind, symbol.flags, isValidTypeOnlyUseSite);
  }
}
function makeVariableStatement(name, type, initializer, flags = 2 /* Const */) {
  return factory.createVariableStatement(
    /*modifiers*/
    void 0,
    factory.createVariableDeclarationList([factory.createVariableDeclaration(
      name,
      /*exclamationToken*/
      void 0,
      type,
      initializer
    )], flags)
  );
}
function addExports(sourceFile, toMove, needExport, useEs6Exports) {
  return flatMap(toMove, (statement) => {
    if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d) => {
      var _a;
      return needExport.includes(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol));
    })) {
      const exports2 = addExport(getSynthesizedDeepClone(statement), useEs6Exports);
      if (exports2) return exports2;
    }
    return getSynthesizedDeepClone(statement);
  });
}
function isExported(sourceFile, decl, useEs6Exports, name) {
  var _a;
  if (useEs6Exports) {
    return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 32 /* Export */) || !!(name && sourceFile.symbol && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText)));
  }
  return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2) => sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2)));
}
function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
  if (importDecl.kind === 272 /* ImportDeclaration */ && importDecl.importClause) {
    const { name, namedBindings } = importDecl.importClause;
    if ((!name || isUnused(name)) && (!namedBindings || namedBindings.kind === 275 /* NamedImports */ && namedBindings.elements.length !== 0 && namedBindings.elements.every((e) => isUnused(e.name)))) {
      return changes.delete(sourceFile, importDecl);
    }
  }
  forEachAliasDeclarationInImportOrRequire(importDecl, (i) => {
    if (i.name && isIdentifier(i.name) && isUnused(i.name)) {
      changes.delete(sourceFile, i);
    }
  });
}
function isTopLevelDeclarationStatement(node) {
  Debug.assert(isSourceFile(node.parent), "Node parent should be a SourceFile");
  return isNonVariableTopLevelDeclaration(node) || isVariableStatement(node);
}
function addExport(decl, useEs6Exports) {
  return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
}
function addEs6Export(d) {
  const modifiers = canHaveModifiers(d) ? concatenate([factory.createModifier(95 /* ExportKeyword */)], getModifiers(d)) : void 0;
  switch (d.kind) {
    case 262 /* FunctionDeclaration */:
      return factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
    case 263 /* ClassDeclaration */:
      const decorators = canHaveDecorators(d) ? getDecorators(d) : void 0;
      return factory.updateClassDeclaration(d, concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members);
    case 243 /* VariableStatement */:
      return factory.updateVariableStatement(d, modifiers, d.declarationList);
    case 267 /* ModuleDeclaration */:
      return factory.updateModuleDeclaration(d, modifiers, d.name, d.body);
    case 266 /* EnumDeclaration */:
      return factory.updateEnumDeclaration(d, modifiers, d.name, d.members);
    case 265 /* TypeAliasDeclaration */:
      return factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type);
    case 264 /* InterfaceDeclaration */:
      return factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
    case 271 /* ImportEqualsDeclaration */:
      return factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference);
    case 244 /* ExpressionStatement */:
      return Debug.fail();
    default:
      return Debug.assertNever(d, `Unexpected declaration kind ${d.kind}`);
  }
}
function addCommonjsExport(decl) {
  return [decl, ...getNamesToExportInCommonJS(decl).map(createExportAssignment)];
}
function createExportAssignment(name) {
  return factory.createExpressionStatement(
    factory.createBinaryExpression(
      factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)),
      64 /* EqualsToken */,
      factory.createIdentifier(name)
    )
  );
}
function getNamesToExportInCommonJS(decl) {
  switch (decl.kind) {
    case 262 /* FunctionDeclaration */:
    case 263 /* ClassDeclaration */:
      return [decl.name.text];
    // TODO: GH#18217
    case 243 /* VariableStatement */:
      return mapDefined(decl.declarationList.declarations, (d) => isIdentifier(d.name) ? d.name.text : void 0);
    case 267 /* ModuleDeclaration */:
    case 266 /* EnumDeclaration */:
    case 265 /* TypeAliasDeclaration */:
    case 264 /* InterfaceDeclaration */:
    case 271 /* ImportEqualsDeclaration */:
      return emptyArray;
    case 244 /* ExpressionStatement */:
      return Debug.fail("Can't export an ExpressionStatement");
    default:
      return Debug.assertNever(decl, `Unexpected decl kind ${decl.kind}`);
  }
}
function filterImport(i, moduleSpecifier, keep) {
  switch (i.kind) {
    case 272 /* ImportDeclaration */: {
      const clause = i.importClause;
      if (!clause) return void 0;
      const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0;
      const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
      return defaultImport || namedBindings ? factory.createImportDeclaration(
        /*modifiers*/
        void 0,
        factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings),
        getSynthesizedDeepClone(moduleSpecifier),
        /*attributes*/
        void 0
      ) : void 0;
    }
    case 271 /* ImportEqualsDeclaration */:
      return keep(i.name) ? i : void 0;
    case 260 /* VariableDeclaration */: {
      const name = filterBindingName(i.name, keep);
      return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0;
    }
    default:
      return Debug.assertNever(i, `Unexpected import kind ${i.kind}`);
  }
}
function filterNamedBindings(namedBindings, keep) {
  if (namedBindings.kind === 274 /* NamespaceImport */) {
    return keep(namedBindings.name) ? namedBindings : void 0;
  } else {
    const newElements = namedBindings.elements.filter((e) => keep(e.name));
    return newElements.length ? factory.createNamedImports(newElements) : void 0;
  }
}
function filterBindingName(name, keep) {
  switch (name.kind) {
    case 80 /* Identifier */:
      return keep(name) ? name : void 0;
    case 207 /* ArrayBindingPattern */:
      return name;
    case 206 /* ObjectBindingPattern */: {
      const newElements = name.elements.filter((prop) => prop.propertyName || !isIdentifier(prop.name) || keep(prop.name));
      return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0;
    }
  }
}
function nameOfTopLevelDeclaration(d) {
  return isExpressionStatement(d) ? tryCast(d.expression.left.name, isIdentifier) : tryCast(d.name, isIdentifier);
}
function getTopLevelDeclarationStatement(d) {
  switch (d.kind) {
    case 260 /* VariableDeclaration */:
      return d.parent.parent;
    case 208 /* BindingElement */:
      return getTopLevelDeclarationStatement(
        cast(d.parent.parent, (p) => isVariableDeclaration(p) || isBindingElement(p))
      );
    default:
      return d;
  }
}
function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) {
  if (isExported(sourceFile, decl, useEs6Exports, name)) return;
  if (useEs6Exports) {
    if (!isExpressionStatement(decl)) changes.insertExportModifier(sourceFile, decl);
  } else {
    const names = getNamesToExportInCommonJS(decl);
    if (names.length !== 0) changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
  }
}
function createNewFileName(oldFile, program, host, toMove) {
  const checker = program.getTypeChecker();
  if (toMove) {
    const usage = getUsageInfo(oldFile, toMove.all, checker);
    const currentDirectory = getDirectoryPath(oldFile.fileName);
    const extension = extensionFromPath(oldFile.fileName);
    const newFileName = combinePaths(
      // new file is always placed in the same directory as the old file
      currentDirectory,
      // ensures the filename computed below isn't already taken
      makeUniqueFilename(
        // infers a name for the new file from the symbols being moved
        inferNewFileName(usage.oldFileImportsFromTargetFile, usage.movedSymbols),
        extension,
        currentDirectory,
        host
      )
    ) + extension;
    return newFileName;
  }
  return "";
}
function getRangeToMove(context) {
  const { file } = context;
  const range = createTextRangeFromSpan(getRefactorContextSpan(context));
  const { statements } = file;
  let startNodeIndex = findIndex(statements, (s) => s.end > range.pos);
  if (startNodeIndex === -1) return void 0;
  const startStatement = statements[startNodeIndex];
  const overloadRangeToMove = getOverloadRangeToMove(file, startStatement);
  if (overloadRangeToMove) {
    startNodeIndex = overloadRangeToMove.start;
  }
  let endNodeIndex = findIndex(statements, (s) => s.end >= range.end, startNodeIndex);
  if (endNodeIndex !== -1 && range.end <= statements[endNodeIndex].getStart()) {
    endNodeIndex--;
  }
  const endingOverloadRangeToMove = getOverloadRangeToMove(file, statements[endNodeIndex]);
  if (endingOverloadRangeToMove) {
    endNodeIndex = endingOverloadRangeToMove.end;
  }
  return {
    toMove: statements.slice(startNodeIndex, endNodeIndex === -1 ? statements.length : endNodeIndex + 1),
    afterLast: endNodeIndex === -1 ? void 0 : statements[endNodeIndex + 1]
  };
}
function getStatementsToMove(context) {
  const rangeToMove = getRangeToMove(context);
  if (rangeToMove === void 0) return void 0;
  const all = [];
  const ranges = [];
  const { toMove, afterLast } = rangeToMove;
  getRangesWhere(toMove, isAllowedStatementToMove, (start, afterEndIndex) => {
    for (let i = start; i < afterEndIndex; i++) all.push(toMove[i]);
    ranges.push({ first: toMove[start], afterLast });
  });
  return all.length === 0 ? void 0 : { all, ranges };
}
function containsJsx(statements) {
  return find(statements, (statement) => !!(statement.transformFlags & 2 /* ContainsJsx */));
}
function isAllowedStatementToMove(statement) {
  return !isPureImport(statement) && !isPrologueDirective(statement);
}
function isPureImport(node) {
  switch (node.kind) {
    case 272 /* ImportDeclaration */:
      return true;
    case 271 /* ImportEqualsDeclaration */:
      return !hasSyntacticModifier(node, 32 /* Export */);
    case 243 /* VariableStatement */:
      return node.declarationList.declarations.every((d) => !!d.initializer && isRequireCall(
        d.initializer,
        /*requireStringLiteralLikeArgument*/
        true
      ));
    default:
      return false;
  }
}
function getUsageInfo(oldFile, toMove, checker, existingTargetLocals = /* @__PURE__ */ new Set(), enclosingRange) {
  var _a;
  const movedSymbols = /* @__PURE__ */ new Set();
  const oldImportsNeededByTargetFile = /* @__PURE__ */ new Map();
  const targetFileImportsFromOldFile = /* @__PURE__ */ new Map();
  const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx(toMove));
  if (jsxNamespaceSymbol) {
    oldImportsNeededByTargetFile.set(jsxNamespaceSymbol, [false, tryCast((_a = jsxNamespaceSymbol.declarations) == null ? void 0 : _a[0], (d) => isImportSpecifier(d) || isImportClause(d) || isNamespaceImport(d) || isImportEqualsDeclaration(d) || isBindingElement(d) || isVariableDeclaration(d))]);
  }
  for (const statement of toMove) {
    forEachTopLevelDeclaration(statement, (decl) => {
      movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here"));
    });
  }
  const unusedImportsFromOldFile = /* @__PURE__ */ new Set();
  for (const statement of toMove) {
    forEachReference(statement, checker, enclosingRange, (symbol, isValidTypeOnlyUseSite) => {
      if (!symbol.declarations) {
        return;
      }
      if (existingTargetLocals.has(skipAlias(symbol, checker))) {
        unusedImportsFromOldFile.add(symbol);
        return;
      }
      const importedDeclaration = find(symbol.declarations, isInImport);
      if (importedDeclaration) {
        const prevIsTypeOnly = oldImportsNeededByTargetFile.get(symbol);
        oldImportsNeededByTargetFile.set(symbol, [
          prevIsTypeOnly === void 0 ? isValidTypeOnlyUseSite : prevIsTypeOnly && isValidTypeOnlyUseSite,
          tryCast(importedDeclaration, (d) => isImportSpecifier(d) || isImportClause(d) || isNamespaceImport(d) || isImportEqualsDeclaration(d) || isBindingElement(d) || isVariableDeclaration(d))
        ]);
      } else if (!movedSymbols.has(symbol) && every(symbol.declarations, (decl) => isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile)) {
        targetFileImportsFromOldFile.set(symbol, isValidTypeOnlyUseSite);
      }
    });
  }
  for (const unusedImport of oldImportsNeededByTargetFile.keys()) {
    unusedImportsFromOldFile.add(unusedImport);
  }
  const oldFileImportsFromTargetFile = /* @__PURE__ */ new Map();
  for (const statement of oldFile.statements) {
    if (contains(toMove, statement)) continue;
    if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) {
      unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
    }
    forEachReference(statement, checker, enclosingRange, (symbol, isValidTypeOnlyUseSite) => {
      if (movedSymbols.has(symbol)) oldFileImportsFromTargetFile.set(symbol, isValidTypeOnlyUseSite);
      unusedImportsFromOldFile.delete(symbol);
    });
  }
  return { movedSymbols, targetFileImportsFromOldFile, oldFileImportsFromTargetFile, oldImportsNeededByTargetFile, unusedImportsFromOldFile };
  function getJsxNamespaceSymbol(containsJsx2) {
    if (containsJsx2 === void 0) {
      return void 0;
    }
    const jsxNamespace = checker.getJsxNamespace(containsJsx2);
    const jsxNamespaceSymbol2 = checker.resolveName(
      jsxNamespace,
      containsJsx2,
      1920 /* Namespace */,
      /*excludeGlobals*/
      true
    );
    return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0;
  }
}
function makeUniqueFilename(proposedFilename, extension, inDirectory, host) {
  let newFilename = proposedFilename;
  for (let i = 1; ; i++) {
    const name = combinePaths(inDirectory, newFilename + extension);
    if (!host.fileExists(name)) return newFilename;
    newFilename = `${proposedFilename}.${i}`;
  }
}
function inferNewFileName(importsFromNewFile, movedSymbols) {
  return forEachKey(importsFromNewFile, symbolNameNoDefault) || forEachKey(movedSymbols, symbolNameNoDefault) || "newFile";
}
function forEachReference(node, checker, enclosingRange, onReference) {
  node.forEachChild(function cb(node2) {
    if (isIdentifier(node2) && !isDeclarationName(node2)) {
      if (enclosingRange && !rangeContainsRange(enclosingRange, node2)) {
        return;
      }
      const sym = checker.getSymbolAtLocation(node2);
      if (sym) onReference(sym, isValidTypeOnlyAliasUseSite(node2));
    } else {
      node2.forEachChild(cb);
    }
  });
}
function forEachTopLevelDeclaration(statement, cb) {
  switch (statement.kind) {
    case 262 /* FunctionDeclaration */:
    case 263 /* ClassDeclaration */:
    case 267 /* ModuleDeclaration */:
    case 266 /* EnumDeclaration */:
    case 265 /* TypeAliasDeclaration */:
    case 264 /* InterfaceDeclaration */:
    case 271 /* ImportEqualsDeclaration */:
      return cb(statement);
    case 243 /* VariableStatement */:
      return firstDefined(statement.declarationList.declarations, (decl) => forEachTopLevelDeclarationInBindingName(decl.name, cb));
    case 244 /* ExpressionStatement */: {
      const { expression } = statement;
      return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0;
    }
  }
}
function isInImport(decl) {
  switch (decl.kind) {
    case 271 /* ImportEqualsDeclaration */:
    case 276 /* ImportSpecifier */:
    case 273 /* ImportClause */:
    case 274 /* NamespaceImport */:
      return true;
    case 260 /* VariableDeclaration */:
      return isVariableDeclarationInImport(decl);
    case 208 /* BindingElement */:
      return isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
    default:
      return false;
  }
}
function isVariableDeclarationInImport(decl) {
  return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall(
    decl.initializer,
    /*requireStringLiteralLikeArgument*/
    true
  );
}
function isTopLevelDeclaration(node) {
  return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent);
}
function sourceFileOfTopLevelDeclaration(node) {
  return isVariableDeclaration(node) ? node.parent.parent.parent : node.parent;
}
function forEachTopLevelDeclarationInBindingName(name, cb) {
  switch (name.kind) {
    case 80 /* Identifier */:
      return cb(cast(name.parent, (x) => isVariableDeclaration(x) || isBindingElement(x)));
    case 207 /* ArrayBindingPattern */:
    case 206 /* ObjectBindingPattern */:
      return firstDefined(name.elements, (em) => isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb));
    default:
      return Debug.assertNever(name, `Unexpected name kind ${name.kind}`);
  }
}
function isNonVariableTopLevelDeclaration(node) {
  switch (node.kind) {
    case 262 /* FunctionDeclaration */:
    case 263 /* ClassDeclaration */:
    case 267 /* ModuleDeclaration */:
    case 266 /* EnumDeclaration */:
    case 265 /* TypeAliasDeclaration */:
    case 264 /* InterfaceDeclaration */:
    case 271 /* ImportEqualsDeclaration */:
      return true;
    default:
      return false;
  }
}
function moveStatementsToTargetFile(changes, program, statements, targetFile, toMove) {
  var _a;
  const removedExports = /* @__PURE__ */ new Set();
  const targetExports = (_a = targetFile.symbol) == null ? void 0 : _a.exports;
  if (targetExports) {
    const checker = program.getTypeChecker();
    const targetToSourceExports = /* @__PURE__ */ new Map();
    for (const node of toMove.all) {
      if (isTopLevelDeclarationStatement(node) && hasSyntacticModifier(node, 32 /* Export */)) {
        forEachTopLevelDeclaration(node, (declaration) => {
          var _a2;
          const targetDeclarations = canHaveSymbol(declaration) ? (_a2 = targetExports.get(declaration.symbol.escapedName)) == null ? void 0 : _a2.declarations : void 0;
          const exportDeclaration = firstDefined(targetDeclarations, (d) => isExportDeclaration(d) ? d : isExportSpecifier(d) ? tryCast(d.parent.parent, isExportDeclaration) : void 0);
          if (exportDeclaration && exportDeclaration.moduleSpecifier) {
            targetToSourceExports.set(exportDeclaration, (targetToSourceExports.get(exportDeclaration) || /* @__PURE__ */ new Set()).add(declaration));
          }
        });
      }
    }
    for (const [exportDeclaration, topLevelDeclarations] of arrayFrom(targetToSourceExports)) {
      if (exportDeclaration.exportClause && isNamedExports(exportDeclaration.exportClause) && length(exportDeclaration.exportClause.elements)) {
        const elements = exportDeclaration.exportClause.elements;
        const updatedElements = filter(elements, (elem) => find(skipAlias(elem.symbol, checker).declarations, (d) => isTopLevelDeclaration(d) && topLevelDeclarations.has(d)) === void 0);
        if (length(updatedElements) === 0) {
          changes.deleteNode(targetFile, exportDeclaration);
          removedExports.add(exportDeclaration);
          continue;
        }
        if (length(updatedElements) < length(elements)) {
          changes.replaceNode(targetFile, exportDeclaration, factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, exportDeclaration.isTypeOnly, factory.updateNamedExports(exportDeclaration.exportClause, factory.createNodeArray(updatedElements, elements.hasTrailingComma)), exportDeclaration.moduleSpecifier, exportDeclaration.attributes));
        }
      }
    }
  }
  const lastReExport = findLast(targetFile.statements, (n) => isExportDeclaration(n) && !!n.moduleSpecifier && !removedExports.has(n));
  if (lastReExport) {
    changes.insertNodesBefore(
      targetFile,
      lastReExport,
      statements,
      /*blankLineBetween*/
      true
    );
  } else {
    changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], statements);
  }
}
function getOverloadRangeToMove(sourceFile, statement) {
  if (isFunctionLikeDeclaration(statement)) {
    const declarations = statement.symbol.declarations;
    if (declarations === void 0 || length(declarations) <= 1 || !contains(declarations, statement)) {
      return void 0;
    }
    const firstDecl = declarations[0];
    const lastDecl = declarations[length(declarations) - 1];
    const statementsToMove = mapDefined(declarations, (d) => getSourceFileOfNode(d) === sourceFile && isStatement(d) ? d : void 0);
    const end = findIndex(sourceFile.statements, (s) => s.end >= lastDecl.end);
    const start = findIndex(sourceFile.statements, (s) => s.end >= firstDecl.end);
    return { toMove: statementsToMove, start, end };
  }
  return void 0;
}
function getExistingLocals(sourceFile, statements, checker) {
  const existingLocals = /* @__PURE__ */ new Set();
  for (const moduleSpecifier of sourceFile.imports) {
    const declaration = importFromModuleSpecifier(moduleSpecifier);
    if (isImportDeclaration(declaration) && declaration.importClause && declaration.importClause.namedBindings && isNamedImports(declaration.importClause.namedBindings)) {
      for (const e of declaration.importClause.namedBindings.elements) {
        const symbol = checker.getSymbolAtLocation(e.propertyName || e.name);
        if (symbol) {
          existingLocals.add(skipAlias(symbol, checker));
        }
      }
    }
    if (isVariableDeclarationInitializedToRequire(declaration.parent) && isObjectBindingPattern(declaration.parent.name)) {
      for (const e of declaration.parent.name.elements) {
        const symbol = checker.getSymbolAtLocation(e.propertyName || e.name);
        if (symbol) {
          existingLocals.add(skipAlias(symbol, checker));
        }
      }
    }
  }
  for (const statement of statements) {
    forEachReference(
      statement,
      checker,
      /*enclosingRange*/
      void 0,
      (s) => {
        const symbol = skipAlias(s, checker);
        if (symbol.valueDeclaration && getSourceFileOfNode(symbol.valueDeclaration).path === sourceFile.path) {
          existingLocals.add(symbol);
        }
      }
    );
  }
  return existingLocals;
}

// src/services/refactors/helpers.ts
function isRefactorErrorInfo(info) {
  return info.error !== void 0;
}
function refactorKindBeginsWith(known, requested) {
  if (!requested) return true;
  return known.substr(0, requested.length) === requested;
}
function getIdentifierForNode(node, scope, checker, file) {
  return isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName(
    node.name.text,
    node,
    111551 /* Value */,
    /*excludeGlobals*/
    false
  ) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file);
}
function addTargetFileImports(oldFile, importsToCopy, targetFileImportsFromOldFile, checker, program, importAdder) {
  importsToCopy.forEach(([isValidTypeOnlyUseSite, declaration], symbol) => {
    var _a;
    const targetSymbol = skipAlias(symbol, checker);
    if (checker.isUnknownSymbol(targetSymbol)) {
      importAdder.addVerbatimImport(Debug.checkDefined(declaration ?? findAncestor((_a = symbol.declarations) == null ? void 0 : _a[0], isAnyImportOrRequireStatement)));
    } else if (targetSymbol.parent === void 0) {
      Debug.assert(declaration !== void 0, "expected module symbol to have a declaration");
      importAdder.addImportForModuleSymbol(symbol, isValidTypeOnlyUseSite, declaration);
    } else {
      importAdder.addImportFromExportedSymbol(targetSymbol, isValidTypeOnlyUseSite, declaration);
    }
  });
  addImportsForMovedSymbols(targetFileImportsFromOldFile, oldFile.fileName, importAdder, program);
}

// src/services/refactors/inlineVariable.ts
var refactorName4 = "Inline variable";
var refactorDescription = getLocaleSpecificMessage(Diagnostics.Inline_variable);
var inlineVariableAction = {
  name: refactorName4,
  description: refactorDescription,
  kind: "refactor.inline.variable"
};
registerRefactor(refactorName4, {
  kinds: [inlineVariableAction.kind],
  getAvailableActions(context) {
    const {
      file,
      program,
      preferences,
      startPosition,
      triggerReason
    } = context;
    const info = getInliningInfo(file, startPosition, triggerReason === "invoked", program);
    if (!info) {
      return emptyArray;
    }
    if (!ts_refactor_exports.isRefactorErrorInfo(info)) {
      return [{
        name: refactorName4,
        description: refactorDescription,
        actions: [inlineVariableAction]
      }];
    }
    if (preferences.provideRefactorNotApplicableReason) {
      return [{
        name: refactorName4,
        description: refactorDescription,
        actions: [{
          ...inlineVariableAction,
          notApplicableReason: info.error
        }]
      }];
    }
    return emptyArray;
  },
  getEditsForAction(context, actionName2) {
    Debug.assert(actionName2 === refactorName4, "Unexpected refactor invoked");
    const { file, program, startPosition } = context;
    const info = getInliningInfo(
      file,
      startPosition,
      /*tryWithReferenceToken*/
      true,
      program
    );
    if (!info || ts_refactor_exports.isRefactorErrorInfo(info)) {
      return void 0;
    }
    const { references, declaration, replacement } = info;
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => {
      for (const node of references) {
        const closestStringIdentifierParent = isStringLiteral(replacement) && isIdentifier(node) && walkUpParenthesizedExpressions(node.parent);
        if (closestStringIdentifierParent && isTemplateSpan(closestStringIdentifierParent) && !isTaggedTemplateExpression(closestStringIdentifierParent.parent.parent)) {
          replaceTemplateStringVariableWithLiteral(tracker, file, closestStringIdentifierParent, replacement);
        } else {
          tracker.replaceNode(file, node, getReplacementExpression(node, replacement));
        }
      }
      tracker.delete(file, declaration);
    });
    return { edits };
  }
});
function getInliningInfo(file, startPosition, tryWithReferenceToken, program) {
  var _a, _b;
  const checker = program.getTypeChecker();
  const token = getTouchingPropertyName(file, startPosition);
  const parent2 = token.parent;
  if (!isIdentifier(token)) {
    return void 0;
  }
  if (isInitializedVariable(parent2) && isVariableDeclarationInVariableStatement(parent2) && isIdentifier(parent2.name)) {
    if (((_a = checker.getMergedSymbol(parent2.symbol).declarations) == null ? void 0 : _a.length) !== 1) {
      return { error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) };
    }
    if (isDeclarationExported(parent2)) {
      return void 0;
    }
    const references = getReferenceNodes(parent2, checker, file);
    return references && { references, declaration: parent2, replacement: parent2.initializer };
  }
  if (tryWithReferenceToken) {
    let definition = checker.resolveName(
      token.text,
      token,
      111551 /* Value */,
      /*excludeGlobals*/
      false
    );
    definition = definition && checker.getMergedSymbol(definition);
    if (((_b = definition == null ? void 0 : definition.declarations) == null ? void 0 : _b.length) !== 1) {
      return { error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) };
    }
    const declaration = definition.declarations[0];
    if (!isInitializedVariable(declaration) || !isVariableDeclarationInVariableStatement(declaration) || !isIdentifier(declaration.name)) {
      return void 0;
    }
    if (isDeclarationExported(declaration)) {
      return void 0;
    }
    const references = getReferenceNodes(declaration, checker, file);
    return references && { references, declaration, replacement: declaration.initializer };
  }
  return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_variable_to_inline) };
}
function isDeclarationExported(declaration) {
  const variableStatement = cast(declaration.parent.parent, isVariableStatement);
  return some(variableStatement.modifiers, isExportModifier);
}
function getReferenceNodes(declaration, checker, file) {
  const references = [];
  const cannotInline = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(declaration.name, checker, file, (ref) => {
    if (ts_FindAllReferences_exports.isWriteAccessForReference(ref) && !isShorthandPropertyAssignment(ref.parent)) {
      return true;
    }
    if (isExportSpecifier(ref.parent) || isExportAssignment(ref.parent)) {
      return true;
    }
    if (isTypeQueryNode(ref.parent)) {
      return true;
    }
    if (textRangeContainsPositionInclusive(declaration, ref.pos)) {
      return true;
    }
    references.push(ref);
  });
  return references.length === 0 || cannotInline ? void 0 : references;
}
function getReplacementExpression(reference, replacement) {
  replacement = getSynthesizedDeepClone(replacement);
  const { parent: parent2 } = reference;
  if (isExpression(parent2) && (getExpressionPrecedence(replacement) < getExpressionPrecedence(parent2) || needsParentheses(parent2))) {
    return factory.createParenthesizedExpression(replacement);
  }
  if (isFunctionLike(replacement) && (isCallLikeExpression(parent2) || isPropertyAccessExpression(parent2))) {
    return factory.createParenthesizedExpression(replacement);
  }
  if (isPropertyAccessExpression(parent2) && (isNumericLiteral(replacement) || isObjectLiteralExpression(replacement))) {
    return factory.createParenthesizedExpression(replacement);
  }
  if (isIdentifier(reference) && isShorthandPropertyAssignment(parent2)) {
    return factory.createPropertyAssignment(reference, replacement);
  }
  return replacement;
}
function replaceTemplateStringVariableWithLiteral(tracker, sourceFile, reference, replacement) {
  const templateExpression = reference.parent;
  const index = templateExpression.templateSpans.indexOf(reference);
  const prevNode = index === 0 ? templateExpression.head : templateExpression.templateSpans[index - 1];
  tracker.replaceRangeWithText(
    sourceFile,
    {
      pos: prevNode.getEnd() - 2,
      end: reference.literal.getStart() + 1
    },
    replacement.text.replace(/\\/g, "\\\\").replace(/`/g, "\\`")
  );
}

// src/services/refactors/moveToNewFile.ts
var refactorName5 = "Move to a new file";
var description2 = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file);
var moveToNewFileAction = {
  name: refactorName5,
  description: description2,
  kind: "refactor.move.newFile"
};
registerRefactor(refactorName5, {
  kinds: [moveToNewFileAction.kind],
  getAvailableActions: function getRefactorActionsToMoveToNewFile(context) {
    const statements = getStatementsToMove(context);
    const file = context.file;
    if (context.triggerReason === "implicit" && context.endPosition !== void 0) {
      const startNodeAncestor = findAncestor(getTokenAtPosition(file, context.startPosition), isBlockLike);
      const endNodeAncestor = findAncestor(getTokenAtPosition(file, context.endPosition), isBlockLike);
      if (startNodeAncestor && !isSourceFile(startNodeAncestor) && endNodeAncestor && !isSourceFile(endNodeAncestor)) {
        return emptyArray;
      }
    }
    if (context.preferences.allowTextChangesInNewFiles && statements) {
      const file2 = context.file;
      const affectedTextRange = {
        start: { line: getLineAndCharacterOfPosition(file2, statements.all[0].getStart(file2)).line, offset: getLineAndCharacterOfPosition(file2, statements.all[0].getStart(file2)).character },
        end: { line: getLineAndCharacterOfPosition(file2, last(statements.all).end).line, offset: getLineAndCharacterOfPosition(file2, last(statements.all).end).character }
      };
      return [{ name: refactorName5, description: description2, actions: [{ ...moveToNewFileAction, range: affectedTextRange }] }];
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return [{ name: refactorName5, description: description2, actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] }];
    }
    return emptyArray;
  },
  getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) {
    Debug.assert(actionName2 === refactorName5, "Wrong refactor invoked");
    const statements = Debug.checkDefined(getStatementsToMove(context));
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context.file, context.program, statements, t, context.host, context, context.preferences));
    return { edits, renameFilename: void 0, renameLocation: void 0 };
  }
});
function doChange4(oldFile, program, toMove, changes, host, context, preferences) {
  const checker = program.getTypeChecker();
  const usage = getUsageInfo(oldFile, toMove.all, checker);
  const newFilename = createNewFileName(oldFile, program, host, toMove);
  const newSourceFile = createFutureSourceFile(newFilename, oldFile.externalModuleIndicator ? 99 /* ESNext */ : oldFile.commonJsModuleIndicator ? 1 /* CommonJS */ : void 0, program, host);
  const importAdderForOldFile = ts_codefix_exports.createImportAdder(oldFile, context.program, context.preferences, context.host);
  const importAdderForNewFile = ts_codefix_exports.createImportAdder(newSourceFile, context.program, context.preferences, context.host);
  getNewStatementsAndRemoveFromOldFile(oldFile, newSourceFile, usage, changes, toMove, program, host, preferences, importAdderForNewFile, importAdderForOldFile);
  addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host));
}

// src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts
var ts_refactor_addOrRemoveBracesToArrowFunction_exports = {};

// src/services/refactors/convertOverloadListToSingleSignature.ts
var refactorName6 = "Convert overload list to single signature";
var refactorDescription2 = getLocaleSpecificMessage(Diagnostics.Convert_overload_list_to_single_signature);
var functionOverloadAction = {
  name: refactorName6,
  description: refactorDescription2,
  kind: "refactor.rewrite.function.overloadList"
};
registerRefactor(refactorName6, {
  kinds: [functionOverloadAction.kind],
  getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature,
  getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature
});
function getRefactorActionsToConvertOverloadsToOneSignature(context) {
  const { file, startPosition, program } = context;
  const info = getConvertableOverloadListAtPosition(file, startPosition, program);
  if (!info) return emptyArray;
  return [{
    name: refactorName6,
    description: refactorDescription2,
    actions: [functionOverloadAction]
  }];
}
function getRefactorEditsToConvertOverloadsToOneSignature(context) {
  const { file, startPosition, program } = context;
  const signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program);
  if (!signatureDecls) return void 0;
  const checker = program.getTypeChecker();
  const lastDeclaration = signatureDecls[signatureDecls.length - 1];
  let updated = lastDeclaration;
  switch (lastDeclaration.kind) {
    case 173 /* MethodSignature */: {
      updated = factory.updateMethodSignature(
        lastDeclaration,
        lastDeclaration.modifiers,
        lastDeclaration.name,
        lastDeclaration.questionToken,
        lastDeclaration.typeParameters,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.type
      );
      break;
    }
    case 174 /* MethodDeclaration */: {
      updated = factory.updateMethodDeclaration(
        lastDeclaration,
        lastDeclaration.modifiers,
        lastDeclaration.asteriskToken,
        lastDeclaration.name,
        lastDeclaration.questionToken,
        lastDeclaration.typeParameters,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.type,
        lastDeclaration.body
      );
      break;
    }
    case 179 /* CallSignature */: {
      updated = factory.updateCallSignature(
        lastDeclaration,
        lastDeclaration.typeParameters,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.type
      );
      break;
    }
    case 176 /* Constructor */: {
      updated = factory.updateConstructorDeclaration(
        lastDeclaration,
        lastDeclaration.modifiers,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.body
      );
      break;
    }
    case 180 /* ConstructSignature */: {
      updated = factory.updateConstructSignature(
        lastDeclaration,
        lastDeclaration.typeParameters,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.type
      );
      break;
    }
    case 262 /* FunctionDeclaration */: {
      updated = factory.updateFunctionDeclaration(
        lastDeclaration,
        lastDeclaration.modifiers,
        lastDeclaration.asteriskToken,
        lastDeclaration.name,
        lastDeclaration.typeParameters,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.type,
        lastDeclaration.body
      );
      break;
    }
    default:
      return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring");
  }
  if (updated === lastDeclaration) {
    return;
  }
  const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => {
    t.replaceNodeRange(file, signatureDecls[0], signatureDecls[signatureDecls.length - 1], updated);
  });
  return { renameFilename: void 0, renameLocation: void 0, edits };
  function getNewParametersForCombinedSignature(signatureDeclarations) {
    const lastSig = signatureDeclarations[signatureDeclarations.length - 1];
    if (isFunctionLikeDeclaration(lastSig) && lastSig.body) {
      signatureDeclarations = signatureDeclarations.slice(0, signatureDeclarations.length - 1);
    }
    return factory.createNodeArray([
      factory.createParameterDeclaration(
        /*modifiers*/
        void 0,
        factory.createToken(26 /* DotDotDotToken */),
        "args",
        /*questionToken*/
        void 0,
        factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple))
      )
    ]);
  }
  function convertSignatureParametersToTuple(decl) {
    const members = map(decl.parameters, convertParameterToNamedTupleMember);
    return setEmitFlags(factory.createTupleTypeNode(members), some(members, (m) => !!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */);
  }
  function convertParameterToNamedTupleMember(p) {
    Debug.assert(isIdentifier(p.name));
    const result = setTextRange(
      factory.createNamedTupleMember(
        p.dotDotDotToken,
        p.name,
        p.questionToken,
        p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */)
      ),
      p
    );
    const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker);
    if (parameterDocComment) {
      const newComment = displayPartsToString(parameterDocComment);
      if (newComment.length) {
        setSyntheticLeadingComments(result, [{
          text: `*
${newComment.split("\n").map((c) => ` * ${c}`).join("\n")}
 `,
          kind: 3 /* MultiLineCommentTrivia */,
          pos: -1,
          end: -1,
          hasTrailingNewLine: true,
          hasLeadingNewline: true
        }]);
      }
    }
    return result;
  }
}
function isConvertableSignatureDeclaration(d) {
  switch (d.kind) {
    case 173 /* MethodSignature */:
    case 174 /* MethodDeclaration */:
    case 179 /* CallSignature */:
    case 176 /* Constructor */:
    case 180 /* ConstructSignature */:
    case 262 /* FunctionDeclaration */:
      return true;
  }
  return false;
}
function getConvertableOverloadListAtPosition(file, startPosition, program) {
  const node = getTokenAtPosition(file, startPosition);
  const containingDecl = findAncestor(node, isConvertableSignatureDeclaration);
  if (!containingDecl) {
    return;
  }
  if (isFunctionLikeDeclaration(containingDecl) && containingDecl.body && rangeContainsPosition(containingDecl.body, startPosition)) {
    return;
  }
  const checker = program.getTypeChecker();
  const signatureSymbol = containingDecl.symbol;
  if (!signatureSymbol) {
    return;
  }
  const decls = signatureSymbol.declarations;
  if (length(decls) <= 1) {
    return;
  }
  if (!every(decls, (d) => getSourceFileOfNode(d) === file)) {
    return;
  }
  if (!isConvertableSignatureDeclaration(decls[0])) {
    return;
  }
  const kindOne = decls[0].kind;
  if (!every(decls, (d) => d.kind === kindOne)) {
    return;
  }
  const signatureDecls = decls;
  if (some(signatureDecls, (d) => !!d.typeParameters || some(d.parameters, (p) => !!p.modifiers || !isIdentifier(p.name)))) {
    return;
  }
  const signatures = mapDefined(signatureDecls, (d) => checker.getSignatureFromDeclaration(d));
  if (length(signatures) !== length(decls)) {
    return;
  }
  const returnOne = checker.getReturnTypeOfSignature(signatures[0]);
  if (!every(signatures, (s) => checker.getReturnTypeOfSignature(s) === returnOne)) {
    return;
  }
  return signatureDecls;
}

// src/services/refactors/addOrRemoveBracesToArrowFunction.ts
var refactorName7 = "Add or remove braces in an arrow function";
var refactorDescription3 = getLocaleSpecificMessage(Diagnostics.Add_or_remove_braces_in_an_arrow_function);
var addBracesAction = {
  name: "Add braces to arrow function",
  description: getLocaleSpecificMessage(Diagnostics.Add_braces_to_arrow_function),
  kind: "refactor.rewrite.arrow.braces.add"
};
var removeBracesAction = {
  name: "Remove braces from arrow function",
  description: getLocaleSpecificMessage(Diagnostics.Remove_braces_from_arrow_function),
  kind: "refactor.rewrite.arrow.braces.remove"
};
registerRefactor(refactorName7, {
  kinds: [removeBracesAction.kind],
  getEditsForAction: getRefactorEditsToRemoveFunctionBraces,
  getAvailableActions: getRefactorActionsToRemoveFunctionBraces
});
function getRefactorActionsToRemoveFunctionBraces(context) {
  const { file, startPosition, triggerReason } = context;
  const info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked");
  if (!info) return emptyArray;
  if (!isRefactorErrorInfo(info)) {
    return [{
      name: refactorName7,
      description: refactorDescription3,
      actions: [
        info.addBraces ? addBracesAction : removeBracesAction
      ]
    }];
  }
  if (context.preferences.provideRefactorNotApplicableReason) {
    return [{
      name: refactorName7,
      description: refactorDescription3,
      actions: [
        { ...addBracesAction, notApplicableReason: info.error },
        { ...removeBracesAction, notApplicableReason: info.error }
      ]
    }];
  }
  return emptyArray;
}
function getRefactorEditsToRemoveFunctionBraces(context, actionName2) {
  const { file, startPosition } = context;
  const info = getConvertibleArrowFunctionAtPosition(file, startPosition);
  Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info");
  const { expression, returnStatement, func } = info;
  let body;
  if (actionName2 === addBracesAction.name) {
    const returnStatement2 = factory.createReturnStatement(expression);
    body = factory.createBlock(
      [returnStatement2],
      /*multiLine*/
      true
    );
    copyLeadingComments(
      expression,
      returnStatement2,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      true
    );
  } else if (actionName2 === removeBracesAction.name && returnStatement) {
    const actualExpression = expression || factory.createVoidZero();
    body = needsParentheses(actualExpression) ? factory.createParenthesizedExpression(actualExpression) : actualExpression;
    copyTrailingAsLeadingComments(
      returnStatement,
      body,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      false
    );
    copyLeadingComments(
      returnStatement,
      body,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      false
    );
    copyTrailingComments(
      returnStatement,
      body,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      false
    );
  } else {
    Debug.fail("invalid action");
  }
  const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => {
    t.replaceNode(file, func.body, body);
  });
  return { renameFilename: void 0, renameLocation: void 0, edits };
}
function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies = true, kind) {
  const node = getTokenAtPosition(file, startPosition);
  const func = getContainingFunction(node);
  if (!func) {
    return {
      error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function)
    };
  }
  if (!isArrowFunction(func)) {
    return {
      error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function)
    };
  }
  if (!rangeContainsRange(func, node) || rangeContainsRange(func.body, node) && !considerFunctionBodies) {
    return void 0;
  }
  if (refactorKindBeginsWith(addBracesAction.kind, kind) && isExpression(func.body)) {
    return { func, addBraces: true, expression: func.body };
  } else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) {
    const firstStatement = first(func.body.statements);
    if (isReturnStatement(firstStatement)) {
      const expression = firstStatement.expression && isObjectLiteralExpression(getLeftmostExpression(
        firstStatement.expression,
        /*stopAtCallExpressions*/
        false
      )) ? factory.createParenthesizedExpression(firstStatement.expression) : firstStatement.expression;
      return { func, addBraces: false, expression, returnStatement: firstStatement };
    }
  }
  return void 0;
}

// src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts
var ts_refactor_convertArrowFunctionOrFunctionExpression_exports = {};

// src/services/refactors/convertArrowFunctionOrFunctionExpression.ts
var refactorName8 = "Convert arrow function or function expression";
var refactorDescription4 = getLocaleSpecificMessage(Diagnostics.Convert_arrow_function_or_function_expression);
var toAnonymousFunctionAction = {
  name: "Convert to anonymous function",
  description: getLocaleSpecificMessage(Diagnostics.Convert_to_anonymous_function),
  kind: "refactor.rewrite.function.anonymous"
};
var toNamedFunctionAction = {
  name: "Convert to named function",
  description: getLocaleSpecificMessage(Diagnostics.Convert_to_named_function),
  kind: "refactor.rewrite.function.named"
};
var toArrowFunctionAction = {
  name: "Convert to arrow function",
  description: getLocaleSpecificMessage(Diagnostics.Convert_to_arrow_function),
  kind: "refactor.rewrite.function.arrow"
};
registerRefactor(refactorName8, {
  kinds: [
    toAnonymousFunctionAction.kind,
    toNamedFunctionAction.kind,
    toArrowFunctionAction.kind
  ],
  getEditsForAction: getRefactorEditsToConvertFunctionExpressions,
  getAvailableActions: getRefactorActionsToConvertFunctionExpressions
});
function getRefactorActionsToConvertFunctionExpressions(context) {
  const { file, startPosition, program, kind } = context;
  const info = getFunctionInfo(file, startPosition, program);
  if (!info) return emptyArray;
  const { selectedVariableDeclaration, func } = info;
  const possibleActions = [];
  const errors = [];
  if (refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) {
    const error2 = selectedVariableDeclaration || isArrowFunction(func) && isVariableDeclaration(func.parent) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_named_function);
    if (error2) {
      errors.push({ ...toNamedFunctionAction, notApplicableReason: error2 });
    } else {
      possibleActions.push(toNamedFunctionAction);
    }
  }
  if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) {
    const error2 = !selectedVariableDeclaration && isArrowFunction(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function);
    if (error2) {
      errors.push({ ...toAnonymousFunctionAction, notApplicableReason: error2 });
    } else {
      possibleActions.push(toAnonymousFunctionAction);
    }
  }
  if (refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) {
    const error2 = isFunctionExpression(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_arrow_function);
    if (error2) {
      errors.push({ ...toArrowFunctionAction, notApplicableReason: error2 });
    } else {
      possibleActions.push(toArrowFunctionAction);
    }
  }
  return [{
    name: refactorName8,
    description: refactorDescription4,
    actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ? errors : possibleActions
  }];
}
function getRefactorEditsToConvertFunctionExpressions(context, actionName2) {
  const { file, startPosition, program } = context;
  const info = getFunctionInfo(file, startPosition, program);
  if (!info) return void 0;
  const { func } = info;
  const edits = [];
  switch (actionName2) {
    case toAnonymousFunctionAction.name:
      edits.push(...getEditInfoForConvertToAnonymousFunction(context, func));
      break;
    case toNamedFunctionAction.name:
      const variableInfo = getVariableInfo(func);
      if (!variableInfo) return void 0;
      edits.push(...getEditInfoForConvertToNamedFunction(context, func, variableInfo));
      break;
    case toArrowFunctionAction.name:
      if (!isFunctionExpression(func)) return void 0;
      edits.push(...getEditInfoForConvertToArrowFunction(context, func));
      break;
    default:
      return Debug.fail("invalid action");
  }
  return { renameFilename: void 0, renameLocation: void 0, edits };
}
function containingThis(node) {
  let containsThis = false;
  node.forEachChild(function checkThis(child) {
    if (isThis(child)) {
      containsThis = true;
      return;
    }
    if (!isClassLike(child) && !isFunctionDeclaration(child) && !isFunctionExpression(child)) {
      forEachChild(child, checkThis);
    }
  });
  return containsThis;
}
function getFunctionInfo(file, startPosition, program) {
  const token = getTokenAtPosition(file, startPosition);
  const typeChecker = program.getTypeChecker();
  const func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent);
  if (func && !containingThis(func.body) && !typeChecker.containsArgumentsReference(func)) {
    return { selectedVariableDeclaration: true, func };
  }
  const maybeFunc = getContainingFunction(token);
  if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) {
    if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) return void 0;
    return { selectedVariableDeclaration: false, func: maybeFunc };
  }
  return void 0;
}
function isSingleVariableDeclaration(parent2) {
  return isVariableDeclaration(parent2) || isVariableDeclarationList(parent2) && parent2.declarations.length === 1;
}
function tryGetFunctionFromVariableDeclaration(sourceFile, typeChecker, parent2) {
  if (!isSingleVariableDeclaration(parent2)) {
    return void 0;
  }
  const variableDeclaration = isVariableDeclaration(parent2) ? parent2 : first(parent2.declarations);
  const initializer = variableDeclaration.initializer;
  if (initializer && (isArrowFunction(initializer) || isFunctionExpression(initializer) && !isFunctionReferencedInFile(sourceFile, typeChecker, initializer))) {
    return initializer;
  }
  return void 0;
}
function convertToBlock(body) {
  if (isExpression(body)) {
    const returnStatement = factory.createReturnStatement(body);
    const file = body.getSourceFile();
    setTextRange(returnStatement, body);
    suppressLeadingAndTrailingTrivia(returnStatement);
    copyTrailingAsLeadingComments(
      body,
      returnStatement,
      file,
      /*commentKind*/
      void 0,
      /*hasTrailingNewLine*/
      true
    );
    return factory.createBlock(
      [returnStatement],
      /*multiLine*/
      true
    );
  } else {
    return body;
  }
}
function getVariableInfo(func) {
  const variableDeclaration = func.parent;
  if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) return void 0;
  const variableDeclarationList = variableDeclaration.parent;
  const statement = variableDeclarationList.parent;
  if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) return void 0;
  return { variableDeclaration, variableDeclarationList, statement, name: variableDeclaration.name };
}
function getEditInfoForConvertToAnonymousFunction(context, func) {
  const { file } = context;
  const body = convertToBlock(func.body);
  const newNode = factory.createFunctionExpression(
    func.modifiers,
    func.asteriskToken,
    /*name*/
    void 0,
    func.typeParameters,
    func.parameters,
    func.type,
    body
  );
  return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode));
}
function getEditInfoForConvertToNamedFunction(context, func, variableInfo) {
  const { file } = context;
  const body = convertToBlock(func.body);
  const { variableDeclaration, variableDeclarationList, statement, name } = variableInfo;
  suppressLeadingTrivia(statement);
  const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 32 /* Export */ | getEffectiveModifierFlags(func);
  const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags);
  const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body);
  if (variableDeclarationList.declarations.length === 1) {
    return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, statement, newNode));
  } else {
    return ts_textChanges_exports.ChangeTracker.with(context, (t) => {
      t.delete(file, variableDeclaration);
      t.insertNodeAfter(file, statement, newNode);
    });
  }
}
function getEditInfoForConvertToArrowFunction(context, func) {
  const { file } = context;
  const statements = func.body.statements;
  const head = statements[0];
  let body;
  if (canBeConvertedToExpression(func.body, head)) {
    body = head.expression;
    suppressLeadingAndTrailingTrivia(body);
    copyComments(head, body);
  } else {
    body = func.body;
  }
  const newNode = factory.createArrowFunction(func.modifiers, func.typeParameters, func.parameters, func.type, factory.createToken(39 /* EqualsGreaterThanToken */), body);
  return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode));
}
function canBeConvertedToExpression(body, head) {
  return body.statements.length === 1 && (isReturnStatement(head) && !!head.expression);
}
function isFunctionReferencedInFile(sourceFile, typeChecker, node) {
  return !!node.name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile);
}

// src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts
var ts_refactor_convertParamsToDestructuredObject_exports = {};

// src/services/refactors/convertParamsToDestructuredObject.ts
var refactorName9 = "Convert parameters to destructured object";
var minimumParameterLength = 1;
var refactorDescription5 = getLocaleSpecificMessage(Diagnostics.Convert_parameters_to_destructured_object);
var toDestructuredAction = {
  name: refactorName9,
  description: refactorDescription5,
  kind: "refactor.rewrite.parameters.toDestructured"
};
registerRefactor(refactorName9, {
  kinds: [toDestructuredAction.kind],
  getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject,
  getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject
});
function getRefactorActionsToConvertParametersToDestructuredObject(context) {
  const { file, startPosition } = context;
  const isJSFile = isSourceFileJS(file);
  if (isJSFile) return emptyArray;
  const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
  if (!functionDeclaration) return emptyArray;
  return [{
    name: refactorName9,
    description: refactorDescription5,
    actions: [toDestructuredAction]
  }];
}
function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName2) {
  Debug.assert(actionName2 === refactorName9, "Unexpected action name");
  const { file, startPosition, program, cancellationToken, host } = context;
  const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
  if (!functionDeclaration || !cancellationToken) return void 0;
  const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
  if (groupedReferences.valid) {
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange5(file, program, host, t, functionDeclaration, groupedReferences));
    return { renameFilename: void 0, renameLocation: void 0, edits };
  }
  return { edits: [] };
}
function doChange5(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
  const signature = groupedReferences.signature;
  const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), (param) => getSynthesizedDeepClone(param));
  if (signature) {
    const newSignatureParams = map(createNewParameters(signature, program, host), (param) => getSynthesizedDeepClone(param));
    replaceParameters(signature, newSignatureParams);
  }
  replaceParameters(functionDeclaration, newFunctionDeclarationParams);
  const functionCalls = sortAndDeduplicate(
    groupedReferences.functionCalls,
    /*comparer*/
    (a, b) => compareValues(a.pos, b.pos)
  );
  for (const call of functionCalls) {
    if (call.arguments && call.arguments.length) {
      const newArgument = getSynthesizedDeepClone(
        createNewArgument(functionDeclaration, call.arguments),
        /*includeTrivia*/
        true
      );
      changes.replaceNodeRange(
        getSourceFileOfNode(call),
        first(call.arguments),
        last(call.arguments),
        newArgument,
        { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include }
      );
    }
  }
  function replaceParameters(declarationOrSignature, parameterDeclarations) {
    changes.replaceNodeRangeWithNodes(
      sourceFile,
      first(declarationOrSignature.parameters),
      last(declarationOrSignature.parameters),
      parameterDeclarations,
      {
        joiner: ", ",
        // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
        indentation: 0,
        leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll,
        trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include
      }
    );
  }
}
function getGroupedReferences(functionDeclaration, program, cancellationToken) {
  const functionNames = getFunctionNames(functionDeclaration);
  const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
  const names = deduplicate([...functionNames, ...classNames], equateValues);
  const checker = program.getTypeChecker();
  const references = flatMap(
    names,
    /*mapfn*/
    (name) => ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)
  );
  const groupedReferences = groupReferences(references);
  if (!every(
    groupedReferences.declarations,
    /*callback*/
    (decl) => contains(names, decl)
  )) {
    groupedReferences.valid = false;
  }
  return groupedReferences;
  function groupReferences(referenceEntries) {
    const classReferences = { accessExpressions: [], typeUsages: [] };
    const groupedReferences2 = { functionCalls: [], declarations: [], classReferences, valid: true };
    const functionSymbols = map(functionNames, getSymbolTargetAtLocation);
    const classSymbols = map(classNames, getSymbolTargetAtLocation);
    const isConstructor = isConstructorDeclaration(functionDeclaration);
    const contextualSymbols = map(functionNames, (name) => getSymbolForContextualType(name, checker));
    for (const entry of referenceEntries) {
      if (entry.kind === ts_FindAllReferences_exports.EntryKind.Span) {
        groupedReferences2.valid = false;
        continue;
      }
      if (contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) {
        if (isValidMethodSignature(entry.node.parent)) {
          groupedReferences2.signature = entry.node.parent;
          continue;
        }
        const call = entryToFunctionCall(entry);
        if (call) {
          groupedReferences2.functionCalls.push(call);
          continue;
        }
      }
      const contextualSymbol = getSymbolForContextualType(entry.node, checker);
      if (contextualSymbol && contains(contextualSymbols, contextualSymbol)) {
        const decl = entryToDeclaration(entry);
        if (decl) {
          groupedReferences2.declarations.push(decl);
          continue;
        }
      }
      if (contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || isNewExpressionTarget(entry.node)) {
        const importOrExportReference = entryToImportOrExport(entry);
        if (importOrExportReference) {
          continue;
        }
        const decl = entryToDeclaration(entry);
        if (decl) {
          groupedReferences2.declarations.push(decl);
          continue;
        }
        const call = entryToFunctionCall(entry);
        if (call) {
          groupedReferences2.functionCalls.push(call);
          continue;
        }
      }
      if (isConstructor && contains(classSymbols, getSymbolTargetAtLocation(entry.node))) {
        const importOrExportReference = entryToImportOrExport(entry);
        if (importOrExportReference) {
          continue;
        }
        const decl = entryToDeclaration(entry);
        if (decl) {
          groupedReferences2.declarations.push(decl);
          continue;
        }
        const accessExpression = entryToAccessExpression(entry);
        if (accessExpression) {
          classReferences.accessExpressions.push(accessExpression);
          continue;
        }
        if (isClassDeclaration(functionDeclaration.parent)) {
          const type = entryToType(entry);
          if (type) {
            classReferences.typeUsages.push(type);
            continue;
          }
        }
      }
      groupedReferences2.valid = false;
    }
    return groupedReferences2;
  }
  function getSymbolTargetAtLocation(node) {
    const symbol = checker.getSymbolAtLocation(node);
    return symbol && getSymbolTarget(symbol, checker);
  }
}
function getSymbolForContextualType(node, checker) {
  const element = getContainingObjectLiteralElement(node);
  if (element) {
    const contextualType = checker.getContextualTypeForObjectLiteralElement(element);
    const symbol = contextualType == null ? void 0 : contextualType.getSymbol();
    if (symbol && !(getCheckFlags(symbol) & 6 /* Synthetic */)) {
      return symbol;
    }
  }
}
function entryToImportOrExport(entry) {
  const node = entry.node;
  if (isImportSpecifier(node.parent) || isImportClause(node.parent) || isImportEqualsDeclaration(node.parent) || isNamespaceImport(node.parent)) {
    return node;
  }
  if (isExportSpecifier(node.parent) || isExportAssignment(node.parent)) {
    return node;
  }
  return void 0;
}
function entryToDeclaration(entry) {
  if (isDeclaration(entry.node.parent)) {
    return entry.node;
  }
  return void 0;
}
function entryToFunctionCall(entry) {
  if (entry.node.parent) {
    const functionReference = entry.node;
    const parent2 = functionReference.parent;
    switch (parent2.kind) {
      // foo(...) or super(...) or new Foo(...)
      case 213 /* CallExpression */:
      case 214 /* NewExpression */:
        const callOrNewExpression = tryCast(parent2, isCallOrNewExpression);
        if (callOrNewExpression && callOrNewExpression.expression === functionReference) {
          return callOrNewExpression;
        }
        break;
      // x.foo(...)
      case 211 /* PropertyAccessExpression */:
        const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression);
        if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
          const callOrNewExpression2 = tryCast(propertyAccessExpression.parent, isCallOrNewExpression);
          if (callOrNewExpression2 && callOrNewExpression2.expression === propertyAccessExpression) {
            return callOrNewExpression2;
          }
        }
        break;
      // x["foo"](...)
      case 212 /* ElementAccessExpression */:
        const elementAccessExpression = tryCast(parent2, isElementAccessExpression);
        if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
          const callOrNewExpression2 = tryCast(elementAccessExpression.parent, isCallOrNewExpression);
          if (callOrNewExpression2 && callOrNewExpression2.expression === elementAccessExpression) {
            return callOrNewExpression2;
          }
        }
        break;
    }
  }
  return void 0;
}
function entryToAccessExpression(entry) {
  if (entry.node.parent) {
    const reference = entry.node;
    const parent2 = reference.parent;
    switch (parent2.kind) {
      // `C.foo`
      case 211 /* PropertyAccessExpression */:
        const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression);
        if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
          return propertyAccessExpression;
        }
        break;
      // `C["foo"]`
      case 212 /* ElementAccessExpression */:
        const elementAccessExpression = tryCast(parent2, isElementAccessExpression);
        if (elementAccessExpression && elementAccessExpression.expression === reference) {
          return elementAccessExpression;
        }
        break;
    }
  }
  return void 0;
}
function entryToType(entry) {
  const reference = entry.node;
  if (getMeaningFromLocation(reference) === 2 /* Type */ || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
    return reference;
  }
  return void 0;
}
function getFunctionDeclarationAtPosition(file, startPosition, checker) {
  const node = getTouchingToken(file, startPosition);
  const functionDeclaration = getContainingFunctionDeclaration(node);
  if (isTopLevelJSDoc(node)) return void 0;
  if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) return functionDeclaration;
  return void 0;
}
function isTopLevelJSDoc(node) {
  const containingJSDoc = findAncestor(node, isJSDocNode);
  if (containingJSDoc) {
    const containingNonJSDoc = findAncestor(containingJSDoc, (n) => !isJSDocNode(n));
    return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc);
  }
  return false;
}
function isValidMethodSignature(node) {
  return isMethodSignature(node) && (isInterfaceDeclaration(node.parent) || isTypeLiteralNode(node.parent));
}
function isValidFunctionDeclaration(functionDeclaration, checker) {
  var _a;
  if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false;
  switch (functionDeclaration.kind) {
    case 262 /* FunctionDeclaration */:
      return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker);
    case 174 /* MethodDeclaration */:
      if (isObjectLiteralExpression(functionDeclaration.parent)) {
        const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker);
        return ((_a = contextualSymbol == null ? void 0 : contextualSymbol.declarations) == null ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker);
      }
      return isSingleImplementation(functionDeclaration, checker);
    case 176 /* Constructor */:
      if (isClassDeclaration(functionDeclaration.parent)) {
        return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker);
      } else {
        return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker);
      }
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
      return isValidVariableDeclaration(functionDeclaration.parent);
  }
  return false;
}
function isSingleImplementation(functionDeclaration, checker) {
  return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
}
function hasNameOrDefault(functionOrClassDeclaration) {
  if (!functionOrClassDeclaration.name) {
    const defaultKeyword = findModifier(functionOrClassDeclaration, 90 /* DefaultKeyword */);
    return !!defaultKeyword;
  }
  return true;
}
function isValidParameterNodeArray(parameters, checker) {
  return getRefactorableParametersLength(parameters) >= minimumParameterLength && every(
    parameters,
    /*callback*/
    (paramDecl) => isValidParameterDeclaration(paramDecl, checker)
  );
}
function isValidParameterDeclaration(parameterDeclaration, checker) {
  if (isRestParameter(parameterDeclaration)) {
    const type = checker.getTypeAtLocation(parameterDeclaration);
    if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false;
  }
  return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name);
}
function isValidVariableDeclaration(node) {
  return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type;
}
function hasThisParameter(parameters) {
  return parameters.length > 0 && isThis(parameters[0].name);
}
function getRefactorableParametersLength(parameters) {
  if (hasThisParameter(parameters)) {
    return parameters.length - 1;
  }
  return parameters.length;
}
function getRefactorableParameters(parameters) {
  if (hasThisParameter(parameters)) {
    parameters = factory.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
  }
  return parameters;
}
function createPropertyOrShorthandAssignment(name, initializer) {
  if (isIdentifier(initializer) && getTextOfIdentifierOrLiteral(initializer) === name) {
    return factory.createShorthandPropertyAssignment(name);
  }
  return factory.createPropertyAssignment(name, initializer);
}
function createNewArgument(functionDeclaration, functionArguments) {
  const parameters = getRefactorableParameters(functionDeclaration.parameters);
  const hasRestParameter2 = isRestParameter(last(parameters));
  const nonRestArguments = hasRestParameter2 ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
  const properties = map(nonRestArguments, (arg, i) => {
    const parameterName = getParameterName(parameters[i]);
    const property = createPropertyOrShorthandAssignment(parameterName, arg);
    suppressLeadingAndTrailingTrivia(property.name);
    if (isPropertyAssignment(property)) suppressLeadingAndTrailingTrivia(property.initializer);
    copyComments(arg, property);
    return property;
  });
  if (hasRestParameter2 && functionArguments.length >= parameters.length) {
    const restArguments = functionArguments.slice(parameters.length - 1);
    const restProperty = factory.createPropertyAssignment(getParameterName(last(parameters)), factory.createArrayLiteralExpression(restArguments));
    properties.push(restProperty);
  }
  const objectLiteral = factory.createObjectLiteralExpression(
    properties,
    /*multiLine*/
    false
  );
  return objectLiteral;
}
function createNewParameters(functionDeclaration, program, host) {
  const checker = program.getTypeChecker();
  const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
  const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration);
  const objectParameterName = factory.createObjectBindingPattern(bindingElements);
  const objectParameterType = createParameterTypeNode(refactorableParameters);
  let objectInitializer;
  if (every(refactorableParameters, isOptionalParameter)) {
    objectInitializer = factory.createObjectLiteralExpression();
  }
  const objectParameter = factory.createParameterDeclaration(
    /*modifiers*/
    void 0,
    /*dotDotDotToken*/
    void 0,
    objectParameterName,
    /*questionToken*/
    void 0,
    objectParameterType,
    objectInitializer
  );
  if (hasThisParameter(functionDeclaration.parameters)) {
    const thisParameter = functionDeclaration.parameters[0];
    const newThisParameter = factory.createParameterDeclaration(
      /*modifiers*/
      void 0,
      /*dotDotDotToken*/
      void 0,
      thisParameter.name,
      /*questionToken*/
      void 0,
      thisParameter.type
    );
    suppressLeadingAndTrailingTrivia(newThisParameter.name);
    copyComments(thisParameter.name, newThisParameter.name);
    if (thisParameter.type) {
      suppressLeadingAndTrailingTrivia(newThisParameter.type);
      copyComments(thisParameter.type, newThisParameter.type);
    }
    return factory.createNodeArray([newThisParameter, objectParameter]);
  }
  return factory.createNodeArray([objectParameter]);
  function createBindingElementFromParameterDeclaration(parameterDeclaration) {
    const element = factory.createBindingElement(
      /*dotDotDotToken*/
      void 0,
      /*propertyName*/
      void 0,
      getParameterName(parameterDeclaration),
      isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer
    );
    suppressLeadingAndTrailingTrivia(element);
    if (parameterDeclaration.initializer && element.initializer) {
      copyComments(parameterDeclaration.initializer, element.initializer);
    }
    return element;
  }
  function createParameterTypeNode(parameters) {
    const members = map(parameters, createPropertySignatureFromParameterDeclaration);
    const typeNode = addEmitFlags(factory.createTypeLiteralNode(members), 1 /* SingleLine */);
    return typeNode;
  }
  function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
    let parameterType = parameterDeclaration.type;
    if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) {
      parameterType = getTypeNode3(parameterDeclaration);
    }
    const propertySignature = factory.createPropertySignature(
      /*modifiers*/
      void 0,
      getParameterName(parameterDeclaration),
      isOptionalParameter(parameterDeclaration) ? factory.createToken(58 /* QuestionToken */) : parameterDeclaration.questionToken,
      parameterType
    );
    suppressLeadingAndTrailingTrivia(propertySignature);
    copyComments(parameterDeclaration.name, propertySignature.name);
    if (parameterDeclaration.type && propertySignature.type) {
      copyComments(parameterDeclaration.type, propertySignature.type);
    }
    return propertySignature;
  }
  function getTypeNode3(node) {
    const type = checker.getTypeAtLocation(node);
    return getTypeNodeIfAccessible(type, node, program, host);
  }
  function isOptionalParameter(parameterDeclaration) {
    if (isRestParameter(parameterDeclaration)) {
      const type = checker.getTypeAtLocation(parameterDeclaration);
      return !checker.isTupleType(type);
    }
    return checker.isOptionalParameter(parameterDeclaration);
  }
}
function getParameterName(paramDeclaration) {
  return getTextOfIdentifierOrLiteral(paramDeclaration.name);
}
function getClassNames(constructorDeclaration) {
  switch (constructorDeclaration.parent.kind) {
    case 263 /* ClassDeclaration */:
      const classDeclaration = constructorDeclaration.parent;
      if (classDeclaration.name) return [classDeclaration.name];
      const defaultModifier = Debug.checkDefined(
        findModifier(classDeclaration, 90 /* DefaultKeyword */),
        "Nameless class declaration should be a default export"
      );
      return [defaultModifier];
    case 231 /* ClassExpression */:
      const classExpression = constructorDeclaration.parent;
      const variableDeclaration = constructorDeclaration.parent.parent;
      const className = classExpression.name;
      if (className) return [className, variableDeclaration.name];
      return [variableDeclaration.name];
  }
}
function getFunctionNames(functionDeclaration) {
  switch (functionDeclaration.kind) {
    case 262 /* FunctionDeclaration */:
      if (functionDeclaration.name) return [functionDeclaration.name];
      const defaultModifier = Debug.checkDefined(
        findModifier(functionDeclaration, 90 /* DefaultKeyword */),
        "Nameless function declaration should be a default export"
      );
      return [defaultModifier];
    case 174 /* MethodDeclaration */:
      return [functionDeclaration.name];
    case 176 /* Constructor */:
      const ctrKeyword = Debug.checkDefined(
        findChildOfKind(functionDeclaration, 137 /* ConstructorKeyword */, functionDeclaration.getSourceFile()),
        "Constructor declaration should have constructor keyword"
      );
      if (functionDeclaration.parent.kind === 231 /* ClassExpression */) {
        const variableDeclaration = functionDeclaration.parent.parent;
        return [variableDeclaration.name, ctrKeyword];
      }
      return [ctrKeyword];
    case 219 /* ArrowFunction */:
      return [functionDeclaration.parent.name];
    case 218 /* FunctionExpression */:
      if (functionDeclaration.name) return [functionDeclaration.name, functionDeclaration.parent.name];
      return [functionDeclaration.parent.name];
    default:
      return Debug.assertNever(functionDeclaration, `Unexpected function declaration kind ${functionDeclaration.kind}`);
  }
}

// src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts
var ts_refactor_convertStringOrTemplateLiteral_exports = {};

// src/services/refactors/convertStringOrTemplateLiteral.ts
var refactorName10 = "Convert to template string";
var refactorDescription6 = getLocaleSpecificMessage(Diagnostics.Convert_to_template_string);
var convertStringAction = {
  name: refactorName10,
  description: refactorDescription6,
  kind: "refactor.rewrite.string"
};
registerRefactor(refactorName10, {
  kinds: [convertStringAction.kind],
  getEditsForAction: getRefactorEditsToConvertToTemplateString,
  getAvailableActions: getRefactorActionsToConvertToTemplateString
});
function getRefactorActionsToConvertToTemplateString(context) {
  const { file, startPosition } = context;
  const node = getNodeOrParentOfParentheses(file, startPosition);
  const maybeBinary = getParentBinaryExpression(node);
  const nodeIsStringLiteral = isStringLiteral(maybeBinary);
  const refactorInfo = { name: refactorName10, description: refactorDescription6, actions: [] };
  if (nodeIsStringLiteral && context.triggerReason !== "invoked") {
    return emptyArray;
  }
  if (isExpressionNode(maybeBinary) && (nodeIsStringLiteral || isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation)) {
    refactorInfo.actions.push(convertStringAction);
    return [refactorInfo];
  } else if (context.preferences.provideRefactorNotApplicableReason) {
    refactorInfo.actions.push({ ...convertStringAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenations_and_string_literals) });
    return [refactorInfo];
  }
  return emptyArray;
}
function getNodeOrParentOfParentheses(file, startPosition) {
  const node = getTokenAtPosition(file, startPosition);
  const nestedBinary = getParentBinaryExpression(node);
  const isNonStringBinary = !treeToArray(nestedBinary).isValidConcatenation;
  if (isNonStringBinary && isParenthesizedExpression(nestedBinary.parent) && isBinaryExpression(nestedBinary.parent.parent)) {
    return nestedBinary.parent.parent;
  }
  return node;
}
function getRefactorEditsToConvertToTemplateString(context, actionName2) {
  const { file, startPosition } = context;
  const node = getNodeOrParentOfParentheses(file, startPosition);
  switch (actionName2) {
    case refactorDescription6:
      return { edits: getEditsForToTemplateLiteral(context, node) };
    default:
      return Debug.fail("invalid action");
  }
}
function getEditsForToTemplateLiteral(context, node) {
  const maybeBinary = getParentBinaryExpression(node);
  const file = context.file;
  const templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file);
  const trailingCommentRanges = getTrailingCommentRanges(file.text, maybeBinary.end);
  if (trailingCommentRanges) {
    const lastComment = trailingCommentRanges[trailingCommentRanges.length - 1];
    const trailingRange = { pos: trailingCommentRanges[0].pos, end: lastComment.end };
    return ts_textChanges_exports.ChangeTracker.with(context, (t) => {
      t.deleteRange(file, trailingRange);
      t.replaceNode(file, maybeBinary, templateLiteral);
    });
  } else {
    return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, maybeBinary, templateLiteral));
  }
}
function isNotEqualsOperator(node) {
  return !(node.operatorToken.kind === 64 /* EqualsToken */ || node.operatorToken.kind === 65 /* PlusEqualsToken */);
}
function getParentBinaryExpression(expr) {
  const container = findAncestor(expr.parent, (n) => {
    switch (n.kind) {
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        return false;
      case 228 /* TemplateExpression */:
      case 226 /* BinaryExpression */:
        return !(isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent));
      default:
        return "quit";
    }
  });
  return container || expr;
}
function treeToArray(current) {
  const loop = (current2) => {
    if (!isBinaryExpression(current2)) {
      return { nodes: [current2], operators: [], validOperators: true, hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) };
    }
    const { nodes: nodes2, operators: operators2, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current2.left);
    if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) {
      return { nodes: [current2], operators: [], hasString: false, validOperators: true };
    }
    const currentOperatorValid = current2.operatorToken.kind === 40 /* PlusToken */;
    const validOperators2 = leftOperatorValid && currentOperatorValid;
    nodes2.push(current2.right);
    operators2.push(current2.operatorToken);
    return { nodes: nodes2, operators: operators2, hasString: true, validOperators: validOperators2 };
  };
  const { nodes, operators, validOperators, hasString } = loop(current);
  return { nodes, operators, isValidConcatenation: validOperators && hasString };
}
var copyTrailingOperatorComments = (operators, file) => (index, targetNode) => {
  if (index < operators.length) {
    copyTrailingComments(
      operators[index],
      targetNode,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      false
    );
  }
};
var copyCommentFromMultiNode = (nodes, file, copyOperatorComments) => (indexes, targetNode) => {
  while (indexes.length > 0) {
    const index = indexes.shift();
    copyTrailingComments(
      nodes[index],
      targetNode,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      false
    );
    copyOperatorComments(index, targetNode);
  }
};
function escapeRawStringForTemplate(s) {
  return s.replace(/\\.|[$`]/g, (m) => m[0] === "\\" ? m : "\\" + m);
}
function getRawTextOfTemplate(node) {
  const rightShaving = isTemplateHead(node) || isTemplateMiddle(node) ? -2 : -1;
  return getTextOfNode(node).slice(1, rightShaving);
}
function concatConsecutiveString(index, nodes) {
  const indexes = [];
  let text = "", rawText = "";
  while (index < nodes.length) {
    const node = nodes[index];
    if (isStringLiteralLike(node)) {
      text += node.text;
      rawText += escapeRawStringForTemplate(getTextOfNode(node).slice(1, -1));
      indexes.push(index);
      index++;
    } else if (isTemplateExpression(node)) {
      text += node.head.text;
      rawText += getRawTextOfTemplate(node.head);
      break;
    } else {
      break;
    }
  }
  return [index, text, rawText, indexes];
}
function nodesToTemplate({ nodes, operators }, file) {
  const copyOperatorComments = copyTrailingOperatorComments(operators, file);
  const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments);
  const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes);
  if (begin === nodes.length) {
    const noSubstitutionTemplateLiteral = factory.createNoSubstitutionTemplateLiteral(headText, rawHeadText);
    copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral);
    return noSubstitutionTemplateLiteral;
  }
  const templateSpans = [];
  const templateHead = factory.createTemplateHead(headText, rawHeadText);
  copyCommentFromStringLiterals(headIndexes, templateHead);
  for (let i = begin; i < nodes.length; i++) {
    const currentNode = getExpressionFromParenthesesOrExpression(nodes[i]);
    copyOperatorComments(i, currentNode);
    const [newIndex, subsequentText, rawSubsequentText, stringIndexes] = concatConsecutiveString(i + 1, nodes);
    i = newIndex - 1;
    const isLast = i === nodes.length - 1;
    if (isTemplateExpression(currentNode)) {
      const spans = map(currentNode.templateSpans, (span, index) => {
        copyExpressionComments(span);
        const isLastSpan = index === currentNode.templateSpans.length - 1;
        const text = span.literal.text + (isLastSpan ? subsequentText : "");
        const rawText = getRawTextOfTemplate(span.literal) + (isLastSpan ? rawSubsequentText : "");
        return factory.createTemplateSpan(
          span.expression,
          isLast && isLastSpan ? factory.createTemplateTail(text, rawText) : factory.createTemplateMiddle(text, rawText)
        );
      });
      templateSpans.push(...spans);
    } else {
      const templatePart = isLast ? factory.createTemplateTail(subsequentText, rawSubsequentText) : factory.createTemplateMiddle(subsequentText, rawSubsequentText);
      copyCommentFromStringLiterals(stringIndexes, templatePart);
      templateSpans.push(factory.createTemplateSpan(currentNode, templatePart));
    }
  }
  return factory.createTemplateExpression(templateHead, templateSpans);
}
function copyExpressionComments(node) {
  const file = node.getSourceFile();
  copyTrailingComments(
    node,
    node.expression,
    file,
    3 /* MultiLineCommentTrivia */,
    /*hasTrailingNewLine*/
    false
  );
  copyTrailingAsLeadingComments(
    node.expression,
    node.expression,
    file,
    3 /* MultiLineCommentTrivia */,
    /*hasTrailingNewLine*/
    false
  );
}
function getExpressionFromParenthesesOrExpression(node) {
  if (isParenthesizedExpression(node)) {
    copyExpressionComments(node);
    node = node.expression;
  }
  return node;
}

// src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts
var ts_refactor_convertToOptionalChainExpression_exports = {};

// src/services/refactors/convertToOptionalChainExpression.ts
var refactorName11 = "Convert to optional chain expression";
var convertToOptionalChainExpressionMessage = getLocaleSpecificMessage(Diagnostics.Convert_to_optional_chain_expression);
var toOptionalChainAction = {
  name: refactorName11,
  description: convertToOptionalChainExpressionMessage,
  kind: "refactor.rewrite.expression.optionalChain"
};
registerRefactor(refactorName11, {
  kinds: [toOptionalChainAction.kind],
  getEditsForAction: getRefactorEditsToConvertToOptionalChain,
  getAvailableActions: getRefactorActionsToConvertToOptionalChain
});
function getRefactorActionsToConvertToOptionalChain(context) {
  const info = getInfo3(context, context.triggerReason === "invoked");
  if (!info) return emptyArray;
  if (!isRefactorErrorInfo(info)) {
    return [{
      name: refactorName11,
      description: convertToOptionalChainExpressionMessage,
      actions: [toOptionalChainAction]
    }];
  }
  if (context.preferences.provideRefactorNotApplicableReason) {
    return [{
      name: refactorName11,
      description: convertToOptionalChainExpressionMessage,
      actions: [{ ...toOptionalChainAction, notApplicableReason: info.error }]
    }];
  }
  return emptyArray;
}
function getRefactorEditsToConvertToOptionalChain(context, actionName2) {
  const info = getInfo3(context);
  Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info");
  const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange6(context.file, context.program.getTypeChecker(), t, info, actionName2));
  return { edits, renameFilename: void 0, renameLocation: void 0 };
}
function isValidExpression(node) {
  return isBinaryExpression(node) || isConditionalExpression(node);
}
function isValidStatement(node) {
  return isExpressionStatement(node) || isReturnStatement(node) || isVariableStatement(node);
}
function isValidExpressionOrStatement(node) {
  return isValidExpression(node) || isValidStatement(node);
}
function getInfo3(context, considerEmptySpans = true) {
  const { file, program } = context;
  const span = getRefactorContextSpan(context);
  const forEmptySpan = span.length === 0;
  if (forEmptySpan && !considerEmptySpans) return void 0;
  const startToken = getTokenAtPosition(file, span.start);
  const endToken = findTokenOnLeftOfPosition(file, span.start + span.length);
  const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd());
  const parent2 = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan);
  const expression = parent2 && isValidExpressionOrStatement(parent2) ? getExpression(parent2) : void 0;
  if (!expression) return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) };
  const checker = program.getTypeChecker();
  return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression);
}
function getConditionalInfo(expression, checker) {
  const condition = expression.condition;
  const finalExpression = getFinalExpressionInChain(expression.whenTrue);
  if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) {
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) };
  }
  if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) {
    return { finalExpression, occurrences: [condition], expression };
  } else if (isBinaryExpression(condition)) {
    const occurrences = getOccurrencesInExpression(finalExpression.expression, condition);
    return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) };
  }
}
function getBinaryInfo(expression) {
  if (expression.operatorToken.kind !== 56 /* AmpersandAmpersandToken */) {
    return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) };
  }
  const finalExpression = getFinalExpressionInChain(expression.right);
  if (!finalExpression) return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) };
  const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left);
  return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) };
}
function getOccurrencesInExpression(matchTo, expression) {
  const occurrences = [];
  while (isBinaryExpression(expression) && expression.operatorToken.kind === 56 /* AmpersandAmpersandToken */) {
    const match = getMatchingStart(skipParentheses(matchTo), skipParentheses(expression.right));
    if (!match) {
      break;
    }
    occurrences.push(match);
    matchTo = match;
    expression = expression.left;
  }
  const finalMatch = getMatchingStart(matchTo, expression);
  if (finalMatch) {
    occurrences.push(finalMatch);
  }
  return occurrences.length > 0 ? occurrences : void 0;
}
function getMatchingStart(chain, subchain) {
  if (!isIdentifier(subchain) && !isPropertyAccessExpression(subchain) && !isElementAccessExpression(subchain)) {
    return void 0;
  }
  return chainStartsWith(chain, subchain) ? subchain : void 0;
}
function chainStartsWith(chain, subchain) {
  while (isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)) {
    if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) break;
    chain = chain.expression;
  }
  while (isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain) || isElementAccessExpression(chain) && isElementAccessExpression(subchain)) {
    if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) return false;
    chain = chain.expression;
    subchain = subchain.expression;
  }
  return isIdentifier(chain) && isIdentifier(subchain) && chain.getText() === subchain.getText();
}
function getTextOfChainNode(node) {
  if (isIdentifier(node) || isStringOrNumericLiteralLike(node)) {
    return node.getText();
  }
  if (isPropertyAccessExpression(node)) {
    return getTextOfChainNode(node.name);
  }
  if (isElementAccessExpression(node)) {
    return getTextOfChainNode(node.argumentExpression);
  }
  return void 0;
}
function getValidParentNodeContainingSpan(node, span) {
  while (node.parent) {
    if (isValidExpressionOrStatement(node) && span.length !== 0 && node.end >= span.start + span.length) {
      return node;
    }
    node = node.parent;
  }
  return void 0;
}
function getValidParentNodeOfEmptySpan(node) {
  while (node.parent) {
    if (isValidExpressionOrStatement(node) && !isValidExpressionOrStatement(node.parent)) {
      return node;
    }
    node = node.parent;
  }
  return void 0;
}
function getExpression(node) {
  if (isValidExpression(node)) {
    return node;
  }
  if (isVariableStatement(node)) {
    const variable = getSingleVariableOfVariableStatement(node);
    const initializer = variable == null ? void 0 : variable.initializer;
    return initializer && isValidExpression(initializer) ? initializer : void 0;
  }
  return node.expression && isValidExpression(node.expression) ? node.expression : void 0;
}
function getFinalExpressionInChain(node) {
  node = skipParentheses(node);
  if (isBinaryExpression(node)) {
    return getFinalExpressionInChain(node.left);
  } else if ((isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node)) && !isOptionalChain(node)) {
    return node;
  }
  return void 0;
}
function convertOccurrences(checker, toConvert, occurrences) {
  if (isPropertyAccessExpression(toConvert) || isElementAccessExpression(toConvert) || isCallExpression(toConvert)) {
    const chain = convertOccurrences(checker, toConvert.expression, occurrences);
    const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : void 0;
    const isOccurrence = (lastOccurrence == null ? void 0 : lastOccurrence.getText()) === toConvert.expression.getText();
    if (isOccurrence) occurrences.pop();
    if (isCallExpression(toConvert)) {
      return isOccurrence ? factory.createCallChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments);
    } else if (isPropertyAccessExpression(toConvert)) {
      return isOccurrence ? factory.createPropertyAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.name) : factory.createPropertyAccessChain(chain, toConvert.questionDotToken, toConvert.name);
    } else if (isElementAccessExpression(toConvert)) {
      return isOccurrence ? factory.createElementAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.argumentExpression) : factory.createElementAccessChain(chain, toConvert.questionDotToken, toConvert.argumentExpression);
    }
  }
  return toConvert;
}
function doChange6(sourceFile, checker, changes, info, _actionName) {
  const { finalExpression, occurrences, expression } = info;
  const firstOccurrence = occurrences[occurrences.length - 1];
  const convertedChain = convertOccurrences(checker, finalExpression, occurrences);
  if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) {
    if (isBinaryExpression(expression)) {
      changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain);
    } else if (isConditionalExpression(expression)) {
      changes.replaceNode(sourceFile, expression, factory.createBinaryExpression(convertedChain, factory.createToken(61 /* QuestionQuestionToken */), expression.whenFalse));
    }
  }
}

// src/services/_namespaces/ts.refactor.extractSymbol.ts
var ts_refactor_extractSymbol_exports = {};
__export(ts_refactor_extractSymbol_exports, {
  Messages: () => Messages,
  RangeFacts: () => RangeFacts,
  getRangeToExtract: () => getRangeToExtract2,
  getRefactorActionsToExtractSymbol: () => getRefactorActionsToExtractSymbol,
  getRefactorEditsToExtractSymbol: () => getRefactorEditsToExtractSymbol
});

// src/services/refactors/extractSymbol.ts
var refactorName12 = "Extract Symbol";
var extractConstantAction = {
  name: "Extract Constant",
  description: getLocaleSpecificMessage(Diagnostics.Extract_constant),
  kind: "refactor.extract.constant"
};
var extractFunctionAction = {
  name: "Extract Function",
  description: getLocaleSpecificMessage(Diagnostics.Extract_function),
  kind: "refactor.extract.function"
};
registerRefactor(refactorName12, {
  kinds: [
    extractConstantAction.kind,
    extractFunctionAction.kind
  ],
  getEditsForAction: getRefactorEditsToExtractSymbol,
  getAvailableActions: getRefactorActionsToExtractSymbol
});
function getRefactorActionsToExtractSymbol(context) {
  const requestedRefactor = context.kind;
  const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context), context.triggerReason === "invoked");
  const targetRange = rangeToExtract.targetRange;
  if (targetRange === void 0) {
    if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) {
      return emptyArray;
    }
    const errors = [];
    if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) {
      errors.push({
        name: refactorName12,
        description: extractFunctionAction.description,
        actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }]
      });
    }
    if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) {
      errors.push({
        name: refactorName12,
        description: extractConstantAction.description,
        actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }]
      });
    }
    return errors;
  }
  const { affectedTextRange, extractions } = getPossibleExtractions(targetRange, context);
  if (extractions === void 0) {
    return emptyArray;
  }
  const functionActions = [];
  const usedFunctionNames = /* @__PURE__ */ new Map();
  let innermostErrorFunctionAction;
  const constantActions = [];
  const usedConstantNames = /* @__PURE__ */ new Map();
  let innermostErrorConstantAction;
  let i = 0;
  for (const { functionExtraction, constantExtraction } of extractions) {
    if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) {
      const description3 = functionExtraction.description;
      if (functionExtraction.errors.length === 0) {
        if (!usedFunctionNames.has(description3)) {
          usedFunctionNames.set(description3, true);
          functionActions.push({
            description: description3,
            name: `function_scope_${i}`,
            kind: extractFunctionAction.kind,
            range: {
              start: { line: getLineAndCharacterOfPosition(context.file, affectedTextRange.pos).line, offset: getLineAndCharacterOfPosition(context.file, affectedTextRange.pos).character },
              end: { line: getLineAndCharacterOfPosition(context.file, affectedTextRange.end).line, offset: getLineAndCharacterOfPosition(context.file, affectedTextRange.end).character }
            }
          });
        }
      } else if (!innermostErrorFunctionAction) {
        innermostErrorFunctionAction = {
          description: description3,
          name: `function_scope_${i}`,
          notApplicableReason: getStringError(functionExtraction.errors),
          kind: extractFunctionAction.kind
        };
      }
    }
    if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) {
      const description3 = constantExtraction.description;
      if (constantExtraction.errors.length === 0) {
        if (!usedConstantNames.has(description3)) {
          usedConstantNames.set(description3, true);
          constantActions.push({
            description: description3,
            name: `constant_scope_${i}`,
            kind: extractConstantAction.kind,
            range: {
              start: { line: getLineAndCharacterOfPosition(context.file, affectedTextRange.pos).line, offset: getLineAndCharacterOfPosition(context.file, affectedTextRange.pos).character },
              end: { line: getLineAndCharacterOfPosition(context.file, affectedTextRange.end).line, offset: getLineAndCharacterOfPosition(context.file, affectedTextRange.end).character }
            }
          });
        }
      } else if (!innermostErrorConstantAction) {
        innermostErrorConstantAction = {
          description: description3,
          name: `constant_scope_${i}`,
          notApplicableReason: getStringError(constantExtraction.errors),
          kind: extractConstantAction.kind
        };
      }
    }
    i++;
  }
  const infos = [];
  if (functionActions.length) {
    infos.push({
      name: refactorName12,
      description: getLocaleSpecificMessage(Diagnostics.Extract_function),
      actions: functionActions
    });
  } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) {
    infos.push({
      name: refactorName12,
      description: getLocaleSpecificMessage(Diagnostics.Extract_function),
      actions: [innermostErrorFunctionAction]
    });
  }
  if (constantActions.length) {
    infos.push({
      name: refactorName12,
      description: getLocaleSpecificMessage(Diagnostics.Extract_constant),
      actions: constantActions
    });
  } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) {
    infos.push({
      name: refactorName12,
      description: getLocaleSpecificMessage(Diagnostics.Extract_constant),
      actions: [innermostErrorConstantAction]
    });
  }
  return infos.length ? infos : emptyArray;
  function getStringError(errors) {
    let error2 = errors[0].messageText;
    if (typeof error2 !== "string") {
      error2 = error2.messageText;
    }
    return error2;
  }
}
function getRefactorEditsToExtractSymbol(context, actionName2) {
  const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context));
  const targetRange = rangeToExtract.targetRange;
  const parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName2);
  if (parsedFunctionIndexMatch) {
    const index = +parsedFunctionIndexMatch[1];
    Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index");
    return getFunctionExtractionAtIndex(targetRange, context, index);
  }
  const parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName2);
  if (parsedConstantIndexMatch) {
    const index = +parsedConstantIndexMatch[1];
    Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index");
    return getConstantExtractionAtIndex(targetRange, context, index);
  }
  Debug.fail("Unrecognized action name");
}
var Messages;
((Messages2) => {
  function createMessage(message) {
    return { message, code: 0, category: 3 /* Message */, key: message };
  }
  Messages2.cannotExtractRange = createMessage("Cannot extract range.");
  Messages2.cannotExtractImport = createMessage("Cannot extract import statement.");
  Messages2.cannotExtractSuper = createMessage("Cannot extract super call.");
  Messages2.cannotExtractJSDoc = createMessage("Cannot extract JSDoc.");
  Messages2.cannotExtractEmpty = createMessage("Cannot extract empty range.");
  Messages2.expressionExpected = createMessage("expression expected.");
  Messages2.uselessConstantType = createMessage("No reason to extract constant of type.");
  Messages2.statementOrExpressionExpected = createMessage("Statement or expression expected.");
  Messages2.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements.");
  Messages2.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement.");
  Messages2.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range.");
  Messages2.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators.");
  Messages2.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope.");
  Messages2.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope.");
  Messages2.cannotExtractIdentifier = createMessage("Select more than a single identifier.");
  Messages2.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration");
  Messages2.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression");
  Messages2.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor");
  Messages2.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts");
  Messages2.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes");
  Messages2.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS");
  Messages2.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block");
  Messages2.cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method");
})(Messages || (Messages = {}));
var RangeFacts = /* @__PURE__ */ ((RangeFacts2) => {
  RangeFacts2[RangeFacts2["None"] = 0] = "None";
  RangeFacts2[RangeFacts2["HasReturn"] = 1] = "HasReturn";
  RangeFacts2[RangeFacts2["IsGenerator"] = 2] = "IsGenerator";
  RangeFacts2[RangeFacts2["IsAsyncFunction"] = 4] = "IsAsyncFunction";
  RangeFacts2[RangeFacts2["UsesThis"] = 8] = "UsesThis";
  RangeFacts2[RangeFacts2["UsesThisInFunction"] = 16] = "UsesThisInFunction";
  RangeFacts2[RangeFacts2["InStaticRegion"] = 32] = "InStaticRegion";
  return RangeFacts2;
})(RangeFacts || {});
function getRangeToExtract2(sourceFile, span, invoked = true) {
  const { length: length2 } = span;
  if (length2 === 0 && !invoked) {
    return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty)] };
  }
  const cursorRequest = length2 === 0 && invoked;
  const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start);
  const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span));
  const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span;
  const start = cursorRequest ? getExtractableParent(startToken) : getParentNodeInSpan(startToken, sourceFile, adjustedSpan);
  const end = cursorRequest ? start : getParentNodeInSpan(endToken, sourceFile, adjustedSpan);
  let rangeFacts = 0 /* None */;
  let thisNode;
  if (!start || !end) {
    return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] };
  }
  if (start.flags & 16777216 /* JSDoc */) {
    return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc)] };
  }
  if (start.parent !== end.parent) {
    return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] };
  }
  if (start !== end) {
    if (!isBlockLike(start.parent)) {
      return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] };
    }
    const statements = [];
    for (const statement of start.parent.statements) {
      if (statement === start || statements.length) {
        const errors2 = checkNode(statement);
        if (errors2) {
          return { errors: errors2 };
        }
        statements.push(statement);
      }
      if (statement === end) {
        break;
      }
    }
    if (!statements.length) {
      return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] };
    }
    return { targetRange: { range: statements, facts: rangeFacts, thisNode } };
  }
  if (isReturnStatement(start) && !start.expression) {
    return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] };
  }
  const node = refineNode(start);
  const errors = checkRootNode(node) || checkNode(node);
  if (errors) {
    return { errors };
  }
  return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode } };
  function refineNode(node2) {
    if (isReturnStatement(node2)) {
      if (node2.expression) {
        return node2.expression;
      }
    } else if (isVariableStatement(node2) || isVariableDeclarationList(node2)) {
      const declarations = isVariableStatement(node2) ? node2.declarationList.declarations : node2.declarations;
      let numInitializers = 0;
      let lastInitializer;
      for (const declaration of declarations) {
        if (declaration.initializer) {
          numInitializers++;
          lastInitializer = declaration.initializer;
        }
      }
      if (numInitializers === 1) {
        return lastInitializer;
      }
    } else if (isVariableDeclaration(node2)) {
      if (node2.initializer) {
        return node2.initializer;
      }
    }
    return node2;
  }
  function checkRootNode(node2) {
    if (isIdentifier(isExpressionStatement(node2) ? node2.expression : node2)) {
      return [createDiagnosticForNode(node2, Messages.cannotExtractIdentifier)];
    }
    return void 0;
  }
  function checkForStaticContext(nodeToCheck, containingClass) {
    let current = nodeToCheck;
    while (current !== containingClass) {
      if (current.kind === 172 /* PropertyDeclaration */) {
        if (isStatic(current)) {
          rangeFacts |= 32 /* InStaticRegion */;
        }
        break;
      } else if (current.kind === 169 /* Parameter */) {
        const ctorOrMethod = getContainingFunction(current);
        if (ctorOrMethod.kind === 176 /* Constructor */) {
          rangeFacts |= 32 /* InStaticRegion */;
        }
        break;
      } else if (current.kind === 174 /* MethodDeclaration */) {
        if (isStatic(current)) {
          rangeFacts |= 32 /* InStaticRegion */;
        }
      }
      current = current.parent;
    }
  }
  function checkNode(nodeToCheck) {
    let PermittedJumps;
    ((PermittedJumps2) => {
      PermittedJumps2[PermittedJumps2["None"] = 0] = "None";
      PermittedJumps2[PermittedJumps2["Break"] = 1] = "Break";
      PermittedJumps2[PermittedJumps2["Continue"] = 2] = "Continue";
      PermittedJumps2[PermittedJumps2["Return"] = 4] = "Return";
    })(PermittedJumps || (PermittedJumps = {}));
    Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)");
    Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)");
    if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck)) && !isStringLiteralJsxAttribute(nodeToCheck)) {
      return [createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)];
    }
    if (nodeToCheck.flags & 33554432 /* Ambient */) {
      return [createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)];
    }
    const containingClass = getContainingClass(nodeToCheck);
    if (containingClass) {
      checkForStaticContext(nodeToCheck, containingClass);
    }
    let errors2;
    let permittedJumps = 4 /* Return */;
    let seenLabels;
    visit(nodeToCheck);
    if (rangeFacts & 8 /* UsesThis */) {
      const container = getThisContainer(
        nodeToCheck,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      );
      if (container.kind === 262 /* FunctionDeclaration */ || container.kind === 174 /* MethodDeclaration */ && container.parent.kind === 210 /* ObjectLiteralExpression */ || container.kind === 218 /* FunctionExpression */) {
        rangeFacts |= 16 /* UsesThisInFunction */;
      }
    }
    return errors2;
    function visit(node2) {
      if (errors2) {
        return true;
      }
      if (isDeclaration(node2)) {
        const declaringNode = node2.kind === 260 /* VariableDeclaration */ ? node2.parent.parent : node2;
        if (hasSyntacticModifier(declaringNode, 32 /* Export */)) {
          (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity));
          return true;
        }
      }
      switch (node2.kind) {
        case 272 /* ImportDeclaration */:
          (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractImport));
          return true;
        case 277 /* ExportAssignment */:
          (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity));
          return true;
        case 108 /* SuperKeyword */:
          if (node2.parent.kind === 213 /* CallExpression */) {
            const containingClass2 = getContainingClass(node2);
            if (containingClass2 === void 0 || containingClass2.pos < span.start || containingClass2.end >= span.start + span.length) {
              (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractSuper));
              return true;
            }
          } else {
            rangeFacts |= 8 /* UsesThis */;
            thisNode = node2;
          }
          break;
        case 219 /* ArrowFunction */:
          forEachChild(node2, function check(n) {
            if (isThis(n)) {
              rangeFacts |= 8 /* UsesThis */;
              thisNode = node2;
            } else if (isClassLike(n) || isFunctionLike(n) && !isArrowFunction(n)) {
              return false;
            } else {
              forEachChild(n, check);
            }
          });
        // falls through
        case 263 /* ClassDeclaration */:
        case 262 /* FunctionDeclaration */:
          if (isSourceFile(node2.parent) && node2.parent.externalModuleIndicator === void 0) {
            (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.functionWillNotBeVisibleInTheNewScope));
          }
        // falls through
        case 231 /* ClassExpression */:
        case 218 /* FunctionExpression */:
        case 174 /* MethodDeclaration */:
        case 176 /* Constructor */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
          return false;
      }
      const savedPermittedJumps = permittedJumps;
      switch (node2.kind) {
        case 245 /* IfStatement */:
          permittedJumps &= ~4 /* Return */;
          break;
        case 258 /* TryStatement */:
          permittedJumps = 0 /* None */;
          break;
        case 241 /* Block */:
          if (node2.parent && node2.parent.kind === 258 /* TryStatement */ && node2.parent.finallyBlock === node2) {
            permittedJumps = 4 /* Return */;
          }
          break;
        case 297 /* DefaultClause */:
        case 296 /* CaseClause */:
          permittedJumps |= 1 /* Break */;
          break;
        default:
          if (isIterationStatement(
            node2,
            /*lookInLabeledStatements*/
            false
          )) {
            permittedJumps |= 1 /* Break */ | 2 /* Continue */;
          }
          break;
      }
      switch (node2.kind) {
        case 197 /* ThisType */:
        case 110 /* ThisKeyword */:
          rangeFacts |= 8 /* UsesThis */;
          thisNode = node2;
          break;
        case 256 /* LabeledStatement */: {
          const label = node2.label;
          (seenLabels || (seenLabels = [])).push(label.escapedText);
          forEachChild(node2, visit);
          seenLabels.pop();
          break;
        }
        case 252 /* BreakStatement */:
        case 251 /* ContinueStatement */: {
          const label = node2.label;
          if (label) {
            if (!contains(seenLabels, label.escapedText)) {
              (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange));
            }
          } else {
            if (!(permittedJumps & (node2.kind === 252 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) {
              (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements));
            }
          }
          break;
        }
        case 223 /* AwaitExpression */:
          rangeFacts |= 4 /* IsAsyncFunction */;
          break;
        case 229 /* YieldExpression */:
          rangeFacts |= 2 /* IsGenerator */;
          break;
        case 253 /* ReturnStatement */:
          if (permittedJumps & 4 /* Return */) {
            rangeFacts |= 1 /* HasReturn */;
          } else {
            (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalReturnStatement));
          }
          break;
        default:
          forEachChild(node2, visit);
          break;
      }
      permittedJumps = savedPermittedJumps;
    }
  }
}
function getAdjustedSpanFromNodes(startNode2, endNode2, sourceFile) {
  const start = startNode2.getStart(sourceFile);
  let end = endNode2.getEnd();
  if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) {
    end++;
  }
  return { start, length: end - start };
}
function getStatementOrExpressionRange(node) {
  if (isStatement(node)) {
    return [node];
  }
  if (isExpressionNode(node)) {
    return isExpressionStatement(node.parent) ? [node.parent] : node;
  }
  if (isStringLiteralJsxAttribute(node)) {
    return node;
  }
  return void 0;
}
function isScope(node) {
  return isArrowFunction(node) ? isFunctionBody(node.body) : isFunctionLikeDeclaration(node) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node);
}
function collectEnclosingScopes(range) {
  let current = isReadonlyArray(range.range) ? first(range.range) : range.range;
  if (range.facts & 8 /* UsesThis */ && !(range.facts & 16 /* UsesThisInFunction */)) {
    const containingClass = getContainingClass(current);
    if (containingClass) {
      const containingFunction = findAncestor(current, isFunctionLikeDeclaration);
      return containingFunction ? [containingFunction, containingClass] : [containingClass];
    }
  }
  const scopes = [];
  while (true) {
    current = current.parent;
    if (current.kind === 169 /* Parameter */) {
      current = findAncestor(current, (parent2) => isFunctionLikeDeclaration(parent2)).parent;
    }
    if (isScope(current)) {
      scopes.push(current);
      if (current.kind === 307 /* SourceFile */) {
        return scopes;
      }
    }
  }
}
function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) {
  const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context);
  Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
  context.cancellationToken.throwIfCancellationRequested();
  return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context);
}
function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) {
  const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context);
  Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
  Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?");
  context.cancellationToken.throwIfCancellationRequested();
  const expression = isExpression(target) ? target : target.statements[0].expression;
  return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context);
}
function getPossibleExtractions(targetRange, context) {
  const { scopes, affectedTextRange, readsAndWrites: { functionErrorsPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context);
  const extractions = scopes.map((scope, i) => {
    const functionDescriptionPart = getDescriptionForFunctionInScope(scope);
    const constantDescriptionPart = getDescriptionForConstantInScope(scope);
    const scopeDescription = isFunctionLikeDeclaration(scope) ? getDescriptionForFunctionLikeDeclaration(scope) : isClassLike(scope) ? getDescriptionForClassLikeDeclaration(scope) : getDescriptionForModuleLikeDeclaration(scope);
    let functionDescription;
    let constantDescription;
    if (scopeDescription === 1 /* Global */) {
      functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]);
      constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]);
    } else if (scopeDescription === 0 /* Module */) {
      functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]);
      constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]);
    } else {
      functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]);
      constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]);
    }
    if (i === 0 && !isClassLike(scope)) {
      constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]);
    }
    return {
      functionExtraction: {
        description: functionDescription,
        errors: functionErrorsPerScope[i]
      },
      constantExtraction: {
        description: constantDescription,
        errors: constantErrorsPerScope[i]
      }
    };
  });
  return { affectedTextRange, extractions };
}
function getPossibleExtractionsWorker(targetRange, context) {
  const { file: sourceFile } = context;
  const scopes = collectEnclosingScopes(targetRange);
  const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile);
  const readsAndWrites = collectReadsAndWrites(
    targetRange,
    scopes,
    enclosingTextRange,
    sourceFile,
    context.program.getTypeChecker(),
    context.cancellationToken
  );
  return { scopes, affectedTextRange: enclosingTextRange, readsAndWrites };
}
function getDescriptionForFunctionInScope(scope) {
  return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) ? "method" : "function";
}
function getDescriptionForConstantInScope(scope) {
  return isClassLike(scope) ? "readonly field" : "constant";
}
function getDescriptionForFunctionLikeDeclaration(scope) {
  switch (scope.kind) {
    case 176 /* Constructor */:
      return "constructor";
    case 218 /* FunctionExpression */:
    case 262 /* FunctionDeclaration */:
      return scope.name ? `function '${scope.name.text}'` : ANONYMOUS;
    case 219 /* ArrowFunction */:
      return "arrow function";
    case 174 /* MethodDeclaration */:
      return `method '${scope.name.getText()}'`;
    case 177 /* GetAccessor */:
      return `'get ${scope.name.getText()}'`;
    case 178 /* SetAccessor */:
      return `'set ${scope.name.getText()}'`;
    default:
      Debug.assertNever(scope, `Unexpected scope kind ${scope.kind}`);
  }
}
function getDescriptionForClassLikeDeclaration(scope) {
  return scope.kind === 263 /* ClassDeclaration */ ? scope.name ? `class '${scope.name.text}'` : "anonymous class declaration" : scope.name ? `class expression '${scope.name.text}'` : "anonymous class expression";
}
function getDescriptionForModuleLikeDeclaration(scope) {
  return scope.kind === 268 /* ModuleBlock */ ? `namespace '${scope.parent.name.getText()}'` : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */;
}
function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParameterUsages, substitutions }, exposedVariableDeclarations, range, context) {
  const checker = context.program.getTypeChecker();
  const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions());
  const importAdder = ts_codefix_exports.createImportAdder(context.file, context.program, context.preferences, context.host);
  const file = scope.getSourceFile();
  const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file);
  const isJS = isInJSFile(scope);
  const functionName = factory.createIdentifier(functionNameText);
  let returnType;
  const parameters = [];
  const callArguments = [];
  let writes;
  usagesInScope.forEach((usage, name) => {
    let typeNode;
    if (!isJS) {
      let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node);
      type = checker.getBaseTypeOfLiteralType(type);
      typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */);
    }
    const paramDecl = factory.createParameterDeclaration(
      /*modifiers*/
      void 0,
      /*dotDotDotToken*/
      void 0,
      /*name*/
      name,
      /*questionToken*/
      void 0,
      typeNode
    );
    parameters.push(paramDecl);
    if (usage.usage === 2 /* Write */) {
      (writes || (writes = [])).push(usage);
    }
    callArguments.push(factory.createIdentifier(name));
  });
  const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type) => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) }));
  typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder);
  const typeParameters = typeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(typeParametersAndDeclarations, ({ declaration }) => declaration);
  const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl) => factory.createTypeReferenceNode(
    decl.name,
    /*typeArguments*/
    void 0
  )) : void 0;
  if (isExpression(node) && !isJS) {
    const contextualType = checker.getContextualType(node);
    returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */);
  }
  const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */));
  suppressLeadingAndTrailingTrivia(body);
  let newFunction;
  const callThis = !!(range.facts & 16 /* UsesThisInFunction */);
  if (isClassLike(scope)) {
    const modifiers = isJS ? [] : [factory.createModifier(123 /* PrivateKeyword */)];
    if (range.facts & 32 /* InStaticRegion */) {
      modifiers.push(factory.createModifier(126 /* StaticKeyword */));
    }
    if (range.facts & 4 /* IsAsyncFunction */) {
      modifiers.push(factory.createModifier(134 /* AsyncKeyword */));
    }
    newFunction = factory.createMethodDeclaration(
      modifiers.length ? modifiers : void 0,
      range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0,
      functionName,
      /*questionToken*/
      void 0,
      typeParameters,
      parameters,
      returnType,
      body
    );
  } else {
    if (callThis) {
      parameters.unshift(
        factory.createParameterDeclaration(
          /*modifiers*/
          void 0,
          /*dotDotDotToken*/
          void 0,
          /*name*/
          "this",
          /*questionToken*/
          void 0,
          checker.typeToTypeNode(
            checker.getTypeAtLocation(range.thisNode),
            scope,
            1 /* NoTruncation */,
            8 /* AllowUnresolvedNames */
          ),
          /*initializer*/
          void 0
        )
      );
    }
    newFunction = factory.createFunctionDeclaration(
      range.facts & 4 /* IsAsyncFunction */ ? [factory.createToken(134 /* AsyncKeyword */)] : void 0,
      range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0,
      functionName,
      typeParameters,
      parameters,
      returnType,
      body
    );
  }
  const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context);
  const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end;
  const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope);
  if (nodeToInsertBefore) {
    changeTracker.insertNodeBefore(
      context.file,
      nodeToInsertBefore,
      newFunction,
      /*blankLineBetween*/
      true
    );
  } else {
    changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction);
  }
  importAdder.writeFixes(changeTracker);
  const newNodes = [];
  const called = getCalledExpression(scope, range, functionNameText);
  if (callThis) {
    callArguments.unshift(factory.createIdentifier("this"));
  }
  let call = factory.createCallExpression(
    callThis ? factory.createPropertyAccessExpression(
      called,
      "call"
    ) : called,
    callTypeArguments,
    // Note that no attempt is made to take advantage of type argument inference
    callArguments
  );
  if (range.facts & 2 /* IsGenerator */) {
    call = factory.createYieldExpression(factory.createToken(42 /* AsteriskToken */), call);
  }
  if (range.facts & 4 /* IsAsyncFunction */) {
    call = factory.createAwaitExpression(call);
  }
  if (isInJSXContent(node)) {
    call = factory.createJsxExpression(
      /*dotDotDotToken*/
      void 0,
      call
    );
  }
  if (exposedVariableDeclarations.length && !writes) {
    Debug.assert(!returnValueProperty, "Expected no returnValueProperty");
    Debug.assert(!(range.facts & 1 /* HasReturn */), "Expected RangeFacts.HasReturn flag to be unset");
    if (exposedVariableDeclarations.length === 1) {
      const variableDeclaration = exposedVariableDeclarations[0];
      newNodes.push(factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList(
          [factory.createVariableDeclaration(
            getSynthesizedDeepClone(variableDeclaration.name),
            /*exclamationToken*/
            void 0,
            /*type*/
            getSynthesizedDeepClone(variableDeclaration.type),
            /*initializer*/
            call
          )],
          variableDeclaration.parent.flags
        )
      ));
    } else {
      const bindingElements = [];
      const typeElements = [];
      let commonNodeFlags = exposedVariableDeclarations[0].parent.flags;
      let sawExplicitType = false;
      for (const variableDeclaration of exposedVariableDeclarations) {
        bindingElements.push(factory.createBindingElement(
          /*dotDotDotToken*/
          void 0,
          /*propertyName*/
          void 0,
          /*name*/
          getSynthesizedDeepClone(variableDeclaration.name)
        ));
        const variableType = checker.typeToTypeNode(
          checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)),
          scope,
          1 /* NoTruncation */,
          8 /* AllowUnresolvedNames */
        );
        typeElements.push(factory.createPropertySignature(
          /*modifiers*/
          void 0,
          /*name*/
          variableDeclaration.symbol.name,
          /*questionToken*/
          void 0,
          /*type*/
          variableType
        ));
        sawExplicitType = sawExplicitType || variableDeclaration.type !== void 0;
        commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags;
      }
      const typeLiteral = sawExplicitType ? factory.createTypeLiteralNode(typeElements) : void 0;
      if (typeLiteral) {
        setEmitFlags(typeLiteral, 1 /* SingleLine */);
      }
      newNodes.push(factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList(
          [factory.createVariableDeclaration(
            factory.createObjectBindingPattern(bindingElements),
            /*exclamationToken*/
            void 0,
            /*type*/
            typeLiteral,
            /*initializer*/
            call
          )],
          commonNodeFlags
        )
      ));
    }
  } else if (exposedVariableDeclarations.length || writes) {
    if (exposedVariableDeclarations.length) {
      for (const variableDeclaration of exposedVariableDeclarations) {
        let flags = variableDeclaration.parent.flags;
        if (flags & 2 /* Const */) {
          flags = flags & ~2 /* Const */ | 1 /* Let */;
        }
        newNodes.push(factory.createVariableStatement(
          /*modifiers*/
          void 0,
          factory.createVariableDeclarationList(
            [factory.createVariableDeclaration(
              variableDeclaration.symbol.name,
              /*exclamationToken*/
              void 0,
              getTypeDeepCloneUnionUndefined(variableDeclaration.type)
            )],
            flags
          )
        ));
      }
    }
    if (returnValueProperty) {
      newNodes.push(factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList(
          [factory.createVariableDeclaration(
            returnValueProperty,
            /*exclamationToken*/
            void 0,
            getTypeDeepCloneUnionUndefined(returnType)
          )],
          1 /* Let */
        )
      ));
    }
    const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
    if (returnValueProperty) {
      assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty));
    }
    if (assignments.length === 1) {
      Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here");
      newNodes.push(factory.createExpressionStatement(factory.createAssignment(assignments[0].name, call)));
      if (range.facts & 1 /* HasReturn */) {
        newNodes.push(factory.createReturnStatement());
      }
    } else {
      newNodes.push(factory.createExpressionStatement(factory.createAssignment(factory.createObjectLiteralExpression(assignments), call)));
      if (returnValueProperty) {
        newNodes.push(factory.createReturnStatement(factory.createIdentifier(returnValueProperty)));
      }
    }
  } else {
    if (range.facts & 1 /* HasReturn */) {
      newNodes.push(factory.createReturnStatement(call));
    } else if (isReadonlyArray(range.range)) {
      newNodes.push(factory.createExpressionStatement(call));
    } else {
      newNodes.push(call);
    }
  }
  if (isReadonlyArray(range.range)) {
    changeTracker.replaceNodeRangeWithNodes(context.file, first(range.range), last(range.range), newNodes);
  } else {
    changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes);
  }
  const edits = changeTracker.getChanges();
  const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range;
  const renameFilename = renameRange.getSourceFile().fileName;
  const renameLocation = getRenameLocation(
    edits,
    renameFilename,
    functionNameText,
    /*preferLastLocation*/
    false
  );
  return { renameFilename, renameLocation, edits };
  function getTypeDeepCloneUnionUndefined(typeNode) {
    if (typeNode === void 0) {
      return void 0;
    }
    const clone2 = getSynthesizedDeepClone(typeNode);
    let withoutParens = clone2;
    while (isParenthesizedTypeNode(withoutParens)) {
      withoutParens = withoutParens.type;
    }
    return isUnionTypeNode(withoutParens) && find(withoutParens.types, (t) => t.kind === 157 /* UndefinedKeyword */) ? clone2 : factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]);
  }
}
function extractConstantInScope(node, scope, { substitutions }, rangeFacts, context) {
  const checker = context.program.getTypeChecker();
  const file = scope.getSourceFile();
  const localNameText = getIdentifierForNode(node, scope, checker, file);
  const isJS = isInJSFile(scope);
  let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */);
  let initializer = transformConstantInitializer(skipParentheses(node), substitutions);
  ({ variableType, initializer } = transformFunctionInitializerAndType(variableType, initializer));
  suppressLeadingAndTrailingTrivia(initializer);
  const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context);
  if (isClassLike(scope)) {
    Debug.assert(!isJS, "Cannot extract to a JS class");
    const modifiers = [];
    modifiers.push(factory.createModifier(123 /* PrivateKeyword */));
    if (rangeFacts & 32 /* InStaticRegion */) {
      modifiers.push(factory.createModifier(126 /* StaticKeyword */));
    }
    modifiers.push(factory.createModifier(148 /* ReadonlyKeyword */));
    const newVariable = factory.createPropertyDeclaration(
      modifiers,
      localNameText,
      /*questionOrExclamationToken*/
      void 0,
      variableType,
      initializer
    );
    let localReference = factory.createPropertyAccessExpression(
      rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(),
      factory.createIdentifier(localNameText)
    );
    if (isInJSXContent(node)) {
      localReference = factory.createJsxExpression(
        /*dotDotDotToken*/
        void 0,
        localReference
      );
    }
    const maxInsertionPos = node.pos;
    const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope);
    changeTracker.insertNodeBefore(
      context.file,
      nodeToInsertBefore,
      newVariable,
      /*blankLineBetween*/
      true
    );
    changeTracker.replaceNode(context.file, node, localReference);
  } else {
    const newVariableDeclaration = factory.createVariableDeclaration(
      localNameText,
      /*exclamationToken*/
      void 0,
      variableType,
      initializer
    );
    const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope);
    if (oldVariableDeclaration) {
      changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration);
      const localReference = factory.createIdentifier(localNameText);
      changeTracker.replaceNode(context.file, node, localReference);
    } else if (node.parent.kind === 244 /* ExpressionStatement */ && scope === findAncestor(node, isScope)) {
      const newVariableStatement = factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)
      );
      changeTracker.replaceNode(context.file, node.parent, newVariableStatement);
    } else {
      const newVariableStatement = factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)
      );
      const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope);
      if (nodeToInsertBefore.pos === 0) {
        changeTracker.insertNodeAtTopOfFile(
          context.file,
          newVariableStatement,
          /*blankLineBetween*/
          false
        );
      } else {
        changeTracker.insertNodeBefore(
          context.file,
          nodeToInsertBefore,
          newVariableStatement,
          /*blankLineBetween*/
          false
        );
      }
      if (node.parent.kind === 244 /* ExpressionStatement */) {
        changeTracker.delete(context.file, node.parent);
      } else {
        let localReference = factory.createIdentifier(localNameText);
        if (isInJSXContent(node)) {
          localReference = factory.createJsxExpression(
            /*dotDotDotToken*/
            void 0,
            localReference
          );
        }
        changeTracker.replaceNode(context.file, node, localReference);
      }
    }
  }
  const edits = changeTracker.getChanges();
  const renameFilename = node.getSourceFile().fileName;
  const renameLocation = getRenameLocation(
    edits,
    renameFilename,
    localNameText,
    /*preferLastLocation*/
    true
  );
  return { renameFilename, renameLocation, edits };
  function transformFunctionInitializerAndType(variableType2, initializer2) {
    if (variableType2 === void 0) return { variableType: variableType2, initializer: initializer2 };
    if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters) return { variableType: variableType2, initializer: initializer2 };
    const functionType = checker.getTypeAtLocation(node);
    const functionSignature = singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */));
    if (!functionSignature) return { variableType: variableType2, initializer: initializer2 };
    if (!!functionSignature.getTypeParameters()) return { variableType: variableType2, initializer: initializer2 };
    const parameters = [];
    let hasAny = false;
    for (const p of initializer2.parameters) {
      if (p.type) {
        parameters.push(p);
      } else {
        const paramType = checker.getTypeAtLocation(p);
        if (paramType === checker.getAnyType()) hasAny = true;
        parameters.push(factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */), p.initializer));
      }
    }
    if (hasAny) return { variableType: variableType2, initializer: initializer2 };
    variableType2 = void 0;
    if (isArrowFunction(initializer2)) {
      initializer2 = factory.updateArrowFunction(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */), initializer2.equalsGreaterThanToken, initializer2.body);
    } else {
      if (functionSignature && !!functionSignature.thisParameter) {
        const firstParameter = firstOrUndefined(parameters);
        if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") {
          const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node);
          parameters.splice(
            0,
            0,
            factory.createParameterDeclaration(
              /*modifiers*/
              void 0,
              /*dotDotDotToken*/
              void 0,
              "this",
              /*questionToken*/
              void 0,
              checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */)
            )
          );
        }
      }
      initializer2 = factory.updateFunctionExpression(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.asteriskToken, initializer2.name, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer2.body);
    }
    return { variableType: variableType2, initializer: initializer2 };
  }
}
function getContainingVariableDeclarationIfInList(node, scope) {
  let prevNode;
  while (node !== void 0 && node !== scope) {
    if (isVariableDeclaration(node) && node.initializer === prevNode && isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1) {
      return node;
    }
    prevNode = node;
    node = node.parent;
  }
}
function getFirstDeclarationBeforePosition(type, position) {
  let firstDeclaration;
  const symbol = type.symbol;
  if (symbol && symbol.declarations) {
    for (const declaration of symbol.declarations) {
      if ((firstDeclaration === void 0 || declaration.pos < firstDeclaration.pos) && declaration.pos < position) {
        firstDeclaration = declaration;
      }
    }
  }
  return firstDeclaration;
}
function compareTypesByDeclarationOrder({ type: type1, declaration: declaration1 }, { type: type2, declaration: declaration2 }) {
  return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive(
    type1.symbol ? type1.symbol.getName() : "",
    type2.symbol ? type2.symbol.getName() : ""
  ) || compareValues(type1.id, type2.id);
}
function getCalledExpression(scope, range, functionNameText) {
  const functionReference = factory.createIdentifier(functionNameText);
  if (isClassLike(scope)) {
    const lhs = range.facts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.text) : factory.createThis();
    return factory.createPropertyAccessExpression(lhs, functionReference);
  } else {
    return functionReference;
  }
}
function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn2) {
  const hasWritesOrVariableDeclarations = writes !== void 0 || exposedVariableDeclarations.length > 0;
  if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) {
    return { body: factory.createBlock(
      body.statements,
      /*multiLine*/
      true
    ), returnValueProperty: void 0 };
  }
  let returnValueProperty;
  let ignoreReturns = false;
  const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [isStatement(body) ? body : factory.createReturnStatement(skipParentheses(body))]);
  if (hasWritesOrVariableDeclarations || substitutions.size) {
    const rewrittenStatements = visitNodes2(statements, visitor, isStatement).slice();
    if (hasWritesOrVariableDeclarations && !hasReturn2 && isStatement(body)) {
      const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
      if (assignments.length === 1) {
        rewrittenStatements.push(factory.createReturnStatement(assignments[0].name));
      } else {
        rewrittenStatements.push(factory.createReturnStatement(factory.createObjectLiteralExpression(assignments)));
      }
    }
    return { body: factory.createBlock(
      rewrittenStatements,
      /*multiLine*/
      true
    ), returnValueProperty };
  } else {
    return { body: factory.createBlock(
      statements,
      /*multiLine*/
      true
    ), returnValueProperty: void 0 };
  }
  function visitor(node) {
    if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) {
      const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
      if (node.expression) {
        if (!returnValueProperty) {
          returnValueProperty = "__return";
        }
        assignments.unshift(factory.createPropertyAssignment(returnValueProperty, visitNode(node.expression, visitor, isExpression)));
      }
      if (assignments.length === 1) {
        return factory.createReturnStatement(assignments[0].name);
      } else {
        return factory.createReturnStatement(factory.createObjectLiteralExpression(assignments));
      }
    } else {
      const oldIgnoreReturns = ignoreReturns;
      ignoreReturns = ignoreReturns || isFunctionLikeDeclaration(node) || isClassLike(node);
      const substitution = substitutions.get(getNodeId(node).toString());
      const result = substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(
        node,
        visitor,
        /*context*/
        void 0
      );
      ignoreReturns = oldIgnoreReturns;
      return result;
    }
  }
}
function transformConstantInitializer(initializer, substitutions) {
  return substitutions.size ? visitor(initializer) : initializer;
  function visitor(node) {
    const substitution = substitutions.get(getNodeId(node).toString());
    return substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(
      node,
      visitor,
      /*context*/
      void 0
    );
  }
}
function getStatementsOrClassElements(scope) {
  if (isFunctionLikeDeclaration(scope)) {
    const body = scope.body;
    if (isBlock(body)) {
      return body.statements;
    }
  } else if (isModuleBlock(scope) || isSourceFile(scope)) {
    return scope.statements;
  } else if (isClassLike(scope)) {
    return scope.members;
  } else {
    assertType(scope);
  }
  return emptyArray;
}
function getNodeToInsertFunctionBefore(minPos, scope) {
  return find(getStatementsOrClassElements(scope), (child) => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child));
}
function getNodeToInsertPropertyBefore(maxPos, scope) {
  const members = scope.members;
  Debug.assert(members.length > 0, "Found no members");
  let prevMember;
  let allProperties = true;
  for (const member of members) {
    if (member.pos > maxPos) {
      return prevMember || members[0];
    }
    if (allProperties && !isPropertyDeclaration(member)) {
      if (prevMember !== void 0) {
        return member;
      }
      allProperties = false;
    }
    prevMember = member;
  }
  if (prevMember === void 0) return Debug.fail();
  return prevMember;
}
function getNodeToInsertConstantBefore(node, scope) {
  Debug.assert(!isClassLike(scope));
  let prevScope;
  for (let curr = node; curr !== scope; curr = curr.parent) {
    if (isScope(curr)) {
      prevScope = curr;
    }
  }
  for (let curr = (prevScope || node).parent; ; curr = curr.parent) {
    if (isBlockLike(curr)) {
      let prevStatement;
      for (const statement of curr.statements) {
        if (statement.pos > node.pos) {
          break;
        }
        prevStatement = statement;
      }
      if (!prevStatement && isCaseClause(curr)) {
        Debug.assert(isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement");
        return curr.parent.parent;
      }
      return Debug.checkDefined(prevStatement, "prevStatement failed to get set");
    }
    Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope");
  }
}
function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) {
  const variableAssignments = map(exposedVariableDeclarations, (v) => factory.createShorthandPropertyAssignment(v.symbol.name));
  const writeAssignments = map(writes, (w) => factory.createShorthandPropertyAssignment(w.symbol.name));
  return variableAssignments === void 0 ? writeAssignments : writeAssignments === void 0 ? variableAssignments : variableAssignments.concat(writeAssignments);
}
function isReadonlyArray(v) {
  return isArray(v);
}
function getEnclosingTextRange(targetRange, sourceFile) {
  return isReadonlyArray(targetRange.range) ? { pos: first(targetRange.range).getStart(sourceFile), end: last(targetRange.range).getEnd() } : targetRange.range;
}
function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) {
  const allTypeParameterUsages = /* @__PURE__ */ new Map();
  const usagesPerScope = [];
  const substitutionsPerScope = [];
  const functionErrorsPerScope = [];
  const constantErrorsPerScope = [];
  const visibleDeclarationsInExtractedRange = [];
  const exposedVariableSymbolSet = /* @__PURE__ */ new Map();
  const exposedVariableDeclarations = [];
  let firstExposedNonVariableDeclaration;
  const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : void 0;
  let expressionDiagnostic;
  if (expression === void 0) {
    const statements = targetRange.range;
    const start = first(statements).getStart();
    const end = last(statements).end;
    expressionDiagnostic = createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected);
  } else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) {
    expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType);
  }
  for (const scope of scopes) {
    usagesPerScope.push({ usages: /* @__PURE__ */ new Map(), typeParameterUsages: /* @__PURE__ */ new Map(), substitutions: /* @__PURE__ */ new Map() });
    substitutionsPerScope.push(/* @__PURE__ */ new Map());
    functionErrorsPerScope.push([]);
    const constantErrors = [];
    if (expressionDiagnostic) {
      constantErrors.push(expressionDiagnostic);
    }
    if (isClassLike(scope) && isInJSFile(scope)) {
      constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass));
    }
    if (isArrowFunction(scope) && !isBlock(scope.body)) {
      constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction));
    }
    constantErrorsPerScope.push(constantErrors);
  }
  const seenUsages = /* @__PURE__ */ new Map();
  const target = isReadonlyArray(targetRange.range) ? factory.createBlock(targetRange.range) : targetRange.range;
  const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range;
  const inGenericContext = isInGenericContext(unmodifiedNode);
  collectUsages(target);
  if (inGenericContext && !isReadonlyArray(targetRange.range) && !isJsxAttribute(targetRange.range)) {
    const contextualType = checker.getContextualType(targetRange.range);
    recordTypeParameterUsages(contextualType);
  }
  if (allTypeParameterUsages.size > 0) {
    const seenTypeParameterUsages = /* @__PURE__ */ new Map();
    let i = 0;
    for (let curr = unmodifiedNode; curr !== void 0 && i < scopes.length; curr = curr.parent) {
      if (curr === scopes[i]) {
        seenTypeParameterUsages.forEach((typeParameter, id) => {
          usagesPerScope[i].typeParameterUsages.set(id, typeParameter);
        });
        i++;
      }
      if (isDeclarationWithTypeParameters(curr)) {
        for (const typeParameterDecl of getEffectiveTypeParameterDeclarations(curr)) {
          const typeParameter = checker.getTypeAtLocation(typeParameterDecl);
          if (allTypeParameterUsages.has(typeParameter.id.toString())) {
            seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter);
          }
        }
      }
    }
    Debug.assert(i === scopes.length, "Should have iterated all scopes");
  }
  if (visibleDeclarationsInExtractedRange.length) {
    const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : getEnclosingBlockScopeContainer(scopes[0]);
    forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
  }
  for (let i = 0; i < scopes.length; i++) {
    const scopeUsages = usagesPerScope[i];
    if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) {
      const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range;
      constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes));
    }
    if (targetRange.facts & 16 /* UsesThisInFunction */ && isClassLike(scopes[i])) {
      functionErrorsPerScope[i].push(createDiagnosticForNode(targetRange.thisNode, Messages.cannotExtractFunctionsContainingThisToMethod));
    }
    let hasWrite = false;
    let readonlyClassPropertyWrite;
    usagesPerScope[i].usages.forEach((value) => {
      if (value.usage === 2 /* Write */) {
        hasWrite = true;
        if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && hasEffectiveModifier(value.symbol.valueDeclaration, 8 /* Readonly */)) {
          readonlyClassPropertyWrite = value.symbol.valueDeclaration;
        }
      }
    });
    Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted");
    if (hasWrite && !isReadonlyArray(targetRange.range)) {
      const diag2 = createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression);
      functionErrorsPerScope[i].push(diag2);
      constantErrorsPerScope[i].push(diag2);
    } else if (readonlyClassPropertyWrite && i > 0) {
      const diag2 = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor);
      functionErrorsPerScope[i].push(diag2);
      constantErrorsPerScope[i].push(diag2);
    } else if (firstExposedNonVariableDeclaration) {
      const diag2 = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity);
      functionErrorsPerScope[i].push(diag2);
      constantErrorsPerScope[i].push(diag2);
    }
  }
  return { target, usagesPerScope, functionErrorsPerScope, constantErrorsPerScope, exposedVariableDeclarations };
  function isInGenericContext(node) {
    return !!findAncestor(node, (n) => isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0);
  }
  function recordTypeParameterUsages(type) {
    const symbolWalker = checker.getSymbolWalker(() => (cancellationToken.throwIfCancellationRequested(), true));
    const { visitedTypes } = symbolWalker.walkType(type);
    for (const visitedType of visitedTypes) {
      if (visitedType.isTypeParameter()) {
        allTypeParameterUsages.set(visitedType.id.toString(), visitedType);
      }
    }
  }
  function collectUsages(node, valueUsage = 1 /* Read */) {
    if (inGenericContext) {
      const type = checker.getTypeAtLocation(node);
      recordTypeParameterUsages(type);
    }
    if (isDeclaration(node) && node.symbol) {
      visibleDeclarationsInExtractedRange.push(node);
    }
    if (isAssignmentExpression(node)) {
      collectUsages(node.left, 2 /* Write */);
      collectUsages(node.right);
    } else if (isUnaryExpressionWithWrite(node)) {
      collectUsages(node.operand, 2 /* Write */);
    } else if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) {
      forEachChild(node, collectUsages);
    } else if (isIdentifier(node)) {
      if (!node.parent) {
        return;
      }
      if (isQualifiedName(node.parent) && node !== node.parent.left) {
        return;
      }
      if (isPropertyAccessExpression(node.parent) && node !== node.parent.expression) {
        return;
      }
      recordUsage(
        node,
        valueUsage,
        /*isTypeNode*/
        isPartOfTypeNode(node)
      );
    } else {
      forEachChild(node, collectUsages);
    }
  }
  function recordUsage(n, usage, isTypeNode2) {
    const symbolId = recordUsagebySymbol(n, usage, isTypeNode2);
    if (symbolId) {
      for (let i = 0; i < scopes.length; i++) {
        const substitution = substitutionsPerScope[i].get(symbolId);
        if (substitution) {
          usagesPerScope[i].substitutions.set(getNodeId(n).toString(), substitution);
        }
      }
    }
  }
  function recordUsagebySymbol(identifier, usage, isTypeName) {
    const symbol = getSymbolReferencedByIdentifier(identifier);
    if (!symbol) {
      return void 0;
    }
    const symbolId = getSymbolId(symbol).toString();
    const lastUsage = seenUsages.get(symbolId);
    if (lastUsage && lastUsage >= usage) {
      return symbolId;
    }
    seenUsages.set(symbolId, usage);
    if (lastUsage) {
      for (const perScope of usagesPerScope) {
        const prevEntry = perScope.usages.get(identifier.text);
        if (prevEntry) {
          perScope.usages.set(identifier.text, { usage, symbol, node: identifier });
        }
      }
      return symbolId;
    }
    const decls = symbol.getDeclarations();
    const declInFile = decls && find(decls, (d) => d.getSourceFile() === sourceFile);
    if (!declInFile) {
      return void 0;
    }
    if (rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) {
      return void 0;
    }
    if (targetRange.facts & 2 /* IsGenerator */ && usage === 2 /* Write */) {
      const diag2 = createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators);
      for (const errors of functionErrorsPerScope) {
        errors.push(diag2);
      }
      for (const errors of constantErrorsPerScope) {
        errors.push(diag2);
      }
    }
    for (let i = 0; i < scopes.length; i++) {
      const scope = scopes[i];
      const resolvedSymbol = checker.resolveName(
        symbol.name,
        scope,
        symbol.flags,
        /*excludeGlobals*/
        false
      );
      if (resolvedSymbol === symbol) {
        continue;
      }
      if (!substitutionsPerScope[i].has(symbolId)) {
        const substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName);
        if (substitution) {
          substitutionsPerScope[i].set(symbolId, substitution);
        } else if (isTypeName) {
          if (!(symbol.flags & 262144 /* TypeParameter */)) {
            const diag2 = createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope);
            functionErrorsPerScope[i].push(diag2);
            constantErrorsPerScope[i].push(diag2);
          }
        } else {
          usagesPerScope[i].usages.set(identifier.text, { usage, symbol, node: identifier });
        }
      }
    }
    return symbolId;
  }
  function checkForUsedDeclarations(node) {
    if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.includes(node)) {
      return;
    }
    const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node);
    if (sym) {
      const decl = find(visibleDeclarationsInExtractedRange, (d) => d.symbol === sym);
      if (decl) {
        if (isVariableDeclaration(decl)) {
          const idString = decl.symbol.id.toString();
          if (!exposedVariableSymbolSet.has(idString)) {
            exposedVariableDeclarations.push(decl);
            exposedVariableSymbolSet.set(idString, true);
          }
        } else {
          firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl;
        }
      }
    }
    forEachChild(node, checkForUsedDeclarations);
  }
  function getSymbolReferencedByIdentifier(identifier) {
    return identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier ? checker.getShorthandAssignmentValueSymbol(identifier.parent) : checker.getSymbolAtLocation(identifier);
  }
  function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode2) {
    if (!symbol) {
      return void 0;
    }
    const decls = symbol.getDeclarations();
    if (decls && decls.some((d) => d.parent === scopeDecl)) {
      return factory.createIdentifier(symbol.name);
    }
    const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode2);
    if (prefix === void 0) {
      return void 0;
    }
    return isTypeNode2 ? factory.createQualifiedName(prefix, factory.createIdentifier(symbol.name)) : factory.createPropertyAccessExpression(prefix, symbol.name);
  }
}
function getExtractableParent(node) {
  return findAncestor(node, (node2) => node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent));
}
function isExtractableExpression(node) {
  const { parent: parent2 } = node;
  switch (parent2.kind) {
    case 306 /* EnumMember */:
      return false;
  }
  switch (node.kind) {
    case 11 /* StringLiteral */:
      return parent2.kind !== 272 /* ImportDeclaration */ && parent2.kind !== 276 /* ImportSpecifier */;
    case 230 /* SpreadElement */:
    case 206 /* ObjectBindingPattern */:
    case 208 /* BindingElement */:
      return false;
    case 80 /* Identifier */:
      return parent2.kind !== 208 /* BindingElement */ && parent2.kind !== 276 /* ImportSpecifier */ && parent2.kind !== 281 /* ExportSpecifier */;
  }
  return true;
}
function isInJSXContent(node) {
  return isStringLiteralJsxAttribute(node) || (isJsxElement(node) || isJsxSelfClosingElement(node) || isJsxFragment(node)) && (isJsxElement(node.parent) || isJsxFragment(node.parent));
}
function isStringLiteralJsxAttribute(node) {
  return isStringLiteral(node) && node.parent && isJsxAttribute(node.parent);
}

// src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts
var ts_refactor_generateGetAccessorAndSetAccessor_exports = {};

// src/services/refactors/generateGetAccessorAndSetAccessor.ts
var actionName = "Generate 'get' and 'set' accessors";
var actionDescription = getLocaleSpecificMessage(Diagnostics.Generate_get_and_set_accessors);
var generateGetSetAction = {
  name: actionName,
  description: actionDescription,
  kind: "refactor.rewrite.property.generateAccessors"
};
registerRefactor(actionName, {
  kinds: [generateGetSetAction.kind],
  getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName2) {
    if (!context.endPosition) return void 0;
    const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition);
    Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info");
    const edits = ts_codefix_exports.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName2);
    if (!edits) return void 0;
    const renameFilename = context.file.fileName;
    const nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName;
    const renameLocationOffset = isIdentifier(nameNeedRename) ? 0 : -1;
    const renameLocation = renameLocationOffset + getRenameLocation(
      edits,
      renameFilename,
      nameNeedRename.text,
      /*preferLastLocation*/
      isParameter(info.declaration)
    );
    return { renameFilename, renameLocation, edits };
  },
  getAvailableActions(context) {
    if (!context.endPosition) return emptyArray;
    const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked");
    if (!info) return emptyArray;
    if (!isRefactorErrorInfo(info)) {
      return [{
        name: actionName,
        description: actionDescription,
        actions: [generateGetSetAction]
      }];
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return [{
        name: actionName,
        description: actionDescription,
        actions: [{ ...generateGetSetAction, notApplicableReason: info.error }]
      }];
    }
    return emptyArray;
  }
});

// src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts
var ts_refactor_inferFunctionReturnType_exports = {};

// src/services/refactors/inferFunctionReturnType.ts
var refactorName13 = "Infer function return type";
var refactorDescription7 = getLocaleSpecificMessage(Diagnostics.Infer_function_return_type);
var inferReturnTypeAction = {
  name: refactorName13,
  description: refactorDescription7,
  kind: "refactor.rewrite.function.returnType"
};
registerRefactor(refactorName13, {
  kinds: [inferReturnTypeAction.kind],
  getEditsForAction: getRefactorEditsToInferReturnType,
  getAvailableActions: getRefactorActionsToInferReturnType
});
function getRefactorEditsToInferReturnType(context) {
  const info = getInfo4(context);
  if (info && !isRefactorErrorInfo(info)) {
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange7(context.file, t, info.declaration, info.returnTypeNode));
    return { renameFilename: void 0, renameLocation: void 0, edits };
  }
  return void 0;
}
function getRefactorActionsToInferReturnType(context) {
  const info = getInfo4(context);
  if (!info) return emptyArray;
  if (!isRefactorErrorInfo(info)) {
    return [{
      name: refactorName13,
      description: refactorDescription7,
      actions: [inferReturnTypeAction]
    }];
  }
  if (context.preferences.provideRefactorNotApplicableReason) {
    return [{
      name: refactorName13,
      description: refactorDescription7,
      actions: [{ ...inferReturnTypeAction, notApplicableReason: info.error }]
    }];
  }
  return emptyArray;
}
function doChange7(sourceFile, changes, declaration, typeNode) {
  const closeParen = findChildOfKind(declaration, 22 /* CloseParenToken */, sourceFile);
  const needParens = isArrowFunction(declaration) && closeParen === void 0;
  const endNode2 = needParens ? first(declaration.parameters) : closeParen;
  if (endNode2) {
    if (needParens) {
      changes.insertNodeBefore(sourceFile, endNode2, factory.createToken(21 /* OpenParenToken */));
      changes.insertNodeAfter(sourceFile, endNode2, factory.createToken(22 /* CloseParenToken */));
    }
    changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { prefix: ": " });
  }
}
function getInfo4(context) {
  if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) return;
  const token = getTouchingPropertyName(context.file, context.startPosition);
  const declaration = findAncestor(token, (n) => isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n));
  if (!declaration || !declaration.body || declaration.type) {
    return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) };
  }
  const typeChecker = context.program.getTypeChecker();
  let returnType;
  if (typeChecker.isImplementationOfOverload(declaration)) {
    const signatures = typeChecker.getTypeAtLocation(declaration).getCallSignatures();
    if (signatures.length > 1) {
      returnType = typeChecker.getUnionType(mapDefined(signatures, (s) => s.getReturnType()));
    }
  }
  if (!returnType) {
    const signature = typeChecker.getSignatureFromDeclaration(declaration);
    if (signature) {
      const typePredicate = typeChecker.getTypePredicateOfSignature(signature);
      if (typePredicate && typePredicate.type) {
        const typePredicateTypeNode = typeChecker.typePredicateToTypePredicateNode(typePredicate, declaration, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */);
        if (typePredicateTypeNode) {
          return { declaration, returnTypeNode: typePredicateTypeNode };
        }
      } else {
        returnType = typeChecker.getReturnTypeOfSignature(signature);
      }
    }
  }
  if (!returnType) {
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) };
  }
  const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */);
  if (returnTypeNode) {
    return { declaration, returnTypeNode };
  }
}
function isConvertibleDeclaration(node) {
  switch (node.kind) {
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
    case 174 /* MethodDeclaration */:
      return true;
    default:
      return false;
  }
}

// src/services/classifier2020.ts
var TokenEncodingConsts = /* @__PURE__ */ ((TokenEncodingConsts2) => {
  TokenEncodingConsts2[TokenEncodingConsts2["typeOffset"] = 8] = "typeOffset";
  TokenEncodingConsts2[TokenEncodingConsts2["modifierMask"] = 255] = "modifierMask";
  return TokenEncodingConsts2;
})(TokenEncodingConsts || {});
var TokenType = /* @__PURE__ */ ((TokenType2) => {
  TokenType2[TokenType2["class"] = 0] = "class";
  TokenType2[TokenType2["enum"] = 1] = "enum";
  TokenType2[TokenType2["interface"] = 2] = "interface";
  TokenType2[TokenType2["namespace"] = 3] = "namespace";
  TokenType2[TokenType2["typeParameter"] = 4] = "typeParameter";
  TokenType2[TokenType2["type"] = 5] = "type";
  TokenType2[TokenType2["parameter"] = 6] = "parameter";
  TokenType2[TokenType2["variable"] = 7] = "variable";
  TokenType2[TokenType2["enumMember"] = 8] = "enumMember";
  TokenType2[TokenType2["property"] = 9] = "property";
  TokenType2[TokenType2["function"] = 10] = "function";
  TokenType2[TokenType2["member"] = 11] = "member";
  return TokenType2;
})(TokenType || {});
var TokenModifier = /* @__PURE__ */ ((TokenModifier2) => {
  TokenModifier2[TokenModifier2["declaration"] = 0] = "declaration";
  TokenModifier2[TokenModifier2["static"] = 1] = "static";
  TokenModifier2[TokenModifier2["async"] = 2] = "async";
  TokenModifier2[TokenModifier2["readonly"] = 3] = "readonly";
  TokenModifier2[TokenModifier2["defaultLibrary"] = 4] = "defaultLibrary";
  TokenModifier2[TokenModifier2["local"] = 5] = "local";
  return TokenModifier2;
})(TokenModifier || {});
function getSemanticClassifications2(program, cancellationToken, sourceFile, span) {
  const classifications = getEncodedSemanticClassifications2(program, cancellationToken, sourceFile, span);
  Debug.assert(classifications.spans.length % 3 === 0);
  const dense = classifications.spans;
  const result = [];
  for (let i = 0; i < dense.length; i += 3) {
    result.push({
      textSpan: createTextSpan(dense[i], dense[i + 1]),
      classificationType: dense[i + 2]
    });
  }
  return result;
}
function getEncodedSemanticClassifications2(program, cancellationToken, sourceFile, span) {
  return {
    spans: getSemanticTokens(program, sourceFile, span, cancellationToken),
    endOfLineState: 0 /* None */
  };
}
function getSemanticTokens(program, sourceFile, span, cancellationToken) {
  const resultTokens = [];
  const collector = (node, typeIdx, modifierSet) => {
    resultTokens.push(node.getStart(sourceFile), node.getWidth(sourceFile), (typeIdx + 1 << 8 /* typeOffset */) + modifierSet);
  };
  if (program && sourceFile) {
    collectTokens(program, sourceFile, span, collector, cancellationToken);
  }
  return resultTokens;
}
function collectTokens(program, sourceFile, span, collector, cancellationToken) {
  const typeChecker = program.getTypeChecker();
  let inJSXElement = false;
  function visit(node) {
    switch (node.kind) {
      case 267 /* ModuleDeclaration */:
      case 263 /* ClassDeclaration */:
      case 264 /* InterfaceDeclaration */:
      case 262 /* FunctionDeclaration */:
      case 231 /* ClassExpression */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
        cancellationToken.throwIfCancellationRequested();
    }
    if (!node || !textSpanIntersectsWith(span, node.pos, node.getFullWidth()) || node.getFullWidth() === 0) {
      return;
    }
    const prevInJSXElement = inJSXElement;
    if (isJsxElement(node) || isJsxSelfClosingElement(node)) {
      inJSXElement = true;
    }
    if (isJsxExpression(node)) {
      inJSXElement = false;
    }
    if (isIdentifier(node) && !inJSXElement && !inImportClause(node) && !isInfinityOrNaNString(node.escapedText)) {
      let symbol = typeChecker.getSymbolAtLocation(node);
      if (symbol) {
        if (symbol.flags & 2097152 /* Alias */) {
          symbol = typeChecker.getAliasedSymbol(symbol);
        }
        let typeIdx = classifySymbol2(symbol, getMeaningFromLocation(node));
        if (typeIdx !== void 0) {
          let modifierSet = 0;
          if (node.parent) {
            const parentIsDeclaration = isBindingElement(node.parent) || tokenFromDeclarationMapping.get(node.parent.kind) === typeIdx;
            if (parentIsDeclaration && node.parent.name === node) {
              modifierSet = 1 << 0 /* declaration */;
            }
          }
          if (typeIdx === 6 /* parameter */ && isRightSideOfQualifiedNameOrPropertyAccess2(node)) {
            typeIdx = 9 /* property */;
          }
          typeIdx = reclassifyByType(typeChecker, node, typeIdx);
          const decl = symbol.valueDeclaration;
          if (decl) {
            const modifiers = getCombinedModifierFlags(decl);
            const nodeFlags = getCombinedNodeFlags(decl);
            if (modifiers & 256 /* Static */) {
              modifierSet |= 1 << 1 /* static */;
            }
            if (modifiers & 1024 /* Async */) {
              modifierSet |= 1 << 2 /* async */;
            }
            if (typeIdx !== 0 /* class */ && typeIdx !== 2 /* interface */) {
              if (modifiers & 8 /* Readonly */ || nodeFlags & 2 /* Const */ || symbol.getFlags() & 8 /* EnumMember */) {
                modifierSet |= 1 << 3 /* readonly */;
              }
            }
            if ((typeIdx === 7 /* variable */ || typeIdx === 10 /* function */) && isLocalDeclaration(decl, sourceFile)) {
              modifierSet |= 1 << 5 /* local */;
            }
            if (program.isSourceFileDefaultLibrary(decl.getSourceFile())) {
              modifierSet |= 1 << 4 /* defaultLibrary */;
            }
          } else if (symbol.declarations && symbol.declarations.some((d) => program.isSourceFileDefaultLibrary(d.getSourceFile()))) {
            modifierSet |= 1 << 4 /* defaultLibrary */;
          }
          collector(node, typeIdx, modifierSet);
        }
      }
    }
    forEachChild(node, visit);
    inJSXElement = prevInJSXElement;
  }
  visit(sourceFile);
}
function classifySymbol2(symbol, meaning) {
  const flags = symbol.getFlags();
  if (flags & 32 /* Class */) {
    return 0 /* class */;
  } else if (flags & 384 /* Enum */) {
    return 1 /* enum */;
  } else if (flags & 524288 /* TypeAlias */) {
    return 5 /* type */;
  } else if (flags & 64 /* Interface */) {
    if (meaning & 2 /* Type */) {
      return 2 /* interface */;
    }
  } else if (flags & 262144 /* TypeParameter */) {
    return 4 /* typeParameter */;
  }
  let decl = symbol.valueDeclaration || symbol.declarations && symbol.declarations[0];
  if (decl && isBindingElement(decl)) {
    decl = getDeclarationForBindingElement(decl);
  }
  return decl && tokenFromDeclarationMapping.get(decl.kind);
}
function reclassifyByType(typeChecker, node, typeIdx) {
  if (typeIdx === 7 /* variable */ || typeIdx === 9 /* property */ || typeIdx === 6 /* parameter */) {
    const type = typeChecker.getTypeAtLocation(node);
    if (type) {
      const test = (condition) => {
        return condition(type) || type.isUnion() && type.types.some(condition);
      };
      if (typeIdx !== 6 /* parameter */ && test((t) => t.getConstructSignatures().length > 0)) {
        return 0 /* class */;
      }
      if (test((t) => t.getCallSignatures().length > 0) && !test((t) => t.getProperties().length > 0) || isExpressionInCallExpression(node)) {
        return typeIdx === 9 /* property */ ? 11 /* member */ : 10 /* function */;
      }
    }
  }
  return typeIdx;
}
function isLocalDeclaration(decl, sourceFile) {
  if (isBindingElement(decl)) {
    decl = getDeclarationForBindingElement(decl);
  }
  if (isVariableDeclaration(decl)) {
    return (!isSourceFile(decl.parent.parent.parent) || isCatchClause(decl.parent)) && decl.getSourceFile() === sourceFile;
  } else if (isFunctionDeclaration(decl)) {
    return !isSourceFile(decl.parent) && decl.getSourceFile() === sourceFile;
  }
  return false;
}
function getDeclarationForBindingElement(element) {
  while (true) {
    if (isBindingElement(element.parent.parent)) {
      element = element.parent.parent;
    } else {
      return element.parent.parent;
    }
  }
}
function inImportClause(node) {
  const parent2 = node.parent;
  return parent2 && (isImportClause(parent2) || isImportSpecifier(parent2) || isNamespaceImport(parent2));
}
function isExpressionInCallExpression(node) {
  while (isRightSideOfQualifiedNameOrPropertyAccess2(node)) {
    node = node.parent;
  }
  return isCallExpression(node.parent) && node.parent.expression === node;
}
function isRightSideOfQualifiedNameOrPropertyAccess2(node) {
  return isQualifiedName(node.parent) && node.parent.right === node || isPropertyAccessExpression(node.parent) && node.parent.name === node;
}
var tokenFromDeclarationMapping = /* @__PURE__ */ new Map([
  [260 /* VariableDeclaration */, 7 /* variable */],
  [169 /* Parameter */, 6 /* parameter */],
  [172 /* PropertyDeclaration */, 9 /* property */],
  [267 /* ModuleDeclaration */, 3 /* namespace */],
  [266 /* EnumDeclaration */, 1 /* enum */],
  [306 /* EnumMember */, 8 /* enumMember */],
  [263 /* ClassDeclaration */, 0 /* class */],
  [174 /* MethodDeclaration */, 11 /* member */],
  [262 /* FunctionDeclaration */, 10 /* function */],
  [218 /* FunctionExpression */, 10 /* function */],
  [173 /* MethodSignature */, 11 /* member */],
  [177 /* GetAccessor */, 9 /* property */],
  [178 /* SetAccessor */, 9 /* property */],
  [171 /* PropertySignature */, 9 /* property */],
  [264 /* InterfaceDeclaration */, 2 /* interface */],
  [265 /* TypeAliasDeclaration */, 5 /* type */],
  [168 /* TypeParameter */, 4 /* typeParameter */],
  [303 /* PropertyAssignment */, 9 /* property */],
  [304 /* ShorthandPropertyAssignment */, 9 /* property */]
]);

// src/services/services.ts
var servicesVersion = "0.8";
function createNode(kind, pos, end, parent2) {
  const node = isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 80 /* Identifier */ ? new IdentifierObject(80 /* Identifier */, pos, end) : kind === 81 /* PrivateIdentifier */ ? new PrivateIdentifierObject(81 /* PrivateIdentifier */, pos, end) : new TokenObject(kind, pos, end);
  node.parent = parent2;
  node.flags = parent2.flags & 101441536 /* ContextFlags */;
  return node;
}
var NodeObject = class {
  constructor(kind, pos, end) {
    this.pos = pos;
    this.end = end;
    this.kind = kind;
    this.id = 0;
    this.flags = 0 /* None */;
    this.modifierFlagsCache = 0 /* None */;
    this.transformFlags = 0 /* None */;
    this.parent = void 0;
    this.original = void 0;
    this.emitNode = void 0;
  }
  assertHasRealPosition(message) {
    Debug.assert(!positionIsSynthesized(this.pos) && !positionIsSynthesized(this.end), message || "Node must have a real position for this operation");
  }
  getSourceFile() {
    return getSourceFileOfNode(this);
  }
  getStart(sourceFile, includeJsDocComment) {
    this.assertHasRealPosition();
    return getTokenPosOfNode(this, sourceFile, includeJsDocComment);
  }
  getFullStart() {
    this.assertHasRealPosition();
    return this.pos;
  }
  getEnd() {
    this.assertHasRealPosition();
    return this.end;
  }
  getWidth(sourceFile) {
    this.assertHasRealPosition();
    return this.getEnd() - this.getStart(sourceFile);
  }
  getFullWidth() {
    this.assertHasRealPosition();
    return this.end - this.pos;
  }
  getLeadingTriviaWidth(sourceFile) {
    this.assertHasRealPosition();
    return this.getStart(sourceFile) - this.pos;
  }
  getFullText(sourceFile) {
    this.assertHasRealPosition();
    return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
  }
  getText(sourceFile) {
    this.assertHasRealPosition();
    if (!sourceFile) {
      sourceFile = this.getSourceFile();
    }
    return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
  }
  getChildCount(sourceFile) {
    return this.getChildren(sourceFile).length;
  }
  getChildAt(index, sourceFile) {
    return this.getChildren(sourceFile)[index];
  }
  getChildren(sourceFile = getSourceFileOfNode(this)) {
    this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine");
    return getNodeChildren(this, sourceFile) ?? setNodeChildren(this, sourceFile, createChildren(this, sourceFile));
  }
  getFirstToken(sourceFile) {
    this.assertHasRealPosition();
    const children = this.getChildren(sourceFile);
    if (!children.length) {
      return void 0;
    }
    const child = find(children, (kid) => kid.kind < 309 /* FirstJSDocNode */ || kid.kind > 351 /* LastJSDocNode */);
    return child.kind < 166 /* FirstNode */ ? child : child.getFirstToken(sourceFile);
  }
  getLastToken(sourceFile) {
    this.assertHasRealPosition();
    const children = this.getChildren(sourceFile);
    const child = lastOrUndefined(children);
    if (!child) {
      return void 0;
    }
    return child.kind < 166 /* FirstNode */ ? child : child.getLastToken(sourceFile);
  }
  forEachChild(cbNode, cbNodeArray) {
    return forEachChild(this, cbNode, cbNodeArray);
  }
};
function createChildren(node, sourceFile) {
  const children = [];
  if (isJSDocCommentContainingNode(node)) {
    node.forEachChild((child) => {
      children.push(child);
    });
    return children;
  }
  scanner.setText((sourceFile || node.getSourceFile()).text);
  let pos = node.pos;
  const processNode = (child) => {
    addSyntheticNodes(children, pos, child.pos, node);
    children.push(child);
    pos = child.end;
  };
  const processNodes = (nodes) => {
    addSyntheticNodes(children, pos, nodes.pos, node);
    children.push(createSyntaxList(nodes, node));
    pos = nodes.end;
  };
  forEach(node.jsDoc, processNode);
  pos = node.pos;
  node.forEachChild(processNode, processNodes);
  addSyntheticNodes(children, pos, node.end, node);
  scanner.setText(void 0);
  return children;
}
function addSyntheticNodes(nodes, pos, end, parent2) {
  scanner.resetTokenState(pos);
  while (pos < end) {
    const token = scanner.scan();
    const textPos = scanner.getTokenEnd();
    if (textPos <= end) {
      if (token === 80 /* Identifier */) {
        if (hasTabstop(parent2)) {
          continue;
        }
        Debug.fail(`Did not expect ${Debug.formatSyntaxKind(parent2.kind)} to have an Identifier in its trivia`);
      }
      nodes.push(createNode(token, pos, textPos, parent2));
    }
    pos = textPos;
    if (token === 1 /* EndOfFileToken */) {
      break;
    }
  }
}
function createSyntaxList(nodes, parent2) {
  const list = createNode(352 /* SyntaxList */, nodes.pos, nodes.end, parent2);
  const children = [];
  let pos = nodes.pos;
  for (const node of nodes) {
    addSyntheticNodes(children, pos, node.pos, parent2);
    children.push(node);
    pos = node.end;
  }
  addSyntheticNodes(children, pos, nodes.end, parent2);
  list._children = children;
  return list;
}
var TokenOrIdentifierObject = class {
  constructor(kind, pos, end) {
    this.pos = pos;
    this.end = end;
    this.kind = kind;
    this.id = 0;
    this.flags = 0 /* None */;
    this.transformFlags = 0 /* None */;
    this.parent = void 0;
    this.emitNode = void 0;
  }
  getSourceFile() {
    return getSourceFileOfNode(this);
  }
  getStart(sourceFile, includeJsDocComment) {
    return getTokenPosOfNode(this, sourceFile, includeJsDocComment);
  }
  getFullStart() {
    return this.pos;
  }
  getEnd() {
    return this.end;
  }
  getWidth(sourceFile) {
    return this.getEnd() - this.getStart(sourceFile);
  }
  getFullWidth() {
    return this.end - this.pos;
  }
  getLeadingTriviaWidth(sourceFile) {
    return this.getStart(sourceFile) - this.pos;
  }
  getFullText(sourceFile) {
    return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
  }
  getText(sourceFile) {
    if (!sourceFile) {
      sourceFile = this.getSourceFile();
    }
    return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
  }
  getChildCount() {
    return this.getChildren().length;
  }
  getChildAt(index) {
    return this.getChildren()[index];
  }
  getChildren() {
    return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || emptyArray : emptyArray;
  }
  getFirstToken() {
    return void 0;
  }
  getLastToken() {
    return void 0;
  }
  forEachChild() {
    return void 0;
  }
};
var SymbolObject = class {
  constructor(flags, name) {
    this.flags = flags;
    this.escapedName = name;
    this.declarations = void 0;
    this.valueDeclaration = void 0;
    this.id = 0;
    this.mergeId = 0;
    this.parent = void 0;
    this.members = void 0;
    this.exports = void 0;
    this.exportSymbol = void 0;
    this.constEnumOnlyModule = void 0;
    this.isReferenced = void 0;
    this.lastAssignmentPos = void 0;
    this.links = void 0;
  }
  getFlags() {
    return this.flags;
  }
  get name() {
    return symbolName(this);
  }
  getEscapedName() {
    return this.escapedName;
  }
  getName() {
    return this.name;
  }
  getDeclarations() {
    return this.declarations;
  }
  getDocumentationComment(checker) {
    if (!this.documentationComment) {
      this.documentationComment = emptyArray;
      if (!this.declarations && isTransientSymbol(this) && this.links.target && isTransientSymbol(this.links.target) && this.links.target.links.tupleLabelDeclaration) {
        const labelDecl = this.links.target.links.tupleLabelDeclaration;
        this.documentationComment = getDocumentationComment([labelDecl], checker);
      } else {
        this.documentationComment = getDocumentationComment(this.declarations, checker);
      }
    }
    return this.documentationComment;
  }
  getContextualDocumentationComment(context, checker) {
    if (context) {
      if (isGetAccessor(context)) {
        if (!this.contextualGetAccessorDocumentationComment) {
          this.contextualGetAccessorDocumentationComment = emptyArray;
          this.contextualGetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isGetAccessor), checker);
        }
        if (length(this.contextualGetAccessorDocumentationComment)) {
          return this.contextualGetAccessorDocumentationComment;
        }
      }
      if (isSetAccessor(context)) {
        if (!this.contextualSetAccessorDocumentationComment) {
          this.contextualSetAccessorDocumentationComment = emptyArray;
          this.contextualSetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isSetAccessor), checker);
        }
        if (length(this.contextualSetAccessorDocumentationComment)) {
          return this.contextualSetAccessorDocumentationComment;
        }
      }
    }
    return this.getDocumentationComment(checker);
  }
  getJsDocTags(checker) {
    if (this.tags === void 0) {
      this.tags = emptyArray;
      this.tags = getJsDocTagsOfDeclarations(this.declarations, checker);
    }
    return this.tags;
  }
  getContextualJsDocTags(context, checker) {
    if (context) {
      if (isGetAccessor(context)) {
        if (!this.contextualGetAccessorTags) {
          this.contextualGetAccessorTags = emptyArray;
          this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isGetAccessor), checker);
        }
        if (length(this.contextualGetAccessorTags)) {
          return this.contextualGetAccessorTags;
        }
      }
      if (isSetAccessor(context)) {
        if (!this.contextualSetAccessorTags) {
          this.contextualSetAccessorTags = emptyArray;
          this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isSetAccessor), checker);
        }
        if (length(this.contextualSetAccessorTags)) {
          return this.contextualSetAccessorTags;
        }
      }
    }
    return this.getJsDocTags(checker);
  }
};
var TokenObject = class extends TokenOrIdentifierObject {
  constructor(kind, pos, end) {
    super(kind, pos, end);
  }
};
var IdentifierObject = class extends TokenOrIdentifierObject {
  constructor(kind, pos, end) {
    super(kind, pos, end);
  }
  get text() {
    return idText(this);
  }
};
var PrivateIdentifierObject = class extends TokenOrIdentifierObject {
  constructor(kind, pos, end) {
    super(kind, pos, end);
  }
  get text() {
    return idText(this);
  }
};
var TypeObject = class {
  constructor(checker, flags) {
    this.flags = flags;
    this.checker = checker;
  }
  getFlags() {
    return this.flags;
  }
  getSymbol() {
    return this.symbol;
  }
  getProperties() {
    return this.checker.getPropertiesOfType(this);
  }
  getProperty(propertyName) {
    return this.checker.getPropertyOfType(this, propertyName);
  }
  getApparentProperties() {
    return this.checker.getAugmentedPropertiesOfType(this);
  }
  getCallSignatures() {
    return this.checker.getSignaturesOfType(this, 0 /* Call */);
  }
  getConstructSignatures() {
    return this.checker.getSignaturesOfType(this, 1 /* Construct */);
  }
  getStringIndexType() {
    return this.checker.getIndexTypeOfType(this, 0 /* String */);
  }
  getNumberIndexType() {
    return this.checker.getIndexTypeOfType(this, 1 /* Number */);
  }
  getBaseTypes() {
    return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : void 0;
  }
  isNullableType() {
    return this.checker.isNullableType(this);
  }
  getNonNullableType() {
    return this.checker.getNonNullableType(this);
  }
  getNonOptionalType() {
    return this.checker.getNonOptionalType(this);
  }
  getConstraint() {
    return this.checker.getBaseConstraintOfType(this);
  }
  getDefault() {
    return this.checker.getDefaultFromTypeParameter(this);
  }
  isUnion() {
    return !!(this.flags & 1048576 /* Union */);
  }
  isIntersection() {
    return !!(this.flags & 2097152 /* Intersection */);
  }
  isUnionOrIntersection() {
    return !!(this.flags & 3145728 /* UnionOrIntersection */);
  }
  isLiteral() {
    return !!(this.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */ | 2048 /* BigIntLiteral */));
  }
  isStringLiteral() {
    return !!(this.flags & 128 /* StringLiteral */);
  }
  isNumberLiteral() {
    return !!(this.flags & 256 /* NumberLiteral */);
  }
  isTypeParameter() {
    return !!(this.flags & 262144 /* TypeParameter */);
  }
  isClassOrInterface() {
    return !!(getObjectFlags(this) & 3 /* ClassOrInterface */);
  }
  isClass() {
    return !!(getObjectFlags(this) & 1 /* Class */);
  }
  isIndexType() {
    return !!(this.flags & 4194304 /* Index */);
  }
  /**
   * This polyfills `referenceType.typeArguments` for API consumers
   */
  get typeArguments() {
    if (getObjectFlags(this) & 4 /* Reference */) {
      return this.checker.getTypeArguments(this);
    }
    return void 0;
  }
};
var SignatureObject = class {
  // same
  constructor(checker, flags) {
    this.flags = flags;
    this.checker = checker;
  }
  getDeclaration() {
    return this.declaration;
  }
  getTypeParameters() {
    return this.typeParameters;
  }
  getParameters() {
    return this.parameters;
  }
  getReturnType() {
    return this.checker.getReturnTypeOfSignature(this);
  }
  getTypeParameterAtPosition(pos) {
    const type = this.checker.getParameterType(this, pos);
    if (type.isIndexType() && isThisTypeParameter(type.type)) {
      const constraint = type.type.getConstraint();
      if (constraint) {
        return this.checker.getIndexType(constraint);
      }
    }
    return type;
  }
  getDocumentationComment() {
    return this.documentationComment || (this.documentationComment = getDocumentationComment(singleElementArray(this.declaration), this.checker));
  }
  getJsDocTags() {
    return this.jsDocTags || (this.jsDocTags = getJsDocTagsOfDeclarations(singleElementArray(this.declaration), this.checker));
  }
};
function hasJSDocInheritDocTag(node) {
  return getJSDocTags(node).some((tag) => tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc");
}
function getJsDocTagsOfDeclarations(declarations, checker) {
  if (!declarations) return emptyArray;
  let tags = ts_JsDoc_exports.getJsDocTagsFromDeclarations(declarations, checker);
  if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) {
    const seenSymbols = /* @__PURE__ */ new Set();
    for (const declaration of declarations) {
      const inheritedTags = findBaseOfDeclaration(checker, declaration, (symbol) => {
        var _a;
        if (!seenSymbols.has(symbol)) {
          seenSymbols.add(symbol);
          if (declaration.kind === 177 /* GetAccessor */ || declaration.kind === 178 /* SetAccessor */) {
            return symbol.getContextualJsDocTags(declaration, checker);
          }
          return ((_a = symbol.declarations) == null ? void 0 : _a.length) === 1 ? symbol.getJsDocTags(checker) : void 0;
        }
      });
      if (inheritedTags) {
        tags = [...inheritedTags, ...tags];
      }
    }
  }
  return tags;
}
function getDocumentationComment(declarations, checker) {
  if (!declarations) return emptyArray;
  let doc = ts_JsDoc_exports.getJsDocCommentsFromDeclarations(declarations, checker);
  if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) {
    const seenSymbols = /* @__PURE__ */ new Set();
    for (const declaration of declarations) {
      const inheritedDocs = findBaseOfDeclaration(checker, declaration, (symbol) => {
        if (!seenSymbols.has(symbol)) {
          seenSymbols.add(symbol);
          if (declaration.kind === 177 /* GetAccessor */ || declaration.kind === 178 /* SetAccessor */) {
            return symbol.getContextualDocumentationComment(declaration, checker);
          }
          return symbol.getDocumentationComment(checker);
        }
      });
      if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(lineBreakPart(), doc);
    }
  }
  return doc;
}
function findBaseOfDeclaration(checker, declaration, cb) {
  var _a;
  const classOrInterfaceDeclaration = ((_a = declaration.parent) == null ? void 0 : _a.kind) === 176 /* Constructor */ ? declaration.parent.parent : declaration.parent;
  if (!classOrInterfaceDeclaration) return;
  const isStaticMember = hasStaticModifier(declaration);
  return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), (superTypeNode) => {
    const baseType = checker.getTypeAtLocation(superTypeNode);
    const type = isStaticMember && baseType.symbol ? checker.getTypeOfSymbol(baseType.symbol) : baseType;
    const symbol = checker.getPropertyOfType(type, declaration.symbol.name);
    return symbol ? cb(symbol) : void 0;
  });
}
var SourceFileObject = class extends NodeObject {
  constructor(kind, pos, end) {
    super(kind, pos, end);
  }
  update(newText, textChangeRange) {
    return updateSourceFile(this, newText, textChangeRange);
  }
  getLineAndCharacterOfPosition(position) {
    return getLineAndCharacterOfPosition(this, position);
  }
  getLineStarts() {
    return getLineStarts(this);
  }
  getPositionOfLineAndCharacter(line, character, allowEdits) {
    return computePositionOfLineAndCharacter(getLineStarts(this), line, character, this.text, allowEdits);
  }
  getLineEndOfPosition(pos) {
    const { line } = this.getLineAndCharacterOfPosition(pos);
    const lineStarts = this.getLineStarts();
    let lastCharPos;
    if (line + 1 >= lineStarts.length) {
      lastCharPos = this.getEnd();
    }
    if (!lastCharPos) {
      lastCharPos = lineStarts[line + 1] - 1;
    }
    const fullText = this.getFullText();
    return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos;
  }
  getNamedDeclarations() {
    if (!this.namedDeclarations) {
      this.namedDeclarations = this.computeNamedDeclarations();
    }
    return this.namedDeclarations;
  }
  computeNamedDeclarations() {
    const result = createMultiMap();
    this.forEachChild(visit);
    return result;
    function addDeclaration(declaration) {
      const name = getDeclarationName(declaration);
      if (name) {
        result.add(name, declaration);
      }
    }
    function getDeclarations(name) {
      let declarations = result.get(name);
      if (!declarations) {
        result.set(name, declarations = []);
      }
      return declarations;
    }
    function getDeclarationName(declaration) {
      const name = getNonAssignedNameOfDeclaration(declaration);
      return name && (isComputedPropertyName(name) && isPropertyAccessExpression(name.expression) ? name.expression.name.text : isPropertyName(name) ? getNameFromPropertyName(name) : void 0);
    }
    function visit(node) {
      switch (node.kind) {
        case 262 /* FunctionDeclaration */:
        case 218 /* FunctionExpression */:
        case 174 /* MethodDeclaration */:
        case 173 /* MethodSignature */:
          const functionDeclaration = node;
          const declarationName = getDeclarationName(functionDeclaration);
          if (declarationName) {
            const declarations = getDeclarations(declarationName);
            const lastDeclaration = lastOrUndefined(declarations);
            if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) {
              if (functionDeclaration.body && !lastDeclaration.body) {
                declarations[declarations.length - 1] = functionDeclaration;
              }
            } else {
              declarations.push(functionDeclaration);
            }
          }
          forEachChild(node, visit);
          break;
        case 263 /* ClassDeclaration */:
        case 231 /* ClassExpression */:
        case 264 /* InterfaceDeclaration */:
        case 265 /* TypeAliasDeclaration */:
        case 266 /* EnumDeclaration */:
        case 267 /* ModuleDeclaration */:
        case 271 /* ImportEqualsDeclaration */:
        case 281 /* ExportSpecifier */:
        case 276 /* ImportSpecifier */:
        case 273 /* ImportClause */:
        case 274 /* NamespaceImport */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
        case 187 /* TypeLiteral */:
          addDeclaration(node);
          forEachChild(node, visit);
          break;
        case 169 /* Parameter */:
          if (!hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */)) {
            break;
          }
        // falls through
        case 260 /* VariableDeclaration */:
        case 208 /* BindingElement */: {
          const decl = node;
          if (isBindingPattern(decl.name)) {
            forEachChild(decl.name, visit);
            break;
          }
          if (decl.initializer) {
            visit(decl.initializer);
          }
        }
        // falls through
        case 306 /* EnumMember */:
        case 172 /* PropertyDeclaration */:
        case 171 /* PropertySignature */:
          addDeclaration(node);
          break;
        case 278 /* ExportDeclaration */:
          const exportDeclaration = node;
          if (exportDeclaration.exportClause) {
            if (isNamedExports(exportDeclaration.exportClause)) {
              forEach(exportDeclaration.exportClause.elements, visit);
            } else {
              visit(exportDeclaration.exportClause.name);
            }
          }
          break;
        case 272 /* ImportDeclaration */:
          const importClause = node.importClause;
          if (importClause) {
            if (importClause.name) {
              addDeclaration(importClause.name);
            }
            if (importClause.namedBindings) {
              if (importClause.namedBindings.kind === 274 /* NamespaceImport */) {
                addDeclaration(importClause.namedBindings);
              } else {
                forEach(importClause.namedBindings.elements, visit);
              }
            }
          }
          break;
        case 226 /* BinaryExpression */:
          if (getAssignmentDeclarationKind(node) !== 0 /* None */) {
            addDeclaration(node);
          }
        // falls through
        default:
          forEachChild(node, visit);
      }
    }
  }
};
var SourceMapSourceObject = class {
  constructor(fileName, text, skipTrivia2) {
    this.fileName = fileName;
    this.text = text;
    this.skipTrivia = skipTrivia2 || ((pos) => pos);
  }
  getLineAndCharacterOfPosition(pos) {
    return getLineAndCharacterOfPosition(this, pos);
  }
};
function getServicesObjectAllocator() {
  return {
    getNodeConstructor: () => NodeObject,
    getTokenConstructor: () => TokenObject,
    getIdentifierConstructor: () => IdentifierObject,
    getPrivateIdentifierConstructor: () => PrivateIdentifierObject,
    getSourceFileConstructor: () => SourceFileObject,
    getSymbolConstructor: () => SymbolObject,
    getTypeConstructor: () => TypeObject,
    getSignatureConstructor: () => SignatureObject,
    getSourceMapSourceConstructor: () => SourceMapSourceObject
  };
}
function toEditorSettings(optionsAsMap) {
  let allPropertiesAreCamelCased = true;
  for (const key in optionsAsMap) {
    if (hasProperty(optionsAsMap, key) && !isCamelCase(key)) {
      allPropertiesAreCamelCased = false;
      break;
    }
  }
  if (allPropertiesAreCamelCased) {
    return optionsAsMap;
  }
  const settings = {};
  for (const key in optionsAsMap) {
    if (hasProperty(optionsAsMap, key)) {
      const newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1);
      settings[newKey] = optionsAsMap[key];
    }
  }
  return settings;
}
function isCamelCase(s) {
  return !s.length || s.charAt(0) === s.charAt(0).toLowerCase();
}
function displayPartsToString(displayParts) {
  if (displayParts) {
    return map(displayParts, (displayPart2) => displayPart2.text).join("");
  }
  return "";
}
function getDefaultCompilerOptions2() {
  return {
    target: 1 /* ES5 */,
    jsx: 1 /* Preserve */
  };
}
function getSupportedCodeFixes() {
  return ts_codefix_exports.getSupportedErrorCodes();
}
var SyntaxTreeCache = class {
  constructor(host) {
    this.host = host;
  }
  getCurrentSourceFile(fileName) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const scriptSnapshot = this.host.getScriptSnapshot(fileName);
    if (!scriptSnapshot) {
      throw new Error("Could not find file: '" + fileName + "'.");
    }
    const scriptKind = getScriptKind(fileName, this.host);
    const version2 = this.host.getScriptVersion(fileName);
    let sourceFile;
    if (this.currentFileName !== fileName) {
      const options = {
        languageVersion: 99 /* Latest */,
        impliedNodeFormat: getImpliedNodeFormatForFile(
          toPath(fileName, this.host.getCurrentDirectory(), ((_c = (_b = (_a = this.host).getCompilerHost) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c.getCanonicalFileName) || hostGetCanonicalFileName(this.host)),
          (_h = (_g = (_f = (_e = (_d = this.host).getCompilerHost) == null ? void 0 : _e.call(_d)) == null ? void 0 : _f.getModuleResolutionCache) == null ? void 0 : _g.call(_f)) == null ? void 0 : _h.getPackageJsonInfoCache(),
          this.host,
          this.host.getCompilationSettings()
        ),
        setExternalModuleIndicator: getSetExternalModuleIndicator(this.host.getCompilationSettings()),
        // These files are used to produce syntax-based highlighting, which reads JSDoc, so we must use ParseAll.
        jsDocParsingMode: 0 /* ParseAll */
      };
      sourceFile = createLanguageServiceSourceFile(
        fileName,
        scriptSnapshot,
        options,
        version2,
        /*setNodeParents*/
        true,
        scriptKind
      );
    } else if (this.currentFileVersion !== version2) {
      const editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot);
      sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version2, editRange);
    }
    if (sourceFile) {
      this.currentFileVersion = version2;
      this.currentFileName = fileName;
      this.currentFileScriptSnapshot = scriptSnapshot;
      this.currentSourceFile = sourceFile;
    }
    return this.currentSourceFile;
  }
};
function setSourceFileFields(sourceFile, scriptSnapshot, version2) {
  sourceFile.version = version2;
  sourceFile.scriptSnapshot = scriptSnapshot;
}
function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTargetOrOptions, version2, setNodeParents, scriptKind) {
  const sourceFile = createSourceFile(fileName, getSnapshotText(scriptSnapshot), scriptTargetOrOptions, setNodeParents, scriptKind);
  setSourceFileFields(sourceFile, scriptSnapshot, version2);
  return sourceFile;
}
function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version2, textChangeRange, aggressiveChecks) {
  if (textChangeRange) {
    if (version2 !== sourceFile.version) {
      let newText;
      const prefix = textChangeRange.span.start !== 0 ? sourceFile.text.substr(0, textChangeRange.span.start) : "";
      const suffix = textSpanEnd(textChangeRange.span) !== sourceFile.text.length ? sourceFile.text.substr(textSpanEnd(textChangeRange.span)) : "";
      if (textChangeRange.newLength === 0) {
        newText = prefix && suffix ? prefix + suffix : prefix || suffix;
      } else {
        const changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength);
        newText = prefix && suffix ? prefix + changedText + suffix : prefix ? prefix + changedText : changedText + suffix;
      }
      const newSourceFile = updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
      setSourceFileFields(newSourceFile, scriptSnapshot, version2);
      newSourceFile.nameTable = void 0;
      if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) {
        if (sourceFile.scriptSnapshot.dispose) {
          sourceFile.scriptSnapshot.dispose();
        }
        sourceFile.scriptSnapshot = void 0;
      }
      return newSourceFile;
    }
  }
  const options = {
    languageVersion: sourceFile.languageVersion,
    impliedNodeFormat: sourceFile.impliedNodeFormat,
    setExternalModuleIndicator: sourceFile.setExternalModuleIndicator,
    jsDocParsingMode: sourceFile.jsDocParsingMode
  };
  return createLanguageServiceSourceFile(
    sourceFile.fileName,
    scriptSnapshot,
    options,
    version2,
    /*setNodeParents*/
    true,
    sourceFile.scriptKind
  );
}
var NoopCancellationToken = {
  isCancellationRequested: returnFalse,
  throwIfCancellationRequested: noop
};
var CancellationTokenObject = class {
  constructor(cancellationToken) {
    this.cancellationToken = cancellationToken;
  }
  isCancellationRequested() {
    return this.cancellationToken.isCancellationRequested();
  }
  throwIfCancellationRequested() {
    var _a;
    if (this.isCancellationRequested()) {
      (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "cancellationThrown", { kind: "CancellationTokenObject" });
      throw new OperationCanceledException();
    }
  }
};
var ThrottledCancellationToken = class {
  constructor(hostCancellationToken, throttleWaitMilliseconds = 20) {
    this.hostCancellationToken = hostCancellationToken;
    this.throttleWaitMilliseconds = throttleWaitMilliseconds;
    // Store when we last tried to cancel.  Checking cancellation can be expensive (as we have
    // to marshall over to the host layer).  So we only bother actually checking once enough
    // time has passed.
    this.lastCancellationCheckTime = 0;
  }
  isCancellationRequested() {
    const time = timestamp();
    const duration = Math.abs(time - this.lastCancellationCheckTime);
    if (duration >= this.throttleWaitMilliseconds) {
      this.lastCancellationCheckTime = time;
      return this.hostCancellationToken.isCancellationRequested();
    }
    return false;
  }
  throwIfCancellationRequested() {
    var _a;
    if (this.isCancellationRequested()) {
      (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "cancellationThrown", { kind: "ThrottledCancellationToken" });
      throw new OperationCanceledException();
    }
  }
};
var invalidOperationsInPartialSemanticMode = [
  "getSemanticDiagnostics",
  "getSuggestionDiagnostics",
  "getCompilerOptionsDiagnostics",
  "getSemanticClassifications",
  "getEncodedSemanticClassifications",
  "getCodeFixesAtPosition",
  "getCombinedCodeFix",
  "applyCodeActionCommand",
  "organizeImports",
  "getEditsForFileRename",
  "getEmitOutput",
  "getApplicableRefactors",
  "getEditsForRefactor",
  "prepareCallHierarchy",
  "provideCallHierarchyIncomingCalls",
  "provideCallHierarchyOutgoingCalls",
  "provideInlayHints",
  "getSupportedCodeFixes",
  "getPasteEdits"
];
var invalidOperationsInSyntacticMode = [
  ...invalidOperationsInPartialSemanticMode,
  "getCompletionsAtPosition",
  "getCompletionEntryDetails",
  "getCompletionEntrySymbol",
  "getSignatureHelpItems",
  "getQuickInfoAtPosition",
  "getDefinitionAtPosition",
  "getDefinitionAndBoundSpan",
  "getImplementationAtPosition",
  "getTypeDefinitionAtPosition",
  "getReferencesAtPosition",
  "findReferences",
  "getDocumentHighlights",
  "getNavigateToItems",
  "getRenameInfo",
  "findRenameLocations",
  "getApplicableRefactors",
  "preparePasteEditsForFile"
];
function createLanguageService(host, documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory(), host.jsDocParsingMode), syntaxOnlyOrLanguageServiceMode) {
  var _a;
  let languageServiceMode;
  if (syntaxOnlyOrLanguageServiceMode === void 0) {
    languageServiceMode = 0 /* Semantic */;
  } else if (typeof syntaxOnlyOrLanguageServiceMode === "boolean") {
    languageServiceMode = syntaxOnlyOrLanguageServiceMode ? 2 /* Syntactic */ : 0 /* Semantic */;
  } else {
    languageServiceMode = syntaxOnlyOrLanguageServiceMode;
  }
  const syntaxTreeCache = new SyntaxTreeCache(host);
  let program;
  let lastProjectVersion;
  let lastTypesRootVersion = 0;
  const cancellationToken = host.getCancellationToken ? new CancellationTokenObject(host.getCancellationToken()) : NoopCancellationToken;
  const currentDirectory = host.getCurrentDirectory();
  maybeSetLocalizedDiagnosticMessages((_a = host.getLocalizedDiagnosticMessages) == null ? void 0 : _a.bind(host));
  function log(message) {
    if (host.log) {
      host.log(message);
    }
  }
  const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host);
  const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2);
  const sourceMapper = getSourceMapper({
    useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2,
    getCurrentDirectory: () => currentDirectory,
    getProgram,
    fileExists: maybeBind(host, host.fileExists),
    readFile: maybeBind(host, host.readFile),
    getDocumentPositionMapper: maybeBind(host, host.getDocumentPositionMapper),
    getSourceFileLike: maybeBind(host, host.getSourceFileLike),
    log
  });
  function getValidSourceFile(fileName) {
    const sourceFile = program.getSourceFile(fileName);
    if (!sourceFile) {
      const error2 = new Error(`Could not find source file: '${fileName}'.`);
      error2.ProgramFiles = program.getSourceFiles().map((f) => f.fileName);
      throw error2;
    }
    return sourceFile;
  }
  function synchronizeHostData() {
    if (host.updateFromProject && !host.updateFromProjectInProgress) {
      host.updateFromProject();
    } else {
      synchronizeHostDataWorker();
    }
  }
  function synchronizeHostDataWorker() {
    var _a2, _b, _c;
    Debug.assert(languageServiceMode !== 2 /* Syntactic */);
    if (host.getProjectVersion) {
      const hostProjectVersion = host.getProjectVersion();
      if (hostProjectVersion) {
        if (lastProjectVersion === hostProjectVersion && !((_a2 = host.hasChangedAutomaticTypeDirectiveNames) == null ? void 0 : _a2.call(host))) {
          return;
        }
        lastProjectVersion = hostProjectVersion;
      }
    }
    const typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0;
    if (lastTypesRootVersion !== typeRootsVersion) {
      log("TypeRoots version has changed; provide new program");
      program = void 0;
      lastTypesRootVersion = typeRootsVersion;
    }
    const rootFileNames = host.getScriptFileNames().slice();
    const newSettings = host.getCompilationSettings() || getDefaultCompilerOptions2();
    const hasInvalidatedResolutions = host.hasInvalidatedResolutions || returnFalse;
    const hasInvalidatedLibResolutions = maybeBind(host, host.hasInvalidatedLibResolutions) || returnFalse;
    const hasChangedAutomaticTypeDirectiveNames = maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames);
    const projectReferences = (_b = host.getProjectReferences) == null ? void 0 : _b.call(host);
    let parsedCommandLines;
    let compilerHost = {
      getSourceFile: getOrCreateSourceFile,
      getSourceFileByPath: getOrCreateSourceFileByPath,
      getCancellationToken: () => cancellationToken,
      getCanonicalFileName,
      useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2,
      getNewLine: () => getNewLineCharacter(newSettings),
      getDefaultLibFileName: (options2) => host.getDefaultLibFileName(options2),
      writeFile: noop,
      getCurrentDirectory: () => currentDirectory,
      fileExists: (fileName) => host.fileExists(fileName),
      readFile: (fileName) => host.readFile && host.readFile(fileName),
      getSymlinkCache: maybeBind(host, host.getSymlinkCache),
      realpath: maybeBind(host, host.realpath),
      directoryExists: (directoryName) => {
        return directoryProbablyExists(directoryName, host);
      },
      getDirectories: (path) => {
        return host.getDirectories ? host.getDirectories(path) : [];
      },
      readDirectory: (path, extensions, exclude, include, depth) => {
        Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'");
        return host.readDirectory(path, extensions, exclude, include, depth);
      },
      onReleaseOldSourceFile,
      onReleaseParsedCommandLine,
      hasInvalidatedResolutions,
      hasInvalidatedLibResolutions,
      hasChangedAutomaticTypeDirectiveNames,
      trace: maybeBind(host, host.trace),
      resolveModuleNames: maybeBind(host, host.resolveModuleNames),
      getModuleResolutionCache: maybeBind(host, host.getModuleResolutionCache),
      createHash: maybeBind(host, host.createHash),
      resolveTypeReferenceDirectives: maybeBind(host, host.resolveTypeReferenceDirectives),
      resolveModuleNameLiterals: maybeBind(host, host.resolveModuleNameLiterals),
      resolveTypeReferenceDirectiveReferences: maybeBind(host, host.resolveTypeReferenceDirectiveReferences),
      resolveLibrary: maybeBind(host, host.resolveLibrary),
      useSourceOfProjectReferenceRedirect: maybeBind(host, host.useSourceOfProjectReferenceRedirect),
      getParsedCommandLine,
      jsDocParsingMode: host.jsDocParsingMode,
      getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation)
    };
    const originalGetSourceFile = compilerHost.getSourceFile;
    const { getSourceFileWithCache } = changeCompilerHostLikeToUseCache(
      compilerHost,
      (fileName) => toPath(fileName, currentDirectory, getCanonicalFileName),
      (...args) => originalGetSourceFile.call(compilerHost, ...args)
    );
    compilerHost.getSourceFile = getSourceFileWithCache;
    (_c = host.setCompilerHost) == null ? void 0 : _c.call(host, compilerHost);
    const parseConfigHost = {
      useCaseSensitiveFileNames: useCaseSensitiveFileNames2,
      fileExists: (fileName) => compilerHost.fileExists(fileName),
      readFile: (fileName) => compilerHost.readFile(fileName),
      directoryExists: (f) => compilerHost.directoryExists(f),
      getDirectories: (f) => compilerHost.getDirectories(f),
      realpath: compilerHost.realpath,
      readDirectory: (...args) => compilerHost.readDirectory(...args),
      trace: compilerHost.trace,
      getCurrentDirectory: compilerHost.getCurrentDirectory,
      onUnRecoverableConfigFileDiagnostic: noop
    };
    const documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
    let releasedScriptKinds = /* @__PURE__ */ new Set();
    if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName) => host.getScriptVersion(fileName), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) {
      compilerHost = void 0;
      parsedCommandLines = void 0;
      releasedScriptKinds = void 0;
      return;
    }
    const options = {
      rootNames: rootFileNames,
      options: newSettings,
      host: compilerHost,
      oldProgram: program,
      projectReferences
    };
    program = createProgram(options);
    compilerHost = void 0;
    parsedCommandLines = void 0;
    releasedScriptKinds = void 0;
    sourceMapper.clearCache();
    program.getTypeChecker();
    return;
    function getParsedCommandLine(fileName) {
      const path = toPath(fileName, currentDirectory, getCanonicalFileName);
      const existing = parsedCommandLines == null ? void 0 : parsedCommandLines.get(path);
      if (existing !== void 0) return existing || void 0;
      const result = host.getParsedCommandLine ? host.getParsedCommandLine(fileName) : getParsedCommandLineOfConfigFileUsingSourceFile(fileName);
      (parsedCommandLines || (parsedCommandLines = /* @__PURE__ */ new Map())).set(path, result || false);
      return result;
    }
    function getParsedCommandLineOfConfigFileUsingSourceFile(configFileName) {
      const result = getOrCreateSourceFile(configFileName, 100 /* JSON */);
      if (!result) return void 0;
      result.path = toPath(configFileName, currentDirectory, getCanonicalFileName);
      result.resolvedPath = result.path;
      result.originalFileName = result.fileName;
      return parseJsonSourceFileConfigFileContent(
        result,
        parseConfigHost,
        getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory),
        /*existingOptions*/
        void 0,
        getNormalizedAbsolutePath(configFileName, currentDirectory)
      );
    }
    function onReleaseParsedCommandLine(configFileName, oldResolvedRef, oldOptions) {
      var _a3;
      if (host.getParsedCommandLine) {
        (_a3 = host.onReleaseParsedCommandLine) == null ? void 0 : _a3.call(host, configFileName, oldResolvedRef, oldOptions);
      } else if (oldResolvedRef) {
        releaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions);
      }
    }
    function releaseOldSourceFile(oldSourceFile, oldOptions) {
      const oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions);
      documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat);
    }
    function onReleaseOldSourceFile(oldSourceFile, oldOptions, hasSourceFileByPath, newSourceFileByResolvedPath) {
      var _a3;
      releaseOldSourceFile(oldSourceFile, oldOptions);
      (_a3 = host.onReleaseOldSourceFile) == null ? void 0 : _a3.call(host, oldSourceFile, oldOptions, hasSourceFileByPath, newSourceFileByResolvedPath);
    }
    function getOrCreateSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) {
      return getOrCreateSourceFileByPath(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), languageVersionOrOptions, onError, shouldCreateNewSourceFile);
    }
    function getOrCreateSourceFileByPath(fileName, path, languageVersionOrOptions, _onError, shouldCreateNewSourceFile) {
      Debug.assert(compilerHost, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host.");
      const scriptSnapshot = host.getScriptSnapshot(fileName);
      if (!scriptSnapshot) {
        return void 0;
      }
      const scriptKind = getScriptKind(fileName, host);
      const scriptVersion = host.getScriptVersion(fileName);
      if (!shouldCreateNewSourceFile) {
        const oldSourceFile = program && program.getSourceFileByPath(path);
        if (oldSourceFile) {
          if (scriptKind === oldSourceFile.scriptKind || releasedScriptKinds.has(oldSourceFile.resolvedPath)) {
            return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions);
          } else {
            documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat);
            releasedScriptKinds.add(oldSourceFile.resolvedPath);
          }
        }
      }
      return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions);
    }
  }
  function getProgram() {
    if (languageServiceMode === 2 /* Syntactic */) {
      Debug.assert(program === void 0);
      return void 0;
    }
    synchronizeHostData();
    return program;
  }
  function getAutoImportProvider() {
    var _a2;
    return (_a2 = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a2.call(host);
  }
  function updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans) {
    const checker = program.getTypeChecker();
    const symbol = getSymbolForProgram();
    if (!symbol) return false;
    for (const referencedSymbol of referencedSymbols) {
      for (const ref of referencedSymbol.references) {
        const refNode = getNodeForSpan(ref);
        Debug.assertIsDefined(refNode);
        if (knownSymbolSpans.has(ref) || ts_FindAllReferences_exports.isDeclarationOfSymbol(refNode, symbol)) {
          knownSymbolSpans.add(ref);
          ref.isDefinition = true;
          const mappedSpan = getMappedDocumentSpan(ref, sourceMapper, maybeBind(host, host.fileExists));
          if (mappedSpan) {
            knownSymbolSpans.add(mappedSpan);
          }
        } else {
          ref.isDefinition = false;
        }
      }
    }
    return true;
    function getSymbolForProgram() {
      for (const referencedSymbol of referencedSymbols) {
        for (const ref of referencedSymbol.references) {
          if (knownSymbolSpans.has(ref)) {
            const refNode = getNodeForSpan(ref);
            Debug.assertIsDefined(refNode);
            return checker.getSymbolAtLocation(refNode);
          }
          const mappedSpan = getMappedDocumentSpan(ref, sourceMapper, maybeBind(host, host.fileExists));
          if (mappedSpan && knownSymbolSpans.has(mappedSpan)) {
            const refNode = getNodeForSpan(mappedSpan);
            if (refNode) {
              return checker.getSymbolAtLocation(refNode);
            }
          }
        }
      }
      return void 0;
    }
    function getNodeForSpan(docSpan) {
      const sourceFile = program.getSourceFile(docSpan.fileName);
      if (!sourceFile) return void 0;
      const rawNode = getTouchingPropertyName(sourceFile, docSpan.textSpan.start);
      const adjustedNode = ts_FindAllReferences_exports.Core.getAdjustedNode(rawNode, { use: ts_FindAllReferences_exports.FindReferencesUse.References });
      return adjustedNode;
    }
  }
  function cleanupSemanticCache() {
    if (program) {
      const key = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions());
      forEach(program.getSourceFiles(), (f) => documentRegistry.releaseDocumentWithKey(f.resolvedPath, key, f.scriptKind, f.impliedNodeFormat));
      program = void 0;
    }
  }
  function dispose() {
    cleanupSemanticCache();
    host = void 0;
  }
  function getSyntacticDiagnostics(fileName) {
    synchronizeHostData();
    return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice();
  }
  function getSemanticDiagnostics(fileName) {
    synchronizeHostData();
    const targetSourceFile = getValidSourceFile(fileName);
    const semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken);
    if (!getEmitDeclarations(program.getCompilerOptions())) {
      return semanticDiagnostics.slice();
    }
    const declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
    return [...semanticDiagnostics, ...declarationDiagnostics];
  }
  function getRegionSemanticDiagnostics(fileName, ranges) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const options = program.getCompilerOptions();
    if (skipTypeChecking(sourceFile, options, program) || !canIncludeBindAndCheckDiagnostics(sourceFile, options) || program.getCachedSemanticDiagnostics(sourceFile)) {
      return void 0;
    }
    const nodes = getNodesForRanges(sourceFile, ranges);
    if (!nodes) {
      return void 0;
    }
    const checkedSpans = normalizeSpans(nodes.map((node) => createTextSpanFromBounds(node.getFullStart(), node.getEnd())));
    const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken, nodes);
    return {
      diagnostics: semanticDiagnostics.slice(),
      spans: checkedSpans
    };
  }
  function getNodesForRanges(file, ranges) {
    const nodes = [];
    const spans = normalizeSpans(ranges.map((range) => createTextSpanFromRange(range)));
    for (const span of spans) {
      const nodesForSpan = getNodesForSpan(file, span);
      if (!nodesForSpan) {
        return void 0;
      }
      nodes.push(...nodesForSpan);
    }
    if (!nodes.length) {
      return void 0;
    }
    return nodes;
  }
  function getNodesForSpan(file, span) {
    if (textSpanContainsTextRange(span, file)) {
      return void 0;
    }
    const endToken = findTokenOnLeftOfPosition(file, textSpanEnd(span)) || file;
    const enclosingNode = findAncestor(endToken, (node) => textRangeContainsTextSpan(node, span));
    const nodes = [];
    chooseOverlappingNodes(span, enclosingNode, nodes);
    if (file.end === span.start + span.length) {
      nodes.push(file.endOfFileToken);
    }
    if (some(nodes, isSourceFile)) {
      return void 0;
    }
    return nodes;
  }
  function chooseOverlappingNodes(span, node, result) {
    if (!nodeOverlapsWithSpan(node, span)) {
      return false;
    }
    if (textSpanContainsTextRange(span, node)) {
      addSourceElement(node, result);
      return true;
    }
    if (isBlockLike(node)) {
      return chooseOverlappingBlockLike(span, node, result);
    }
    if (isClassLike(node)) {
      return chooseOverlappingClassLike(span, node, result);
    }
    addSourceElement(node, result);
    return true;
  }
  function nodeOverlapsWithSpan(node, span) {
    const spanEnd = span.start + span.length;
    return node.pos < spanEnd && node.end > span.start;
  }
  function addSourceElement(node, result) {
    while (node.parent && !isSourceElement(node)) {
      node = node.parent;
    }
    result.push(node);
  }
  function chooseOverlappingBlockLike(span, node, result) {
    const childResult = [];
    const stmts = node.statements.filter((stmt) => chooseOverlappingNodes(span, stmt, childResult));
    if (stmts.length === node.statements.length) {
      addSourceElement(node, result);
      return true;
    }
    result.push(...childResult);
    return false;
  }
  function chooseOverlappingClassLike(span, node, result) {
    var _a2, _b, _c;
    const overlaps = (n) => textRangeIntersectsWithTextSpan(n, span);
    if (((_a2 = node.modifiers) == null ? void 0 : _a2.some(overlaps)) || node.name && overlaps(node.name) || ((_b = node.typeParameters) == null ? void 0 : _b.some(overlaps)) || ((_c = node.heritageClauses) == null ? void 0 : _c.some(overlaps))) {
      addSourceElement(node, result);
      return true;
    }
    const childResult = [];
    const members = node.members.filter((member) => chooseOverlappingNodes(span, member, childResult));
    if (members.length === node.members.length) {
      addSourceElement(node, result);
      return true;
    }
    result.push(...childResult);
    return false;
  }
  function getSuggestionDiagnostics(fileName) {
    synchronizeHostData();
    return computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken);
  }
  function getCompilerOptionsDiagnostics() {
    synchronizeHostData();
    return [...program.getOptionsDiagnostics(cancellationToken), ...program.getGlobalDiagnostics(cancellationToken)];
  }
  function getCompletionsAtPosition2(fileName, position, options = emptyOptions, formattingSettings) {
    const fullPreferences = {
      ...identity(options),
      // avoid excess property check
      includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports,
      includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions
    };
    synchronizeHostData();
    return ts_Completions_exports.getCompletionsAtPosition(
      host,
      program,
      log,
      getValidSourceFile(fileName),
      position,
      fullPreferences,
      options.triggerCharacter,
      options.triggerKind,
      cancellationToken,
      formattingSettings && ts_formatting_exports.getFormatContext(formattingSettings, host),
      options.includeSymbol
    );
  }
  function getCompletionEntryDetails2(fileName, position, name, formattingOptions, source, preferences = emptyOptions, data) {
    synchronizeHostData();
    return ts_Completions_exports.getCompletionEntryDetails(
      program,
      log,
      getValidSourceFile(fileName),
      position,
      { name, source, data },
      host,
      formattingOptions && ts_formatting_exports.getFormatContext(formattingOptions, host),
      // TODO: GH#18217
      preferences,
      cancellationToken
    );
  }
  function getCompletionEntrySymbol2(fileName, position, name, source, preferences = emptyOptions) {
    synchronizeHostData();
    return ts_Completions_exports.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name, source }, host, preferences);
  }
  function getQuickInfoAtPosition(fileName, position) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const node = getTouchingPropertyName(sourceFile, position);
    if (node === sourceFile) {
      return void 0;
    }
    const typeChecker = program.getTypeChecker();
    const nodeForQuickInfo = getNodeForQuickInfo(node);
    const symbol = getSymbolAtLocationForQuickInfo(nodeForQuickInfo, typeChecker);
    if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
      const type = shouldGetType(sourceFile, nodeForQuickInfo, position) ? typeChecker.getTypeAtLocation(nodeForQuickInfo) : void 0;
      return type && {
        kind: "" /* unknown */,
        kindModifiers: "" /* none */,
        textSpan: createTextSpanFromNode(nodeForQuickInfo, sourceFile),
        displayParts: typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2) => typeToDisplayParts(typeChecker2, type, getContainerNode(nodeForQuickInfo))),
        documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : void 0,
        tags: type.symbol ? type.symbol.getJsDocTags(typeChecker) : void 0
      };
    }
    const { symbolKind, displayParts, documentation, tags } = typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2) => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker2, symbol, sourceFile, getContainerNode(nodeForQuickInfo), nodeForQuickInfo));
    return {
      kind: symbolKind,
      kindModifiers: ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol),
      textSpan: createTextSpanFromNode(nodeForQuickInfo, sourceFile),
      displayParts,
      documentation,
      tags
    };
  }
  function preparePasteEditsForFile(fileName, copiedTextRange) {
    synchronizeHostData();
    return ts_preparePasteEdits_exports.preparePasteEdits(
      getValidSourceFile(fileName),
      copiedTextRange,
      program.getTypeChecker()
    );
  }
  function getPasteEdits(args, formatOptions) {
    synchronizeHostData();
    return ts_PasteEdits_exports.pasteEditsProvider(
      getValidSourceFile(args.targetFile),
      args.pastedText,
      args.pasteLocations,
      args.copiedFrom ? { file: getValidSourceFile(args.copiedFrom.file), range: args.copiedFrom.range } : void 0,
      host,
      args.preferences,
      ts_formatting_exports.getFormatContext(formatOptions, host),
      cancellationToken
    );
  }
  function getNodeForQuickInfo(node) {
    if (isNewExpression(node.parent) && node.pos === node.parent.pos) {
      return node.parent.expression;
    }
    if (isNamedTupleMember(node.parent) && node.pos === node.parent.pos) {
      return node.parent;
    }
    if (isImportMeta(node.parent) && node.parent.name === node) {
      return node.parent;
    }
    if (isJsxNamespacedName(node.parent)) {
      return node.parent;
    }
    return node;
  }
  function shouldGetType(sourceFile, node, position) {
    switch (node.kind) {
      case 80 /* Identifier */:
        if (node.flags & 16777216 /* JSDoc */ && !isInJSFile(node) && (node.parent.kind === 171 /* PropertySignature */ && node.parent.name === node || findAncestor(node, (n) => n.kind === 169 /* Parameter */))) {
          return false;
        }
        return !isLabelName(node) && !isTagName(node) && !isConstTypeReference(node.parent);
      case 211 /* PropertyAccessExpression */:
      case 166 /* QualifiedName */:
        return !isInComment(sourceFile, position);
      case 110 /* ThisKeyword */:
      case 197 /* ThisType */:
      case 108 /* SuperKeyword */:
      case 202 /* NamedTupleMember */:
        return true;
      case 236 /* MetaProperty */:
        return isImportMeta(node);
      default:
        return false;
    }
  }
  function getDefinitionAtPosition2(fileName, position, searchOtherFilesOnly, stopAtAlias) {
    synchronizeHostData();
    return ts_GoToDefinition_exports.getDefinitionAtPosition(program, getValidSourceFile(fileName), position, searchOtherFilesOnly, stopAtAlias);
  }
  function getDefinitionAndBoundSpan2(fileName, position) {
    synchronizeHostData();
    return ts_GoToDefinition_exports.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position);
  }
  function getTypeDefinitionAtPosition2(fileName, position) {
    synchronizeHostData();
    return ts_GoToDefinition_exports.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position);
  }
  function getImplementationAtPosition(fileName, position) {
    synchronizeHostData();
    return ts_FindAllReferences_exports.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
  }
  function getDocumentHighlights(fileName, position, filesToSearch) {
    const normalizedFileName = normalizePath(fileName);
    Debug.assert(filesToSearch.some((f) => normalizePath(f) === normalizedFileName));
    synchronizeHostData();
    const sourceFilesToSearch = mapDefined(filesToSearch, (fileName2) => program.getSourceFile(fileName2));
    const sourceFile = getValidSourceFile(fileName);
    return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch);
  }
  function findRenameLocations(fileName, position, findInStrings, findInComments, preferences) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position));
    if (!ts_Rename_exports.nodeIsEligibleForRename(node)) return void 0;
    if (isIdentifier(node) && (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) && isIntrinsicJsxName(node.escapedText)) {
      const { openingElement, closingElement } = node.parent.parent;
      return [openingElement, closingElement].map((node2) => {
        const textSpan = createTextSpanFromNode(node2.tagName, sourceFile);
        return {
          fileName: sourceFile.fileName,
          textSpan,
          ...ts_FindAllReferences_exports.toContextSpan(textSpan, sourceFile, node2.parent)
        };
      });
    } else {
      const quotePreference = getQuotePreference(sourceFile, preferences ?? emptyOptions);
      const providePrefixAndSuffixTextForRename = typeof preferences === "boolean" ? preferences : preferences == null ? void 0 : preferences.providePrefixAndSuffixTextForRename;
      return getReferencesWorker2(node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: ts_FindAllReferences_exports.FindReferencesUse.Rename }, (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference));
    }
  }
  function getReferencesAtPosition(fileName, position) {
    synchronizeHostData();
    return getReferencesWorker2(getTouchingPropertyName(getValidSourceFile(fileName), position), position, { use: ts_FindAllReferences_exports.FindReferencesUse.References }, ts_FindAllReferences_exports.toReferenceEntry);
  }
  function getReferencesWorker2(node, position, options, cb) {
    synchronizeHostData();
    const sourceFiles = options && options.use === ts_FindAllReferences_exports.FindReferencesUse.Rename ? program.getSourceFiles().filter((sourceFile) => !program.isSourceFileDefaultLibrary(sourceFile)) : program.getSourceFiles();
    return ts_FindAllReferences_exports.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb);
  }
  function findReferences(fileName, position) {
    synchronizeHostData();
    return ts_FindAllReferences_exports.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
  }
  function getFileReferences(fileName) {
    synchronizeHostData();
    return ts_FindAllReferences_exports.Core.getReferencesForFileName(fileName, program, program.getSourceFiles()).map(ts_FindAllReferences_exports.toReferenceEntry);
  }
  function getNavigateToItems2(searchValue, maxResultCount, fileName, excludeDtsFiles = false, excludeLibFiles = false) {
    synchronizeHostData();
    const sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles();
    return getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles, excludeLibFiles);
  }
  function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const customTransformers = host.getCustomTransformers && host.getCustomTransformers();
    return getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit);
  }
  function getSignatureHelpItems2(fileName, position, { triggerReason } = emptyOptions) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    return ts_SignatureHelp_exports.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken);
  }
  function getNonBoundSourceFile(fileName) {
    return syntaxTreeCache.getCurrentSourceFile(fileName);
  }
  function getNameOrDottedNameSpan(fileName, startPos, _endPos) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const node = getTouchingPropertyName(sourceFile, startPos);
    if (node === sourceFile) {
      return void 0;
    }
    switch (node.kind) {
      case 211 /* PropertyAccessExpression */:
      case 166 /* QualifiedName */:
      case 11 /* StringLiteral */:
      case 97 /* FalseKeyword */:
      case 112 /* TrueKeyword */:
      case 106 /* NullKeyword */:
      case 108 /* SuperKeyword */:
      case 110 /* ThisKeyword */:
      case 197 /* ThisType */:
      case 80 /* Identifier */:
        break;
      // Cant create the text span
      default:
        return void 0;
    }
    let nodeForStartPos = node;
    while (true) {
      if (isRightSideOfPropertyAccess(nodeForStartPos) || isRightSideOfQualifiedName(nodeForStartPos)) {
        nodeForStartPos = nodeForStartPos.parent;
      } else if (isNameOfModuleDeclaration(nodeForStartPos)) {
        if (nodeForStartPos.parent.parent.kind === 267 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) {
          nodeForStartPos = nodeForStartPos.parent.parent.name;
        } else {
          break;
        }
      } else {
        break;
      }
    }
    return createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd());
  }
  function getBreakpointStatementAtPosition(fileName, position) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    return ts_BreakpointResolver_exports.spanInSourceFileAtLocation(sourceFile, position);
  }
  function getNavigationBarItems2(fileName) {
    return getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
  }
  function getNavigationTree2(fileName) {
    return getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
  }
  function getSemanticClassifications3(fileName, span, format) {
    synchronizeHostData();
    const responseFormat = format || "original" /* Original */;
    if (responseFormat === "2020" /* TwentyTwenty */) {
      return getSemanticClassifications2(program, cancellationToken, getValidSourceFile(fileName), span);
    } else {
      return getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
    }
  }
  function getEncodedSemanticClassifications3(fileName, span, format) {
    synchronizeHostData();
    const responseFormat = format || "original" /* Original */;
    if (responseFormat === "original" /* Original */) {
      return getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
    } else {
      return getEncodedSemanticClassifications2(program, cancellationToken, getValidSourceFile(fileName), span);
    }
  }
  function getSyntacticClassifications2(fileName, span) {
    return getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
  }
  function getEncodedSyntacticClassifications2(fileName, span) {
    return getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
  }
  function getOutliningSpans(fileName) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    return ts_OutliningElementsCollector_exports.collectElements(sourceFile, cancellationToken);
  }
  const braceMatching = new Map(Object.entries({
    [19 /* OpenBraceToken */]: 20 /* CloseBraceToken */,
    [21 /* OpenParenToken */]: 22 /* CloseParenToken */,
    [23 /* OpenBracketToken */]: 24 /* CloseBracketToken */,
    [32 /* GreaterThanToken */]: 30 /* LessThanToken */
  }));
  braceMatching.forEach((value, key) => braceMatching.set(value.toString(), Number(key)));
  function getBraceMatchingAtPosition(fileName, position) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const token = getTouchingToken(sourceFile, position);
    const matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : void 0;
    const match = matchKind && findChildOfKind(token.parent, matchKind, sourceFile);
    return match ? [createTextSpanFromNode(token, sourceFile), createTextSpanFromNode(match, sourceFile)].sort((a, b) => a.start - b.start) : emptyArray;
  }
  function getIndentationAtPosition(fileName, position, editorOptions) {
    let start = timestamp();
    const settings = toEditorSettings(editorOptions);
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    log("getIndentationAtPosition: getCurrentSourceFile: " + (timestamp() - start));
    start = timestamp();
    const result = ts_formatting_exports.SmartIndenter.getIndentation(position, sourceFile, settings);
    log("getIndentationAtPosition: computeIndentation  : " + (timestamp() - start));
    return result;
  }
  function getFormattingEditsForRange(fileName, start, end, options) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    return ts_formatting_exports.formatSelection(start, end, sourceFile, ts_formatting_exports.getFormatContext(toEditorSettings(options), host));
  }
  function getFormattingEditsForDocument(fileName, options) {
    return ts_formatting_exports.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts_formatting_exports.getFormatContext(toEditorSettings(options), host));
  }
  function getFormattingEditsAfterKeystroke(fileName, position, key, options) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const formatContext = ts_formatting_exports.getFormatContext(toEditorSettings(options), host);
    if (!isInComment(sourceFile, position)) {
      switch (key) {
        case "{":
          return ts_formatting_exports.formatOnOpeningCurly(position, sourceFile, formatContext);
        case "}":
          return ts_formatting_exports.formatOnClosingCurly(position, sourceFile, formatContext);
        case ";":
          return ts_formatting_exports.formatOnSemicolon(position, sourceFile, formatContext);
        case "\n":
          return ts_formatting_exports.formatOnEnter(position, sourceFile, formatContext);
      }
    }
    return [];
  }
  function getCodeFixesAtPosition(fileName, start, end, errorCodes68, formatOptions, preferences = emptyOptions) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const span = createTextSpanFromBounds(start, end);
    const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host);
    return flatMap(deduplicate(errorCodes68, equateValues, compareValues), (errorCode) => {
      cancellationToken.throwIfCancellationRequested();
      return ts_codefix_exports.getFixes({ errorCode, sourceFile, span, program, host, cancellationToken, formatContext, preferences });
    });
  }
  function getCombinedCodeFix(scope, fixId56, formatOptions, preferences = emptyOptions) {
    synchronizeHostData();
    Debug.assert(scope.type === "file");
    const sourceFile = getValidSourceFile(scope.fileName);
    const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host);
    return ts_codefix_exports.getAllFixes({ fixId: fixId56, sourceFile, program, host, cancellationToken, formatContext, preferences });
  }
  function organizeImports2(args, formatOptions, preferences = emptyOptions) {
    synchronizeHostData();
    Debug.assert(args.type === "file");
    const sourceFile = getValidSourceFile(args.fileName);
    if (containsParseError(sourceFile)) return emptyArray;
    const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host);
    const mode = args.mode ?? (args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : "All" /* All */);
    return ts_OrganizeImports_exports.organizeImports(sourceFile, formatContext, host, program, preferences, mode);
  }
  function getEditsForFileRename2(oldFilePath, newFilePath, formatOptions, preferences = emptyOptions) {
    return getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts_formatting_exports.getFormatContext(formatOptions, host), preferences, sourceMapper);
  }
  function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) {
    const action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName;
    return isArray(action) ? Promise.all(action.map((a) => applySingleCodeActionCommand(a))) : applySingleCodeActionCommand(action);
  }
  function applySingleCodeActionCommand(action) {
    const getPath = (path) => toPath(path, currentDirectory, getCanonicalFileName);
    Debug.assertEqual(action.type, "install package");
    return host.installPackage ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`");
  }
  function getDocCommentTemplateAtPosition2(fileName, position, options, formatOptions) {
    const formatSettings = formatOptions ? ts_formatting_exports.getFormatContext(formatOptions, host).options : void 0;
    return ts_JsDoc_exports.getDocCommentTemplateAtPosition(getNewLineOrDefaultFromHost(host, formatSettings), syntaxTreeCache.getCurrentSourceFile(fileName), position, options);
  }
  function isValidBraceCompletionAtPosition(fileName, position, openingBrace) {
    if (openingBrace === 60 /* lessThan */) {
      return false;
    }
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    if (isInString(sourceFile, position)) {
      return false;
    }
    if (isInsideJsxElementOrAttribute(sourceFile, position)) {
      return openingBrace === 123 /* openBrace */;
    }
    if (isInTemplateString(sourceFile, position)) {
      return false;
    }
    switch (openingBrace) {
      case 39 /* singleQuote */:
      case 34 /* doubleQuote */:
      case 96 /* backtick */:
        return !isInComment(sourceFile, position);
    }
    return true;
  }
  function getJsxClosingTagAtPosition(fileName, position) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const token = findPrecedingToken(position, sourceFile);
    if (!token) return void 0;
    const element = token.kind === 32 /* GreaterThanToken */ && isJsxOpeningElement(token.parent) ? token.parent.parent : isJsxText(token) && isJsxElement(token.parent) ? token.parent : void 0;
    if (element && isUnclosedTag(element)) {
      return { newText: `</${element.openingElement.tagName.getText(sourceFile)}>` };
    }
    const fragment = token.kind === 32 /* GreaterThanToken */ && isJsxOpeningFragment(token.parent) ? token.parent.parent : isJsxText(token) && isJsxFragment(token.parent) ? token.parent : void 0;
    if (fragment && isUnclosedFragment(fragment)) {
      return { newText: "</>" };
    }
  }
  function getLinkedEditingRangeAtPosition(fileName, position) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const token = findPrecedingToken(position, sourceFile);
    if (!token || token.parent.kind === 307 /* SourceFile */) return void 0;
    const jsxTagWordPattern = "[a-zA-Z0-9:\\-\\._$]*";
    if (isJsxFragment(token.parent.parent)) {
      const openFragment = token.parent.parent.openingFragment;
      const closeFragment = token.parent.parent.closingFragment;
      if (containsParseError(openFragment) || containsParseError(closeFragment)) return void 0;
      const openPos = openFragment.getStart(sourceFile) + 1;
      const closePos = closeFragment.getStart(sourceFile) + 2;
      if (position !== openPos && position !== closePos) return void 0;
      return {
        ranges: [{ start: openPos, length: 0 }, { start: closePos, length: 0 }],
        wordPattern: jsxTagWordPattern
      };
    } else {
      const tag = findAncestor(token.parent, (n) => {
        if (isJsxOpeningElement(n) || isJsxClosingElement(n)) {
          return true;
        }
        return false;
      });
      if (!tag) return void 0;
      Debug.assert(isJsxOpeningElement(tag) || isJsxClosingElement(tag), "tag should be opening or closing element");
      const openTag = tag.parent.openingElement;
      const closeTag = tag.parent.closingElement;
      const openTagNameStart = openTag.tagName.getStart(sourceFile);
      const openTagNameEnd = openTag.tagName.end;
      const closeTagNameStart = closeTag.tagName.getStart(sourceFile);
      const closeTagNameEnd = closeTag.tagName.end;
      if (openTagNameStart === openTag.getStart(sourceFile) || closeTagNameStart === closeTag.getStart(sourceFile) || openTagNameEnd === openTag.getEnd() || closeTagNameEnd === closeTag.getEnd()) return void 0;
      if (!(openTagNameStart <= position && position <= openTagNameEnd || closeTagNameStart <= position && position <= closeTagNameEnd)) return void 0;
      const openingTagText = openTag.tagName.getText(sourceFile);
      if (openingTagText !== closeTag.tagName.getText(sourceFile)) return void 0;
      return {
        ranges: [{ start: openTagNameStart, length: openTagNameEnd - openTagNameStart }, { start: closeTagNameStart, length: closeTagNameEnd - closeTagNameStart }],
        wordPattern: jsxTagWordPattern
      };
    }
  }
  function getLinesForRange(sourceFile, textRange) {
    return {
      lineStarts: sourceFile.getLineStarts(),
      firstLine: sourceFile.getLineAndCharacterOfPosition(textRange.pos).line,
      lastLine: sourceFile.getLineAndCharacterOfPosition(textRange.end).line
    };
  }
  function toggleLineComment(fileName, textRange, insertComment) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const textChanges2 = [];
    const { lineStarts, firstLine, lastLine } = getLinesForRange(sourceFile, textRange);
    let isCommenting = insertComment || false;
    let leftMostPosition = Number.MAX_VALUE;
    const lineTextStarts = /* @__PURE__ */ new Map();
    const firstNonWhitespaceCharacterRegex = new RegExp(/\S/);
    const isJsx = isInsideJsxElement(sourceFile, lineStarts[firstLine]);
    const openComment = isJsx ? "{/*" : "//";
    for (let i = firstLine; i <= lastLine; i++) {
      const lineText = sourceFile.text.substring(lineStarts[i], sourceFile.getLineEndOfPosition(lineStarts[i]));
      const regExec = firstNonWhitespaceCharacterRegex.exec(lineText);
      if (regExec) {
        leftMostPosition = Math.min(leftMostPosition, regExec.index);
        lineTextStarts.set(i.toString(), regExec.index);
        if (lineText.substr(regExec.index, openComment.length) !== openComment) {
          isCommenting = insertComment === void 0 || insertComment;
        }
      }
    }
    for (let i = firstLine; i <= lastLine; i++) {
      if (firstLine !== lastLine && lineStarts[i] === textRange.end) {
        continue;
      }
      const lineTextStart = lineTextStarts.get(i.toString());
      if (lineTextStart !== void 0) {
        if (isJsx) {
          textChanges2.push(...toggleMultilineComment(fileName, { pos: lineStarts[i] + leftMostPosition, end: sourceFile.getLineEndOfPosition(lineStarts[i]) }, isCommenting, isJsx));
        } else if (isCommenting) {
          textChanges2.push({
            newText: openComment,
            span: {
              length: 0,
              start: lineStarts[i] + leftMostPosition
            }
          });
        } else if (sourceFile.text.substr(lineStarts[i] + lineTextStart, openComment.length) === openComment) {
          textChanges2.push({
            newText: "",
            span: {
              length: openComment.length,
              start: lineStarts[i] + lineTextStart
            }
          });
        }
      }
    }
    return textChanges2;
  }
  function toggleMultilineComment(fileName, textRange, insertComment, isInsideJsx) {
    var _a2;
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const textChanges2 = [];
    const { text } = sourceFile;
    let hasComment = false;
    let isCommenting = insertComment || false;
    const positions = [];
    let { pos } = textRange;
    const isJsx = isInsideJsx !== void 0 ? isInsideJsx : isInsideJsxElement(sourceFile, pos);
    const openMultiline = isJsx ? "{/*" : "/*";
    const closeMultiline = isJsx ? "*/}" : "*/";
    const openMultilineRegex = isJsx ? "\\{\\/\\*" : "\\/\\*";
    const closeMultilineRegex = isJsx ? "\\*\\/\\}" : "\\*\\/";
    while (pos <= textRange.end) {
      const offset = text.substr(pos, openMultiline.length) === openMultiline ? openMultiline.length : 0;
      const commentRange = isInComment(sourceFile, pos + offset);
      if (commentRange) {
        if (isJsx) {
          commentRange.pos--;
          commentRange.end++;
        }
        positions.push(commentRange.pos);
        if (commentRange.kind === 3 /* MultiLineCommentTrivia */) {
          positions.push(commentRange.end);
        }
        hasComment = true;
        pos = commentRange.end + 1;
      } else {
        const newPos = text.substring(pos, textRange.end).search(`(${openMultilineRegex})|(${closeMultilineRegex})`);
        isCommenting = insertComment !== void 0 ? insertComment : isCommenting || !isTextWhiteSpaceLike(text, pos, newPos === -1 ? textRange.end : pos + newPos);
        pos = newPos === -1 ? textRange.end + 1 : pos + newPos + closeMultiline.length;
      }
    }
    if (isCommenting || !hasComment) {
      if (((_a2 = isInComment(sourceFile, textRange.pos)) == null ? void 0 : _a2.kind) !== 2 /* SingleLineCommentTrivia */) {
        insertSorted(positions, textRange.pos, compareValues);
      }
      insertSorted(positions, textRange.end, compareValues);
      const firstPos = positions[0];
      if (text.substr(firstPos, openMultiline.length) !== openMultiline) {
        textChanges2.push({
          newText: openMultiline,
          span: {
            length: 0,
            start: firstPos
          }
        });
      }
      for (let i = 1; i < positions.length - 1; i++) {
        if (text.substr(positions[i] - closeMultiline.length, closeMultiline.length) !== closeMultiline) {
          textChanges2.push({
            newText: closeMultiline,
            span: {
              length: 0,
              start: positions[i]
            }
          });
        }
        if (text.substr(positions[i], openMultiline.length) !== openMultiline) {
          textChanges2.push({
            newText: openMultiline,
            span: {
              length: 0,
              start: positions[i]
            }
          });
        }
      }
      if (textChanges2.length % 2 !== 0) {
        textChanges2.push({
          newText: closeMultiline,
          span: {
            length: 0,
            start: positions[positions.length - 1]
          }
        });
      }
    } else {
      for (const pos2 of positions) {
        const from = pos2 - closeMultiline.length > 0 ? pos2 - closeMultiline.length : 0;
        const offset = text.substr(from, closeMultiline.length) === closeMultiline ? closeMultiline.length : 0;
        textChanges2.push({
          newText: "",
          span: {
            length: openMultiline.length,
            start: pos2 - offset
          }
        });
      }
    }
    return textChanges2;
  }
  function commentSelection(fileName, textRange) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const { firstLine, lastLine } = getLinesForRange(sourceFile, textRange);
    return firstLine === lastLine && textRange.pos !== textRange.end ? toggleMultilineComment(
      fileName,
      textRange,
      /*insertComment*/
      true
    ) : toggleLineComment(
      fileName,
      textRange,
      /*insertComment*/
      true
    );
  }
  function uncommentSelection(fileName, textRange) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const textChanges2 = [];
    const { pos } = textRange;
    let { end } = textRange;
    if (pos === end) {
      end += isInsideJsxElement(sourceFile, pos) ? 2 : 1;
    }
    for (let i = pos; i <= end; i++) {
      const commentRange = isInComment(sourceFile, i);
      if (commentRange) {
        switch (commentRange.kind) {
          case 2 /* SingleLineCommentTrivia */:
            textChanges2.push(...toggleLineComment(
              fileName,
              { end: commentRange.end, pos: commentRange.pos + 1 },
              /*insertComment*/
              false
            ));
            break;
          case 3 /* MultiLineCommentTrivia */:
            textChanges2.push(...toggleMultilineComment(
              fileName,
              { end: commentRange.end, pos: commentRange.pos + 1 },
              /*insertComment*/
              false
            ));
        }
        i = commentRange.end + 1;
      }
    }
    return textChanges2;
  }
  function isUnclosedTag({ openingElement, closingElement, parent: parent2 }) {
    return !tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || isJsxElement(parent2) && tagNamesAreEquivalent(openingElement.tagName, parent2.openingElement.tagName) && isUnclosedTag(parent2);
  }
  function isUnclosedFragment({ closingFragment, parent: parent2 }) {
    return !!(closingFragment.flags & 262144 /* ThisNodeHasError */) || isJsxFragment(parent2) && isUnclosedFragment(parent2);
  }
  function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const range = ts_formatting_exports.getRangeOfEnclosingComment(sourceFile, position);
    return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? createTextSpanFromRange(range) : void 0;
  }
  function getTodoComments(fileName, descriptors) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    cancellationToken.throwIfCancellationRequested();
    const fileContents = sourceFile.text;
    const result = [];
    if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) {
      const regExp = getTodoCommentsRegExp();
      let matchArray;
      while (matchArray = regExp.exec(fileContents)) {
        cancellationToken.throwIfCancellationRequested();
        const firstDescriptorCaptureIndex = 3;
        Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex);
        const preamble = matchArray[1];
        const matchPosition = matchArray.index + preamble.length;
        if (!isInComment(sourceFile, matchPosition)) {
          continue;
        }
        let descriptor;
        for (let i = 0; i < descriptors.length; i++) {
          if (matchArray[i + firstDescriptorCaptureIndex]) {
            descriptor = descriptors[i];
          }
        }
        if (descriptor === void 0) return Debug.fail();
        if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) {
          continue;
        }
        const message = matchArray[2];
        result.push({ descriptor, message, position: matchPosition });
      }
    }
    return result;
    function escapeRegExp(str) {
      return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&");
    }
    function getTodoCommentsRegExp() {
      const singleLineCommentStart = /(?:\/{2,}\s*)/.source;
      const multiLineCommentStart = /(?:\/\*+\s*)/.source;
      const anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source;
      const preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")";
      const literals = "(?:" + map(descriptors, (d) => "(" + escapeRegExp(d.text) + ")").join("|") + ")";
      const endOfLineOrEndOfComment = /(?:$|\*\/)/.source;
      const messageRemainder = /(?:.*?)/.source;
      const messagePortion = "(" + literals + messageRemainder + ")";
      const regExpString = preamble + messagePortion + endOfLineOrEndOfComment;
      return new RegExp(regExpString, "gim");
    }
    function isLetterOrDigit(char) {
      return char >= 97 /* a */ && char <= 122 /* z */ || char >= 65 /* A */ && char <= 90 /* Z */ || char >= 48 /* _0 */ && char <= 57 /* _9 */;
    }
    function isNodeModulesFile(path) {
      return path.includes("/node_modules/");
    }
  }
  function getRenameInfo2(fileName, position, preferences) {
    synchronizeHostData();
    return ts_Rename_exports.getRenameInfo(program, getValidSourceFile(fileName), position, preferences || {});
  }
  function getRefactorContext(file, positionOrRange, preferences, formatOptions, triggerReason, kind) {
    const [startPosition, endPosition] = typeof positionOrRange === "number" ? [positionOrRange, void 0] : [positionOrRange.pos, positionOrRange.end];
    return {
      file,
      startPosition,
      endPosition,
      program: getProgram(),
      host,
      formatContext: ts_formatting_exports.getFormatContext(formatOptions, host),
      // TODO: GH#18217
      cancellationToken,
      preferences,
      triggerReason,
      kind
    };
  }
  function getInlayHintsContext(file, span, preferences) {
    return {
      file,
      program: getProgram(),
      host,
      span,
      preferences,
      cancellationToken
    };
  }
  function getSmartSelectionRange2(fileName, position) {
    return ts_SmartSelectionRange_exports.getSmartSelectionRange(position, syntaxTreeCache.getCurrentSourceFile(fileName));
  }
  function getApplicableRefactors2(fileName, positionOrRange, preferences = emptyOptions, triggerReason, kind, includeInteractiveActions) {
    synchronizeHostData();
    const file = getValidSourceFile(fileName);
    return ts_refactor_exports.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, emptyOptions, triggerReason, kind), includeInteractiveActions);
  }
  function getMoveToRefactoringFileSuggestions(fileName, positionOrRange, preferences = emptyOptions) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const allFiles = Debug.checkDefined(program.getSourceFiles());
    const extension = extensionFromPath(fileName);
    const toMove = getStatementsToMove(getRefactorContext(sourceFile, positionOrRange, preferences, emptyOptions));
    const toMoveContainsJsx = containsJsx(toMove == null ? void 0 : toMove.all);
    const files = mapDefined(allFiles, (file) => {
      const fileNameExtension = extensionFromPath(file.fileName);
      const isValidSourceFile = !(program == null ? void 0 : program.isSourceFileFromExternalLibrary(sourceFile)) && !(sourceFile === getValidSourceFile(file.fileName) || extension === ".ts" /* Ts */ && fileNameExtension === ".d.ts" /* Dts */ || extension === ".d.ts" /* Dts */ && startsWith(getBaseFileName(file.fileName), "lib.") && fileNameExtension === ".d.ts" /* Dts */);
      return isValidSourceFile && (extension === fileNameExtension || (extension === ".tsx" /* Tsx */ && fileNameExtension === ".ts" /* Ts */ || extension === ".jsx" /* Jsx */ && fileNameExtension === ".js" /* Js */) && !toMoveContainsJsx) ? file.fileName : void 0;
    });
    return { newFileName: createNewFileName(sourceFile, program, host, toMove), files };
  }
  function getEditsForRefactor2(fileName, formatOptions, positionOrRange, refactorName14, actionName2, preferences = emptyOptions, interactiveRefactorArguments) {
    synchronizeHostData();
    const file = getValidSourceFile(fileName);
    return ts_refactor_exports.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName14, actionName2, interactiveRefactorArguments);
  }
  function toLineColumnOffset(fileName, position) {
    if (position === 0) {
      return { line: 0, character: 0 };
    }
    return sourceMapper.toLineColumnOffset(fileName, position);
  }
  function prepareCallHierarchy(fileName, position) {
    synchronizeHostData();
    const declarations = ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, getTouchingPropertyName(getValidSourceFile(fileName), position));
    return declarations && mapOneOrMany(declarations, (declaration) => ts_CallHierarchy_exports.createCallHierarchyItem(program, declaration));
  }
  function provideCallHierarchyIncomingCalls(fileName, position) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const declaration = firstOrOnly(ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : getTouchingPropertyName(sourceFile, position)));
    return declaration ? ts_CallHierarchy_exports.getIncomingCalls(program, declaration, cancellationToken) : [];
  }
  function provideCallHierarchyOutgoingCalls(fileName, position) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const declaration = firstOrOnly(ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : getTouchingPropertyName(sourceFile, position)));
    return declaration ? ts_CallHierarchy_exports.getOutgoingCalls(program, declaration) : [];
  }
  function provideInlayHints2(fileName, span, preferences = emptyOptions) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    return ts_InlayHints_exports.provideInlayHints(getInlayHintsContext(sourceFile, span, preferences));
  }
  function mapCode2(sourceFile, contents, focusLocations, formatOptions, preferences) {
    return ts_MapCode_exports.mapCode(
      syntaxTreeCache.getCurrentSourceFile(sourceFile),
      contents,
      focusLocations,
      host,
      ts_formatting_exports.getFormatContext(formatOptions, host),
      preferences
    );
  }
  const ls = {
    dispose,
    cleanupSemanticCache,
    getSyntacticDiagnostics,
    getSemanticDiagnostics,
    getRegionSemanticDiagnostics,
    getSuggestionDiagnostics,
    getCompilerOptionsDiagnostics,
    getSyntacticClassifications: getSyntacticClassifications2,
    getSemanticClassifications: getSemanticClassifications3,
    getEncodedSyntacticClassifications: getEncodedSyntacticClassifications2,
    getEncodedSemanticClassifications: getEncodedSemanticClassifications3,
    getCompletionsAtPosition: getCompletionsAtPosition2,
    getCompletionEntryDetails: getCompletionEntryDetails2,
    getCompletionEntrySymbol: getCompletionEntrySymbol2,
    getSignatureHelpItems: getSignatureHelpItems2,
    getQuickInfoAtPosition,
    getDefinitionAtPosition: getDefinitionAtPosition2,
    getDefinitionAndBoundSpan: getDefinitionAndBoundSpan2,
    getImplementationAtPosition,
    getTypeDefinitionAtPosition: getTypeDefinitionAtPosition2,
    getReferencesAtPosition,
    findReferences,
    getFileReferences,
    getDocumentHighlights,
    getNameOrDottedNameSpan,
    getBreakpointStatementAtPosition,
    getNavigateToItems: getNavigateToItems2,
    getRenameInfo: getRenameInfo2,
    getSmartSelectionRange: getSmartSelectionRange2,
    findRenameLocations,
    getNavigationBarItems: getNavigationBarItems2,
    getNavigationTree: getNavigationTree2,
    getOutliningSpans,
    getTodoComments,
    getBraceMatchingAtPosition,
    getIndentationAtPosition,
    getFormattingEditsForRange,
    getFormattingEditsForDocument,
    getFormattingEditsAfterKeystroke,
    getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition2,
    isValidBraceCompletionAtPosition,
    getJsxClosingTagAtPosition,
    getLinkedEditingRangeAtPosition,
    getSpanOfEnclosingComment,
    getCodeFixesAtPosition,
    getCombinedCodeFix,
    applyCodeActionCommand,
    organizeImports: organizeImports2,
    getEditsForFileRename: getEditsForFileRename2,
    getEmitOutput,
    getNonBoundSourceFile,
    getProgram,
    getCurrentProgram: () => program,
    getAutoImportProvider,
    updateIsDefinitionOfReferencedSymbols,
    getApplicableRefactors: getApplicableRefactors2,
    getEditsForRefactor: getEditsForRefactor2,
    getMoveToRefactoringFileSuggestions,
    toLineColumnOffset,
    getSourceMapper: () => sourceMapper,
    clearSourceMapperCache: () => sourceMapper.clearCache(),
    prepareCallHierarchy,
    provideCallHierarchyIncomingCalls,
    provideCallHierarchyOutgoingCalls,
    toggleLineComment,
    toggleMultilineComment,
    commentSelection,
    uncommentSelection,
    provideInlayHints: provideInlayHints2,
    getSupportedCodeFixes,
    preparePasteEditsForFile,
    getPasteEdits,
    mapCode: mapCode2
  };
  switch (languageServiceMode) {
    case 0 /* Semantic */:
      break;
    case 1 /* PartialSemantic */:
      invalidOperationsInPartialSemanticMode.forEach(
        (key) => ls[key] = () => {
          throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.PartialSemantic`);
        }
      );
      break;
    case 2 /* Syntactic */:
      invalidOperationsInSyntacticMode.forEach(
        (key) => ls[key] = () => {
          throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.Syntactic`);
        }
      );
      break;
    default:
      Debug.assertNever(languageServiceMode);
  }
  return ls;
}
function getNameTable(sourceFile) {
  if (!sourceFile.nameTable) {
    initializeNameTable(sourceFile);
  }
  return sourceFile.nameTable;
}
function initializeNameTable(sourceFile) {
  const nameTable = sourceFile.nameTable = /* @__PURE__ */ new Map();
  sourceFile.forEachChild(function walk(node) {
    if (isIdentifier(node) && !isTagName(node) && node.escapedText || isStringOrNumericLiteralLike(node) && literalIsName(node)) {
      const text = getEscapedTextOfIdentifierOrLiteral(node);
      nameTable.set(text, nameTable.get(text) === void 0 ? node.pos : -1);
    } else if (isPrivateIdentifier(node)) {
      const text = node.escapedText;
      nameTable.set(text, nameTable.get(text) === void 0 ? node.pos : -1);
    }
    forEachChild(node, walk);
    if (hasJSDocNodes(node)) {
      for (const jsDoc of node.jsDoc) {
        forEachChild(jsDoc, walk);
      }
    }
  });
}
function literalIsName(node) {
  return isDeclarationName(node) || node.parent.kind === 283 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || isLiteralComputedPropertyDeclarationName(node);
}
function getContainingObjectLiteralElement(node) {
  const element = getContainingObjectLiteralElementWorker(node);
  return element && (isObjectLiteralExpression(element.parent) || isJsxAttributes(element.parent)) ? element : void 0;
}
function getContainingObjectLiteralElementWorker(node) {
  switch (node.kind) {
    case 11 /* StringLiteral */:
    case 15 /* NoSubstitutionTemplateLiteral */:
    case 9 /* NumericLiteral */:
      if (node.parent.kind === 167 /* ComputedPropertyName */) {
        return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : void 0;
      }
    // falls through
    case 80 /* Identifier */:
      return isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 210 /* ObjectLiteralExpression */ || node.parent.parent.kind === 292 /* JsxAttributes */) && node.parent.name === node ? node.parent : void 0;
  }
  return void 0;
}
function getSymbolAtLocationForQuickInfo(node, checker) {
  const object = getContainingObjectLiteralElement(node);
  if (object) {
    const contextualType = checker.getContextualType(object.parent);
    const properties = contextualType && getPropertySymbolsFromContextualType(
      object,
      checker,
      contextualType,
      /*unionSymbolOk*/
      false
    );
    if (properties && properties.length === 1) {
      return first(properties);
    }
  }
  return checker.getSymbolAtLocation(node);
}
function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) {
  const name = getNameFromPropertyName(node.name);
  if (!name) return emptyArray;
  if (!contextualType.isUnion()) {
    const symbol = contextualType.getProperty(name);
    return symbol ? [symbol] : emptyArray;
  }
  const filteredTypes = isObjectLiteralExpression(node.parent) || isJsxAttributes(node.parent) ? filter(contextualType.types, (t) => !checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent)) : contextualType.types;
  const discriminatedPropertySymbols = mapDefined(filteredTypes, (t) => t.getProperty(name));
  if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) {
    const symbol = contextualType.getProperty(name);
    if (symbol) return [symbol];
  }
  if (!filteredTypes.length && !discriminatedPropertySymbols.length) {
    return mapDefined(contextualType.types, (t) => t.getProperty(name));
  }
  return deduplicate(discriminatedPropertySymbols, equateValues);
}
function isArgumentOfElementAccessExpression(node) {
  return node && node.parent && node.parent.kind === 212 /* ElementAccessExpression */ && node.parent.argumentExpression === node;
}
function getDefaultLibFilePath(options) {
  if (sys) {
    return combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options));
  }
  throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. ");
}
setObjectAllocator(getServicesObjectAllocator());

// src/services/transform.ts
function transform(source, transformers, compilerOptions) {
  const diagnostics = [];
  compilerOptions = fixupCompilerOptions(compilerOptions, diagnostics);
  const nodes = isArray(source) ? source : [source];
  const result = transformNodes(
    /*resolver*/
    void 0,
    /*host*/
    void 0,
    factory,
    compilerOptions,
    nodes,
    transformers,
    /*allowDtsFiles*/
    true
  );
  result.diagnostics = concatenate(result.diagnostics, diagnostics);
  return result;
}

// src/services/_namespaces/ts.BreakpointResolver.ts
var ts_BreakpointResolver_exports = {};
__export(ts_BreakpointResolver_exports, {
  spanInSourceFileAtLocation: () => spanInSourceFileAtLocation
});

// src/services/breakpoints.ts
function spanInSourceFileAtLocation(sourceFile, position) {
  if (sourceFile.isDeclarationFile) {
    return void 0;
  }
  let tokenAtLocation = getTokenAtPosition(sourceFile, position);
  const lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
  if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
    const preceding = findPrecedingToken(tokenAtLocation.pos, sourceFile);
    if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) {
      return void 0;
    }
    tokenAtLocation = preceding;
  }
  if (tokenAtLocation.flags & 33554432 /* Ambient */) {
    return void 0;
  }
  return spanInNode(tokenAtLocation);
  function textSpan(startNode2, endNode2) {
    const lastDecorator = canHaveDecorators(startNode2) ? findLast(startNode2.modifiers, isDecorator) : void 0;
    const start = lastDecorator ? skipTrivia(sourceFile.text, lastDecorator.end) : startNode2.getStart(sourceFile);
    return createTextSpanFromBounds(start, (endNode2 || startNode2).getEnd());
  }
  function textSpanEndingAtNextToken(startNode2, previousTokenToFindNextEndToken) {
    return textSpan(startNode2, findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
  }
  function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
    if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
      return spanInNode(node);
    }
    return spanInNode(otherwiseOnNode);
  }
  function spanInNodeArray(nodeArray, node, match) {
    if (nodeArray) {
      const index = nodeArray.indexOf(node);
      if (index >= 0) {
        let start = index;
        let end = index + 1;
        while (start > 0 && match(nodeArray[start - 1])) start--;
        while (end < nodeArray.length && match(nodeArray[end])) end++;
        return createTextSpanFromBounds(skipTrivia(sourceFile.text, nodeArray[start].pos), nodeArray[end - 1].end);
      }
    }
    return textSpan(node);
  }
  function spanInPreviousNode(node) {
    return spanInNode(findPrecedingToken(node.pos, sourceFile));
  }
  function spanInNextNode(node) {
    return spanInNode(findNextToken(node, node.parent, sourceFile));
  }
  function spanInNode(node) {
    if (node) {
      const { parent: parent2 } = node;
      switch (node.kind) {
        case 243 /* VariableStatement */:
          return spanInVariableDeclaration(node.declarationList.declarations[0]);
        case 260 /* VariableDeclaration */:
        case 172 /* PropertyDeclaration */:
        case 171 /* PropertySignature */:
          return spanInVariableDeclaration(node);
        case 169 /* Parameter */:
          return spanInParameterDeclaration(node);
        case 262 /* FunctionDeclaration */:
        case 174 /* MethodDeclaration */:
        case 173 /* MethodSignature */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
        case 176 /* Constructor */:
        case 218 /* FunctionExpression */:
        case 219 /* ArrowFunction */:
          return spanInFunctionDeclaration(node);
        case 241 /* Block */:
          if (isFunctionBlock(node)) {
            return spanInFunctionBlock(node);
          }
        // falls through
        case 268 /* ModuleBlock */:
          return spanInBlock(node);
        case 299 /* CatchClause */:
          return spanInBlock(node.block);
        case 244 /* ExpressionStatement */:
          return textSpan(node.expression);
        case 253 /* ReturnStatement */:
          return textSpan(node.getChildAt(0), node.expression);
        case 247 /* WhileStatement */:
          return textSpanEndingAtNextToken(node, node.expression);
        case 246 /* DoStatement */:
          return spanInNode(node.statement);
        case 259 /* DebuggerStatement */:
          return textSpan(node.getChildAt(0));
        case 245 /* IfStatement */:
          return textSpanEndingAtNextToken(node, node.expression);
        case 256 /* LabeledStatement */:
          return spanInNode(node.statement);
        case 252 /* BreakStatement */:
        case 251 /* ContinueStatement */:
          return textSpan(node.getChildAt(0), node.label);
        case 248 /* ForStatement */:
          return spanInForStatement(node);
        case 249 /* ForInStatement */:
          return textSpanEndingAtNextToken(node, node.expression);
        case 250 /* ForOfStatement */:
          return spanInInitializerOfForLike(node);
        case 255 /* SwitchStatement */:
          return textSpanEndingAtNextToken(node, node.expression);
        case 296 /* CaseClause */:
        case 297 /* DefaultClause */:
          return spanInNode(node.statements[0]);
        case 258 /* TryStatement */:
          return spanInBlock(node.tryBlock);
        case 257 /* ThrowStatement */:
          return textSpan(node, node.expression);
        case 277 /* ExportAssignment */:
          return textSpan(node, node.expression);
        case 271 /* ImportEqualsDeclaration */:
          return textSpan(node, node.moduleReference);
        case 272 /* ImportDeclaration */:
          return textSpan(node, node.moduleSpecifier);
        case 278 /* ExportDeclaration */:
          return textSpan(node, node.moduleSpecifier);
        case 267 /* ModuleDeclaration */:
          if (getModuleInstanceState(node) !== 1 /* Instantiated */) {
            return void 0;
          }
        // falls through
        case 263 /* ClassDeclaration */:
        case 266 /* EnumDeclaration */:
        case 306 /* EnumMember */:
        case 208 /* BindingElement */:
          return textSpan(node);
        case 254 /* WithStatement */:
          return spanInNode(node.statement);
        case 170 /* Decorator */:
          return spanInNodeArray(parent2.modifiers, node, isDecorator);
        case 206 /* ObjectBindingPattern */:
        case 207 /* ArrayBindingPattern */:
          return spanInBindingPattern(node);
        // No breakpoint in interface, type alias
        case 264 /* InterfaceDeclaration */:
        case 265 /* TypeAliasDeclaration */:
          return void 0;
        // Tokens:
        case 27 /* SemicolonToken */:
        case 1 /* EndOfFileToken */:
          return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile));
        case 28 /* CommaToken */:
          return spanInPreviousNode(node);
        case 19 /* OpenBraceToken */:
          return spanInOpenBraceToken(node);
        case 20 /* CloseBraceToken */:
          return spanInCloseBraceToken(node);
        case 24 /* CloseBracketToken */:
          return spanInCloseBracketToken(node);
        case 21 /* OpenParenToken */:
          return spanInOpenParenToken(node);
        case 22 /* CloseParenToken */:
          return spanInCloseParenToken(node);
        case 59 /* ColonToken */:
          return spanInColonToken(node);
        case 32 /* GreaterThanToken */:
        case 30 /* LessThanToken */:
          return spanInGreaterThanOrLessThanToken(node);
        // Keywords:
        case 117 /* WhileKeyword */:
          return spanInWhileKeyword(node);
        case 93 /* ElseKeyword */:
        case 85 /* CatchKeyword */:
        case 98 /* FinallyKeyword */:
          return spanInNextNode(node);
        case 165 /* OfKeyword */:
          return spanInOfKeyword(node);
        default:
          if (isArrayLiteralOrObjectLiteralDestructuringPattern(node)) {
            return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node);
          }
          if ((node.kind === 80 /* Identifier */ || node.kind === 230 /* SpreadElement */ || node.kind === 303 /* PropertyAssignment */ || node.kind === 304 /* ShorthandPropertyAssignment */) && isArrayLiteralOrObjectLiteralDestructuringPattern(parent2)) {
            return textSpan(node);
          }
          if (node.kind === 226 /* BinaryExpression */) {
            const { left, operatorToken } = node;
            if (isArrayLiteralOrObjectLiteralDestructuringPattern(left)) {
              return spanInArrayLiteralOrObjectLiteralDestructuringPattern(
                left
              );
            }
            if (operatorToken.kind === 64 /* EqualsToken */ && isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
              return textSpan(node);
            }
            if (operatorToken.kind === 28 /* CommaToken */) {
              return spanInNode(left);
            }
          }
          if (isExpressionNode(node)) {
            switch (parent2.kind) {
              case 246 /* DoStatement */:
                return spanInPreviousNode(node);
              case 170 /* Decorator */:
                return spanInNode(node.parent);
              case 248 /* ForStatement */:
              case 250 /* ForOfStatement */:
                return textSpan(node);
              case 226 /* BinaryExpression */:
                if (node.parent.operatorToken.kind === 28 /* CommaToken */) {
                  return textSpan(node);
                }
                break;
              case 219 /* ArrowFunction */:
                if (node.parent.body === node) {
                  return textSpan(node);
                }
                break;
            }
          }
          switch (node.parent.kind) {
            case 303 /* PropertyAssignment */:
              if (node.parent.name === node && !isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
                return spanInNode(node.parent.initializer);
              }
              break;
            case 216 /* TypeAssertionExpression */:
              if (node.parent.type === node) {
                return spanInNextNode(node.parent.type);
              }
              break;
            case 260 /* VariableDeclaration */:
            case 169 /* Parameter */: {
              const { initializer, type } = node.parent;
              if (initializer === node || type === node || isAssignmentOperator(node.kind)) {
                return spanInPreviousNode(node);
              }
              break;
            }
            case 226 /* BinaryExpression */: {
              const { left } = node.parent;
              if (isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
                return spanInPreviousNode(node);
              }
              break;
            }
            default:
              if (isFunctionLike(node.parent) && node.parent.type === node) {
                return spanInPreviousNode(node);
              }
          }
          return spanInNode(node.parent);
      }
    }
    function textSpanFromVariableDeclaration(variableDeclaration) {
      if (isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) {
        return textSpan(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
      } else {
        return textSpan(variableDeclaration);
      }
    }
    function spanInVariableDeclaration(variableDeclaration) {
      if (variableDeclaration.parent.parent.kind === 249 /* ForInStatement */) {
        return spanInNode(variableDeclaration.parent.parent);
      }
      const parent2 = variableDeclaration.parent;
      if (isBindingPattern(variableDeclaration.name)) {
        return spanInBindingPattern(variableDeclaration.name);
      }
      if (hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer || hasSyntacticModifier(variableDeclaration, 32 /* Export */) || parent2.parent.kind === 250 /* ForOfStatement */) {
        return textSpanFromVariableDeclaration(variableDeclaration);
      }
      if (isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] !== variableDeclaration) {
        return spanInNode(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent));
      }
    }
    function canHaveSpanInParameterDeclaration(parameter) {
      return !!parameter.initializer || parameter.dotDotDotToken !== void 0 || hasSyntacticModifier(parameter, 1 /* Public */ | 2 /* Private */);
    }
    function spanInParameterDeclaration(parameter) {
      if (isBindingPattern(parameter.name)) {
        return spanInBindingPattern(parameter.name);
      } else if (canHaveSpanInParameterDeclaration(parameter)) {
        return textSpan(parameter);
      } else {
        const functionDeclaration = parameter.parent;
        const indexOfParameter = functionDeclaration.parameters.indexOf(parameter);
        Debug.assert(indexOfParameter !== -1);
        if (indexOfParameter !== 0) {
          return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]);
        } else {
          return spanInNode(functionDeclaration.body);
        }
      }
    }
    function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) {
      return hasSyntacticModifier(functionDeclaration, 32 /* Export */) || functionDeclaration.parent.kind === 263 /* ClassDeclaration */ && functionDeclaration.kind !== 176 /* Constructor */;
    }
    function spanInFunctionDeclaration(functionDeclaration) {
      if (!functionDeclaration.body) {
        return void 0;
      }
      if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) {
        return textSpan(functionDeclaration);
      }
      return spanInNode(functionDeclaration.body);
    }
    function spanInFunctionBlock(block) {
      const nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
      if (canFunctionHaveSpanInWholeDeclaration(block.parent)) {
        return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock);
      }
      return spanInNode(nodeForSpanInBlock);
    }
    function spanInBlock(block) {
      switch (block.parent.kind) {
        case 267 /* ModuleDeclaration */:
          if (getModuleInstanceState(block.parent) !== 1 /* Instantiated */) {
            return void 0;
          }
        // Set on parent if on same line otherwise on first statement
        // falls through
        case 247 /* WhileStatement */:
        case 245 /* IfStatement */:
        case 249 /* ForInStatement */:
          return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]);
        // Set span on previous token if it starts on same line otherwise on the first statement of the block
        case 248 /* ForStatement */:
        case 250 /* ForOfStatement */:
          return spanInNodeIfStartsOnSameLine(findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]);
      }
      return spanInNode(block.statements[0]);
    }
    function spanInInitializerOfForLike(forLikeStatement) {
      if (forLikeStatement.initializer.kind === 261 /* VariableDeclarationList */) {
        const variableDeclarationList = forLikeStatement.initializer;
        if (variableDeclarationList.declarations.length > 0) {
          return spanInNode(variableDeclarationList.declarations[0]);
        }
      } else {
        return spanInNode(forLikeStatement.initializer);
      }
    }
    function spanInForStatement(forStatement) {
      if (forStatement.initializer) {
        return spanInInitializerOfForLike(forStatement);
      }
      if (forStatement.condition) {
        return textSpan(forStatement.condition);
      }
      if (forStatement.incrementor) {
        return textSpan(forStatement.incrementor);
      }
    }
    function spanInBindingPattern(bindingPattern) {
      const firstBindingElement = forEach(bindingPattern.elements, (element) => element.kind !== 232 /* OmittedExpression */ ? element : void 0);
      if (firstBindingElement) {
        return spanInNode(firstBindingElement);
      }
      if (bindingPattern.parent.kind === 208 /* BindingElement */) {
        return textSpan(bindingPattern.parent);
      }
      return textSpanFromVariableDeclaration(bindingPattern.parent);
    }
    function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node2) {
      Debug.assert(node2.kind !== 207 /* ArrayBindingPattern */ && node2.kind !== 206 /* ObjectBindingPattern */);
      const elements = node2.kind === 209 /* ArrayLiteralExpression */ ? node2.elements : node2.properties;
      const firstBindingElement = forEach(elements, (element) => element.kind !== 232 /* OmittedExpression */ ? element : void 0);
      if (firstBindingElement) {
        return spanInNode(firstBindingElement);
      }
      return textSpan(node2.parent.kind === 226 /* BinaryExpression */ ? node2.parent : node2);
    }
    function spanInOpenBraceToken(node2) {
      switch (node2.parent.kind) {
        case 266 /* EnumDeclaration */:
          const enumDeclaration = node2.parent;
          return spanInNodeIfStartsOnSameLine(findPrecedingToken(node2.pos, sourceFile, node2.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile));
        case 263 /* ClassDeclaration */:
          const classDeclaration = node2.parent;
          return spanInNodeIfStartsOnSameLine(findPrecedingToken(node2.pos, sourceFile, node2.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile));
        case 269 /* CaseBlock */:
          return spanInNodeIfStartsOnSameLine(node2.parent.parent, node2.parent.clauses[0]);
      }
      return spanInNode(node2.parent);
    }
    function spanInCloseBraceToken(node2) {
      switch (node2.parent.kind) {
        case 268 /* ModuleBlock */:
          if (getModuleInstanceState(node2.parent.parent) !== 1 /* Instantiated */) {
            return void 0;
          }
        // falls through
        case 266 /* EnumDeclaration */:
        case 263 /* ClassDeclaration */:
          return textSpan(node2);
        case 241 /* Block */:
          if (isFunctionBlock(node2.parent)) {
            return textSpan(node2);
          }
        // falls through
        case 299 /* CatchClause */:
          return spanInNode(lastOrUndefined(node2.parent.statements));
        case 269 /* CaseBlock */:
          const caseBlock = node2.parent;
          const lastClause = lastOrUndefined(caseBlock.clauses);
          if (lastClause) {
            return spanInNode(lastOrUndefined(lastClause.statements));
          }
          return void 0;
        case 206 /* ObjectBindingPattern */:
          const bindingPattern = node2.parent;
          return spanInNode(lastOrUndefined(bindingPattern.elements) || bindingPattern);
        // Default to parent node
        default:
          if (isArrayLiteralOrObjectLiteralDestructuringPattern(node2.parent)) {
            const objectLiteral = node2.parent;
            return textSpan(lastOrUndefined(objectLiteral.properties) || objectLiteral);
          }
          return spanInNode(node2.parent);
      }
    }
    function spanInCloseBracketToken(node2) {
      switch (node2.parent.kind) {
        case 207 /* ArrayBindingPattern */:
          const bindingPattern = node2.parent;
          return textSpan(lastOrUndefined(bindingPattern.elements) || bindingPattern);
        default:
          if (isArrayLiteralOrObjectLiteralDestructuringPattern(node2.parent)) {
            const arrayLiteral = node2.parent;
            return textSpan(lastOrUndefined(arrayLiteral.elements) || arrayLiteral);
          }
          return spanInNode(node2.parent);
      }
    }
    function spanInOpenParenToken(node2) {
      if (node2.parent.kind === 246 /* DoStatement */ || // Go to while keyword and do action instead
      node2.parent.kind === 213 /* CallExpression */ || node2.parent.kind === 214 /* NewExpression */) {
        return spanInPreviousNode(node2);
      }
      if (node2.parent.kind === 217 /* ParenthesizedExpression */) {
        return spanInNextNode(node2);
      }
      return spanInNode(node2.parent);
    }
    function spanInCloseParenToken(node2) {
      switch (node2.parent.kind) {
        case 218 /* FunctionExpression */:
        case 262 /* FunctionDeclaration */:
        case 219 /* ArrowFunction */:
        case 174 /* MethodDeclaration */:
        case 173 /* MethodSignature */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
        case 176 /* Constructor */:
        case 247 /* WhileStatement */:
        case 246 /* DoStatement */:
        case 248 /* ForStatement */:
        case 250 /* ForOfStatement */:
        case 213 /* CallExpression */:
        case 214 /* NewExpression */:
        case 217 /* ParenthesizedExpression */:
          return spanInPreviousNode(node2);
        // Default to parent node
        default:
          return spanInNode(node2.parent);
      }
    }
    function spanInColonToken(node2) {
      if (isFunctionLike(node2.parent) || node2.parent.kind === 303 /* PropertyAssignment */ || node2.parent.kind === 169 /* Parameter */) {
        return spanInPreviousNode(node2);
      }
      return spanInNode(node2.parent);
    }
    function spanInGreaterThanOrLessThanToken(node2) {
      if (node2.parent.kind === 216 /* TypeAssertionExpression */) {
        return spanInNextNode(node2);
      }
      return spanInNode(node2.parent);
    }
    function spanInWhileKeyword(node2) {
      if (node2.parent.kind === 246 /* DoStatement */) {
        return textSpanEndingAtNextToken(node2, node2.parent.expression);
      }
      return spanInNode(node2.parent);
    }
    function spanInOfKeyword(node2) {
      if (node2.parent.kind === 250 /* ForOfStatement */) {
        return spanInNextNode(node2);
      }
      return spanInNode(node2.parent);
    }
  }
}

// src/services/_namespaces/ts.CallHierarchy.ts
var ts_CallHierarchy_exports = {};
__export(ts_CallHierarchy_exports, {
  createCallHierarchyItem: () => createCallHierarchyItem,
  getIncomingCalls: () => getIncomingCalls,
  getOutgoingCalls: () => getOutgoingCalls,
  resolveCallHierarchyDeclaration: () => resolveCallHierarchyDeclaration
});

// src/services/callHierarchy.ts
function isNamedExpression(node) {
  return (isFunctionExpression(node) || isClassExpression(node)) && isNamedDeclaration(node);
}
function isVariableLike2(node) {
  return isPropertyDeclaration(node) || isVariableDeclaration(node);
}
function isAssignedExpression(node) {
  return (isFunctionExpression(node) || isArrowFunction(node) || isClassExpression(node)) && isVariableLike2(node.parent) && node === node.parent.initializer && isIdentifier(node.parent.name) && (!!(getCombinedNodeFlags(node.parent) & 2 /* Const */) || isPropertyDeclaration(node.parent));
}
function isPossibleCallHierarchyDeclaration(node) {
  return isSourceFile(node) || isModuleDeclaration(node) || isFunctionDeclaration(node) || isFunctionExpression(node) || isClassDeclaration(node) || isClassExpression(node) || isClassStaticBlockDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node);
}
function isValidCallHierarchyDeclaration(node) {
  return isSourceFile(node) || isModuleDeclaration(node) && isIdentifier(node.name) || isFunctionDeclaration(node) || isClassDeclaration(node) || isClassStaticBlockDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node) || isNamedExpression(node) || isAssignedExpression(node);
}
function getCallHierarchyDeclarationReferenceNode(node) {
  if (isSourceFile(node)) return node;
  if (isNamedDeclaration(node)) return node.name;
  if (isAssignedExpression(node)) return node.parent.name;
  return Debug.checkDefined(node.modifiers && find(node.modifiers, isDefaultModifier3));
}
function isDefaultModifier3(node) {
  return node.kind === 90 /* DefaultKeyword */;
}
function getSymbolOfCallHierarchyDeclaration(typeChecker, node) {
  const location = getCallHierarchyDeclarationReferenceNode(node);
  return location && typeChecker.getSymbolAtLocation(location);
}
function getCallHierarchyItemName(program, node) {
  if (isSourceFile(node)) {
    return { text: node.fileName, pos: 0, end: 0 };
  }
  if ((isFunctionDeclaration(node) || isClassDeclaration(node)) && !isNamedDeclaration(node)) {
    const defaultModifier = node.modifiers && find(node.modifiers, isDefaultModifier3);
    if (defaultModifier) {
      return { text: "default", pos: defaultModifier.getStart(), end: defaultModifier.getEnd() };
    }
  }
  if (isClassStaticBlockDeclaration(node)) {
    const sourceFile = node.getSourceFile();
    const pos = skipTrivia(sourceFile.text, moveRangePastModifiers(node).pos);
    const end = pos + 6;
    const typeChecker = program.getTypeChecker();
    const symbol = typeChecker.getSymbolAtLocation(node.parent);
    const prefix = symbol ? `${typeChecker.symbolToString(symbol, node.parent)} ` : "";
    return { text: `${prefix}static {}`, pos, end };
  }
  const declName = isAssignedExpression(node) ? node.parent.name : Debug.checkDefined(getNameOfDeclaration(node), "Expected call hierarchy item to have a name");
  let text = isIdentifier(declName) ? idText(declName) : isStringOrNumericLiteralLike(declName) ? declName.text : isComputedPropertyName(declName) ? isStringOrNumericLiteralLike(declName.expression) ? declName.expression.text : void 0 : void 0;
  if (text === void 0) {
    const typeChecker = program.getTypeChecker();
    const symbol = typeChecker.getSymbolAtLocation(declName);
    if (symbol) {
      text = typeChecker.symbolToString(symbol, node);
    }
  }
  if (text === void 0) {
    const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon();
    text = usingSingleLineStringWriter((writer) => printer.writeNode(4 /* Unspecified */, node, node.getSourceFile(), writer));
  }
  return { text, pos: declName.getStart(), end: declName.getEnd() };
}
function getCallHierarchItemContainerName(node) {
  var _a, _b, _c, _d;
  if (isAssignedExpression(node)) {
    if (isPropertyDeclaration(node.parent) && isClassLike(node.parent.parent)) {
      return isClassExpression(node.parent.parent) ? (_a = getAssignedName(node.parent.parent)) == null ? void 0 : _a.getText() : (_b = node.parent.parent.name) == null ? void 0 : _b.getText();
    }
    if (isModuleBlock(node.parent.parent.parent.parent) && isIdentifier(node.parent.parent.parent.parent.parent.name)) {
      return node.parent.parent.parent.parent.parent.name.getText();
    }
    return;
  }
  switch (node.kind) {
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
    case 174 /* MethodDeclaration */:
      if (node.parent.kind === 210 /* ObjectLiteralExpression */) {
        return (_c = getAssignedName(node.parent)) == null ? void 0 : _c.getText();
      }
      return (_d = getNameOfDeclaration(node.parent)) == null ? void 0 : _d.getText();
    case 262 /* FunctionDeclaration */:
    case 263 /* ClassDeclaration */:
    case 267 /* ModuleDeclaration */:
      if (isModuleBlock(node.parent) && isIdentifier(node.parent.parent.name)) {
        return node.parent.parent.name.getText();
      }
  }
}
function findImplementation(typeChecker, node) {
  if (node.body) {
    return node;
  }
  if (isConstructorDeclaration(node)) {
    return getFirstConstructorWithBody(node.parent);
  }
  if (isFunctionDeclaration(node) || isMethodDeclaration(node)) {
    const symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node);
    if (symbol && symbol.valueDeclaration && isFunctionLikeDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.body) {
      return symbol.valueDeclaration;
    }
    return void 0;
  }
  return node;
}
function findAllInitialDeclarations(typeChecker, node) {
  const symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node);
  let declarations;
  if (symbol && symbol.declarations) {
    const indices = indicesOf(symbol.declarations);
    const keys = map(symbol.declarations, (decl) => ({ file: decl.getSourceFile().fileName, pos: decl.pos }));
    indices.sort((a, b) => compareStringsCaseSensitive(keys[a].file, keys[b].file) || keys[a].pos - keys[b].pos);
    const sortedDeclarations = map(indices, (i) => symbol.declarations[i]);
    let lastDecl;
    for (const decl of sortedDeclarations) {
      if (isValidCallHierarchyDeclaration(decl)) {
        if (!lastDecl || lastDecl.parent !== decl.parent || lastDecl.end !== decl.pos) {
          declarations = append(declarations, decl);
        }
        lastDecl = decl;
      }
    }
  }
  return declarations;
}
function findImplementationOrAllInitialDeclarations(typeChecker, node) {
  if (isClassStaticBlockDeclaration(node)) {
    return node;
  }
  if (isFunctionLikeDeclaration(node)) {
    return findImplementation(typeChecker, node) ?? findAllInitialDeclarations(typeChecker, node) ?? node;
  }
  return findAllInitialDeclarations(typeChecker, node) ?? node;
}
function resolveCallHierarchyDeclaration(program, location) {
  const typeChecker = program.getTypeChecker();
  let followingSymbol = false;
  while (true) {
    if (isValidCallHierarchyDeclaration(location)) {
      return findImplementationOrAllInitialDeclarations(typeChecker, location);
    }
    if (isPossibleCallHierarchyDeclaration(location)) {
      const ancestor = findAncestor(location, isValidCallHierarchyDeclaration);
      return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor);
    }
    if (isDeclarationName(location)) {
      if (isValidCallHierarchyDeclaration(location.parent)) {
        return findImplementationOrAllInitialDeclarations(typeChecker, location.parent);
      }
      if (isPossibleCallHierarchyDeclaration(location.parent)) {
        const ancestor = findAncestor(location.parent, isValidCallHierarchyDeclaration);
        return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor);
      }
      if (isVariableLike2(location.parent) && location.parent.initializer && isAssignedExpression(location.parent.initializer)) {
        return location.parent.initializer;
      }
      return void 0;
    }
    if (isConstructorDeclaration(location)) {
      if (isValidCallHierarchyDeclaration(location.parent)) {
        return location.parent;
      }
      return void 0;
    }
    if (location.kind === 126 /* StaticKeyword */ && isClassStaticBlockDeclaration(location.parent)) {
      location = location.parent;
      continue;
    }
    if (isVariableDeclaration(location) && location.initializer && isAssignedExpression(location.initializer)) {
      return location.initializer;
    }
    if (!followingSymbol) {
      let symbol = typeChecker.getSymbolAtLocation(location);
      if (symbol) {
        if (symbol.flags & 2097152 /* Alias */) {
          symbol = typeChecker.getAliasedSymbol(symbol);
        }
        if (symbol.valueDeclaration) {
          followingSymbol = true;
          location = symbol.valueDeclaration;
          continue;
        }
      }
    }
    return void 0;
  }
}
function createCallHierarchyItem(program, node) {
  const sourceFile = node.getSourceFile();
  const name = getCallHierarchyItemName(program, node);
  const containerName = getCallHierarchItemContainerName(node);
  const kind = getNodeKind(node);
  const kindModifiers = getNodeModifiers(node);
  const span = createTextSpanFromBounds(skipTrivia(
    sourceFile.text,
    node.getFullStart(),
    /*stopAfterLineBreak*/
    false,
    /*stopAtComments*/
    true
  ), node.getEnd());
  const selectionSpan = createTextSpanFromBounds(name.pos, name.end);
  return { file: sourceFile.fileName, kind, kindModifiers, name: name.text, containerName, span, selectionSpan };
}
function isDefined(x) {
  return x !== void 0;
}
function convertEntryToCallSite(entry) {
  if (entry.kind === ts_FindAllReferences_exports.EntryKind.Node) {
    const { node } = entry;
    if (isCallOrNewExpressionTarget(
      node,
      /*includeElementAccess*/
      true,
      /*skipPastOuterExpressions*/
      true
    ) || isTaggedTemplateTag(
      node,
      /*includeElementAccess*/
      true,
      /*skipPastOuterExpressions*/
      true
    ) || isDecoratorTarget(
      node,
      /*includeElementAccess*/
      true,
      /*skipPastOuterExpressions*/
      true
    ) || isJsxOpeningLikeElementTagName(
      node,
      /*includeElementAccess*/
      true,
      /*skipPastOuterExpressions*/
      true
    ) || isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node)) {
      const sourceFile = node.getSourceFile();
      const ancestor = findAncestor(node, isValidCallHierarchyDeclaration) || sourceFile;
      return { declaration: ancestor, range: createTextRangeFromNode(node, sourceFile) };
    }
  }
}
function getCallSiteGroupKey(entry) {
  return getNodeId(entry.declaration);
}
function createCallHierarchyIncomingCall(from, fromSpans) {
  return { from, fromSpans };
}
function convertCallSiteGroupToIncomingCall(program, entries) {
  return createCallHierarchyIncomingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, (entry) => createTextSpanFromRange(entry.range)));
}
function getIncomingCalls(program, declaration, cancellationToken) {
  if (isSourceFile(declaration) || isModuleDeclaration(declaration) || isClassStaticBlockDeclaration(declaration)) {
    return [];
  }
  const location = getCallHierarchyDeclarationReferenceNode(declaration);
  const calls = filter(ts_FindAllReferences_exports.findReferenceOrRenameEntries(
    program,
    cancellationToken,
    program.getSourceFiles(),
    location,
    /*position*/
    0,
    { use: ts_FindAllReferences_exports.FindReferencesUse.References },
    convertEntryToCallSite
  ), isDefined);
  return calls ? group(calls, getCallSiteGroupKey, (entries) => convertCallSiteGroupToIncomingCall(program, entries)) : [];
}
function createCallSiteCollector(program, callSites) {
  function recordCallSite(node) {
    const target = isTaggedTemplateExpression(node) ? node.tag : isJsxOpeningLikeElement(node) ? node.tagName : isAccessExpression(node) ? node : isClassStaticBlockDeclaration(node) ? node : node.expression;
    const declaration = resolveCallHierarchyDeclaration(program, target);
    if (declaration) {
      const range = createTextRangeFromNode(target, node.getSourceFile());
      if (isArray(declaration)) {
        for (const decl of declaration) {
          callSites.push({ declaration: decl, range });
        }
      } else {
        callSites.push({ declaration, range });
      }
    }
  }
  function collect(node) {
    if (!node) return;
    if (node.flags & 33554432 /* Ambient */) {
      return;
    }
    if (isValidCallHierarchyDeclaration(node)) {
      if (isClassLike(node)) {
        for (const member of node.members) {
          if (member.name && isComputedPropertyName(member.name)) {
            collect(member.name.expression);
          }
        }
      }
      return;
    }
    switch (node.kind) {
      case 80 /* Identifier */:
      case 271 /* ImportEqualsDeclaration */:
      case 272 /* ImportDeclaration */:
      case 278 /* ExportDeclaration */:
      case 264 /* InterfaceDeclaration */:
      case 265 /* TypeAliasDeclaration */:
        return;
      case 175 /* ClassStaticBlockDeclaration */:
        recordCallSite(node);
        return;
      case 216 /* TypeAssertionExpression */:
      case 234 /* AsExpression */:
        collect(node.expression);
        return;
      case 260 /* VariableDeclaration */:
      case 169 /* Parameter */:
        collect(node.name);
        collect(node.initializer);
        return;
      case 213 /* CallExpression */:
        recordCallSite(node);
        collect(node.expression);
        forEach(node.arguments, collect);
        return;
      case 214 /* NewExpression */:
        recordCallSite(node);
        collect(node.expression);
        forEach(node.arguments, collect);
        return;
      case 215 /* TaggedTemplateExpression */:
        recordCallSite(node);
        collect(node.tag);
        collect(node.template);
        return;
      case 286 /* JsxOpeningElement */:
      case 285 /* JsxSelfClosingElement */:
        recordCallSite(node);
        collect(node.tagName);
        collect(node.attributes);
        return;
      case 170 /* Decorator */:
        recordCallSite(node);
        collect(node.expression);
        return;
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        recordCallSite(node);
        forEachChild(node, collect);
        break;
      case 238 /* SatisfiesExpression */:
        collect(node.expression);
        return;
    }
    if (isPartOfTypeNode(node)) {
      return;
    }
    forEachChild(node, collect);
  }
  return collect;
}
function collectCallSitesOfSourceFile(node, collect) {
  forEach(node.statements, collect);
}
function collectCallSitesOfModuleDeclaration(node, collect) {
  if (!hasSyntacticModifier(node, 128 /* Ambient */) && node.body && isModuleBlock(node.body)) {
    forEach(node.body.statements, collect);
  }
}
function collectCallSitesOfFunctionLikeDeclaration(typeChecker, node, collect) {
  const implementation = findImplementation(typeChecker, node);
  if (implementation) {
    forEach(implementation.parameters, collect);
    collect(implementation.body);
  }
}
function collectCallSitesOfClassStaticBlockDeclaration(node, collect) {
  collect(node.body);
}
function collectCallSitesOfClassLikeDeclaration(node, collect) {
  forEach(node.modifiers, collect);
  const heritage = getClassExtendsHeritageElement(node);
  if (heritage) {
    collect(heritage.expression);
  }
  for (const member of node.members) {
    if (canHaveModifiers(member)) {
      forEach(member.modifiers, collect);
    }
    if (isPropertyDeclaration(member)) {
      collect(member.initializer);
    } else if (isConstructorDeclaration(member) && member.body) {
      forEach(member.parameters, collect);
      collect(member.body);
    } else if (isClassStaticBlockDeclaration(member)) {
      collect(member);
    }
  }
}
function collectCallSites(program, node) {
  const callSites = [];
  const collect = createCallSiteCollector(program, callSites);
  switch (node.kind) {
    case 307 /* SourceFile */:
      collectCallSitesOfSourceFile(node, collect);
      break;
    case 267 /* ModuleDeclaration */:
      collectCallSitesOfModuleDeclaration(node, collect);
      break;
    case 262 /* FunctionDeclaration */:
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
    case 174 /* MethodDeclaration */:
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
      collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect);
      break;
    case 263 /* ClassDeclaration */:
    case 231 /* ClassExpression */:
      collectCallSitesOfClassLikeDeclaration(node, collect);
      break;
    case 175 /* ClassStaticBlockDeclaration */:
      collectCallSitesOfClassStaticBlockDeclaration(node, collect);
      break;
    default:
      Debug.assertNever(node);
  }
  return callSites;
}
function createCallHierarchyOutgoingCall(to, fromSpans) {
  return { to, fromSpans };
}
function convertCallSiteGroupToOutgoingCall(program, entries) {
  return createCallHierarchyOutgoingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, (entry) => createTextSpanFromRange(entry.range)));
}
function getOutgoingCalls(program, declaration) {
  if (declaration.flags & 33554432 /* Ambient */ || isMethodSignature(declaration)) {
    return [];
  }
  return group(collectCallSites(program, declaration), getCallSiteGroupKey, (entries) => convertCallSiteGroupToOutgoingCall(program, entries));
}

// src/services/_namespaces/ts.classifier.ts
var ts_classifier_exports = {};
__export(ts_classifier_exports, {
  v2020: () => ts_classifier_v2020_exports
});

// src/services/_namespaces/ts.classifier.v2020.ts
var ts_classifier_v2020_exports = {};
__export(ts_classifier_v2020_exports, {
  TokenEncodingConsts: () => TokenEncodingConsts,
  TokenModifier: () => TokenModifier,
  TokenType: () => TokenType,
  getEncodedSemanticClassifications: () => getEncodedSemanticClassifications2,
  getSemanticClassifications: () => getSemanticClassifications2
});

// src/services/_namespaces/ts.codefix.ts
var ts_codefix_exports = {};
__export(ts_codefix_exports, {
  PreserveOptionalFlags: () => PreserveOptionalFlags,
  addNewNodeForMemberSymbol: () => addNewNodeForMemberSymbol,
  codeFixAll: () => codeFixAll,
  createCodeFixAction: () => createCodeFixAction,
  createCodeFixActionMaybeFixAll: () => createCodeFixActionMaybeFixAll,
  createCodeFixActionWithoutFixAll: () => createCodeFixActionWithoutFixAll,
  createCombinedCodeActions: () => createCombinedCodeActions,
  createFileTextChanges: () => createFileTextChanges,
  createImportAdder: () => createImportAdder,
  createImportSpecifierResolver: () => createImportSpecifierResolver,
  createMissingMemberNodes: () => createMissingMemberNodes,
  createSignatureDeclarationFromCallExpression: () => createSignatureDeclarationFromCallExpression,
  createSignatureDeclarationFromSignature: () => createSignatureDeclarationFromSignature,
  createStubbedBody: () => createStubbedBody,
  eachDiagnostic: () => eachDiagnostic,
  findAncestorMatchingSpan: () => findAncestorMatchingSpan,
  generateAccessorFromProperty: () => generateAccessorFromProperty,
  getAccessorConvertiblePropertyAtPosition: () => getAccessorConvertiblePropertyAtPosition,
  getAllFixes: () => getAllFixes,
  getAllSupers: () => getAllSupers,
  getFixes: () => getFixes,
  getImportCompletionAction: () => getImportCompletionAction,
  getImportKind: () => getImportKind,
  getJSDocTypedefNodes: () => getJSDocTypedefNodes,
  getNoopSymbolTrackerWithResolver: () => getNoopSymbolTrackerWithResolver,
  getPromoteTypeOnlyCompletionAction: () => getPromoteTypeOnlyCompletionAction,
  getSupportedErrorCodes: () => getSupportedErrorCodes,
  importFixName: () => importFixName,
  importSymbols: () => importSymbols,
  parameterShouldGetTypeFromJSDoc: () => parameterShouldGetTypeFromJSDoc,
  registerCodeFix: () => registerCodeFix,
  setJsonCompilerOptionValue: () => setJsonCompilerOptionValue,
  setJsonCompilerOptionValues: () => setJsonCompilerOptionValues,
  tryGetAutoImportableReferenceFromTypeNode: () => tryGetAutoImportableReferenceFromTypeNode,
  typeNodeToAutoImportableTypeNode: () => typeNodeToAutoImportableTypeNode,
  typePredicateToAutoImportableTypeNode: () => typePredicateToAutoImportableTypeNode,
  typeToAutoImportableTypeNode: () => typeToAutoImportableTypeNode,
  typeToMinimizedReferenceType: () => typeToMinimizedReferenceType
});

// src/services/codeFixProvider.ts
var errorCodeToFixes = createMultiMap();
var fixIdToRegistration = /* @__PURE__ */ new Map();
function createCodeFixActionWithoutFixAll(fixName8, changes, description3) {
  return createCodeFixActionWorker(
    fixName8,
    diagnosticToString(description3),
    changes,
    /*fixId*/
    void 0,
    /*fixAllDescription*/
    void 0
  );
}
function createCodeFixAction(fixName8, changes, description3, fixId56, fixAllDescription, command) {
  return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId56, diagnosticToString(fixAllDescription), command);
}
function createCodeFixActionMaybeFixAll(fixName8, changes, description3, fixId56, fixAllDescription, command) {
  return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId56, fixAllDescription && diagnosticToString(fixAllDescription), command);
}
function createCodeFixActionWorker(fixName8, description3, changes, fixId56, fixAllDescription, command) {
  return { fixName: fixName8, description: description3, changes, fixId: fixId56, fixAllDescription, commands: command ? [command] : void 0 };
}
function registerCodeFix(reg) {
  for (const error2 of reg.errorCodes) {
    errorCodeToFixesArray = void 0;
    errorCodeToFixes.add(String(error2), reg);
  }
  if (reg.fixIds) {
    for (const fixId56 of reg.fixIds) {
      Debug.assert(!fixIdToRegistration.has(fixId56));
      fixIdToRegistration.set(fixId56, reg);
    }
  }
}
var errorCodeToFixesArray;
function getSupportedErrorCodes() {
  return errorCodeToFixesArray ?? (errorCodeToFixesArray = arrayFrom(errorCodeToFixes.keys()));
}
function removeFixIdIfFixAllUnavailable(registration, diagnostics) {
  const { errorCodes: errorCodes68 } = registration;
  let maybeFixableDiagnostics = 0;
  for (const diag2 of diagnostics) {
    if (contains(errorCodes68, diag2.code)) maybeFixableDiagnostics++;
    if (maybeFixableDiagnostics > 1) break;
  }
  const fixAllUnavailable = maybeFixableDiagnostics < 2;
  return ({ fixId: fixId56, fixAllDescription, ...action }) => {
    return fixAllUnavailable ? action : { ...action, fixId: fixId56, fixAllDescription };
  };
}
function getFixes(context) {
  const diagnostics = getDiagnostics(context);
  const registrations = errorCodeToFixes.get(String(context.errorCode));
  return flatMap(registrations, (f) => map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics)));
}
function getAllFixes(context) {
  return fixIdToRegistration.get(cast(context.fixId, isString)).getAllCodeActions(context);
}
function createCombinedCodeActions(changes, commands) {
  return { changes, commands };
}
function createFileTextChanges(fileName, textChanges2) {
  return { fileName, textChanges: textChanges2 };
}
function codeFixAll(context, errorCodes68, use) {
  const commands = [];
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => eachDiagnostic(context, errorCodes68, (diag2) => use(t, diag2, commands)));
  return createCombinedCodeActions(changes, commands.length === 0 ? void 0 : commands);
}
function eachDiagnostic(context, errorCodes68, cb) {
  for (const diag2 of getDiagnostics(context)) {
    if (contains(errorCodes68, diag2.code)) {
      cb(diag2);
    }
  }
}
function getDiagnostics({ program, sourceFile, cancellationToken }) {
  const diagnostics = [
    ...program.getSemanticDiagnostics(sourceFile, cancellationToken),
    ...program.getSyntacticDiagnostics(sourceFile, cancellationToken),
    ...computeSuggestionDiagnostics(sourceFile, program, cancellationToken)
  ];
  if (getEmitDeclarations(program.getCompilerOptions())) {
    diagnostics.push(
      ...program.getDeclarationDiagnostics(sourceFile, cancellationToken)
    );
  }
  return diagnostics;
}

// src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts
var fixId = "addConvertToUnknownForNonOverlappingTypes";
var errorCodes = [Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code];
registerCodeFix({
  errorCodes,
  getCodeActions: function getCodeActionsToAddConvertToUnknownForNonOverlappingTypes(context) {
    const assertion = getAssertion(context.sourceFile, context.span.start);
    if (assertion === void 0) return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange(t, context.sourceFile, assertion));
    return [createCodeFixAction(fixId, changes, Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)];
  },
  fixIds: [fixId],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes, (changes, diag2) => {
    const assertion = getAssertion(diag2.file, diag2.start);
    if (assertion) {
      makeChange(changes, diag2.file, assertion);
    }
  })
});
function makeChange(changeTracker, sourceFile, assertion) {
  const replacement = isAsExpression(assertion) ? factory.createAsExpression(assertion.expression, factory.createKeywordTypeNode(159 /* UnknownKeyword */)) : factory.createTypeAssertion(factory.createKeywordTypeNode(159 /* UnknownKeyword */), assertion.expression);
  changeTracker.replaceNode(sourceFile, assertion.expression, replacement);
}
function getAssertion(sourceFile, pos) {
  if (isInJSFile(sourceFile)) return void 0;
  return findAncestor(getTokenAtPosition(sourceFile, pos), (n) => isAsExpression(n) || isTypeAssertionExpression(n));
}

// src/services/codefixes/addEmptyExportDeclaration.ts
registerCodeFix({
  errorCodes: [
    Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code,
    Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code,
    Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code
  ],
  getCodeActions: function getCodeActionsToAddEmptyExportDeclaration(context) {
    const { sourceFile } = context;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => {
      const exportDeclaration = factory.createExportDeclaration(
        /*modifiers*/
        void 0,
        /*isTypeOnly*/
        false,
        factory.createNamedExports([]),
        /*moduleSpecifier*/
        void 0
      );
      changes2.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration);
    });
    return [createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, Diagnostics.Add_export_to_make_this_file_into_a_module)];
  }
});

// src/services/codefixes/addMissingAsync.ts
var fixId2 = "addMissingAsync";
var errorCodes2 = [
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1.code,
  Diagnostics.Type_0_is_not_comparable_to_type_1.code
];
registerCodeFix({
  fixIds: [fixId2],
  errorCodes: errorCodes2,
  getCodeActions: function getCodeActionsToAddMissingAsync(context) {
    const { sourceFile, errorCode, cancellationToken, program, span } = context;
    const diagnostic = find(program.getTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode));
    const directSpan = diagnostic && diagnostic.relatedInformation && find(diagnostic.relatedInformation, (r) => r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code);
    const decl = getFixableErrorSpanDeclaration(sourceFile, directSpan);
    if (!decl) {
      return;
    }
    const trackChanges = (cb) => ts_textChanges_exports.ChangeTracker.with(context, cb);
    return [getFix(context, decl, trackChanges)];
  },
  getAllCodeActions: (context) => {
    const { sourceFile } = context;
    const fixedDeclarations = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes2, (t, diagnostic) => {
      const span = diagnostic.relatedInformation && find(diagnostic.relatedInformation, (r) => r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code);
      const decl = getFixableErrorSpanDeclaration(sourceFile, span);
      if (!decl) {
        return;
      }
      const trackChanges = (cb) => (cb(t), []);
      return getFix(context, decl, trackChanges, fixedDeclarations);
    });
  }
});
function getFix(context, decl, trackChanges, fixedDeclarations) {
  const changes = trackChanges((t) => makeChange2(t, context.sourceFile, decl, fixedDeclarations));
  return createCodeFixAction(fixId2, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId2, Diagnostics.Add_all_missing_async_modifiers);
}
function makeChange2(changeTracker, sourceFile, insertionSite, fixedDeclarations) {
  if (fixedDeclarations) {
    if (fixedDeclarations.has(getNodeId(insertionSite))) {
      return;
    }
  }
  fixedDeclarations == null ? void 0 : fixedDeclarations.add(getNodeId(insertionSite));
  const cloneWithModifier = factory.replaceModifiers(
    getSynthesizedDeepClone(
      insertionSite,
      /*includeTrivia*/
      true
    ),
    factory.createNodeArray(factory.createModifiersFromModifierFlags(getSyntacticModifierFlags(insertionSite) | 1024 /* Async */))
  );
  changeTracker.replaceNode(
    sourceFile,
    insertionSite,
    cloneWithModifier
  );
}
function getFixableErrorSpanDeclaration(sourceFile, span) {
  if (!span) return void 0;
  const token = getTokenAtPosition(sourceFile, span.start);
  const decl = findAncestor(token, (node) => {
    if (node.getStart(sourceFile) < span.start || node.getEnd() > textSpanEnd(span)) {
      return "quit";
    }
    return (isArrowFunction(node) || isMethodDeclaration(node) || isFunctionExpression(node) || isFunctionDeclaration(node)) && textSpansEqual(span, createTextSpanFromNode(node, sourceFile));
  });
  return decl;
}
function getIsMatchingAsyncError(span, errorCode) {
  return ({ start, length: length2, relatedInformation, code }) => isNumber(start) && isNumber(length2) && textSpansEqual({ start, length: length2 }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, (related) => related.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code);
}

// src/services/codefixes/addMissingAwait.ts
var fixId3 = "addMissingAwait";
var propertyAccessCode = Diagnostics.Property_0_does_not_exist_on_type_1.code;
var callableConstructableErrorCodes = [
  Diagnostics.This_expression_is_not_callable.code,
  Diagnostics.This_expression_is_not_constructable.code
];
var errorCodes3 = [
  Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type.code,
  Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
  Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
  Diagnostics.Operator_0_cannot_be_applied_to_type_1.code,
  Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code,
  Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap.code,
  Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code,
  Diagnostics.Type_0_is_not_an_array_type.code,
  Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code,
  Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher.code,
  Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
  Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
  Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
  Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator.code,
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
  propertyAccessCode,
  ...callableConstructableErrorCodes
];
registerCodeFix({
  fixIds: [fixId3],
  errorCodes: errorCodes3,
  getCodeActions: function getCodeActionsToAddMissingAwait(context) {
    const { sourceFile, errorCode, span, cancellationToken, program } = context;
    const expression = getAwaitErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program);
    if (!expression) {
      return;
    }
    const checker = context.program.getTypeChecker();
    const trackChanges = (cb) => ts_textChanges_exports.ChangeTracker.with(context, cb);
    return compact([
      getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges),
      getUseSiteFix(context, expression, errorCode, checker, trackChanges)
    ]);
  },
  getAllCodeActions: (context) => {
    const { sourceFile, program, cancellationToken } = context;
    const checker = context.program.getTypeChecker();
    const fixedDeclarations = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes3, (t, diagnostic) => {
      const expression = getAwaitErrorSpanExpression(sourceFile, diagnostic.code, diagnostic, cancellationToken, program);
      if (!expression) {
        return;
      }
      const trackChanges = (cb) => (cb(t), []);
      return getDeclarationSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations) || getUseSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations);
    });
  }
});
function getAwaitErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program) {
  const expression = getFixableErrorSpanExpression(sourceFile, span);
  return expression && isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) && isInsideAwaitableBody(expression) ? expression : void 0;
}
function getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) {
  const { sourceFile, program, cancellationToken } = context;
  const awaitableInitializers = findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker);
  if (awaitableInitializers) {
    const initializerChanges = trackChanges((t) => {
      forEach(awaitableInitializers.initializers, ({ expression: expression2 }) => makeChange3(t, errorCode, sourceFile, checker, expression2, fixedDeclarations));
      if (fixedDeclarations && awaitableInitializers.needsSecondPassForFixAll) {
        makeChange3(t, errorCode, sourceFile, checker, expression, fixedDeclarations);
      }
    });
    return createCodeFixActionWithoutFixAll(
      "addMissingAwaitToInitializer",
      initializerChanges,
      awaitableInitializers.initializers.length === 1 ? [Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name] : Diagnostics.Add_await_to_initializers
    );
  }
}
function getUseSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) {
  const changes = trackChanges((t) => makeChange3(t, errorCode, context.sourceFile, checker, expression, fixedDeclarations));
  return createCodeFixAction(fixId3, changes, Diagnostics.Add_await, fixId3, Diagnostics.Fix_all_expressions_possibly_missing_await);
}
function isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) {
  const checker = program.getTypeChecker();
  const diagnostics = checker.getDiagnostics(sourceFile, cancellationToken);
  return some(diagnostics, ({ start, length: length2, relatedInformation, code }) => isNumber(start) && isNumber(length2) && textSpansEqual({ start, length: length2 }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, (related) => related.code === Diagnostics.Did_you_forget_to_use_await.code));
}
function findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker) {
  const identifiers = getIdentifiersFromErrorSpanExpression(expression, checker);
  if (!identifiers) {
    return;
  }
  let isCompleteFix = identifiers.isCompleteFix;
  let initializers;
  for (const identifier of identifiers.identifiers) {
    const symbol = checker.getSymbolAtLocation(identifier);
    if (!symbol) {
      continue;
    }
    const declaration = tryCast(symbol.valueDeclaration, isVariableDeclaration);
    const variableName = declaration && tryCast(declaration.name, isIdentifier);
    const variableStatement = getAncestor(declaration, 243 /* VariableStatement */);
    if (!declaration || !variableStatement || declaration.type || !declaration.initializer || variableStatement.getSourceFile() !== sourceFile || hasSyntacticModifier(variableStatement, 32 /* Export */) || !variableName || !isInsideAwaitableBody(declaration.initializer)) {
      isCompleteFix = false;
      continue;
    }
    const diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken);
    const isUsedElsewhere = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(variableName, checker, sourceFile, (reference) => {
      return identifier !== reference && !symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker);
    });
    if (isUsedElsewhere) {
      isCompleteFix = false;
      continue;
    }
    (initializers || (initializers = [])).push({
      expression: declaration.initializer,
      declarationSymbol: symbol
    });
  }
  return initializers && {
    initializers,
    needsSecondPassForFixAll: !isCompleteFix
  };
}
function getIdentifiersFromErrorSpanExpression(expression, checker) {
  if (isPropertyAccessExpression(expression.parent) && isIdentifier(expression.parent.expression)) {
    return { identifiers: [expression.parent.expression], isCompleteFix: true };
  }
  if (isIdentifier(expression)) {
    return { identifiers: [expression], isCompleteFix: true };
  }
  if (isBinaryExpression(expression)) {
    let sides;
    let isCompleteFix = true;
    for (const side of [expression.left, expression.right]) {
      const type = checker.getTypeAtLocation(side);
      if (checker.getPromisedTypeOfPromise(type)) {
        if (!isIdentifier(side)) {
          isCompleteFix = false;
          continue;
        }
        (sides || (sides = [])).push(side);
      }
    }
    return sides && { identifiers: sides, isCompleteFix };
  }
}
function symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker) {
  const errorNode = isPropertyAccessExpression(reference.parent) ? reference.parent.name : isBinaryExpression(reference.parent) ? reference.parent : reference;
  const diagnostic = find(diagnostics, (diagnostic2) => diagnostic2.start === errorNode.getStart(sourceFile) && diagnostic2.start + diagnostic2.length === errorNode.getEnd());
  return diagnostic && contains(errorCodes3, diagnostic.code) || // A Promise is usually not correct in a binary expression (it's not valid
  // in an arithmetic expression and an equality comparison seems unusual),
  // but if the other side of the binary expression has an error, the side
  // is typed `any` which will squash the error that would identify this
  // Promise as an invalid operand. So if the whole binary expression is
  // typed `any` as a result, there is a strong likelihood that this Promise
  // is accidentally missing `await`.
  checker.getTypeAtLocation(errorNode).flags & 1 /* Any */;
}
function isInsideAwaitableBody(node) {
  return node.flags & 65536 /* AwaitContext */ || !!findAncestor(node, (ancestor) => ancestor.parent && isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || isBlock(ancestor) && (ancestor.parent.kind === 262 /* FunctionDeclaration */ || ancestor.parent.kind === 218 /* FunctionExpression */ || ancestor.parent.kind === 219 /* ArrowFunction */ || ancestor.parent.kind === 174 /* MethodDeclaration */));
}
function makeChange3(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) {
  if (isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) {
    const exprType = checker.getTypeAtLocation(insertionSite);
    const asyncIter = checker.getAnyAsyncIterableType();
    if (asyncIter && checker.isTypeAssignableTo(exprType, asyncIter)) {
      const forOf = insertionSite.parent;
      changeTracker.replaceNode(sourceFile, forOf, factory.updateForOfStatement(forOf, factory.createToken(135 /* AwaitKeyword */), forOf.initializer, forOf.expression, forOf.statement));
      return;
    }
  }
  if (isBinaryExpression(insertionSite)) {
    for (const side of [insertionSite.left, insertionSite.right]) {
      if (fixedDeclarations && isIdentifier(side)) {
        const symbol = checker.getSymbolAtLocation(side);
        if (symbol && fixedDeclarations.has(getSymbolId(symbol))) {
          continue;
        }
      }
      const type = checker.getTypeAtLocation(side);
      const newNode = checker.getPromisedTypeOfPromise(type) ? factory.createAwaitExpression(side) : side;
      changeTracker.replaceNode(sourceFile, side, newNode);
    }
  } else if (errorCode === propertyAccessCode && isPropertyAccessExpression(insertionSite.parent)) {
    if (fixedDeclarations && isIdentifier(insertionSite.parent.expression)) {
      const symbol = checker.getSymbolAtLocation(insertionSite.parent.expression);
      if (symbol && fixedDeclarations.has(getSymbolId(symbol))) {
        return;
      }
    }
    changeTracker.replaceNode(
      sourceFile,
      insertionSite.parent.expression,
      factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite.parent.expression))
    );
    insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile);
  } else if (contains(callableConstructableErrorCodes, errorCode) && isCallOrNewExpression(insertionSite.parent)) {
    if (fixedDeclarations && isIdentifier(insertionSite)) {
      const symbol = checker.getSymbolAtLocation(insertionSite);
      if (symbol && fixedDeclarations.has(getSymbolId(symbol))) {
        return;
      }
    }
    changeTracker.replaceNode(sourceFile, insertionSite, factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite)));
    insertLeadingSemicolonIfNeeded(changeTracker, insertionSite, sourceFile);
  } else {
    if (fixedDeclarations && isVariableDeclaration(insertionSite.parent) && isIdentifier(insertionSite.parent.name)) {
      const symbol = checker.getSymbolAtLocation(insertionSite.parent.name);
      if (symbol && !tryAddToSet(fixedDeclarations, getSymbolId(symbol))) {
        return;
      }
    }
    changeTracker.replaceNode(sourceFile, insertionSite, factory.createAwaitExpression(insertionSite));
  }
}
function insertLeadingSemicolonIfNeeded(changeTracker, beforeNode, sourceFile) {
  const precedingToken = findPrecedingToken(beforeNode.pos, sourceFile);
  if (precedingToken && positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
    changeTracker.insertText(sourceFile, beforeNode.getStart(sourceFile), ";");
  }
}

// src/services/codefixes/addMissingConst.ts
var fixId4 = "addMissingConst";
var errorCodes4 = [
  Diagnostics.Cannot_find_name_0.code,
  Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code
];
registerCodeFix({
  errorCodes: errorCodes4,
  getCodeActions: function getCodeActionsToAddMissingConst(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange4(t, context.sourceFile, context.span.start, context.program));
    if (changes.length > 0) {
      return [createCodeFixAction(fixId4, changes, Diagnostics.Add_const_to_unresolved_variable, fixId4, Diagnostics.Add_const_to_all_unresolved_variables)];
    }
  },
  fixIds: [fixId4],
  getAllCodeActions: (context) => {
    const fixedNodes = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes4, (changes, diag2) => makeChange4(changes, diag2.file, diag2.start, context.program, fixedNodes));
  }
});
function makeChange4(changeTracker, sourceFile, pos, program, fixedNodes) {
  const token = getTokenAtPosition(sourceFile, pos);
  const forInitializer = findAncestor(token, (node) => isForInOrOfStatement(node.parent) ? node.parent.initializer === node : isPossiblyPartOfDestructuring(node) ? false : "quit");
  if (forInitializer) return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes);
  const parent2 = token.parent;
  if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */ && isExpressionStatement(parent2.parent)) {
    return applyChange(changeTracker, token, sourceFile, fixedNodes);
  }
  if (isArrayLiteralExpression(parent2)) {
    const checker = program.getTypeChecker();
    if (!every(parent2.elements, (element) => arrayElementCouldBeVariableDeclaration(element, checker))) {
      return;
    }
    return applyChange(changeTracker, parent2, sourceFile, fixedNodes);
  }
  const commaExpression = findAncestor(token, (node) => isExpressionStatement(node.parent) ? true : isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit");
  if (commaExpression) {
    const checker = program.getTypeChecker();
    if (!expressionCouldBeVariableDeclaration(commaExpression, checker)) {
      return;
    }
    return applyChange(changeTracker, commaExpression, sourceFile, fixedNodes);
  }
}
function applyChange(changeTracker, initializer, sourceFile, fixedNodes) {
  if (!fixedNodes || tryAddToSet(fixedNodes, initializer)) {
    changeTracker.insertModifierBefore(sourceFile, 87 /* ConstKeyword */, initializer);
  }
}
function isPossiblyPartOfDestructuring(node) {
  switch (node.kind) {
    case 80 /* Identifier */:
    case 209 /* ArrayLiteralExpression */:
    case 210 /* ObjectLiteralExpression */:
    case 303 /* PropertyAssignment */:
    case 304 /* ShorthandPropertyAssignment */:
      return true;
    default:
      return false;
  }
}
function arrayElementCouldBeVariableDeclaration(expression, checker) {
  const identifier = isIdentifier(expression) ? expression : isAssignmentExpression(
    expression,
    /*excludeCompoundAssignment*/
    true
  ) && isIdentifier(expression.left) ? expression.left : void 0;
  return !!identifier && !checker.getSymbolAtLocation(identifier);
}
function isPossiblyPartOfCommaSeperatedInitializer(node) {
  switch (node.kind) {
    case 80 /* Identifier */:
    case 226 /* BinaryExpression */:
    case 28 /* CommaToken */:
      return true;
    default:
      return false;
  }
}
function expressionCouldBeVariableDeclaration(expression, checker) {
  if (!isBinaryExpression(expression)) {
    return false;
  }
  if (expression.operatorToken.kind === 28 /* CommaToken */) {
    return every([expression.left, expression.right], (expression2) => expressionCouldBeVariableDeclaration(expression2, checker));
  }
  return expression.operatorToken.kind === 64 /* EqualsToken */ && isIdentifier(expression.left) && !checker.getSymbolAtLocation(expression.left);
}

// src/services/codefixes/addMissingDeclareProperty.ts
var fixId5 = "addMissingDeclareProperty";
var errorCodes5 = [
  Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration.code
];
registerCodeFix({
  errorCodes: errorCodes5,
  getCodeActions: function getCodeActionsToAddMissingDeclareOnProperty(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange5(t, context.sourceFile, context.span.start));
    if (changes.length > 0) {
      return [createCodeFixAction(fixId5, changes, Diagnostics.Prefix_with_declare, fixId5, Diagnostics.Prefix_all_incorrect_property_declarations_with_declare)];
    }
  },
  fixIds: [fixId5],
  getAllCodeActions: (context) => {
    const fixedNodes = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes5, (changes, diag2) => makeChange5(changes, diag2.file, diag2.start, fixedNodes));
  }
});
function makeChange5(changeTracker, sourceFile, pos, fixedNodes) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (!isIdentifier(token)) {
    return;
  }
  const declaration = token.parent;
  if (declaration.kind === 172 /* PropertyDeclaration */ && (!fixedNodes || tryAddToSet(fixedNodes, declaration))) {
    changeTracker.insertModifierBefore(sourceFile, 138 /* DeclareKeyword */, declaration);
  }
}

// src/services/codefixes/addMissingInvocationForDecorator.ts
var fixId6 = "addMissingInvocationForDecorator";
var errorCodes6 = [Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code];
registerCodeFix({
  errorCodes: errorCodes6,
  getCodeActions: function getCodeActionsToAddMissingInvocationForDecorator(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange6(t, context.sourceFile, context.span.start));
    return [createCodeFixAction(fixId6, changes, Diagnostics.Call_decorator_expression, fixId6, Diagnostics.Add_to_all_uncalled_decorators)];
  },
  fixIds: [fixId6],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes6, (changes, diag2) => makeChange6(changes, diag2.file, diag2.start))
});
function makeChange6(changeTracker, sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  const decorator = findAncestor(token, isDecorator);
  Debug.assert(!!decorator, "Expected position to be owned by a decorator.");
  const replacement = factory.createCallExpression(
    decorator.expression,
    /*typeArguments*/
    void 0,
    /*argumentsArray*/
    void 0
  );
  changeTracker.replaceNode(sourceFile, decorator.expression, replacement);
}

// src/services/codefixes/addMissingResolutionModeImportAttribute.ts
var fixId7 = "addMissingResolutionModeImportAttribute";
var errorCodes7 = [
  Diagnostics.Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute.code,
  Diagnostics.Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute.code
];
registerCodeFix({
  errorCodes: errorCodes7,
  getCodeActions: function getCodeActionsToAddMissingResolutionModeImportAttribute(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange7(t, context.sourceFile, context.span.start, context.program, context.host, context.preferences));
    return [createCodeFixAction(fixId7, changes, Diagnostics.Add_resolution_mode_import_attribute, fixId7, Diagnostics.Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it)];
  },
  fixIds: [fixId7],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes7, (changes, diag2) => makeChange7(changes, diag2.file, diag2.start, context.program, context.host, context.preferences))
});
function makeChange7(changeTracker, sourceFile, pos, program, host, preferences) {
  var _a, _b, _c;
  const token = getTokenAtPosition(sourceFile, pos);
  const importNode = findAncestor(token, or(isImportDeclaration, isImportTypeNode));
  Debug.assert(!!importNode, "Expected position to be owned by an ImportDeclaration or ImportType.");
  const useSingleQuotes = getQuotePreference(sourceFile, preferences) === 0 /* Single */;
  const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(importNode);
  const canUseImportMode = !moduleSpecifier || ((_a = resolveModuleName(
    moduleSpecifier.text,
    sourceFile.fileName,
    program.getCompilerOptions(),
    host,
    program.getModuleResolutionCache(),
    /*redirectedReference*/
    void 0,
    99 /* ESNext */
  ).resolvedModule) == null ? void 0 : _a.resolvedFileName) === ((_c = (_b = program.getResolvedModuleFromModuleSpecifier(
    moduleSpecifier,
    sourceFile
  )) == null ? void 0 : _b.resolvedModule) == null ? void 0 : _c.resolvedFileName);
  const attributes = importNode.attributes ? factory.updateImportAttributes(
    importNode.attributes,
    factory.createNodeArray([
      ...importNode.attributes.elements,
      factory.createImportAttribute(
        factory.createStringLiteral("resolution-mode", useSingleQuotes),
        factory.createStringLiteral(canUseImportMode ? "import" : "require", useSingleQuotes)
      )
    ], importNode.attributes.elements.hasTrailingComma),
    importNode.attributes.multiLine
  ) : factory.createImportAttributes(
    factory.createNodeArray([
      factory.createImportAttribute(
        factory.createStringLiteral("resolution-mode", useSingleQuotes),
        factory.createStringLiteral(canUseImportMode ? "import" : "require", useSingleQuotes)
      )
    ])
  );
  if (importNode.kind === 272 /* ImportDeclaration */) {
    changeTracker.replaceNode(
      sourceFile,
      importNode,
      factory.updateImportDeclaration(
        importNode,
        importNode.modifiers,
        importNode.importClause,
        importNode.moduleSpecifier,
        attributes
      )
    );
  } else {
    changeTracker.replaceNode(
      sourceFile,
      importNode,
      factory.updateImportTypeNode(
        importNode,
        importNode.argument,
        attributes,
        importNode.qualifier,
        importNode.typeArguments
      )
    );
  }
}

// src/services/codefixes/addNameToNamelessParameter.ts
var fixId8 = "addNameToNamelessParameter";
var errorCodes8 = [Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code];
registerCodeFix({
  errorCodes: errorCodes8,
  getCodeActions: function getCodeActionsToAddNameToNamelessParameter(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange8(t, context.sourceFile, context.span.start));
    return [createCodeFixAction(fixId8, changes, Diagnostics.Add_parameter_name, fixId8, Diagnostics.Add_names_to_all_parameters_without_names)];
  },
  fixIds: [fixId8],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes8, (changes, diag2) => makeChange8(changes, diag2.file, diag2.start))
});
function makeChange8(changeTracker, sourceFile, start) {
  const token = getTokenAtPosition(sourceFile, start);
  const param = token.parent;
  if (!isParameter(param)) {
    return Debug.fail("Tried to add a parameter name to a non-parameter: " + Debug.formatSyntaxKind(token.kind));
  }
  const i = param.parent.parameters.indexOf(param);
  Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one.");
  Debug.assert(i > -1, "Parameter not found in parent parameter list.");
  let end = param.name.getEnd();
  let typeNode = factory.createTypeReferenceNode(
    param.name,
    /*typeArguments*/
    void 0
  );
  let nextParam = tryGetNextParam(sourceFile, param);
  while (nextParam) {
    typeNode = factory.createArrayTypeNode(typeNode);
    end = nextParam.getEnd();
    nextParam = tryGetNextParam(sourceFile, nextParam);
  }
  const replacement = factory.createParameterDeclaration(
    param.modifiers,
    param.dotDotDotToken,
    "arg" + i,
    param.questionToken,
    param.dotDotDotToken && !isArrayTypeNode(typeNode) ? factory.createArrayTypeNode(typeNode) : typeNode,
    param.initializer
  );
  changeTracker.replaceRange(sourceFile, createRange(param.getStart(sourceFile), end), replacement);
}
function tryGetNextParam(sourceFile, param) {
  const nextToken = findNextToken(param.name, param.parent, sourceFile);
  if (nextToken && nextToken.kind === 23 /* OpenBracketToken */ && isArrayBindingPattern(nextToken.parent) && isParameter(nextToken.parent.parent)) {
    return nextToken.parent.parent;
  }
  return void 0;
}

// src/services/codefixes/addOptionalPropertyUndefined.ts
var addOptionalPropertyUndefined = "addOptionalPropertyUndefined";
var errorCodes9 = [
  Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code,
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code
];
registerCodeFix({
  errorCodes: errorCodes9,
  getCodeActions(context) {
    const typeChecker = context.program.getTypeChecker();
    const toAdd = getPropertiesToAdd(context.sourceFile, context.span, typeChecker);
    if (!toAdd.length) {
      return void 0;
    }
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addUndefinedToOptionalProperty(t, toAdd));
    return [createCodeFixActionWithoutFixAll(addOptionalPropertyUndefined, changes, Diagnostics.Add_undefined_to_optional_property_type)];
  },
  fixIds: [addOptionalPropertyUndefined]
});
function getPropertiesToAdd(file, span, checker) {
  var _a, _b;
  const sourceTarget = getSourceTarget(getFixableErrorSpanExpression(file, span), checker);
  if (!sourceTarget) {
    return emptyArray;
  }
  const { source: sourceNode, target: targetNode } = sourceTarget;
  const target = shouldUseParentTypeOfProperty(sourceNode, targetNode, checker) ? checker.getTypeAtLocation(targetNode.expression) : checker.getTypeAtLocation(targetNode);
  if ((_b = (_a = target.symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b.some((d) => getSourceFileOfNode(d).fileName.match(/\.d\.ts$/))) {
    return emptyArray;
  }
  return checker.getExactOptionalProperties(target);
}
function shouldUseParentTypeOfProperty(sourceNode, targetNode, checker) {
  return isPropertyAccessExpression(targetNode) && !!checker.getExactOptionalProperties(checker.getTypeAtLocation(targetNode.expression)).length && checker.getTypeAtLocation(sourceNode) === checker.getUndefinedType();
}
function getSourceTarget(errorNode, checker) {
  var _a;
  if (!errorNode) {
    return void 0;
  } else if (isBinaryExpression(errorNode.parent) && errorNode.parent.operatorToken.kind === 64 /* EqualsToken */) {
    return { source: errorNode.parent.right, target: errorNode.parent.left };
  } else if (isVariableDeclaration(errorNode.parent) && errorNode.parent.initializer) {
    return { source: errorNode.parent.initializer, target: errorNode.parent.name };
  } else if (isCallExpression(errorNode.parent)) {
    const n = checker.getSymbolAtLocation(errorNode.parent.expression);
    if (!(n == null ? void 0 : n.valueDeclaration) || !isFunctionLikeKind(n.valueDeclaration.kind)) return void 0;
    if (!isExpression(errorNode)) return void 0;
    const i = errorNode.parent.arguments.indexOf(errorNode);
    if (i === -1) return void 0;
    const name = n.valueDeclaration.parameters[i].name;
    if (isIdentifier(name)) return { source: errorNode, target: name };
  } else if (isPropertyAssignment(errorNode.parent) && isIdentifier(errorNode.parent.name) || isShorthandPropertyAssignment(errorNode.parent)) {
    const parentTarget = getSourceTarget(errorNode.parent.parent, checker);
    if (!parentTarget) return void 0;
    const prop = checker.getPropertyOfType(checker.getTypeAtLocation(parentTarget.target), errorNode.parent.name.text);
    const declaration = (_a = prop == null ? void 0 : prop.declarations) == null ? void 0 : _a[0];
    if (!declaration) return void 0;
    return {
      source: isPropertyAssignment(errorNode.parent) ? errorNode.parent.initializer : errorNode.parent.name,
      target: declaration
    };
  }
  return void 0;
}
function addUndefinedToOptionalProperty(changes, toAdd) {
  for (const add of toAdd) {
    const d = add.valueDeclaration;
    if (d && (isPropertySignature(d) || isPropertyDeclaration(d)) && d.type) {
      const t = factory.createUnionTypeNode([
        ...d.type.kind === 192 /* UnionType */ ? d.type.types : [d.type],
        factory.createTypeReferenceNode("undefined")
      ]);
      changes.replaceNode(d.getSourceFile(), d.type, t);
    }
  }
}

// src/services/codefixes/annotateWithTypeFromJSDoc.ts
var fixId9 = "annotateWithTypeFromJSDoc";
var errorCodes10 = [Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
registerCodeFix({
  errorCodes: errorCodes10,
  getCodeActions(context) {
    const decl = getDeclaration(context.sourceFile, context.span.start);
    if (!decl) return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange8(t, context.sourceFile, decl));
    return [createCodeFixAction(fixId9, changes, Diagnostics.Annotate_with_type_from_JSDoc, fixId9, Diagnostics.Annotate_everything_with_types_from_JSDoc)];
  },
  fixIds: [fixId9],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes10, (changes, diag2) => {
    const decl = getDeclaration(diag2.file, diag2.start);
    if (decl) doChange8(changes, diag2.file, decl);
  })
});
function getDeclaration(file, pos) {
  const name = getTokenAtPosition(file, pos);
  return tryCast(isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc);
}
function parameterShouldGetTypeFromJSDoc(node) {
  return isDeclarationWithType(node) && hasUsableJSDoc(node);
}
function hasUsableJSDoc(decl) {
  return isFunctionLikeDeclaration(decl) ? decl.parameters.some(hasUsableJSDoc) || !decl.type && !!getJSDocReturnType(decl) : !decl.type && !!getJSDocType(decl);
}
function doChange8(changes, sourceFile, decl) {
  if (isFunctionLikeDeclaration(decl) && (getJSDocReturnType(decl) || decl.parameters.some((p) => !!getJSDocType(p)))) {
    if (!decl.typeParameters) {
      const typeParameters = getJSDocTypeParameterDeclarations(decl);
      if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters);
    }
    const needParens = isArrowFunction(decl) && !findChildOfKind(decl, 21 /* OpenParenToken */, sourceFile);
    if (needParens) changes.insertNodeBefore(sourceFile, first(decl.parameters), factory.createToken(21 /* OpenParenToken */));
    for (const param of decl.parameters) {
      if (!param.type) {
        const paramType = getJSDocType(param);
        if (paramType) changes.tryInsertTypeAnnotation(sourceFile, param, visitNode(paramType, transformJSDocType, isTypeNode));
      }
    }
    if (needParens) changes.insertNodeAfter(sourceFile, last(decl.parameters), factory.createToken(22 /* CloseParenToken */));
    if (!decl.type) {
      const returnType = getJSDocReturnType(decl);
      if (returnType) changes.tryInsertTypeAnnotation(sourceFile, decl, visitNode(returnType, transformJSDocType, isTypeNode));
    }
  } else {
    const jsdocType = Debug.checkDefined(getJSDocType(decl), "A JSDocType for this declaration should exist");
    Debug.assert(!decl.type, "The JSDocType decl should have a type");
    changes.tryInsertTypeAnnotation(sourceFile, decl, visitNode(jsdocType, transformJSDocType, isTypeNode));
  }
}
function isDeclarationWithType(node) {
  return isFunctionLikeDeclaration(node) || node.kind === 260 /* VariableDeclaration */ || node.kind === 171 /* PropertySignature */ || node.kind === 172 /* PropertyDeclaration */;
}
function transformJSDocType(node) {
  switch (node.kind) {
    case 312 /* JSDocAllType */:
    case 313 /* JSDocUnknownType */:
      return factory.createTypeReferenceNode("any", emptyArray);
    case 316 /* JSDocOptionalType */:
      return transformJSDocOptionalType(node);
    case 315 /* JSDocNonNullableType */:
      return transformJSDocType(node.type);
    case 314 /* JSDocNullableType */:
      return transformJSDocNullableType(node);
    case 318 /* JSDocVariadicType */:
      return transformJSDocVariadicType(node);
    case 317 /* JSDocFunctionType */:
      return transformJSDocFunctionType(node);
    case 183 /* TypeReference */:
      return transformJSDocTypeReference(node);
    case 322 /* JSDocTypeLiteral */:
      return transformJSDocTypeLiteral(node);
    default:
      const visited = visitEachChild(
        node,
        transformJSDocType,
        /*context*/
        void 0
      );
      setEmitFlags(visited, 1 /* SingleLine */);
      return visited;
  }
}
function transformJSDocTypeLiteral(node) {
  const typeNode = factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (tag) => factory.createPropertySignature(
    /*modifiers*/
    void 0,
    isIdentifier(tag.name) ? tag.name : tag.name.right,
    isOptionalJSDocPropertyLikeTag(tag) ? factory.createToken(58 /* QuestionToken */) : void 0,
    tag.typeExpression && visitNode(tag.typeExpression.type, transformJSDocType, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */)
  )));
  setEmitFlags(typeNode, 1 /* SingleLine */);
  return typeNode;
}
function transformJSDocOptionalType(node) {
  return factory.createUnionTypeNode([visitNode(node.type, transformJSDocType, isTypeNode), factory.createTypeReferenceNode("undefined", emptyArray)]);
}
function transformJSDocNullableType(node) {
  return factory.createUnionTypeNode([visitNode(node.type, transformJSDocType, isTypeNode), factory.createTypeReferenceNode("null", emptyArray)]);
}
function transformJSDocVariadicType(node) {
  return factory.createArrayTypeNode(visitNode(node.type, transformJSDocType, isTypeNode));
}
function transformJSDocFunctionType(node) {
  return factory.createFunctionTypeNode(emptyArray, node.parameters.map(transformJSDocParameter), node.type ?? factory.createKeywordTypeNode(133 /* AnyKeyword */));
}
function transformJSDocParameter(node) {
  const index = node.parent.parameters.indexOf(node);
  const isRest = node.type.kind === 318 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
  const name = node.name || (isRest ? "rest" : "arg" + index);
  const dotdotdot = isRest ? factory.createToken(26 /* DotDotDotToken */) : node.dotDotDotToken;
  return factory.createParameterDeclaration(node.modifiers, dotdotdot, name, node.questionToken, visitNode(node.type, transformJSDocType, isTypeNode), node.initializer);
}
function transformJSDocTypeReference(node) {
  let name = node.typeName;
  let args = node.typeArguments;
  if (isIdentifier(node.typeName)) {
    if (isJSDocIndexSignature(node)) {
      return transformJSDocIndexSignature(node);
    }
    let text = node.typeName.text;
    switch (node.typeName.text) {
      case "String":
      case "Boolean":
      case "Object":
      case "Number":
        text = text.toLowerCase();
        break;
      case "array":
      case "date":
      case "promise":
        text = text[0].toUpperCase() + text.slice(1);
        break;
    }
    name = factory.createIdentifier(text);
    if ((text === "Array" || text === "Promise") && !node.typeArguments) {
      args = factory.createNodeArray([factory.createTypeReferenceNode("any", emptyArray)]);
    } else {
      args = visitNodes2(node.typeArguments, transformJSDocType, isTypeNode);
    }
  }
  return factory.createTypeReferenceNode(name, args);
}
function transformJSDocIndexSignature(node) {
  const index = factory.createParameterDeclaration(
    /*modifiers*/
    void 0,
    /*dotDotDotToken*/
    void 0,
    node.typeArguments[0].kind === 150 /* NumberKeyword */ ? "n" : "s",
    /*questionToken*/
    void 0,
    factory.createTypeReferenceNode(node.typeArguments[0].kind === 150 /* NumberKeyword */ ? "number" : "string", []),
    /*initializer*/
    void 0
  );
  const indexSignature = factory.createTypeLiteralNode([factory.createIndexSignature(
    /*modifiers*/
    void 0,
    [index],
    node.typeArguments[1]
  )]);
  setEmitFlags(indexSignature, 1 /* SingleLine */);
  return indexSignature;
}

// src/services/codefixes/convertFunctionToEs6Class.ts
var fixId10 = "convertFunctionToEs6Class";
var errorCodes11 = [Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code];
registerCodeFix({
  errorCodes: errorCodes11,
  getCodeActions(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange9(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions()));
    return [createCodeFixAction(fixId10, changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId10, Diagnostics.Convert_all_constructor_functions_to_classes)];
  },
  fixIds: [fixId10],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes11, (changes, err) => doChange9(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions()))
});
function doChange9(changes, sourceFile, position, checker, preferences, compilerOptions) {
  const ctorSymbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, position));
  if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
    return void 0;
  }
  const ctorDeclaration = ctorSymbol.valueDeclaration;
  if (isFunctionDeclaration(ctorDeclaration) || isFunctionExpression(ctorDeclaration)) {
    changes.replaceNode(sourceFile, ctorDeclaration, createClassFromFunction(ctorDeclaration));
  } else if (isVariableDeclaration(ctorDeclaration)) {
    const classDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
    if (!classDeclaration) {
      return void 0;
    }
    const ancestor = ctorDeclaration.parent.parent;
    if (isVariableDeclarationList(ctorDeclaration.parent) && ctorDeclaration.parent.declarations.length > 1) {
      changes.delete(sourceFile, ctorDeclaration);
      changes.insertNodeAfter(sourceFile, ancestor, classDeclaration);
    } else {
      changes.replaceNode(sourceFile, ancestor, classDeclaration);
    }
  }
  function createClassElementsFromSymbol(symbol) {
    const memberElements = [];
    if (symbol.exports) {
      symbol.exports.forEach((member) => {
        if (member.name === "prototype" && member.declarations) {
          const firstDeclaration = member.declarations[0];
          if (member.declarations.length === 1 && isPropertyAccessExpression(firstDeclaration) && isBinaryExpression(firstDeclaration.parent) && firstDeclaration.parent.operatorToken.kind === 64 /* EqualsToken */ && isObjectLiteralExpression(firstDeclaration.parent.right)) {
            const prototypes = firstDeclaration.parent.right;
            createClassElement(
              prototypes.symbol,
              /*modifiers*/
              void 0,
              memberElements
            );
          }
        } else {
          createClassElement(member, [factory.createToken(126 /* StaticKeyword */)], memberElements);
        }
      });
    }
    if (symbol.members) {
      symbol.members.forEach((member, key) => {
        var _a, _b, _c, _d;
        if (key === "constructor" && member.valueDeclaration) {
          const prototypeAssignment = (_d = (_c = (_b = (_a = symbol.exports) == null ? void 0 : _a.get("prototype")) == null ? void 0 : _b.declarations) == null ? void 0 : _c[0]) == null ? void 0 : _d.parent;
          if (prototypeAssignment && isBinaryExpression(prototypeAssignment) && isObjectLiteralExpression(prototypeAssignment.right) && some(prototypeAssignment.right.properties, isConstructorAssignment)) {
          } else {
            changes.delete(sourceFile, member.valueDeclaration.parent);
          }
          return;
        }
        createClassElement(
          member,
          /*modifiers*/
          void 0,
          memberElements
        );
      });
    }
    return memberElements;
    function shouldConvertDeclaration(_target, source) {
      if (isAccessExpression(_target)) {
        if (isPropertyAccessExpression(_target) && isConstructorAssignment(_target)) return true;
        return isFunctionLike(source);
      } else {
        return every(_target.properties, (property) => {
          if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) return true;
          if (isPropertyAssignment(property) && isFunctionExpression(property.initializer) && !!property.name) return true;
          if (isConstructorAssignment(property)) return true;
          return false;
        });
      }
    }
    function createClassElement(symbol2, modifiers, members) {
      if (!(symbol2.flags & 8192 /* Method */) && !(symbol2.flags & 4096 /* ObjectLiteral */)) {
        return;
      }
      const memberDeclaration = symbol2.valueDeclaration;
      const assignmentBinaryExpression = memberDeclaration.parent;
      const assignmentExpr = assignmentBinaryExpression.right;
      if (!shouldConvertDeclaration(memberDeclaration, assignmentExpr)) {
        return;
      }
      if (some(members, (m) => {
        const name = getNameOfDeclaration(m);
        if (name && isIdentifier(name) && idText(name) === symbolName(symbol2)) {
          return true;
        }
        return false;
      })) {
        return;
      }
      const nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 244 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
      changes.delete(sourceFile, nodeToDelete);
      if (!assignmentExpr) {
        members.push(factory.createPropertyDeclaration(
          modifiers,
          symbol2.name,
          /*questionOrExclamationToken*/
          void 0,
          /*type*/
          void 0,
          /*initializer*/
          void 0
        ));
        return;
      }
      if (isAccessExpression(memberDeclaration) && (isFunctionExpression(assignmentExpr) || isArrowFunction(assignmentExpr))) {
        const quotePreference = getQuotePreference(sourceFile, preferences);
        const name = tryGetPropertyName(memberDeclaration, compilerOptions, quotePreference);
        if (name) {
          createFunctionLikeExpressionMember(members, assignmentExpr, name);
        }
        return;
      } else if (isObjectLiteralExpression(assignmentExpr)) {
        forEach(
          assignmentExpr.properties,
          (property) => {
            if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) {
              members.push(property);
            }
            if (isPropertyAssignment(property) && isFunctionExpression(property.initializer)) {
              createFunctionLikeExpressionMember(members, property.initializer, property.name);
            }
            if (isConstructorAssignment(property)) return;
            return;
          }
        );
        return;
      } else {
        if (isSourceFileJS(sourceFile)) return;
        if (!isPropertyAccessExpression(memberDeclaration)) return;
        const prop = factory.createPropertyDeclaration(
          modifiers,
          memberDeclaration.name,
          /*questionOrExclamationToken*/
          void 0,
          /*type*/
          void 0,
          assignmentExpr
        );
        copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
        members.push(prop);
        return;
      }
      function createFunctionLikeExpressionMember(members2, expression, name) {
        if (isFunctionExpression(expression)) return createFunctionExpressionMember(members2, expression, name);
        else return createArrowFunctionExpressionMember(members2, expression, name);
      }
      function createFunctionExpressionMember(members2, functionExpression, name) {
        const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, 134 /* AsyncKeyword */));
        const method = factory.createMethodDeclaration(
          fullModifiers,
          /*asteriskToken*/
          void 0,
          name,
          /*questionToken*/
          void 0,
          /*typeParameters*/
          void 0,
          functionExpression.parameters,
          /*type*/
          void 0,
          functionExpression.body
        );
        copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
        members2.push(method);
        return;
      }
      function createArrowFunctionExpressionMember(members2, arrowFunction, name) {
        const arrowFunctionBody = arrowFunction.body;
        let bodyBlock;
        if (arrowFunctionBody.kind === 241 /* Block */) {
          bodyBlock = arrowFunctionBody;
        } else {
          bodyBlock = factory.createBlock([factory.createReturnStatement(arrowFunctionBody)]);
        }
        const fullModifiers = concatenate(modifiers, getModifierKindFromSource(arrowFunction, 134 /* AsyncKeyword */));
        const method = factory.createMethodDeclaration(
          fullModifiers,
          /*asteriskToken*/
          void 0,
          name,
          /*questionToken*/
          void 0,
          /*typeParameters*/
          void 0,
          arrowFunction.parameters,
          /*type*/
          void 0,
          bodyBlock
        );
        copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
        members2.push(method);
      }
    }
  }
  function createClassFromVariableDeclaration(node) {
    const initializer = node.initializer;
    if (!initializer || !isFunctionExpression(initializer) || !isIdentifier(node.name)) {
      return void 0;
    }
    const memberElements = createClassElementsFromSymbol(node.symbol);
    if (initializer.body) {
      memberElements.unshift(factory.createConstructorDeclaration(
        /*modifiers*/
        void 0,
        initializer.parameters,
        initializer.body
      ));
    }
    const modifiers = getModifierKindFromSource(node.parent.parent, 95 /* ExportKeyword */);
    const cls = factory.createClassDeclaration(
      modifiers,
      node.name,
      /*typeParameters*/
      void 0,
      /*heritageClauses*/
      void 0,
      memberElements
    );
    return cls;
  }
  function createClassFromFunction(node) {
    const memberElements = createClassElementsFromSymbol(ctorSymbol);
    if (node.body) {
      memberElements.unshift(factory.createConstructorDeclaration(
        /*modifiers*/
        void 0,
        node.parameters,
        node.body
      ));
    }
    const modifiers = getModifierKindFromSource(node, 95 /* ExportKeyword */);
    const cls = factory.createClassDeclaration(
      modifiers,
      node.name,
      /*typeParameters*/
      void 0,
      /*heritageClauses*/
      void 0,
      memberElements
    );
    return cls;
  }
}
function getModifierKindFromSource(source, kind) {
  return canHaveModifiers(source) ? filter(source.modifiers, (modifier) => modifier.kind === kind) : void 0;
}
function isConstructorAssignment(x) {
  if (!x.name) return false;
  if (isIdentifier(x.name) && x.name.text === "constructor") return true;
  return false;
}
function tryGetPropertyName(node, compilerOptions, quotePreference) {
  if (isPropertyAccessExpression(node)) {
    return node.name;
  }
  const propName = node.argumentExpression;
  if (isNumericLiteral(propName)) {
    return propName;
  }
  if (isStringLiteralLike(propName)) {
    return isIdentifierText(propName.text, getEmitScriptTarget(compilerOptions)) ? factory.createIdentifier(propName.text) : isNoSubstitutionTemplateLiteral(propName) ? factory.createStringLiteral(propName.text, quotePreference === 0 /* Single */) : propName;
  }
  return void 0;
}

// src/services/codefixes/convertToAsyncFunction.ts
var fixId11 = "convertToAsyncFunction";
var errorCodes12 = [Diagnostics.This_may_be_converted_to_an_async_function.code];
var codeActionSucceeded = true;
registerCodeFix({
  errorCodes: errorCodes12,
  getCodeActions(context) {
    codeActionSucceeded = true;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker()));
    return codeActionSucceeded ? [createCodeFixAction(fixId11, changes, Diagnostics.Convert_to_async_function, fixId11, Diagnostics.Convert_all_to_async_functions)] : [];
  },
  fixIds: [fixId11],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes12, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker()))
});
function convertToAsyncFunction(changes, sourceFile, position, checker) {
  const tokenAtPosition = getTokenAtPosition(sourceFile, position);
  let functionToConvert;
  if (isIdentifier(tokenAtPosition) && isVariableDeclaration(tokenAtPosition.parent) && tokenAtPosition.parent.initializer && isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) {
    functionToConvert = tokenAtPosition.parent.initializer;
  } else {
    functionToConvert = tryCast(getContainingFunction(getTokenAtPosition(sourceFile, position)), canBeConvertedToAsync);
  }
  if (!functionToConvert) {
    return;
  }
  const synthNamesMap = /* @__PURE__ */ new Map();
  const isInJavascript = isInJSFile(functionToConvert);
  const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker);
  const functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap);
  if (!returnsPromise(functionToConvertRenamed, checker)) {
    return;
  }
  const returnStatements = functionToConvertRenamed.body && isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : emptyArray;
  const transformer = { checker, synthNamesMap, setOfExpressionsToReturn, isInJSFile: isInJavascript };
  if (!returnStatements.length) {
    return;
  }
  const pos = skipTrivia(sourceFile.text, moveRangePastModifiers(functionToConvert).pos);
  changes.insertModifierAt(sourceFile, pos, 134 /* AsyncKeyword */, { suffix: " " });
  for (const returnStatement of returnStatements) {
    forEachChild(returnStatement, function visit(node) {
      if (isCallExpression(node)) {
        const newNodes = transformExpression(
          node,
          node,
          transformer,
          /*hasContinuation*/
          false
        );
        if (hasFailed()) {
          return true;
        }
        changes.replaceNodeWithNodes(sourceFile, returnStatement, newNodes);
      } else if (!isFunctionLike(node)) {
        forEachChild(node, visit);
        if (hasFailed()) {
          return true;
        }
      }
    });
    if (hasFailed()) {
      return;
    }
  }
}
function getReturnStatementsWithPromiseHandlers(body, checker) {
  const res = [];
  forEachReturnStatement(body, (ret) => {
    if (isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret);
  });
  return res;
}
function getAllPromiseExpressionsToReturn(func, checker) {
  if (!func.body) {
    return /* @__PURE__ */ new Set();
  }
  const setOfExpressionsToReturn = /* @__PURE__ */ new Set();
  forEachChild(func.body, function visit(node) {
    if (isPromiseReturningCallExpression(node, checker, "then")) {
      setOfExpressionsToReturn.add(getNodeId(node));
      forEach(node.arguments, visit);
    } else if (isPromiseReturningCallExpression(node, checker, "catch") || isPromiseReturningCallExpression(node, checker, "finally")) {
      setOfExpressionsToReturn.add(getNodeId(node));
      forEachChild(node, visit);
    } else if (isPromiseTypedExpression(node, checker)) {
      setOfExpressionsToReturn.add(getNodeId(node));
    } else {
      forEachChild(node, visit);
    }
  });
  return setOfExpressionsToReturn;
}
function isPromiseReturningCallExpression(node, checker, name) {
  if (!isCallExpression(node)) return false;
  const isExpressionOfName = hasPropertyAccessExpressionWithName(node, name);
  const nodeType = isExpressionOfName && checker.getTypeAtLocation(node);
  return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType));
}
function isReferenceToType(type, target) {
  return (getObjectFlags(type) & 4 /* Reference */) !== 0 && type.target === target;
}
function getExplicitPromisedTypeOfPromiseReturningCallExpression(node, callback, checker) {
  if (node.expression.name.escapedText === "finally") {
    return void 0;
  }
  const promiseType = checker.getTypeAtLocation(node.expression.expression);
  if (isReferenceToType(promiseType, checker.getPromiseType()) || isReferenceToType(promiseType, checker.getPromiseLikeType())) {
    if (node.expression.name.escapedText === "then") {
      if (callback === elementAt(node.arguments, 0)) {
        return elementAt(node.typeArguments, 0);
      } else if (callback === elementAt(node.arguments, 1)) {
        return elementAt(node.typeArguments, 1);
      }
    } else {
      return elementAt(node.typeArguments, 0);
    }
  }
}
function isPromiseTypedExpression(node, checker) {
  if (!isExpression(node)) return false;
  return !!checker.getPromisedTypeOfPromise(checker.getTypeAtLocation(node));
}
function renameCollidingVarNames(nodeToRename, checker, synthNamesMap) {
  const identsToRenameMap = /* @__PURE__ */ new Map();
  const collidingSymbolMap = createMultiMap();
  forEachChild(nodeToRename, function visit(node) {
    if (!isIdentifier(node)) {
      forEachChild(node, visit);
      return;
    }
    const symbol = checker.getSymbolAtLocation(node);
    if (symbol) {
      const type = checker.getTypeAtLocation(node);
      const lastCallSignature = getLastCallSignature(type, checker);
      const symbolIdString = getSymbolId(symbol).toString();
      if (lastCallSignature && !isParameter(node.parent) && !isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) {
        const firstParameter = firstOrUndefined(lastCallSignature.parameters);
        const ident = (firstParameter == null ? void 0 : firstParameter.valueDeclaration) && isParameter(firstParameter.valueDeclaration) && tryCast(firstParameter.valueDeclaration.name, isIdentifier) || factory.createUniqueName("result", 16 /* Optimistic */);
        const synthName = getNewNameIfConflict(ident, collidingSymbolMap);
        synthNamesMap.set(symbolIdString, synthName);
        collidingSymbolMap.add(ident.text, symbol);
      } else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent) || isBindingElement(node.parent))) {
        const originalName = node.text;
        const collidingSymbols = collidingSymbolMap.get(originalName);
        if (collidingSymbols && collidingSymbols.some((prevSymbol) => prevSymbol !== symbol)) {
          const newName = getNewNameIfConflict(node, collidingSymbolMap);
          identsToRenameMap.set(symbolIdString, newName.identifier);
          synthNamesMap.set(symbolIdString, newName);
          collidingSymbolMap.add(originalName, symbol);
        } else {
          const identifier = getSynthesizedDeepClone(node);
          synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier));
          collidingSymbolMap.add(originalName, symbol);
        }
      }
    }
  });
  return getSynthesizedDeepCloneWithReplacements(
    nodeToRename,
    /*includeTrivia*/
    true,
    (original) => {
      if (isBindingElement(original) && isIdentifier(original.name) && isObjectBindingPattern(original.parent)) {
        const symbol = checker.getSymbolAtLocation(original.name);
        const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol)));
        if (renameInfo && renameInfo.text !== (original.name || original.propertyName).getText()) {
          return factory.createBindingElement(
            original.dotDotDotToken,
            original.propertyName || original.name,
            renameInfo,
            original.initializer
          );
        }
      } else if (isIdentifier(original)) {
        const symbol = checker.getSymbolAtLocation(original);
        const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol)));
        if (renameInfo) {
          return factory.createIdentifier(renameInfo.text);
        }
      }
    }
  );
}
function getNewNameIfConflict(name, originalNames) {
  const numVarsSameName = (originalNames.get(name.text) || emptyArray).length;
  const identifier = numVarsSameName === 0 ? name : factory.createIdentifier(name.text + "_" + numVarsSameName);
  return createSynthIdentifier(identifier);
}
function hasFailed() {
  return !codeActionSucceeded;
}
function silentFail() {
  codeActionSucceeded = false;
  return emptyArray;
}
function transformExpression(returnContextNode, node, transformer, hasContinuation, continuationArgName) {
  if (isPromiseReturningCallExpression(node, transformer.checker, "then")) {
    return transformThen(node, elementAt(node.arguments, 0), elementAt(node.arguments, 1), transformer, hasContinuation, continuationArgName);
  }
  if (isPromiseReturningCallExpression(node, transformer.checker, "catch")) {
    return transformCatch(node, elementAt(node.arguments, 0), transformer, hasContinuation, continuationArgName);
  }
  if (isPromiseReturningCallExpression(node, transformer.checker, "finally")) {
    return transformFinally(node, elementAt(node.arguments, 0), transformer, hasContinuation, continuationArgName);
  }
  if (isPropertyAccessExpression(node)) {
    return transformExpression(returnContextNode, node.expression, transformer, hasContinuation, continuationArgName);
  }
  const nodeType = transformer.checker.getTypeAtLocation(node);
  if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) {
    Debug.assertNode(getOriginalNode(node).parent, isPropertyAccessExpression);
    return transformPromiseExpressionOfPropertyAccess(returnContextNode, node, transformer, hasContinuation, continuationArgName);
  }
  return silentFail();
}
function isNullOrUndefined2({ checker }, node) {
  if (node.kind === 106 /* NullKeyword */) return true;
  if (isIdentifier(node) && !isGeneratedIdentifier(node) && idText(node) === "undefined") {
    const symbol = checker.getSymbolAtLocation(node);
    return !symbol || checker.isUndefinedSymbol(symbol);
  }
  return false;
}
function createUniqueSynthName(prevArgName) {
  const renamedPrevArg = factory.createUniqueName(prevArgName.identifier.text, 16 /* Optimistic */);
  return createSynthIdentifier(renamedPrevArg);
}
function getPossibleNameForVarDecl(node, transformer, continuationArgName) {
  let possibleNameForVarDecl;
  if (continuationArgName && !shouldReturn(node, transformer)) {
    if (isSynthIdentifier(continuationArgName)) {
      possibleNameForVarDecl = continuationArgName;
      transformer.synthNamesMap.forEach((val, key) => {
        if (val.identifier.text === continuationArgName.identifier.text) {
          const newSynthName = createUniqueSynthName(continuationArgName);
          transformer.synthNamesMap.set(key, newSynthName);
        }
      });
    } else {
      possibleNameForVarDecl = createSynthIdentifier(factory.createUniqueName("result", 16 /* Optimistic */), continuationArgName.types);
    }
    declareSynthIdentifier(possibleNameForVarDecl);
  }
  return possibleNameForVarDecl;
}
function finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName) {
  const statements = [];
  let varDeclIdentifier;
  if (possibleNameForVarDecl && !shouldReturn(node, transformer)) {
    varDeclIdentifier = getSynthesizedDeepClone(declareSynthIdentifier(possibleNameForVarDecl));
    const typeArray = possibleNameForVarDecl.types;
    const unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */);
    const unionTypeNode = transformer.isInJSFile ? void 0 : transformer.checker.typeToTypeNode(
      unionType,
      /*enclosingDeclaration*/
      void 0,
      /*flags*/
      void 0
    );
    const varDecl = [factory.createVariableDeclaration(
      varDeclIdentifier,
      /*exclamationToken*/
      void 0,
      unionTypeNode
    )];
    const varDeclList = factory.createVariableStatement(
      /*modifiers*/
      void 0,
      factory.createVariableDeclarationList(varDecl, 1 /* Let */)
    );
    statements.push(varDeclList);
  }
  statements.push(tryStatement);
  if (continuationArgName && varDeclIdentifier && isSynthBindingPattern(continuationArgName)) {
    statements.push(factory.createVariableStatement(
      /*modifiers*/
      void 0,
      factory.createVariableDeclarationList([
        factory.createVariableDeclaration(
          getSynthesizedDeepClone(declareSynthBindingPattern(continuationArgName)),
          /*exclamationToken*/
          void 0,
          /*type*/
          void 0,
          varDeclIdentifier
        )
      ], 2 /* Const */)
    ));
  }
  return statements;
}
function transformFinally(node, onFinally, transformer, hasContinuation, continuationArgName) {
  if (!onFinally || isNullOrUndefined2(transformer, onFinally)) {
    return transformExpression(
      /* returnContextNode */
      node,
      node.expression.expression,
      transformer,
      hasContinuation,
      continuationArgName
    );
  }
  const possibleNameForVarDecl = getPossibleNameForVarDecl(node, transformer, continuationArgName);
  const inlinedLeftHandSide = transformExpression(
    /*returnContextNode*/
    node,
    node.expression.expression,
    transformer,
    /*hasContinuation*/
    true,
    possibleNameForVarDecl
  );
  if (hasFailed()) return silentFail();
  const inlinedCallback = transformCallbackArgument(
    onFinally,
    hasContinuation,
    /*continuationArgName*/
    void 0,
    /*inputArgName*/
    void 0,
    node,
    transformer
  );
  if (hasFailed()) return silentFail();
  const tryBlock = factory.createBlock(inlinedLeftHandSide);
  const finallyBlock = factory.createBlock(inlinedCallback);
  const tryStatement = factory.createTryStatement(
    tryBlock,
    /*catchClause*/
    void 0,
    finallyBlock
  );
  return finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName);
}
function transformCatch(node, onRejected, transformer, hasContinuation, continuationArgName) {
  if (!onRejected || isNullOrUndefined2(transformer, onRejected)) {
    return transformExpression(
      /* returnContextNode */
      node,
      node.expression.expression,
      transformer,
      hasContinuation,
      continuationArgName
    );
  }
  const inputArgName = getArgBindingName(onRejected, transformer);
  const possibleNameForVarDecl = getPossibleNameForVarDecl(node, transformer, continuationArgName);
  const inlinedLeftHandSide = transformExpression(
    /*returnContextNode*/
    node,
    node.expression.expression,
    transformer,
    /*hasContinuation*/
    true,
    possibleNameForVarDecl
  );
  if (hasFailed()) return silentFail();
  const inlinedCallback = transformCallbackArgument(onRejected, hasContinuation, possibleNameForVarDecl, inputArgName, node, transformer);
  if (hasFailed()) return silentFail();
  const tryBlock = factory.createBlock(inlinedLeftHandSide);
  const catchClause = factory.createCatchClause(inputArgName && getSynthesizedDeepClone(declareSynthBindingName(inputArgName)), factory.createBlock(inlinedCallback));
  const tryStatement = factory.createTryStatement(
    tryBlock,
    catchClause,
    /*finallyBlock*/
    void 0
  );
  return finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName);
}
function transformThen(node, onFulfilled, onRejected, transformer, hasContinuation, continuationArgName) {
  if (!onFulfilled || isNullOrUndefined2(transformer, onFulfilled)) {
    return transformCatch(node, onRejected, transformer, hasContinuation, continuationArgName);
  }
  if (onRejected && !isNullOrUndefined2(transformer, onRejected)) {
    return silentFail();
  }
  const inputArgName = getArgBindingName(onFulfilled, transformer);
  const inlinedLeftHandSide = transformExpression(
    node.expression.expression,
    node.expression.expression,
    transformer,
    /*hasContinuation*/
    true,
    inputArgName
  );
  if (hasFailed()) return silentFail();
  const inlinedCallback = transformCallbackArgument(onFulfilled, hasContinuation, continuationArgName, inputArgName, node, transformer);
  if (hasFailed()) return silentFail();
  return concatenate(inlinedLeftHandSide, inlinedCallback);
}
function transformPromiseExpressionOfPropertyAccess(returnContextNode, node, transformer, hasContinuation, continuationArgName) {
  if (shouldReturn(returnContextNode, transformer)) {
    let returnValue = getSynthesizedDeepClone(node);
    if (hasContinuation) {
      returnValue = factory.createAwaitExpression(returnValue);
    }
    return [factory.createReturnStatement(returnValue)];
  }
  return createVariableOrAssignmentOrExpressionStatement(
    continuationArgName,
    factory.createAwaitExpression(node),
    /*typeAnnotation*/
    void 0
  );
}
function createVariableOrAssignmentOrExpressionStatement(variableName, rightHandSide, typeAnnotation) {
  if (!variableName || isEmptyBindingName(variableName)) {
    return [factory.createExpressionStatement(rightHandSide)];
  }
  if (isSynthIdentifier(variableName) && variableName.hasBeenDeclared) {
    return [factory.createExpressionStatement(factory.createAssignment(getSynthesizedDeepClone(referenceSynthIdentifier(variableName)), rightHandSide))];
  }
  return [
    factory.createVariableStatement(
      /*modifiers*/
      void 0,
      factory.createVariableDeclarationList([
        factory.createVariableDeclaration(
          getSynthesizedDeepClone(declareSynthBindingName(variableName)),
          /*exclamationToken*/
          void 0,
          typeAnnotation,
          rightHandSide
        )
      ], 2 /* Const */)
    )
  ];
}
function maybeAnnotateAndReturn(expressionToReturn, typeAnnotation) {
  if (typeAnnotation && expressionToReturn) {
    const name = factory.createUniqueName("result", 16 /* Optimistic */);
    return [
      ...createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation),
      factory.createReturnStatement(name)
    ];
  }
  return [factory.createReturnStatement(expressionToReturn)];
}
function transformCallbackArgument(func, hasContinuation, continuationArgName, inputArgName, parent2, transformer) {
  var _a;
  switch (func.kind) {
    case 106 /* NullKeyword */:
      break;
    case 211 /* PropertyAccessExpression */:
    case 80 /* Identifier */:
      if (!inputArgName) {
        break;
      }
      const synthCall = factory.createCallExpression(
        getSynthesizedDeepClone(func),
        /*typeArguments*/
        void 0,
        isSynthIdentifier(inputArgName) ? [referenceSynthIdentifier(inputArgName)] : []
      );
      if (shouldReturn(parent2, transformer)) {
        return maybeAnnotateAndReturn(synthCall, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker));
      }
      const type = transformer.checker.getTypeAtLocation(func);
      const callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */);
      if (!callSignatures.length) {
        return silentFail();
      }
      const returnType = callSignatures[0].getReturnType();
      const varDeclOrAssignment = createVariableOrAssignmentOrExpressionStatement(continuationArgName, factory.createAwaitExpression(synthCall), getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker));
      if (continuationArgName) {
        continuationArgName.types.push(transformer.checker.getAwaitedType(returnType) || returnType);
      }
      return varDeclOrAssignment;
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */: {
      const funcBody = func.body;
      const returnType2 = (_a = getLastCallSignature(transformer.checker.getTypeAtLocation(func), transformer.checker)) == null ? void 0 : _a.getReturnType();
      if (isBlock(funcBody)) {
        let refactoredStmts = [];
        let seenReturnStatement = false;
        for (const statement of funcBody.statements) {
          if (isReturnStatement(statement)) {
            seenReturnStatement = true;
            if (isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) {
              refactoredStmts = refactoredStmts.concat(transformReturnStatementWithFixablePromiseHandler(transformer, statement, hasContinuation, continuationArgName));
            } else {
              const possiblyAwaitedRightHandSide = returnType2 && statement.expression ? getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, statement.expression) : statement.expression;
              refactoredStmts.push(...maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker)));
            }
          } else if (hasContinuation && forEachReturnStatement(statement, returnTrue)) {
            return silentFail();
          } else {
            refactoredStmts.push(statement);
          }
        }
        return shouldReturn(parent2, transformer) ? refactoredStmts.map((s) => getSynthesizedDeepClone(s)) : removeReturns(
          refactoredStmts,
          continuationArgName,
          transformer,
          seenReturnStatement
        );
      } else {
        const inlinedStatements = isFixablePromiseHandler(funcBody, transformer.checker) ? transformReturnStatementWithFixablePromiseHandler(transformer, factory.createReturnStatement(funcBody), hasContinuation, continuationArgName) : emptyArray;
        if (inlinedStatements.length > 0) {
          return inlinedStatements;
        }
        if (returnType2) {
          const possiblyAwaitedRightHandSide = getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, funcBody);
          if (!shouldReturn(parent2, transformer)) {
            const transformedStatement = createVariableOrAssignmentOrExpressionStatement(
              continuationArgName,
              possiblyAwaitedRightHandSide,
              /*typeAnnotation*/
              void 0
            );
            if (continuationArgName) {
              continuationArgName.types.push(transformer.checker.getAwaitedType(returnType2) || returnType2);
            }
            return transformedStatement;
          } else {
            return maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker));
          }
        } else {
          return silentFail();
        }
      }
    }
    default:
      return silentFail();
  }
  return emptyArray;
}
function getPossiblyAwaitedRightHandSide(checker, type, expr) {
  const rightHandSide = getSynthesizedDeepClone(expr);
  return !!checker.getPromisedTypeOfPromise(type) ? factory.createAwaitExpression(rightHandSide) : rightHandSide;
}
function getLastCallSignature(type, checker) {
  const callSignatures = checker.getSignaturesOfType(type, 0 /* Call */);
  return lastOrUndefined(callSignatures);
}
function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) {
  const ret = [];
  for (const stmt of stmts) {
    if (isReturnStatement(stmt)) {
      if (stmt.expression) {
        const possiblyAwaitedExpression = isPromiseTypedExpression(stmt.expression, transformer.checker) ? factory.createAwaitExpression(stmt.expression) : stmt.expression;
        if (prevArgName === void 0) {
          ret.push(factory.createExpressionStatement(possiblyAwaitedExpression));
        } else if (isSynthIdentifier(prevArgName) && prevArgName.hasBeenDeclared) {
          ret.push(factory.createExpressionStatement(factory.createAssignment(referenceSynthIdentifier(prevArgName), possiblyAwaitedExpression)));
        } else {
          ret.push(factory.createVariableStatement(
            /*modifiers*/
            void 0,
            factory.createVariableDeclarationList([factory.createVariableDeclaration(
              declareSynthBindingName(prevArgName),
              /*exclamationToken*/
              void 0,
              /*type*/
              void 0,
              possiblyAwaitedExpression
            )], 2 /* Const */)
          ));
        }
      }
    } else {
      ret.push(getSynthesizedDeepClone(stmt));
    }
  }
  if (!seenReturnStatement && prevArgName !== void 0) {
    ret.push(factory.createVariableStatement(
      /*modifiers*/
      void 0,
      factory.createVariableDeclarationList([factory.createVariableDeclaration(
        declareSynthBindingName(prevArgName),
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        factory.createIdentifier("undefined")
      )], 2 /* Const */)
    ));
  }
  return ret;
}
function transformReturnStatementWithFixablePromiseHandler(transformer, innerRetStmt, hasContinuation, continuationArgName) {
  let innerCbBody = [];
  forEachChild(innerRetStmt, function visit(node) {
    if (isCallExpression(node)) {
      const temp = transformExpression(node, node, transformer, hasContinuation, continuationArgName);
      innerCbBody = innerCbBody.concat(temp);
      if (innerCbBody.length > 0) {
        return;
      }
    } else if (!isFunctionLike(node)) {
      forEachChild(node, visit);
    }
  });
  return innerCbBody;
}
function getArgBindingName(funcNode, transformer) {
  const types = [];
  let name;
  if (isFunctionLikeDeclaration(funcNode)) {
    if (funcNode.parameters.length > 0) {
      const param = funcNode.parameters[0].name;
      name = getMappedBindingNameOrDefault(param);
    }
  } else if (isIdentifier(funcNode)) {
    name = getMapEntryOrDefault(funcNode);
  } else if (isPropertyAccessExpression(funcNode) && isIdentifier(funcNode.name)) {
    name = getMapEntryOrDefault(funcNode.name);
  }
  if (!name || "identifier" in name && name.identifier.text === "undefined") {
    return void 0;
  }
  return name;
  function getMappedBindingNameOrDefault(bindingName) {
    if (isIdentifier(bindingName)) return getMapEntryOrDefault(bindingName);
    const elements = flatMap(bindingName.elements, (element) => {
      if (isOmittedExpression(element)) return [];
      return [getMappedBindingNameOrDefault(element.name)];
    });
    return createSynthBindingPattern(bindingName, elements);
  }
  function getMapEntryOrDefault(identifier) {
    const originalNode = getOriginalNode2(identifier);
    const symbol = getSymbol2(originalNode);
    if (!symbol) {
      return createSynthIdentifier(identifier, types);
    }
    const mapEntry = transformer.synthNamesMap.get(getSymbolId(symbol).toString());
    return mapEntry || createSynthIdentifier(identifier, types);
  }
  function getSymbol2(node) {
    var _a;
    return ((_a = tryCast(node, canHaveSymbol)) == null ? void 0 : _a.symbol) ?? transformer.checker.getSymbolAtLocation(node);
  }
  function getOriginalNode2(node) {
    return node.original ? node.original : node;
  }
}
function isEmptyBindingName(bindingName) {
  if (!bindingName) {
    return true;
  }
  if (isSynthIdentifier(bindingName)) {
    return !bindingName.identifier.text;
  }
  return every(bindingName.elements, isEmptyBindingName);
}
function createSynthIdentifier(identifier, types = []) {
  return { kind: 0 /* Identifier */, identifier, types, hasBeenDeclared: false, hasBeenReferenced: false };
}
function createSynthBindingPattern(bindingPattern, elements = emptyArray, types = []) {
  return { kind: 1 /* BindingPattern */, bindingPattern, elements, types };
}
function referenceSynthIdentifier(synthId) {
  synthId.hasBeenReferenced = true;
  return synthId.identifier;
}
function declareSynthBindingName(synthName) {
  return isSynthIdentifier(synthName) ? declareSynthIdentifier(synthName) : declareSynthBindingPattern(synthName);
}
function declareSynthBindingPattern(synthPattern) {
  for (const element of synthPattern.elements) {
    declareSynthBindingName(element);
  }
  return synthPattern.bindingPattern;
}
function declareSynthIdentifier(synthId) {
  synthId.hasBeenDeclared = true;
  return synthId.identifier;
}
function isSynthIdentifier(bindingName) {
  return bindingName.kind === 0 /* Identifier */;
}
function isSynthBindingPattern(bindingName) {
  return bindingName.kind === 1 /* BindingPattern */;
}
function shouldReturn(expression, transformer) {
  return !!expression.original && transformer.setOfExpressionsToReturn.has(getNodeId(expression.original));
}

// src/services/codefixes/convertToEsModule.ts
registerCodeFix({
  errorCodes: [Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module.code],
  getCodeActions(context) {
    const { sourceFile, program, preferences } = context;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => {
      const moduleExportsChangedToDefault = convertFileToEsModule(sourceFile, program.getTypeChecker(), changes2, getEmitScriptTarget(program.getCompilerOptions()), getQuotePreference(sourceFile, preferences));
      if (moduleExportsChangedToDefault) {
        for (const importingFile of program.getSourceFiles()) {
          fixImportOfModuleExports(importingFile, sourceFile, program, changes2, getQuotePreference(importingFile, preferences));
        }
      }
    });
    return [createCodeFixActionWithoutFixAll("convertToEsModule", changes, Diagnostics.Convert_to_ES_module)];
  }
});
function fixImportOfModuleExports(importingFile, exportingFile, program, changes, quotePreference) {
  var _a;
  for (const moduleSpecifier of importingFile.imports) {
    const imported = (_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier, importingFile)) == null ? void 0 : _a.resolvedModule;
    if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
      continue;
    }
    const importNode = importFromModuleSpecifier(moduleSpecifier);
    switch (importNode.kind) {
      case 271 /* ImportEqualsDeclaration */:
        changes.replaceNode(importingFile, importNode, makeImport(
          importNode.name,
          /*namedImports*/
          void 0,
          moduleSpecifier,
          quotePreference
        ));
        break;
      case 213 /* CallExpression */:
        if (isRequireCall(
          importNode,
          /*requireStringLiteralLikeArgument*/
          false
        )) {
          changes.replaceNode(importingFile, importNode, factory.createPropertyAccessExpression(getSynthesizedDeepClone(importNode), "default"));
        }
        break;
    }
  }
}
function convertFileToEsModule(sourceFile, checker, changes, target, quotePreference) {
  const identifiers = { original: collectFreeIdentifiers(sourceFile), additional: /* @__PURE__ */ new Set() };
  const exports2 = collectExportRenames(sourceFile, checker, identifiers);
  convertExportsAccesses(sourceFile, exports2, changes);
  let moduleExportsChangedToDefault = false;
  let useSitesToUnqualify;
  for (const statement of filter(sourceFile.statements, isVariableStatement)) {
    const newUseSites = convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference);
    if (newUseSites) {
      copyEntries(newUseSites, useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map()));
    }
  }
  for (const statement of filter(sourceFile.statements, (s) => !isVariableStatement(s))) {
    const moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports2, useSitesToUnqualify, quotePreference);
    moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
  }
  useSitesToUnqualify == null ? void 0 : useSitesToUnqualify.forEach((replacement, original) => {
    changes.replaceNode(sourceFile, original, replacement);
  });
  return moduleExportsChangedToDefault;
}
function collectExportRenames(sourceFile, checker, identifiers) {
  const res = /* @__PURE__ */ new Map();
  forEachExportReference(sourceFile, (node) => {
    const { text } = node.name;
    if (!res.has(text) && (isIdentifierANonContextualKeyword(node.name) || checker.resolveName(
      text,
      node,
      111551 /* Value */,
      /*excludeGlobals*/
      true
    ))) {
      res.set(text, makeUniqueName(`_${text}`, identifiers));
    }
  });
  return res;
}
function convertExportsAccesses(sourceFile, exports2, changes) {
  forEachExportReference(sourceFile, (node, isAssignmentLhs) => {
    if (isAssignmentLhs) {
      return;
    }
    const { text } = node.name;
    changes.replaceNode(sourceFile, node, factory.createIdentifier(exports2.get(text) || text));
  });
}
function forEachExportReference(sourceFile, cb) {
  sourceFile.forEachChild(function recur(node) {
    if (isPropertyAccessExpression(node) && isExportsOrModuleExportsOrAlias(sourceFile, node.expression) && isIdentifier(node.name)) {
      const { parent: parent2 } = node;
      cb(node, isBinaryExpression(parent2) && parent2.left === node && parent2.operatorToken.kind === 64 /* EqualsToken */);
    }
    node.forEachChild(recur);
  });
}
function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports2, useSitesToUnqualify, quotePreference) {
  switch (statement.kind) {
    case 243 /* VariableStatement */:
      convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference);
      return false;
    case 244 /* ExpressionStatement */: {
      const { expression } = statement;
      switch (expression.kind) {
        case 213 /* CallExpression */: {
          if (isRequireCall(
            expression,
            /*requireStringLiteralLikeArgument*/
            true
          )) {
            changes.replaceNode(sourceFile, statement, makeImport(
              /*defaultImport*/
              void 0,
              /*namedImports*/
              void 0,
              expression.arguments[0],
              quotePreference
            ));
          }
          return false;
        }
        case 226 /* BinaryExpression */: {
          const { operatorToken } = expression;
          return operatorToken.kind === 64 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports2, useSitesToUnqualify);
        }
      }
    }
    // falls through
    default:
      return false;
  }
}
function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) {
  const { declarationList } = statement;
  let foundImport = false;
  const converted = map(declarationList.declarations, (decl) => {
    const { name, initializer } = decl;
    if (initializer) {
      if (isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
        foundImport = true;
        return convertedImports([]);
      } else if (isRequireCall(
        initializer,
        /*requireStringLiteralLikeArgument*/
        true
      )) {
        foundImport = true;
        return convertSingleImport(name, initializer.arguments[0], checker, identifiers, target, quotePreference);
      } else if (isPropertyAccessExpression(initializer) && isRequireCall(
        initializer.expression,
        /*requireStringLiteralLikeArgument*/
        true
      )) {
        foundImport = true;
        return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference);
      }
    }
    return convertedImports([factory.createVariableStatement(
      /*modifiers*/
      void 0,
      factory.createVariableDeclarationList([decl], declarationList.flags)
    )]);
  });
  if (foundImport) {
    changes.replaceNodeWithNodes(sourceFile, statement, flatMap(converted, (c) => c.newImports));
    let combinedUseSites;
    forEach(converted, (c) => {
      if (c.useSitesToUnqualify) {
        copyEntries(c.useSitesToUnqualify, combinedUseSites ?? (combinedUseSites = /* @__PURE__ */ new Map()));
      }
    });
    return combinedUseSites;
  }
}
function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) {
  switch (name.kind) {
    case 206 /* ObjectBindingPattern */:
    case 207 /* ArrayBindingPattern */: {
      const tmp = makeUniqueName(propertyName, identifiers);
      return convertedImports([
        makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference),
        makeConst(
          /*modifiers*/
          void 0,
          name,
          factory.createIdentifier(tmp)
        )
      ]);
    }
    case 80 /* Identifier */:
      return convertedImports([makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]);
    default:
      return Debug.assertNever(name, `Convert to ES module got invalid syntax form ${name.kind}`);
  }
}
function convertAssignment(sourceFile, checker, assignment, changes, exports2, useSitesToUnqualify) {
  const { left, right } = assignment;
  if (!isPropertyAccessExpression(left)) {
    return false;
  }
  if (isExportsOrModuleExportsOrAlias(sourceFile, left)) {
    if (isExportsOrModuleExportsOrAlias(sourceFile, right)) {
      changes.delete(sourceFile, assignment.parent);
    } else {
      const replacement = isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right, useSitesToUnqualify) : isRequireCall(
        right,
        /*requireStringLiteralLikeArgument*/
        true
      ) ? convertReExportAll(right.arguments[0], checker) : void 0;
      if (replacement) {
        changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
        return replacement[1];
      } else {
        changes.replaceRangeWithText(sourceFile, createRange(left.getStart(sourceFile), right.pos), "export default");
        return true;
      }
    }
  } else if (isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
    convertNamedExport(sourceFile, assignment, changes, exports2);
  }
  return false;
}
function tryChangeModuleExportsObject(object, useSitesToUnqualify) {
  const statements = mapAllOrFail(object.properties, (prop) => {
    switch (prop.kind) {
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
      // falls through
      case 304 /* ShorthandPropertyAssignment */:
      case 305 /* SpreadAssignment */:
        return void 0;
      case 303 /* PropertyAssignment */:
        return !isIdentifier(prop.name) ? void 0 : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer, useSitesToUnqualify);
      case 174 /* MethodDeclaration */:
        return !isIdentifier(prop.name) ? void 0 : functionExpressionToDeclaration(prop.name.text, [factory.createToken(95 /* ExportKeyword */)], prop, useSitesToUnqualify);
      default:
        Debug.assertNever(prop, `Convert to ES6 got invalid prop kind ${prop.kind}`);
    }
  });
  return statements && [statements, false];
}
function convertNamedExport(sourceFile, assignment, changes, exports2) {
  const { text } = assignment.left.name;
  const rename = exports2.get(text);
  if (rename !== void 0) {
    const newNodes = [
      makeConst(
        /*modifiers*/
        void 0,
        rename,
        assignment.right
      ),
      makeExportDeclaration([factory.createExportSpecifier(
        /*isTypeOnly*/
        false,
        rename,
        text
      )])
    ];
    changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
  } else {
    convertExportsPropertyAssignment(assignment, sourceFile, changes);
  }
}
function convertReExportAll(reExported, checker) {
  const moduleSpecifier = reExported.text;
  const moduleSymbol = checker.getSymbolAtLocation(reExported);
  const exports2 = moduleSymbol ? moduleSymbol.exports : emptyMap;
  return exports2.has("export=" /* ExportEquals */) ? [[reExportDefault(moduleSpecifier)], true] : !exports2.has("default" /* Default */) ? [[reExportStar(moduleSpecifier)], false] : (
    // If there's some non-default export, must include both `export *` and `export default`.
    exports2.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]
  );
}
function reExportStar(moduleSpecifier) {
  return makeExportDeclaration(
    /*exportSpecifiers*/
    void 0,
    moduleSpecifier
  );
}
function reExportDefault(moduleSpecifier) {
  return makeExportDeclaration([factory.createExportSpecifier(
    /*isTypeOnly*/
    false,
    /*propertyName*/
    void 0,
    "default"
  )], moduleSpecifier);
}
function convertExportsPropertyAssignment({ left, right, parent: parent2 }, sourceFile, changes) {
  const name = left.name.text;
  if ((isFunctionExpression(right) || isArrowFunction(right) || isClassExpression(right)) && (!right.name || right.name.text === name)) {
    changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, factory.createToken(95 /* ExportKeyword */), { suffix: " " });
    if (!right.name) changes.insertName(sourceFile, right, name);
    const semi = findChildOfKind(parent2, 27 /* SemicolonToken */, sourceFile);
    if (semi) changes.delete(sourceFile, semi);
  } else {
    changes.replaceNodeRangeWithNodes(sourceFile, left.expression, findChildOfKind(left, 25 /* DotToken */, sourceFile), [factory.createToken(95 /* ExportKeyword */), factory.createToken(87 /* ConstKeyword */)], { joiner: " ", suffix: " " });
  }
}
function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualify) {
  const modifiers = [factory.createToken(95 /* ExportKeyword */)];
  switch (exported.kind) {
    case 218 /* FunctionExpression */: {
      const { name: expressionName } = exported;
      if (expressionName && expressionName.text !== name) {
        return exportConst();
      }
    }
    // falls through
    case 219 /* ArrowFunction */:
      return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify);
    case 231 /* ClassExpression */:
      return classExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify);
    default:
      return exportConst();
  }
  function exportConst() {
    return makeConst(modifiers, factory.createIdentifier(name), replaceImportUseSites(exported, useSitesToUnqualify));
  }
}
function replaceImportUseSites(nodeOrNodes, useSitesToUnqualify) {
  if (!useSitesToUnqualify || !some(arrayFrom(useSitesToUnqualify.keys()), (original) => rangeContainsRange(nodeOrNodes, original))) {
    return nodeOrNodes;
  }
  return isArray(nodeOrNodes) ? getSynthesizedDeepClonesWithReplacements(
    nodeOrNodes,
    /*includeTrivia*/
    true,
    replaceNode
  ) : getSynthesizedDeepCloneWithReplacements(
    nodeOrNodes,
    /*includeTrivia*/
    true,
    replaceNode
  );
  function replaceNode(original) {
    if (original.kind === 211 /* PropertyAccessExpression */) {
      const replacement = useSitesToUnqualify.get(original);
      useSitesToUnqualify.delete(original);
      return replacement;
    }
  }
}
function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) {
  switch (name.kind) {
    case 206 /* ObjectBindingPattern */: {
      const importSpecifiers = mapAllOrFail(name.elements, (e) => e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier2(e.propertyName && e.propertyName.text, e.name.text));
      if (importSpecifiers) {
        return convertedImports([makeImport(
          /*defaultImport*/
          void 0,
          importSpecifiers,
          moduleSpecifier,
          quotePreference
        )]);
      }
    }
    // falls through -- object destructuring has an interesting pattern and must be a variable declaration
    case 207 /* ArrayBindingPattern */: {
      const tmp = makeUniqueName(moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
      return convertedImports([
        makeImport(
          factory.createIdentifier(tmp),
          /*namedImports*/
          void 0,
          moduleSpecifier,
          quotePreference
        ),
        makeConst(
          /*modifiers*/
          void 0,
          getSynthesizedDeepClone(name),
          factory.createIdentifier(tmp)
        )
      ]);
    }
    case 80 /* Identifier */:
      return convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference);
    default:
      return Debug.assertNever(name, `Convert to ES module got invalid name kind ${name.kind}`);
  }
}
function convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference) {
  const nameSymbol = checker.getSymbolAtLocation(name);
  const namedBindingsNames = /* @__PURE__ */ new Map();
  let needDefaultImport = false;
  let useSitesToUnqualify;
  for (const use of identifiers.original.get(name.text)) {
    if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
      continue;
    }
    const { parent: parent2 } = use;
    if (isPropertyAccessExpression(parent2)) {
      const { name: { text: propertyName } } = parent2;
      if (propertyName === "default") {
        needDefaultImport = true;
        const importDefaultName = use.getText();
        (useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map())).set(parent2, factory.createIdentifier(importDefaultName));
      } else {
        Debug.assert(parent2.expression === use, "Didn't expect expression === use");
        let idName = namedBindingsNames.get(propertyName);
        if (idName === void 0) {
          idName = makeUniqueName(propertyName, identifiers);
          namedBindingsNames.set(propertyName, idName);
        }
        (useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map())).set(parent2, factory.createIdentifier(idName));
      }
    } else {
      needDefaultImport = true;
    }
  }
  const namedBindings = namedBindingsNames.size === 0 ? void 0 : arrayFrom(mapIterator(namedBindingsNames.entries(), ([propertyName, idName]) => factory.createImportSpecifier(
    /*isTypeOnly*/
    false,
    propertyName === idName ? void 0 : factory.createIdentifier(propertyName),
    factory.createIdentifier(idName)
  )));
  if (!namedBindings) {
    needDefaultImport = true;
  }
  return convertedImports(
    [makeImport(needDefaultImport ? getSynthesizedDeepClone(name) : void 0, namedBindings, moduleSpecifier, quotePreference)],
    useSitesToUnqualify
  );
}
function makeUniqueName(name, identifiers) {
  while (identifiers.original.has(name) || identifiers.additional.has(name)) {
    name = `_${name}`;
  }
  identifiers.additional.add(name);
  return name;
}
function collectFreeIdentifiers(file) {
  const map2 = createMultiMap();
  forEachFreeIdentifier(file, (id) => map2.add(id.text, id));
  return map2;
}
function forEachFreeIdentifier(node, cb) {
  if (isIdentifier(node) && isFreeIdentifier(node)) cb(node);
  node.forEachChild((child) => forEachFreeIdentifier(child, cb));
}
function isFreeIdentifier(node) {
  const { parent: parent2 } = node;
  switch (parent2.kind) {
    case 211 /* PropertyAccessExpression */:
      return parent2.name !== node;
    case 208 /* BindingElement */:
      return parent2.propertyName !== node;
    case 276 /* ImportSpecifier */:
      return parent2.propertyName !== node;
    default:
      return true;
  }
}
function functionExpressionToDeclaration(name, additionalModifiers, fn, useSitesToUnqualify) {
  return factory.createFunctionDeclaration(
    concatenate(additionalModifiers, getSynthesizedDeepClones(fn.modifiers)),
    getSynthesizedDeepClone(fn.asteriskToken),
    name,
    getSynthesizedDeepClones(fn.typeParameters),
    getSynthesizedDeepClones(fn.parameters),
    getSynthesizedDeepClone(fn.type),
    factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))
  );
}
function classExpressionToDeclaration(name, additionalModifiers, cls, useSitesToUnqualify) {
  return factory.createClassDeclaration(
    concatenate(additionalModifiers, getSynthesizedDeepClones(cls.modifiers)),
    name,
    getSynthesizedDeepClones(cls.typeParameters),
    getSynthesizedDeepClones(cls.heritageClauses),
    replaceImportUseSites(cls.members, useSitesToUnqualify)
  );
}
function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) {
  return propertyName === "default" ? makeImport(
    factory.createIdentifier(localName),
    /*namedImports*/
    void 0,
    moduleSpecifier,
    quotePreference
  ) : makeImport(
    /*defaultImport*/
    void 0,
    [makeImportSpecifier2(propertyName, localName)],
    moduleSpecifier,
    quotePreference
  );
}
function makeImportSpecifier2(propertyName, name) {
  return factory.createImportSpecifier(
    /*isTypeOnly*/
    false,
    propertyName !== void 0 && propertyName !== name ? factory.createIdentifier(propertyName) : void 0,
    factory.createIdentifier(name)
  );
}
function makeConst(modifiers, name, init) {
  return factory.createVariableStatement(
    modifiers,
    factory.createVariableDeclarationList(
      [factory.createVariableDeclaration(
        name,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        init
      )],
      2 /* Const */
    )
  );
}
function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
  return factory.createExportDeclaration(
    /*modifiers*/
    void 0,
    /*isTypeOnly*/
    false,
    exportSpecifiers && factory.createNamedExports(exportSpecifiers),
    moduleSpecifier === void 0 ? void 0 : factory.createStringLiteral(moduleSpecifier)
  );
}
function convertedImports(newImports, useSitesToUnqualify) {
  return {
    newImports,
    useSitesToUnqualify
  };
}

// src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts
var fixId12 = "correctQualifiedNameToIndexedAccessType";
var errorCodes13 = [Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code];
registerCodeFix({
  errorCodes: errorCodes13,
  getCodeActions(context) {
    const qualifiedName = getQualifiedName(context.sourceFile, context.span.start);
    if (!qualifiedName) return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange10(t, context.sourceFile, qualifiedName));
    const newText = `${qualifiedName.left.text}["${qualifiedName.right.text}"]`;
    return [createCodeFixAction(fixId12, changes, [Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId12, Diagnostics.Rewrite_all_as_indexed_access_types)];
  },
  fixIds: [fixId12],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes13, (changes, diag2) => {
    const q = getQualifiedName(diag2.file, diag2.start);
    if (q) {
      doChange10(changes, diag2.file, q);
    }
  })
});
function getQualifiedName(sourceFile, pos) {
  const qualifiedName = findAncestor(getTokenAtPosition(sourceFile, pos), isQualifiedName);
  Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name.");
  return isIdentifier(qualifiedName.left) ? qualifiedName : void 0;
}
function doChange10(changeTracker, sourceFile, qualifiedName) {
  const rightText = qualifiedName.right.text;
  const replacement = factory.createIndexedAccessTypeNode(
    factory.createTypeReferenceNode(
      qualifiedName.left,
      /*typeArguments*/
      void 0
    ),
    factory.createLiteralTypeNode(factory.createStringLiteral(rightText))
  );
  changeTracker.replaceNode(sourceFile, qualifiedName, replacement);
}

// src/services/codefixes/convertToTypeOnlyExport.ts
var errorCodes14 = [Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type.code];
var fixId13 = "convertToTypeOnlyExport";
registerCodeFix({
  errorCodes: errorCodes14,
  getCodeActions: function getCodeActionsToConvertToTypeOnlyExport(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context));
    if (changes.length) {
      return [createCodeFixAction(fixId13, changes, Diagnostics.Convert_to_type_only_export, fixId13, Diagnostics.Convert_all_re_exported_types_to_type_only_exports)];
    }
  },
  fixIds: [fixId13],
  getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyExport(context) {
    const fixedExportDeclarations = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes14, (changes, diag2) => {
      const exportSpecifier = getExportSpecifierForDiagnosticSpan(diag2, context.sourceFile);
      if (exportSpecifier && addToSeen(fixedExportDeclarations, getNodeId(exportSpecifier.parent.parent))) {
        fixSingleExportDeclaration(changes, exportSpecifier, context);
      }
    });
  }
});
function getExportSpecifierForDiagnosticSpan(span, sourceFile) {
  return tryCast(getTokenAtPosition(sourceFile, span.start).parent, isExportSpecifier);
}
function fixSingleExportDeclaration(changes, exportSpecifier, context) {
  if (!exportSpecifier) {
    return;
  }
  const exportClause = exportSpecifier.parent;
  const exportDeclaration = exportClause.parent;
  const typeExportSpecifiers = getTypeExportSpecifiers(exportSpecifier, context);
  if (typeExportSpecifiers.length === exportClause.elements.length) {
    changes.insertModifierBefore(context.sourceFile, 156 /* TypeKeyword */, exportClause);
  } else {
    const valueExportDeclaration = factory.updateExportDeclaration(
      exportDeclaration,
      exportDeclaration.modifiers,
      /*isTypeOnly*/
      false,
      factory.updateNamedExports(exportClause, filter(exportClause.elements, (e) => !contains(typeExportSpecifiers, e))),
      exportDeclaration.moduleSpecifier,
      /*attributes*/
      void 0
    );
    const typeExportDeclaration = factory.createExportDeclaration(
      /*modifiers*/
      void 0,
      /*isTypeOnly*/
      true,
      factory.createNamedExports(typeExportSpecifiers),
      exportDeclaration.moduleSpecifier,
      /*attributes*/
      void 0
    );
    changes.replaceNode(context.sourceFile, exportDeclaration, valueExportDeclaration, {
      leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll,
      trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude
    });
    changes.insertNodeAfter(context.sourceFile, exportDeclaration, typeExportDeclaration);
  }
}
function getTypeExportSpecifiers(originExportSpecifier, context) {
  const exportClause = originExportSpecifier.parent;
  if (exportClause.elements.length === 1) {
    return exportClause.elements;
  }
  const diagnostics = getDiagnosticsWithinSpan(
    createTextSpanFromNode(exportClause),
    context.program.getSemanticDiagnostics(context.sourceFile, context.cancellationToken)
  );
  return filter(exportClause.elements, (element) => {
    var _a;
    return element === originExportSpecifier || ((_a = findDiagnosticForNode(element, diagnostics)) == null ? void 0 : _a.code) === errorCodes14[0];
  });
}

// src/services/codefixes/convertToTypeOnlyImport.ts
var errorCodes15 = [
  Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled.code,
  Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled.code
];
var fixId14 = "convertToTypeOnlyImport";
registerCodeFix({
  errorCodes: errorCodes15,
  getCodeActions: function getCodeActionsToConvertToTypeOnlyImport(context) {
    var _a;
    const declaration = getDeclaration2(context.sourceFile, context.span.start);
    if (declaration) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, context.sourceFile, declaration));
      const importDeclarationChanges = declaration.kind === 276 /* ImportSpecifier */ && isImportDeclaration(declaration.parent.parent.parent) && canConvertImportDeclarationForSpecifier(declaration, context.sourceFile, context.program) ? ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, context.sourceFile, declaration.parent.parent.parent)) : void 0;
      const mainAction = createCodeFixAction(
        fixId14,
        changes,
        declaration.kind === 276 /* ImportSpecifier */ ? [Diagnostics.Use_type_0, ((_a = declaration.propertyName) == null ? void 0 : _a.text) ?? declaration.name.text] : Diagnostics.Use_import_type,
        fixId14,
        Diagnostics.Fix_all_with_type_only_imports
      );
      if (some(importDeclarationChanges)) {
        return [
          createCodeFixActionWithoutFixAll(fixId14, importDeclarationChanges, Diagnostics.Use_import_type),
          mainAction
        ];
      }
      return [mainAction];
    }
    return void 0;
  },
  fixIds: [fixId14],
  getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyImport(context) {
    const fixedImportDeclarations = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes15, (changes, diag2) => {
      const errorDeclaration = getDeclaration2(diag2.file, diag2.start);
      if ((errorDeclaration == null ? void 0 : errorDeclaration.kind) === 272 /* ImportDeclaration */ && !fixedImportDeclarations.has(errorDeclaration)) {
        doChange11(changes, diag2.file, errorDeclaration);
        fixedImportDeclarations.add(errorDeclaration);
      } else if ((errorDeclaration == null ? void 0 : errorDeclaration.kind) === 276 /* ImportSpecifier */ && isImportDeclaration(errorDeclaration.parent.parent.parent) && !fixedImportDeclarations.has(errorDeclaration.parent.parent.parent) && canConvertImportDeclarationForSpecifier(errorDeclaration, diag2.file, context.program)) {
        doChange11(changes, diag2.file, errorDeclaration.parent.parent.parent);
        fixedImportDeclarations.add(errorDeclaration.parent.parent.parent);
      } else if ((errorDeclaration == null ? void 0 : errorDeclaration.kind) === 276 /* ImportSpecifier */) {
        doChange11(changes, diag2.file, errorDeclaration);
      }
    });
  }
});
function getDeclaration2(sourceFile, pos) {
  const { parent: parent2 } = getTokenAtPosition(sourceFile, pos);
  return isImportSpecifier(parent2) || isImportDeclaration(parent2) && parent2.importClause ? parent2 : void 0;
}
function canConvertImportDeclarationForSpecifier(specifier, sourceFile, program) {
  if (specifier.parent.parent.name) {
    return false;
  }
  const nonTypeOnlySpecifiers = specifier.parent.elements.filter((e) => !e.isTypeOnly);
  if (nonTypeOnlySpecifiers.length === 1) {
    return true;
  }
  const checker = program.getTypeChecker();
  for (const specifier2 of nonTypeOnlySpecifiers) {
    const isUsedAsValue = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(specifier2.name, checker, sourceFile, (usage) => {
      const symbol = checker.getSymbolAtLocation(usage);
      return !!symbol && checker.symbolIsValue(symbol) || !isValidTypeOnlyAliasUseSite(usage);
    });
    if (isUsedAsValue) {
      return false;
    }
  }
  return true;
}
function doChange11(changes, sourceFile, declaration) {
  var _a;
  if (isImportSpecifier(declaration)) {
    changes.replaceNode(sourceFile, declaration, factory.updateImportSpecifier(
      declaration,
      /*isTypeOnly*/
      true,
      declaration.propertyName,
      declaration.name
    ));
  } else {
    const importClause = declaration.importClause;
    if (importClause.name && importClause.namedBindings) {
      changes.replaceNodeWithNodes(sourceFile, declaration, [
        factory.createImportDeclaration(
          getSynthesizedDeepClones(
            declaration.modifiers,
            /*includeTrivia*/
            true
          ),
          factory.createImportClause(
            /*isTypeOnly*/
            true,
            getSynthesizedDeepClone(
              importClause.name,
              /*includeTrivia*/
              true
            ),
            /*namedBindings*/
            void 0
          ),
          getSynthesizedDeepClone(
            declaration.moduleSpecifier,
            /*includeTrivia*/
            true
          ),
          getSynthesizedDeepClone(
            declaration.attributes,
            /*includeTrivia*/
            true
          )
        ),
        factory.createImportDeclaration(
          getSynthesizedDeepClones(
            declaration.modifiers,
            /*includeTrivia*/
            true
          ),
          factory.createImportClause(
            /*isTypeOnly*/
            true,
            /*name*/
            void 0,
            getSynthesizedDeepClone(
              importClause.namedBindings,
              /*includeTrivia*/
              true
            )
          ),
          getSynthesizedDeepClone(
            declaration.moduleSpecifier,
            /*includeTrivia*/
            true
          ),
          getSynthesizedDeepClone(
            declaration.attributes,
            /*includeTrivia*/
            true
          )
        )
      ]);
    } else {
      const newNamedBindings = ((_a = importClause.namedBindings) == null ? void 0 : _a.kind) === 275 /* NamedImports */ ? factory.updateNamedImports(
        importClause.namedBindings,
        sameMap(importClause.namedBindings.elements, (e) => factory.updateImportSpecifier(
          e,
          /*isTypeOnly*/
          false,
          e.propertyName,
          e.name
        ))
      ) : importClause.namedBindings;
      const importDeclaration = factory.updateImportDeclaration(declaration, declaration.modifiers, factory.updateImportClause(
        importClause,
        /*isTypeOnly*/
        true,
        importClause.name,
        newNamedBindings
      ), declaration.moduleSpecifier, declaration.attributes);
      changes.replaceNode(sourceFile, declaration, importDeclaration);
    }
  }
}

// src/services/codefixes/convertTypedefToType.ts
var fixId15 = "convertTypedefToType";
var errorCodes16 = [Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type.code];
registerCodeFix({
  fixIds: [fixId15],
  errorCodes: errorCodes16,
  getCodeActions(context) {
    const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options);
    const node = getTokenAtPosition(
      context.sourceFile,
      context.span.start
    );
    if (!node) return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile, newLineCharacter));
    if (changes.length > 0) {
      return [
        createCodeFixAction(
          fixId15,
          changes,
          Diagnostics.Convert_typedef_to_TypeScript_type,
          fixId15,
          Diagnostics.Convert_all_typedef_to_TypeScript_types
        )
      ];
    }
  },
  getAllCodeActions: (context) => codeFixAll(
    context,
    errorCodes16,
    (changes, diag2) => {
      const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options);
      const node = getTokenAtPosition(diag2.file, diag2.start);
      const fixAll = true;
      if (node) doChange12(changes, node, diag2.file, newLineCharacter, fixAll);
    }
  )
});
function doChange12(changes, node, sourceFile, newLine, fixAll = false) {
  if (!isJSDocTypedefTag(node)) return;
  const declaration = createDeclaration(node);
  if (!declaration) return;
  const commentNode = node.parent;
  const { leftSibling, rightSibling } = getLeftAndRightSiblings(node);
  let pos = commentNode.getStart();
  let prefix = "";
  if (!leftSibling && commentNode.comment) {
    pos = findEndOfTextBetween(commentNode, commentNode.getStart(), node.getStart());
    prefix = `${newLine} */${newLine}`;
  }
  if (leftSibling) {
    if (fixAll && isJSDocTypedefTag(leftSibling)) {
      pos = node.getStart();
      prefix = "";
    } else {
      pos = findEndOfTextBetween(commentNode, leftSibling.getStart(), node.getStart());
      prefix = `${newLine} */${newLine}`;
    }
  }
  let end = commentNode.getEnd();
  let suffix = "";
  if (rightSibling) {
    if (fixAll && isJSDocTypedefTag(rightSibling)) {
      end = rightSibling.getStart();
      suffix = `${newLine}${newLine}`;
    } else {
      end = rightSibling.getStart();
      suffix = `${newLine}/**${newLine} * `;
    }
  }
  changes.replaceRange(sourceFile, { pos, end }, declaration, { prefix, suffix });
}
function getLeftAndRightSiblings(typedefNode) {
  const commentNode = typedefNode.parent;
  const maxChildIndex = commentNode.getChildCount() - 1;
  const currentNodeIndex = commentNode.getChildren().findIndex(
    (n) => n.getStart() === typedefNode.getStart() && n.getEnd() === typedefNode.getEnd()
  );
  const leftSibling = currentNodeIndex > 0 ? commentNode.getChildAt(currentNodeIndex - 1) : void 0;
  const rightSibling = currentNodeIndex < maxChildIndex ? commentNode.getChildAt(currentNodeIndex + 1) : void 0;
  return { leftSibling, rightSibling };
}
function findEndOfTextBetween(jsDocComment, from, to) {
  const comment = jsDocComment.getText().substring(from - jsDocComment.getStart(), to - jsDocComment.getStart());
  for (let i = comment.length; i > 0; i--) {
    if (!/[*/\s]/.test(comment.substring(i - 1, i))) {
      return from + i;
    }
  }
  return to;
}
function createDeclaration(tag) {
  var _a;
  const { typeExpression } = tag;
  if (!typeExpression) return;
  const typeName = (_a = tag.name) == null ? void 0 : _a.getText();
  if (!typeName) return;
  if (typeExpression.kind === 322 /* JSDocTypeLiteral */) {
    return createInterfaceForTypeLiteral(typeName, typeExpression);
  }
  if (typeExpression.kind === 309 /* JSDocTypeExpression */) {
    return createTypeAliasForTypeExpression(typeName, typeExpression);
  }
}
function createInterfaceForTypeLiteral(typeName, typeLiteral) {
  const propertySignatures = createSignatureFromTypeLiteral(typeLiteral);
  if (!some(propertySignatures)) return;
  return factory.createInterfaceDeclaration(
    /*modifiers*/
    void 0,
    typeName,
    /*typeParameters*/
    void 0,
    /*heritageClauses*/
    void 0,
    propertySignatures
  );
}
function createTypeAliasForTypeExpression(typeName, typeExpression) {
  const typeReference = getSynthesizedDeepClone(typeExpression.type);
  if (!typeReference) return;
  return factory.createTypeAliasDeclaration(
    /*modifiers*/
    void 0,
    factory.createIdentifier(typeName),
    /*typeParameters*/
    void 0,
    typeReference
  );
}
function createSignatureFromTypeLiteral(typeLiteral) {
  const propertyTags = typeLiteral.jsDocPropertyTags;
  if (!some(propertyTags)) return;
  const getSignature = (tag) => {
    var _a;
    const name = getPropertyName(tag);
    const type = (_a = tag.typeExpression) == null ? void 0 : _a.type;
    const isOptional = tag.isBracketed;
    let typeReference;
    if (type && isJSDocTypeLiteral(type)) {
      const signatures = createSignatureFromTypeLiteral(type);
      typeReference = factory.createTypeLiteralNode(signatures);
    } else if (type) {
      typeReference = getSynthesizedDeepClone(type);
    }
    if (typeReference && name) {
      const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0;
      return factory.createPropertySignature(
        /*modifiers*/
        void 0,
        name,
        questionToken,
        typeReference
      );
    }
  };
  return mapDefined(propertyTags, getSignature);
}
function getPropertyName(tag) {
  return tag.name.kind === 80 /* Identifier */ ? tag.name.text : tag.name.right.text;
}
function getJSDocTypedefNodes(node) {
  if (hasJSDocNodes(node)) {
    return flatMap(node.jsDoc, (doc) => {
      var _a;
      return (_a = doc.tags) == null ? void 0 : _a.filter((tag) => isJSDocTypedefTag(tag));
    });
  }
  return [];
}

// src/services/codefixes/convertLiteralTypeToMappedType.ts
var fixId16 = "convertLiteralTypeToMappedType";
var errorCodes17 = [Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0.code];
registerCodeFix({
  errorCodes: errorCodes17,
  getCodeActions: function getCodeActionsToConvertLiteralTypeToMappedType(context) {
    const { sourceFile, span } = context;
    const info = getInfo5(sourceFile, span.start);
    if (!info) {
      return void 0;
    }
    const { name, constraint } = info;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange13(t, sourceFile, info));
    return [createCodeFixAction(fixId16, changes, [Diagnostics.Convert_0_to_1_in_0, constraint, name], fixId16, Diagnostics.Convert_all_type_literals_to_mapped_type)];
  },
  fixIds: [fixId16],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes17, (changes, diag2) => {
    const info = getInfo5(diag2.file, diag2.start);
    if (info) {
      doChange13(changes, diag2.file, info);
    }
  })
});
function getInfo5(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (isIdentifier(token)) {
    const propertySignature = cast(token.parent.parent, isPropertySignature);
    const propertyName = token.getText(sourceFile);
    return {
      container: cast(propertySignature.parent, isTypeLiteralNode),
      typeNode: propertySignature.type,
      constraint: propertyName,
      name: propertyName === "K" ? "P" : "K"
    };
  }
  return void 0;
}
function doChange13(changes, sourceFile, { container, typeNode, constraint, name }) {
  changes.replaceNode(
    sourceFile,
    container,
    factory.createMappedTypeNode(
      /*readonlyToken*/
      void 0,
      factory.createTypeParameterDeclaration(
        /*modifiers*/
        void 0,
        name,
        factory.createTypeReferenceNode(constraint)
      ),
      /*nameType*/
      void 0,
      /*questionToken*/
      void 0,
      typeNode,
      /*members*/
      void 0
    )
  );
}

// src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts
var errorCodes18 = [
  Diagnostics.Class_0_incorrectly_implements_interface_1.code,
  Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code
];
var fixId17 = "fixClassIncorrectlyImplementsInterface";
registerCodeFix({
  errorCodes: errorCodes18,
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const classDeclaration = getClass(sourceFile, span.start);
    return mapDefined(getEffectiveImplementsTypeNodes(classDeclaration), (implementedTypeNode) => {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences));
      return changes.length === 0 ? void 0 : createCodeFixAction(fixId17, changes, [Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId17, Diagnostics.Implement_all_unimplemented_interfaces);
    });
  },
  fixIds: [fixId17],
  getAllCodeActions(context) {
    const seenClassDeclarations = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes18, (changes, diag2) => {
      const classDeclaration = getClass(diag2.file, diag2.start);
      if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) {
        for (const implementedTypeNode of getEffectiveImplementsTypeNodes(classDeclaration)) {
          addMissingDeclarations(context, implementedTypeNode, diag2.file, classDeclaration, changes, context.preferences);
        }
      }
    });
  }
});
function getClass(sourceFile, pos) {
  return Debug.checkDefined(getContainingClass(getTokenAtPosition(sourceFile, pos)), "There should be a containing class");
}
function symbolPointsToNonPrivateMember(symbol) {
  return !symbol.valueDeclaration || !(getEffectiveModifierFlags(symbol.valueDeclaration) & 2 /* Private */);
}
function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) {
  const checker = context.program.getTypeChecker();
  const maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker);
  const implementedType = checker.getTypeAtLocation(implementedTypeNode);
  const implementedTypeSymbols = checker.getPropertiesOfType(implementedType);
  const nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(and(symbolPointsToNonPrivateMember, (symbol) => !maybeHeritageClauseSymbol.has(symbol.escapedName)));
  const classType = checker.getTypeAtLocation(classDeclaration);
  const constructor = find(classDeclaration.members, (m) => isConstructorDeclaration(m));
  if (!classType.getNumberIndexType()) {
    createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */);
  }
  if (!classType.getStringIndexType()) {
    createMissingIndexSignatureDeclaration(implementedType, 0 /* String */);
  }
  const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host);
  createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, sourceFile, context, preferences, importAdder, (member) => insertInterfaceMemberNode(sourceFile, classDeclaration, member));
  importAdder.writeFixes(changeTracker);
  function createMissingIndexSignatureDeclaration(type, kind) {
    const indexInfoOfKind = checker.getIndexInfoOfType(type, kind);
    if (indexInfoOfKind) {
      insertInterfaceMemberNode(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(
        indexInfoOfKind,
        classDeclaration,
        /*flags*/
        void 0,
        /*internalFlags*/
        void 0,
        getNoopSymbolTrackerWithResolver(context)
      ));
    }
  }
  function insertInterfaceMemberNode(sourceFile2, cls, newElement) {
    if (constructor) {
      changeTracker.insertNodeAfter(sourceFile2, constructor, newElement);
    } else {
      changeTracker.insertMemberAtStart(sourceFile2, cls, newElement);
    }
  }
}
function getHeritageClauseSymbolTable(classDeclaration, checker) {
  const heritageClauseNode = getEffectiveBaseTypeNode(classDeclaration);
  if (!heritageClauseNode) return createSymbolTable();
  const heritageClauseType = checker.getTypeAtLocation(heritageClauseNode);
  const heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType);
  return createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember));
}

// src/services/codefixes/importFixes.ts
var importFixName = "import";
var importFixId = "fixMissingImport";
var errorCodes19 = [
  Diagnostics.Cannot_find_name_0.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
  Diagnostics.Cannot_find_namespace_0.code,
  Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code,
  Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code,
  Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code,
  Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code,
  Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery.code,
  Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later.code,
  Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom.code,
  Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code,
  Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig.code,
  Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha.code,
  Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode.code,
  Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig.code,
  Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code,
  Diagnostics.This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found.code
];
registerCodeFix({
  errorCodes: errorCodes19,
  getCodeActions(context) {
    const { errorCode, preferences, sourceFile, span, program } = context;
    const info = getFixInfos(
      context,
      errorCode,
      span.start,
      /*useAutoImportProvider*/
      true
    );
    if (!info) return void 0;
    return info.map(
      ({ fix, symbolName: symbolName2, errorIdentifierText }) => codeActionForFix(
        context,
        sourceFile,
        symbolName2,
        fix,
        /*includeSymbolNameInDescription*/
        symbolName2 !== errorIdentifierText,
        program,
        preferences
      )
    );
  },
  fixIds: [importFixId],
  getAllCodeActions: (context) => {
    const { sourceFile, program, preferences, host, cancellationToken } = context;
    const importAdder = createImportAdderWorker(
      sourceFile,
      program,
      /*useAutoImportProvider*/
      true,
      preferences,
      host,
      cancellationToken
    );
    eachDiagnostic(context, errorCodes19, (diag2) => importAdder.addImportFromDiagnostic(diag2, context));
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, importAdder.writeFixes));
  }
});
function createImportAdder(sourceFile, program, preferences, host, cancellationToken) {
  return createImportAdderWorker(
    sourceFile,
    program,
    /*useAutoImportProvider*/
    false,
    preferences,
    host,
    cancellationToken
  );
}
function createImportAdderWorker(sourceFile, program, useAutoImportProvider, preferences, host, cancellationToken) {
  const compilerOptions = program.getCompilerOptions();
  const addToNamespace = [];
  const importType = [];
  const addToExisting = /* @__PURE__ */ new Map();
  const removeExisting = /* @__PURE__ */ new Set();
  const verbatimImports = /* @__PURE__ */ new Set();
  const newImports = /* @__PURE__ */ new Map();
  return { addImportFromDiagnostic, addImportFromExportedSymbol, addImportForModuleSymbol, writeFixes, hasFixes, addImportForUnresolvedIdentifier, addImportForNonExistentExport, removeExistingImport, addVerbatimImport };
  function addVerbatimImport(declaration) {
    verbatimImports.add(declaration);
  }
  function addImportForUnresolvedIdentifier(context, symbolToken, useAutoImportProvider2) {
    const info = getFixInfosWithoutDiagnostic(context, symbolToken, useAutoImportProvider2);
    if (!info || !info.length) return;
    addImport(first(info));
  }
  function addImportFromDiagnostic(diagnostic, context) {
    const info = getFixInfos(context, diagnostic.code, diagnostic.start, useAutoImportProvider);
    if (!info || !info.length) return;
    addImport(first(info));
  }
  function addImportFromExportedSymbol(exportedSymbol, isValidTypeOnlyUseSite, referenceImport) {
    var _a, _b;
    const moduleSymbol = Debug.checkDefined(exportedSymbol.parent, "Expected exported symbol to have module symbol as parent");
    const symbolName2 = getNameForExportedSymbol(exportedSymbol, getEmitScriptTarget(compilerOptions));
    const checker = program.getTypeChecker();
    const symbol = checker.getMergedSymbol(skipAlias(exportedSymbol, checker));
    const exportInfo = getAllExportInfoForSymbol(
      sourceFile,
      symbol,
      symbolName2,
      moduleSymbol,
      /*preferCapitalized*/
      false,
      program,
      host,
      preferences,
      cancellationToken
    );
    if (!exportInfo) {
      Debug.assert((_a = preferences.autoImportFileExcludePatterns) == null ? void 0 : _a.length);
      return;
    }
    const useRequire = shouldUseRequire(sourceFile, program);
    let fix = getImportFixForSymbol(
      sourceFile,
      exportInfo,
      program,
      /*position*/
      void 0,
      !!isValidTypeOnlyUseSite,
      useRequire,
      host,
      preferences
    );
    if (fix) {
      const localName = ((_b = tryCast(referenceImport == null ? void 0 : referenceImport.name, isIdentifier)) == null ? void 0 : _b.text) ?? symbolName2;
      let addAsTypeOnly;
      let propertyName;
      if (referenceImport && isTypeOnlyImportDeclaration(referenceImport) && (fix.kind === 3 /* AddNew */ || fix.kind === 2 /* AddToExisting */) && fix.addAsTypeOnly === 1 /* Allowed */) {
        addAsTypeOnly = 2 /* Required */;
      }
      if (exportedSymbol.name !== localName) {
        propertyName = exportedSymbol.name;
      }
      fix = {
        ...fix,
        ...addAsTypeOnly === void 0 ? {} : { addAsTypeOnly },
        ...propertyName === void 0 ? {} : { propertyName }
      };
      addImport({ fix, symbolName: localName ?? symbolName2, errorIdentifierText: void 0 });
    }
  }
  function addImportForModuleSymbol(symbolAlias, isValidTypeOnlyUseSite, referenceImport) {
    var _a, _b, _c;
    const checker = program.getTypeChecker();
    const moduleSymbol = checker.getAliasedSymbol(symbolAlias);
    Debug.assert(moduleSymbol.flags & 1536 /* Module */, "Expected symbol to be a module");
    const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host);
    const moduleSpecifierResult = ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo(
      moduleSymbol,
      checker,
      compilerOptions,
      sourceFile,
      moduleSpecifierResolutionHost,
      preferences,
      /*options*/
      void 0,
      /*forAutoImport*/
      true
    );
    const useRequire = shouldUseRequire(sourceFile, program);
    let addAsTypeOnly = getAddAsTypeOnly(
      isValidTypeOnlyUseSite,
      /*isForNewImportDeclaration*/
      true,
      /*symbol*/
      void 0,
      symbolAlias.flags,
      program.getTypeChecker(),
      compilerOptions
    );
    addAsTypeOnly = addAsTypeOnly === 1 /* Allowed */ && isTypeOnlyImportDeclaration(referenceImport) ? 2 /* Required */ : 1 /* Allowed */;
    const importKind = isImportDeclaration(referenceImport) ? isDefaultImport(referenceImport) ? 1 /* Default */ : 2 /* Namespace */ : isImportSpecifier(referenceImport) ? 0 /* Named */ : isImportClause(referenceImport) && !!referenceImport.name ? 1 /* Default */ : 2 /* Namespace */;
    const exportInfo = [{
      symbol: symbolAlias,
      moduleSymbol,
      moduleFileName: (_c = (_b = (_a = moduleSymbol.declarations) == null ? void 0 : _a[0]) == null ? void 0 : _b.getSourceFile()) == null ? void 0 : _c.fileName,
      exportKind: 4 /* Module */,
      targetFlags: symbolAlias.flags,
      isFromPackageJson: false
    }];
    const existingFix = getImportFixForSymbol(
      sourceFile,
      exportInfo,
      program,
      /*position*/
      void 0,
      !!isValidTypeOnlyUseSite,
      useRequire,
      host,
      preferences
    );
    let fix;
    if (existingFix && importKind !== 2 /* Namespace */) {
      fix = {
        ...existingFix,
        addAsTypeOnly,
        importKind
      };
    } else {
      fix = {
        kind: 3 /* AddNew */,
        moduleSpecifierKind: existingFix !== void 0 ? existingFix.moduleSpecifierKind : moduleSpecifierResult.kind,
        moduleSpecifier: existingFix !== void 0 ? existingFix.moduleSpecifier : first(moduleSpecifierResult.moduleSpecifiers),
        importKind,
        addAsTypeOnly,
        useRequire
      };
    }
    addImport({ fix, symbolName: symbolAlias.name, errorIdentifierText: void 0 });
  }
  function addImportForNonExistentExport(exportName, exportingFileName, exportKind, exportedMeanings, isImportUsageValidAsTypeOnly) {
    const exportingSourceFile = program.getSourceFile(exportingFileName);
    const useRequire = shouldUseRequire(sourceFile, program);
    if (exportingSourceFile && exportingSourceFile.symbol) {
      const { fixes } = getImportFixes(
        [{
          exportKind,
          isFromPackageJson: false,
          moduleFileName: exportingFileName,
          moduleSymbol: exportingSourceFile.symbol,
          targetFlags: exportedMeanings
        }],
        /*usagePosition*/
        void 0,
        isImportUsageValidAsTypeOnly,
        useRequire,
        program,
        sourceFile,
        host,
        preferences
      );
      if (fixes.length) {
        addImport({ fix: fixes[0], symbolName: exportName, errorIdentifierText: exportName });
      }
    } else {
      const futureExportingSourceFile = createFutureSourceFile(exportingFileName, 99 /* ESNext */, program, host);
      const moduleSpecifier = ts_moduleSpecifiers_exports.getLocalModuleSpecifierBetweenFileNames(
        sourceFile,
        exportingFileName,
        compilerOptions,
        createModuleSpecifierResolutionHost(program, host),
        preferences
      );
      const importKind = getImportKind(futureExportingSourceFile, exportKind, program);
      const addAsTypeOnly = getAddAsTypeOnly(
        isImportUsageValidAsTypeOnly,
        /*isForNewImportDeclaration*/
        true,
        /*symbol*/
        void 0,
        exportedMeanings,
        program.getTypeChecker(),
        compilerOptions
      );
      const fix = {
        kind: 3 /* AddNew */,
        moduleSpecifierKind: "relative",
        moduleSpecifier,
        importKind,
        addAsTypeOnly,
        useRequire
      };
      addImport({ fix, symbolName: exportName, errorIdentifierText: exportName });
    }
  }
  function removeExistingImport(declaration) {
    if (declaration.kind === 273 /* ImportClause */) {
      Debug.assertIsDefined(declaration.name, "ImportClause should have a name if it's being removed");
    }
    removeExisting.add(declaration);
  }
  function addImport(info) {
    var _a, _b, _c;
    const { fix, symbolName: symbolName2 } = info;
    switch (fix.kind) {
      case 0 /* UseNamespace */:
        addToNamespace.push(fix);
        break;
      case 1 /* JsdocTypeImport */:
        importType.push(fix);
        break;
      case 2 /* AddToExisting */: {
        const { importClauseOrBindingPattern, importKind, addAsTypeOnly, propertyName } = fix;
        let entry = addToExisting.get(importClauseOrBindingPattern);
        if (!entry) {
          addToExisting.set(importClauseOrBindingPattern, entry = { importClauseOrBindingPattern, defaultImport: void 0, namedImports: /* @__PURE__ */ new Map() });
        }
        if (importKind === 0 /* Named */) {
          const prevTypeOnly = (_a = entry == null ? void 0 : entry.namedImports.get(symbolName2)) == null ? void 0 : _a.addAsTypeOnly;
          entry.namedImports.set(symbolName2, { addAsTypeOnly: reduceAddAsTypeOnlyValues(prevTypeOnly, addAsTypeOnly), propertyName });
        } else {
          Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add to Existing) Default import should be missing or match symbolName");
          entry.defaultImport = {
            name: symbolName2,
            addAsTypeOnly: reduceAddAsTypeOnlyValues((_b = entry.defaultImport) == null ? void 0 : _b.addAsTypeOnly, addAsTypeOnly)
          };
        }
        break;
      }
      case 3 /* AddNew */: {
        const { moduleSpecifier, importKind, useRequire, addAsTypeOnly, propertyName } = fix;
        const entry = getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly);
        Debug.assert(entry.useRequire === useRequire, "(Add new) Tried to add an `import` and a `require` for the same module");
        switch (importKind) {
          case 1 /* Default */:
            Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add new) Default import should be missing or match symbolName");
            entry.defaultImport = { name: symbolName2, addAsTypeOnly: reduceAddAsTypeOnlyValues((_c = entry.defaultImport) == null ? void 0 : _c.addAsTypeOnly, addAsTypeOnly) };
            break;
          case 0 /* Named */:
            const prevValue = (entry.namedImports || (entry.namedImports = /* @__PURE__ */ new Map())).get(symbolName2);
            entry.namedImports.set(symbolName2, [reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly), propertyName]);
            break;
          case 3 /* CommonJS */:
            if (compilerOptions.verbatimModuleSyntax) {
              const prevValue2 = (entry.namedImports || (entry.namedImports = /* @__PURE__ */ new Map())).get(symbolName2);
              entry.namedImports.set(symbolName2, [reduceAddAsTypeOnlyValues(prevValue2, addAsTypeOnly), propertyName]);
            } else {
              Debug.assert(entry.namespaceLikeImport === void 0 || entry.namespaceLikeImport.name === symbolName2, "Namespacelike import shoudl be missing or match symbolName");
              entry.namespaceLikeImport = { importKind, name: symbolName2, addAsTypeOnly };
            }
            break;
          case 2 /* Namespace */:
            Debug.assert(entry.namespaceLikeImport === void 0 || entry.namespaceLikeImport.name === symbolName2, "Namespacelike import shoudl be missing or match symbolName");
            entry.namespaceLikeImport = { importKind, name: symbolName2, addAsTypeOnly };
            break;
        }
        break;
      }
      case 4 /* PromoteTypeOnly */:
        break;
      default:
        Debug.assertNever(fix, `fix wasn't never - got kind ${fix.kind}`);
    }
    function reduceAddAsTypeOnlyValues(prevValue, newValue) {
      return Math.max(prevValue ?? 0, newValue);
    }
    function getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly) {
      const typeOnlyKey = newImportsKey(
        moduleSpecifier,
        /*topLevelTypeOnly*/
        true
      );
      const nonTypeOnlyKey = newImportsKey(
        moduleSpecifier,
        /*topLevelTypeOnly*/
        false
      );
      const typeOnlyEntry = newImports.get(typeOnlyKey);
      const nonTypeOnlyEntry = newImports.get(nonTypeOnlyKey);
      const newEntry = {
        defaultImport: void 0,
        namedImports: void 0,
        namespaceLikeImport: void 0,
        useRequire
      };
      if (importKind === 1 /* Default */ && addAsTypeOnly === 2 /* Required */) {
        if (typeOnlyEntry) return typeOnlyEntry;
        newImports.set(typeOnlyKey, newEntry);
        return newEntry;
      }
      if (addAsTypeOnly === 1 /* Allowed */ && (typeOnlyEntry || nonTypeOnlyEntry)) {
        return typeOnlyEntry || nonTypeOnlyEntry;
      }
      if (nonTypeOnlyEntry) {
        return nonTypeOnlyEntry;
      }
      newImports.set(nonTypeOnlyKey, newEntry);
      return newEntry;
    }
    function newImportsKey(moduleSpecifier, topLevelTypeOnly) {
      return `${topLevelTypeOnly ? 1 : 0}|${moduleSpecifier}`;
    }
  }
  function writeFixes(changeTracker, oldFileQuotePreference) {
    var _a, _b;
    let quotePreference;
    if (sourceFile.imports !== void 0 && sourceFile.imports.length === 0 && oldFileQuotePreference !== void 0) {
      quotePreference = oldFileQuotePreference;
    } else {
      quotePreference = getQuotePreference(sourceFile, preferences);
    }
    for (const fix of addToNamespace) {
      addNamespaceQualifier(changeTracker, sourceFile, fix);
    }
    for (const fix of importType) {
      addImportType(changeTracker, sourceFile, fix, quotePreference);
    }
    let importSpecifiersToRemoveWhileAdding;
    if (removeExisting.size) {
      Debug.assert(isFullSourceFile(sourceFile), "Cannot remove imports from a future source file");
      const importDeclarationsWithRemovals = new Set(mapDefined([...removeExisting], (d) => findAncestor(d, isImportDeclaration)));
      const variableDeclarationsWithRemovals = new Set(mapDefined([...removeExisting], (d) => findAncestor(d, isVariableDeclarationInitializedToRequire)));
      const emptyImportDeclarations = [...importDeclarationsWithRemovals].filter(
        (d) => {
          var _a2, _b2, _c;
          return (
            // nothing added to the import declaration
            !addToExisting.has(d.importClause) && // no default, or default is being removed
            (!((_a2 = d.importClause) == null ? void 0 : _a2.name) || removeExisting.has(d.importClause)) && // no namespace import, or namespace import is being removed
            (!tryCast((_b2 = d.importClause) == null ? void 0 : _b2.namedBindings, isNamespaceImport) || removeExisting.has(d.importClause.namedBindings)) && // no named imports, or all named imports are being removed
            (!tryCast((_c = d.importClause) == null ? void 0 : _c.namedBindings, isNamedImports) || every(d.importClause.namedBindings.elements, (e) => removeExisting.has(e)))
          );
        }
      );
      const emptyVariableDeclarations = [...variableDeclarationsWithRemovals].filter(
        (d) => (
          // no binding elements being added to the variable declaration
          (d.name.kind !== 206 /* ObjectBindingPattern */ || !addToExisting.has(d.name)) && // no binding elements, or all binding elements are being removed
          (d.name.kind !== 206 /* ObjectBindingPattern */ || every(d.name.elements, (e) => removeExisting.has(e)))
        )
      );
      const namedBindingsToDelete = [...importDeclarationsWithRemovals].filter(
        (d) => {
          var _a2, _b2;
          return (
            // has named bindings
            ((_a2 = d.importClause) == null ? void 0 : _a2.namedBindings) && // is not being fully removed
            emptyImportDeclarations.indexOf(d) === -1 && // is not gaining named imports
            !((_b2 = addToExisting.get(d.importClause)) == null ? void 0 : _b2.namedImports) && // all named imports are being removed
            (d.importClause.namedBindings.kind === 274 /* NamespaceImport */ || every(d.importClause.namedBindings.elements, (e) => removeExisting.has(e)))
          );
        }
      );
      for (const declaration of [...emptyImportDeclarations, ...emptyVariableDeclarations]) {
        changeTracker.delete(sourceFile, declaration);
      }
      for (const declaration of namedBindingsToDelete) {
        changeTracker.replaceNode(
          sourceFile,
          declaration.importClause,
          factory.updateImportClause(
            declaration.importClause,
            declaration.importClause.isTypeOnly,
            declaration.importClause.name,
            /*namedBindings*/
            void 0
          )
        );
      }
      for (const declaration of removeExisting) {
        const importDeclaration = findAncestor(declaration, isImportDeclaration);
        if (importDeclaration && emptyImportDeclarations.indexOf(importDeclaration) === -1 && namedBindingsToDelete.indexOf(importDeclaration) === -1) {
          if (declaration.kind === 273 /* ImportClause */) {
            changeTracker.delete(sourceFile, declaration.name);
          } else {
            Debug.assert(declaration.kind === 276 /* ImportSpecifier */, "NamespaceImport should have been handled earlier");
            if ((_a = addToExisting.get(importDeclaration.importClause)) == null ? void 0 : _a.namedImports) {
              (importSpecifiersToRemoveWhileAdding ?? (importSpecifiersToRemoveWhileAdding = /* @__PURE__ */ new Set())).add(declaration);
            } else {
              changeTracker.delete(sourceFile, declaration);
            }
          }
        } else if (declaration.kind === 208 /* BindingElement */) {
          if ((_b = addToExisting.get(declaration.parent)) == null ? void 0 : _b.namedImports) {
            (importSpecifiersToRemoveWhileAdding ?? (importSpecifiersToRemoveWhileAdding = /* @__PURE__ */ new Set())).add(declaration);
          } else {
            changeTracker.delete(sourceFile, declaration);
          }
        } else if (declaration.kind === 271 /* ImportEqualsDeclaration */) {
          changeTracker.delete(sourceFile, declaration);
        }
      }
    }
    addToExisting.forEach(({ importClauseOrBindingPattern, defaultImport, namedImports }) => {
      doAddExistingFix(
        changeTracker,
        sourceFile,
        importClauseOrBindingPattern,
        defaultImport,
        arrayFrom(namedImports.entries(), ([name, { addAsTypeOnly, propertyName }]) => ({ addAsTypeOnly, propertyName, name })),
        importSpecifiersToRemoveWhileAdding,
        preferences
      );
    });
    let newDeclarations;
    newImports.forEach(({ useRequire, defaultImport, namedImports, namespaceLikeImport }, key) => {
      const moduleSpecifier = key.slice(2);
      const getDeclarations = useRequire ? getNewRequires : getNewImports;
      const declarations = getDeclarations(
        moduleSpecifier,
        quotePreference,
        defaultImport,
        namedImports && arrayFrom(namedImports.entries(), ([name, [addAsTypeOnly, propertyName]]) => ({ addAsTypeOnly, propertyName, name })),
        namespaceLikeImport,
        compilerOptions,
        preferences
      );
      newDeclarations = combine(newDeclarations, declarations);
    });
    newDeclarations = combine(newDeclarations, getCombinedVerbatimImports());
    if (newDeclarations) {
      insertImports(
        changeTracker,
        sourceFile,
        newDeclarations,
        /*blankLineBetween*/
        true,
        preferences
      );
    }
  }
  function getCombinedVerbatimImports() {
    if (!verbatimImports.size) return void 0;
    const importDeclarations = new Set(mapDefined([...verbatimImports], (d) => findAncestor(d, isImportDeclaration)));
    const requireStatements = new Set(mapDefined([...verbatimImports], (d) => findAncestor(d, isRequireVariableStatement)));
    return [
      ...mapDefined([...verbatimImports], (d) => d.kind === 271 /* ImportEqualsDeclaration */ ? getSynthesizedDeepClone(
        d,
        /*includeTrivia*/
        true
      ) : void 0),
      ...[...importDeclarations].map((d) => {
        var _a;
        if (verbatimImports.has(d)) {
          return getSynthesizedDeepClone(
            d,
            /*includeTrivia*/
            true
          );
        }
        return getSynthesizedDeepClone(
          factory.updateImportDeclaration(
            d,
            d.modifiers,
            d.importClause && factory.updateImportClause(
              d.importClause,
              d.importClause.isTypeOnly,
              verbatimImports.has(d.importClause) ? d.importClause.name : void 0,
              verbatimImports.has(d.importClause.namedBindings) ? d.importClause.namedBindings : ((_a = tryCast(d.importClause.namedBindings, isNamedImports)) == null ? void 0 : _a.elements.some((e) => verbatimImports.has(e))) ? factory.updateNamedImports(
                d.importClause.namedBindings,
                d.importClause.namedBindings.elements.filter((e) => verbatimImports.has(e))
              ) : void 0
            ),
            d.moduleSpecifier,
            d.attributes
          ),
          /*includeTrivia*/
          true
        );
      }),
      ...[...requireStatements].map((s) => {
        if (verbatimImports.has(s)) {
          return getSynthesizedDeepClone(
            s,
            /*includeTrivia*/
            true
          );
        }
        return getSynthesizedDeepClone(
          factory.updateVariableStatement(
            s,
            s.modifiers,
            factory.updateVariableDeclarationList(
              s.declarationList,
              mapDefined(s.declarationList.declarations, (d) => {
                if (verbatimImports.has(d)) {
                  return d;
                }
                return factory.updateVariableDeclaration(
                  d,
                  d.name.kind === 206 /* ObjectBindingPattern */ ? factory.updateObjectBindingPattern(
                    d.name,
                    d.name.elements.filter((e) => verbatimImports.has(e))
                  ) : d.name,
                  d.exclamationToken,
                  d.type,
                  d.initializer
                );
              })
            )
          ),
          /*includeTrivia*/
          true
        );
      })
    ];
  }
  function hasFixes() {
    return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0 || verbatimImports.size > 0 || removeExisting.size > 0;
  }
}
function createImportSpecifierResolver(importingFile, program, host, preferences) {
  const packageJsonImportFilter = createPackageJsonImportFilter(importingFile, preferences, host);
  const importMap = createExistingImportMap(importingFile, program);
  return { getModuleSpecifierForBestExportInfo };
  function getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite, fromCacheOnly) {
    const { fixes, computedWithoutCacheCount } = getImportFixes(
      exportInfo,
      position,
      isValidTypeOnlyUseSite,
      /*useRequire*/
      false,
      program,
      importingFile,
      host,
      preferences,
      importMap,
      fromCacheOnly
    );
    const result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host, preferences);
    return result && { ...result, computedWithoutCacheCount };
  }
}
function getImportCompletionAction(targetSymbol, moduleSymbol, exportMapKey, sourceFile, symbolName2, isJsxTagName, host, program, formatContext, position, preferences, cancellationToken) {
  let exportInfos;
  if (exportMapKey) {
    exportInfos = getExportInfoMap(sourceFile, host, program, preferences, cancellationToken).get(sourceFile.path, exportMapKey);
    Debug.assertIsDefined(exportInfos, "Some exportInfo should match the specified exportMapKey");
  } else {
    exportInfos = pathIsBareSpecifier(stripQuotes(moduleSymbol.name)) ? [getSingleExportInfoForSymbol(targetSymbol, symbolName2, moduleSymbol, program, host)] : getAllExportInfoForSymbol(sourceFile, targetSymbol, symbolName2, moduleSymbol, isJsxTagName, program, host, preferences, cancellationToken);
    Debug.assertIsDefined(exportInfos, "Some exportInfo should match the specified symbol / moduleSymbol");
  }
  const useRequire = shouldUseRequire(sourceFile, program);
  const isValidTypeOnlyUseSite = isValidTypeOnlyAliasUseSite(getTokenAtPosition(sourceFile, position));
  const fix = Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences));
  return {
    moduleSpecifier: fix.moduleSpecifier,
    codeAction: codeFixActionToCodeAction(codeActionForFix(
      { host, formatContext, preferences },
      sourceFile,
      symbolName2,
      fix,
      /*includeSymbolNameInDescription*/
      false,
      program,
      preferences
    ))
  };
}
function getPromoteTypeOnlyCompletionAction(sourceFile, symbolToken, program, host, formatContext, preferences) {
  const compilerOptions = program.getCompilerOptions();
  const symbolName2 = single(getSymbolNamesToImport(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions));
  const fix = getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program);
  const includeSymbolNameInDescription = symbolName2 !== symbolToken.text;
  return fix && codeFixActionToCodeAction(codeActionForFix(
    { host, formatContext, preferences },
    sourceFile,
    symbolName2,
    fix,
    includeSymbolNameInDescription,
    program,
    preferences
  ));
}
function getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences) {
  const packageJsonImportFilter = createPackageJsonImportFilter(sourceFile, preferences, host);
  return getBestFix(getImportFixes(exportInfos, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes, sourceFile, program, packageJsonImportFilter, host, preferences);
}
function codeFixActionToCodeAction({ description: description3, changes, commands }) {
  return { description: description3, changes, commands };
}
function getAllExportInfoForSymbol(importingFile, symbol, symbolName2, moduleSymbol, preferCapitalized, program, host, preferences, cancellationToken) {
  const getChecker = createGetChecker(program, host);
  const isFileExcluded = preferences.autoImportFileExcludePatterns && getIsFileExcluded(host, preferences);
  const mergedModuleSymbol = program.getTypeChecker().getMergedSymbol(moduleSymbol);
  const moduleSourceFile = isFileExcluded && mergedModuleSymbol.declarations && getDeclarationOfKind(mergedModuleSymbol, 307 /* SourceFile */);
  const moduleSymbolExcluded = moduleSourceFile && isFileExcluded(moduleSourceFile);
  return getExportInfoMap(importingFile, host, program, preferences, cancellationToken).search(importingFile.path, preferCapitalized, (name) => name === symbolName2, (info) => {
    const checker = getChecker(info[0].isFromPackageJson);
    if (checker.getMergedSymbol(skipAlias(info[0].symbol, checker)) === symbol && (moduleSymbolExcluded || info.some((i) => checker.getMergedSymbol(i.moduleSymbol) === moduleSymbol || i.symbol.parent === moduleSymbol))) {
      return info;
    }
  });
}
function getSingleExportInfoForSymbol(symbol, symbolName2, moduleSymbol, program, host) {
  var _a, _b;
  const mainProgramInfo = getInfoWithChecker(
    program.getTypeChecker(),
    /*isFromPackageJson*/
    false
  );
  if (mainProgramInfo) {
    return mainProgramInfo;
  }
  const autoImportProvider = (_b = (_a = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getTypeChecker();
  return Debug.checkDefined(autoImportProvider && getInfoWithChecker(
    autoImportProvider,
    /*isFromPackageJson*/
    true
  ), `Could not find symbol in specified module for code actions`);
  function getInfoWithChecker(checker, isFromPackageJson) {
    const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker);
    if (defaultInfo && skipAlias(defaultInfo.symbol, checker) === symbol) {
      return { symbol: defaultInfo.symbol, moduleSymbol, moduleFileName: void 0, exportKind: defaultInfo.exportKind, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson };
    }
    const named = checker.tryGetMemberInModuleExportsAndProperties(symbolName2, moduleSymbol);
    if (named && skipAlias(named, checker) === symbol) {
      return { symbol: named, moduleSymbol, moduleFileName: void 0, exportKind: 0 /* Named */, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson };
    }
  }
}
function getImportFixes(exportInfos, usagePosition, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap = isFullSourceFile(sourceFile) ? createExistingImportMap(sourceFile, program) : void 0, fromCacheOnly) {
  const checker = program.getTypeChecker();
  const existingImports = importMap ? flatMap(exportInfos, importMap.getImportsForExportInfo) : emptyArray;
  const useNamespace = usagePosition !== void 0 && tryUseExistingNamespaceImport(existingImports, usagePosition);
  const addToExisting = tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, program.getCompilerOptions());
  if (addToExisting) {
    return {
      computedWithoutCacheCount: 0,
      fixes: [...useNamespace ? [useNamespace] : emptyArray, addToExisting]
    };
  }
  const { fixes, computedWithoutCacheCount = 0 } = getFixesForAddImport(
    exportInfos,
    existingImports,
    program,
    sourceFile,
    usagePosition,
    isValidTypeOnlyUseSite,
    useRequire,
    host,
    preferences,
    fromCacheOnly
  );
  return {
    computedWithoutCacheCount,
    fixes: [...useNamespace ? [useNamespace] : emptyArray, ...fixes]
  };
}
function tryUseExistingNamespaceImport(existingImports, position) {
  return firstDefined(existingImports, ({ declaration, importKind }) => {
    var _a;
    if (importKind !== 0 /* Named */) return void 0;
    const namespacePrefix = getNamespaceLikeImportText(declaration);
    const moduleSpecifier = namespacePrefix && ((_a = tryGetModuleSpecifierFromDeclaration(declaration)) == null ? void 0 : _a.text);
    if (moduleSpecifier) {
      return { kind: 0 /* UseNamespace */, namespacePrefix, usagePosition: position, moduleSpecifierKind: void 0, moduleSpecifier };
    }
  });
}
function getNamespaceLikeImportText(declaration) {
  var _a, _b, _c;
  switch (declaration.kind) {
    case 260 /* VariableDeclaration */:
      return (_a = tryCast(declaration.name, isIdentifier)) == null ? void 0 : _a.text;
    case 271 /* ImportEqualsDeclaration */:
      return declaration.name.text;
    case 351 /* JSDocImportTag */:
    case 272 /* ImportDeclaration */:
      return (_c = tryCast((_b = declaration.importClause) == null ? void 0 : _b.namedBindings, isNamespaceImport)) == null ? void 0 : _c.name.text;
    default:
      return Debug.assertNever(declaration);
  }
}
function getAddAsTypeOnly(isValidTypeOnlyUseSite, isForNewImportDeclaration, symbol, targetFlags, checker, compilerOptions) {
  if (!isValidTypeOnlyUseSite) {
    return 4 /* NotAllowed */;
  }
  if (symbol && compilerOptions.verbatimModuleSyntax && (!(targetFlags & 111551 /* Value */) || !!checker.getTypeOnlyAliasDeclaration(symbol))) {
    return 2 /* Required */;
  }
  return 1 /* Allowed */;
}
function tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, compilerOptions) {
  let best;
  for (const existingImport of existingImports) {
    const fix = getAddToExistingImportFix(existingImport);
    if (!fix) continue;
    const isTypeOnly = isTypeOnlyImportDeclaration(fix.importClauseOrBindingPattern);
    if (fix.addAsTypeOnly !== 4 /* NotAllowed */ && isTypeOnly || fix.addAsTypeOnly === 4 /* NotAllowed */ && !isTypeOnly) {
      return fix;
    }
    best ?? (best = fix);
  }
  return best;
  function getAddToExistingImportFix({ declaration, importKind, symbol, targetFlags }) {
    if (importKind === 3 /* CommonJS */ || importKind === 2 /* Namespace */ || declaration.kind === 271 /* ImportEqualsDeclaration */) {
      return void 0;
    }
    if (declaration.kind === 260 /* VariableDeclaration */) {
      return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 206 /* ObjectBindingPattern */ ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind, moduleSpecifierKind: void 0, moduleSpecifier: declaration.initializer.arguments[0].text, addAsTypeOnly: 4 /* NotAllowed */ } : void 0;
    }
    const { importClause } = declaration;
    if (!importClause || !isStringLiteralLike(declaration.moduleSpecifier)) {
      return void 0;
    }
    const { name, namedBindings } = importClause;
    if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) {
      return void 0;
    }
    const addAsTypeOnly = getAddAsTypeOnly(
      isValidTypeOnlyUseSite,
      /*isForNewImportDeclaration*/
      false,
      symbol,
      targetFlags,
      checker,
      compilerOptions
    );
    if (importKind === 1 /* Default */ && (name || // Cannot add a default import to a declaration that already has one
    addAsTypeOnly === 2 /* Required */ && namedBindings)) {
      return void 0;
    }
    if (importKind === 0 /* Named */ && (namedBindings == null ? void 0 : namedBindings.kind) === 274 /* NamespaceImport */) {
      return void 0;
    }
    return {
      kind: 2 /* AddToExisting */,
      importClauseOrBindingPattern: importClause,
      importKind,
      moduleSpecifierKind: void 0,
      moduleSpecifier: declaration.moduleSpecifier.text,
      addAsTypeOnly
    };
  }
}
function createExistingImportMap(importingFile, program) {
  const checker = program.getTypeChecker();
  let importMap;
  for (const moduleSpecifier of importingFile.imports) {
    const i = importFromModuleSpecifier(moduleSpecifier);
    if (isVariableDeclarationInitializedToRequire(i.parent)) {
      const moduleSymbol = checker.resolveExternalModuleName(moduleSpecifier);
      if (moduleSymbol) {
        (importMap || (importMap = createMultiMap())).add(getSymbolId(moduleSymbol), i.parent);
      }
    } else if (i.kind === 272 /* ImportDeclaration */ || i.kind === 271 /* ImportEqualsDeclaration */ || i.kind === 351 /* JSDocImportTag */) {
      const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
      if (moduleSymbol) {
        (importMap || (importMap = createMultiMap())).add(getSymbolId(moduleSymbol), i);
      }
    }
  }
  return {
    getImportsForExportInfo: ({ moduleSymbol, exportKind, targetFlags, symbol }) => {
      const matchingDeclarations = importMap == null ? void 0 : importMap.get(getSymbolId(moduleSymbol));
      if (!matchingDeclarations) return emptyArray;
      if (isSourceFileJS(importingFile) && !(targetFlags & 111551 /* Value */) && !every(matchingDeclarations, isJSDocImportTag)) return emptyArray;
      const importKind = getImportKind(importingFile, exportKind, program);
      return matchingDeclarations.map((declaration) => ({ declaration, importKind, symbol, targetFlags }));
    }
  };
}
function shouldUseRequire(sourceFile, program) {
  if (!hasJSFileExtension(sourceFile.fileName)) {
    return false;
  }
  if (sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator) return true;
  if (sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) return false;
  const compilerOptions = program.getCompilerOptions();
  if (compilerOptions.configFile) {
    return getEmitModuleKind(compilerOptions) < 5 /* ES2015 */;
  }
  if (getImpliedNodeFormatForEmit(sourceFile, program) === 1 /* CommonJS */) return true;
  if (getImpliedNodeFormatForEmit(sourceFile, program) === 99 /* ESNext */) return false;
  for (const otherFile of program.getSourceFiles()) {
    if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue;
    if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator) return true;
    if (otherFile.externalModuleIndicator && !otherFile.commonJsModuleIndicator) return false;
  }
  return true;
}
function createGetChecker(program, host) {
  return memoizeOne((isFromPackageJson) => isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker());
}
function getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfo, host, preferences, fromCacheOnly) {
  const isJs = hasJSFileExtension(sourceFile.fileName);
  const compilerOptions = program.getCompilerOptions();
  const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host);
  const getChecker = createGetChecker(program, host);
  const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
  const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(moduleResolution);
  const getModuleSpecifiers2 = fromCacheOnly ? (exportInfo2) => ts_moduleSpecifiers_exports.tryGetModuleSpecifiersFromCache(exportInfo2.moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences) : (exportInfo2, checker) => ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo(
    exportInfo2.moduleSymbol,
    checker,
    compilerOptions,
    sourceFile,
    moduleSpecifierResolutionHost,
    preferences,
    /*options*/
    void 0,
    /*forAutoImport*/
    true
  );
  let computedWithoutCacheCount = 0;
  const fixes = flatMap(exportInfo, (exportInfo2, i) => {
    const checker = getChecker(exportInfo2.isFromPackageJson);
    const { computedWithoutCache, moduleSpecifiers, kind: moduleSpecifierKind } = getModuleSpecifiers2(exportInfo2, checker) ?? {};
    const importedSymbolHasValueMeaning = !!(exportInfo2.targetFlags & 111551 /* Value */);
    const addAsTypeOnly = getAddAsTypeOnly(
      isValidTypeOnlyUseSite,
      /*isForNewImportDeclaration*/
      true,
      exportInfo2.symbol,
      exportInfo2.targetFlags,
      checker,
      compilerOptions
    );
    computedWithoutCacheCount += computedWithoutCache ? 1 : 0;
    return mapDefined(moduleSpecifiers, (moduleSpecifier) => {
      if (rejectNodeModulesRelativePaths && pathContainsNodeModules(moduleSpecifier)) {
        return void 0;
      }
      if (!importedSymbolHasValueMeaning && isJs && usagePosition !== void 0) {
        return { kind: 1 /* JsdocTypeImport */, moduleSpecifierKind, moduleSpecifier, usagePosition, exportInfo: exportInfo2, isReExport: i > 0 };
      }
      const importKind = getImportKind(sourceFile, exportInfo2.exportKind, program);
      let qualification;
      if (usagePosition !== void 0 && importKind === 3 /* CommonJS */ && exportInfo2.exportKind === 0 /* Named */) {
        const exportEquals = checker.resolveExternalModuleSymbol(exportInfo2.moduleSymbol);
        let namespacePrefix;
        if (exportEquals !== exportInfo2.moduleSymbol) {
          namespacePrefix = forEachNameOfDefaultExport(exportEquals, checker, getEmitScriptTarget(compilerOptions), identity);
        }
        namespacePrefix || (namespacePrefix = moduleSymbolToValidIdentifier(
          exportInfo2.moduleSymbol,
          getEmitScriptTarget(compilerOptions),
          /*forceCapitalize*/
          false
        ));
        qualification = { namespacePrefix, usagePosition };
      }
      return {
        kind: 3 /* AddNew */,
        moduleSpecifierKind,
        moduleSpecifier,
        importKind,
        useRequire,
        addAsTypeOnly,
        exportInfo: exportInfo2,
        isReExport: i > 0,
        qualification
      };
    });
  });
  return { computedWithoutCacheCount, fixes };
}
function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, host, preferences, fromCacheOnly) {
  const existingDeclaration = firstDefined(existingImports, (info) => newImportInfoFromExistingSpecifier(info, isValidTypeOnlyUseSite, useRequire, program.getTypeChecker(), program.getCompilerOptions()));
  return existingDeclaration ? { fixes: [existingDeclaration] } : getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfos, host, preferences, fromCacheOnly);
}
function newImportInfoFromExistingSpecifier({ declaration, importKind, symbol, targetFlags }, isValidTypeOnlyUseSite, useRequire, checker, compilerOptions) {
  var _a;
  const moduleSpecifier = (_a = tryGetModuleSpecifierFromDeclaration(declaration)) == null ? void 0 : _a.text;
  if (moduleSpecifier) {
    const addAsTypeOnly = useRequire ? 4 /* NotAllowed */ : getAddAsTypeOnly(
      isValidTypeOnlyUseSite,
      /*isForNewImportDeclaration*/
      true,
      symbol,
      targetFlags,
      checker,
      compilerOptions
    );
    return { kind: 3 /* AddNew */, moduleSpecifierKind: void 0, moduleSpecifier, importKind, addAsTypeOnly, useRequire };
  }
}
function getFixInfos(context, errorCode, pos, useAutoImportProvider) {
  const symbolToken = getTokenAtPosition(context.sourceFile, pos);
  let info;
  if (errorCode === Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) {
    info = getFixesInfoForUMDImport(context, symbolToken);
  } else if (!isIdentifier(symbolToken)) {
    return void 0;
  } else if (errorCode === Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code) {
    const symbolName2 = single(getSymbolNamesToImport(context.sourceFile, context.program.getTypeChecker(), symbolToken, context.program.getCompilerOptions()));
    const fix = getTypeOnlyPromotionFix(context.sourceFile, symbolToken, symbolName2, context.program);
    return fix && [{ fix, symbolName: symbolName2, errorIdentifierText: symbolToken.text }];
  } else {
    info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider);
  }
  const packageJsonImportFilter = createPackageJsonImportFilter(context.sourceFile, context.preferences, context.host);
  return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host, context.preferences);
}
function sortFixInfo(fixes, sourceFile, program, packageJsonImportFilter, host, preferences) {
  const _toPath = (fileName) => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host));
  return toSorted(fixes, (a, b) => compareBooleans(!!a.isJsxNamespaceFix, !!b.isJsxNamespaceFix) || compareValues(a.fix.kind, b.fix.kind) || compareModuleSpecifiers(a.fix, b.fix, sourceFile, program, preferences, packageJsonImportFilter.allowsImportingSpecifier, _toPath));
}
function getFixInfosWithoutDiagnostic(context, symbolToken, useAutoImportProvider) {
  const info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider);
  const packageJsonImportFilter = createPackageJsonImportFilter(context.sourceFile, context.preferences, context.host);
  return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host, context.preferences);
}
function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host, preferences) {
  if (!some(fixes)) return;
  if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) {
    return fixes[0];
  }
  return fixes.reduce(
    (best, fix) => (
      // Takes true branch of conditional if `fix` is better than `best`
      compareModuleSpecifiers(
        fix,
        best,
        sourceFile,
        program,
        preferences,
        packageJsonImportFilter.allowsImportingSpecifier,
        (fileName) => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host))
      ) === -1 /* LessThan */ ? fix : best
    )
  );
}
function compareModuleSpecifiers(a, b, importingFile, program, preferences, allowsImportingSpecifier, toPath3) {
  if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) {
    return compareBooleans(
      b.moduleSpecifierKind !== "node_modules" || allowsImportingSpecifier(b.moduleSpecifier),
      a.moduleSpecifierKind !== "node_modules" || allowsImportingSpecifier(a.moduleSpecifier)
    ) || compareModuleSpecifierRelativity(a, b, preferences) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || compareBooleans(
      isFixPossiblyReExportingImportingFile(a, importingFile.path, toPath3),
      isFixPossiblyReExportingImportingFile(b, importingFile.path, toPath3)
    ) || compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier);
  }
  return 0 /* EqualTo */;
}
function compareModuleSpecifierRelativity(a, b, preferences) {
  if (preferences.importModuleSpecifierPreference === "non-relative" || preferences.importModuleSpecifierPreference === "project-relative") {
    return compareBooleans(a.moduleSpecifierKind === "relative", b.moduleSpecifierKind === "relative");
  }
  return 0 /* EqualTo */;
}
function isFixPossiblyReExportingImportingFile(fix, importingFilePath, toPath3) {
  var _a;
  if (fix.isReExport && ((_a = fix.exportInfo) == null ? void 0 : _a.moduleFileName) && isIndexFileName(fix.exportInfo.moduleFileName)) {
    const reExportDir = toPath3(getDirectoryPath(fix.exportInfo.moduleFileName));
    return startsWith(importingFilePath, reExportDir);
  }
  return false;
}
function isIndexFileName(fileName) {
  return getBaseFileName(
    fileName,
    [".js", ".jsx", ".d.ts", ".ts", ".tsx"],
    /*ignoreCase*/
    true
  ) === "index";
}
function compareNodeCoreModuleSpecifiers(a, b, importingFile, program) {
  if (startsWith(a, "node:") && !startsWith(b, "node:")) return shouldUseUriStyleNodeCoreModules(importingFile, program) ? -1 /* LessThan */ : 1 /* GreaterThan */;
  if (startsWith(b, "node:") && !startsWith(a, "node:")) return shouldUseUriStyleNodeCoreModules(importingFile, program) ? 1 /* GreaterThan */ : -1 /* LessThan */;
  return 0 /* EqualTo */;
}
function getFixesInfoForUMDImport({ sourceFile, program, host, preferences }, token) {
  const checker = program.getTypeChecker();
  const umdSymbol = getUmdSymbol(token, checker);
  if (!umdSymbol) return void 0;
  const symbol = checker.getAliasedSymbol(umdSymbol);
  const symbolName2 = umdSymbol.name;
  const exportInfo = [{ symbol: umdSymbol, moduleSymbol: symbol, moduleFileName: void 0, exportKind: 3 /* UMD */, targetFlags: symbol.flags, isFromPackageJson: false }];
  const useRequire = shouldUseRequire(sourceFile, program);
  const fixes = getImportFixes(
    exportInfo,
    /*usagePosition*/
    void 0,
    /*isValidTypeOnlyUseSite*/
    false,
    useRequire,
    program,
    sourceFile,
    host,
    preferences
  ).fixes;
  return fixes.map((fix) => {
    var _a;
    return { fix, symbolName: symbolName2, errorIdentifierText: (_a = tryCast(token, isIdentifier)) == null ? void 0 : _a.text };
  });
}
function getUmdSymbol(token, checker) {
  const umdSymbol = isIdentifier(token) ? checker.getSymbolAtLocation(token) : void 0;
  if (isUMDExportSymbol(umdSymbol)) return umdSymbol;
  const { parent: parent2 } = token;
  if (isJsxOpeningLikeElement(parent2) && parent2.tagName === token || isJsxOpeningFragment(parent2)) {
    const parentSymbol = checker.resolveName(
      checker.getJsxNamespace(parent2),
      isJsxOpeningLikeElement(parent2) ? token : parent2,
      111551 /* Value */,
      /*excludeGlobals*/
      false
    );
    if (isUMDExportSymbol(parentSymbol)) {
      return parentSymbol;
    }
  }
  return void 0;
}
function getImportKind(importingFile, exportKind, program, forceImportKeyword) {
  if (program.getCompilerOptions().verbatimModuleSyntax && getEmitModuleFormatOfFile(importingFile, program) === 1 /* CommonJS */) {
    return 3 /* CommonJS */;
  }
  switch (exportKind) {
    case 0 /* Named */:
      return 0 /* Named */;
    case 1 /* Default */:
      return 1 /* Default */;
    case 2 /* ExportEquals */:
      return getExportEqualsImportKind(importingFile, program.getCompilerOptions(), !!forceImportKeyword);
    case 3 /* UMD */:
      return getUmdImportKind(importingFile, program, !!forceImportKeyword);
    case 4 /* Module */:
      return 2 /* Namespace */;
    default:
      return Debug.assertNever(exportKind);
  }
}
function getUmdImportKind(importingFile, program, forceImportKeyword) {
  if (getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
    return 1 /* Default */;
  }
  const moduleKind = getEmitModuleKind(program.getCompilerOptions());
  switch (moduleKind) {
    case 2 /* AMD */:
    case 1 /* CommonJS */:
    case 3 /* UMD */:
      if (hasJSFileExtension(importingFile.fileName)) {
        return importingFile.externalModuleIndicator || forceImportKeyword ? 2 /* Namespace */ : 3 /* CommonJS */;
      }
      return 3 /* CommonJS */;
    case 4 /* System */:
    case 5 /* ES2015 */:
    case 6 /* ES2020 */:
    case 7 /* ES2022 */:
    case 99 /* ESNext */:
    case 0 /* None */:
    case 200 /* Preserve */:
      return 2 /* Namespace */;
    case 100 /* Node16 */:
    case 199 /* NodeNext */:
      return getImpliedNodeFormatForEmit(importingFile, program) === 99 /* ESNext */ ? 2 /* Namespace */ : 3 /* CommonJS */;
    default:
      return Debug.assertNever(moduleKind, `Unexpected moduleKind ${moduleKind}`);
  }
}
function getFixesInfoForNonUMDImport({ sourceFile, program, cancellationToken, host, preferences }, symbolToken, useAutoImportProvider) {
  const checker = program.getTypeChecker();
  const compilerOptions = program.getCompilerOptions();
  return flatMap(getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions), (symbolName2) => {
    if (symbolName2 === "default" /* Default */) {
      return void 0;
    }
    const isValidTypeOnlyUseSite = isValidTypeOnlyAliasUseSite(symbolToken);
    const useRequire = shouldUseRequire(sourceFile, program);
    const exportInfo = getExportInfos(symbolName2, isJSXTagName(symbolToken), getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences);
    return arrayFrom(
      flatMapIterator(exportInfo.values(), (exportInfos) => getImportFixes(exportInfos, symbolToken.getStart(sourceFile), isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes),
      (fix) => ({ fix, symbolName: symbolName2, errorIdentifierText: symbolToken.text, isJsxNamespaceFix: symbolName2 !== symbolToken.text })
    );
  });
}
function getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program) {
  const checker = program.getTypeChecker();
  const symbol = checker.resolveName(
    symbolName2,
    symbolToken,
    111551 /* Value */,
    /*excludeGlobals*/
    true
  );
  if (!symbol) return void 0;
  const typeOnlyAliasDeclaration = checker.getTypeOnlyAliasDeclaration(symbol);
  if (!typeOnlyAliasDeclaration || getSourceFileOfNode(typeOnlyAliasDeclaration) !== sourceFile) return void 0;
  return { kind: 4 /* PromoteTypeOnly */, typeOnlyAliasDeclaration };
}
function getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions) {
  const parent2 = symbolToken.parent;
  if ((isJsxOpeningLikeElement(parent2) || isJsxClosingElement(parent2)) && parent2.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) {
    const jsxNamespace = checker.getJsxNamespace(sourceFile);
    if (needsJsxNamespaceFix(jsxNamespace, symbolToken, checker)) {
      const needsComponentNameFix = !isIntrinsicJsxName(symbolToken.text) && !checker.resolveName(
        symbolToken.text,
        symbolToken,
        111551 /* Value */,
        /*excludeGlobals*/
        false
      );
      return needsComponentNameFix ? [symbolToken.text, jsxNamespace] : [jsxNamespace];
    }
  }
  return [symbolToken.text];
}
function needsJsxNamespaceFix(jsxNamespace, symbolToken, checker) {
  if (isIntrinsicJsxName(symbolToken.text)) return true;
  const namespaceSymbol = checker.resolveName(
    jsxNamespace,
    symbolToken,
    111551 /* Value */,
    /*excludeGlobals*/
    true
  );
  return !namespaceSymbol || some(namespaceSymbol.declarations, isTypeOnlyImportOrExportDeclaration) && !(namespaceSymbol.flags & 111551 /* Value */);
}
function getExportInfos(symbolName2, isJsxTagName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host, preferences) {
  var _a;
  const originalSymbolToExportInfos = createMultiMap();
  const packageJsonFilter = createPackageJsonImportFilter(fromFile, preferences, host);
  const moduleSpecifierCache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host);
  const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson) => {
    return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host);
  });
  function addSymbol(moduleSymbol, toFile, exportedSymbol, exportKind, program2, isFromPackageJson) {
    const moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson);
    if (isImportable(program2, fromFile, toFile, moduleSymbol, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache)) {
      const checker = program2.getTypeChecker();
      originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol, moduleFileName: toFile == null ? void 0 : toFile.fileName, exportKind, targetFlags: skipAlias(exportedSymbol, checker).flags, isFromPackageJson });
    }
  }
  forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, (moduleSymbol, sourceFile, program2, isFromPackageJson) => {
    const checker = program2.getTypeChecker();
    cancellationToken.throwIfCancellationRequested();
    const compilerOptions = program2.getCompilerOptions();
    const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker);
    if (defaultInfo && symbolFlagsHaveMeaning(checker.getSymbolFlags(defaultInfo.symbol), currentTokenMeaning) && forEachNameOfDefaultExport(defaultInfo.symbol, checker, getEmitScriptTarget(compilerOptions), (name, capitalizedName) => (isJsxTagName ? capitalizedName ?? name : name) === symbolName2)) {
      addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program2, isFromPackageJson);
    }
    const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName2, moduleSymbol);
    if (exportSymbolWithIdenticalName && symbolFlagsHaveMeaning(checker.getSymbolFlags(exportSymbolWithIdenticalName), currentTokenMeaning)) {
      addSymbol(moduleSymbol, sourceFile, exportSymbolWithIdenticalName, 0 /* Named */, program2, isFromPackageJson);
    }
  });
  return originalSymbolToExportInfos;
}
function getExportEqualsImportKind(importingFile, compilerOptions, forceImportKeyword) {
  const allowSyntheticDefaults = getAllowSyntheticDefaultImports(compilerOptions);
  const isJS = hasJSFileExtension(importingFile.fileName);
  if (!isJS && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */) {
    return allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */;
  }
  if (isJS) {
    return importingFile.externalModuleIndicator || forceImportKeyword ? allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */ : 3 /* CommonJS */;
  }
  for (const statement of importingFile.statements ?? emptyArray) {
    if (isImportEqualsDeclaration(statement) && !nodeIsMissing(statement.moduleReference)) {
      return 3 /* CommonJS */;
    }
  }
  return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */;
}
function codeActionForFix(context, sourceFile, symbolName2, fix, includeSymbolNameInDescription, program, preferences) {
  let diag2;
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => {
    diag2 = codeActionForFixWorker(tracker, sourceFile, symbolName2, fix, includeSymbolNameInDescription, program, preferences);
  });
  return createCodeFixAction(importFixName, changes, diag2, importFixId, Diagnostics.Add_all_missing_imports);
}
function codeActionForFixWorker(changes, sourceFile, symbolName2, fix, includeSymbolNameInDescription, program, preferences) {
  const quotePreference = getQuotePreference(sourceFile, preferences);
  switch (fix.kind) {
    case 0 /* UseNamespace */:
      addNamespaceQualifier(changes, sourceFile, fix);
      return [Diagnostics.Change_0_to_1, symbolName2, `${fix.namespacePrefix}.${symbolName2}`];
    case 1 /* JsdocTypeImport */:
      addImportType(changes, sourceFile, fix, quotePreference);
      return [Diagnostics.Change_0_to_1, symbolName2, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName2];
    case 2 /* AddToExisting */: {
      const { importClauseOrBindingPattern, importKind, addAsTypeOnly, moduleSpecifier } = fix;
      doAddExistingFix(
        changes,
        sourceFile,
        importClauseOrBindingPattern,
        importKind === 1 /* Default */ ? { name: symbolName2, addAsTypeOnly } : void 0,
        importKind === 0 /* Named */ ? [{ name: symbolName2, addAsTypeOnly }] : emptyArray,
        /*removeExistingImportSpecifiers*/
        void 0,
        preferences
      );
      const moduleSpecifierWithoutQuotes = stripQuotes(moduleSpecifier);
      return includeSymbolNameInDescription ? [Diagnostics.Import_0_from_1, symbolName2, moduleSpecifierWithoutQuotes] : [Diagnostics.Update_import_from_0, moduleSpecifierWithoutQuotes];
    }
    case 3 /* AddNew */: {
      const { importKind, moduleSpecifier, addAsTypeOnly, useRequire, qualification } = fix;
      const getDeclarations = useRequire ? getNewRequires : getNewImports;
      const defaultImport = importKind === 1 /* Default */ ? { name: symbolName2, addAsTypeOnly } : void 0;
      const namedImports = importKind === 0 /* Named */ ? [{ name: symbolName2, addAsTypeOnly }] : void 0;
      const namespaceLikeImport = importKind === 2 /* Namespace */ || importKind === 3 /* CommonJS */ ? { importKind, name: (qualification == null ? void 0 : qualification.namespacePrefix) || symbolName2, addAsTypeOnly } : void 0;
      insertImports(
        changes,
        sourceFile,
        getDeclarations(
          moduleSpecifier,
          quotePreference,
          defaultImport,
          namedImports,
          namespaceLikeImport,
          program.getCompilerOptions(),
          preferences
        ),
        /*blankLineBetween*/
        true,
        preferences
      );
      if (qualification) {
        addNamespaceQualifier(changes, sourceFile, qualification);
      }
      return includeSymbolNameInDescription ? [Diagnostics.Import_0_from_1, symbolName2, moduleSpecifier] : [Diagnostics.Add_import_from_0, moduleSpecifier];
    }
    case 4 /* PromoteTypeOnly */: {
      const { typeOnlyAliasDeclaration } = fix;
      const promotedDeclaration = promoteFromTypeOnly(changes, typeOnlyAliasDeclaration, program, sourceFile, preferences);
      return promotedDeclaration.kind === 276 /* ImportSpecifier */ ? [Diagnostics.Remove_type_from_import_of_0_from_1, symbolName2, getModuleSpecifierText(promotedDeclaration.parent.parent)] : [Diagnostics.Remove_type_from_import_declaration_from_0, getModuleSpecifierText(promotedDeclaration)];
    }
    default:
      return Debug.assertNever(fix, `Unexpected fix kind ${fix.kind}`);
  }
}
function getModuleSpecifierText(promotedDeclaration) {
  var _a, _b;
  return promotedDeclaration.kind === 271 /* ImportEqualsDeclaration */ ? ((_b = tryCast((_a = tryCast(promotedDeclaration.moduleReference, isExternalModuleReference)) == null ? void 0 : _a.expression, isStringLiteralLike)) == null ? void 0 : _b.text) || promotedDeclaration.moduleReference.getText() : cast(promotedDeclaration.parent.moduleSpecifier, isStringLiteral).text;
}
function promoteFromTypeOnly(changes, aliasDeclaration, program, sourceFile, preferences) {
  const compilerOptions = program.getCompilerOptions();
  const convertExistingToTypeOnly = compilerOptions.verbatimModuleSyntax;
  switch (aliasDeclaration.kind) {
    case 276 /* ImportSpecifier */:
      if (aliasDeclaration.isTypeOnly) {
        if (aliasDeclaration.parent.elements.length > 1) {
          const newSpecifier = factory.updateImportSpecifier(
            aliasDeclaration,
            /*isTypeOnly*/
            false,
            aliasDeclaration.propertyName,
            aliasDeclaration.name
          );
          const { specifierComparer } = ts_OrganizeImports_exports.getNamedImportSpecifierComparerWithDetection(aliasDeclaration.parent.parent.parent, preferences, sourceFile);
          const insertionIndex = ts_OrganizeImports_exports.getImportSpecifierInsertionIndex(aliasDeclaration.parent.elements, newSpecifier, specifierComparer);
          if (insertionIndex !== aliasDeclaration.parent.elements.indexOf(aliasDeclaration)) {
            changes.delete(sourceFile, aliasDeclaration);
            changes.insertImportSpecifierAtIndex(sourceFile, newSpecifier, aliasDeclaration.parent, insertionIndex);
            return aliasDeclaration;
          }
        }
        changes.deleteRange(sourceFile, { pos: getTokenPosOfNode(aliasDeclaration.getFirstToken()), end: getTokenPosOfNode(aliasDeclaration.propertyName ?? aliasDeclaration.name) });
        return aliasDeclaration;
      } else {
        Debug.assert(aliasDeclaration.parent.parent.isTypeOnly);
        promoteImportClause(aliasDeclaration.parent.parent);
        return aliasDeclaration.parent.parent;
      }
    case 273 /* ImportClause */:
      promoteImportClause(aliasDeclaration);
      return aliasDeclaration;
    case 274 /* NamespaceImport */:
      promoteImportClause(aliasDeclaration.parent);
      return aliasDeclaration.parent;
    case 271 /* ImportEqualsDeclaration */:
      changes.deleteRange(sourceFile, aliasDeclaration.getChildAt(1));
      return aliasDeclaration;
    default:
      Debug.failBadSyntaxKind(aliasDeclaration);
  }
  function promoteImportClause(importClause) {
    var _a;
    changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(importClause, sourceFile));
    if (!compilerOptions.allowImportingTsExtensions) {
      const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(importClause.parent);
      const resolvedModule = moduleSpecifier && ((_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier, sourceFile)) == null ? void 0 : _a.resolvedModule);
      if (resolvedModule == null ? void 0 : resolvedModule.resolvedUsingTsExtension) {
        const changedExtension = changeAnyExtension(moduleSpecifier.text, getOutputExtension(moduleSpecifier.text, compilerOptions));
        changes.replaceNode(sourceFile, moduleSpecifier, factory.createStringLiteral(changedExtension));
      }
    }
    if (convertExistingToTypeOnly) {
      const namedImports = tryCast(importClause.namedBindings, isNamedImports);
      if (namedImports && namedImports.elements.length > 1) {
        const sortState = ts_OrganizeImports_exports.getNamedImportSpecifierComparerWithDetection(importClause.parent, preferences, sourceFile);
        if (sortState.isSorted !== false && aliasDeclaration.kind === 276 /* ImportSpecifier */ && namedImports.elements.indexOf(aliasDeclaration) !== 0) {
          changes.delete(sourceFile, aliasDeclaration);
          changes.insertImportSpecifierAtIndex(sourceFile, aliasDeclaration, namedImports, 0);
        }
        for (const element of namedImports.elements) {
          if (element !== aliasDeclaration && !element.isTypeOnly) {
            changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */, element);
          }
        }
      }
    }
  }
}
function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, removeExistingImportSpecifiers, preferences) {
  var _a;
  if (clause.kind === 206 /* ObjectBindingPattern */) {
    if (removeExistingImportSpecifiers && clause.elements.some((e) => removeExistingImportSpecifiers.has(e))) {
      changes.replaceNode(
        sourceFile,
        clause,
        factory.createObjectBindingPattern([
          ...clause.elements.filter((e) => !removeExistingImportSpecifiers.has(e)),
          ...defaultImport ? [factory.createBindingElement(
            /*dotDotDotToken*/
            void 0,
            /*propertyName*/
            "default",
            defaultImport.name
          )] : emptyArray,
          ...namedImports.map((i) => factory.createBindingElement(
            /*dotDotDotToken*/
            void 0,
            i.propertyName,
            i.name
          ))
        ])
      );
      return;
    }
    if (defaultImport) {
      addElementToBindingPattern(clause, defaultImport.name, "default");
    }
    for (const specifier of namedImports) {
      addElementToBindingPattern(clause, specifier.name, specifier.propertyName);
    }
    return;
  }
  const promoteFromTypeOnly2 = clause.isTypeOnly && some([defaultImport, ...namedImports], (i) => (i == null ? void 0 : i.addAsTypeOnly) === 4 /* NotAllowed */);
  const existingSpecifiers = clause.namedBindings && ((_a = tryCast(clause.namedBindings, isNamedImports)) == null ? void 0 : _a.elements);
  if (defaultImport) {
    Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one");
    changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), factory.createIdentifier(defaultImport.name), { suffix: ", " });
  }
  if (namedImports.length) {
    const { specifierComparer, isSorted } = ts_OrganizeImports_exports.getNamedImportSpecifierComparerWithDetection(clause.parent, preferences, sourceFile);
    const newSpecifiers = toSorted(
      namedImports.map(
        (namedImport) => factory.createImportSpecifier(
          (!clause.isTypeOnly || promoteFromTypeOnly2) && shouldUseTypeOnly(namedImport, preferences),
          namedImport.propertyName === void 0 ? void 0 : factory.createIdentifier(namedImport.propertyName),
          factory.createIdentifier(namedImport.name)
        )
      ),
      specifierComparer
    );
    if (removeExistingImportSpecifiers) {
      changes.replaceNode(
        sourceFile,
        clause.namedBindings,
        factory.updateNamedImports(
          clause.namedBindings,
          toSorted([...existingSpecifiers.filter((s) => !removeExistingImportSpecifiers.has(s)), ...newSpecifiers], specifierComparer)
        )
      );
    } else if ((existingSpecifiers == null ? void 0 : existingSpecifiers.length) && isSorted !== false) {
      const transformedExistingSpecifiers = promoteFromTypeOnly2 && existingSpecifiers ? factory.updateNamedImports(
        clause.namedBindings,
        sameMap(existingSpecifiers, (e) => factory.updateImportSpecifier(
          e,
          /*isTypeOnly*/
          true,
          e.propertyName,
          e.name
        ))
      ).elements : existingSpecifiers;
      for (const spec of newSpecifiers) {
        const insertionIndex = ts_OrganizeImports_exports.getImportSpecifierInsertionIndex(transformedExistingSpecifiers, spec, specifierComparer);
        changes.insertImportSpecifierAtIndex(sourceFile, spec, clause.namedBindings, insertionIndex);
      }
    } else if (existingSpecifiers == null ? void 0 : existingSpecifiers.length) {
      for (const spec of newSpecifiers) {
        changes.insertNodeInListAfter(sourceFile, last(existingSpecifiers), spec, existingSpecifiers);
      }
    } else {
      if (newSpecifiers.length) {
        const namedImports2 = factory.createNamedImports(newSpecifiers);
        if (clause.namedBindings) {
          changes.replaceNode(sourceFile, clause.namedBindings, namedImports2);
        } else {
          changes.insertNodeAfter(sourceFile, Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports2);
        }
      }
    }
  }
  if (promoteFromTypeOnly2) {
    changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(clause, sourceFile));
    if (existingSpecifiers) {
      for (const specifier of existingSpecifiers) {
        changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */, specifier);
      }
    }
  }
  function addElementToBindingPattern(bindingPattern, name, propertyName) {
    const element = factory.createBindingElement(
      /*dotDotDotToken*/
      void 0,
      propertyName,
      name
    );
    if (bindingPattern.elements.length) {
      changes.insertNodeInListAfter(sourceFile, last(bindingPattern.elements), element);
    } else {
      changes.replaceNode(sourceFile, bindingPattern, factory.createObjectBindingPattern([element]));
    }
  }
}
function addNamespaceQualifier(changes, sourceFile, { namespacePrefix, usagePosition }) {
  changes.insertText(sourceFile, usagePosition, namespacePrefix + ".");
}
function addImportType(changes, sourceFile, { moduleSpecifier, usagePosition: position }, quotePreference) {
  changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference));
}
function getImportTypePrefix(moduleSpecifier, quotePreference) {
  const quote2 = getQuoteFromPreference(quotePreference);
  return `import(${quote2}${moduleSpecifier}${quote2}).`;
}
function needsTypeOnly({ addAsTypeOnly }) {
  return addAsTypeOnly === 2 /* Required */;
}
function shouldUseTypeOnly(info, preferences) {
  return needsTypeOnly(info) || !!preferences.preferTypeOnlyAutoImports && info.addAsTypeOnly !== 4 /* NotAllowed */;
}
function getNewImports(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport, compilerOptions, preferences) {
  const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference);
  let statements;
  if (defaultImport !== void 0 || (namedImports == null ? void 0 : namedImports.length)) {
    const topLevelTypeOnly = (!defaultImport || needsTypeOnly(defaultImport)) && every(namedImports, needsTypeOnly) || (compilerOptions.verbatimModuleSyntax || preferences.preferTypeOnlyAutoImports) && (defaultImport == null ? void 0 : defaultImport.addAsTypeOnly) !== 4 /* NotAllowed */ && !some(namedImports, (i) => i.addAsTypeOnly === 4 /* NotAllowed */);
    statements = combine(
      statements,
      makeImport(
        defaultImport && factory.createIdentifier(defaultImport.name),
        namedImports == null ? void 0 : namedImports.map(
          (namedImport) => factory.createImportSpecifier(
            !topLevelTypeOnly && shouldUseTypeOnly(namedImport, preferences),
            namedImport.propertyName === void 0 ? void 0 : factory.createIdentifier(namedImport.propertyName),
            factory.createIdentifier(namedImport.name)
          )
        ),
        moduleSpecifier,
        quotePreference,
        topLevelTypeOnly
      )
    );
  }
  if (namespaceLikeImport) {
    const declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ ? factory.createImportEqualsDeclaration(
      /*modifiers*/
      void 0,
      shouldUseTypeOnly(namespaceLikeImport, preferences),
      factory.createIdentifier(namespaceLikeImport.name),
      factory.createExternalModuleReference(quotedModuleSpecifier)
    ) : factory.createImportDeclaration(
      /*modifiers*/
      void 0,
      factory.createImportClause(
        shouldUseTypeOnly(namespaceLikeImport, preferences),
        /*name*/
        void 0,
        factory.createNamespaceImport(factory.createIdentifier(namespaceLikeImport.name))
      ),
      quotedModuleSpecifier,
      /*attributes*/
      void 0
    );
    statements = combine(statements, declaration);
  }
  return Debug.checkDefined(statements);
}
function getNewRequires(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport) {
  const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference);
  let statements;
  if (defaultImport || (namedImports == null ? void 0 : namedImports.length)) {
    const bindingElements = (namedImports == null ? void 0 : namedImports.map(({ name, propertyName }) => factory.createBindingElement(
      /*dotDotDotToken*/
      void 0,
      propertyName,
      name
    ))) || [];
    if (defaultImport) {
      bindingElements.unshift(factory.createBindingElement(
        /*dotDotDotToken*/
        void 0,
        "default",
        defaultImport.name
      ));
    }
    const declaration = createConstEqualsRequireDeclaration(factory.createObjectBindingPattern(bindingElements), quotedModuleSpecifier);
    statements = combine(statements, declaration);
  }
  if (namespaceLikeImport) {
    const declaration = createConstEqualsRequireDeclaration(namespaceLikeImport.name, quotedModuleSpecifier);
    statements = combine(statements, declaration);
  }
  return Debug.checkDefined(statements);
}
function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) {
  return factory.createVariableStatement(
    /*modifiers*/
    void 0,
    factory.createVariableDeclarationList([
      factory.createVariableDeclaration(
        typeof name === "string" ? factory.createIdentifier(name) : name,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        factory.createCallExpression(
          factory.createIdentifier("require"),
          /*typeArguments*/
          void 0,
          [quotedModuleSpecifier]
        )
      )
    ], 2 /* Const */)
  );
}
function symbolFlagsHaveMeaning(flags, meaning) {
  return meaning === 7 /* All */ ? true : meaning & 1 /* Value */ ? !!(flags & 111551 /* Value */) : meaning & 2 /* Type */ ? !!(flags & 788968 /* Type */) : meaning & 4 /* Namespace */ ? !!(flags & 1920 /* Namespace */) : false;
}
function getImpliedNodeFormatForEmit(file, program) {
  return isFullSourceFile(file) ? program.getImpliedNodeFormatForEmit(file) : getImpliedNodeFormatForEmitWorker(file, program.getCompilerOptions());
}
function getEmitModuleFormatOfFile(file, program) {
  return isFullSourceFile(file) ? program.getEmitModuleFormatOfFile(file) : getEmitModuleFormatOfFileWorker(file, program.getCompilerOptions());
}

// src/services/codefixes/fixAddMissingConstraint.ts
var fixId18 = "addMissingConstraint";
var errorCodes20 = [
  // We want errors this could be attached to:
  // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint
  Diagnostics.Type_0_is_not_comparable_to_type_1.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1.code,
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code,
  Diagnostics.Property_0_is_incompatible_with_index_signature.code,
  Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code,
  Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code
];
registerCodeFix({
  errorCodes: errorCodes20,
  getCodeActions(context) {
    const { sourceFile, span, program, preferences, host } = context;
    const info = getInfo6(program, sourceFile, span);
    if (info === void 0) return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingConstraint(t, program, preferences, host, sourceFile, info));
    return [createCodeFixAction(fixId18, changes, Diagnostics.Add_extends_constraint, fixId18, Diagnostics.Add_extends_constraint_to_all_type_parameters)];
  },
  fixIds: [fixId18],
  getAllCodeActions: (context) => {
    const { program, preferences, host } = context;
    const seen = /* @__PURE__ */ new Set();
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      eachDiagnostic(context, errorCodes20, (diag2) => {
        const info = getInfo6(program, diag2.file, createTextSpan(diag2.start, diag2.length));
        if (info) {
          if (addToSeen(seen, getNodeId(info.declaration))) {
            return addMissingConstraint(changes, program, preferences, host, diag2.file, info);
          }
        }
        return void 0;
      });
    }));
  }
});
function getInfo6(program, sourceFile, span) {
  const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length);
  if (diag2 === void 0 || diag2.relatedInformation === void 0) return;
  const related = find(diag2.relatedInformation, (related2) => related2.code === Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code);
  if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) return;
  let declaration = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length));
  if (declaration === void 0) return;
  if (isIdentifier(declaration) && isTypeParameterDeclaration(declaration.parent)) {
    declaration = declaration.parent;
  }
  if (isTypeParameterDeclaration(declaration)) {
    if (isMappedTypeNode(declaration.parent)) return;
    const token = getTokenAtPosition(sourceFile, span.start);
    const checker = program.getTypeChecker();
    const constraint = tryGetConstraintType(checker, token) || tryGetConstraintFromDiagnosticMessage(related.messageText);
    return { constraint, declaration, token };
  }
  return void 0;
}
function addMissingConstraint(changes, program, preferences, host, sourceFile, info) {
  const { declaration, constraint } = info;
  const checker = program.getTypeChecker();
  if (isString(constraint)) {
    changes.insertText(sourceFile, declaration.name.end, ` extends ${constraint}`);
  } else {
    const scriptTarget = getEmitScriptTarget(program.getCompilerOptions());
    const tracker = getNoopSymbolTrackerWithResolver({ program, host });
    const importAdder = createImportAdder(sourceFile, program, preferences, host);
    const typeNode = typeToAutoImportableTypeNode(
      checker,
      importAdder,
      constraint,
      /*contextNode*/
      void 0,
      scriptTarget,
      /*flags*/
      void 0,
      /*internalFlags*/
      void 0,
      tracker
    );
    if (typeNode) {
      changes.replaceNode(sourceFile, declaration, factory.updateTypeParameterDeclaration(
        declaration,
        /*modifiers*/
        void 0,
        declaration.name,
        typeNode,
        declaration.default
      ));
      importAdder.writeFixes(changes);
    }
  }
}
function tryGetConstraintFromDiagnosticMessage(messageText) {
  const [, constraint] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || [];
  return constraint;
}
function tryGetConstraintType(checker, node) {
  if (isTypeNode(node.parent)) {
    return checker.getTypeArgumentConstraint(node.parent);
  }
  const contextualType = isExpression(node) ? checker.getContextualType(node) : void 0;
  return contextualType || checker.getTypeAtLocation(node);
}

// src/services/codefixes/fixOverrideModifier.ts
var fixName = "fixOverrideModifier";
var fixAddOverrideId = "fixAddOverrideModifier";
var fixRemoveOverrideId = "fixRemoveOverrideModifier";
var errorCodes21 = [
  Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code,
  Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code,
  Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code,
  Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code,
  Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code,
  Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code,
  Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code,
  Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code,
  Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code
];
var errorCodeFixIdMap = {
  // case #1:
  [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Add_override_modifier,
    fixId: fixAddOverrideId,
    fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers
  },
  [Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Add_override_modifier,
    fixId: fixAddOverrideId,
    fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers
  },
  // case #2:
  [Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code]: {
    descriptions: Diagnostics.Remove_override_modifier,
    fixId: fixRemoveOverrideId,
    fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers
  },
  [Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code]: {
    descriptions: Diagnostics.Remove_override_modifier,
    fixId: fixRemoveOverrideId,
    fixAllDescriptions: Diagnostics.Remove_override_modifier
  },
  // case #3:
  [Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code]: {
    descriptions: Diagnostics.Add_override_modifier,
    fixId: fixAddOverrideId,
    fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers
  },
  [Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Add_override_modifier,
    fixId: fixAddOverrideId,
    fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers
  },
  // case #4:
  [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Add_override_modifier,
    fixId: fixAddOverrideId,
    fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers
  },
  // case #5:
  [Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Remove_override_modifier,
    fixId: fixRemoveOverrideId,
    fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers
  },
  [Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Remove_override_modifier,
    fixId: fixRemoveOverrideId,
    fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers
  }
};
registerCodeFix({
  errorCodes: errorCodes21,
  getCodeActions: function getCodeActionsToFixOverrideModifierIssues(context) {
    const { errorCode, span } = context;
    const info = errorCodeFixIdMap[errorCode];
    if (!info) return emptyArray;
    const { descriptions, fixId: fixId56, fixAllDescriptions } = info;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => dispatchChanges(changes2, context, errorCode, span.start));
    return [
      createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId56, fixAllDescriptions)
    ];
  },
  fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes21, (changes, diag2) => {
    const { code, start } = diag2;
    const info = errorCodeFixIdMap[code];
    if (!info || info.fixId !== context.fixId) {
      return;
    }
    dispatchChanges(changes, context, code, start);
  })
});
function dispatchChanges(changeTracker, context, errorCode, pos) {
  switch (errorCode) {
    case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code:
    case Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code:
    case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code:
    case Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code:
    case Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code:
      return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos);
    case Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code:
    case Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code:
    case Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code:
    case Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code:
      return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos);
    default:
      Debug.fail("Unexpected error code: " + errorCode);
  }
}
function doAddOverrideModifierChange(changeTracker, sourceFile, pos) {
  const classElement = findContainerClassElementLike(sourceFile, pos);
  if (isSourceFileJS(sourceFile)) {
    changeTracker.addJSDocTags(sourceFile, classElement, [factory.createJSDocOverrideTag(factory.createIdentifier("override"))]);
    return;
  }
  const modifiers = classElement.modifiers || emptyArray;
  const staticModifier = find(modifiers, isStaticModifier);
  const abstractModifier = find(modifiers, isAbstractModifier);
  const accessibilityModifier = find(modifiers, (m) => isAccessibilityModifier(m.kind));
  const lastDecorator = findLast(modifiers, isDecorator);
  const modifierPos = abstractModifier ? abstractModifier.end : staticModifier ? staticModifier.end : accessibilityModifier ? accessibilityModifier.end : lastDecorator ? skipTrivia(sourceFile.text, lastDecorator.end) : classElement.getStart(sourceFile);
  const options = accessibilityModifier || staticModifier || abstractModifier ? { prefix: " " } : { suffix: " " };
  changeTracker.insertModifierAt(sourceFile, modifierPos, 164 /* OverrideKeyword */, options);
}
function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) {
  const classElement = findContainerClassElementLike(sourceFile, pos);
  if (isSourceFileJS(sourceFile)) {
    changeTracker.filterJSDocTags(sourceFile, classElement, not(isJSDocOverrideTag));
    return;
  }
  const overrideModifier = find(classElement.modifiers, isOverrideModifier);
  Debug.assertIsDefined(overrideModifier);
  changeTracker.deleteModifier(sourceFile, overrideModifier);
}
function isClassElementLikeHasJSDoc(node) {
  switch (node.kind) {
    case 176 /* Constructor */:
    case 172 /* PropertyDeclaration */:
    case 174 /* MethodDeclaration */:
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
      return true;
    case 169 /* Parameter */:
      return isParameterPropertyDeclaration(node, node.parent);
    default:
      return false;
  }
}
function findContainerClassElementLike(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  const classElement = findAncestor(token, (node) => {
    if (isClassLike(node)) return "quit";
    return isClassElementLikeHasJSDoc(node);
  });
  Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement));
  return classElement;
}

// src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts
var fixId19 = "fixNoPropertyAccessFromIndexSignature";
var errorCodes22 = [
  Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code
];
registerCodeFix({
  errorCodes: errorCodes22,
  fixIds: [fixId19],
  getCodeActions(context) {
    const { sourceFile, span, preferences } = context;
    const property = getPropertyAccessExpression(sourceFile, span.start);
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange14(t, context.sourceFile, property, preferences));
    return [createCodeFixAction(fixId19, changes, [Diagnostics.Use_element_access_for_0, property.name.text], fixId19, Diagnostics.Use_element_access_for_all_undeclared_properties)];
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes22, (changes, diag2) => doChange14(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences))
});
function doChange14(changes, sourceFile, node, preferences) {
  const quotePreference = getQuotePreference(sourceFile, preferences);
  const argumentsExpression = factory.createStringLiteral(node.name.text, quotePreference === 0 /* Single */);
  changes.replaceNode(
    sourceFile,
    node,
    isPropertyAccessChain(node) ? factory.createElementAccessChain(node.expression, node.questionDotToken, argumentsExpression) : factory.createElementAccessExpression(node.expression, argumentsExpression)
  );
}
function getPropertyAccessExpression(sourceFile, pos) {
  return cast(getTokenAtPosition(sourceFile, pos).parent, isPropertyAccessExpression);
}

// src/services/codefixes/fixImplicitThis.ts
var fixId20 = "fixImplicitThis";
var errorCodes23 = [Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code];
registerCodeFix({
  errorCodes: errorCodes23,
  getCodeActions: function getCodeActionsToFixImplicitThis(context) {
    const { sourceFile, program, span } = context;
    let diagnostic;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => {
      diagnostic = doChange15(t, sourceFile, span.start, program.getTypeChecker());
    });
    return diagnostic ? [createCodeFixAction(fixId20, changes, diagnostic, fixId20, Diagnostics.Fix_all_implicit_this_errors)] : emptyArray;
  },
  fixIds: [fixId20],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes23, (changes, diag2) => {
    doChange15(changes, diag2.file, diag2.start, context.program.getTypeChecker());
  })
});
function doChange15(changes, sourceFile, pos, checker) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (!isThis(token)) return void 0;
  const fn = getThisContainer(
    token,
    /*includeArrowFunctions*/
    false,
    /*includeClassComputedPropertyName*/
    false
  );
  if (!isFunctionDeclaration(fn) && !isFunctionExpression(fn)) return void 0;
  if (!isSourceFile(getThisContainer(
    fn,
    /*includeArrowFunctions*/
    false,
    /*includeClassComputedPropertyName*/
    false
  ))) {
    const fnKeyword = Debug.checkDefined(findChildOfKind(fn, 100 /* FunctionKeyword */, sourceFile));
    const { name } = fn;
    const body = Debug.checkDefined(fn.body);
    if (isFunctionExpression(fn)) {
      if (name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) {
        return void 0;
      }
      changes.delete(sourceFile, fnKeyword);
      if (name) {
        changes.delete(sourceFile, name);
      }
      changes.insertText(sourceFile, body.pos, " =>");
      return [Diagnostics.Convert_function_expression_0_to_arrow_function, name ? name.text : ANONYMOUS];
    } else {
      changes.replaceNode(sourceFile, fnKeyword, factory.createToken(87 /* ConstKeyword */));
      changes.insertText(sourceFile, name.end, " = ");
      changes.insertText(sourceFile, body.pos, " =>");
      return [Diagnostics.Convert_function_declaration_0_to_arrow_function, name.text];
    }
  }
}

// src/services/codefixes/fixImportNonExportedMember.ts
var fixId21 = "fixImportNonExportedMember";
var errorCodes24 = [
  Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code
];
registerCodeFix({
  errorCodes: errorCodes24,
  fixIds: [fixId21],
  getCodeActions(context) {
    const { sourceFile, span, program } = context;
    const info = getInfo7(sourceFile, span.start, program);
    if (info === void 0) return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange16(t, program, info));
    return [createCodeFixAction(fixId21, changes, [Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId21, Diagnostics.Export_all_referenced_locals)];
  },
  getAllCodeActions(context) {
    const { program } = context;
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      const exports2 = /* @__PURE__ */ new Map();
      eachDiagnostic(context, errorCodes24, (diag2) => {
        const info = getInfo7(diag2.file, diag2.start, program);
        if (info === void 0) return void 0;
        const { exportName, node, moduleSourceFile } = info;
        if (tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly) === void 0 && canHaveExportModifier(node)) {
          changes.insertExportModifier(moduleSourceFile, node);
        } else {
          const moduleExports = exports2.get(moduleSourceFile) || { typeOnlyExports: [], exports: [] };
          if (exportName.isTypeOnly) {
            moduleExports.typeOnlyExports.push(exportName);
          } else {
            moduleExports.exports.push(exportName);
          }
          exports2.set(moduleSourceFile, moduleExports);
        }
      });
      exports2.forEach((moduleExports, moduleSourceFile) => {
        const exportDeclaration = tryGetExportDeclaration(
          moduleSourceFile,
          /*isTypeOnly*/
          true
        );
        if (exportDeclaration && exportDeclaration.isTypeOnly) {
          doChanges(changes, program, moduleSourceFile, moduleExports.typeOnlyExports, exportDeclaration);
          doChanges(changes, program, moduleSourceFile, moduleExports.exports, tryGetExportDeclaration(
            moduleSourceFile,
            /*isTypeOnly*/
            false
          ));
        } else {
          doChanges(changes, program, moduleSourceFile, [...moduleExports.exports, ...moduleExports.typeOnlyExports], exportDeclaration);
        }
      });
    }));
  }
});
function getInfo7(sourceFile, pos, program) {
  var _a, _b;
  const token = getTokenAtPosition(sourceFile, pos);
  if (isIdentifier(token)) {
    const importDeclaration = findAncestor(token, isImportDeclaration);
    if (importDeclaration === void 0) return void 0;
    const moduleSpecifier = isStringLiteral(importDeclaration.moduleSpecifier) ? importDeclaration.moduleSpecifier : void 0;
    if (moduleSpecifier === void 0) return void 0;
    const resolvedModule = (_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier, sourceFile)) == null ? void 0 : _a.resolvedModule;
    if (resolvedModule === void 0) return void 0;
    const moduleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName);
    if (moduleSourceFile === void 0 || isSourceFileFromLibrary(program, moduleSourceFile)) return void 0;
    const moduleSymbol = moduleSourceFile.symbol;
    const locals = (_b = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _b.locals;
    if (locals === void 0) return void 0;
    const localSymbol = locals.get(token.escapedText);
    if (localSymbol === void 0) return void 0;
    const node = getNodeOfSymbol(localSymbol);
    if (node === void 0) return void 0;
    const exportName = { node: token, isTypeOnly: isTypeDeclaration(node) };
    return { exportName, node, moduleSourceFile, moduleSpecifier: moduleSpecifier.text };
  }
  return void 0;
}
function doChange16(changes, program, { exportName, node, moduleSourceFile }) {
  const exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly);
  if (exportDeclaration) {
    updateExport(changes, program, moduleSourceFile, exportDeclaration, [exportName]);
  } else if (canHaveExportModifier(node)) {
    changes.insertExportModifier(moduleSourceFile, node);
  } else {
    createExport(changes, program, moduleSourceFile, [exportName]);
  }
}
function doChanges(changes, program, sourceFile, moduleExports, node) {
  if (length(moduleExports)) {
    if (node) {
      updateExport(changes, program, sourceFile, node, moduleExports);
    } else {
      createExport(changes, program, sourceFile, moduleExports);
    }
  }
}
function tryGetExportDeclaration(sourceFile, isTypeOnly) {
  const predicate = (node) => isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly);
  return findLast(sourceFile.statements, predicate);
}
function updateExport(changes, program, sourceFile, node, names) {
  const namedExports = node.exportClause && isNamedExports(node.exportClause) ? node.exportClause.elements : factory.createNodeArray([]);
  const allowTypeModifier = !node.isTypeOnly && !!(getIsolatedModules(program.getCompilerOptions()) || find(namedExports, (e) => e.isTypeOnly));
  changes.replaceNode(
    sourceFile,
    node,
    factory.updateExportDeclaration(
      node,
      node.modifiers,
      node.isTypeOnly,
      factory.createNamedExports(
        factory.createNodeArray(
          [...namedExports, ...createExportSpecifiers(names, allowTypeModifier)],
          /*hasTrailingComma*/
          namedExports.hasTrailingComma
        )
      ),
      node.moduleSpecifier,
      node.attributes
    )
  );
}
function createExport(changes, program, sourceFile, names) {
  changes.insertNodeAtEndOfScope(sourceFile, sourceFile, factory.createExportDeclaration(
    /*modifiers*/
    void 0,
    /*isTypeOnly*/
    false,
    factory.createNamedExports(createExportSpecifiers(
      names,
      /*allowTypeModifier*/
      getIsolatedModules(program.getCompilerOptions())
    )),
    /*moduleSpecifier*/
    void 0,
    /*attributes*/
    void 0
  ));
}
function createExportSpecifiers(names, allowTypeModifier) {
  return factory.createNodeArray(map(names, (n) => factory.createExportSpecifier(
    allowTypeModifier && n.isTypeOnly,
    /*propertyName*/
    void 0,
    n.node
  )));
}
function getNodeOfSymbol(symbol) {
  if (symbol.valueDeclaration === void 0) {
    return firstOrUndefined(symbol.declarations);
  }
  const declaration = symbol.valueDeclaration;
  const variableStatement = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : void 0;
  return variableStatement && length(variableStatement.declarationList.declarations) === 1 ? variableStatement : declaration;
}

// src/services/codefixes/fixIncorrectNamedTupleSyntax.ts
var fixId22 = "fixIncorrectNamedTupleSyntax";
var errorCodes25 = [
  Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type.code,
  Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type.code
];
registerCodeFix({
  errorCodes: errorCodes25,
  getCodeActions: function getCodeActionsToFixIncorrectNamedTupleSyntax(context) {
    const { sourceFile, span } = context;
    const namedTupleMember = getNamedTupleMember(sourceFile, span.start);
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange17(t, sourceFile, namedTupleMember));
    return [createCodeFixAction(fixId22, changes, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels, fixId22, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels)];
  },
  fixIds: [fixId22]
});
function getNamedTupleMember(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  return findAncestor(token, (t) => t.kind === 202 /* NamedTupleMember */);
}
function doChange17(changes, sourceFile, namedTupleMember) {
  if (!namedTupleMember) {
    return;
  }
  let unwrappedType = namedTupleMember.type;
  let sawOptional = false;
  let sawRest = false;
  while (unwrappedType.kind === 190 /* OptionalType */ || unwrappedType.kind === 191 /* RestType */ || unwrappedType.kind === 196 /* ParenthesizedType */) {
    if (unwrappedType.kind === 190 /* OptionalType */) {
      sawOptional = true;
    } else if (unwrappedType.kind === 191 /* RestType */) {
      sawRest = true;
    }
    unwrappedType = unwrappedType.type;
  }
  const updated = factory.updateNamedTupleMember(
    namedTupleMember,
    namedTupleMember.dotDotDotToken || (sawRest ? factory.createToken(26 /* DotDotDotToken */) : void 0),
    namedTupleMember.name,
    namedTupleMember.questionToken || (sawOptional ? factory.createToken(58 /* QuestionToken */) : void 0),
    unwrappedType
  );
  if (updated === namedTupleMember) {
    return;
  }
  changes.replaceNode(sourceFile, namedTupleMember, updated);
}

// src/services/codefixes/fixSpelling.ts
var fixId23 = "fixSpelling";
var errorCodes26 = [
  Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
  Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
  Diagnostics.Could_not_find_name_0_Did_you_mean_1.code,
  Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
  Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2.code,
  Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1.code,
  Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1.code,
  // for JSX class components
  Diagnostics.No_overload_matches_this_call.code,
  // for JSX FC
  Diagnostics.Type_0_is_not_assignable_to_type_1.code
];
registerCodeFix({
  errorCodes: errorCodes26,
  getCodeActions(context) {
    const { sourceFile, errorCode } = context;
    const info = getInfo8(sourceFile, context.span.start, context, errorCode);
    if (!info) return void 0;
    const { node, suggestedSymbol } = info;
    const target = getEmitScriptTarget(context.host.getCompilationSettings());
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18(t, sourceFile, node, suggestedSymbol, target));
    return [createCodeFixAction("spelling", changes, [Diagnostics.Change_spelling_to_0, symbolName(suggestedSymbol)], fixId23, Diagnostics.Fix_all_detected_spelling_errors)];
  },
  fixIds: [fixId23],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes26, (changes, diag2) => {
    const info = getInfo8(diag2.file, diag2.start, context, diag2.code);
    const target = getEmitScriptTarget(context.host.getCompilationSettings());
    if (info) doChange18(changes, context.sourceFile, info.node, info.suggestedSymbol, target);
  })
});
function getInfo8(sourceFile, pos, context, errorCode) {
  const node = getTokenAtPosition(sourceFile, pos);
  const parent2 = node.parent;
  if ((errorCode === Diagnostics.No_overload_matches_this_call.code || errorCode === Diagnostics.Type_0_is_not_assignable_to_type_1.code) && !isJsxAttribute(parent2)) return void 0;
  const checker = context.program.getTypeChecker();
  let suggestedSymbol;
  if (isPropertyAccessExpression(parent2) && parent2.name === node) {
    Debug.assert(isMemberName(node), "Expected an identifier for spelling (property access)");
    let containingType = checker.getTypeAtLocation(parent2.expression);
    if (parent2.flags & 64 /* OptionalChain */) {
      containingType = checker.getNonNullableType(containingType);
    }
    suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, containingType);
  } else if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 103 /* InKeyword */ && parent2.left === node && isPrivateIdentifier(node)) {
    const receiverType = checker.getTypeAtLocation(parent2.right);
    suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, receiverType);
  } else if (isQualifiedName(parent2) && parent2.right === node) {
    const symbol = checker.getSymbolAtLocation(parent2.left);
    if (symbol && symbol.flags & 1536 /* Module */) {
      suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(parent2.right, symbol);
    }
  } else if (isImportSpecifier(parent2) && parent2.name === node) {
    Debug.assertNode(node, isIdentifier, "Expected an identifier for spelling (import)");
    const importDeclaration = findAncestor(node, isImportDeclaration);
    const resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(context, importDeclaration, sourceFile);
    if (resolvedSourceFile && resolvedSourceFile.symbol) {
      suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol);
    }
  } else if (isJsxAttribute(parent2) && parent2.name === node) {
    Debug.assertNode(node, isIdentifier, "Expected an identifier for JSX attribute");
    const tag = findAncestor(node, isJsxOpeningLikeElement);
    const props = checker.getContextualTypeForArgumentAtIndex(tag, 0);
    suggestedSymbol = checker.getSuggestedSymbolForNonexistentJSXAttribute(node, props);
  } else if (hasOverrideModifier(parent2) && isClassElement(parent2) && parent2.name === node) {
    const baseDeclaration = findAncestor(node, isClassLike);
    const baseTypeNode = baseDeclaration ? getEffectiveBaseTypeNode(baseDeclaration) : void 0;
    const baseType = baseTypeNode ? checker.getTypeAtLocation(baseTypeNode) : void 0;
    if (baseType) {
      suggestedSymbol = checker.getSuggestedSymbolForNonexistentClassMember(getTextOfNode(node), baseType);
    }
  } else {
    const meaning = getMeaningFromLocation(node);
    const name = getTextOfNode(node);
    Debug.assert(name !== void 0, "name should be defined");
    suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning));
  }
  return suggestedSymbol === void 0 ? void 0 : { node, suggestedSymbol };
}
function doChange18(changes, sourceFile, node, suggestedSymbol, target) {
  const suggestion = symbolName(suggestedSymbol);
  if (!isIdentifierText(suggestion, target) && isPropertyAccessExpression(node.parent)) {
    const valDecl = suggestedSymbol.valueDeclaration;
    if (valDecl && isNamedDeclaration(valDecl) && isPrivateIdentifier(valDecl.name)) {
      changes.replaceNode(sourceFile, node, factory.createIdentifier(suggestion));
    } else {
      changes.replaceNode(sourceFile, node.parent, factory.createElementAccessExpression(node.parent.expression, factory.createStringLiteral(suggestion)));
    }
  } else {
    changes.replaceNode(sourceFile, node, factory.cre