TypeScript/src/server/typingsInstaller/typingsInstaller.ts

454 lines
22 KiB
TypeScript
Raw Normal View History

/// <reference path="../../compiler/core.ts" />
/// <reference path="../../compiler/moduleNameResolver.ts" />
2016-08-14 20:16:11 +02:00
/// <reference path="../../services/jsTyping.ts"/>
/// <reference path="../types.ts"/>
/// <reference path="../shared.ts"/>
2016-08-12 20:04:43 +02:00
namespace ts.server.typingsInstaller {
2016-08-26 01:25:34 +02:00
interface NpmConfig {
devDependencies: MapLike<any>;
}
export interface Log {
isEnabled(): boolean;
writeLine(text: string): void;
}
2016-08-17 23:47:54 +02:00
const nullLog: Log = {
isEnabled: () => false,
writeLine: noop
2016-08-17 23:47:54 +02:00
};
2018-01-04 23:04:14 +01:00
const timestampsFileName = "timestamps.json";
function typingToFileName(cachePath: string, packageName: string, installTypingHost: InstallTypingHost, log: Log): string {
try {
const result = resolveModuleName(packageName, combinePaths(cachePath, "index.d.ts"), { moduleResolution: ModuleResolutionKind.NodeJs }, installTypingHost);
return result.resolvedModule && result.resolvedModule.resolvedFileName;
}
catch (e) {
if (log.isEnabled()) {
log.writeLine(`Failed to resolve ${packageName} in folder '${cachePath}': ${(<Error>e).message}`);
}
return undefined;
}
}
export type RequestCompletedAction = (success: boolean) => void;
interface PendingRequest {
2016-09-20 23:14:51 +02:00
requestId: number;
packageNames: string[];
2016-09-20 23:14:51 +02:00
cwd: string;
Merge release-2.1 into master (#12157) * Update LKG * Update version * Update LKG * Skip overloads with too-short function parameters If the parameter of an overload is a function and the argument is also a function, skip the overload if the parameter has fewer arguments than the argument does. That overload cannot possibly apply, and should not participate in, for example, contextual typing. Example: ```ts interface I { (a: number): void; (b: string, c): void; } declare function f(i: I): void; f((x, y) => {}); ``` This code now skips the first overload instead of considering. This was a longstanding bug but was only uncovered now that more functions expressions are context sensitive. * Test skip overloads w/too-short function params 1. Update changed baseline. 2. Add a new test with baseline. * Minor style improvements * Ignore optionality when skipping overloads * Do not use contextual signatures with too few parameters * isAritySmaller runs later: getNonGenericSignature * rewrite void-returning statements in constructors that capture result of super call (#11868) * rewrite void-returning statements in constructors that capture result of super call * linter * Update LKG * Fix emit inferred type which is a generic type-alias both fully and partially fill type parameters * Add tests and baselines * Skip trying to use alias if there is target type * Update baselines * Add diagnostics to remind adding tsconfig file for certain external project (#11932) * Add diagnostics for certain external project * Show tsconfig suggestion * fix lint error * Address pr * fix comment * Update error message * Flag for not overwrite js files by default without generating errors (#11980) * WIP * Properly naming things * refactor * apply the option to all files and check out options * Fix typo * Update LKG * lockLinter * use local registry to check if typings package exist (#12014) (#12032) use local registry to check if typings package exist * Add test for https://github.com/Microsoft/TypeScript/pull/11980 (#12027) * add test for the fix for overwrite emitting error * cr feedback * enable sending telemetry events to tsserver client (#12034) (#12051) enable sending telemetry events * Update LKG * Reuse subtree transform flags for incrementally parsed nodes (#12088) * Update LKG * Update version * Update LKG * Do not emit "use strict" when targeting es6 or higher or module kind is es2015 and the file is external module * Add tests and baselines * [Release 2.1] fix11754 global augmentation (#12133) * Exclude global augmentation from module resolution logic * Address PR: check using string literal instead of NodeFlags.globalAugmentation * Remove comment
2016-11-10 23:28:34 +01:00
onRequestCompleted: RequestCompletedAction;
}
2016-09-20 23:14:51 +02:00
2017-11-21 01:43:02 +01:00
interface TypeDeclarationTimestampFile {
2018-01-04 23:04:14 +01:00
// entries maps from package names (e.g. "@types/node") to timestamp values (as produced by Date#getTime)
2017-11-21 01:43:02 +01:00
entries: MapLike<number>;
}
function loadTypeDeclarationTimestampFile(typeDeclarationTimestampFilePath: string, host: InstallTypingHost, log: Log): MapLike<number> {
2017-11-21 01:43:02 +01:00
try {
2018-01-04 23:04:14 +01:00
if (log.isEnabled()) {
log.writeLine("Loading type declaration timestamp file.");
2017-11-21 01:43:02 +01:00
}
2018-01-04 23:04:14 +01:00
const content = <TypeDeclarationTimestampFile>JSON.parse(host.readFile(typeDeclarationTimestampFilePath));
return content.entries || {};
2017-11-21 01:43:02 +01:00
}
catch (e) {
if (log.isEnabled()) {
log.writeLine(`Error when loading type declaration timestamp file '${typeDeclarationTimestampFilePath}': ${(<Error>e).message}, ${(<Error>e).stack}`);
}
2018-01-04 23:04:14 +01:00
// If file cannot be read, we update all requested type declarations.
return {};
2017-11-21 01:43:02 +01:00
}
}
function writeTypeDeclarationTimestampFile(typeDeclarationTimestampFilePath: string, newContents: TypeDeclarationTimestampFile, host: InstallTypingHost, log: Log): void {
try {
2018-01-04 23:04:14 +01:00
if (log.isEnabled()) {
log.writeLine("Writing type declaration timestamp file.");
2017-11-21 01:43:02 +01:00
}
2018-01-04 23:04:14 +01:00
host.writeFile(typeDeclarationTimestampFilePath, JSON.stringify(newContents));
2017-11-21 01:43:02 +01:00
}
catch (e) {
if (log.isEnabled()) {
2018-01-04 23:04:14 +01:00
log.writeLine(`Error when writing type declaration timestamp file '${typeDeclarationTimestampFilePath}': ${(<Error>e).message}, ${(<Error>e).stack}`);
2017-11-21 01:43:02 +01:00
}
}
}
2016-08-12 20:04:43 +02:00
export abstract class TypingsInstaller {
2017-11-21 01:43:02 +01:00
private readonly packageNameToTypingLocation: Map<JsTyping.CachedTyping> = createMap<JsTyping.CachedTyping>();
private readonly missingTypingsSet: Map<true> = createMap<true>();
private readonly knownCachesSet: Map<true> = createMap<true>();
private readonly projectWatchers: Map<FileWatcher[]> = createMap<FileWatcher[]>();
private safeList: JsTyping.SafeList | undefined;
2016-09-20 23:14:51 +02:00
readonly pendingRunRequests: PendingRequest[] = [];
private globalTypeDeclarationTimestamps: MapLike<number> = {};
2016-09-20 23:14:51 +02:00
private installRunCount = 1;
2016-09-20 23:14:51 +02:00
private inFlightRequestCount = 0;
2016-08-16 23:21:09 +02:00
abstract readonly typesRegistry: Map<void>;
2016-09-20 23:14:51 +02:00
constructor(
2017-07-14 23:26:13 +02:00
protected readonly installTypingHost: InstallTypingHost,
private readonly globalCachePath: string,
private readonly safeListPath: Path,
2017-07-28 01:07:50 +02:00
private readonly typesMapLocation: Path,
2017-07-14 23:26:13 +02:00
private readonly throttleLimit: number,
2016-09-20 23:14:51 +02:00
protected readonly log = nullLog) {
if (this.log.isEnabled()) {
2017-07-28 01:07:50 +02:00
this.log.writeLine(`Global cache location '${globalCachePath}', safe file path '${safeListPath}', types map path ${typesMapLocation}`);
}
this.globalTypeDeclarationTimestamps = this.processCacheLocation(this.globalCachePath);
2016-08-12 20:04:43 +02:00
}
2016-08-16 23:21:09 +02:00
closeProject(req: CloseProject) {
this.closeWatchers(req.projectName);
}
private closeWatchers(projectName: string): void {
2016-08-16 23:21:09 +02:00
if (this.log.isEnabled()) {
this.log.writeLine(`Closing file watchers for project '${projectName}'`);
}
2016-12-05 23:13:32 +01:00
const watchers = this.projectWatchers.get(projectName);
2016-08-16 23:21:09 +02:00
if (!watchers) {
if (this.log.isEnabled()) {
this.log.writeLine(`No watchers are registered for project '${projectName}'`);
}
return;
2016-08-16 23:21:09 +02:00
}
for (const w of watchers) {
w.close();
}
2016-12-05 23:13:32 +01:00
this.projectWatchers.delete(projectName);
2016-08-16 23:21:09 +02:00
if (this.log.isEnabled()) {
this.log.writeLine(`Closing file watchers for project '${projectName}' - done.`);
}
}
install(req: DiscoverTypings) {
if (this.log.isEnabled()) {
this.log.writeLine(`Got install request ${JSON.stringify(req)}`);
}
2016-08-12 20:04:43 +02:00
2016-09-26 20:33:25 +02:00
// load existing typing information from the cache
2018-01-04 23:04:14 +01:00
const timestampsFilePath = combinePaths(req.cachePath || this.globalCachePath, timestampsFileName);
let localTimestamps: MapLike<number>;
if (req.cachePath) {
if (this.log.isEnabled()) {
this.log.writeLine(`Request specifies cache path '${req.cachePath}', loading cached information...`);
}
localTimestamps = this.processCacheLocation(req.cachePath, timestampsFilePath);
}
if (this.safeList === undefined) {
2017-07-28 01:07:50 +02:00
this.initializeSafeList();
}
2016-08-12 20:04:43 +02:00
const discoverTypingsResult = JsTyping.discoverTypings(
this.installTypingHost,
this.log.isEnabled() ? (s => this.log.writeLine(s)) : undefined,
2016-08-12 20:04:43 +02:00
req.fileNames,
req.projectRootPath,
this.safeList,
this.packageNameToTypingLocation,
req.typeAcquisition,
req.unresolvedImports);
2016-08-17 23:47:54 +02:00
if (this.log.isEnabled()) {
this.log.writeLine(`Finished typings discovery: ${JSON.stringify(discoverTypingsResult)}`);
}
2016-08-12 20:04:43 +02:00
2016-08-12 21:14:25 +02:00
// start watching files
this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch);
// install typings
if (discoverTypingsResult.newTypingNames.length) {
this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames, timestampsFilePath, localTimestamps || this.globalTypeDeclarationTimestamps);
}
else {
this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
if (this.log.isEnabled()) {
this.log.writeLine(`No new typings were requested as a result of typings discovery`);
}
}
2016-08-12 20:04:43 +02:00
}
2017-07-28 01:07:50 +02:00
private initializeSafeList() {
// Prefer the safe list from the types map if it exists
if (this.typesMapLocation) {
const safeListFromMap = JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation);
if (safeListFromMap) {
this.log.writeLine(`Loaded safelist from types map file '${this.typesMapLocation}'`);
this.safeList = safeListFromMap;
return;
}
this.log.writeLine(`Failed to load safelist from types map file '${this.typesMapLocation}'`);
}
this.safeList = JsTyping.loadSafeList(this.installTypingHost, this.safeListPath);
}
private processCacheLocation(cacheLocation: string, timestampsFilePath?: string): MapLike<number> {
if (this.log.isEnabled()) {
this.log.writeLine(`Processing cache location '${cacheLocation}'`);
}
2016-12-05 23:13:32 +01:00
if (this.knownCachesSet.get(cacheLocation)) {
if (this.log.isEnabled()) {
2016-08-17 23:47:54 +02:00
this.log.writeLine(`Cache location was already processed...`);
}
return;
}
const typeDeclarationTimestamps: MapLike<number> = loadTypeDeclarationTimestampFile(timestampsFilePath || combinePaths(cacheLocation, timestampsFileName), this.installTypingHost, this.log);
2016-08-26 01:25:34 +02:00
const packageJson = combinePaths(cacheLocation, "package.json");
if (this.log.isEnabled()) {
2016-08-26 01:25:34 +02:00
this.log.writeLine(`Trying to find '${packageJson}'...`);
}
2016-08-26 01:25:34 +02:00
if (this.installTypingHost.fileExists(packageJson)) {
const npmConfig = <NpmConfig>JSON.parse(this.installTypingHost.readFile(packageJson));
if (this.log.isEnabled()) {
this.log.writeLine(`Loaded content of '${packageJson}': ${JSON.stringify(npmConfig)}`);
}
2016-08-26 01:25:34 +02:00
if (npmConfig.devDependencies) {
for (const key in npmConfig.devDependencies) {
// key is @types/<package name>
2016-08-27 01:37:31 +02:00
const packageName = getBaseFileName(key);
if (!packageName) {
continue;
}
const typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
2016-08-26 01:25:34 +02:00
if (!typingFile) {
2016-12-05 23:13:32 +01:00
this.missingTypingsSet.set(packageName, true);
2016-08-26 01:25:34 +02:00
continue;
}
2016-12-05 23:13:32 +01:00
const existingTypingFile = this.packageNameToTypingLocation.get(packageName);
if (existingTypingFile) {
2017-12-29 23:21:55 +01:00
if (existingTypingFile.typingLocation === typingFile) {
continue;
}
if (this.log.isEnabled()) {
this.log.writeLine(`New typing for package ${packageName} from '${typingFile}' conflicts with existing typing file '${existingTypingFile}'`);
}
}
if (this.log.isEnabled()) {
this.log.writeLine(`Adding entry into typings cache: '${packageName}' => '${typingFile}'`);
}
if (getProperty(typeDeclarationTimestamps, key) === undefined) {
2017-11-21 01:43:02 +01:00
// getModifiedTime is only undefined if we were to use the ChakraHost, but we never do in this scenario
// defaults to old behavior of never updating if we ever use a host without getModifiedTime in the future
const timestamp = this.installTypingHost.getModifiedTime === undefined ? Date.now() : this.installTypingHost.getModifiedTime(typingFile).getTime();
typeDeclarationTimestamps[key] = timestamp;
if (this.log.isEnabled()) {
this.log.writeLine(`Adding entry into timestamp cache: '${key}' => '${timestamp}'`);
}
2017-11-21 01:43:02 +01:00
}
// timestamp guaranteed to not be undefined by above check
const newTyping: JsTyping.CachedTyping = { typingLocation: typingFile, timestamp: getProperty(typeDeclarationTimestamps, key) };
2017-11-21 01:43:02 +01:00
this.packageNameToTypingLocation.set(packageName, newTyping);
}
}
}
if (this.log.isEnabled()) {
this.log.writeLine(`Finished processing cache location '${cacheLocation}'`);
}
2016-12-05 23:13:32 +01:00
this.knownCachesSet.set(cacheLocation, true);
return typeDeclarationTimestamps;
}
2017-12-04 22:36:01 +01:00
private filterTypings(typingsToInstall: ReadonlyArray<string>): ReadonlyArray<string> {
return typingsToInstall.filter(typing => {
if (this.missingTypingsSet.get(typing)) {
if (this.log.isEnabled()) this.log.writeLine(`'${typing}' is in missingTypingsSet - skipping...`);
return false;
}
2017-11-21 01:43:02 +01:00
if (this.packageNameToTypingLocation.get(typing) && !JsTyping.isTypingExpired(this.packageNameToTypingLocation.get(typing))) {
2017-12-04 22:36:01 +01:00
if (this.log.isEnabled()) this.log.writeLine(`'${typing}' already has a typing - skipping...`);
return false;
}
2017-12-04 22:36:01 +01:00
const validationResult = JsTyping.validatePackageName(typing);
if (validationResult !== JsTyping.PackageNameValidationResult.Ok) {
// add typing name to missing set so we won't process it again
2016-12-05 23:13:32 +01:00
this.missingTypingsSet.set(typing, true);
2017-12-04 22:36:01 +01:00
if (this.log.isEnabled()) this.log.writeLine(JsTyping.renderPackageNameValidationFailure(validationResult, typing));
return false;
}
2017-12-04 22:36:01 +01:00
if (!this.typesRegistry.has(typing)) {
if (this.log.isEnabled()) this.log.writeLine(`Entry for package '${typing}' does not exist in local types registry - skipping...`);
return false;
}
return true;
});
}
protected ensurePackageDirectoryExists(directory: string) {
const npmConfigPath = combinePaths(directory, "package.json");
if (this.log.isEnabled()) {
this.log.writeLine(`Npm config file: ${npmConfigPath}`);
}
if (!this.installTypingHost.fileExists(npmConfigPath)) {
if (this.log.isEnabled()) {
this.log.writeLine(`Npm config file: '${npmConfigPath}' is missing, creating new one...`);
}
this.ensureDirectoryExists(directory, this.installTypingHost);
this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
2016-08-12 21:14:25 +02:00
}
}
2016-08-12 21:14:25 +02:00
private installTypings(req: DiscoverTypings, cachePath: string, currentlyCachedTypings: string[], typingsToInstall: string[], timestampsFilePath: string, typeDeclarationTimestamps: MapLike<number>) {
if (this.log.isEnabled()) {
this.log.writeLine(`Installing typings ${JSON.stringify(typingsToInstall)}`);
}
const filteredTypings = this.filterTypings(typingsToInstall);
if (filteredTypings.length === 0) {
if (this.log.isEnabled()) {
this.log.writeLine(`All typings are known to be missing or invalid - no need to install more typings`);
}
this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
return;
2016-08-12 20:04:43 +02:00
}
2016-08-12 21:14:25 +02:00
this.ensurePackageDirectoryExists(cachePath);
const requestId = this.installRunCount;
this.installRunCount++;
// send progress event
this.sendResponse(<BeginInstallTypes>{
kind: EventBeginInstallTypes,
eventId: requestId,
typingsInstallerVersion: ts.version, // qualified explicitly to prevent occasional shadowing
projectName: req.projectName
});
const scopedTypings = filteredTypings.map(typingsName);
this.installTypingsAsync(requestId, scopedTypings, cachePath, ok => {
try {
if (!ok) {
if (this.log.isEnabled()) {
this.log.writeLine(`install request failed, marking packages as missing to prevent repeated requests: ${JSON.stringify(filteredTypings)}`);
}
for (const typing of filteredTypings) {
2016-12-05 23:13:32 +01:00
this.missingTypingsSet.set(typing, true);
}
return;
}
// TODO: watch project directory
if (this.log.isEnabled()) {
this.log.writeLine(`Installed typings ${JSON.stringify(scopedTypings)}`);
}
const installedTypingFiles: string[] = [];
const typesPackageName = (packageName: string) => `@types/${packageName}`;
for (const packageName of filteredTypings) {
const typingFile = typingToFileName(cachePath, packageName, this.installTypingHost, this.log);
if (!typingFile) {
2016-12-05 23:13:32 +01:00
this.missingTypingsSet.set(packageName, true);
continue;
}
const newTimestamp = Date.now();
const newTyping: JsTyping.CachedTyping = { typingLocation: typingFile, timestamp: newTimestamp };
this.packageNameToTypingLocation.set(packageName, newTyping);
typeDeclarationTimestamps[typesPackageName(packageName)] = newTimestamp;
installedTypingFiles.push(typingFile);
2016-08-26 01:25:34 +02:00
}
if (this.log.isEnabled()) {
this.log.writeLine(`Installed typing files ${JSON.stringify(installedTypingFiles)}`);
2016-09-01 06:14:24 +02:00
}
const newFileContents: TypeDeclarationTimestampFile = { entries: typeDeclarationTimestamps };
2018-01-04 23:04:14 +01:00
writeTypeDeclarationTimestampFile(timestampsFilePath, newFileContents, this.installTypingHost, this.log);
2017-11-21 01:43:02 +01:00
this.sendResponse(this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
}
finally {
const response: EndInstallTypes = {
kind: EventEndInstallTypes,
eventId: requestId,
projectName: req.projectName,
packagesToInstall: scopedTypings,
installSuccess: ok,
typingsInstallerVersion: ts.version // qualified explicitly to prevent occasional shadowing
};
this.sendResponse(response);
}
2016-08-12 21:14:25 +02:00
});
2016-08-12 20:04:43 +02:00
}
2016-08-13 08:04:17 +02:00
private ensureDirectoryExists(directory: string, host: InstallTypingHost): void {
const directoryName = getDirectoryPath(directory);
if (!host.directoryExists(directoryName)) {
this.ensureDirectoryExists(directoryName, host);
}
if (!host.directoryExists(directory)) {
host.createDirectory(directory);
}
}
private watchFiles(projectName: string, files: string[]) {
2016-08-16 23:21:09 +02:00
if (!files.length) {
return;
}
// shut down existing watchers
this.closeWatchers(projectName);
// handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings
let isInvoked = false;
2016-08-16 23:21:09 +02:00
const watchers: FileWatcher[] = [];
for (const file of files) {
const w = this.installTypingHost.watchFile(file, f => {
if (this.log.isEnabled()) {
this.log.writeLine(`Got FS notification for ${f}, handler is already invoked '${isInvoked}'`);
2016-08-16 23:21:09 +02:00
}
if (!isInvoked) {
this.sendResponse({ projectName, kind: server.ActionInvalidate });
isInvoked = true;
}
}, /*pollingInterval*/ 2000);
2016-08-16 23:21:09 +02:00
watchers.push(w);
}
2016-12-05 23:13:32 +01:00
this.projectWatchers.set(projectName, watchers);
2016-08-12 20:04:43 +02:00
}
2016-08-16 23:21:09 +02:00
private createSetTypings(request: DiscoverTypings, typings: string[]): SetTypings {
2016-08-12 20:04:43 +02:00
return {
projectName: request.projectName,
typeAcquisition: request.typeAcquisition,
2016-08-12 20:04:43 +02:00
compilerOptions: request.compilerOptions,
2016-08-16 23:21:09 +02:00
typings,
unresolvedImports: request.unresolvedImports,
Merge release-2.1 into master (#12157) * Update LKG * Update version * Update LKG * Skip overloads with too-short function parameters If the parameter of an overload is a function and the argument is also a function, skip the overload if the parameter has fewer arguments than the argument does. That overload cannot possibly apply, and should not participate in, for example, contextual typing. Example: ```ts interface I { (a: number): void; (b: string, c): void; } declare function f(i: I): void; f((x, y) => {}); ``` This code now skips the first overload instead of considering. This was a longstanding bug but was only uncovered now that more functions expressions are context sensitive. * Test skip overloads w/too-short function params 1. Update changed baseline. 2. Add a new test with baseline. * Minor style improvements * Ignore optionality when skipping overloads * Do not use contextual signatures with too few parameters * isAritySmaller runs later: getNonGenericSignature * rewrite void-returning statements in constructors that capture result of super call (#11868) * rewrite void-returning statements in constructors that capture result of super call * linter * Update LKG * Fix emit inferred type which is a generic type-alias both fully and partially fill type parameters * Add tests and baselines * Skip trying to use alias if there is target type * Update baselines * Add diagnostics to remind adding tsconfig file for certain external project (#11932) * Add diagnostics for certain external project * Show tsconfig suggestion * fix lint error * Address pr * fix comment * Update error message * Flag for not overwrite js files by default without generating errors (#11980) * WIP * Properly naming things * refactor * apply the option to all files and check out options * Fix typo * Update LKG * lockLinter * use local registry to check if typings package exist (#12014) (#12032) use local registry to check if typings package exist * Add test for https://github.com/Microsoft/TypeScript/pull/11980 (#12027) * add test for the fix for overwrite emitting error * cr feedback * enable sending telemetry events to tsserver client (#12034) (#12051) enable sending telemetry events * Update LKG * Reuse subtree transform flags for incrementally parsed nodes (#12088) * Update LKG * Update version * Update LKG * Do not emit "use strict" when targeting es6 or higher or module kind is es2015 and the file is external module * Add tests and baselines * [Release 2.1] fix11754 global augmentation (#12133) * Exclude global augmentation from module resolution logic * Address PR: check using string literal instead of NodeFlags.globalAugmentation * Remove comment
2016-11-10 23:28:34 +01:00
kind: ActionSet
2016-08-12 20:04:43 +02:00
};
}
private installTypingsAsync(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void {
this.pendingRunRequests.unshift({ requestId, packageNames, cwd, onRequestCompleted });
2016-09-20 23:14:51 +02:00
this.executeWithThrottling();
}
private executeWithThrottling() {
while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
this.inFlightRequestCount++;
const request = this.pendingRunRequests.pop();
this.installWorker(request.requestId, request.packageNames, request.cwd, ok => {
2016-09-20 23:14:51 +02:00
this.inFlightRequestCount--;
request.onRequestCompleted(ok);
2016-09-20 23:14:51 +02:00
this.executeWithThrottling();
});
}
}
protected abstract installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void;
protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes): void;
2016-08-12 20:04:43 +02:00
}
/* @internal */
export function typingsName(packageName: string): string {
return `@types/${packageName}@ts${versionMajorMinor}`;
}
2016-08-12 20:04:43 +02:00
}