Merge remote-tracking branch 'upstream/master' into AddToggleCommentFeature

This commit is contained in:
Armando Aguirre committed 2020-07-09 21:55:36 -07:00
commit ef81a0d0ee
2236 files changed
+248785 -159199

No files matched your search

+180 -73
View File
@@ -150,12 +150,6 @@ namespace ts.server {
export type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void;
/*@internal*/
export interface PerformanceEvent {
kind: "UpdateGraph";
durationMs: number;
}
/*@internal*/
export type PerformanceEventHandler = (event: PerformanceEvent) => void;
@@ -163,11 +157,11 @@ namespace ts.server {
[name: string]: { match: RegExp, exclude?: (string | number)[][], types?: string[] };
}
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions: CommandLineOption[]): Map<Map<number>> {
const map: Map<Map<number>> = createMap<Map<number>>();
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions: CommandLineOption[]): ESMap<string, ESMap<string, number>> {
const map: ESMap<string, ESMap<string, number>> = createMap<ESMap<string, number>>();
for (const option of commandLineOptions) {
if (typeof option.type === "object") {
const optionMap = <Map<number>>option.type;
const optionMap = <ESMap<string, number>>option.type;
// verify that map contains only numbers
optionMap.forEach(value => {
Debug.assert(typeof value === "number");
@@ -379,7 +373,7 @@ namespace ts.server {
* It is false when the open file that would still be impacted by existence of
* this config file but it is not the root of inferred project
*/
openFilesImpactedByConfigFile: Map<boolean>;
openFilesImpactedByConfigFile: ESMap<Path, boolean>;
/**
* The file watcher watching the config file because there is open script info that is root of
* inferred project and will be impacted by change in the status of the config file
@@ -540,6 +534,7 @@ namespace ts.server {
/*@internal*/
export function updateProjectIfDirty(project: Project) {
project.invalidateResolutionsOfFailedLookupLocations();
return project.dirty && project.updateGraph();
}
@@ -591,11 +586,11 @@ namespace ts.server {
* Map to the real path of the infos
*/
/* @internal */
readonly realpathToScriptInfos: MultiMap<ScriptInfo> | undefined;
readonly realpathToScriptInfos: MultiMap<Path, ScriptInfo> | undefined;
/**
* maps external project file name to list of config files that were the part of this project
*/
private readonly externalProjectToConfiguredProjectMap: Map<NormalizedPath[]> = createMap<NormalizedPath[]>();
private readonly externalProjectToConfiguredProjectMap: ESMap<string, NormalizedPath[]> = createMap<NormalizedPath[]>();
/**
* external projects (configuration and list of root files is not controlled by tsserver)
@@ -608,11 +603,11 @@ namespace ts.server {
/**
* projects specified by a tsconfig.json file
*/
readonly configuredProjects = createMap<ConfiguredProject>();
readonly configuredProjects: Map<ConfiguredProject> = createMap<ConfiguredProject>();
/**
* Open files: with value being project root path, and key being Path of the file that is open
*/
readonly openFiles = createMap<NormalizedPath | undefined>();
readonly openFiles: Map<NormalizedPath | undefined> = new Map<Path, NormalizedPath | undefined>();
/**
* Map of open files that are opened without complete path but have projectRoot as current directory
*/
@@ -625,7 +620,7 @@ namespace ts.server {
/**
* Project size for configured or external projects
*/
private readonly projectToSizeMap: Map<number> = createMap<number>();
private readonly projectToSizeMap: ESMap<string, number> = createMap<number>();
/**
* This is a map of config file paths existence that doesnt need query to disk
* - The entry can be present because there is inferred project that needs to watch addition of config file to directory
@@ -634,7 +629,7 @@ namespace ts.server {
* In this case the exists property is always true
*/
private readonly configFileExistenceInfoCache = createMap<ConfigFileExistenceInfo>();
private readonly throttledOperations: ThrottledOperations;
/*@internal*/ readonly throttledOperations: ThrottledOperations;
private readonly hostConfiguration: HostConfiguration;
private safelist: SafeList = defaultTypeSafeList;
@@ -661,7 +656,7 @@ namespace ts.server {
public readonly globalPlugins: readonly string[];
public readonly pluginProbeLocations: readonly string[];
public readonly allowLocalPluginLoads: boolean;
private currentPluginConfigOverrides: Map<any> | undefined;
private currentPluginConfigOverrides: ESMap<string, any> | undefined;
public readonly typesMapLocation: string | undefined;
@@ -673,6 +668,12 @@ namespace ts.server {
/*@internal*/
readonly watchFactory: WatchFactory<WatchType, Project>;
/*@internal*/
readonly packageJsonCache: PackageJsonCache;
/*@internal*/
private packageJsonFilesMap: ESMap<Path, FileWatcher> | undefined;
private performanceEventHandler?: PerformanceEventHandler;
constructor(opts: ProjectServiceOptions) {
@@ -724,7 +725,14 @@ namespace ts.server {
const watchLogLevel = this.logger.hasLevel(LogLevel.verbose) ? WatchLogLevel.Verbose :
this.logger.loggingEnabled() ? WatchLogLevel.TriggerOnly : WatchLogLevel.None;
const log: (s: string) => void = watchLogLevel !== WatchLogLevel.None ? (s => this.logger.info(s)) : noop;
this.watchFactory = getWatchFactory(watchLogLevel, log, getDetailWatchInfo);
this.packageJsonCache = createPackageJsonCache(this);
this.watchFactory = this.syntaxOnly ?
{
watchFile: returnNoopFileWatcher,
watchFilePath: returnNoopFileWatcher,
watchDirectory: returnNoopFileWatcher,
} :
getWatchFactory(watchLogLevel, log, getDetailWatchInfo);
}
toPath(fileName: string) {
@@ -823,7 +831,8 @@ namespace ts.server {
this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
}
private delayEnsureProjectForOpenFiles() {
/*@internal*/
delayEnsureProjectForOpenFiles() {
this.pendingEnsureProjectForOpenFiles = true;
this.throttledOperations.schedule("*ensureProjectForOpenFiles*", /*delay*/ 2500, () => {
if (this.pendingProjectUpdates.size !== 0) {
@@ -913,9 +922,9 @@ namespace ts.server {
}
/* @internal */
sendUpdateGraphPerformanceEvent(durationMs: number) {
sendPerformanceEvent(kind: PerformanceEvent["kind"], durationMs: number) {
if (this.performanceEventHandler) {
this.performanceEventHandler({ kind: "UpdateGraph", durationMs });
this.performanceEventHandler({ kind, durationMs });
}
}
@@ -1111,9 +1120,9 @@ namespace ts.server {
}
}
private delayUpdateSourceInfoProjects(sourceInfos: Map<true> | undefined) {
private delayUpdateSourceInfoProjects(sourceInfos: Set<Path> | undefined) {
if (sourceInfos) {
sourceInfos.forEach((_value, path) => this.delayUpdateProjectsOfScriptInfoPath(path as Path));
sourceInfos.forEach((_value, path) => this.delayUpdateProjectsOfScriptInfoPath(path));
}
}
@@ -1154,12 +1163,34 @@ namespace ts.server {
*/
/*@internal*/
watchWildcardDirectory(directory: Path, flags: WatchDirectoryFlags, project: ConfiguredProject) {
const watchOptions = this.getWatchOptions(project);
return this.watchFactory.watchDirectory(
this.host,
directory,
fileOrDirectory => {
let fileOrDirectoryPath: Path | undefined = this.toPath(fileOrDirectory);
const fileOrDirectoryPath = this.toPath(fileOrDirectory);
const fsResult = project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
const configFileName = project.getConfigFilePath();
if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) &&
(fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectoryPath))
) {
this.logger.info(`Project: ${configFileName} Detected new package.json: ${fileOrDirectory}`);
this.onAddPackageJson(fileOrDirectoryPath);
}
if (isIgnoredFileFromWildCardWatching({
watchedDirPath: directory,
fileOrDirectory,
fileOrDirectoryPath,
configFileName,
configFileSpecs: project.configFileSpecs!,
extraFileExtensions: this.hostConfiguration.extraFileExtensions,
currentDirectory: this.currentDirectory,
options: project.getCompilationSettings(),
program: project.getCurrentProgram(),
useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames,
writeLog: s => this.logger.info(s)
})) return;
// don't trigger callback on open, existing files
if (project.fileIsOpen(fileOrDirectoryPath)) {
@@ -1176,24 +1207,6 @@ namespace ts.server {
return;
}
fileOrDirectoryPath = removeIgnoredPath(fileOrDirectoryPath);
if (!fileOrDirectoryPath) return;
const configFilename = project.getConfigFilePath();
if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) &&
(fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectoryPath))
) {
this.logger.info(`Project: ${configFilename} Detected new package.json: ${fileOrDirectory}`);
project.onAddPackageJson(fileOrDirectoryPath);
}
// If the the added or created file or directory is not supported file name, ignore the file
// But when watched directory is added/removed, we need to reload the file list
if (fileOrDirectoryPath !== directory && hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, project.getCompilationSettings(), this.hostConfiguration.extraFileExtensions)) {
this.logger.info(`Project: ${configFilename} Detected file add/remove of non supported extension: ${fileOrDirectory}`);
return;
}
// Reload is pending, do the reload
if (project.pendingReload !== ConfigFileProgramReloadLevel.Full) {
project.pendingReload = ConfigFileProgramReloadLevel.Partial;
@@ -1201,7 +1214,7 @@ namespace ts.server {
}
},
flags,
this.getWatchOptions(project),
watchOptions,
WatchType.WildcardDirectory,
project
);
@@ -1480,7 +1493,7 @@ namespace ts.server {
// Cache the host value of file exists and add the info to map of open files impacted by this config file
const exists = this.host.fileExists(configFileName);
const openFilesImpactedByConfigFile = createMap<boolean>();
const openFilesImpactedByConfigFile = new Map<Path, boolean>();
if (isOpenScriptInfo(info)) {
openFilesImpactedByConfigFile.set(info.path, false);
}
@@ -1508,7 +1521,7 @@ namespace ts.server {
// Since that route doesnt check if the config file is present or not
this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, {
exists: true,
openFilesImpactedByConfigFile: createMap<boolean>()
openFilesImpactedByConfigFile: new Map<Path, boolean>()
});
}
}
@@ -1546,7 +1559,7 @@ namespace ts.server {
const inferredRoots: string[] = [];
const otherFiles: string[] = [];
configFileExistenceInfo.openFilesImpactedByConfigFile.forEach((isRootOfInferredProject, key) => {
const info = this.getScriptInfoForPath(key as Path)!;
const info = this.getScriptInfoForPath(key)!;
(isRootOfInferredProject ? inferredRoots : otherFiles).push(info.fileName);
});
@@ -1644,7 +1657,7 @@ namespace ts.server {
// Create the cache
configFileExistenceInfo = {
exists: this.host.fileExists(configFileName),
openFilesImpactedByConfigFile: createMap<boolean>()
openFilesImpactedByConfigFile: new Map<Path, boolean>()
};
this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo);
}
@@ -1978,9 +1991,6 @@ namespace ts.server {
const configFileContent = tryReadFile(configFilename, fileName => this.host.readFile(fileName));
const result = parseJsonText(configFilename, isString(configFileContent) ? configFileContent : "");
if (!result.endOfFileToken) {
result.endOfFileToken = <EndOfFileToken>{ kind: SyntaxKind.EndOfFileToken };
}
const configFileErrors = result.parseDiagnostics as Diagnostic[];
if (!isString(configFileContent)) configFileErrors.push(configFileContent);
const parsedCommandLine = parseJsonSourceFileConfigFileContent(
@@ -2017,7 +2027,7 @@ namespace ts.server {
};
}
project.configFileSpecs = parsedCommandLine.configFileSpecs;
project.canConfigFileJsonReportNoInputFiles = canJsonReportNoInutFiles(parsedCommandLine.raw);
project.canConfigFileJsonReportNoInputFiles = canJsonReportNoInputFiles(parsedCommandLine.raw);
project.setProjectErrors(configFileErrors);
project.updateReferences(parsedCommandLine.projectReferences);
const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader);
@@ -2036,7 +2046,7 @@ namespace ts.server {
this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition!, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions);
}
private updateNonInferredProjectFiles<T>(project: ExternalProject | ConfiguredProject, files: T[], propertyReader: FilePropertyReader<T>) {
private updateNonInferredProjectFiles<T>(project: ExternalProject | ConfiguredProject | AutoImportProviderProject, files: T[], propertyReader: FilePropertyReader<T>) {
const projectRootFilesMap = project.getRootFilesMap();
const newRootScriptInfoMap = createMap<true>();
@@ -2133,6 +2143,11 @@ namespace ts.server {
return project.updateGraph();
}
/*@internal*/
setFileNamesOfAutoImportProviderProject(project: AutoImportProviderProject, fileNames: string[]) {
this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader);
}
/**
* Read the config file of the project again by clearing the cache and update the project graph
*/
@@ -2288,8 +2303,8 @@ namespace ts.server {
* Note that this does not return projects in info.containingProjects
*/
/*@internal*/
getSymlinkedProjects(info: ScriptInfo): MultiMap<Project> | undefined {
let projects: MultiMap<Project> | undefined;
getSymlinkedProjects(info: ScriptInfo): MultiMap<Path, Project> | undefined {
let projects: MultiMap<Path, Project> | undefined;
if (this.realpathToScriptInfos) {
const realpath = info.getRealpathIfDifferent();
if (realpath) {
@@ -2584,11 +2599,11 @@ namespace ts.server {
return documentPositionMapper;
}
private addSourceInfoToSourceMap(sourceFileName: string | undefined, project: Project, sourceInfos?: Map<true>) {
private addSourceInfoToSourceMap(sourceFileName: string | undefined, project: Project, sourceInfos?: Set<Path>) {
if (sourceFileName) {
// Attach as source
const sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(sourceFileName, project.currentDirectory, project.directoryStructureHost)!;
(sourceInfos || (sourceInfos = createMap())).set(sourceInfo.path, true);
(sourceInfos || (sourceInfos = new Set())).add(sourceInfo.path);
}
return sourceInfos;
}
@@ -2630,7 +2645,7 @@ namespace ts.server {
if (declarationInfo && isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) {
const sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
if (sourceMapInfo) {
(sourceMapInfo.sourceInfos || (sourceMapInfo.sourceInfos = createMap())).set(info.path, true);
(sourceMapInfo.sourceInfos || (sourceMapInfo.sourceInfos = new Set())).add(info.path);
}
}
@@ -2677,7 +2692,7 @@ namespace ts.server {
this.logger.info("Format host information updated");
}
if (args.preferences) {
const { lazyConfiguredProjectsFromExternalProject } = this.hostConfiguration.preferences;
const { lazyConfiguredProjectsFromExternalProject, includePackageJsonAutoImports } = this.hostConfiguration.preferences;
this.hostConfiguration.preferences = { ...this.hostConfiguration.preferences, ...args.preferences };
if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) {
// Load configured projects for external projects that are pending reload
@@ -2689,6 +2704,9 @@ namespace ts.server {
}
});
}
if (includePackageJsonAutoImports !== args.preferences.includePackageJsonAutoImports) {
this.invalidateProjectAutoImports(/*packageJsonPath*/ undefined);
}
}
if (args.extraFileExtensions) {
this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
@@ -2729,7 +2747,7 @@ namespace ts.server {
// as there is no need to load contents of the files from the disk
// Reload Projects
this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, returnTrue, "User requested reload projects");
this.reloadConfiguredProjectForFiles(this.openFiles as ESMap<Path, NormalizedPath | undefined>, /*delayReload*/ false, returnTrue, "User requested reload projects");
this.ensureProjectForOpenFiles();
}
@@ -2753,7 +2771,7 @@ namespace ts.server {
* If the there is no existing project it just opens the configured project for the config file
* reloadForInfo provides a way to filter out files to reload configured project for
*/
private reloadConfiguredProjectForFiles<T>(openFiles: Map<T>, delayReload: boolean, shouldReloadProjectFor: (openFileValue: T) => boolean, reason: string) {
private reloadConfiguredProjectForFiles<T>(openFiles: ESMap<Path, T>, delayReload: boolean, shouldReloadProjectFor: (openFileValue: T) => boolean, reason: string) {
const updatedProjects = createMap<true>();
// try to reload config file for all open files
openFiles.forEach((openFileValue, path) => {
@@ -2762,7 +2780,7 @@ namespace ts.server {
return;
}
const info = this.getScriptInfoForPath(path as Path)!; // TODO: GH#18217
const info = this.getScriptInfoForPath(path)!; // TODO: GH#18217
Debug.assert(info.isScriptOpen());
// This tries to search for a tsconfig.json for the given file. If we found it,
// we first detect if there is already a configured project created for it: if so,
@@ -2918,9 +2936,9 @@ namespace ts.server {
function addOriginalConfiguredProject(originalProject: ConfiguredProject) {
if (!project.originalConfiguredProjects) {
project.originalConfiguredProjects = createMap<true>();
project.originalConfiguredProjects = new Set();
}
project.originalConfiguredProjects.set(originalProject.canonicalConfigFilePath, true);
project.originalConfiguredProjects.add(originalProject.canonicalConfigFilePath);
}
}
@@ -3067,13 +3085,13 @@ namespace ts.server {
}
/*@internal*/
loadAncestorProjectTree(forProjects?: ReadonlyMap<true>) {
forProjects = forProjects || mapDefinedMap(
loadAncestorProjectTree(forProjects?: ReadonlyCollection<string>) {
forProjects = forProjects || mapDefinedEntries(
this.configuredProjects,
project => !project.isInitialLoadPending() || undefined
(key, project) => !project.isInitialLoadPending() ? [key, true] : undefined
);
const seenProjects = createMap<true>();
const seenProjects = new Set<NormalizedPath>();
// Work on array copy as we could add more projects as part of callback
for (const project of arrayFrom(this.configuredProjects.values())) {
// If this project has potential project reference for any of the project we are loading ancestor tree for
@@ -3091,8 +3109,8 @@ namespace ts.server {
}
}
private ensureProjectChildren(project: ConfiguredProject, seenProjects: Map<true>) {
if (!addToSeen(seenProjects, project.canonicalConfigFilePath)) return;
private ensureProjectChildren(project: ConfiguredProject, seenProjects: Set<NormalizedPath>) {
if (!tryAddToSet(seenProjects, project.canonicalConfigFilePath)) return;
// Update the project
updateProjectIfDirty(project);
@@ -3193,10 +3211,10 @@ namespace ts.server {
const toRemoveScriptInfos = cloneMap(this.filenameToScriptInfo);
this.filenameToScriptInfo.forEach(info => {
// If script info is open or orphan, retain it and its dependencies
if (!info.isScriptOpen() && info.isOrphan()) {
if (!info.isScriptOpen() && info.isOrphan() && !info.isContainedByAutoImportProvider()) {
// Otherwise if there is any source info that is alive, this alive too
if (!info.sourceMapFilePath) return;
let sourceInfos: Map<true> | undefined;
let sourceInfos: Set<Path> | undefined;
if (isString(info.sourceMapFilePath)) {
const sourceMapInfo = this.getScriptInfoForPath(info.sourceMapFilePath);
sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos;
@@ -3206,7 +3224,7 @@ namespace ts.server {
}
if (!sourceInfos) return;
if (!forEachKey(sourceInfos, path => {
const info = this.getScriptInfoForPath(path as Path);
const info = this.getScriptInfoForPath(path);
return !!info && (info.isScriptOpen() || !info.isOrphan());
})) {
return;
@@ -3216,7 +3234,7 @@ namespace ts.server {
// Retain this script info
toRemoveScriptInfos.delete(info.path);
if (info.sourceMapFilePath) {
let sourceInfos: Map<true> | undefined;
let sourceInfos: Set<Path> | undefined;
if (isString(info.sourceMapFilePath)) {
// And map file info and source infos
toRemoveScriptInfos.delete(info.sourceMapFilePath);
@@ -3671,6 +3689,95 @@ namespace ts.server {
this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || createMap();
this.currentPluginConfigOverrides.set(args.pluginName, args.configuration);
}
/*@internal*/
getPackageJsonsVisibleToFile(fileName: string, rootDir?: string): readonly PackageJsonInfo[] {
const packageJsonCache = this.packageJsonCache;
const watchPackageJsonFile = this.watchPackageJsonFile.bind(this);
const toPath = this.toPath.bind(this);
const rootPath = rootDir && toPath(rootDir);
const filePath = toPath(fileName);
const result: PackageJsonInfo[] = [];
forEachAncestorDirectory(getDirectoryPath(filePath), function processDirectory(directory): boolean | undefined {
switch (packageJsonCache.directoryHasPackageJson(directory)) {
// Sync and check same directory again
case Ternary.Maybe:
packageJsonCache.searchDirectoryAndAncestors(directory);
return processDirectory(directory);
// Check package.json
case Ternary.True:
const packageJsonFileName = combinePaths(directory, "package.json");
watchPackageJsonFile(packageJsonFileName);
const info = packageJsonCache.getInDirectory(directory);
if (info) result.push(info);
}
if (rootPath && rootPath === toPath(directory)) {
return true;
}
});
return result;
}
/*@internal*/
private watchPackageJsonFile(path: Path) {
const watchers = this.packageJsonFilesMap || (this.packageJsonFilesMap = createMap());
if (!watchers.has(path)) {
this.invalidateProjectAutoImports(path);
watchers.set(path, this.watchFactory.watchFile(
this.host,
path,
(fileName, eventKind) => {
const path = this.toPath(fileName);
switch (eventKind) {
case FileWatcherEventKind.Created:
return Debug.fail();
case FileWatcherEventKind.Changed:
this.packageJsonCache.addOrUpdate(path);
this.invalidateProjectAutoImports(path);
break;
case FileWatcherEventKind.Deleted:
this.packageJsonCache.delete(path);
this.invalidateProjectAutoImports(path);
watchers.get(path)!.close();
watchers.delete(path);
}
},
PollingInterval.Low,
this.hostConfiguration.watchOptions,
WatchType.PackageJsonFile,
));
}
}
/*@internal*/
private onAddPackageJson(path: Path) {
this.packageJsonCache.addOrUpdate(path);
this.watchPackageJsonFile(path);
}
/*@internal*/
includePackageJsonAutoImports(): PackageJsonAutoImportPreference {
switch (this.hostConfiguration.preferences.includePackageJsonAutoImports) {
case "none": return PackageJsonAutoImportPreference.None;
case "all": return PackageJsonAutoImportPreference.All;
default: return PackageJsonAutoImportPreference.ExcludeDevDependencies;
}
}
/*@internal*/
private invalidateProjectAutoImports(packageJsonPath: Path | undefined) {
if (this.includePackageJsonAutoImports()) {
this.configuredProjects.forEach(invalidate);
this.inferredProjects.forEach(invalidate);
this.externalProjects.forEach(invalidate);
}
function invalidate(project: Project) {
if (!packageJsonPath || project.packageJsonsForAutoImport?.has(packageJsonPath)) {
project.markAutoImportProviderAsDirty();
}
}
}
}
/* @internal */
+9 -5
View File
@@ -2,17 +2,21 @@
namespace ts.server {
export interface PackageJsonCache {
addOrUpdate(fileName: Path): void;
forEach(action: (info: PackageJsonInfo, fileName: Path) => void): void;
delete(fileName: Path): void;
get(fileName: Path): PackageJsonInfo | false | undefined;
getInDirectory(directory: Path): PackageJsonInfo | undefined;
directoryHasPackageJson(directory: Path): Ternary;
searchDirectoryAndAncestors(directory: Path): void;
}
export function createPackageJsonCache(project: Project): PackageJsonCache {
const packageJsons = createMap<PackageJsonInfo | false>();
export function createPackageJsonCache(host: ProjectService): PackageJsonCache {
const packageJsons = createMap<PackageJsonInfo>();
const directoriesWithoutPackageJson = createMap<true>();
return {
addOrUpdate,
forEach: packageJsons.forEach.bind(packageJsons),
get: packageJsons.get.bind(packageJsons),
delete: fileName => {
packageJsons.delete(fileName);
directoriesWithoutPackageJson.set(getDirectoryPath(fileName), true);
@@ -26,8 +30,8 @@ namespace ts.server {
if (directoryHasPackageJson(ancestor) !== Ternary.Maybe) {
return true;
}
const packageJsonFileName = project.toPath(combinePaths(ancestor, "package.json"));
if (tryFileExists(project, packageJsonFileName)) {
const packageJsonFileName = host.toPath(combinePaths(ancestor, "package.json"));
if (tryFileExists(host, packageJsonFileName)) {
addOrUpdate(packageJsonFileName);
}
else {
@@ -38,7 +42,7 @@ namespace ts.server {
};
function addOrUpdate(fileName: Path) {
const packageJsonInfo = createPackageJsonInfo(fileName, project);
const packageJsonInfo = createPackageJsonInfo(fileName, host.host);
if (packageJsonInfo !== undefined) {
packageJsons.set(fileName, packageJsonInfo);
directoriesWithoutPackageJson.delete(getDirectoryPath(fileName));
+307 -118
View File
@@ -3,7 +3,8 @@ namespace ts.server {
export enum ProjectKind {
Inferred,
Configured,
External
External,
AutoImportProvider,
}
/* @internal */
@@ -113,7 +114,7 @@ namespace ts.server {
generatedFilePath: Path;
watcher: FileWatcher;
}
type GeneratedFileWatcherMap = GeneratedFileWatcher | Map<GeneratedFileWatcher>;
type GeneratedFileWatcherMap = GeneratedFileWatcher | ESMap<Path, GeneratedFileWatcher>;
function isGeneratedFileWatcher(watch: GeneratedFileWatcherMap): watch is GeneratedFileWatcher {
return (watch as GeneratedFileWatcher).generatedFilePath !== undefined;
}
@@ -129,20 +130,17 @@ namespace ts.server {
private rootFilesMap = createMap<ProjectRootFile>();
private program: Program | undefined;
private externalFiles: SortedReadonlyArray<string> | undefined;
private missingFilesMap: Map<FileWatcher> | undefined;
private missingFilesMap: ESMap<Path, FileWatcher> | undefined;
private generatedFilesMap: GeneratedFileWatcherMap | undefined;
private plugins: PluginModuleWithName[] = [];
/*@internal*/
private packageJsonFilesMap: Map<FileWatcher> | undefined;
/*@internal*/
/**
* This is map from files to unresolved imports in it
* Maop does not contain entries for files that do not have unresolved imports
* This helps in containing the set of files to invalidate
*/
cachedUnresolvedImportsPerFile = createMap<readonly string[]>();
cachedUnresolvedImportsPerFile = new Map<Path, readonly string[]>();
/*@internal*/
lastCachedUnresolvedImportsList: SortedReadonlyArray<string> | undefined;
@@ -169,11 +167,11 @@ namespace ts.server {
/**
* Set of files names that were updated since the last call to getChangesSinceVersion.
*/
private updatedFileNames: Map<true> | undefined;
private updatedFileNames: Set<string> | undefined;
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
*/
private lastReportedFileNames: Map<boolean> | undefined;
private lastReportedFileNames: ESMap<string, boolean> | undefined;
/**
* Last version that was reported.
*/
@@ -196,14 +194,14 @@ namespace ts.server {
/*@internal*/
dirty = false;
/*@internal*/
hasChangedAutomaticTypeDirectiveNames = false;
/*@internal*/
typingFiles: SortedReadonlyArray<string> = emptyArray;
/*@internal*/
originalConfiguredProjects: Map<true> | undefined;
originalConfiguredProjects: Set<NormalizedPath> | undefined;
/*@internal*/
packageJsonsForAutoImport: Set<string> | undefined;
/*@internal*/
getResolvedProjectReferenceToRedirect(_fileName: string): ResolvedProjectReference | undefined {
@@ -243,15 +241,14 @@ namespace ts.server {
/*@internal*/
public readonly getCanonicalFileName: GetCanonicalFileName;
/*@internal*/
readonly packageJsonCache: PackageJsonCache;
/*@internal*/
private importSuggestionsCache = Completions.createImportSuggestionsForFileCache();
/*@internal*/
private dirtyFilesForSuggestions: Map<true> | undefined;
private dirtyFilesForSuggestions: Set<Path> | undefined;
/*@internal*/
private symlinks: ReadonlyMap<string> | undefined;
private symlinks: ReadonlyESMap<string, string> | undefined;
/*@internal*/
autoImportProviderHost: AutoImportProviderProject | false | undefined;
/*@internal*/
constructor(
@@ -282,7 +279,11 @@ namespace ts.server {
this.compilerOptions.allowNonTsExtensions = true;
}
this.languageServiceEnabled = !projectService.syntaxOnly;
this.languageServiceEnabled = true;
if (projectService.syntaxOnly) {
this.compilerOptions.noResolve = true;
this.compilerOptions.types = [];
}
this.setInternalCompilerOptionsForEmittingJsFiles();
const host = this.projectService.host;
@@ -296,13 +297,14 @@ namespace ts.server {
// Use the current directory as resolution root only if the project created using current directory string
this.resolutionCache = createResolutionCache(this, currentDirectory && this.currentDirectory, /*logChangesWhenResolvingModule*/ true);
this.languageService = createLanguageService(this, this.documentRegistry, projectService.syntaxOnly);
this.languageService = createLanguageService(this, this.documentRegistry, this.projectService.syntaxOnly);
if (lastFileExceededProgramSize) {
this.disableLanguageService(lastFileExceededProgramSize);
}
this.markAsDirty();
this.projectService.pendingEnsureProjectForOpenFiles = true;
this.packageJsonCache = createPackageJsonCache(this);
if (projectKind !== ProjectKind.AutoImportProvider) {
this.projectService.pendingEnsureProjectForOpenFiles = true;
}
}
isKnownTypesPackageName(name: string): boolean {
@@ -322,7 +324,7 @@ namespace ts.server {
}
/*@internal*/
getProbableSymlinks(files: readonly SourceFile[]): ReadonlyMap<string> {
getProbableSymlinks(files: readonly SourceFile[]): ReadonlyESMap<string, string> {
return this.symlinks || (this.symlinks = discoverProbableSymlinks(
files,
this.getCanonicalFileName,
@@ -479,6 +481,29 @@ namespace ts.server {
);
}
/*@internal*/
clearInvalidateResolutionOfFailedLookupTimer() {
return this.projectService.throttledOperations.cancel(`${this.getProjectName()}FailedLookupInvalidation`);
}
/*@internal*/
scheduleInvalidateResolutionsOfFailedLookupLocations() {
this.projectService.throttledOperations.schedule(`${this.getProjectName()}FailedLookupInvalidation`, /*delay*/ 1000, () => {
if (this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
}
});
}
/*@internal*/
invalidateResolutionsOfFailedLookupLocations() {
if (this.clearInvalidateResolutionOfFailedLookupTimer() &&
this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
this.markAsDirty();
this.projectService.delayEnsureProjectForOpenFiles();
}
}
/*@internal*/
onInvalidatedResolution() {
this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
@@ -497,9 +522,13 @@ namespace ts.server {
);
}
/*@internal*/
hasChangedAutomaticTypeDirectiveNames() {
return this.resolutionCache.hasChangedAutomaticTypeDirectiveNames();
}
/*@internal*/
onChangedAutomaticTypeDirectiveNames() {
this.hasChangedAutomaticTypeDirectiveNames = true;
this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
}
@@ -618,7 +647,7 @@ namespace ts.server {
}
enableLanguageService() {
if (this.languageServiceEnabled || this.projectService.syntaxOnly) {
if (this.languageServiceEnabled) {
return;
}
this.languageServiceEnabled = true;
@@ -630,11 +659,14 @@ namespace ts.server {
if (!this.languageServiceEnabled) {
return;
}
Debug.assert(!this.projectService.syntaxOnly);
this.languageService.cleanupSemanticCache();
this.languageServiceEnabled = false;
this.lastFileExceededProgramSize = lastFileExceededProgramSize;
this.builderState = undefined;
if (this.autoImportProviderHost) {
this.autoImportProviderHost.close();
}
this.autoImportProviderHost = undefined;
this.resolutionCache.closeTypeRootsWatch();
this.clearGeneratedFileWatch();
this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false);
@@ -695,6 +727,7 @@ namespace ts.server {
}
});
}
// Release external files
forEach(this.externalFiles, externalFile => this.detachScriptInfoIfNotRoot(externalFile));
// Always remove root files from the project
@@ -718,11 +751,12 @@ namespace ts.server {
clearMap(this.missingFilesMap, closeFileWatcher);
this.missingFilesMap = undefined!;
}
if (this.packageJsonFilesMap) {
clearMap(this.packageJsonFilesMap, closeFileWatcher);
this.packageJsonFilesMap = undefined;
}
this.clearGeneratedFileWatch();
this.clearInvalidateResolutionOfFailedLookupTimer();
if (this.autoImportProviderHost) {
this.autoImportProviderHost.close();
}
this.autoImportProviderHost = undefined;
// signal language service to release source files acquired from document registry
this.languageService.dispose();
@@ -901,14 +935,14 @@ namespace ts.server {
}
registerFileUpdate(fileName: string) {
(this.updatedFileNames || (this.updatedFileNames = createMap<true>())).set(fileName, true);
(this.updatedFileNames || (this.updatedFileNames = new Set<string>())).add(fileName);
}
/*@internal*/
markFileAsDirty(changedFile: Path) {
this.markAsDirty();
if (!this.importSuggestionsCache.isEmpty()) {
(this.dirtyFilesForSuggestions || (this.dirtyFilesForSuggestions = createMap())).set(changedFile, true);
(this.dirtyFilesForSuggestions || (this.dirtyFilesForSuggestions = new Set())).add(changedFile);
}
}
@@ -919,6 +953,15 @@ namespace ts.server {
}
}
/*@internal*/
markAutoImportProviderAsDirty() {
if (this.autoImportProviderHost === false) {
this.autoImportProviderHost = undefined;
}
this.autoImportProviderHost?.markAsDirty();
this.importSuggestionsCache.clear();
}
/* @internal */
onFileAddedOrRemoved() {
this.hasAddedorRemovedFiles = true;
@@ -945,7 +988,7 @@ namespace ts.server {
// update builder only if language service is enabled
// otherwise tell it to drop its internal state
if (this.languageServiceEnabled) {
if (this.languageServiceEnabled && !this.projectService.syntaxOnly) {
// 1. no changes in structure, no changes in unresolved imports - do nothing
// 2. no changes in structure, unresolved imports were changed - collect unresolved imports for all files
// (can reuse cached imports for files that were not changed)
@@ -962,9 +1005,18 @@ namespace ts.server {
this.lastCachedUnresolvedImportsList = undefined;
}
const isFirstLoad = this.projectProgramVersion === 0;
if (hasNewProgram) {
this.projectProgramVersion++;
}
if (hasAddedorRemovedFiles) {
if (!this.autoImportProviderHost) this.autoImportProviderHost = undefined;
this.autoImportProviderHost?.markAsDirty();
}
if (isFirstLoad) {
// Preload auto import provider so it's not created during completions request
this.getPackageJsonAutoImportProvider();
}
perfLogger.logStopUpdateGraph();
return !hasNewProgram;
}
@@ -1007,7 +1059,6 @@ namespace ts.server {
// - oldProgram is not set - this is a first time updateGraph is called
// - newProgram is different from the old program and structure of the old program was not reused.
const hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused! & StructureIsReused.Completely)));
this.hasChangedAutomaticTypeDirectiveNames = false;
if (hasNewProgram) {
if (oldProgram) {
for (const f of oldProgram.getSourceFiles()) {
@@ -1029,13 +1080,13 @@ namespace ts.server {
// Update the missing file paths watcher
updateMissingFilePathsWatch(
this.program,
this.missingFilesMap || (this.missingFilesMap = createMap()),
this.missingFilesMap || (this.missingFilesMap = new Map()),
// Watch the missing files
missingFilePath => this.addMissingFileWatcher(missingFilePath)
);
if (this.generatedFilesMap) {
const outPath = this.compilerOptions.outFile && this.compilerOptions.out;
const outPath = outFile(this.compilerOptions);
if (isGeneratedFileWatcher(this.generatedFilesMap)) {
// --out
if (!outPath || !this.isValidGeneratedFileWatcher(
@@ -1052,7 +1103,7 @@ namespace ts.server {
}
else {
this.generatedFilesMap.forEach((watcher, source) => {
const sourceFile = this.program!.getSourceFileByPath(source as Path);
const sourceFile = this.program!.getSourceFileByPath(source);
if (!sourceFile ||
sourceFile.resolvedPath !== source ||
!this.isValidGeneratedFileWatcher(
@@ -1060,7 +1111,7 @@ namespace ts.server {
watcher
)) {
closeFileWatcherOf(watcher);
(this.generatedFilesMap as Map<GeneratedFileWatcher>).delete(source);
(this.generatedFilesMap as ESMap<string, GeneratedFileWatcher>).delete(source);
}
});
}
@@ -1068,7 +1119,7 @@ namespace ts.server {
}
// Watch the type locations that would be added to program as part of automatic type resolutions
if (this.languageServiceEnabled) {
if (this.languageServiceEnabled && !this.projectService.syntaxOnly) {
this.resolutionCache.updateTypeRootsWatch();
}
}
@@ -1109,7 +1160,7 @@ namespace ts.server {
removed => this.detachScriptInfoFromProject(removed)
);
const elapsed = timestamp() - start;
this.projectService.sendUpdateGraphPerformanceEvent(elapsed);
this.sendPerformanceEvent("UpdateGraph", elapsed);
this.writeLog(`Finishing updateGraphWorker: Project: ${this.getProjectName()} Version: ${this.getProjectVersion()} structureChanged: ${hasNewProgram} Elapsed: ${elapsed}ms`);
if (this.hasAddedorRemovedFiles) {
this.print(/*writeProjectFileNames*/ true);
@@ -1120,6 +1171,11 @@ namespace ts.server {
return hasNewProgram;
}
/* @internal */
sendPerformanceEvent(kind: PerformanceEvent["kind"], durationMs: number) {
this.projectService.sendPerformanceEvent(kind, durationMs);
}
/*@internal*/
private sourceFileHasChangedOwnImportSuggestions(oldSourceFile: SourceFile | undefined, newSourceFile: SourceFile | undefined) {
if (!oldSourceFile && !newSourceFile) {
@@ -1209,7 +1265,7 @@ namespace ts.server {
/* @internal */
addGeneratedFileWatch(generatedFile: string, sourceFile: string) {
if (this.compilerOptions.outFile || this.compilerOptions.out) {
if (outFile(this.compilerOptions)) {
// Single watcher
if (!this.generatedFilesMap) {
this.generatedFilesMap = this.createGeneratedFileWatcher(generatedFile);
@@ -1296,6 +1352,9 @@ namespace ts.server {
this.writeLog(`Project '${this.projectName}' (${ProjectKind[this.projectKind]})`);
this.writeLog(this.filesToString(writeProjectFileNames && this.projectService.logger.hasLevel(LogLevel.verbose)));
this.writeLog("-----------------------------------------------");
if (this.autoImportProviderHost) {
this.autoImportProviderHost.print(/*writeProjectFileNames*/ false);
}
}
setCompilerOptions(compilerOptions: CompilerOptions) {
@@ -1328,11 +1387,11 @@ namespace ts.server {
getChangesSinceVersion(lastKnownVersion?: number, includeProjectReferenceRedirectInfo?: boolean): ProjectFilesWithTSDiagnostics {
const includeProjectReferenceRedirectInfoIfRequested =
includeProjectReferenceRedirectInfo
? (files: Map<boolean>) => arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]): protocol.FileWithProjectReferenceRedirectInfo => ({
? (files: ESMap<string, boolean>) => arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]): protocol.FileWithProjectReferenceRedirectInfo => ({
fileName,
isSourceOfProjectReferenceRedirect
}))
: (files: Map<boolean>) => arrayFrom(files.keys());
: (files: ESMap<string, boolean>) => arrayFrom(files.keys());
// Update the graph only if initial configured project load is not pending
if (!this.isInitialLoadPending()) {
@@ -1367,8 +1426,8 @@ namespace ts.server {
info => info.isSourceOfProjectReferenceRedirect
);
const added: Map<boolean> = new Map<boolean>();
const removed: Map<boolean> = new Map<boolean>();
const added: ESMap<string, boolean> = new Map<string, boolean>();
const removed: ESMap<string, boolean> = new Map<string, boolean>();
const updated: string[] = updatedFileNames ? arrayFrom(updatedFileNames.keys()) : [];
const updatedRedirects: protocol.FileWithProjectReferenceRedirectInfo[] = [];
@@ -1546,37 +1605,14 @@ namespace ts.server {
/*@internal*/
getPackageJsonsVisibleToFile(fileName: string, rootDir?: string): readonly PackageJsonInfo[] {
const packageJsonCache = this.packageJsonCache;
const watchPackageJsonFile = this.watchPackageJsonFile.bind(this);
const toPath = this.toPath.bind(this);
const rootPath = rootDir && toPath(rootDir);
const filePath = toPath(fileName);
const result: PackageJsonInfo[] = [];
forEachAncestorDirectory(getDirectoryPath(filePath), function processDirectory(directory): boolean | undefined {
switch (packageJsonCache.directoryHasPackageJson(directory)) {
// Sync and check same directory again
case Ternary.Maybe:
packageJsonCache.searchDirectoryAndAncestors(directory);
return processDirectory(directory);
// Check package.json
case Ternary.True:
const packageJsonFileName = combinePaths(directory, "package.json");
watchPackageJsonFile(packageJsonFileName);
const info = packageJsonCache.getInDirectory(directory);
if (info) result.push(info);
}
if (rootPath && rootPath === toPath(directory)) {
return true;
}
});
return result;
return this.projectService.getPackageJsonsVisibleToFile(fileName, rootDir);
}
/*@internal*/
onAddPackageJson(path: Path) {
this.packageJsonCache.addOrUpdate(path);
this.watchPackageJsonFile(path);
getPackageJsonsForAutoImport(rootDir?: string): readonly PackageJsonInfo[] {
const packageJsons = this.getPackageJsonsVisibleToFile(combinePaths(this.currentDirectory, inferredTypesContainingFile), rootDir);
this.packageJsonsForAutoImport = new Set(packageJsons.map(p => p.fileName));
return packageJsons;
}
/*@internal*/
@@ -1584,40 +1620,56 @@ namespace ts.server {
return this.importSuggestionsCache;
}
private watchPackageJsonFile(path: Path) {
const watchers = this.packageJsonFilesMap || (this.packageJsonFilesMap = createMap());
if (!watchers.has(path)) {
watchers.set(path, this.projectService.watchFactory.watchFile(
this.projectService.host,
path,
(fileName, eventKind) => {
const path = this.toPath(fileName);
switch (eventKind) {
case FileWatcherEventKind.Created:
return Debug.fail();
case FileWatcherEventKind.Changed:
this.packageJsonCache.addOrUpdate(path);
break;
case FileWatcherEventKind.Deleted:
this.packageJsonCache.delete(path);
watchers.get(path)!.close();
watchers.delete(path);
}
},
PollingInterval.Low,
this.projectService.getWatchOptions(this),
WatchType.PackageJsonFile,
));
/*@internal*/
includePackageJsonAutoImports(): PackageJsonAutoImportPreference {
if (this.projectService.includePackageJsonAutoImports() === PackageJsonAutoImportPreference.None ||
!this.languageServiceEnabled ||
isInsideNodeModules(this.currentDirectory) ||
!this.isDefaultProjectForOpenFiles()) {
return PackageJsonAutoImportPreference.None;
}
return this.projectService.includePackageJsonAutoImports();
}
/*@internal*/
getPackageJsonAutoImportProvider(): Program | undefined {
if (this.autoImportProviderHost === false) {
return undefined;
}
if (this.autoImportProviderHost) {
updateProjectIfDirty(this.autoImportProviderHost);
if (!this.autoImportProviderHost.hasRoots()) {
this.autoImportProviderHost.close();
this.autoImportProviderHost = undefined;
return undefined;
}
return this.autoImportProviderHost.getCurrentProgram();
}
const dependencySelection = this.includePackageJsonAutoImports();
if (dependencySelection) {
this.autoImportProviderHost = AutoImportProviderProject.create(dependencySelection, this, this.projectService.host, this.documentRegistry);
if (this.autoImportProviderHost) {
updateProjectIfDirty(this.autoImportProviderHost);
return this.autoImportProviderHost.getCurrentProgram();
}
}
}
/*@internal*/
private isDefaultProjectForOpenFiles(): boolean {
return !!forEachEntry(
this.projectService.openFiles,
(_, fileName) => this.projectService.tryGetDefaultProjectForFile(toNormalizedPath(fileName)) === this);
}
}
function getUnresolvedImports(program: Program, cachedUnresolvedImportsPerFile: Map<readonly string[]>): SortedReadonlyArray<string> {
function getUnresolvedImports(program: Program, cachedUnresolvedImportsPerFile: ESMap<Path, readonly string[]>): SortedReadonlyArray<string> {
const ambientModules = program.getTypeChecker().getAmbientModules().map(mod => stripQuotes(mod.getName()));
return sortAndDeduplicate(flatMap(program.getSourceFiles(), sourceFile =>
extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile)));
}
function extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules: readonly string[], cachedUnresolvedImportsPerFile: Map<readonly string[]>): readonly string[] {
function extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules: readonly string[], cachedUnresolvedImportsPerFile: ESMap<Path, readonly string[]>): readonly string[] {
return getOrUpdate(cachedUnresolvedImportsPerFile, file.path, () => {
if (!file.resolvedModules) return emptyArray;
let unresolvedImports: string[] | undefined;
@@ -1633,19 +1685,17 @@ namespace ts.server {
});
}
function createProjectNameFactoryWithCounter(nameFactory: (counter: number) => string) {
let nextId = 1;
return () => nameFactory(nextId++);
}
/**
* If a file is opened and no tsconfig (or jsconfig) is found,
* the file and its imports/references are put into an InferredProject.
*/
export class InferredProject extends Project {
private static readonly newName = (() => {
let nextId = 1;
return () => {
const id = nextId;
nextId++;
return makeInferredProjectName(id);
};
})();
private static readonly newName = createProjectNameFactoryWithCounter(makeInferredProjectName);
private _isJsInferredProject = false;
@@ -1687,7 +1737,7 @@ namespace ts.server {
watchOptions: WatchOptions | undefined,
projectRootPath: NormalizedPath | undefined,
currentDirectory: string | undefined,
pluginConfigOverrides: Map<any> | undefined) {
pluginConfigOverrides: ESMap<string, any> | undefined) {
super(InferredProject.newName(),
ProjectKind.Inferred,
projectService,
@@ -1747,12 +1797,151 @@ namespace ts.server {
getTypeAcquisition(): TypeAcquisition {
return {
enable: allRootFilesAreJsOrDts(this),
include: [],
exclude: []
include: ts.emptyArray,
exclude: ts.emptyArray
};
}
}
export class AutoImportProviderProject extends Project {
private static readonly newName = createProjectNameFactoryWithCounter(makeAutoImportProviderProjectName);
/*@internal*/
static getRootFileNames(dependencySelection: PackageJsonAutoImportPreference, hostProject: Project, moduleResolutionHost: ModuleResolutionHost, compilerOptions: CompilerOptions): string[] {
if (!dependencySelection) {
return ts.emptyArray;
}
let dependencyNames: Set<string> | undefined;
let rootNames: string[] | undefined;
const rootFileName = combinePaths(hostProject.currentDirectory, inferredTypesContainingFile);
const packageJsons = hostProject.getPackageJsonsForAutoImport(combinePaths(hostProject.currentDirectory, rootFileName));
for (const packageJson of packageJsons) {
packageJson.dependencies?.forEach((_, dependenyName) => addDependency(dependenyName));
packageJson.peerDependencies?.forEach((_, dependencyName) => addDependency(dependencyName));
if (dependencySelection === PackageJsonAutoImportPreference.All) {
packageJson.devDependencies?.forEach((_, dependencyName) => addDependency(dependencyName));
}
}
if (dependencyNames) {
const resolutions = map(arrayFrom(dependencyNames.keys()), name => resolveTypeReferenceDirective(
name,
rootFileName,
compilerOptions,
moduleResolutionHost));
for (const resolution of resolutions) {
if (resolution.resolvedTypeReferenceDirective?.resolvedFileName && !hostProject.getCurrentProgram()!.getSourceFile(resolution.resolvedTypeReferenceDirective.resolvedFileName)) {
rootNames = append(rootNames, resolution.resolvedTypeReferenceDirective.resolvedFileName);
}
}
}
return rootNames || ts.emptyArray;
function addDependency(dependency: string) {
if (!startsWith(dependency, "@types/")) {
(dependencyNames || (dependencyNames = new Set())).add(dependency);
}
}
}
/*@internal*/
static create(dependencySelection: PackageJsonAutoImportPreference, hostProject: Project, moduleResolutionHost: ModuleResolutionHost, documentRegistry: DocumentRegistry): AutoImportProviderProject | undefined {
if (dependencySelection === PackageJsonAutoImportPreference.None) {
return undefined;
}
const compilerOptions: CompilerOptions = {
...hostProject.getCompilerOptions(),
noLib: true,
diagnostics: false,
skipLibCheck: true,
types: ts.emptyArray,
lib: ts.emptyArray,
sourceMap: false
};
const rootNames = this.getRootFileNames(dependencySelection, hostProject, moduleResolutionHost, compilerOptions);
if (!rootNames.length) {
return undefined;
}
return new AutoImportProviderProject(hostProject, rootNames, documentRegistry, compilerOptions);
}
private rootFileNames: string[] | undefined;
/*@internal*/
constructor(
private hostProject: Project,
initialRootNames: string[],
documentRegistry: DocumentRegistry,
compilerOptions: CompilerOptions,
) {
super(AutoImportProviderProject.newName(),
ProjectKind.AutoImportProvider,
hostProject.projectService,
documentRegistry,
/*hasExplicitListOfFiles*/ false,
/*lastFileExceededProgramSize*/ undefined,
compilerOptions,
/*compileOnSaveEnabled*/ false,
hostProject.getWatchOptions(),
hostProject.projectService.host,
hostProject.currentDirectory);
this.rootFileNames = initialRootNames;
}
isOrphan() {
return true;
}
updateGraph() {
let rootFileNames = this.rootFileNames;
if (!rootFileNames) {
rootFileNames = AutoImportProviderProject.getRootFileNames(
this.hostProject.includePackageJsonAutoImports(),
this.hostProject,
this.projectService.host,
this.getCompilationSettings());
}
this.projectService.setFileNamesOfAutoImportProviderProject(this, rootFileNames);
this.rootFileNames = rootFileNames;
this.hostProject.getImportSuggestionsCache().clear();
return super.updateGraph();
}
markAsDirty() {
this.rootFileNames = undefined;
super.markAsDirty();
}
getScriptFileNames() {
return this.rootFileNames || ts.emptyArray;
}
getLanguageService(): never {
throw new Error("AutoImportProviderProject language service should never be used. To get the program, use `project.getCurrentProgram()`.");
}
markAutoImportProviderAsDirty(): never {
throw new Error("AutoImportProviderProject is an auto import provider; use `markAsDirty()` instead.");
}
/*@internal*/
includePackageJsonAutoImports() {
return PackageJsonAutoImportPreference.None;
}
getTypeAcquisition(): TypeAcquisition {
return { enable: false };
}
}
/**
* If a file is opened, the server will look for a tsconfig (or jsconfig)
* and if successful create a ConfiguredProject for it.
@@ -1762,7 +1951,7 @@ namespace ts.server {
private typeAcquisition!: TypeAcquisition; // TODO: GH#18217
/* @internal */
configFileWatcher: FileWatcher | undefined;
private directoriesWatchedForWildcards: Map<WildcardDirectoryWatcher> | undefined;
private directoriesWatchedForWildcards: ESMap<string, WildcardDirectoryWatcher> | undefined;
readonly canonicalConfigFilePath: NormalizedPath;
/* @internal */
@@ -1788,7 +1977,7 @@ namespace ts.server {
/** Potential project references before the project is actually loaded (read config file) */
/*@internal*/
potentialProjectReferences: Map<true> | undefined;
potentialProjectReferences: Set<string> | undefined;
/*@internal*/
projectOptions?: ProjectOptions | true;
@@ -1914,7 +2103,7 @@ namespace ts.server {
/*@internal*/
setPotentialProjectReference(canonicalConfigPath: NormalizedPath) {
Debug.assert(this.isInitialLoadPending());
(this.potentialProjectReferences || (this.potentialProjectReferences = createMap())).set(canonicalConfigPath, true);
(this.potentialProjectReferences || (this.potentialProjectReferences = new Set())).add(canonicalConfigPath);
}
/*@internal*/
@@ -1924,7 +2113,7 @@ namespace ts.server {
}
/*@internal*/
enablePluginsWithOptions(options: CompilerOptions, pluginConfigOverrides: Map<any> | undefined) {
enablePluginsWithOptions(options: CompilerOptions, pluginConfigOverrides: ESMap<string, any> | undefined) {
const host = this.projectService.host;
if (!host.require) {
@@ -1979,7 +2168,7 @@ namespace ts.server {
}
/*@internal*/
watchWildcards(wildcardDirectories: Map<WatchDirectoryFlags>) {
watchWildcards(wildcardDirectories: ESMap<string, WatchDirectoryFlags>) {
updateWatchingWildcardDirectories(
this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = createMap()),
wildcardDirectories,
@@ -2067,8 +2256,8 @@ namespace ts.server {
return forEachEntry(
configFileExistenceInfo.openFilesImpactedByConfigFile,
(_value, infoPath) => isSolution ?
!!this.getDefaultChildProjectFromSolution(this.projectService.getScriptInfoForPath(infoPath as Path)!) :
this.containsScriptInfo(this.projectService.getScriptInfoForPath(infoPath as Path)!)
!!this.getDefaultChildProjectFromSolution(this.projectService.getScriptInfoForPath(infoPath)!) :
this.containsScriptInfo(this.projectService.getScriptInfoForPath(infoPath)!)
) || false;
}
@@ -2102,7 +2291,7 @@ namespace ts.server {
lastFileExceededProgramSize: string | undefined,
public compileOnSaveEnabled: boolean,
projectFilePath?: string,
pluginConfigOverrides?: Map<any>,
pluginConfigOverrides?: ESMap<string, any>,
watchOptions?: WatchOptions) {
super(externalProjectName,
ProjectKind.External,
+20 -1
View File
@@ -259,6 +259,10 @@ namespace ts.server.protocol {
* Time spent updating the program graph, in milliseconds.
*/
updateGraphDurationMs?: number;
/**
* The time spent creating or updating the auto-import program, in milliseconds.
*/
createAutoImportProviderProgramDurationMs?: number;
}
/**
@@ -509,6 +513,7 @@ namespace ts.server.protocol {
code: number;
/** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */
reportsUnnecessary?: {};
reportsDeprecated?: {};
relatedInformation?: DiagnosticRelatedInformation[];
}
@@ -557,7 +562,11 @@ namespace ts.server.protocol {
command: CommandTypes.GetApplicableRefactors;
arguments: GetApplicableRefactorsRequestArgs;
}
export type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs;
export type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs & {
triggerReason?: RefactorTriggerReason
};
export type RefactorTriggerReason = "implicit" | "invoked";
/**
* Response is a list of available refactorings.
@@ -2185,6 +2194,11 @@ namespace ts.server.protocol {
* and therefore may not be accurate.
*/
isFromUncheckedFile?: true;
/**
* If true, this completion was for an auto-import of a module not yet in the program, but listed
* in the project package.json.
*/
isPackageJsonImport?: true;
}
/**
@@ -2562,6 +2576,8 @@ namespace ts.server.protocol {
reportsUnnecessary?: {};
reportsDeprecated?: {};
/**
* Any related spans the diagnostic may have, such as other locations relevant to an error, such as declarartion sites
*/
@@ -3093,9 +3109,11 @@ namespace ts.server.protocol {
export interface CallHierarchyItem {
name: string;
kind: ScriptElementKind;
kindModifiers?: string
file: string;
span: TextSpan;
selectionSpan: TextSpan;
containerName?: string;
}
export interface CallHierarchyIncomingCall {
@@ -3200,6 +3218,7 @@ namespace ts.server.protocol {
readonly lazyConfiguredProjectsFromExternalProject?: boolean;
readonly providePrefixAndSuffixTextForRename?: boolean;
readonly allowRenameOfImportPath?: boolean;
readonly includePackageJsonAutoImports?: "exclude-dev" | "all" | "none";
}
export interface CompilerOptions {
+21 -5
View File
@@ -286,7 +286,7 @@ namespace ts.server {
/*@internal*/
export interface SourceMapFileWatcher {
watcher: FileWatcher;
sourceInfos?: Map<true>;
sourceInfos?: Set<Path>;
}
export class ScriptInfo {
@@ -324,7 +324,7 @@ namespace ts.server {
/*@internal*/
declarationInfoPath?: Path;
/*@internal*/
sourceInfos?: Map<true>;
sourceInfos?: Set<Path>;
/*@internal*/
documentPositionMapper?: DocumentPositionMapper | false;
@@ -491,7 +491,7 @@ namespace ts.server {
case 0:
return Errors.ThrowNoProject();
case 1:
return this.containingProjects[0];
return ensureNotAutoImportProvider(this.containingProjects[0]);
default:
// If this file belongs to multiple projects, below is the order in which default project is used
// - for open script info, its default configured project during opening is default if info is part of it
@@ -501,6 +501,7 @@ namespace ts.server {
// - first inferred project
let firstExternalProject: ExternalProject | undefined;
let firstConfiguredProject: ConfiguredProject | undefined;
let firstInferredProject: InferredProject | undefined;
let firstNonSourceOfProjectReferenceRedirect: ConfiguredProject | undefined;
let defaultConfiguredProject: ConfiguredProject | false | undefined;
for (let index = 0; index < this.containingProjects.length; index++) {
@@ -521,12 +522,15 @@ namespace ts.server {
else if (!firstExternalProject && isExternalProject(project)) {
firstExternalProject = project;
}
else if (!firstInferredProject && isInferredProject(project)) {
firstInferredProject = project;
}
}
return defaultConfiguredProject ||
return ensureNotAutoImportProvider(defaultConfiguredProject ||
firstNonSourceOfProjectReferenceRedirect ||
firstConfiguredProject ||
firstExternalProject ||
this.containingProjects[0];
firstInferredProject);
}
}
@@ -607,6 +611,11 @@ namespace ts.server {
return !forEach(this.containingProjects, p => !p.isOrphan());
}
/*@internal*/
isContainedByAutoImportProvider() {
return some(this.containingProjects, p => p.projectKind === ProjectKind.AutoImportProvider);
}
/**
* @param line 1 based index
*/
@@ -650,6 +659,13 @@ namespace ts.server {
}
}
function ensureNotAutoImportProvider(project: Project | undefined) {
if (!project || project.projectKind === ProjectKind.AutoImportProvider) {
return Errors.ThrowNoProject();
}
return project;
}
function failIfInvalidPosition(position: number) {
Debug.assert(typeof position === "number", `Expected position ${position} to be a number.`);
Debug.assert(position >= 0, `Expected position to be non-negative.`);
+81 -25
View File
@@ -56,6 +56,7 @@ namespace ts.server {
code: diag.code,
category: diagnosticCategoryName(diag),
reportsUnnecessary: diag.reportsUnnecessary,
reportsDeprecated: diag.reportsDeprecated,
source: diag.source,
relatedInformation: map(diag.relatedInformation, formatRelatedInformation),
};
@@ -100,6 +101,7 @@ namespace ts.server {
code,
category,
reportsUnnecessary: diag.reportsUnnecessary,
reportsDeprecated: diag.reportsDeprecated,
source,
relatedInformation: map(diag.relatedInformation, formatRelatedInformation),
};
@@ -260,7 +262,7 @@ namespace ts.server {
type Projects = readonly Project[] | {
readonly projects: readonly Project[];
readonly symLinkedProjects: MultiMap<Project>;
readonly symLinkedProjects: MultiMap<Path, Project>;
};
/**
@@ -275,7 +277,7 @@ namespace ts.server {
const outputs = flatMapToMutable(isArray(projects) ? projects : projects.projects, project => action(project, defaultValue));
if (!isArray(projects) && projects.symLinkedProjects) {
projects.symLinkedProjects.forEach((projects, path) => {
const value = getValue(path as Path);
const value = getValue(path);
outputs.push(...flatMap(projects, project => action(project, value)));
});
}
@@ -421,7 +423,7 @@ namespace ts.server {
): void {
const projectService = defaultProject.projectService;
let toDo: ProjectAndLocation<TLocation>[] | undefined;
const seenProjects = createMap<true>();
const seenProjects = new Set<string>();
forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, (project, path) => {
// TLocation should be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid.
const location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined) as TLocation;
@@ -494,7 +496,7 @@ namespace ts.server {
location: TLocation,
projectService: ProjectService,
toDo: ProjectAndLocation<TLocation>[] | undefined,
seenProjects: Map<true>,
seenProjects: Set<string>,
cb: CombineProjectOutputCallback<TLocation>,
): ProjectAndLocation<TLocation>[] | undefined {
if (project.getCancellationToken().isCancellationRequested()) return undefined; // Skip rest of toDo if cancelled
@@ -515,7 +517,7 @@ namespace ts.server {
if (symlinkedProjectsMap) {
symlinkedProjectsMap.forEach((symlinkedProjects, symlinkedPath) => {
for (const symlinkedProject of symlinkedProjects) {
addToTodo(symlinkedProject, { fileName: symlinkedPath, pos: originalLocation.pos } as TLocation, toDo!, seenProjects);
addToTodo(symlinkedProject, { fileName: symlinkedPath as string, pos: originalLocation.pos } as TLocation, toDo!, seenProjects);
}
});
}
@@ -524,12 +526,12 @@ namespace ts.server {
return toDo;
}
function addToTodo<TLocation extends DocumentPosition | undefined>(project: Project, location: TLocation, toDo: Push<ProjectAndLocation<TLocation>>, seenProjects: Map<true>): void {
function addToTodo<TLocation extends DocumentPosition | undefined>(project: Project, location: TLocation, toDo: Push<ProjectAndLocation<TLocation>>, seenProjects: Set<string>): void {
if (addToSeen(seenProjects, project)) toDo.push({ project, location });
}
function addToSeen(seenProjects: Map<true>, project: Project) {
return ts.addToSeen(seenProjects, getProjectKey(project));
function addToSeen(seenProjects: Set<string>, project: Project) {
return tryAddToSet(seenProjects, getProjectKey(project));
}
function getProjectKey(project: Project) {
@@ -575,6 +577,42 @@ namespace ts.server {
undefined;
}
const invalidSyntaxOnlyCommands: readonly CommandNames[] = [
CommandNames.OpenExternalProject,
CommandNames.OpenExternalProjects,
CommandNames.CloseExternalProject,
CommandNames.SynchronizeProjectList,
CommandNames.EmitOutput,
CommandNames.CompileOnSaveAffectedFileList,
CommandNames.CompileOnSaveEmitFile,
CommandNames.CompilerOptionsDiagnosticsFull,
CommandNames.EncodedSemanticClassificationsFull,
CommandNames.SemanticDiagnosticsSync,
CommandNames.SyntacticDiagnosticsSync,
CommandNames.SuggestionDiagnosticsSync,
CommandNames.Geterr,
CommandNames.GeterrForProject,
CommandNames.Reload,
CommandNames.ReloadProjects,
CommandNames.GetCodeFixes,
CommandNames.GetCodeFixesFull,
CommandNames.GetCombinedCodeFix,
CommandNames.GetCombinedCodeFixFull,
CommandNames.ApplyCodeActionCommand,
CommandNames.GetSupportedCodeFixes,
CommandNames.GetApplicableRefactors,
CommandNames.GetEditsForRefactor,
CommandNames.GetEditsForRefactorFull,
CommandNames.OrganizeImports,
CommandNames.OrganizeImportsFull,
CommandNames.GetEditsForFileRename,
CommandNames.GetEditsForFileRenameFull,
CommandNames.ConfigurePlugin,
CommandNames.PrepareCallHierarchy,
CommandNames.ProvideCallHierarchyIncomingCalls,
CommandNames.ProvideCallHierarchyOutgoingCalls,
];
export interface SessionOptions {
host: ServerHost;
cancellationToken: ServerCancellationToken;
@@ -606,7 +644,7 @@ namespace ts.server {
protected projectService: ProjectService;
private changeSeq = 0;
private updateGraphDurationMs: number | undefined;
private performanceData: protocol.PerformanceData | undefined;
private currentRequestId!: number;
private errorCheck: MultistepOperation;
@@ -667,18 +705,36 @@ namespace ts.server {
this.projectService = new ProjectService(settings);
this.projectService.setPerformanceEventHandler(this.performanceEventHandler.bind(this));
this.gcTimer = new GcTimer(this.host, /*delay*/ 7000, this.logger);
// Make sure to setup handlers to throw error for not allowed commands on syntax server;
if (this.projectService.syntaxOnly) {
invalidSyntaxOnlyCommands.forEach(commandName =>
this.handlers.set(commandName, request => {
throw new Error(`Request: ${request.command} not allowed on syntaxServer`);
})
);
}
}
private sendRequestCompletedEvent(requestId: number): void {
this.event<protocol.RequestCompletedEventBody>({ request_seq: requestId }, "requestCompleted");
}
private addPerformanceData(key: keyof protocol.PerformanceData, value: number) {
if (!this.performanceData) {
this.performanceData = {};
}
this.performanceData[key] = (this.performanceData[key] ?? 0) + value;
}
private performanceEventHandler(event: PerformanceEvent) {
switch (event.kind) {
case "UpdateGraph": {
this.updateGraphDurationMs = (this.updateGraphDurationMs || 0) + event.durationMs;
case "UpdateGraph":
this.addPerformanceData("updateGraphDurationMs", event.durationMs);
break;
case "CreatePackageJsonAutoImportProvider":
this.addPerformanceData("createAutoImportProviderProgramDurationMs", event.durationMs);
break;
}
}
}
@@ -820,11 +876,7 @@ namespace ts.server {
command: cmdName,
request_seq: reqSeq,
success,
performanceData: !this.updateGraphDurationMs
? undefined
: {
updateGraphDurationMs: this.updateGraphDurationMs,
},
performanceData: this.performanceData
};
if (success) {
@@ -1018,6 +1070,7 @@ namespace ts.server {
startLocation: (d.file && convertToLocation(getLineAndCharacterOfPosition(d.file, d.start!)))!, // TODO: GH#18217
endLocation: (d.file && convertToLocation(getLineAndCharacterOfPosition(d.file, d.start! + d.length!)))!, // TODO: GH#18217
reportsUnnecessary: d.reportsUnnecessary,
reportsDeprecated: d.reportsDeprecated,
relatedInformation: map(d.relatedInformation, formatRelatedInformation)
}));
}
@@ -1047,6 +1100,7 @@ namespace ts.server {
startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start!), // TODO: GH#18217
endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start! + d.length!),
reportsUnnecessary: d.reportsUnnecessary,
reportsDeprecated: d.reportsDeprecated,
relatedInformation: map(d.relatedInformation, formatRelatedInformation),
});
}
@@ -1253,9 +1307,9 @@ namespace ts.server {
}
private getJsxClosingTag(args: protocol.JsxClosingTagRequestArgs): TextInsertion | undefined {
const { file, project } = this.getFileAndProject(args);
const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
const position = this.getPositionInFile(args, file);
const tag = project.getLanguageService().getJsxClosingTagAtPosition(file, position);
const tag = languageService.getJsxClosingTagAtPosition(file, position);
return tag === undefined ? undefined : { newText: tag.newText, caretOffset: 0 };
}
@@ -1306,7 +1360,7 @@ namespace ts.server {
private getProjects(args: protocol.FileRequestArgs, getScriptInfoEnsuringProjectsUptoDate?: boolean, ignoreNoProjectError?: boolean): Projects {
let projects: readonly Project[] | undefined;
let symLinkedProjects: MultiMap<Project> | undefined;
let symLinkedProjects: MultiMap<Path, Project> | undefined;
if (args.projectFileName) {
const project = this.getProject(args.projectFileName);
if (project) {
@@ -1661,10 +1715,10 @@ namespace ts.server {
const prefix = args.prefix || "";
const entries = mapDefined<CompletionEntry, protocol.CompletionEntry>(completions.entries, entry => {
if (completions.isMemberCompletion || startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) {
const { name, kind, kindModifiers, sortText, insertText, replacementSpan, hasAction, source, isRecommended } = entry;
const { name, kind, kindModifiers, sortText, insertText, replacementSpan, hasAction, source, isRecommended, isPackageJsonImport } = entry;
const convertedSpan = replacementSpan ? toProtocolTextSpan(replacementSpan, scriptInfo) : undefined;
// Use `hasAction || undefined` to avoid serializing `false`.
return { name, kind, kindModifiers, sortText, insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source, isRecommended };
return { name, kind, kindModifiers, sortText, insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source, isRecommended, isPackageJsonImport };
}
}).sort((a, b) => compareStringsCaseSensitiveUI(a.name, b.name));
@@ -1721,7 +1775,7 @@ namespace ts.server {
return {
projectFileName: project.getProjectName(),
fileNames: project.getCompileOnSaveAffectedFileList(info),
projectUsesOutFile: !!compilationSettings.outFile || !!compilationSettings.out
projectUsesOutFile: !!outFile(compilationSettings)
};
}
);
@@ -1882,6 +1936,7 @@ namespace ts.server {
const bakedItem: protocol.NavtoItem = {
name: navItem.name,
kind: navItem.kind,
kindModifiers: navItem.kindModifiers,
isCaseSensitive: navItem.isCaseSensitive,
matchKind: navItem.matchKind,
file: navItem.fileName,
@@ -1975,7 +2030,7 @@ namespace ts.server {
private getApplicableRefactors(args: protocol.GetApplicableRefactorsRequestArgs): protocol.ApplicableRefactorInfo[] {
const { file, project } = this.getFileAndProject(args);
const scriptInfo = project.getScriptInfoForNormalizedPath(file)!;
return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file));
return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file), args.triggerReason);
}
private getEditsForRefactor(args: protocol.GetEditsForRefactorRequestArgs, simplifiedResult: boolean): RefactorEditInfo | protocol.RefactorEditInfo {
@@ -2290,6 +2345,7 @@ namespace ts.server {
return {
name: item.name,
kind: item.kind,
kindModifiers: item.kindModifiers,
file: item.file,
span: toProtocolTextSpan(item.span, scriptInfo),
selectionSpan: toProtocolTextSpan(item.selectionSpan, scriptInfo)
@@ -2780,7 +2836,7 @@ namespace ts.server {
public onMessage(message: string) {
this.gcTimer.scheduleCollect();
this.updateGraphDurationMs = undefined;
this.performanceData = undefined;
let start: number[] | undefined;
if (this.logger.hasLevel(LogLevel.requestTime)) {
+3 -3
View File
@@ -5,7 +5,7 @@ namespace ts.server {
}
// for backwards-compatibility
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
// eslint-disable-next-line @typescript-eslint/naming-convention
export interface ITypingsInstaller {
isKnownTypesPackageName(name: string): boolean;
installPackage(options: InstallPackageOptionsWithProject): Promise<ApplyCodeActionCommandResult>;
@@ -41,7 +41,7 @@ namespace ts.server {
if ((arr1 || emptyArray).length === 0 && (arr2 || emptyArray).length === 0) {
return true;
}
const set: Map<boolean> = createMap<boolean>();
const set: ESMap<string, boolean> = createMap<boolean>();
let unique = 0;
for (const v of arr1!) {
@@ -83,7 +83,7 @@ namespace ts.server {
/*@internal*/
export class TypingsCache {
private readonly perProjectCache: Map<TypingsCacheEntry> = createMap<TypingsCacheEntry>();
private readonly perProjectCache: ESMap<string, TypingsCacheEntry> = createMap<TypingsCacheEntry>();
constructor(private readonly installer: ITypingsInstaller) {
}
+8 -1
View File
@@ -1,7 +1,7 @@
/* @internal */
namespace ts.server {
export class ThrottledOperations {
private readonly pendingTimeouts: Map<any> = createMap<any>();
private readonly pendingTimeouts: ESMap<string, any> = createMap<any>();
private readonly logger?: Logger | undefined;
constructor(private readonly host: ServerHost, logger: Logger) {
this.logger = logger.hasLevel(LogLevel.verbose) ? logger : undefined;
@@ -26,6 +26,13 @@ namespace ts.server {
}
}
public cancel(operationId: string) {
const pendingTimeout = this.pendingTimeouts.get(operationId);
if (!pendingTimeout) return false;
this.host.clearTimeout(pendingTimeout);
return this.pendingTimeouts.delete(operationId);
}
private static run(self: ThrottledOperations, operationId: string, cb: () => void) {
perfLogger.logStartScheduledOperation(operationId);
self.pendingTimeouts.delete(operationId);
+5
View File
@@ -117,6 +117,11 @@ namespace ts.server {
return `/dev/null/inferredProject${counter}*`;
}
/*@internal*/
export function makeAutoImportProviderProjectName(counter: number) {
return `/dev/null/autoImportProviderProject${counter}*`;
}
export function createSortedArray<T>(): SortedArray<T> {
return [] as any as SortedArray<T>; // TODO: GH#19873
}