From 1aa4d3a722a9d6b5f7df948ebc649a0d26ea8339 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Wed, 9 Aug 2023 15:53:16 -0700 Subject: [PATCH 01/10] Make tsserver a thin wrapper around tsserverlibrary --- Herebyfile.mjs | 6 +- src/tsconfig-eslint.json | 5 +- src/tsserver/_namespaces/ts.server.ts | 6 - src/tsserver/_namespaces/ts.ts | 8 - src/tsserver/common.ts | 36 ++-- src/tsserver/nodeServer.ts | 242 +++++++++++--------------- src/tsserver/server.ts | 55 +++--- src/tsserver/tsconfig.json | 10 +- 8 files changed, 151 insertions(+), 217 deletions(-) delete mode 100644 src/tsserver/_namespaces/ts.server.ts delete mode 100644 src/tsserver/_namespaces/ts.ts diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 38269cbcc3929..039e1239f69ae 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -177,6 +177,10 @@ function createBundler(entrypoint, outfile, taskOptions = {}) { sourcesContent: false, treeShaking: taskOptions.treeShaking, packages: "external", + external: ["typescript", "./typescript.js"], + alias: { + typescript: "./typescript.js", + }, logLevel: "warning", // legalComments: "none", // If we add copyright headers to the source files, uncomment. }; @@ -384,7 +388,7 @@ const { main: tsserver, watch: watchTsserver } = entrypointBuildTask({ srcEntrypoint: "./src/tsserver/server.ts", builtEntrypoint: "./built/local/tsserver/server.js", output: "./built/local/tsserver.js", - mainDeps: [generateLibs], + mainDeps: [generateLibs, services], }); export { tsserver, watchTsserver }; diff --git a/src/tsconfig-eslint.json b/src/tsconfig-eslint.json index 087b75ff7dc15..bb9dde7b56fdc 100644 --- a/src/tsconfig-eslint.json +++ b/src/tsconfig-eslint.json @@ -1,6 +1,9 @@ { "extends": "./tsconfig-base", "compilerOptions": { - "types": ["node", "mocha", "chai"] + "types": ["node", "mocha", "chai"], + "paths": { + "typescript": ["./typescript/typescript"] + } } } diff --git a/src/tsserver/_namespaces/ts.server.ts b/src/tsserver/_namespaces/ts.server.ts deleted file mode 100644 index 18cb6abae0e42..0000000000000 --- a/src/tsserver/_namespaces/ts.server.ts +++ /dev/null @@ -1,6 +0,0 @@ -/* Generated file to emulate the ts.server namespace. */ - -export * from "../../jsTyping/_namespaces/ts.server"; -export * from "../../server/_namespaces/ts.server"; -export * from "../nodeServer"; -export * from "../common"; diff --git a/src/tsserver/_namespaces/ts.ts b/src/tsserver/_namespaces/ts.ts deleted file mode 100644 index f590869290d26..0000000000000 --- a/src/tsserver/_namespaces/ts.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* Generated file to emulate the ts namespace. */ - -export * from "../../compiler/_namespaces/ts"; -export * from "../../services/_namespaces/ts"; -export * from "../../jsTyping/_namespaces/ts"; -export * from "../../server/_namespaces/ts"; -import * as server from "./ts.server"; -export { server }; diff --git a/src/tsserver/common.ts b/src/tsserver/common.ts index 76ff50afed512..3136ce1d1e308 100644 --- a/src/tsserver/common.ts +++ b/src/tsserver/common.ts @@ -1,18 +1,12 @@ -import { LanguageServiceMode } from "./_namespaces/ts"; -import { - Logger, - LogLevel, - ServerCancellationToken, - SessionOptions, -} from "./_namespaces/ts.server"; +import * as ts from "typescript"; /** @internal */ export function getLogLevel(level: string | undefined) { if (level) { const l = level.toLowerCase(); - for (const name in LogLevel) { + for (const name in ts.server.LogLevel) { if (isNaN(+name) && l === name.toLowerCase()) { - return LogLevel[name] as any as LogLevel; + return ts.server.LogLevel[name] as any as ts.server.LogLevel; } } } @@ -21,22 +15,22 @@ export function getLogLevel(level: string | undefined) { /** @internal */ export interface StartSessionOptions { - globalPlugins: SessionOptions["globalPlugins"]; - pluginProbeLocations: SessionOptions["pluginProbeLocations"]; - allowLocalPluginLoads: SessionOptions["allowLocalPluginLoads"]; - useSingleInferredProject: SessionOptions["useSingleInferredProject"]; - useInferredProjectPerProjectRoot: SessionOptions["useInferredProjectPerProjectRoot"]; - suppressDiagnosticEvents: SessionOptions["suppressDiagnosticEvents"]; - noGetErrOnBackgroundUpdate: SessionOptions["noGetErrOnBackgroundUpdate"]; - serverMode: SessionOptions["serverMode"]; + globalPlugins: ts.server.SessionOptions["globalPlugins"]; + pluginProbeLocations: ts.server.SessionOptions["pluginProbeLocations"]; + allowLocalPluginLoads: ts.server.SessionOptions["allowLocalPluginLoads"]; + useSingleInferredProject: ts.server.SessionOptions["useSingleInferredProject"]; + useInferredProjectPerProjectRoot: ts.server.SessionOptions["useInferredProjectPerProjectRoot"]; + suppressDiagnosticEvents: ts.server.SessionOptions["suppressDiagnosticEvents"]; + noGetErrOnBackgroundUpdate: ts.server.SessionOptions["noGetErrOnBackgroundUpdate"]; + serverMode: ts.server.SessionOptions["serverMode"]; } /** @internal */ export interface StartInput { args: readonly string[]; - logger: Logger; - cancellationToken: ServerCancellationToken; - serverMode: LanguageServiceMode | undefined; + logger: ts.server.Logger; + cancellationToken: ts.server.ServerCancellationToken; + serverMode: ts.LanguageServiceMode | undefined; unknownServerMode?: string; - startSession: (option: StartSessionOptions, logger: Logger, cancellationToken: ServerCancellationToken) => void; + startSession: (option: StartSessionOptions, logger: ts.server.Logger, cancellationToken: ts.server.ServerCancellationToken) => void; } diff --git a/src/tsserver/nodeServer.ts b/src/tsserver/nodeServer.ts index e33a94bce796f..2d481b1aa516e 100644 --- a/src/tsserver/nodeServer.ts +++ b/src/tsserver/nodeServer.ts @@ -1,5 +1,3 @@ -import * as protocol from "../server/protocol"; -import * as ts from "./_namespaces/ts"; import { ApplyCodeActionCommandResult, assertType, @@ -30,55 +28,15 @@ import { validateLocaleAndSetLanguage, versionMajorMinor, WatchOptions, -} from "./_namespaces/ts"; -import * as server from "./_namespaces/ts.server"; -import { - ActionInvalidate, - ActionPackageInstalled, - ActionSet, - ActionWatchTypingLocations, - Arguments, - BeginInstallTypes, - createInstallTypingsRequest, - EndInstallTypes, - EventBeginInstallTypes, - EventEndInstallTypes, - EventInitializationFailed, - EventTypesRegistry, - findArgument, - formatMessage, - getLogLevel, - hasArgument, - indent, - InitializationFailedResponse, - InstallPackageOptionsWithProject, - InstallPackageRequest, - InvalidateCachedTypings, - ITypingsInstaller, - Logger, - LogLevel, - Msg, - nowString, - nullCancellationToken, - nullTypingsInstaller, - PackageInstalledResponse, - Project, - ProjectService, - ServerCancellationToken, - ServerHost, - Session, - SetTypings, - StartInput, - StartSessionOptions, - stringifyIndented, - toEvent, - TypesRegistryResponse, - TypingInstallerRequestUnion, -} from "./_namespaces/ts.server"; +} from "typescript"; +import * as ts from "typescript"; + +import { getLogLevel, StartInput, StartSessionOptions } from "./common"; + interface LogOptions { file?: string; - detailLevel?: LogLevel; + detailLevel?: ts.server.LogLevel; traceToConsole?: boolean; logToFile?: boolean; } @@ -119,7 +77,7 @@ function parseLoggingEnvironmentString(logEnvStr: string | undefined): LogOption break; case "-level": const level = getLogLevel(value); - logEnv.detailLevel = level !== undefined ? level : LogLevel.normal; + logEnv.detailLevel = level !== undefined ? level : ts.server.LogLevel.normal; break; case "-traceToConsole": logEnv.traceToConsole = value.toLowerCase() === "true"; @@ -149,7 +107,7 @@ function parseLoggingEnvironmentString(logEnvStr: string | undefined): LogOption } function parseServerMode(): LanguageServiceMode | string | undefined { - const mode = findArgument("--serverMode"); + const mode = ts.server.findArgument("--serverMode"); if (!mode) return undefined; switch (mode.toLowerCase()) { @@ -166,7 +124,7 @@ function parseServerMode(): LanguageServiceMode | string | undefined { /** @internal */ export function initializeNodeSystem(): StartInput { - const sys = Debug.checkDefined(ts.sys) as ServerHost; + const sys = Debug.checkDefined(ts.sys) as ts.server.ServerHost; const childProcess: { execFileSync(file: string, args: string[], options: { stdio: "ignore", env: MapLike }): string | Buffer; } = require("child_process"); @@ -211,7 +169,7 @@ export function initializeNodeSystem(): StartInput { constructor( private readonly logFilename: string, private readonly traceToConsole: boolean, - private readonly level: LogLevel + private readonly level: ts.server.LogLevel ) { if (this.logFilename) { try { @@ -234,13 +192,13 @@ export function initializeNodeSystem(): StartInput { return this.logFilename; } perftrc(s: string) { - this.msg(s, Msg.Perf); + this.msg(s, ts.server.Msg.Perf); } info(s: string) { - this.msg(s, Msg.Info); + this.msg(s, ts.server.Msg.Info); } err(s: string) { - this.msg(s, Msg.Err); + this.msg(s, ts.server.Msg.Err); } startGroup() { this.inGroup = true; @@ -252,15 +210,15 @@ export function initializeNodeSystem(): StartInput { loggingEnabled() { return !!this.logFilename || this.traceToConsole; } - hasLevel(level: LogLevel) { + hasLevel(level: ts.server.LogLevel) { return this.loggingEnabled() && this.level >= level; } - msg(s: string, type: Msg = Msg.Err) { + msg(s: string, type: ts.server.Msg = ts.server.Msg.Err) { switch (type) { - case Msg.Info: + case ts.server.Msg.Info: perfLogger?.logInfoEvent(s); break; - case Msg.Perf: + case ts.server.Msg.Perf: perfLogger?.logPerfEvent(s); break; default: // Msg.Err @@ -270,7 +228,7 @@ export function initializeNodeSystem(): StartInput { if (!this.canWrite()) return; - s = `[${nowString()}] ${s}\n`; + s = `[${ts.server.nowString()}] ${s}\n`; if (!this.inGroup || this.firstInGroup) { const prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); s = prefix + s; @@ -283,7 +241,7 @@ export function initializeNodeSystem(): StartInput { protected canWrite() { return this.fd >= 0 || this.traceToConsole; } - protected write(s: string, _type: Msg) { + protected write(s: string, _type: ts.server.Msg) { if (this.fd >= 0) { const buf = sys.bufferFrom!(s); // eslint-disable-next-line no-null/no-null @@ -298,7 +256,7 @@ export function initializeNodeSystem(): StartInput { const libDirectory = getDirectoryPath(normalizePath(sys.getExecutingFilePath())); const useWatchGuard = process.platform === "win32"; - const originalWatchDirectory: ServerHost["watchDirectory"] = sys.watchDirectory.bind(sys); + const originalWatchDirectory: ts.server.ServerHost["watchDirectory"] = sys.watchDirectory.bind(sys); const logger = createLogger(); // enable deprecation logging @@ -307,10 +265,10 @@ export function initializeNodeSystem(): StartInput { switch (level) { case ts.LogLevel.Error: case ts.LogLevel.Warning: - return logger.msg(s, Msg.Err); + return logger.msg(s, ts.server.Msg.Err); case ts.LogLevel.Info: case ts.LogLevel.Verbose: - return logger.msg(s, Msg.Info); + return logger.msg(s, ts.server.Msg.Info); } } }; @@ -325,23 +283,23 @@ export function initializeNodeSystem(): StartInput { const cacheKey = extractWatchDirectoryCacheKey(path, currentDrive); let status = cacheKey && statusCache.get(cacheKey); if (status === undefined) { - if (logger.hasLevel(LogLevel.verbose)) { + if (logger.hasLevel(ts.server.LogLevel.verbose)) { logger.info(`${cacheKey} for path ${path} not found in cache...`); } try { const args = [combinePaths(libDirectory, "watchGuard.js"), path]; - if (logger.hasLevel(LogLevel.verbose)) { - logger.info(`Starting ${process.execPath} with args:${stringifyIndented(args)}`); + if (logger.hasLevel(ts.server.LogLevel.verbose)) { + logger.info(`Starting ${process.execPath} with args:${ts.server.stringifyIndented(args)}`); } childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } }); status = true; - if (logger.hasLevel(LogLevel.verbose)) { + if (logger.hasLevel(ts.server.LogLevel.verbose)) { logger.info(`WatchGuard for path ${path} returned: OK`); } } catch (e) { status = false; - if (logger.hasLevel(LogLevel.verbose)) { + if (logger.hasLevel(ts.server.LogLevel.verbose)) { logger.info(`WatchGuard for path ${path} returned: ${e.message}`); } } @@ -349,7 +307,7 @@ export function initializeNodeSystem(): StartInput { statusCache.set(cacheKey, status); } } - else if (logger.hasLevel(LogLevel.verbose)) { + else if (logger.hasLevel(ts.server.LogLevel.verbose)) { logger.info(`watchDirectory for ${path} uses cached drive information.`); } if (status) { @@ -380,16 +338,16 @@ export function initializeNodeSystem(): StartInput { sys.gc = () => global.gc?.(); } - let cancellationToken: ServerCancellationToken; + let cancellationToken: ts.server.ServerCancellationToken; try { const factory = require("./cancellationToken"); cancellationToken = factory(sys.args); } catch (e) { - cancellationToken = nullCancellationToken; + cancellationToken = ts.server.nullCancellationToken; } - const localeStr = findArgument("--locale"); + const localeStr = ts.server.findArgument("--locale"); if (localeStr) { validateLocaleAndSetLanguage(localeStr, sys); } @@ -412,8 +370,8 @@ export function initializeNodeSystem(): StartInput { // TSS_LOG "{ level: "normal | verbose | terse", file?: string}" function createLogger() { - const cmdLineLogFileName = findArgument("--logFile"); - const cmdLineVerbosity = getLogLevel(findArgument("--logVerbosity")); + const cmdLineLogFileName = ts.server.findArgument("--logFile"); + const cmdLineVerbosity = getLogLevel(ts.server.findArgument("--logVerbosity")); const envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG); const unsubstitutedLogFileName = cmdLineLogFileName @@ -494,7 +452,7 @@ function parseEventPort(eventPortStr: string | undefined) { const eventPort = eventPortStr === undefined ? undefined : parseInt(eventPortStr); return eventPort !== undefined && !isNaN(eventPort) ? eventPort : undefined; } -function startNodeSession(options: StartSessionOptions, logger: Logger, cancellationToken: ServerCancellationToken) { +function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger, cancellationToken: ts.server.ServerCancellationToken) { const childProcess: { fork(modulePath: string, args: string[], options?: { execArgv: string[], env?: MapLike }): NodeChildProcess; } = require("child_process"); @@ -523,9 +481,9 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella operation: () => void; } - class NodeTypingsInstaller implements ITypingsInstaller { + class NodeTypingsInstaller implements ts.server.ITypingsInstaller { private installer!: NodeChildProcess; - private projectService!: ProjectService; + private projectService!: ts.server.ProjectService; private activeRequestCount = 0; private requestQueue = createQueue(); private requestMap = new Map(); // Maps operation ID to newest requestQueue entry with that ID @@ -544,14 +502,14 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella constructor( private readonly telemetryEnabled: boolean, - private readonly logger: Logger, - private readonly host: ServerHost, + private readonly logger: ts.server.Logger, + private readonly host: ts.server.ServerHost, readonly globalTypingsCacheLocation: string, readonly typingSafeListLocation: string, readonly typesMapLocation: string, private readonly npmLocation: string | undefined, private readonly validateDefaultNpmLocation: boolean, - private event: server.Event) { + private event: ts.server.Event) { } isKnownTypesPackageName(name: string): boolean { @@ -570,38 +528,38 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella return false; } - installPackage(options: InstallPackageOptionsWithProject): Promise { - this.send({ kind: "installPackage", ...options }); + installPackage(options: ts.server.InstallPackageOptionsWithProject): Promise { + this.send({ kind: "installPackage", ...options }); Debug.assert(this.packageInstalledPromise === undefined); return new Promise((resolve, reject) => { this.packageInstalledPromise = { resolve, reject }; }); } - attach(projectService: ProjectService) { + attach(projectService: ts.server.ProjectService) { this.projectService = projectService; - if (this.logger.hasLevel(LogLevel.requestTime)) { + if (this.logger.hasLevel(ts.server.LogLevel.requestTime)) { this.logger.info("Binding..."); } - const args: string[] = [Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation]; + const args: string[] = [ts.server.Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation]; if (this.telemetryEnabled) { - args.push(Arguments.EnableTelemetry); + args.push(ts.server.Arguments.EnableTelemetry); } if (this.logger.loggingEnabled() && this.logger.getLogFileName()) { - args.push(Arguments.LogFile, combinePaths(getDirectoryPath(normalizeSlashes(this.logger.getLogFileName()!)), `ti-${process.pid}.log`)); + args.push(ts.server.Arguments.LogFile, combinePaths(getDirectoryPath(normalizeSlashes(this.logger.getLogFileName()!)), `ti-${process.pid}.log`)); } if (this.typingSafeListLocation) { - args.push(Arguments.TypingSafeListLocation, this.typingSafeListLocation); + args.push(ts.server.Arguments.TypingSafeListLocation, this.typingSafeListLocation); } if (this.typesMapLocation) { - args.push(Arguments.TypesMapLocation, this.typesMapLocation); + args.push(ts.server.Arguments.TypesMapLocation, this.typesMapLocation); } if (this.npmLocation) { - args.push(Arguments.NpmLocation, this.npmLocation); + args.push(ts.server.Arguments.NpmLocation, this.npmLocation); } if (this.validateDefaultNpmLocation) { - args.push(Arguments.ValidateDefaultNpmLocation); + args.push(ts.server.Arguments.ValidateDefaultNpmLocation); } const execArgv: string[] = []; @@ -633,26 +591,26 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella }); } - onProjectClosed(p: Project): void { + onProjectClosed(p: ts.server.Project): void { this.send({ projectName: p.getProjectName(), kind: "closeProject" }); } - private send(rq: T): void { + private send(rq: T): void { this.installer.send(rq); } - enqueueInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray): void { - const request = createInstallTypingsRequest(project, typeAcquisition, unresolvedImports); - if (this.logger.hasLevel(LogLevel.verbose)) { - if (this.logger.hasLevel(LogLevel.verbose)) { - this.logger.info(`Scheduling throttled operation:${stringifyIndented(request)}`); + enqueueInstallTypingsRequest(project: ts.server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray): void { + const request = ts.server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports); + if (this.logger.hasLevel(ts.server.LogLevel.verbose)) { + if (this.logger.hasLevel(ts.server.LogLevel.verbose)) { + this.logger.info(`Scheduling throttled operation:${ts.server.stringifyIndented(request)}`); } } const operationId = project.getProjectName(); const operation = () => { - if (this.logger.hasLevel(LogLevel.verbose)) { - this.logger.info(`Sending request:${stringifyIndented(request)}`); + if (this.logger.hasLevel(ts.server.LogLevel.verbose)) { + this.logger.info(`Sending request:${ts.server.stringifyIndented(request)}`); } this.send(request); }; @@ -662,7 +620,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella this.scheduleRequest(queuedRequest); } else { - if (this.logger.hasLevel(LogLevel.verbose)) { + if (this.logger.hasLevel(ts.server.LogLevel.verbose)) { this.logger.info(`Deferring request for: ${operationId}`); } this.requestQueue.enqueue(queuedRequest); @@ -670,16 +628,16 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella } } - private handleMessage(response: TypesRegistryResponse | PackageInstalledResponse | SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | InitializationFailedResponse | server.WatchTypingLocations) { - if (this.logger.hasLevel(LogLevel.verbose)) { - this.logger.info(`Received response:${stringifyIndented(response)}`); + private handleMessage(response: ts.server.TypesRegistryResponse | ts.server.PackageInstalledResponse | ts.server.SetTypings | ts.server.InvalidateCachedTypings | ts.server.BeginInstallTypes | ts.server.EndInstallTypes | ts.server.InitializationFailedResponse | ts.server.WatchTypingLocations) { + if (this.logger.hasLevel(ts.server.LogLevel.verbose)) { + this.logger.info(`Received response:${ts.server.stringifyIndented(response)}`); } switch (response.kind) { - case EventTypesRegistry: + case ts.server.EventTypesRegistry: this.typesRegistryCache = new Map(Object.entries(response.typesRegistry)); break; - case ActionPackageInstalled: { + case ts.server.ActionPackageInstalled: { const { success, message } = response; if (success) { this.packageInstalledPromise!.resolve({ successMessage: message }); @@ -695,26 +653,26 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella this.event(response, "setTypings"); break; } - case EventInitializationFailed: { - const body: protocol.TypesInstallerInitializationFailedEventBody = { + case ts.server.EventInitializationFailed: { + const body: ts.server.protocol.TypesInstallerInitializationFailedEventBody = { message: response.message }; - const eventName: protocol.TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed"; + const eventName: ts.server.protocol.TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed"; this.event(body, eventName); break; } - case EventBeginInstallTypes: { - const body: protocol.BeginInstallTypesEventBody = { + case ts.server.EventBeginInstallTypes: { + const body: ts.server.protocol.BeginInstallTypesEventBody = { eventId: response.eventId, packages: response.packagesToInstall, }; - const eventName: protocol.BeginInstallTypesEventName = "beginInstallTypes"; + const eventName: ts.server.protocol.BeginInstallTypesEventName = "beginInstallTypes"; this.event(body, eventName); break; } - case EventEndInstallTypes: { + case ts.server.EventEndInstallTypes: { if (this.telemetryEnabled) { - const body: protocol.TypingsInstalledTelemetryEventBody = { + const body: ts.server.protocol.TypingsInstalledTelemetryEventBody = { telemetryEventName: "typingsInstalled", payload: { installedPackages: response.packagesToInstall.join(","), @@ -722,24 +680,24 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella typingsInstallerVersion: response.typingsInstallerVersion } }; - const eventName: protocol.TelemetryEventName = "telemetry"; + const eventName: ts.server.protocol.TelemetryEventName = "telemetry"; this.event(body, eventName); } - const body: protocol.EndInstallTypesEventBody = { + const body: ts.server.protocol.EndInstallTypesEventBody = { eventId: response.eventId, packages: response.packagesToInstall, success: response.installSuccess, }; - const eventName: protocol.EndInstallTypesEventName = "endInstallTypes"; + const eventName: ts.server.protocol.EndInstallTypesEventName = "endInstallTypes"; this.event(body, eventName); break; } - case ActionInvalidate: { + case ts.server.ActionInvalidate: { this.projectService.updateTypingsForProject(response); break; } - case ActionSet: { + case ts.server.ActionSet: { if (this.activeRequestCount > 0) { this.activeRequestCount--; } @@ -755,7 +713,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella break; } - if (this.logger.hasLevel(LogLevel.verbose)) { + if (this.logger.hasLevel(ts.server.LogLevel.verbose)) { this.logger.info(`Skipping defunct request for: ${queuedRequest.operationId}`); } } @@ -766,7 +724,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella break; } - case ActionWatchTypingLocations: + case ts.server.ActionWatchTypingLocations: this.projectService.watchTypingLocations(response); break; default: @@ -775,7 +733,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella } private scheduleRequest(request: QueuedOperation) { - if (this.logger.hasLevel(LogLevel.verbose)) { + if (this.logger.hasLevel(ts.server.LogLevel.verbose)) { this.logger.info(`Scheduling request for: ${request.operationId}`); } this.activeRequestCount++; @@ -783,7 +741,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella } } - class IOSession extends Session { + class IOSession extends ts.server.Session { private eventPort: number | undefined; private eventSocket: NodeSocket | undefined; private socketEventQueue: { body: any, eventName: string }[] | undefined; @@ -795,7 +753,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella this.event(body, eventName); }; - const host = sys as ServerHost; + const host = sys as ts.server.ServerHost; const typingsInstaller = disableAutomaticTypingAcquisition ? undefined @@ -805,7 +763,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella host, cancellationToken, ...options, - typingsInstaller: typingsInstaller || nullTypingsInstaller, + typingsInstaller: typingsInstaller || ts.server.nullTypingsInstaller, byteLength: Buffer.byteLength, hrtime: process.hrtime, logger, @@ -835,7 +793,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella if (this.canUseEvents && this.eventPort) { if (!this.eventSocket) { - if (this.logger.hasLevel(LogLevel.verbose)) { + if (this.logger.hasLevel(ts.server.LogLevel.verbose)) { this.logger.info(`eventPort: event "${eventName}" queued, but socket not yet initialized`); } (this.socketEventQueue || (this.socketEventQueue = [])).push({ body, eventName }); @@ -852,7 +810,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella } private writeToEventSocket(body: object, eventName: string): void { - this.eventSocket!.write(formatMessage(toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8"); + this.eventSocket!.write(ts.server.formatMessage(ts.server.toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8"); } override exit() { @@ -876,18 +834,18 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella class IpcIOSession extends IOSession { - protected override writeMessage(msg: protocol.Message): void { - const verboseLogging = logger.hasLevel(LogLevel.verbose); + protected override writeMessage(msg: ts.server.protocol.Message): void { + const verboseLogging = logger.hasLevel(ts.server.LogLevel.verbose); if (verboseLogging) { const json = JSON.stringify(msg); - logger.info(`${msg.type}:${indent(json)}`); + logger.info(`${msg.type}:${ts.server.indent(json)}`); } process.send!(msg); } - protected override parseMessage(message: any): protocol.Request { - return message as protocol.Request; + protected override parseMessage(message: any): ts.server.protocol.Request { + return message as ts.server.protocol.Request; } protected override toStringMessage(message: any) { @@ -905,15 +863,15 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella } } - const eventPort: number | undefined = parseEventPort(findArgument("--eventPort")); - const typingSafeListLocation = findArgument(Arguments.TypingSafeListLocation)!; // TODO: GH#18217 - const typesMapLocation = findArgument(Arguments.TypesMapLocation) || combinePaths(getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); - const npmLocation = findArgument(Arguments.NpmLocation); - const validateDefaultNpmLocation = hasArgument(Arguments.ValidateDefaultNpmLocation); - const disableAutomaticTypingAcquisition = hasArgument("--disableAutomaticTypingAcquisition"); - const useNodeIpc = hasArgument("--useNodeIpc"); - const telemetryEnabled = hasArgument(Arguments.EnableTelemetry); - const commandLineTraceDir = findArgument("--traceDirectory"); + const eventPort: number | undefined = parseEventPort(ts.server.findArgument("--eventPort")); + const typingSafeListLocation = ts.server.findArgument(ts.server.Arguments.TypingSafeListLocation)!; // TODO: GH#18217 + const typesMapLocation = ts.server.findArgument(ts.server.Arguments.TypesMapLocation) || combinePaths(getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); + const npmLocation = ts.server.findArgument(ts.server.Arguments.NpmLocation); + const validateDefaultNpmLocation = ts.server.hasArgument(ts.server.Arguments.ValidateDefaultNpmLocation); + const disableAutomaticTypingAcquisition = ts.server.hasArgument("--disableAutomaticTypingAcquisition"); + const useNodeIpc = ts.server.hasArgument("--useNodeIpc"); + const telemetryEnabled = ts.server.hasArgument(ts.server.Arguments.EnableTelemetry); + const commandLineTraceDir = ts.server.findArgument("--traceDirectory"); const traceDir = commandLineTraceDir ? stripQuotes(commandLineTraceDir) : process.env.TSS_TRACE; diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index f752178022f08..fd874729ca89e 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -1,24 +1,13 @@ -import { - Debug, - setStackTraceLimit, - sys, - version, -} from "./_namespaces/ts"; -import { - emptyArray, - findArgument, - hasArgument, - initializeNodeSystem, - Msg, - StartInput, -} from "./_namespaces/ts.server"; +import * as ts from "typescript"; + +import { StartInput } from "./common"; +import { initializeNodeSystem } from "./nodeServer"; -export * from "./_namespaces/ts"; function findArgumentStringArray(argName: string): readonly string[] { - const arg = findArgument(argName); + const arg = ts.server.findArgument(argName); if (arg === undefined) { - return emptyArray; + return ts.emptyArray; } return arg.split(",").filter(name => name !== ""); } @@ -27,38 +16,38 @@ function findArgumentStringArray(argName: string): readonly string[] { function start({ args, logger, cancellationToken, serverMode, unknownServerMode, startSession: startServer }: StartInput, platform: string) { logger.info(`Starting TS Server`); - logger.info(`Version: ${version}`); + logger.info(`Version: ${ts.version}`); logger.info(`Arguments: ${args.join(" ")}`); - logger.info(`Platform: ${platform} NodeVersion: ${process.version} CaseSensitive: ${sys.useCaseSensitiveFileNames}`); + logger.info(`Platform: ${platform} NodeVersion: ${process.version} CaseSensitive: ${ts.sys.useCaseSensitiveFileNames}`); logger.info(`ServerMode: ${serverMode} hasUnknownServerMode: ${unknownServerMode}`); - setStackTraceLimit(); + ts.setStackTraceLimit(); - if (Debug.isDebugging) { - Debug.enableDebugInfo(); + if (ts.Debug.isDebugging) { + ts.Debug.enableDebugInfo(); } - if (sys.tryEnableSourceMapsForHost && /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV"))) { - sys.tryEnableSourceMapsForHost(); + if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) { + ts.sys.tryEnableSourceMapsForHost(); } // Overwrites the current console messages to instead write to // the log. This is so that language service plugins which use // console.log don't break the message passing between tsserver // and the client - console.log = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), Msg.Info); - console.warn = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), Msg.Err); - console.error = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), Msg.Err); + console.log = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), ts.server.Msg.Info); + console.warn = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), ts.server.Msg.Err); + console.error = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), ts.server.Msg.Err); startServer( { globalPlugins: findArgumentStringArray("--globalPlugins"), pluginProbeLocations: findArgumentStringArray("--pluginProbeLocations"), - allowLocalPluginLoads: hasArgument("--allowLocalPluginLoads"), - useSingleInferredProject: hasArgument("--useSingleInferredProject"), - useInferredProjectPerProjectRoot: hasArgument("--useInferredProjectPerProjectRoot"), - suppressDiagnosticEvents: hasArgument("--suppressDiagnosticEvents"), - noGetErrOnBackgroundUpdate: hasArgument("--noGetErrOnBackgroundUpdate"), + allowLocalPluginLoads: ts.server.hasArgument("--allowLocalPluginLoads"), + useSingleInferredProject: ts.server.hasArgument("--useSingleInferredProject"), + useInferredProjectPerProjectRoot: ts.server.hasArgument("--useInferredProjectPerProjectRoot"), + suppressDiagnosticEvents: ts.server.hasArgument("--suppressDiagnosticEvents"), + noGetErrOnBackgroundUpdate: ts.server.hasArgument("--noGetErrOnBackgroundUpdate"), serverMode }, logger, @@ -66,5 +55,5 @@ function start({ args, logger, cancellationToken, serverMode, unknownServerMode, ); } -setStackTraceLimit(); +ts.setStackTraceLimit(); start(initializeNodeSystem(), require("os").platform()); diff --git a/src/tsserver/tsconfig.json b/src/tsserver/tsconfig.json index f24abdaf6fc07..50c711e9363bc 100644 --- a/src/tsserver/tsconfig.json +++ b/src/tsserver/tsconfig.json @@ -4,13 +4,13 @@ "compilerOptions": { "types": [ "node" - ] + ], + "paths": { + "typescript": ["../typescript/typescript"] + } }, "references": [ - { "path": "../compiler" }, - { "path": "../services" }, - { "path": "../jsTyping" }, - { "path": "../server" }, + { "path": "../typescript" }, ], "include": ["**/*"] } From 8318c80be332801e4b4a5869790e37c201844bae Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Mon, 11 Dec 2023 12:19:56 -0800 Subject: [PATCH 02/10] fmt --- src/tsserver/server.ts | 9 ++++++--- src/tsserver/tsconfig.json | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 0ca227bbc9d3a..b7ce8c5fe3b03 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -1,8 +1,11 @@ import * as ts from "typescript"; -import { StartInput } from "./common"; -import { initializeNodeSystem } from "./nodeServer"; - +import { + StartInput, +} from "./common"; +import { + initializeNodeSystem, +} from "./nodeServer"; function findArgumentStringArray(argName: string): readonly string[] { const arg = ts.server.findArgument(argName); diff --git a/src/tsserver/tsconfig.json b/src/tsserver/tsconfig.json index 6699daf23766d..f6748593e8ae4 100644 --- a/src/tsserver/tsconfig.json +++ b/src/tsserver/tsconfig.json @@ -10,7 +10,7 @@ } }, "references": [ - { "path": "../typescript" }, + { "path": "../typescript" } ], "include": ["**/*"] } From fde5d2f2ba60608f80be4d6d69dfb9b2e527db3f Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Fri, 8 Mar 2024 13:50:31 -0800 Subject: [PATCH 03/10] Rework a little --- Herebyfile.mjs | 26 +++++++++++++++++++------- src/tsserver/_namespaces/ts.ts | 1 + src/tsserver/common.ts | 2 +- src/tsserver/nodeServer.ts | 5 ++--- src/tsserver/server.ts | 3 +-- src/tsserver/tsconfig.json | 5 +---- 6 files changed, 25 insertions(+), 17 deletions(-) create mode 100644 src/tsserver/_namespaces/ts.ts diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 54010ff849e86..3da60f47a1e15 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -184,6 +184,7 @@ async function runDtsBundler(entrypoint, output) { * @typedef BundlerTaskOptions * @property {boolean} [exportIsTsObject] * @property {boolean} [treeShaking] + * @property {boolean} [useTypeScriptPublicAPI] * @property {() => void} [onWatchRebuild] */ function createBundler(entrypoint, outfile, taskOptions = {}) { @@ -204,14 +205,23 @@ function createBundler(entrypoint, outfile, taskOptions = {}) { sourcesContent: false, treeShaking: taskOptions.treeShaking, packages: "external", - external: ["typescript", "./typescript.js"], - alias: { - typescript: "./typescript.js", - }, logLevel: "warning", // legalComments: "none", // If we add copyright headers to the source files, uncomment. }; + if (taskOptions.useTypeScriptPublicAPI) { + options.external = ["./typescript.js"]; + options.plugins ||= []; + options.plugins.push({ + name: "remap-typescript-to-require", + setup(build) { + build.onLoad({ filter: /src[\\/]typescript[\\/]typescript\.ts$/ }, () => { + return { contents: `export * from "./typescript.js"` }; + }); + }, + }); + } + if (taskOptions.exportIsTsObject) { // Monaco bundles us as ESM by wrapping our code with something that defines module.exports // but then does not use it, instead using the `ts` variable. Ensure that if we think we're CJS @@ -239,9 +249,10 @@ function createBundler(entrypoint, outfile, taskOptions = {}) { const toCommonJsRegExp = /var __toCommonJS .*/; const toCommonJsRegExpReplacement = "var __toCommonJS = (mod) => (__copyProps, mod); // Modified helper to skip setting __esModule."; - options.plugins = [ + options.plugins ||= []; + options.plugins.push( { - name: "post-process", + name: "post-process-exports", setup: build => { build.onEnd(async () => { let contents = await fs.promises.readFile(outfile, "utf-8"); @@ -256,7 +267,7 @@ function createBundler(entrypoint, outfile, taskOptions = {}) { }); }, }, - ]; + ); } return options; @@ -427,6 +438,7 @@ const { main: tsserver, watch: watchTsserver } = entrypointBuildTask({ builtEntrypoint: "./built/local/tsserver/server.js", output: "./built/local/tsserver.js", mainDeps: [generateLibs, services], + bundlerOptions: { useTypeScriptPublicAPI: true }, }); export { tsserver, watchTsserver }; diff --git a/src/tsserver/_namespaces/ts.ts b/src/tsserver/_namespaces/ts.ts new file mode 100644 index 0000000000000..205e6849694b0 --- /dev/null +++ b/src/tsserver/_namespaces/ts.ts @@ -0,0 +1 @@ +export * from "../../typescript/typescript"; diff --git a/src/tsserver/common.ts b/src/tsserver/common.ts index dd132451b955c..3a973486cbd73 100644 --- a/src/tsserver/common.ts +++ b/src/tsserver/common.ts @@ -1,4 +1,4 @@ -import * as ts from "typescript"; +import * as ts from "./_namespaces/ts"; /** @internal */ export function getLogLevel(level: string | undefined) { diff --git a/src/tsserver/nodeServer.ts b/src/tsserver/nodeServer.ts index d3b5ec98b93c7..09ad7a88f830e 100644 --- a/src/tsserver/nodeServer.ts +++ b/src/tsserver/nodeServer.ts @@ -23,9 +23,8 @@ import { validateLocaleAndSetLanguage, versionMajorMinor, WatchOptions, -} from "typescript"; -import * as ts from "typescript"; - +} from "./_namespaces/ts"; +import * as ts from "./_namespaces/ts"; import { getLogLevel, StartInput, diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index b7ce8c5fe3b03..bcd6f78d84e5b 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -1,5 +1,4 @@ -import * as ts from "typescript"; - +import * as ts from "./_namespaces/ts"; import { StartInput, } from "./common"; diff --git a/src/tsserver/tsconfig.json b/src/tsserver/tsconfig.json index f6748593e8ae4..69c24a3936b74 100644 --- a/src/tsserver/tsconfig.json +++ b/src/tsserver/tsconfig.json @@ -4,10 +4,7 @@ "compilerOptions": { "types": [ "node" - ], - "paths": { - "typescript": ["../typescript/typescript"] - } + ] }, "references": [ { "path": "../typescript" } From 9ffd92c61153377aa54383fff54e3560e5b1bca7 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Fri, 8 Mar 2024 13:52:34 -0800 Subject: [PATCH 04/10] yay node 14 --- Herebyfile.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 3da60f47a1e15..6dbc13f9de07d 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -211,7 +211,7 @@ function createBundler(entrypoint, outfile, taskOptions = {}) { if (taskOptions.useTypeScriptPublicAPI) { options.external = ["./typescript.js"]; - options.plugins ||= []; + options.plugins = options.plugins || []; options.plugins.push({ name: "remap-typescript-to-require", setup(build) { @@ -249,7 +249,7 @@ function createBundler(entrypoint, outfile, taskOptions = {}) { const toCommonJsRegExp = /var __toCommonJS .*/; const toCommonJsRegExpReplacement = "var __toCommonJS = (mod) => (__copyProps, mod); // Modified helper to skip setting __esModule."; - options.plugins ||= []; + options.plugins = options.plugins || []; options.plugins.push( { name: "post-process-exports", From 7184143a70dc3e6f204eb09bd78fcb0001ae823b Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Fri, 8 Mar 2024 14:00:08 -0800 Subject: [PATCH 05/10] now do typingsInstaller --- Herebyfile.mjs | 2 + src/typingsInstaller/_namespaces/ts.server.ts | 6 -- .../_namespaces/ts.server.typingsInstaller.ts | 4 -- src/typingsInstaller/_namespaces/ts.ts | 8 +-- src/typingsInstaller/nodeTypingsInstaller.ts | 58 +++++++------------ src/typingsInstaller/tsconfig.json | 4 +- 6 files changed, 25 insertions(+), 57 deletions(-) delete mode 100644 src/typingsInstaller/_namespaces/ts.server.ts delete mode 100644 src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 6dbc13f9de07d..969841de73875 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -588,6 +588,8 @@ const { main: typingsInstaller, watch: watchTypingsInstaller } = entrypointBuild srcEntrypoint: "./src/typingsInstaller/nodeTypingsInstaller.ts", builtEntrypoint: "./built/local/typingsInstaller/nodeTypingsInstaller.js", output: "./built/local/typingsInstaller.js", + mainDeps: [services], + bundlerOptions: { useTypeScriptPublicAPI: true }, }); const { main: watchGuard, watch: watchWatchGuard } = entrypointBuildTask({ diff --git a/src/typingsInstaller/_namespaces/ts.server.ts b/src/typingsInstaller/_namespaces/ts.server.ts deleted file mode 100644 index 97838f9d9818c..0000000000000 --- a/src/typingsInstaller/_namespaces/ts.server.ts +++ /dev/null @@ -1,6 +0,0 @@ -/* Generated file to emulate the ts.server namespace. */ - -export * from "../../jsTyping/_namespaces/ts.server"; -export * from "../../typingsInstallerCore/_namespaces/ts.server"; -import * as typingsInstaller from "./ts.server.typingsInstaller"; -export { typingsInstaller }; diff --git a/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts b/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts deleted file mode 100644 index 595dd244d302e..0000000000000 --- a/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts +++ /dev/null @@ -1,4 +0,0 @@ -/* Generated file to emulate the ts.server.typingsInstaller namespace. */ - -export * from "../../typingsInstallerCore/_namespaces/ts.server.typingsInstaller"; -export * from "../nodeTypingsInstaller"; diff --git a/src/typingsInstaller/_namespaces/ts.ts b/src/typingsInstaller/_namespaces/ts.ts index efb16fe7a138d..205e6849694b0 100644 --- a/src/typingsInstaller/_namespaces/ts.ts +++ b/src/typingsInstaller/_namespaces/ts.ts @@ -1,7 +1 @@ -/* Generated file to emulate the ts namespace. */ - -export * from "../../compiler/_namespaces/ts"; -export * from "../../jsTyping/_namespaces/ts"; -export * from "../../typingsInstallerCore/_namespaces/ts"; -import * as server from "./ts.server"; -export { server }; +export * from "../../typescript/typescript"; diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index 46ca2f41c484d..4846a1e40d30c 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -12,25 +12,9 @@ import { toPath, version, } from "./_namespaces/ts"; -import { - Arguments, - findArgument, - hasArgument, - InitializationFailedResponse, - InstallTypingHost, - nowString, - stringifyIndented, - TypingInstallerRequestUnion, - TypingInstallerResponseUnion, -} from "./_namespaces/ts.server"; -import { - installNpmPackages, - Log, - RequestCompletedAction, - TypingsInstaller, -} from "./_namespaces/ts.server.typingsInstaller"; +import * as ts from "./_namespaces/ts"; -class FileLog implements Log { +class FileLog implements ts.server.typingsInstaller.Log { constructor(private logFile: string | undefined) { } @@ -41,7 +25,7 @@ class FileLog implements Log { if (typeof this.logFile !== "string") return; try { - fs.appendFileSync(this.logFile, `[${nowString()}] ${text}${sys.newLine}`); + fs.appendFileSync(this.logFile, `[${ts.server.nowString()}] ${text}${sys.newLine}`); } catch (e) { this.logFile = undefined; @@ -50,7 +34,7 @@ class FileLog implements Log { } /** Used if `--npmLocation` is not passed. */ -function getDefaultNPMLocation(processName: string, validateDefaultNpmLocation: boolean, host: InstallTypingHost): string { +function getDefaultNPMLocation(processName: string, validateDefaultNpmLocation: boolean, host: ts.server.InstallTypingHost): string { if (path.basename(processName).indexOf("node") === 0) { const npmPath = path.join(path.dirname(process.argv[0]), "npm"); if (!validateDefaultNpmLocation) { @@ -67,7 +51,7 @@ interface TypesRegistryFile { entries: MapLike>; } -function loadTypesRegistryFile(typesRegistryFilePath: string, host: InstallTypingHost, log: Log): Map> { +function loadTypesRegistryFile(typesRegistryFilePath: string, host: ts.server.InstallTypingHost, log: ts.server.typingsInstaller.Log): Map> { if (!host.fileExists(typesRegistryFilePath)) { if (log.isEnabled()) { log.writeLine(`Types registry file '${typesRegistryFilePath}' does not exist`); @@ -97,14 +81,14 @@ interface ExecSyncOptions { } type ExecSync = (command: string, options: ExecSyncOptions) => string; -export class NodeTypingsInstaller extends TypingsInstaller { +export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInstaller { private readonly nodeExecSync: ExecSync; private readonly npmPath: string; readonly typesRegistry: Map>; - private delayedInitializationError: InitializationFailedResponse | undefined; + private delayedInitializationError: ts.server.InitializationFailedResponse | undefined; - constructor(globalTypingsCacheLocation: string, typingSafeListLocation: string, typesMapLocation: string, npmLocation: string | undefined, validateDefaultNpmLocation: boolean, throttleLimit: number, log: Log) { + constructor(globalTypingsCacheLocation: string, typingSafeListLocation: string, typesMapLocation: string, npmLocation: string | undefined, validateDefaultNpmLocation: boolean, throttleLimit: number, log: ts.server.typingsInstaller.Log) { const libDirectory = getDirectoryPath(normalizePath(sys.getExecutingFilePath())); super( sys, @@ -122,7 +106,7 @@ export class NodeTypingsInstaller extends TypingsInstaller { } if (this.log.isEnabled()) { this.log.writeLine(`Process id: ${process.pid}`); - this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`); + this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${ts.server.Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`); this.log.writeLine(`validateDefaultNpmLocation: ${validateDefaultNpmLocation}`); } ({ execSync: this.nodeExecSync } = require("child_process")); @@ -153,7 +137,7 @@ export class NodeTypingsInstaller extends TypingsInstaller { this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), this.installTypingHost, this.log); } - override handleRequest(req: TypingInstallerRequestUnion) { + override handleRequest(req: ts.server.TypingInstallerRequestUnion) { if (this.delayedInitializationError) { // report initializationFailed error this.sendResponse(this.delayedInitializationError); @@ -162,9 +146,9 @@ export class NodeTypingsInstaller extends TypingsInstaller { super.handleRequest(req); } - protected sendResponse(response: TypingInstallerResponseUnion) { + protected sendResponse(response: ts.server.TypingInstallerResponseUnion) { if (this.log.isEnabled()) { - this.log.writeLine(`Sending response:${stringifyIndented(response)}`); + this.log.writeLine(`Sending response:${ts.server.stringifyIndented(response)}`); } process.send!(response); // TODO: GH#18217 if (this.log.isEnabled()) { @@ -172,12 +156,12 @@ export class NodeTypingsInstaller extends TypingsInstaller { } } - protected installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void { + protected installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: ts.server.typingsInstaller.RequestCompletedAction): void { if (this.log.isEnabled()) { this.log.writeLine(`#${requestId} with cwd: ${cwd} arguments: ${JSON.stringify(packageNames)}`); } const start = Date.now(); - const hasError = installNpmPackages(this.npmPath, version, packageNames, command => this.execSyncAndLog(command, { cwd })); + const hasError = ts.server.typingsInstaller.installNpmPackages(this.npmPath, version, packageNames, command => this.execSyncAndLog(command, { cwd })); if (this.log.isEnabled()) { this.log.writeLine(`npm install #${requestId} took: ${Date.now() - start} ms`); } @@ -204,12 +188,12 @@ export class NodeTypingsInstaller extends TypingsInstaller { } } -const logFilePath = findArgument(Arguments.LogFile); -const globalTypingsCacheLocation = findArgument(Arguments.GlobalCacheLocation); -const typingSafeListLocation = findArgument(Arguments.TypingSafeListLocation); -const typesMapLocation = findArgument(Arguments.TypesMapLocation); -const npmLocation = findArgument(Arguments.NpmLocation); -const validateDefaultNpmLocation = hasArgument(Arguments.ValidateDefaultNpmLocation); +const logFilePath = ts.server.findArgument(ts.server.Arguments.LogFile); +const globalTypingsCacheLocation = ts.server.findArgument(ts.server.Arguments.GlobalCacheLocation); +const typingSafeListLocation = ts.server.findArgument(ts.server.Arguments.TypingSafeListLocation); +const typesMapLocation = ts.server.findArgument(ts.server.Arguments.TypesMapLocation); +const npmLocation = ts.server.findArgument(ts.server.Arguments.NpmLocation); +const validateDefaultNpmLocation = ts.server.hasArgument(ts.server.Arguments.ValidateDefaultNpmLocation); const log = new FileLog(logFilePath); if (log.isEnabled()) { @@ -224,7 +208,7 @@ process.on("disconnect", () => { process.exit(0); }); let installer: NodeTypingsInstaller | undefined; -process.on("message", (req: TypingInstallerRequestUnion) => { +process.on("message", (req: ts.server.TypingInstallerRequestUnion) => { installer ??= new NodeTypingsInstaller(globalTypingsCacheLocation!, typingSafeListLocation!, typesMapLocation!, npmLocation, validateDefaultNpmLocation, /*throttleLimit*/ 5, log); // TODO: GH#18217 installer.handleRequest(req); }); diff --git a/src/typingsInstaller/tsconfig.json b/src/typingsInstaller/tsconfig.json index 8dcebe6b4d15a..0bb3c6c017c7a 100644 --- a/src/typingsInstaller/tsconfig.json +++ b/src/typingsInstaller/tsconfig.json @@ -6,9 +6,7 @@ ] }, "references": [ - { "path": "../compiler" }, - { "path": "../jsTyping" }, - { "path": "../typingsInstallerCore" } + { "path": "../typescript" } ], "include": ["**/*"] } From dcf3c7086e4ed32857d5be70125c24015c6d037a Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Fri, 8 Mar 2024 14:14:27 -0800 Subject: [PATCH 06/10] Revert eslint config --- src/tsconfig-eslint.json | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/tsconfig-eslint.json b/src/tsconfig-eslint.json index bb9dde7b56fdc..087b75ff7dc15 100644 --- a/src/tsconfig-eslint.json +++ b/src/tsconfig-eslint.json @@ -1,9 +1,6 @@ { "extends": "./tsconfig-base", "compilerOptions": { - "types": ["node", "mocha", "chai"], - "paths": { - "typescript": ["./typescript/typescript"] - } + "types": ["node", "mocha", "chai"] } } From 40601ab606096b3252511a91049bf674b6a93b68 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Fri, 8 Mar 2024 14:15:12 -0800 Subject: [PATCH 07/10] Simplfy terms --- Herebyfile.mjs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 969841de73875..40a56b13bbb68 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -184,7 +184,7 @@ async function runDtsBundler(entrypoint, output) { * @typedef BundlerTaskOptions * @property {boolean} [exportIsTsObject] * @property {boolean} [treeShaking] - * @property {boolean} [useTypeScriptPublicAPI] + * @property {boolean} [usePublicAPI] * @property {() => void} [onWatchRebuild] */ function createBundler(entrypoint, outfile, taskOptions = {}) { @@ -209,7 +209,7 @@ function createBundler(entrypoint, outfile, taskOptions = {}) { // legalComments: "none", // If we add copyright headers to the source files, uncomment. }; - if (taskOptions.useTypeScriptPublicAPI) { + if (taskOptions.usePublicAPI) { options.external = ["./typescript.js"]; options.plugins = options.plugins || []; options.plugins.push({ @@ -438,7 +438,7 @@ const { main: tsserver, watch: watchTsserver } = entrypointBuildTask({ builtEntrypoint: "./built/local/tsserver/server.js", output: "./built/local/tsserver.js", mainDeps: [generateLibs, services], - bundlerOptions: { useTypeScriptPublicAPI: true }, + bundlerOptions: { usePublicAPI: true }, }); export { tsserver, watchTsserver }; @@ -589,7 +589,7 @@ const { main: typingsInstaller, watch: watchTypingsInstaller } = entrypointBuild builtEntrypoint: "./built/local/typingsInstaller/nodeTypingsInstaller.js", output: "./built/local/typingsInstaller.js", mainDeps: [services], - bundlerOptions: { useTypeScriptPublicAPI: true }, + bundlerOptions: { usePublicAPI: true }, }); const { main: watchGuard, watch: watchWatchGuard } = entrypointBuildTask({ From 273e354bb2528d05bc2fda78711fd952c478f583 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Fri, 15 Mar 2024 11:25:29 -0700 Subject: [PATCH 08/10] Update Herebyfile.mjs --- Herebyfile.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 40a56b13bbb68..fd5e48752b568 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -252,7 +252,7 @@ function createBundler(entrypoint, outfile, taskOptions = {}) { options.plugins = options.plugins || []; options.plugins.push( { - name: "post-process-exports", + name: "post-process", setup: build => { build.onEnd(async () => { let contents = await fs.promises.readFile(outfile, "utf-8"); From 1e5fd9db2ab53c23bebd7dffab389998ea488e4d Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Fri, 15 Mar 2024 11:46:19 -0700 Subject: [PATCH 09/10] Restore namespace files and pass through namespaces --- src/tsserver/_namespaces/ts.server.ts | 2 + src/tsserver/common.ts | 40 +++-- src/tsserver/nodeServer.ts | 140 ++++++++++-------- src/tsserver/server.ts | 53 ++++--- src/typingsInstaller/_namespaces/ts.server.ts | 2 + .../_namespaces/ts.server.typingsInstaller.ts | 2 + src/typingsInstaller/nodeTypingsInstaller.ts | 58 +++++--- 7 files changed, 180 insertions(+), 117 deletions(-) create mode 100644 src/tsserver/_namespaces/ts.server.ts create mode 100644 src/typingsInstaller/_namespaces/ts.server.ts create mode 100644 src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts diff --git a/src/tsserver/_namespaces/ts.server.ts b/src/tsserver/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..04e8befd7ecc6 --- /dev/null +++ b/src/tsserver/_namespaces/ts.server.ts @@ -0,0 +1,2 @@ +import * as ts from "../../typescript/typescript"; +export = ts.server; diff --git a/src/tsserver/common.ts b/src/tsserver/common.ts index 3a973486cbd73..c21f3ba1dfd5c 100644 --- a/src/tsserver/common.ts +++ b/src/tsserver/common.ts @@ -1,12 +1,20 @@ -import * as ts from "./_namespaces/ts"; +import { + LanguageServiceMode, +} from "./_namespaces/ts"; +import { + Logger, + LogLevel, + ServerCancellationToken, + SessionOptions, +} from "./_namespaces/ts.server"; /** @internal */ export function getLogLevel(level: string | undefined) { if (level) { const l = level.toLowerCase(); - for (const name in ts.server.LogLevel) { + for (const name in LogLevel) { if (isNaN(+name) && l === name.toLowerCase()) { - return ts.server.LogLevel[name] as any as ts.server.LogLevel; + return LogLevel[name] as any as LogLevel; } } } @@ -15,23 +23,23 @@ export function getLogLevel(level: string | undefined) { /** @internal */ export interface StartSessionOptions { - globalPlugins: ts.server.SessionOptions["globalPlugins"]; - pluginProbeLocations: ts.server.SessionOptions["pluginProbeLocations"]; - allowLocalPluginLoads: ts.server.SessionOptions["allowLocalPluginLoads"]; - useSingleInferredProject: ts.server.SessionOptions["useSingleInferredProject"]; - useInferredProjectPerProjectRoot: ts.server.SessionOptions["useInferredProjectPerProjectRoot"]; - suppressDiagnosticEvents: ts.server.SessionOptions["suppressDiagnosticEvents"]; - noGetErrOnBackgroundUpdate: ts.server.SessionOptions["noGetErrOnBackgroundUpdate"]; - canUseWatchEvents: ts.server.SessionOptions["canUseWatchEvents"]; - serverMode: ts.server.SessionOptions["serverMode"]; + globalPlugins: SessionOptions["globalPlugins"]; + pluginProbeLocations: SessionOptions["pluginProbeLocations"]; + allowLocalPluginLoads: SessionOptions["allowLocalPluginLoads"]; + useSingleInferredProject: SessionOptions["useSingleInferredProject"]; + useInferredProjectPerProjectRoot: SessionOptions["useInferredProjectPerProjectRoot"]; + suppressDiagnosticEvents: SessionOptions["suppressDiagnosticEvents"]; + noGetErrOnBackgroundUpdate: SessionOptions["noGetErrOnBackgroundUpdate"]; + canUseWatchEvents: SessionOptions["canUseWatchEvents"]; + serverMode: SessionOptions["serverMode"]; } /** @internal */ export interface StartInput { args: readonly string[]; - logger: ts.server.Logger; - cancellationToken: ts.server.ServerCancellationToken; - serverMode: ts.LanguageServiceMode | undefined; + logger: Logger; + cancellationToken: ServerCancellationToken; + serverMode: LanguageServiceMode | undefined; unknownServerMode?: string; - startSession: (option: StartSessionOptions, logger: ts.server.Logger, cancellationToken: ts.server.ServerCancellationToken) => void; + startSession: (option: StartSessionOptions, logger: Logger, cancellationToken: ServerCancellationToken) => void; } diff --git a/src/tsserver/nodeServer.ts b/src/tsserver/nodeServer.ts index 09ad7a88f830e..81043a45daefd 100644 --- a/src/tsserver/nodeServer.ts +++ b/src/tsserver/nodeServer.ts @@ -1,3 +1,5 @@ +import * as protocol from "../server/protocol"; +import * as ts from "./_namespaces/ts"; import { CharacterCodes, combinePaths, @@ -24,7 +26,25 @@ import { versionMajorMinor, WatchOptions, } from "./_namespaces/ts"; -import * as ts from "./_namespaces/ts"; +import { + Arguments, + Event, + findArgument, + formatMessage, + hasArgument, + indent, + Logger, + LogLevel, + Msg, + nowString, + nullCancellationToken, + ServerCancellationToken, + ServerHost, + Session, + stringifyIndented, + toEvent, + TypingsInstallerAdapter, +} from "./_namespaces/ts.server"; import { getLogLevel, StartInput, @@ -33,7 +53,7 @@ import { interface LogOptions { file?: string; - detailLevel?: ts.server.LogLevel; + detailLevel?: LogLevel; traceToConsole?: boolean; logToFile?: boolean; } @@ -74,7 +94,7 @@ function parseLoggingEnvironmentString(logEnvStr: string | undefined): LogOption break; case "-level": const level = getLogLevel(value); - logEnv.detailLevel = level !== undefined ? level : ts.server.LogLevel.normal; + logEnv.detailLevel = level !== undefined ? level : LogLevel.normal; break; case "-traceToConsole": logEnv.traceToConsole = value.toLowerCase() === "true"; @@ -106,7 +126,7 @@ function parseLoggingEnvironmentString(logEnvStr: string | undefined): LogOption } function parseServerMode(): LanguageServiceMode | string | undefined { - const mode = ts.server.findArgument("--serverMode"); + const mode = findArgument("--serverMode"); if (!mode) return undefined; switch (mode.toLowerCase()) { @@ -123,7 +143,7 @@ function parseServerMode(): LanguageServiceMode | string | undefined { /** @internal */ export function initializeNodeSystem(): StartInput { - const sys = Debug.checkDefined(ts.sys) as ts.server.ServerHost; + const sys = Debug.checkDefined(ts.sys) as ServerHost; const childProcess: { execFileSync(file: string, args: string[], options: { stdio: "ignore"; env: MapLike; }): string | Buffer; } = require("child_process"); @@ -168,7 +188,7 @@ export function initializeNodeSystem(): StartInput { constructor( private readonly logFilename: string, private readonly traceToConsole: boolean, - private readonly level: ts.server.LogLevel, + private readonly level: LogLevel, ) { if (this.logFilename) { try { @@ -191,13 +211,13 @@ export function initializeNodeSystem(): StartInput { return this.logFilename; } perftrc(s: string) { - this.msg(s, ts.server.Msg.Perf); + this.msg(s, Msg.Perf); } info(s: string) { - this.msg(s, ts.server.Msg.Info); + this.msg(s, Msg.Info); } err(s: string) { - this.msg(s, ts.server.Msg.Err); + this.msg(s, Msg.Err); } startGroup() { this.inGroup = true; @@ -209,15 +229,15 @@ export function initializeNodeSystem(): StartInput { loggingEnabled() { return !!this.logFilename || this.traceToConsole; } - hasLevel(level: ts.server.LogLevel) { + hasLevel(level: LogLevel) { return this.loggingEnabled() && this.level >= level; } - msg(s: string, type: ts.server.Msg = ts.server.Msg.Err) { + msg(s: string, type: Msg = Msg.Err) { switch (type) { - case ts.server.Msg.Info: + case Msg.Info: perfLogger?.logInfoEvent(s); break; - case ts.server.Msg.Perf: + case Msg.Perf: perfLogger?.logPerfEvent(s); break; default: // Msg.Err @@ -227,7 +247,7 @@ export function initializeNodeSystem(): StartInput { if (!this.canWrite()) return; - s = `[${ts.server.nowString()}] ${s}\n`; + s = `[${nowString()}] ${s}\n`; if (!this.inGroup || this.firstInGroup) { const prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); s = prefix + s; @@ -240,7 +260,7 @@ export function initializeNodeSystem(): StartInput { protected canWrite() { return this.fd >= 0 || this.traceToConsole; } - protected write(s: string, _type: ts.server.Msg) { + protected write(s: string, _type: Msg) { if (this.fd >= 0) { const buf = sys.bufferFrom!(s); // eslint-disable-next-line no-null/no-null @@ -255,7 +275,7 @@ export function initializeNodeSystem(): StartInput { const libDirectory = getDirectoryPath(normalizePath(sys.getExecutingFilePath())); const useWatchGuard = process.platform === "win32"; - const originalWatchDirectory: ts.server.ServerHost["watchDirectory"] = sys.watchDirectory.bind(sys); + const originalWatchDirectory: ServerHost["watchDirectory"] = sys.watchDirectory.bind(sys); const logger = createLogger(); // enable deprecation logging @@ -264,10 +284,10 @@ export function initializeNodeSystem(): StartInput { switch (level) { case ts.LogLevel.Error: case ts.LogLevel.Warning: - return logger.msg(s, ts.server.Msg.Err); + return logger.msg(s, Msg.Err); case ts.LogLevel.Info: case ts.LogLevel.Verbose: - return logger.msg(s, ts.server.Msg.Info); + return logger.msg(s, Msg.Info); } }, }; @@ -282,23 +302,23 @@ export function initializeNodeSystem(): StartInput { const cacheKey = extractWatchDirectoryCacheKey(path, currentDrive); let status = cacheKey && statusCache.get(cacheKey); if (status === undefined) { - if (logger.hasLevel(ts.server.LogLevel.verbose)) { + if (logger.hasLevel(LogLevel.verbose)) { logger.info(`${cacheKey} for path ${path} not found in cache...`); } try { const args = [combinePaths(libDirectory, "watchGuard.js"), path]; - if (logger.hasLevel(ts.server.LogLevel.verbose)) { - logger.info(`Starting ${process.execPath} with args:${ts.server.stringifyIndented(args)}`); + if (logger.hasLevel(LogLevel.verbose)) { + logger.info(`Starting ${process.execPath} with args:${stringifyIndented(args)}`); } childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } }); status = true; - if (logger.hasLevel(ts.server.LogLevel.verbose)) { + if (logger.hasLevel(LogLevel.verbose)) { logger.info(`WatchGuard for path ${path} returned: OK`); } } catch (e) { status = false; - if (logger.hasLevel(ts.server.LogLevel.verbose)) { + if (logger.hasLevel(LogLevel.verbose)) { logger.info(`WatchGuard for path ${path} returned: ${e.message}`); } } @@ -306,7 +326,7 @@ export function initializeNodeSystem(): StartInput { statusCache.set(cacheKey, status); } } - else if (logger.hasLevel(ts.server.LogLevel.verbose)) { + else if (logger.hasLevel(LogLevel.verbose)) { logger.info(`watchDirectory for ${path} uses cached drive information.`); } if (status) { @@ -337,16 +357,16 @@ export function initializeNodeSystem(): StartInput { sys.gc = () => global.gc?.(); } - let cancellationToken: ts.server.ServerCancellationToken; + let cancellationToken: ServerCancellationToken; try { const factory = require("./cancellationToken"); cancellationToken = factory(sys.args); } catch (e) { - cancellationToken = ts.server.nullCancellationToken; + cancellationToken = nullCancellationToken; } - const localeStr = ts.server.findArgument("--locale"); + const localeStr = findArgument("--locale"); if (localeStr) { validateLocaleAndSetLanguage(localeStr, sys); } @@ -369,8 +389,8 @@ export function initializeNodeSystem(): StartInput { // TSS_LOG "{ level: "normal | verbose | terse", file?: string}" function createLogger() { - const cmdLineLogFileName = ts.server.findArgument("--logFile"); - const cmdLineVerbosity = getLogLevel(ts.server.findArgument("--logVerbosity")); + const cmdLineLogFileName = findArgument("--logFile"); + const cmdLineVerbosity = getLogLevel(findArgument("--logVerbosity")); const envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG); const unsubstitutedLogFileName = cmdLineLogFileName @@ -451,7 +471,7 @@ function parseEventPort(eventPortStr: string | undefined) { const eventPort = eventPortStr === undefined ? undefined : parseInt(eventPortStr); return eventPort !== undefined && !isNaN(eventPort) ? eventPort : undefined; } -function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger, cancellationToken: ts.server.ServerCancellationToken) { +function startNodeSession(options: StartSessionOptions, logger: Logger, cancellationToken: ServerCancellationToken) { const childProcess: { fork(modulePath: string, args: string[], options?: { execArgv: string[]; env?: MapLike; }): NodeChildProcess; } = require("child_process"); @@ -475,7 +495,7 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger terminal: false, }); - class NodeTypingsInstallerAdapter extends ts.server.TypingsInstallerAdapter { + class NodeTypingsInstallerAdapter extends TypingsInstallerAdapter { protected override installer!: NodeChildProcess; // This number is essentially arbitrary. Processing more than one typings request // at a time makes sense, but having too many in the pipe results in a hang @@ -486,14 +506,14 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger constructor( telemetryEnabled: boolean, - logger: ts.server.Logger, - host: ts.server.ServerHost, + logger: Logger, + host: ServerHost, globalTypingsCacheLocation: string, readonly typingSafeListLocation: string, readonly typesMapLocation: string, private readonly npmLocation: string | undefined, private readonly validateDefaultNpmLocation: boolean, - event: ts.server.Event, + event: Event, ) { super( telemetryEnabled, @@ -506,28 +526,28 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger } createInstallerProcess() { - if (this.logger.hasLevel(ts.server.LogLevel.requestTime)) { + if (this.logger.hasLevel(LogLevel.requestTime)) { this.logger.info("Binding..."); } - const args: string[] = [ts.server.Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation]; + const args: string[] = [Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation]; if (this.telemetryEnabled) { - args.push(ts.server.Arguments.EnableTelemetry); + args.push(Arguments.EnableTelemetry); } if (this.logger.loggingEnabled() && this.logger.getLogFileName()) { - args.push(ts.server.Arguments.LogFile, combinePaths(getDirectoryPath(normalizeSlashes(this.logger.getLogFileName()!)), `ti-${process.pid}.log`)); + args.push(Arguments.LogFile, combinePaths(getDirectoryPath(normalizeSlashes(this.logger.getLogFileName()!)), `ti-${process.pid}.log`)); } if (this.typingSafeListLocation) { - args.push(ts.server.Arguments.TypingSafeListLocation, this.typingSafeListLocation); + args.push(Arguments.TypingSafeListLocation, this.typingSafeListLocation); } if (this.typesMapLocation) { - args.push(ts.server.Arguments.TypesMapLocation, this.typesMapLocation); + args.push(Arguments.TypesMapLocation, this.typesMapLocation); } if (this.npmLocation) { - args.push(ts.server.Arguments.NpmLocation, this.npmLocation); + args.push(Arguments.NpmLocation, this.npmLocation); } if (this.validateDefaultNpmLocation) { - args.push(ts.server.Arguments.ValidateDefaultNpmLocation); + args.push(Arguments.ValidateDefaultNpmLocation); } const execArgv: string[] = []; @@ -561,7 +581,7 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger } } - class IOSession extends ts.server.Session { + class IOSession extends Session { private eventPort: number | undefined; private eventSocket: NodeSocket | undefined; private socketEventQueue: { body: any; eventName: string; }[] | undefined; @@ -573,7 +593,7 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger this.event(body, eventName); }; - const host = sys as ts.server.ServerHost; + const host = sys as ServerHost; const typingsInstaller = disableAutomaticTypingAcquisition ? undefined @@ -613,7 +633,7 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger if (this.canUseEvents && this.eventPort) { if (!this.eventSocket) { - if (this.logger.hasLevel(ts.server.LogLevel.verbose)) { + if (this.logger.hasLevel(LogLevel.verbose)) { this.logger.info(`eventPort: event "${eventName}" queued, but socket not yet initialized`); } (this.socketEventQueue || (this.socketEventQueue = [])).push({ body, eventName }); @@ -630,7 +650,7 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger } private writeToEventSocket(body: object, eventName: string): void { - this.eventSocket!.write(ts.server.formatMessage(ts.server.toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8"); + this.eventSocket!.write(formatMessage(toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8"); } override exit() { @@ -653,18 +673,18 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger } class IpcIOSession extends IOSession { - protected override writeMessage(msg: ts.server.protocol.Message): void { - const verboseLogging = logger.hasLevel(ts.server.LogLevel.verbose); + protected override writeMessage(msg: protocol.Message): void { + const verboseLogging = logger.hasLevel(LogLevel.verbose); if (verboseLogging) { const json = JSON.stringify(msg); - logger.info(`${msg.type}:${ts.server.indent(json)}`); + logger.info(`${msg.type}:${indent(json)}`); } process.send!(msg); } - protected override parseMessage(message: any): ts.server.protocol.Request { - return message as ts.server.protocol.Request; + protected override parseMessage(message: any): protocol.Request { + return message as protocol.Request; } protected override toStringMessage(message: any) { @@ -682,15 +702,15 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger } } - const eventPort: number | undefined = parseEventPort(ts.server.findArgument("--eventPort")); - const typingSafeListLocation = ts.server.findArgument(ts.server.Arguments.TypingSafeListLocation)!; // TODO: GH#18217 - const typesMapLocation = ts.server.findArgument(ts.server.Arguments.TypesMapLocation) || combinePaths(getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); - const npmLocation = ts.server.findArgument(ts.server.Arguments.NpmLocation); - const validateDefaultNpmLocation = ts.server.hasArgument(ts.server.Arguments.ValidateDefaultNpmLocation); - const disableAutomaticTypingAcquisition = ts.server.hasArgument("--disableAutomaticTypingAcquisition"); - const useNodeIpc = ts.server.hasArgument("--useNodeIpc"); - const telemetryEnabled = ts.server.hasArgument(ts.server.Arguments.EnableTelemetry); - const commandLineTraceDir = ts.server.findArgument("--traceDirectory"); + const eventPort: number | undefined = parseEventPort(findArgument("--eventPort")); + const typingSafeListLocation = findArgument(Arguments.TypingSafeListLocation)!; // TODO: GH#18217 + const typesMapLocation = findArgument(Arguments.TypesMapLocation) || combinePaths(getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); + const npmLocation = findArgument(Arguments.NpmLocation); + const validateDefaultNpmLocation = hasArgument(Arguments.ValidateDefaultNpmLocation); + const disableAutomaticTypingAcquisition = hasArgument("--disableAutomaticTypingAcquisition"); + const useNodeIpc = hasArgument("--useNodeIpc"); + const telemetryEnabled = hasArgument(Arguments.EnableTelemetry); + const commandLineTraceDir = findArgument("--traceDirectory"); const traceDir = commandLineTraceDir ? stripQuotes(commandLineTraceDir) : process.env.TSS_TRACE; diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index bcd6f78d84e5b..4d333597fed03 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -1,4 +1,15 @@ -import * as ts from "./_namespaces/ts"; +import { + Debug, + setStackTraceLimit, + sys, + version, +} from "./_namespaces/ts"; +import { + emptyArray, + findArgument, + hasArgument, + Msg, +} from "./_namespaces/ts.server"; import { StartInput, } from "./common"; @@ -6,49 +17,51 @@ import { initializeNodeSystem, } from "./nodeServer"; +export * from "./_namespaces/ts"; + function findArgumentStringArray(argName: string): readonly string[] { - const arg = ts.server.findArgument(argName); + const arg = findArgument(argName); if (arg === undefined) { - return ts.emptyArray; + return emptyArray; } return arg.split(",").filter(name => name !== ""); } function start({ args, logger, cancellationToken, serverMode, unknownServerMode, startSession: startServer }: StartInput, platform: string) { logger.info(`Starting TS Server`); - logger.info(`Version: ${ts.version}`); + logger.info(`Version: ${version}`); logger.info(`Arguments: ${args.join(" ")}`); - logger.info(`Platform: ${platform} NodeVersion: ${process.version} CaseSensitive: ${ts.sys.useCaseSensitiveFileNames}`); + logger.info(`Platform: ${platform} NodeVersion: ${process.version} CaseSensitive: ${sys.useCaseSensitiveFileNames}`); logger.info(`ServerMode: ${serverMode} hasUnknownServerMode: ${unknownServerMode}`); - ts.setStackTraceLimit(); + setStackTraceLimit(); - if (ts.Debug.isDebugging) { - ts.Debug.enableDebugInfo(); + if (Debug.isDebugging) { + Debug.enableDebugInfo(); } - if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) { - ts.sys.tryEnableSourceMapsForHost(); + if (sys.tryEnableSourceMapsForHost && /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV"))) { + sys.tryEnableSourceMapsForHost(); } // Overwrites the current console messages to instead write to // the log. This is so that language service plugins which use // console.log don't break the message passing between tsserver // and the client - console.log = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), ts.server.Msg.Info); - console.warn = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), ts.server.Msg.Err); - console.error = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), ts.server.Msg.Err); + console.log = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), Msg.Info); + console.warn = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), Msg.Err); + console.error = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), Msg.Err); startServer( { globalPlugins: findArgumentStringArray("--globalPlugins"), pluginProbeLocations: findArgumentStringArray("--pluginProbeLocations"), - allowLocalPluginLoads: ts.server.hasArgument("--allowLocalPluginLoads"), - useSingleInferredProject: ts.server.hasArgument("--useSingleInferredProject"), - useInferredProjectPerProjectRoot: ts.server.hasArgument("--useInferredProjectPerProjectRoot"), - suppressDiagnosticEvents: ts.server.hasArgument("--suppressDiagnosticEvents"), - noGetErrOnBackgroundUpdate: ts.server.hasArgument("--noGetErrOnBackgroundUpdate"), - canUseWatchEvents: ts.server.hasArgument("--canUseWatchEvents"), + allowLocalPluginLoads: hasArgument("--allowLocalPluginLoads"), + useSingleInferredProject: hasArgument("--useSingleInferredProject"), + useInferredProjectPerProjectRoot: hasArgument("--useInferredProjectPerProjectRoot"), + suppressDiagnosticEvents: hasArgument("--suppressDiagnosticEvents"), + noGetErrOnBackgroundUpdate: hasArgument("--noGetErrOnBackgroundUpdate"), + canUseWatchEvents: hasArgument("--canUseWatchEvents"), serverMode, }, logger, @@ -56,5 +69,5 @@ function start({ args, logger, cancellationToken, serverMode, unknownServerMode, ); } -ts.setStackTraceLimit(); +setStackTraceLimit(); start(initializeNodeSystem(), require("os").platform()); diff --git a/src/typingsInstaller/_namespaces/ts.server.ts b/src/typingsInstaller/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..04e8befd7ecc6 --- /dev/null +++ b/src/typingsInstaller/_namespaces/ts.server.ts @@ -0,0 +1,2 @@ +import * as ts from "../../typescript/typescript"; +export = ts.server; diff --git a/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts b/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts new file mode 100644 index 0000000000000..cbe0b051e5528 --- /dev/null +++ b/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts @@ -0,0 +1,2 @@ +import * as ts from "../../typescript/typescript"; +export = ts.server.typingsInstaller; diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index 4846a1e40d30c..46ca2f41c484d 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -12,9 +12,25 @@ import { toPath, version, } from "./_namespaces/ts"; -import * as ts from "./_namespaces/ts"; +import { + Arguments, + findArgument, + hasArgument, + InitializationFailedResponse, + InstallTypingHost, + nowString, + stringifyIndented, + TypingInstallerRequestUnion, + TypingInstallerResponseUnion, +} from "./_namespaces/ts.server"; +import { + installNpmPackages, + Log, + RequestCompletedAction, + TypingsInstaller, +} from "./_namespaces/ts.server.typingsInstaller"; -class FileLog implements ts.server.typingsInstaller.Log { +class FileLog implements Log { constructor(private logFile: string | undefined) { } @@ -25,7 +41,7 @@ class FileLog implements ts.server.typingsInstaller.Log { if (typeof this.logFile !== "string") return; try { - fs.appendFileSync(this.logFile, `[${ts.server.nowString()}] ${text}${sys.newLine}`); + fs.appendFileSync(this.logFile, `[${nowString()}] ${text}${sys.newLine}`); } catch (e) { this.logFile = undefined; @@ -34,7 +50,7 @@ class FileLog implements ts.server.typingsInstaller.Log { } /** Used if `--npmLocation` is not passed. */ -function getDefaultNPMLocation(processName: string, validateDefaultNpmLocation: boolean, host: ts.server.InstallTypingHost): string { +function getDefaultNPMLocation(processName: string, validateDefaultNpmLocation: boolean, host: InstallTypingHost): string { if (path.basename(processName).indexOf("node") === 0) { const npmPath = path.join(path.dirname(process.argv[0]), "npm"); if (!validateDefaultNpmLocation) { @@ -51,7 +67,7 @@ interface TypesRegistryFile { entries: MapLike>; } -function loadTypesRegistryFile(typesRegistryFilePath: string, host: ts.server.InstallTypingHost, log: ts.server.typingsInstaller.Log): Map> { +function loadTypesRegistryFile(typesRegistryFilePath: string, host: InstallTypingHost, log: Log): Map> { if (!host.fileExists(typesRegistryFilePath)) { if (log.isEnabled()) { log.writeLine(`Types registry file '${typesRegistryFilePath}' does not exist`); @@ -81,14 +97,14 @@ interface ExecSyncOptions { } type ExecSync = (command: string, options: ExecSyncOptions) => string; -export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInstaller { +export class NodeTypingsInstaller extends TypingsInstaller { private readonly nodeExecSync: ExecSync; private readonly npmPath: string; readonly typesRegistry: Map>; - private delayedInitializationError: ts.server.InitializationFailedResponse | undefined; + private delayedInitializationError: InitializationFailedResponse | undefined; - constructor(globalTypingsCacheLocation: string, typingSafeListLocation: string, typesMapLocation: string, npmLocation: string | undefined, validateDefaultNpmLocation: boolean, throttleLimit: number, log: ts.server.typingsInstaller.Log) { + constructor(globalTypingsCacheLocation: string, typingSafeListLocation: string, typesMapLocation: string, npmLocation: string | undefined, validateDefaultNpmLocation: boolean, throttleLimit: number, log: Log) { const libDirectory = getDirectoryPath(normalizePath(sys.getExecutingFilePath())); super( sys, @@ -106,7 +122,7 @@ export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInst } if (this.log.isEnabled()) { this.log.writeLine(`Process id: ${process.pid}`); - this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${ts.server.Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`); + this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`); this.log.writeLine(`validateDefaultNpmLocation: ${validateDefaultNpmLocation}`); } ({ execSync: this.nodeExecSync } = require("child_process")); @@ -137,7 +153,7 @@ export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInst this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), this.installTypingHost, this.log); } - override handleRequest(req: ts.server.TypingInstallerRequestUnion) { + override handleRequest(req: TypingInstallerRequestUnion) { if (this.delayedInitializationError) { // report initializationFailed error this.sendResponse(this.delayedInitializationError); @@ -146,9 +162,9 @@ export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInst super.handleRequest(req); } - protected sendResponse(response: ts.server.TypingInstallerResponseUnion) { + protected sendResponse(response: TypingInstallerResponseUnion) { if (this.log.isEnabled()) { - this.log.writeLine(`Sending response:${ts.server.stringifyIndented(response)}`); + this.log.writeLine(`Sending response:${stringifyIndented(response)}`); } process.send!(response); // TODO: GH#18217 if (this.log.isEnabled()) { @@ -156,12 +172,12 @@ export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInst } } - protected installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: ts.server.typingsInstaller.RequestCompletedAction): void { + protected installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void { if (this.log.isEnabled()) { this.log.writeLine(`#${requestId} with cwd: ${cwd} arguments: ${JSON.stringify(packageNames)}`); } const start = Date.now(); - const hasError = ts.server.typingsInstaller.installNpmPackages(this.npmPath, version, packageNames, command => this.execSyncAndLog(command, { cwd })); + const hasError = installNpmPackages(this.npmPath, version, packageNames, command => this.execSyncAndLog(command, { cwd })); if (this.log.isEnabled()) { this.log.writeLine(`npm install #${requestId} took: ${Date.now() - start} ms`); } @@ -188,12 +204,12 @@ export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInst } } -const logFilePath = ts.server.findArgument(ts.server.Arguments.LogFile); -const globalTypingsCacheLocation = ts.server.findArgument(ts.server.Arguments.GlobalCacheLocation); -const typingSafeListLocation = ts.server.findArgument(ts.server.Arguments.TypingSafeListLocation); -const typesMapLocation = ts.server.findArgument(ts.server.Arguments.TypesMapLocation); -const npmLocation = ts.server.findArgument(ts.server.Arguments.NpmLocation); -const validateDefaultNpmLocation = ts.server.hasArgument(ts.server.Arguments.ValidateDefaultNpmLocation); +const logFilePath = findArgument(Arguments.LogFile); +const globalTypingsCacheLocation = findArgument(Arguments.GlobalCacheLocation); +const typingSafeListLocation = findArgument(Arguments.TypingSafeListLocation); +const typesMapLocation = findArgument(Arguments.TypesMapLocation); +const npmLocation = findArgument(Arguments.NpmLocation); +const validateDefaultNpmLocation = hasArgument(Arguments.ValidateDefaultNpmLocation); const log = new FileLog(logFilePath); if (log.isEnabled()) { @@ -208,7 +224,7 @@ process.on("disconnect", () => { process.exit(0); }); let installer: NodeTypingsInstaller | undefined; -process.on("message", (req: ts.server.TypingInstallerRequestUnion) => { +process.on("message", (req: TypingInstallerRequestUnion) => { installer ??= new NodeTypingsInstaller(globalTypingsCacheLocation!, typingSafeListLocation!, typesMapLocation!, npmLocation, validateDefaultNpmLocation, /*throttleLimit*/ 5, log); // TODO: GH#18217 installer.handleRequest(req); }); From 68b5ef504a2b3f9715d1019d78cc4dbb9926965a Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Fri, 15 Mar 2024 13:12:07 -0700 Subject: [PATCH 10/10] Revert "Restore namespace files and pass through namespaces" This reverts commit 1e5fd9db2ab53c23bebd7dffab389998ea488e4d. --- src/tsserver/_namespaces/ts.server.ts | 2 - src/tsserver/common.ts | 40 ++--- src/tsserver/nodeServer.ts | 140 ++++++++---------- src/tsserver/server.ts | 53 +++---- src/typingsInstaller/_namespaces/ts.server.ts | 2 - .../_namespaces/ts.server.typingsInstaller.ts | 2 - src/typingsInstaller/nodeTypingsInstaller.ts | 58 +++----- 7 files changed, 117 insertions(+), 180 deletions(-) delete mode 100644 src/tsserver/_namespaces/ts.server.ts delete mode 100644 src/typingsInstaller/_namespaces/ts.server.ts delete mode 100644 src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts diff --git a/src/tsserver/_namespaces/ts.server.ts b/src/tsserver/_namespaces/ts.server.ts deleted file mode 100644 index 04e8befd7ecc6..0000000000000 --- a/src/tsserver/_namespaces/ts.server.ts +++ /dev/null @@ -1,2 +0,0 @@ -import * as ts from "../../typescript/typescript"; -export = ts.server; diff --git a/src/tsserver/common.ts b/src/tsserver/common.ts index c21f3ba1dfd5c..3a973486cbd73 100644 --- a/src/tsserver/common.ts +++ b/src/tsserver/common.ts @@ -1,20 +1,12 @@ -import { - LanguageServiceMode, -} from "./_namespaces/ts"; -import { - Logger, - LogLevel, - ServerCancellationToken, - SessionOptions, -} from "./_namespaces/ts.server"; +import * as ts from "./_namespaces/ts"; /** @internal */ export function getLogLevel(level: string | undefined) { if (level) { const l = level.toLowerCase(); - for (const name in LogLevel) { + for (const name in ts.server.LogLevel) { if (isNaN(+name) && l === name.toLowerCase()) { - return LogLevel[name] as any as LogLevel; + return ts.server.LogLevel[name] as any as ts.server.LogLevel; } } } @@ -23,23 +15,23 @@ export function getLogLevel(level: string | undefined) { /** @internal */ export interface StartSessionOptions { - globalPlugins: SessionOptions["globalPlugins"]; - pluginProbeLocations: SessionOptions["pluginProbeLocations"]; - allowLocalPluginLoads: SessionOptions["allowLocalPluginLoads"]; - useSingleInferredProject: SessionOptions["useSingleInferredProject"]; - useInferredProjectPerProjectRoot: SessionOptions["useInferredProjectPerProjectRoot"]; - suppressDiagnosticEvents: SessionOptions["suppressDiagnosticEvents"]; - noGetErrOnBackgroundUpdate: SessionOptions["noGetErrOnBackgroundUpdate"]; - canUseWatchEvents: SessionOptions["canUseWatchEvents"]; - serverMode: SessionOptions["serverMode"]; + globalPlugins: ts.server.SessionOptions["globalPlugins"]; + pluginProbeLocations: ts.server.SessionOptions["pluginProbeLocations"]; + allowLocalPluginLoads: ts.server.SessionOptions["allowLocalPluginLoads"]; + useSingleInferredProject: ts.server.SessionOptions["useSingleInferredProject"]; + useInferredProjectPerProjectRoot: ts.server.SessionOptions["useInferredProjectPerProjectRoot"]; + suppressDiagnosticEvents: ts.server.SessionOptions["suppressDiagnosticEvents"]; + noGetErrOnBackgroundUpdate: ts.server.SessionOptions["noGetErrOnBackgroundUpdate"]; + canUseWatchEvents: ts.server.SessionOptions["canUseWatchEvents"]; + serverMode: ts.server.SessionOptions["serverMode"]; } /** @internal */ export interface StartInput { args: readonly string[]; - logger: Logger; - cancellationToken: ServerCancellationToken; - serverMode: LanguageServiceMode | undefined; + logger: ts.server.Logger; + cancellationToken: ts.server.ServerCancellationToken; + serverMode: ts.LanguageServiceMode | undefined; unknownServerMode?: string; - startSession: (option: StartSessionOptions, logger: Logger, cancellationToken: ServerCancellationToken) => void; + startSession: (option: StartSessionOptions, logger: ts.server.Logger, cancellationToken: ts.server.ServerCancellationToken) => void; } diff --git a/src/tsserver/nodeServer.ts b/src/tsserver/nodeServer.ts index 81043a45daefd..09ad7a88f830e 100644 --- a/src/tsserver/nodeServer.ts +++ b/src/tsserver/nodeServer.ts @@ -1,5 +1,3 @@ -import * as protocol from "../server/protocol"; -import * as ts from "./_namespaces/ts"; import { CharacterCodes, combinePaths, @@ -26,25 +24,7 @@ import { versionMajorMinor, WatchOptions, } from "./_namespaces/ts"; -import { - Arguments, - Event, - findArgument, - formatMessage, - hasArgument, - indent, - Logger, - LogLevel, - Msg, - nowString, - nullCancellationToken, - ServerCancellationToken, - ServerHost, - Session, - stringifyIndented, - toEvent, - TypingsInstallerAdapter, -} from "./_namespaces/ts.server"; +import * as ts from "./_namespaces/ts"; import { getLogLevel, StartInput, @@ -53,7 +33,7 @@ import { interface LogOptions { file?: string; - detailLevel?: LogLevel; + detailLevel?: ts.server.LogLevel; traceToConsole?: boolean; logToFile?: boolean; } @@ -94,7 +74,7 @@ function parseLoggingEnvironmentString(logEnvStr: string | undefined): LogOption break; case "-level": const level = getLogLevel(value); - logEnv.detailLevel = level !== undefined ? level : LogLevel.normal; + logEnv.detailLevel = level !== undefined ? level : ts.server.LogLevel.normal; break; case "-traceToConsole": logEnv.traceToConsole = value.toLowerCase() === "true"; @@ -126,7 +106,7 @@ function parseLoggingEnvironmentString(logEnvStr: string | undefined): LogOption } function parseServerMode(): LanguageServiceMode | string | undefined { - const mode = findArgument("--serverMode"); + const mode = ts.server.findArgument("--serverMode"); if (!mode) return undefined; switch (mode.toLowerCase()) { @@ -143,7 +123,7 @@ function parseServerMode(): LanguageServiceMode | string | undefined { /** @internal */ export function initializeNodeSystem(): StartInput { - const sys = Debug.checkDefined(ts.sys) as ServerHost; + const sys = Debug.checkDefined(ts.sys) as ts.server.ServerHost; const childProcess: { execFileSync(file: string, args: string[], options: { stdio: "ignore"; env: MapLike; }): string | Buffer; } = require("child_process"); @@ -188,7 +168,7 @@ export function initializeNodeSystem(): StartInput { constructor( private readonly logFilename: string, private readonly traceToConsole: boolean, - private readonly level: LogLevel, + private readonly level: ts.server.LogLevel, ) { if (this.logFilename) { try { @@ -211,13 +191,13 @@ export function initializeNodeSystem(): StartInput { return this.logFilename; } perftrc(s: string) { - this.msg(s, Msg.Perf); + this.msg(s, ts.server.Msg.Perf); } info(s: string) { - this.msg(s, Msg.Info); + this.msg(s, ts.server.Msg.Info); } err(s: string) { - this.msg(s, Msg.Err); + this.msg(s, ts.server.Msg.Err); } startGroup() { this.inGroup = true; @@ -229,15 +209,15 @@ export function initializeNodeSystem(): StartInput { loggingEnabled() { return !!this.logFilename || this.traceToConsole; } - hasLevel(level: LogLevel) { + hasLevel(level: ts.server.LogLevel) { return this.loggingEnabled() && this.level >= level; } - msg(s: string, type: Msg = Msg.Err) { + msg(s: string, type: ts.server.Msg = ts.server.Msg.Err) { switch (type) { - case Msg.Info: + case ts.server.Msg.Info: perfLogger?.logInfoEvent(s); break; - case Msg.Perf: + case ts.server.Msg.Perf: perfLogger?.logPerfEvent(s); break; default: // Msg.Err @@ -247,7 +227,7 @@ export function initializeNodeSystem(): StartInput { if (!this.canWrite()) return; - s = `[${nowString()}] ${s}\n`; + s = `[${ts.server.nowString()}] ${s}\n`; if (!this.inGroup || this.firstInGroup) { const prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); s = prefix + s; @@ -260,7 +240,7 @@ export function initializeNodeSystem(): StartInput { protected canWrite() { return this.fd >= 0 || this.traceToConsole; } - protected write(s: string, _type: Msg) { + protected write(s: string, _type: ts.server.Msg) { if (this.fd >= 0) { const buf = sys.bufferFrom!(s); // eslint-disable-next-line no-null/no-null @@ -275,7 +255,7 @@ export function initializeNodeSystem(): StartInput { const libDirectory = getDirectoryPath(normalizePath(sys.getExecutingFilePath())); const useWatchGuard = process.platform === "win32"; - const originalWatchDirectory: ServerHost["watchDirectory"] = sys.watchDirectory.bind(sys); + const originalWatchDirectory: ts.server.ServerHost["watchDirectory"] = sys.watchDirectory.bind(sys); const logger = createLogger(); // enable deprecation logging @@ -284,10 +264,10 @@ export function initializeNodeSystem(): StartInput { switch (level) { case ts.LogLevel.Error: case ts.LogLevel.Warning: - return logger.msg(s, Msg.Err); + return logger.msg(s, ts.server.Msg.Err); case ts.LogLevel.Info: case ts.LogLevel.Verbose: - return logger.msg(s, Msg.Info); + return logger.msg(s, ts.server.Msg.Info); } }, }; @@ -302,23 +282,23 @@ export function initializeNodeSystem(): StartInput { const cacheKey = extractWatchDirectoryCacheKey(path, currentDrive); let status = cacheKey && statusCache.get(cacheKey); if (status === undefined) { - if (logger.hasLevel(LogLevel.verbose)) { + if (logger.hasLevel(ts.server.LogLevel.verbose)) { logger.info(`${cacheKey} for path ${path} not found in cache...`); } try { const args = [combinePaths(libDirectory, "watchGuard.js"), path]; - if (logger.hasLevel(LogLevel.verbose)) { - logger.info(`Starting ${process.execPath} with args:${stringifyIndented(args)}`); + if (logger.hasLevel(ts.server.LogLevel.verbose)) { + logger.info(`Starting ${process.execPath} with args:${ts.server.stringifyIndented(args)}`); } childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } }); status = true; - if (logger.hasLevel(LogLevel.verbose)) { + if (logger.hasLevel(ts.server.LogLevel.verbose)) { logger.info(`WatchGuard for path ${path} returned: OK`); } } catch (e) { status = false; - if (logger.hasLevel(LogLevel.verbose)) { + if (logger.hasLevel(ts.server.LogLevel.verbose)) { logger.info(`WatchGuard for path ${path} returned: ${e.message}`); } } @@ -326,7 +306,7 @@ export function initializeNodeSystem(): StartInput { statusCache.set(cacheKey, status); } } - else if (logger.hasLevel(LogLevel.verbose)) { + else if (logger.hasLevel(ts.server.LogLevel.verbose)) { logger.info(`watchDirectory for ${path} uses cached drive information.`); } if (status) { @@ -357,16 +337,16 @@ export function initializeNodeSystem(): StartInput { sys.gc = () => global.gc?.(); } - let cancellationToken: ServerCancellationToken; + let cancellationToken: ts.server.ServerCancellationToken; try { const factory = require("./cancellationToken"); cancellationToken = factory(sys.args); } catch (e) { - cancellationToken = nullCancellationToken; + cancellationToken = ts.server.nullCancellationToken; } - const localeStr = findArgument("--locale"); + const localeStr = ts.server.findArgument("--locale"); if (localeStr) { validateLocaleAndSetLanguage(localeStr, sys); } @@ -389,8 +369,8 @@ export function initializeNodeSystem(): StartInput { // TSS_LOG "{ level: "normal | verbose | terse", file?: string}" function createLogger() { - const cmdLineLogFileName = findArgument("--logFile"); - const cmdLineVerbosity = getLogLevel(findArgument("--logVerbosity")); + const cmdLineLogFileName = ts.server.findArgument("--logFile"); + const cmdLineVerbosity = getLogLevel(ts.server.findArgument("--logVerbosity")); const envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG); const unsubstitutedLogFileName = cmdLineLogFileName @@ -471,7 +451,7 @@ function parseEventPort(eventPortStr: string | undefined) { const eventPort = eventPortStr === undefined ? undefined : parseInt(eventPortStr); return eventPort !== undefined && !isNaN(eventPort) ? eventPort : undefined; } -function startNodeSession(options: StartSessionOptions, logger: Logger, cancellationToken: ServerCancellationToken) { +function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger, cancellationToken: ts.server.ServerCancellationToken) { const childProcess: { fork(modulePath: string, args: string[], options?: { execArgv: string[]; env?: MapLike; }): NodeChildProcess; } = require("child_process"); @@ -495,7 +475,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella terminal: false, }); - class NodeTypingsInstallerAdapter extends TypingsInstallerAdapter { + class NodeTypingsInstallerAdapter extends ts.server.TypingsInstallerAdapter { protected override installer!: NodeChildProcess; // This number is essentially arbitrary. Processing more than one typings request // at a time makes sense, but having too many in the pipe results in a hang @@ -506,14 +486,14 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella constructor( telemetryEnabled: boolean, - logger: Logger, - host: ServerHost, + logger: ts.server.Logger, + host: ts.server.ServerHost, globalTypingsCacheLocation: string, readonly typingSafeListLocation: string, readonly typesMapLocation: string, private readonly npmLocation: string | undefined, private readonly validateDefaultNpmLocation: boolean, - event: Event, + event: ts.server.Event, ) { super( telemetryEnabled, @@ -526,28 +506,28 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella } createInstallerProcess() { - if (this.logger.hasLevel(LogLevel.requestTime)) { + if (this.logger.hasLevel(ts.server.LogLevel.requestTime)) { this.logger.info("Binding..."); } - const args: string[] = [Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation]; + const args: string[] = [ts.server.Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation]; if (this.telemetryEnabled) { - args.push(Arguments.EnableTelemetry); + args.push(ts.server.Arguments.EnableTelemetry); } if (this.logger.loggingEnabled() && this.logger.getLogFileName()) { - args.push(Arguments.LogFile, combinePaths(getDirectoryPath(normalizeSlashes(this.logger.getLogFileName()!)), `ti-${process.pid}.log`)); + args.push(ts.server.Arguments.LogFile, combinePaths(getDirectoryPath(normalizeSlashes(this.logger.getLogFileName()!)), `ti-${process.pid}.log`)); } if (this.typingSafeListLocation) { - args.push(Arguments.TypingSafeListLocation, this.typingSafeListLocation); + args.push(ts.server.Arguments.TypingSafeListLocation, this.typingSafeListLocation); } if (this.typesMapLocation) { - args.push(Arguments.TypesMapLocation, this.typesMapLocation); + args.push(ts.server.Arguments.TypesMapLocation, this.typesMapLocation); } if (this.npmLocation) { - args.push(Arguments.NpmLocation, this.npmLocation); + args.push(ts.server.Arguments.NpmLocation, this.npmLocation); } if (this.validateDefaultNpmLocation) { - args.push(Arguments.ValidateDefaultNpmLocation); + args.push(ts.server.Arguments.ValidateDefaultNpmLocation); } const execArgv: string[] = []; @@ -581,7 +561,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella } } - class IOSession extends Session { + class IOSession extends ts.server.Session { private eventPort: number | undefined; private eventSocket: NodeSocket | undefined; private socketEventQueue: { body: any; eventName: string; }[] | undefined; @@ -593,7 +573,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella this.event(body, eventName); }; - const host = sys as ServerHost; + const host = sys as ts.server.ServerHost; const typingsInstaller = disableAutomaticTypingAcquisition ? undefined @@ -633,7 +613,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella if (this.canUseEvents && this.eventPort) { if (!this.eventSocket) { - if (this.logger.hasLevel(LogLevel.verbose)) { + if (this.logger.hasLevel(ts.server.LogLevel.verbose)) { this.logger.info(`eventPort: event "${eventName}" queued, but socket not yet initialized`); } (this.socketEventQueue || (this.socketEventQueue = [])).push({ body, eventName }); @@ -650,7 +630,7 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella } private writeToEventSocket(body: object, eventName: string): void { - this.eventSocket!.write(formatMessage(toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8"); + this.eventSocket!.write(ts.server.formatMessage(ts.server.toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8"); } override exit() { @@ -673,18 +653,18 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella } class IpcIOSession extends IOSession { - protected override writeMessage(msg: protocol.Message): void { - const verboseLogging = logger.hasLevel(LogLevel.verbose); + protected override writeMessage(msg: ts.server.protocol.Message): void { + const verboseLogging = logger.hasLevel(ts.server.LogLevel.verbose); if (verboseLogging) { const json = JSON.stringify(msg); - logger.info(`${msg.type}:${indent(json)}`); + logger.info(`${msg.type}:${ts.server.indent(json)}`); } process.send!(msg); } - protected override parseMessage(message: any): protocol.Request { - return message as protocol.Request; + protected override parseMessage(message: any): ts.server.protocol.Request { + return message as ts.server.protocol.Request; } protected override toStringMessage(message: any) { @@ -702,15 +682,15 @@ function startNodeSession(options: StartSessionOptions, logger: Logger, cancella } } - const eventPort: number | undefined = parseEventPort(findArgument("--eventPort")); - const typingSafeListLocation = findArgument(Arguments.TypingSafeListLocation)!; // TODO: GH#18217 - const typesMapLocation = findArgument(Arguments.TypesMapLocation) || combinePaths(getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); - const npmLocation = findArgument(Arguments.NpmLocation); - const validateDefaultNpmLocation = hasArgument(Arguments.ValidateDefaultNpmLocation); - const disableAutomaticTypingAcquisition = hasArgument("--disableAutomaticTypingAcquisition"); - const useNodeIpc = hasArgument("--useNodeIpc"); - const telemetryEnabled = hasArgument(Arguments.EnableTelemetry); - const commandLineTraceDir = findArgument("--traceDirectory"); + const eventPort: number | undefined = parseEventPort(ts.server.findArgument("--eventPort")); + const typingSafeListLocation = ts.server.findArgument(ts.server.Arguments.TypingSafeListLocation)!; // TODO: GH#18217 + const typesMapLocation = ts.server.findArgument(ts.server.Arguments.TypesMapLocation) || combinePaths(getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); + const npmLocation = ts.server.findArgument(ts.server.Arguments.NpmLocation); + const validateDefaultNpmLocation = ts.server.hasArgument(ts.server.Arguments.ValidateDefaultNpmLocation); + const disableAutomaticTypingAcquisition = ts.server.hasArgument("--disableAutomaticTypingAcquisition"); + const useNodeIpc = ts.server.hasArgument("--useNodeIpc"); + const telemetryEnabled = ts.server.hasArgument(ts.server.Arguments.EnableTelemetry); + const commandLineTraceDir = ts.server.findArgument("--traceDirectory"); const traceDir = commandLineTraceDir ? stripQuotes(commandLineTraceDir) : process.env.TSS_TRACE; diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 4d333597fed03..bcd6f78d84e5b 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -1,15 +1,4 @@ -import { - Debug, - setStackTraceLimit, - sys, - version, -} from "./_namespaces/ts"; -import { - emptyArray, - findArgument, - hasArgument, - Msg, -} from "./_namespaces/ts.server"; +import * as ts from "./_namespaces/ts"; import { StartInput, } from "./common"; @@ -17,51 +6,49 @@ import { initializeNodeSystem, } from "./nodeServer"; -export * from "./_namespaces/ts"; - function findArgumentStringArray(argName: string): readonly string[] { - const arg = findArgument(argName); + const arg = ts.server.findArgument(argName); if (arg === undefined) { - return emptyArray; + return ts.emptyArray; } return arg.split(",").filter(name => name !== ""); } function start({ args, logger, cancellationToken, serverMode, unknownServerMode, startSession: startServer }: StartInput, platform: string) { logger.info(`Starting TS Server`); - logger.info(`Version: ${version}`); + logger.info(`Version: ${ts.version}`); logger.info(`Arguments: ${args.join(" ")}`); - logger.info(`Platform: ${platform} NodeVersion: ${process.version} CaseSensitive: ${sys.useCaseSensitiveFileNames}`); + logger.info(`Platform: ${platform} NodeVersion: ${process.version} CaseSensitive: ${ts.sys.useCaseSensitiveFileNames}`); logger.info(`ServerMode: ${serverMode} hasUnknownServerMode: ${unknownServerMode}`); - setStackTraceLimit(); + ts.setStackTraceLimit(); - if (Debug.isDebugging) { - Debug.enableDebugInfo(); + if (ts.Debug.isDebugging) { + ts.Debug.enableDebugInfo(); } - if (sys.tryEnableSourceMapsForHost && /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV"))) { - sys.tryEnableSourceMapsForHost(); + if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) { + ts.sys.tryEnableSourceMapsForHost(); } // Overwrites the current console messages to instead write to // the log. This is so that language service plugins which use // console.log don't break the message passing between tsserver // and the client - console.log = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), Msg.Info); - console.warn = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), Msg.Err); - console.error = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), Msg.Err); + console.log = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), ts.server.Msg.Info); + console.warn = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), ts.server.Msg.Err); + console.error = (...args) => logger.msg(args.length === 1 ? args[0] : args.join(", "), ts.server.Msg.Err); startServer( { globalPlugins: findArgumentStringArray("--globalPlugins"), pluginProbeLocations: findArgumentStringArray("--pluginProbeLocations"), - allowLocalPluginLoads: hasArgument("--allowLocalPluginLoads"), - useSingleInferredProject: hasArgument("--useSingleInferredProject"), - useInferredProjectPerProjectRoot: hasArgument("--useInferredProjectPerProjectRoot"), - suppressDiagnosticEvents: hasArgument("--suppressDiagnosticEvents"), - noGetErrOnBackgroundUpdate: hasArgument("--noGetErrOnBackgroundUpdate"), - canUseWatchEvents: hasArgument("--canUseWatchEvents"), + allowLocalPluginLoads: ts.server.hasArgument("--allowLocalPluginLoads"), + useSingleInferredProject: ts.server.hasArgument("--useSingleInferredProject"), + useInferredProjectPerProjectRoot: ts.server.hasArgument("--useInferredProjectPerProjectRoot"), + suppressDiagnosticEvents: ts.server.hasArgument("--suppressDiagnosticEvents"), + noGetErrOnBackgroundUpdate: ts.server.hasArgument("--noGetErrOnBackgroundUpdate"), + canUseWatchEvents: ts.server.hasArgument("--canUseWatchEvents"), serverMode, }, logger, @@ -69,5 +56,5 @@ function start({ args, logger, cancellationToken, serverMode, unknownServerMode, ); } -setStackTraceLimit(); +ts.setStackTraceLimit(); start(initializeNodeSystem(), require("os").platform()); diff --git a/src/typingsInstaller/_namespaces/ts.server.ts b/src/typingsInstaller/_namespaces/ts.server.ts deleted file mode 100644 index 04e8befd7ecc6..0000000000000 --- a/src/typingsInstaller/_namespaces/ts.server.ts +++ /dev/null @@ -1,2 +0,0 @@ -import * as ts from "../../typescript/typescript"; -export = ts.server; diff --git a/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts b/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts deleted file mode 100644 index cbe0b051e5528..0000000000000 --- a/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts +++ /dev/null @@ -1,2 +0,0 @@ -import * as ts from "../../typescript/typescript"; -export = ts.server.typingsInstaller; diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index 46ca2f41c484d..4846a1e40d30c 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -12,25 +12,9 @@ import { toPath, version, } from "./_namespaces/ts"; -import { - Arguments, - findArgument, - hasArgument, - InitializationFailedResponse, - InstallTypingHost, - nowString, - stringifyIndented, - TypingInstallerRequestUnion, - TypingInstallerResponseUnion, -} from "./_namespaces/ts.server"; -import { - installNpmPackages, - Log, - RequestCompletedAction, - TypingsInstaller, -} from "./_namespaces/ts.server.typingsInstaller"; +import * as ts from "./_namespaces/ts"; -class FileLog implements Log { +class FileLog implements ts.server.typingsInstaller.Log { constructor(private logFile: string | undefined) { } @@ -41,7 +25,7 @@ class FileLog implements Log { if (typeof this.logFile !== "string") return; try { - fs.appendFileSync(this.logFile, `[${nowString()}] ${text}${sys.newLine}`); + fs.appendFileSync(this.logFile, `[${ts.server.nowString()}] ${text}${sys.newLine}`); } catch (e) { this.logFile = undefined; @@ -50,7 +34,7 @@ class FileLog implements Log { } /** Used if `--npmLocation` is not passed. */ -function getDefaultNPMLocation(processName: string, validateDefaultNpmLocation: boolean, host: InstallTypingHost): string { +function getDefaultNPMLocation(processName: string, validateDefaultNpmLocation: boolean, host: ts.server.InstallTypingHost): string { if (path.basename(processName).indexOf("node") === 0) { const npmPath = path.join(path.dirname(process.argv[0]), "npm"); if (!validateDefaultNpmLocation) { @@ -67,7 +51,7 @@ interface TypesRegistryFile { entries: MapLike>; } -function loadTypesRegistryFile(typesRegistryFilePath: string, host: InstallTypingHost, log: Log): Map> { +function loadTypesRegistryFile(typesRegistryFilePath: string, host: ts.server.InstallTypingHost, log: ts.server.typingsInstaller.Log): Map> { if (!host.fileExists(typesRegistryFilePath)) { if (log.isEnabled()) { log.writeLine(`Types registry file '${typesRegistryFilePath}' does not exist`); @@ -97,14 +81,14 @@ interface ExecSyncOptions { } type ExecSync = (command: string, options: ExecSyncOptions) => string; -export class NodeTypingsInstaller extends TypingsInstaller { +export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInstaller { private readonly nodeExecSync: ExecSync; private readonly npmPath: string; readonly typesRegistry: Map>; - private delayedInitializationError: InitializationFailedResponse | undefined; + private delayedInitializationError: ts.server.InitializationFailedResponse | undefined; - constructor(globalTypingsCacheLocation: string, typingSafeListLocation: string, typesMapLocation: string, npmLocation: string | undefined, validateDefaultNpmLocation: boolean, throttleLimit: number, log: Log) { + constructor(globalTypingsCacheLocation: string, typingSafeListLocation: string, typesMapLocation: string, npmLocation: string | undefined, validateDefaultNpmLocation: boolean, throttleLimit: number, log: ts.server.typingsInstaller.Log) { const libDirectory = getDirectoryPath(normalizePath(sys.getExecutingFilePath())); super( sys, @@ -122,7 +106,7 @@ export class NodeTypingsInstaller extends TypingsInstaller { } if (this.log.isEnabled()) { this.log.writeLine(`Process id: ${process.pid}`); - this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`); + this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${ts.server.Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`); this.log.writeLine(`validateDefaultNpmLocation: ${validateDefaultNpmLocation}`); } ({ execSync: this.nodeExecSync } = require("child_process")); @@ -153,7 +137,7 @@ export class NodeTypingsInstaller extends TypingsInstaller { this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), this.installTypingHost, this.log); } - override handleRequest(req: TypingInstallerRequestUnion) { + override handleRequest(req: ts.server.TypingInstallerRequestUnion) { if (this.delayedInitializationError) { // report initializationFailed error this.sendResponse(this.delayedInitializationError); @@ -162,9 +146,9 @@ export class NodeTypingsInstaller extends TypingsInstaller { super.handleRequest(req); } - protected sendResponse(response: TypingInstallerResponseUnion) { + protected sendResponse(response: ts.server.TypingInstallerResponseUnion) { if (this.log.isEnabled()) { - this.log.writeLine(`Sending response:${stringifyIndented(response)}`); + this.log.writeLine(`Sending response:${ts.server.stringifyIndented(response)}`); } process.send!(response); // TODO: GH#18217 if (this.log.isEnabled()) { @@ -172,12 +156,12 @@ export class NodeTypingsInstaller extends TypingsInstaller { } } - protected installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void { + protected installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: ts.server.typingsInstaller.RequestCompletedAction): void { if (this.log.isEnabled()) { this.log.writeLine(`#${requestId} with cwd: ${cwd} arguments: ${JSON.stringify(packageNames)}`); } const start = Date.now(); - const hasError = installNpmPackages(this.npmPath, version, packageNames, command => this.execSyncAndLog(command, { cwd })); + const hasError = ts.server.typingsInstaller.installNpmPackages(this.npmPath, version, packageNames, command => this.execSyncAndLog(command, { cwd })); if (this.log.isEnabled()) { this.log.writeLine(`npm install #${requestId} took: ${Date.now() - start} ms`); } @@ -204,12 +188,12 @@ export class NodeTypingsInstaller extends TypingsInstaller { } } -const logFilePath = findArgument(Arguments.LogFile); -const globalTypingsCacheLocation = findArgument(Arguments.GlobalCacheLocation); -const typingSafeListLocation = findArgument(Arguments.TypingSafeListLocation); -const typesMapLocation = findArgument(Arguments.TypesMapLocation); -const npmLocation = findArgument(Arguments.NpmLocation); -const validateDefaultNpmLocation = hasArgument(Arguments.ValidateDefaultNpmLocation); +const logFilePath = ts.server.findArgument(ts.server.Arguments.LogFile); +const globalTypingsCacheLocation = ts.server.findArgument(ts.server.Arguments.GlobalCacheLocation); +const typingSafeListLocation = ts.server.findArgument(ts.server.Arguments.TypingSafeListLocation); +const typesMapLocation = ts.server.findArgument(ts.server.Arguments.TypesMapLocation); +const npmLocation = ts.server.findArgument(ts.server.Arguments.NpmLocation); +const validateDefaultNpmLocation = ts.server.hasArgument(ts.server.Arguments.ValidateDefaultNpmLocation); const log = new FileLog(logFilePath); if (log.isEnabled()) { @@ -224,7 +208,7 @@ process.on("disconnect", () => { process.exit(0); }); let installer: NodeTypingsInstaller | undefined; -process.on("message", (req: TypingInstallerRequestUnion) => { +process.on("message", (req: ts.server.TypingInstallerRequestUnion) => { installer ??= new NodeTypingsInstaller(globalTypingsCacheLocation!, typingSafeListLocation!, typesMapLocation!, npmLocation, validateDefaultNpmLocation, /*throttleLimit*/ 5, log); // TODO: GH#18217 installer.handleRequest(req); });