Merge branch 'main' into test/implementations-codelens

This commit is contained in:
Ritesh Kudkelwar
2025-10-11 10:50:06 +05:30
committed by GitHub
2070 changed files with 57296 additions and 49665 deletions

View File

@@ -8,7 +8,7 @@ import * as vscode from 'vscode';
export interface Command {
readonly id: string;
execute(...args: any[]): void | any;
execute(...args: unknown[]): void | unknown;
}
export class CommandManager {

View File

@@ -13,7 +13,7 @@ export class ConfigurePluginCommand implements Command {
private readonly pluginManager: PluginManager,
) { }
public execute(pluginId: string, configuration: any) {
public execute(pluginId: string, configuration: unknown) {
this.pluginManager.setConfiguration(pluginId, configuration);
}
}

View File

@@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { TypeScriptRequests } from '../typescriptService';
import { ExecConfig, TypeScriptRequests } from '../typescriptService';
import TypeScriptServiceClientHost from '../typeScriptServiceClientHost';
import { nulToken } from '../utils/cancellation';
import { Lazy } from '../utils/lazy';
@@ -14,7 +14,7 @@ function isCancellationToken(value: any): value is vscode.CancellationToken {
return value && typeof value.isCancellationRequested === 'boolean' && typeof value.onCancellationRequested === 'function';
}
interface RequestArgs {
export interface RequestArgs {
readonly file?: unknown;
readonly $traceId?: unknown;
}
@@ -26,7 +26,7 @@ export class TSServerRequestCommand implements Command {
private readonly lazyClientHost: Lazy<TypeScriptServiceClientHost>
) { }
public async execute(command: keyof TypeScriptRequests, args?: any, config?: any, token?: vscode.CancellationToken): Promise<unknown> {
public async execute(command: keyof TypeScriptRequests, args?: unknown, config?: ExecConfig, token?: vscode.CancellationToken): Promise<unknown> {
if (!isCancellationToken(token)) {
token = nulToken;
}
@@ -35,7 +35,7 @@ export class TSServerRequestCommand implements Command {
const hasFile = requestArgs.file instanceof vscode.Uri;
const hasTraceId = typeof requestArgs.$traceId === 'string';
if (hasFile || hasTraceId) {
const newArgs = { ...args };
const newArgs = { file: undefined as string | undefined, ...args };
if (hasFile) {
const client = this.lazyClientHost.value.serviceClient;
newArgs.file = client.toOpenTsFilePath(requestArgs.file);

View File

@@ -6,6 +6,8 @@
import * as vscode from 'vscode';
import { Command } from './commandManager';
export const tsNativeExtensionId = 'typescriptteam.native-preview';
export class EnableTsgoCommand implements Command {
public readonly id = 'typescript.experimental.enableTsgo';
@@ -27,7 +29,7 @@ export class DisableTsgoCommand implements Command {
* @param enable Whether to enable or disable TypeScript Go
*/
async function updateTsgoSetting(enable: boolean): Promise<void> {
const tsgoExtension = vscode.extensions.getExtension('typescript.typescript-lsp');
const tsgoExtension = vscode.extensions.getExtension(tsNativeExtensionId);
// Error if the TypeScript Go extension is not installed with a button to open the GitHub repo
if (!tsgoExtension) {
const selection = await vscode.window.showErrorMessage(
@@ -68,7 +70,5 @@ async function updateTsgoSetting(enable: boolean): Promise<void> {
}
}
// Update the setting, restart the extension host, and enable the TypeScript Go extension
await tsConfig.update('experimental.useTsgo', enable, target);
await vscode.commands.executeCommand('workbench.action.restartExtensionHost');
}

View File

@@ -8,7 +8,7 @@ import * as fs from 'fs';
import * as vscode from 'vscode';
import { Api, getExtensionApi } from './api';
import { CommandManager } from './commands/commandManager';
import { DisableTsgoCommand } from './commands/useTsgo';
import { DisableTsgoCommand, tsNativeExtensionId } from './commands/useTsgo';
import { registerBaseCommands } from './commands/index';
import { ElectronServiceConfigurationProvider } from './configuration/configuration.electron';
import { ExperimentationTelemetryReporter, IExperimentationTelemetryReporter } from './experimentTelemetryReporter';
@@ -25,27 +25,12 @@ import { onCaseInsensitiveFileSystem } from './utils/fs.electron';
import { Lazy } from './utils/lazy';
import { getPackageInfo } from './utils/packageInfo';
import * as temp from './utils/temp.electron';
import { conditionalRegistration, requireGlobalConfiguration, requireHasVsCodeExtension } from './languageFeatures/util/dependentRegistration';
import { DisposableStore } from './utils/dispose';
export function activate(
context: vscode.ExtensionContext
): Api {
const commandManager = new CommandManager();
context.subscriptions.push(commandManager);
// Disable extension if using the experimental TypeScript Go extension
const config = vscode.workspace.getConfiguration('typescript');
const useTsgo = config.get<boolean>('experimental.useTsgo', false);
if (useTsgo) {
commandManager.register(new DisableTsgoCommand());
// Return a no-op API when disabled
return {
getAPI() {
return undefined;
}
};
}
const pluginManager = new PluginManager();
context.subscriptions.push(pluginManager);
@@ -55,9 +40,6 @@ export function activate(
const logDirectoryProvider = new NodeLogDirectoryProvider(context);
const versionProvider = new DiskTypeScriptVersionProvider();
const activeJsTsEditorTracker = new ActiveJsTsEditorTracker();
context.subscriptions.push(activeJsTsEditorTracker);
let experimentTelemetryReporter: IExperimentationTelemetryReporter | undefined;
const packageInfo = getPackageInfo(context);
if (packageInfo) {
@@ -71,34 +53,56 @@ export function activate(
new ExperimentationService(experimentTelemetryReporter, id, version, context.globalState);
}
const logger = new Logger();
context.subscriptions.push(conditionalRegistration([
requireGlobalConfiguration('typescript', 'experimental.useTsgo'),
requireHasVsCodeExtension(tsNativeExtensionId),
], () => {
// TSGO. Only register a small set of features that don't use TS Server
const disposables = new DisposableStore();
const lazyClientHost = createLazyClientHost(context, onCaseInsensitiveFileSystem(), {
pluginManager,
commandManager,
logDirectoryProvider,
cancellerFactory: nodeRequestCancellerFactory,
versionProvider,
processFactory: new ElectronServiceProcessFactory(),
activeJsTsEditorTracker,
serviceConfigurationProvider: new ElectronServiceConfigurationProvider(),
experimentTelemetryReporter,
logger,
}, item => {
onCompletionAccepted.fire(item);
});
const commandManager = disposables.add(new CommandManager());
commandManager.register(new DisableTsgoCommand());
registerBaseCommands(commandManager, lazyClientHost, pluginManager, activeJsTsEditorTracker);
return disposables;
}, () => {
// Normal registration path
const disposables = new DisposableStore();
import('./task/taskProvider').then(module => {
context.subscriptions.push(module.register(new Lazy(() => lazyClientHost.value.serviceClient)));
});
const commandManager = disposables.add(new CommandManager());
const activeJsTsEditorTracker = disposables.add(new ActiveJsTsEditorTracker());
import('./languageFeatures/tsconfig').then(module => {
context.subscriptions.push(module.register());
});
const lazyClientHost = createLazyClientHost(context, onCaseInsensitiveFileSystem(), {
pluginManager,
commandManager,
logDirectoryProvider,
cancellerFactory: nodeRequestCancellerFactory,
versionProvider,
processFactory: new ElectronServiceProcessFactory(),
activeJsTsEditorTracker,
serviceConfigurationProvider: new ElectronServiceConfigurationProvider(),
experimentTelemetryReporter,
logger: new Logger(),
}, item => {
onCompletionAccepted.fire(item);
}).map(clientHost => {
return disposables.add(clientHost);
});
context.subscriptions.push(lazilyActivateClient(lazyClientHost, pluginManager, activeJsTsEditorTracker));
// Register features
registerBaseCommands(commandManager, lazyClientHost, pluginManager, activeJsTsEditorTracker);
import('./task/taskProvider').then(module => {
disposables.add(module.register(new Lazy(() => lazyClientHost.value.serviceClient)));
});
import('./languageFeatures/tsconfig').then(module => {
disposables.add(module.register());
});
disposables.add(lazilyActivateClient(lazyClientHost, pluginManager, activeJsTsEditorTracker));
return disposables;
},));
return getExtensionApi(onCompletionAccepted.event, pluginManager);
}

View File

@@ -56,7 +56,7 @@ class MyCompletionItem extends vscode.CompletionItem {
public readonly document: vscode.TextDocument,
public readonly tsEntry: Proto.CompletionEntry,
private readonly completionContext: CompletionContext,
public readonly metadata: any | undefined,
public readonly metadata: unknown | undefined,
client: ITypeScriptServiceClient,
defaultCommitCharacters: readonly string[] | undefined,
) {
@@ -777,7 +777,7 @@ class TypeScriptCompletionItemProvider implements vscode.CompletionItemProvider<
dotAccessorContext = { range, text };
}
}
const isIncomplete = !!response.body.isIncomplete || (response.metadata as any)?.isIncomplete;
const isIncomplete = !!response.body.isIncomplete || !!(response.metadata as Record<string, unknown>)?.isIncomplete;
const entries = response.body.entries;
const metadata = response.metadata;
const defaultCommitCharacters = Object.freeze(response.body.defaultCommitCharacters);

View File

@@ -285,7 +285,7 @@ export class DiagnosticsManager extends Disposable {
private readonly _diagnostics: ResourceMap<FileDiagnostics>;
private readonly _settings = new DiagnosticSettings();
private readonly _currentDiagnostics: vscode.DiagnosticCollection;
private readonly _pendingUpdates: ResourceMap<any>;
private readonly _pendingUpdates: ResourceMap</* timeout */ any>;
private readonly _updateDelay = 50;

View File

@@ -57,7 +57,7 @@ class DidOrganizeImportsCommand implements Command {
private readonly telemetryReporter: TelemetryReporter,
) { }
public async execute(): Promise<any> {
public async execute(): Promise<void> {
/* __GDPR__
"organizeImports.execute" : {
"owner": "mjbvz",

View File

@@ -366,22 +366,19 @@ class TypeScriptQuickFixProvider implements vscode.CodeActionProvider<VsCodeCode
let expand: Expand | undefined;
let title = action.description;
if (action.fixName === fixNames.classIncorrectlyImplementsInterface) {
title += ' with Copilot';
message = `Implement the stubbed-out class members for ${document.getText(diagnostic.range)} with a useful implementation.`;
title = vscode.l10n.t('{0} with AI', action.description);
message = vscode.l10n.t(`Implement the stubbed-out class members for ${document.getText(diagnostic.range)} with a useful implementation.`);
expand = { kind: 'code-action', action };
}
else if (action.fixName === fixNames.fixClassDoesntImplementInheritedAbstractMember) {
title += ' with Copilot';
message = `Implement the stubbed-out class members for ${document.getText(diagnostic.range)} with a useful implementation.`;
} else if (action.fixName === fixNames.fixClassDoesntImplementInheritedAbstractMember) {
title = vscode.l10n.t('{0} with AI', action.description);
message = vscode.l10n.t(`Implement the stubbed-out class members for {0} with a useful implementation.`, document.getText(diagnostic.range));
expand = { kind: 'code-action', action };
}
else if (action.fixName === fixNames.fixMissingFunctionDeclaration) {
title = `Implement missing function declaration '${document.getText(diagnostic.range)}' using Copilot`;
message = `Provide a reasonable implementation of the function ${document.getText(diagnostic.range)} given its type and the context it's called in.`;
} else if (action.fixName === fixNames.fixMissingFunctionDeclaration) {
title = vscode.l10n.t(`Implement missing function declaration '{0}' using AI`, document.getText(diagnostic.range));
message = vscode.l10n.t(`Provide a reasonable implementation of the function {0} given its type and the context it's called in.`, document.getText(diagnostic.range));
expand = { kind: 'code-action', action };
}
else if (action.fixName === fixNames.inferFromUsage) {
const inferFromBody = new VsCodeCodeAction(action, 'Infer types using Copilot', vscode.CodeActionKind.QuickFix);
} else if (action.fixName === fixNames.inferFromUsage) {
const inferFromBody = new VsCodeCodeAction(action, vscode.l10n.t('Infer types using AI'), vscode.CodeActionKind.QuickFix);
inferFromBody.edit = new vscode.WorkspaceEdit();
inferFromBody.diagnostics = [diagnostic];
inferFromBody.ranges = [diagnostic.range];
@@ -389,7 +386,7 @@ class TypeScriptQuickFixProvider implements vscode.CodeActionProvider<VsCodeCode
inferFromBody.command = {
command: EditorChatFollowUp.ID,
arguments: [{
message: 'Add types to this code. Add separate interfaces when possible. Do not change the code except for adding types.',
message: vscode.l10n.t('Add types to this code. Add separate interfaces when possible. Do not change the code except for adding types.'),
expand: { kind: 'navtree-function', pos: diagnostic.range.start },
document,
action: { type: 'quickfix', quickfix: action }
@@ -400,8 +397,8 @@ class TypeScriptQuickFixProvider implements vscode.CodeActionProvider<VsCodeCode
}
else if (action.fixName === fixNames.addNameToNamelessParameter) {
const newText = action.changes.map(change => change.textChanges.map(textChange => textChange.newText).join('')).join('');
title = 'Add meaningful parameter name with Copilot';
message = `Rename the parameter ${newText} with a more meaningful name.`;
title = vscode.l10n.t('Add meaningful parameter name with AI');
message = vscode.l10n.t(`Rename the parameter {0} with a more meaningful name.`, newText);
expand = {
kind: 'navtree-function',
pos: diagnostic.range.start

View File

@@ -105,9 +105,9 @@ function toTsTriggerReason(context: vscode.SignatureHelpContext): Proto.Signatur
case vscode.SignatureHelpTriggerKind.TriggerCharacter:
if (context.triggerCharacter) {
if (context.isRetrigger) {
return { kind: 'retrigger', triggerCharacter: context.triggerCharacter as any };
return { kind: 'retrigger', triggerCharacter: context.triggerCharacter as Proto.SignatureHelpRetriggerCharacter };
} else {
return { kind: 'characterTyped', triggerCharacter: context.triggerCharacter as any };
return { kind: 'characterTyped', triggerCharacter: context.triggerCharacter as Proto.SignatureHelpTriggerCharacter };
}
} else {
return { kind: 'invoked' };

View File

@@ -34,11 +34,15 @@ export class Condition extends Disposable {
}
class ConditionalRegistration {
private registration: vscode.Disposable | undefined = undefined;
private state?: {
readonly enabled: boolean;
readonly registration: vscode.Disposable | undefined;
};
public constructor(
private readonly conditions: readonly Condition[],
private readonly doRegister: () => vscode.Disposable
private readonly doRegister: () => vscode.Disposable,
private readonly elseDoRegister?: () => vscode.Disposable
) {
for (const condition of conditions) {
condition.onDidChange(() => this.update());
@@ -47,17 +51,22 @@ class ConditionalRegistration {
}
public dispose() {
this.registration?.dispose();
this.registration = undefined;
this.state?.registration?.dispose();
this.state = undefined;
}
private update() {
const enabled = this.conditions.every(condition => condition.value);
if (enabled) {
this.registration ??= this.doRegister();
if (!this.state?.enabled) {
this.state?.registration?.dispose();
this.state = { enabled: true, registration: this.doRegister() };
}
} else {
this.registration?.dispose();
this.registration = undefined;
if (this.state?.enabled || !this.state) {
this.state?.registration?.dispose();
this.state = { enabled: false, registration: this.elseDoRegister?.() };
}
}
}
}
@@ -65,8 +74,9 @@ class ConditionalRegistration {
export function conditionalRegistration(
conditions: readonly Condition[],
doRegister: () => vscode.Disposable,
elseDoRegister?: () => vscode.Disposable
): vscode.Disposable {
return new ConditionalRegistration(conditions, doRegister);
return new ConditionalRegistration(conditions, doRegister, elseDoRegister);
}
export function requireMinVersion(
@@ -101,3 +111,15 @@ export function requireSomeCapability(
client.onDidChangeCapabilities
);
}
export function requireHasVsCodeExtension(
extensionId: string
) {
return new Condition(
() => {
return !!vscode.extensions.getExtension(extensionId);
},
vscode.extensions.onDidChange
);
}

View File

@@ -38,16 +38,12 @@ export function createLazyClientHost(
onCompletionAccepted: (item: vscode.CompletionItem) => void,
): Lazy<TypeScriptServiceClientHost> {
return new Lazy(() => {
const clientHost = new TypeScriptServiceClientHost(
return new TypeScriptServiceClientHost(
standardLanguageDescriptions,
context,
onCaseInsensitiveFileSystem,
services,
onCompletionAccepted);
context.subscriptions.push(clientHost);
return clientHost;
});
}

View File

@@ -16,17 +16,17 @@ export class Logger {
return this.output.value.logLevel;
}
public info(message: string, ...args: any[]): void {
public info(message: string, ...args: unknown[]): void {
this.output.value.info(message, ...args);
}
public trace(message: string, ...args: any[]): void {
public trace(message: string, ...args: unknown[]): void {
this.output.value.trace(message, ...args);
}
public error(message: string, data?: any): void {
public error(message: string, data?: unknown): void {
// See https://github.com/microsoft/TypeScript/issues/10496
if (data && data.message === 'No content available.') {
if (data && (data as { message?: string }).message === 'No content available.') {
return;
}
this.output.value.error(message, ...(data ? [data] : []));

View File

@@ -32,7 +32,7 @@ export default class Tracer extends Disposable {
}
}
public traceRequestCompleted(serverId: string, command: string, request_seq: number, meta: RequestExecutionMetadata): any {
public traceRequestCompleted(serverId: string, command: string, request_seq: number, meta: RequestExecutionMetadata): void {
if (this.logger.logLevel === vscode.LogLevel.Trace) {
this.trace(serverId, `Async response received: ${command} (${request_seq}). Request took ${Date.now() - meta.queuingStartTime} ms.`);
}

View File

@@ -168,7 +168,7 @@ class SyncedBuffer {
) { }
public open(): void {
const args: Proto.OpenRequestArgs = {
const args: Proto.OpenRequestArgs & { plugins?: string[] } = {
file: this.filepath,
fileContent: this.document.getText(),
projectRootPath: this.getProjectRootPath(this.document.uri),
@@ -183,7 +183,7 @@ class SyncedBuffer {
.filter(x => x.languages.indexOf(this.document.languageId) >= 0);
if (tsPluginsForDocument.length) {
(args as any).plugins = tsPluginsForDocument.map(plugin => plugin.name);
args.plugins = tsPluginsForDocument.map(plugin => plugin.name);
}
this.synchronizer.open(this.resource, args);
@@ -349,15 +349,15 @@ class GetErrRequest {
}
}
private areProjectDiagnosticsEnabled() {
private areProjectDiagnosticsEnabled(): boolean {
return this.client.configuration.enableProjectDiagnostics && this.client.capabilities.has(ClientCapability.Semantic);
}
private areRegionDiagnosticsEnabled() {
private areRegionDiagnosticsEnabled(): boolean {
return this.client.configuration.enableRegionDiagnostics && this.client.apiVersion.gte(API.v560);
}
public cancel(): any {
public cancel(): void {
if (!this._done) {
this._token.cancel();
}

View File

@@ -26,7 +26,7 @@ namespace TypeScriptServerPlugin {
}
export class PluginManager extends Disposable {
private readonly _pluginConfigurations = new Map<string, {}>();
private readonly _pluginConfigurations = new Map<string, unknown>();
private _plugins?: Map<string, ReadonlyArray<TypeScriptServerPlugin>>;
@@ -54,15 +54,15 @@ export class PluginManager extends Disposable {
private readonly _onDidUpdatePlugins = this._register(new vscode.EventEmitter<this>());
public readonly onDidChangePlugins = this._onDidUpdatePlugins.event;
private readonly _onDidUpdateConfig = this._register(new vscode.EventEmitter<{ pluginId: string; config: {} }>());
private readonly _onDidUpdateConfig = this._register(new vscode.EventEmitter<{ pluginId: string; config: unknown }>());
public readonly onDidUpdateConfig = this._onDidUpdateConfig.event;
public setConfiguration(pluginId: string, config: {}) {
public setConfiguration(pluginId: string, config: unknown) {
this._pluginConfigurations.set(pluginId, config);
this._onDidUpdateConfig.fire({ pluginId, config });
}
public configurations(): IterableIterator<[string, {}]> {
public configurations(): IterableIterator<[string, unknown]> {
return this._pluginConfigurations.entries();
}

View File

@@ -86,7 +86,7 @@ export class RequestQueue {
return false;
}
public createRequest(command: string, args: any): Proto.Request {
public createRequest(command: string, args: unknown): Proto.Request {
return {
seq: this.sequenceNumber++,
type: 'request',

View File

@@ -5,6 +5,7 @@
import { Cancellation } from '@vscode/sync-api-common/lib/common/messageCancellation';
import * as vscode from 'vscode';
import { RequestArgs } from '../commands/tsserverRequests';
import { TypeScriptServiceConfiguration } from '../configuration/configuration';
import { TelemetryReporter } from '../logging/telemetry';
import Tracer from '../logging/tracer';
@@ -15,11 +16,11 @@ import { ServerResponse, ServerType, TypeScriptRequests } from '../typescriptSer
import { Disposable } from '../utils/dispose';
import { isWebAndHasSharedArrayBuffers } from '../utils/platform';
import { OngoingRequestCanceller } from './cancellation';
import { NodeVersionManager } from './nodeManager';
import type * as Proto from './protocol/protocol';
import { EventName } from './protocol/protocol.const';
import { TypeScriptVersionManager } from './versionManager';
import { TypeScriptVersion } from './versionProvider';
import { NodeVersionManager } from './nodeManager';
export enum ExecutionTarget {
Semantic,
@@ -38,7 +39,7 @@ export type TsServerLog =
export interface ITypeScriptServer {
readonly onEvent: vscode.Event<Proto.Event>;
readonly onExit: vscode.Event<TypeScriptServerExitEvent>;
readonly onError: vscode.Event<any>;
readonly onError: vscode.Event<unknown>;
readonly tsServerLog: TsServerLog | undefined;
@@ -48,7 +49,7 @@ export interface ITypeScriptServer {
* @return A list of all execute requests. If there are multiple entries, the first item is the primary
* request while the rest are secondary ones.
*/
executeImpl(command: keyof TypeScriptRequests, args: any, executeInfo: { isAsync: boolean; token?: vscode.CancellationToken; expectsResult: boolean; lowPriority?: boolean; executionTarget?: ExecutionTarget }): Array<Promise<ServerResponse.Response<Proto.Response>> | undefined>;
executeImpl(command: keyof TypeScriptRequests, args: unknown, executeInfo: { isAsync: boolean; token?: vscode.CancellationToken; expectsResult: boolean; lowPriority?: boolean; executionTarget?: ExecutionTarget }): Array<Promise<ServerResponse.Response<Proto.Response>> | undefined>;
dispose(): void;
}
@@ -124,7 +125,7 @@ export class SingleTsServer extends Disposable implements ITypeScriptServer {
private readonly _onExit = this._register(new vscode.EventEmitter<TypeScriptServerExitEvent>());
public readonly onExit = this._onExit.event;
private readonly _onError = this._register(new vscode.EventEmitter<any>());
private readonly _onError = this._register(new vscode.EventEmitter<unknown>());
public readonly onError = this._onError.event;
public get tsServerLog() { return this._tsServerLog; }
@@ -283,7 +284,8 @@ export class SingleTsServer extends Disposable implements ITypeScriptServer {
}
this._requestQueue.enqueue(requestInfo);
if (args && typeof (args as any).$traceId === 'string') {
const traceId = (args as RequestArgs | undefined)?.$traceId;
if (args && typeof traceId === 'string') {
const queueLength = this._requestQueue.length - 1;
const pendingResponses = this._pendingResponses.size;
const data: { command: string; queueLength: number; pendingResponses: number; queuedCommands?: string[]; pendingCommands?: string[] } = {
@@ -298,7 +300,7 @@ export class SingleTsServer extends Disposable implements ITypeScriptServer {
data.pendingCommands = this.getPendingCommands();
}
this._telemetryReporter.logTraceEvent('TSServer.enqueueRequest', (args as any).$traceId, JSON.stringify(data));
this._telemetryReporter.logTraceEvent('TSServer.enqueueRequest', traceId, JSON.stringify(data));
}
this.sendNextRequests();
@@ -404,7 +406,7 @@ class RequestRouter {
public execute(
command: keyof TypeScriptRequests,
args: any,
args: unknown,
executeInfo: ExecuteInfo,
): Array<Promise<ServerResponse.Response<Proto.Response>> | undefined> {
if (RequestRouter.sharedCommands.has(command) && typeof executeInfo.executionTarget === 'undefined') {
@@ -526,7 +528,7 @@ export class GetErrRoutingTsServer extends Disposable implements ITypeScriptServ
private readonly _onExit = this._register(new vscode.EventEmitter<TypeScriptServerExitEvent>());
public readonly onExit = this._onExit.event;
private readonly _onError = this._register(new vscode.EventEmitter<any>());
private readonly _onError = this._register(new vscode.EventEmitter<unknown>());
public readonly onError = this._onError.event;
public get tsServerLog() { return this.mainServer.tsServerLog; }
@@ -536,7 +538,7 @@ export class GetErrRoutingTsServer extends Disposable implements ITypeScriptServ
this.mainServer.kill();
}
public executeImpl(command: keyof TypeScriptRequests, args: any, executeInfo: { isAsync: boolean; token?: vscode.CancellationToken; expectsResult: boolean; lowPriority?: boolean; executionTarget?: ExecutionTarget }): Array<Promise<ServerResponse.Response<Proto.Response>> | undefined> {
public executeImpl(command: keyof TypeScriptRequests, args: unknown, executeInfo: { isAsync: boolean; token?: vscode.CancellationToken; expectsResult: boolean; lowPriority?: boolean; executionTarget?: ExecutionTarget }): Array<Promise<ServerResponse.Response<Proto.Response>> | undefined> {
return this.router.execute(command, args, executeInfo);
}
}
@@ -664,10 +666,10 @@ export class SyntaxRoutingTsServer extends Disposable implements ITypeScriptServ
private readonly _onEvent = this._register(new vscode.EventEmitter<Proto.Event>());
public readonly onEvent = this._onEvent.event;
private readonly _onExit = this._register(new vscode.EventEmitter<any>());
private readonly _onExit = this._register(new vscode.EventEmitter<TypeScriptServerExitEvent>());
public readonly onExit = this._onExit.event;
private readonly _onError = this._register(new vscode.EventEmitter<any>());
private readonly _onError = this._register(new vscode.EventEmitter<unknown>());
public readonly onError = this._onError.event;
public get tsServerLog() { return this.semanticServer.tsServerLog; }
@@ -677,7 +679,7 @@ export class SyntaxRoutingTsServer extends Disposable implements ITypeScriptServ
this.semanticServer.kill();
}
public executeImpl(command: keyof TypeScriptRequests, args: any, executeInfo: { isAsync: boolean; token?: vscode.CancellationToken; expectsResult: boolean; lowPriority?: boolean; executionTarget?: ExecutionTarget }): Array<Promise<ServerResponse.Response<Proto.Response>> | undefined> {
public executeImpl(command: keyof TypeScriptRequests, args: unknown, executeInfo: { isAsync: boolean; token?: vscode.CancellationToken; expectsResult: boolean; lowPriority?: boolean; executionTarget?: ExecutionTarget }): Array<Promise<ServerResponse.Response<Proto.Response>> | undefined> {
return this.router.execute(command, args, executeInfo);
}
}

View File

@@ -183,7 +183,7 @@ export class DiskTypeScriptVersionProvider implements ITypeScriptVersionProvider
}
const contents = fs.readFileSync(fileName).toString();
let desc: any = null;
let desc: any;
try {
desc = JSON.parse(contents);
} catch (err) {

View File

@@ -108,7 +108,6 @@ interface WatchEvent {
export default class TypeScriptServiceClient extends Disposable implements ITypeScriptServiceClient {
private readonly _onReady?: { promise: Promise<void>; resolve: () => void; reject: () => void };
private _configuration: TypeScriptServiceConfiguration;
private readonly pluginPathsProvider: TypeScriptPluginPathsProvider;
@@ -445,12 +444,17 @@ export default class TypeScriptServiceClient extends Disposable implements IType
typeScriptVersionSource: version.source,
});
handle.onError((err: Error) => {
handle.onError((err: unknown) => {
if (this.token !== mytoken) {
// this is coming from an old process
return;
}
if (!(err instanceof Error)) {
this.logger.error('TSServer got unknown error type:', err);
return;
}
if (err) {
vscode.window.showErrorMessage(vscode.l10n.t("TypeScript language server exited with error. Error message is: {0}", err.message || err.name));
}
@@ -632,6 +636,10 @@ export default class TypeScriptServiceClient extends Disposable implements IType
this.serverState = ServerState.None;
if (this.isDisposed) {
return;
}
if (restart) {
const diff = Date.now() - this.lastStart;
this.numberRestarts++;
@@ -848,7 +856,7 @@ export default class TypeScriptServiceClient extends Disposable implements IType
return vscode.workspace.getWorkspaceFolder(resource)?.uri;
}
public execute(command: keyof TypeScriptRequests, args: any, token: vscode.CancellationToken, config?: ExecConfig): Promise<ServerResponse.Response<Proto.Response>> {
public execute(command: keyof TypeScriptRequests, args: unknown, token: vscode.CancellationToken, config?: ExecConfig): Promise<ServerResponse.Response<Proto.Response>> {
let executions: Array<Promise<ServerResponse.Response<Proto.Response>> | undefined> | undefined;
if (config?.cancelOnResourceChange) {
@@ -904,7 +912,7 @@ export default class TypeScriptServiceClient extends Disposable implements IType
return executions[0]!;
}
public executeWithoutWaitingForResponse(command: keyof TypeScriptRequests, args: any): void {
public executeWithoutWaitingForResponse(command: keyof TypeScriptRequests, args: unknown): void {
this.executeImpl(command, args, {
isAsync: false,
token: undefined,
@@ -920,7 +928,7 @@ export default class TypeScriptServiceClient extends Disposable implements IType
})[0]!;
}
private executeImpl(command: keyof TypeScriptRequests, args: any, executeInfo: { isAsync: boolean; token?: vscode.CancellationToken; expectsResult: boolean; lowPriority?: boolean; requireSemantic?: boolean }): Array<Promise<ServerResponse.Response<Proto.Response>> | undefined> {
private executeImpl(command: keyof TypeScriptRequests, args: unknown, executeInfo: { isAsync: boolean; token?: vscode.CancellationToken; expectsResult: boolean; lowPriority?: boolean; requireSemantic?: boolean }): Array<Promise<ServerResponse.Response<Proto.Response>> | undefined> {
const serverState = this.serverState;
if (serverState.type === ServerState.Type.Running) {
this.bufferSyncSupport.beforeCommand(command);
@@ -1227,7 +1235,7 @@ export default class TypeScriptServiceClient extends Disposable implements IType
this.telemetryReporter.logTelemetry(telemetryData.telemetryEventName, properties);
}
private configurePlugin(pluginName: string, configuration: {}): any {
private configurePlugin(pluginName: string, configuration: unknown): void {
this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration });
}
}

View File

@@ -61,7 +61,7 @@ export class Delayer<T> {
}
}
export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): Disposable {
export function setImmediate(callback: (...args: unknown[]) => void, ...args: unknown[]): Disposable {
if (global.setImmediate) {
const handle = global.setImmediate(callback, ...args);
return { dispose: () => global.clearImmediate(handle) };

View File

@@ -44,4 +44,8 @@ export class Lazy<T> {
* Get the wrapped value without forcing evaluation.
*/
get rawValue(): T | undefined { return this._value; }
map<R>(fn: (value: T) => R): Lazy<R> {
return new Lazy(() => fn(this.value));
}
}

View File

@@ -10,7 +10,7 @@ export function isWeb(): boolean {
}
export function isWebAndHasSharedArrayBuffers(): boolean {
return isWeb() && (globalThis as any)['crossOriginIsolated'];
return isWeb() && !!(globalThis as Record<string, unknown>)['crossOriginIsolated'];
}
export function supportsReadableByteStreams(): boolean {