@teambit/ts-server 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,3 @@
1
1
  import { Diagnostic } from 'typescript/lib/protocol';
2
2
  export declare function formatDiagnostics(diagnostics: readonly Diagnostic[], filePath: string): string;
3
+ export declare function formatDiagnostic(diagnostic: Diagnostic, filePath: string): string;
@@ -5,6 +5,7 @@ require("core-js/modules/es.array.iterator.js");
5
5
  Object.defineProperty(exports, "__esModule", {
6
6
  value: true
7
7
  });
8
+ exports.formatDiagnostic = formatDiagnostic;
8
9
  exports.formatDiagnostics = formatDiagnostics;
9
10
 
10
11
  // eslint-disable-next-line import/no-unresolved
@@ -32,7 +33,7 @@ function formatDiagnostic(diagnostic, filePath) {
32
33
  line,
33
34
  offset
34
35
  } = diagnostic.start;
35
- return `${filePath}(${line + 1},${offset + 1}): ${errorMessage}`;
36
+ return `${filePath}(${line},${offset}): ${errorMessage}`;
36
37
  }
37
38
 
38
39
  function flattenDiagnosticMessageText(diag, newLine, indent = 0) {
@@ -1 +1 @@
1
- {"version":3,"sources":["format-diagnostics.ts"],"names":["formatDiagnostics","diagnostics","filePath","output","diagnostic","formatDiagnostic","diagnosticCategoryName","category","errorMessage","code","flattenDiagnosticMessageText","text","line","offset","start","diag","newLine","indent","undefined","result","i","messageText","next","kid"],"mappings":";;;;;;;;;AAAA;;AAIA;AACA;AACA;AACA;AACA;AACO,SAASA,iBAAT,CAA2BC,WAA3B,EAA+DC,QAA/D,EAAyF;AAC9F,MAAIC,MAAM,GAAG,EAAb;;AAEA,OAAK,MAAMC,UAAX,IAAyBH,WAAzB,EAAsC;AACpCE,IAAAA,MAAM,IAAIE,gBAAgB,CAACD,UAAD,EAAaF,QAAb,CAA1B;AACD;;AACD,SAAOC,MAAP;AACD;;AAED,MAAMG,sBAAsB,GAAIF,UAAD,IAA4BA,UAAU,CAACG,QAAtE;;AAEA,SAASF,gBAAT,CAA0BD,UAA1B,EAAkDF,QAAlD,EAA4E;AAC1E,QAAMM,YAAY,GAAI,GAAEF,sBAAsB,CAACF,UAAD,CAAa,MAAKA,UAAU,CAACK,IAAK,KAAIC,4BAA4B,CAC9GN,UAAU,CAACO,IADmG,EAE9G,IAF8G,CAG9G,GAAE,IAAK,EAHT;AAKA,QAAM;AAAEC,IAAAA,IAAF;AAAQC,IAAAA;AAAR,MAAmBT,UAAU,CAACU,KAApC;AACA,SAAQ,GAAEZ,QAAS,IAAGU,IAAI,GAAG,CAAE,IAAGC,MAAM,GAAG,CAAE,MAAKL,YAAa,EAA/D;AACD;;AAED,SAASE,4BAAT,CACEK,IADF,EAEEC,OAFF,EAGEC,MAAM,GAAG,CAHX,EAIU;AACR,MAAI,OAAOF,IAAP,KAAgB,QAApB,EAA8B;AAC5B,WAAOA,IAAP;AACD;;AACD,MAAIA,IAAI,KAAKG,SAAb,EAAwB;AACtB,WAAO,EAAP;AACD;;AACD,MAAIC,MAAM,GAAG,EAAb;;AACA,MAAIF,MAAJ,EAAY;AACVE,IAAAA,MAAM,IAAIH,OAAV;;AAEA,SAAK,IAAII,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGH,MAApB,EAA4BG,CAAC,IAAI,CAAjC,EAAoC;AAClCD,MAAAA,MAAM,IAAI,IAAV;AACD;AACF;;AACDA,EAAAA,MAAM,IAAIJ,IAAI,CAACM,WAAf;AACAJ,EAAAA,MAAM,IAAI,CAAV;;AACA,MAAIF,IAAI,CAACO,IAAT,EAAe;AACb,SAAK,MAAMC,GAAX,IAAkBR,IAAI,CAACO,IAAvB,EAA6B;AAC3BH,MAAAA,MAAM,IAAIT,4BAA4B,CAACa,GAAD,EAAMP,OAAN,EAAeC,MAAf,CAAtC;AACD;AACF;;AACD,SAAOE,MAAP;AACD","sourcesContent":["// eslint-disable-next-line import/no-unresolved\nimport { Diagnostic } from 'typescript/lib/protocol';\nimport { DiagnosticMessageChain } from 'typescript';\n\n/**\n * mostly taken from ts repo, src/compiler/program.ts \"formatDiagnosticsWithColorAndContext\" method.\n * sadly, it's impossible to use that method for the diagnostic format coming from ts-server. it only\n * works with the diagnostic format of \"ts\" APIs.\n */\nexport function formatDiagnostics(diagnostics: readonly Diagnostic[], filePath: string): string {\n let output = '';\n\n for (const diagnostic of diagnostics) {\n output += formatDiagnostic(diagnostic, filePath);\n }\n return output;\n}\n\nconst diagnosticCategoryName = (diagnostic: Diagnostic) => diagnostic.category;\n\nfunction formatDiagnostic(diagnostic: Diagnostic, filePath: string): string {\n const errorMessage = `${diagnosticCategoryName(diagnostic)} TS${diagnostic.code}: ${flattenDiagnosticMessageText(\n diagnostic.text,\n '\\n'\n )}${'\\n'}`;\n\n const { line, offset } = diagnostic.start;\n return `${filePath}(${line + 1},${offset + 1}): ${errorMessage}`;\n}\n\nfunction flattenDiagnosticMessageText(\n diag: string | DiagnosticMessageChain | undefined,\n newLine: string,\n indent = 0\n): string {\n if (typeof diag === 'string') {\n return diag;\n }\n if (diag === undefined) {\n return '';\n }\n let result = '';\n if (indent) {\n result += newLine;\n\n for (let i = 0; i < indent; i += 1) {\n result += ' ';\n }\n }\n result += diag.messageText;\n indent += 1;\n if (diag.next) {\n for (const kid of diag.next) {\n result += flattenDiagnosticMessageText(kid, newLine, indent);\n }\n }\n return result;\n}\n"]}
1
+ {"version":3,"sources":["format-diagnostics.ts"],"names":["formatDiagnostics","diagnostics","filePath","output","diagnostic","formatDiagnostic","diagnosticCategoryName","category","errorMessage","code","flattenDiagnosticMessageText","text","line","offset","start","diag","newLine","indent","undefined","result","i","messageText","next","kid"],"mappings":";;;;;;;;;;AAAA;;AAIA;AACA;AACA;AACA;AACA;AACO,SAASA,iBAAT,CAA2BC,WAA3B,EAA+DC,QAA/D,EAAyF;AAC9F,MAAIC,MAAM,GAAG,EAAb;;AAEA,OAAK,MAAMC,UAAX,IAAyBH,WAAzB,EAAsC;AACpCE,IAAAA,MAAM,IAAIE,gBAAgB,CAACD,UAAD,EAAaF,QAAb,CA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line import/no-unresolved\nimport { Diagnostic } from 'typescript/lib/protocol';\nimport { DiagnosticMessageChain } from 'typescript';\n\n/**\n * mostly taken from ts repo, src/compiler/program.ts \"formatDiagnosticsWithColorAndContext\" method.\n * sadly, it's impossible to use that method for the diagnostic format coming from ts-server. it only\n * works with the diagnostic format of \"ts\" APIs.\n */\nexport function formatDiagnostics(diagnostics: readonly Diagnostic[], filePath: string): string {\n let output = '';\n\n for (const diagnostic of diagnostics) {\n output += formatDiagnostic(diagnostic, filePath);\n }\n return output;\n}\n\nconst diagnosticCategoryName = (diagnostic: Diagnostic) => diagnostic.category;\n\nexport function formatDiagnostic(diagnostic: Diagnostic, filePath: string): string {\n const errorMessage = `${diagnosticCategoryName(diagnostic)} TS${diagnostic.code}: ${flattenDiagnosticMessageText(\n diagnostic.text,\n '\\n'\n )}${'\\n'}`;\n\n const { line, offset } = diagnostic.start;\n return `${filePath}(${line},${offset}): ${errorMessage}`;\n}\n\nfunction flattenDiagnosticMessageText(\n diag: string | DiagnosticMessageChain | undefined,\n newLine: string,\n indent = 0\n): string {\n if (typeof diag === 'string') {\n return diag;\n }\n if (diag === undefined) {\n return '';\n }\n let result = '';\n if (indent) {\n result += newLine;\n\n for (let i = 0; i < indent; i += 1) {\n result += ' ';\n }\n }\n result += diag.messageText;\n indent += 1;\n if (diag.next) {\n for (const kid of diag.next) {\n result += flattenDiagnosticMessageText(kid, newLine, indent);\n }\n }\n return result;\n}\n"]}
@@ -96,8 +96,7 @@ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "functio
96
96
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
97
97
 
98
98
  /**
99
- * copied over from https://github.com/typescript-language-server/typescript-language-server/blob/master/src/tsp-client.ts
100
- * modified to accommodate Bit needs
99
+ * part of this file was copied over from https://github.com/typescript-language-server/typescript-language-server/blob/master/src/tsp-client.ts
101
100
  */
102
101
 
103
102
  /*
@@ -1 +1 @@
1
- {"version":3,"sources":["process-based-tsserver.ts"],"names":["ProcessBasedTsServer","constructor","options","tsServerArgs","logger","start","readlineInterface","tsserverPath","logFile","logVerbosity","maxTsServerMemory","globalPlugins","pluginProbeLocations","args","push","length","join","cancellationPipeName","tempy","file","name","info","tsserverPathIsModule","path","extname","silent","execArgv","tsServerProcess","cp","fork","spawn","readline","createInterface","stdout","stdin","undefined","process","on","close","destroy","kill","line","processMessage","dec","decoder","StringDecoder","stderr","addListener","data","stringMsg","write","error","notify","command","sendMessage","request","token","seq","deferred","Deferred","deferreds","promise","onCancelled","onCancellationRequested","dispose","requestCancellationPipeName","fs","writeFile","err","then","unlink","log","msg","obj","logToConsole","console","JSON","stringify","debug","notification","type","arguments","serializedRequest","untrimmedMessageString","messageString","trim","startsWith","message","parse","isResponse","resolveResponse","request_seq","success","isEvent","isRequestCompletedEvent","body","onEvent","resolve","reject","event"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAYA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA;AAAA;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CAACP,OAAD,EAAuE;AACpG,WAAO,KAAKM,OAAL,CAAaN,OAAb,KAAyBA,OAAO,CAACY,KAAR,KAAkB,kBAAlD;AACD;;AA3K+B","sourcesContent":["/**\n * copied over from https://github.com/typescript-language-server/typescript-language-server/blob/master/src/tsp-client.ts\n * modified to accommodate Bit needs\n */\n\n/*\n * Copyright (C) 2017, 2018 TypeFox and others.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as cp from 'child_process';\nimport * as readline from 'readline';\nimport { Logger } from '@teambit/logger';\nimport { Readable, Writable } from 'stream';\nimport * as decoder from 'string_decoder';\n// eslint-disable-next-line import/no-unresolved\nimport protocol from 'typescript/lib/protocol';\nimport tempy from 'tempy';\nimport { CancellationToken } from 'vscode-jsonrpc';\nimport { CommandTypes } from './tsp-command-types';\nimport { Deferred } from './utils';\n\nexport interface TspClientOptions {\n logger: Logger;\n tsserverPath: string;\n logToConsole?: boolean;\n onEvent?: (event: protocol.Event) => void;\n}\n\nexport interface TsServerArgs {\n logFile?: string;\n logVerbosity?: string;\n maxTsServerMemory?: number;\n globalPlugins?: string[];\n pluginProbeLocations?: string[];\n}\n\nexport interface TypeScriptRequestTypes {\n geterr: [protocol.GeterrRequestArgs, any];\n geterrForProject: [protocol.GeterrForProjectRequestArgs, any];\n compilerOptionsForInferredProjects: [\n protocol.SetCompilerOptionsForInferredProjectsArgs,\n protocol.SetCompilerOptionsForInferredProjectsResponse\n ];\n documentHighlights: [protocol.DocumentHighlightsRequestArgs, protocol.DocumentHighlightsResponse];\n applyCodeActionCommand: [protocol.ApplyCodeActionCommandRequestArgs, protocol.ApplyCodeActionCommandResponse];\n completionEntryDetails: [protocol.CompletionDetailsRequestArgs, protocol.CompletionDetailsResponse];\n completionInfo: [protocol.CompletionsRequestArgs, protocol.CompletionInfoResponse];\n configure: [protocol.ConfigureRequestArguments, protocol.ConfigureResponse];\n definition: [protocol.FileLocationRequestArgs, protocol.DefinitionResponse];\n definitionAndBoundSpan: [protocol.FileLocationRequestArgs, protocol.DefinitionInfoAndBoundSpanReponse];\n docCommentTemplate: [protocol.FileLocationRequestArgs, protocol.DocCommandTemplateResponse];\n format: [protocol.FormatRequestArgs, protocol.FormatResponse];\n formatonkey: [protocol.FormatOnKeyRequestArgs, protocol.FormatResponse];\n getApplicableRefactors: [protocol.GetApplicableRefactorsRequestArgs, protocol.GetApplicableRefactorsResponse];\n getCodeFixes: [protocol.CodeFixRequestArgs, protocol.GetCodeFixesResponse];\n getCombinedCodeFix: [protocol.GetCombinedCodeFixRequestArgs, protocol.GetCombinedCodeFixResponse];\n getEditsForFileRename: [protocol.GetEditsForFileRenameRequestArgs, protocol.GetEditsForFileRenameResponse];\n getEditsForRefactor: [protocol.GetEditsForRefactorRequestArgs, protocol.GetEditsForRefactorResponse];\n getOutliningSpans: [protocol.FileRequestArgs, protocol.OutliningSpansResponse];\n getSupportedCodeFixes: [null, protocol.GetSupportedCodeFixesResponse];\n implementation: [protocol.FileLocationRequestArgs, protocol.ImplementationResponse];\n jsxClosingTag: [protocol.JsxClosingTagRequestArgs, protocol.JsxClosingTagResponse];\n navto: [protocol.NavtoRequestArgs, protocol.NavtoResponse];\n navtree: [protocol.FileRequestArgs, protocol.NavTreeResponse];\n occurrences: [protocol.FileLocationRequestArgs, protocol.OccurrencesResponse];\n organizeImports: [protocol.OrganizeImportsRequestArgs, protocol.OrganizeImportsResponse];\n projectInfo: [protocol.ProjectInfoRequestArgs, protocol.ProjectInfoResponse];\n quickinfo: [protocol.FileLocationRequestArgs, protocol.QuickInfoResponse];\n references: [protocol.FileLocationRequestArgs, protocol.ReferencesResponse];\n rename: [protocol.RenameRequestArgs, protocol.RenameResponse];\n signatureHelp: [protocol.SignatureHelpRequestArgs, protocol.SignatureHelpResponse];\n typeDefinition: [protocol.FileLocationRequestArgs, protocol.TypeDefinitionResponse];\n provideInlayHints: [protocol.InlayHintsRequestArgs, protocol.InlayHintsResponse];\n}\n\nexport class ProcessBasedTsServer {\n private readlineInterface: readline.ReadLine;\n private tsServerProcess: cp.ChildProcess;\n private seq = 0;\n\n private readonly deferreds: {\n [seq: number]: Deferred<any>;\n } = {};\n\n private logger: Logger;\n private cancellationPipeName: string | undefined;\n\n constructor(private options: TspClientOptions, private tsServerArgs: TsServerArgs = {}) {\n this.logger = options.logger;\n }\n\n start(): void {\n if (this.readlineInterface) {\n return;\n }\n const { tsserverPath } = this.options;\n const { logFile, logVerbosity, maxTsServerMemory, globalPlugins, pluginProbeLocations } = this.tsServerArgs;\n const args: string[] = [];\n if (logFile) {\n args.push('--logFile', logFile);\n }\n if (logVerbosity) {\n args.push('--logVerbosity', logVerbosity);\n }\n if (globalPlugins && globalPlugins.length) {\n args.push('--globalPlugins', globalPlugins.join(','));\n }\n if (pluginProbeLocations && pluginProbeLocations.length) {\n args.push('--pluginProbeLocations', pluginProbeLocations.join(','));\n }\n this.cancellationPipeName = tempy.file({ name: 'tscancellation' });\n args.push('--cancellationPipeName', `${this.cancellationPipeName}*`);\n this.logger.info(`Starting tsserver : '${tsserverPath} ${args.join(' ')}'`);\n const tsserverPathIsModule = path.extname(tsserverPath) === '.js';\n const options = {\n silent: true,\n execArgv: [...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : [])],\n };\n this.tsServerProcess = tsserverPathIsModule ? cp.fork(tsserverPath, args, options) : cp.spawn(tsserverPath, args);\n this.readlineInterface = readline.createInterface(\n this.tsServerProcess.stdout as Readable,\n this.tsServerProcess.stdin as Writable,\n undefined\n );\n process.on('exit', () => {\n this.readlineInterface.close();\n this.tsServerProcess.stdin?.destroy();\n this.tsServerProcess.kill();\n });\n this.readlineInterface.on('line', (line) => this.processMessage(line));\n\n const dec = new decoder.StringDecoder('utf-8');\n this.tsServerProcess.stderr?.addListener('data', (data) => {\n const stringMsg = typeof data === 'string' ? data : dec.write(data);\n this.logger.error(stringMsg);\n });\n }\n\n notify(command: CommandTypes.Open, args: protocol.OpenRequestArgs): void;\n notify(command: CommandTypes.Close, args: protocol.FileRequestArgs): void;\n notify(command: CommandTypes.Saveto, args: protocol.SavetoRequestArgs): void;\n notify(command: CommandTypes.Change, args: protocol.ChangeRequestArgs): void;\n notify(command: string, args: any): void {\n this.sendMessage(command, true, args);\n }\n\n request<K extends keyof TypeScriptRequestTypes>(\n command: K,\n args: TypeScriptRequestTypes[K][0],\n token?: CancellationToken\n ): Promise<TypeScriptRequestTypes[K][1]> {\n this.sendMessage(command, false, args);\n const seq = this.seq;\n const deferred = new Deferred<TypeScriptRequestTypes[K][1]>();\n this.deferreds[seq] = deferred;\n const request = deferred.promise;\n if (token) {\n const onCancelled = token.onCancellationRequested(() => {\n onCancelled.dispose();\n if (this.cancellationPipeName) {\n const requestCancellationPipeName = `${this.cancellationPipeName}${seq}`;\n fs.writeFile(requestCancellationPipeName, '', (err) => {\n if (!err) {\n // eslint-disable-next-line\n request.then(() =>\n fs.unlink(requestCancellationPipeName, () => {\n /* no-op */\n })\n );\n }\n });\n }\n });\n }\n return request;\n }\n\n kill() {\n this.tsServerProcess.kill();\n }\n\n private log(msg: string, obj: Record<string, any> = {}) {\n msg = `[tsserver] ${msg}`;\n if (this.options.logToConsole) {\n this.logger.console(`${msg} ${JSON.stringify(obj, undefined, 4)}`);\n } else {\n this.logger.debug(msg, obj);\n }\n }\n\n protected sendMessage(command: string, notification: boolean, args?: any): void {\n this.seq += 1;\n const request: protocol.Request = {\n command,\n seq: this.seq,\n type: 'request',\n };\n if (args) {\n request.arguments = args;\n }\n const serializedRequest = `${JSON.stringify(request)}\\n`;\n this.tsServerProcess.stdin?.write(serializedRequest);\n this.log(notification ? 'notify' : 'request', request);\n }\n\n protected processMessage(untrimmedMessageString: string): void {\n const messageString = untrimmedMessageString.trim();\n if (!messageString || messageString.startsWith('Content-Length:')) {\n return;\n }\n const message: protocol.Message = JSON.parse(messageString);\n this.log('processMessage', message);\n if (this.isResponse(message)) {\n this.resolveResponse(message, message.request_seq, message.success);\n } else if (this.isEvent(message)) {\n if (this.isRequestCompletedEvent(message)) {\n this.resolveResponse(message, message.body.request_seq, true);\n } else if (this.options.onEvent) {\n this.options.onEvent(message);\n }\n }\n }\n\n private resolveResponse(message: protocol.Message, request_seq: number, success: boolean) {\n const deferred = this.deferreds[request_seq];\n this.log('request completed', { request_seq, success });\n if (deferred) {\n if (success) {\n this.deferreds[request_seq].resolve(message);\n } else {\n this.deferreds[request_seq].reject(message);\n }\n delete this.deferreds[request_seq];\n }\n }\n\n private isEvent(message: protocol.Message): message is protocol.Event {\n return message.type === 'event';\n }\n\n private isResponse(message: protocol.Message): message is protocol.Response {\n return message.type === 'response';\n }\n\n private isRequestCompletedEvent(message: protocol.Message): message is protocol.RequestCompletedEvent {\n return this.isEvent(message) && message.event === 'requestCompleted';\n }\n}\n"]}
1
+ {"version":3,"sources":["process-based-tsserver.ts"],"names":["ProcessBasedTsServer","constructor","options","tsServerArgs","logger","start","readlineInterface","tsserverPath","logFile","logVerbosity","maxTsServerMemory","globalPlugins","pluginProbeLocations","args","push","length","join","cancellationPipeName","tempy","file","name","info","tsserverPathIsModule","path","extname","silent","execArgv","tsServerProcess","cp","fork","spawn","readline","createInterface","stdout","stdin","undefined","process","on","close","destroy","kill","line","processMessage","dec","decoder","StringDecoder","stderr","addListener","data","stringMsg","write","error","notify","command","sendMessage","request","token","seq","deferred","Deferred","deferreds","promise","onCancelled","onCancellationRequested","dispose","requestCancellationPipeName","fs","writeFile","err","then","unlink","log","msg","obj","logToConsole","console","JSON","stringify","debug","notification","type","arguments","serializedRequest","untrimmedMessageString","messageString","trim","startsWith","message","parse","isResponse","resolveResponse","request_seq","success","isEvent","isRequestCompletedEvent","body","onEvent","resolve","reject","event"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AA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AAAA,OAAO,CAACN,OAAD,EAAuD;AACpE,WAAOA,OAAO,CAACP,IAAR,KAAiB,OAAxB;AACD;;AAEOS,EAAAA,UAAU,CAACF,OAAD,EAA0D;AAC1E,WAAOA,OAAO,CAACP,IAAR,KAAiB,UAAxB;AACD;;AAEOc,EAAAA,uBAAuB,CAACP,OAAD,EAAuE;AACpG,WAAO,KAAKM,OAAL,CAAaN,OAAb,KAAyBA,OAAO,CAACY,KAAR,KAAkB,kBAAlD;AACD;;AA3K+B","sourcesContent":["/**\n * part of this file was copied over from https://github.com/typescript-language-server/typescript-language-server/blob/master/src/tsp-client.ts\n */\n\n/*\n * Copyright (C) 2017, 2018 TypeFox and others.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as cp from 'child_process';\nimport * as readline from 'readline';\nimport { Logger } from '@teambit/logger';\nimport { Readable, Writable } from 'stream';\nimport * as decoder from 'string_decoder';\n// eslint-disable-next-line import/no-unresolved\nimport protocol from 'typescript/lib/protocol';\nimport tempy from 'tempy';\nimport { CancellationToken } from 'vscode-jsonrpc';\nimport { CommandTypes } from './tsp-command-types';\nimport { Deferred } from './utils';\n\nexport interface TspClientOptions {\n logger: Logger;\n tsserverPath: string;\n logToConsole?: boolean;\n onEvent?: (event: protocol.Event) => void;\n}\n\nexport interface TsServerArgs {\n logFile?: string;\n logVerbosity?: string;\n maxTsServerMemory?: number;\n globalPlugins?: string[];\n pluginProbeLocations?: string[];\n}\n\nexport interface TypeScriptRequestTypes {\n geterr: [protocol.GeterrRequestArgs, any];\n geterrForProject: [protocol.GeterrForProjectRequestArgs, any];\n compilerOptionsForInferredProjects: [\n protocol.SetCompilerOptionsForInferredProjectsArgs,\n protocol.SetCompilerOptionsForInferredProjectsResponse\n ];\n documentHighlights: [protocol.DocumentHighlightsRequestArgs, protocol.DocumentHighlightsResponse];\n applyCodeActionCommand: [protocol.ApplyCodeActionCommandRequestArgs, protocol.ApplyCodeActionCommandResponse];\n completionEntryDetails: [protocol.CompletionDetailsRequestArgs, protocol.CompletionDetailsResponse];\n completionInfo: [protocol.CompletionsRequestArgs, protocol.CompletionInfoResponse];\n configure: [protocol.ConfigureRequestArguments, protocol.ConfigureResponse];\n definition: [protocol.FileLocationRequestArgs, protocol.DefinitionResponse];\n definitionAndBoundSpan: [protocol.FileLocationRequestArgs, protocol.DefinitionInfoAndBoundSpanReponse];\n docCommentTemplate: [protocol.FileLocationRequestArgs, protocol.DocCommandTemplateResponse];\n format: [protocol.FormatRequestArgs, protocol.FormatResponse];\n formatonkey: [protocol.FormatOnKeyRequestArgs, protocol.FormatResponse];\n getApplicableRefactors: [protocol.GetApplicableRefactorsRequestArgs, protocol.GetApplicableRefactorsResponse];\n getCodeFixes: [protocol.CodeFixRequestArgs, protocol.GetCodeFixesResponse];\n getCombinedCodeFix: [protocol.GetCombinedCodeFixRequestArgs, protocol.GetCombinedCodeFixResponse];\n getEditsForFileRename: [protocol.GetEditsForFileRenameRequestArgs, protocol.GetEditsForFileRenameResponse];\n getEditsForRefactor: [protocol.GetEditsForRefactorRequestArgs, protocol.GetEditsForRefactorResponse];\n getOutliningSpans: [protocol.FileRequestArgs, protocol.OutliningSpansResponse];\n getSupportedCodeFixes: [null, protocol.GetSupportedCodeFixesResponse];\n implementation: [protocol.FileLocationRequestArgs, protocol.ImplementationResponse];\n jsxClosingTag: [protocol.JsxClosingTagRequestArgs, protocol.JsxClosingTagResponse];\n navto: [protocol.NavtoRequestArgs, protocol.NavtoResponse];\n navtree: [protocol.FileRequestArgs, protocol.NavTreeResponse];\n occurrences: [protocol.FileLocationRequestArgs, protocol.OccurrencesResponse];\n organizeImports: [protocol.OrganizeImportsRequestArgs, protocol.OrganizeImportsResponse];\n projectInfo: [protocol.ProjectInfoRequestArgs, protocol.ProjectInfoResponse];\n quickinfo: [protocol.FileLocationRequestArgs, protocol.QuickInfoResponse];\n references: [protocol.FileLocationRequestArgs, protocol.ReferencesResponse];\n rename: [protocol.RenameRequestArgs, protocol.RenameResponse];\n signatureHelp: [protocol.SignatureHelpRequestArgs, protocol.SignatureHelpResponse];\n typeDefinition: [protocol.FileLocationRequestArgs, protocol.TypeDefinitionResponse];\n provideInlayHints: [protocol.InlayHintsRequestArgs, protocol.InlayHintsResponse];\n}\n\nexport class ProcessBasedTsServer {\n private readlineInterface: readline.ReadLine;\n private tsServerProcess: cp.ChildProcess;\n private seq = 0;\n\n private readonly deferreds: {\n [seq: number]: Deferred<any>;\n } = {};\n\n private logger: Logger;\n private cancellationPipeName: string | undefined;\n\n constructor(private options: TspClientOptions, private tsServerArgs: TsServerArgs = {}) {\n this.logger = options.logger;\n }\n\n start(): void {\n if (this.readlineInterface) {\n return;\n }\n const { tsserverPath } = this.options;\n const { logFile, logVerbosity, maxTsServerMemory, globalPlugins, pluginProbeLocations } = this.tsServerArgs;\n const args: string[] = [];\n if (logFile) {\n args.push('--logFile', logFile);\n }\n if (logVerbosity) {\n args.push('--logVerbosity', logVerbosity);\n }\n if (globalPlugins && globalPlugins.length) {\n args.push('--globalPlugins', globalPlugins.join(','));\n }\n if (pluginProbeLocations && pluginProbeLocations.length) {\n args.push('--pluginProbeLocations', pluginProbeLocations.join(','));\n }\n this.cancellationPipeName = tempy.file({ name: 'tscancellation' });\n args.push('--cancellationPipeName', `${this.cancellationPipeName}*`);\n this.logger.info(`Starting tsserver : '${tsserverPath} ${args.join(' ')}'`);\n const tsserverPathIsModule = path.extname(tsserverPath) === '.js';\n const options = {\n silent: true,\n execArgv: [...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : [])],\n };\n this.tsServerProcess = tsserverPathIsModule ? cp.fork(tsserverPath, args, options) : cp.spawn(tsserverPath, args);\n this.readlineInterface = readline.createInterface(\n this.tsServerProcess.stdout as Readable,\n this.tsServerProcess.stdin as Writable,\n undefined\n );\n process.on('exit', () => {\n this.readlineInterface.close();\n this.tsServerProcess.stdin?.destroy();\n this.tsServerProcess.kill();\n });\n this.readlineInterface.on('line', (line) => this.processMessage(line));\n\n const dec = new decoder.StringDecoder('utf-8');\n this.tsServerProcess.stderr?.addListener('data', (data) => {\n const stringMsg = typeof data === 'string' ? data : dec.write(data);\n this.logger.error(stringMsg);\n });\n }\n\n notify(command: CommandTypes.Open, args: protocol.OpenRequestArgs): void;\n notify(command: CommandTypes.Close, args: protocol.FileRequestArgs): void;\n notify(command: CommandTypes.Saveto, args: protocol.SavetoRequestArgs): void;\n notify(command: CommandTypes.Change, args: protocol.ChangeRequestArgs): void;\n notify(command: string, args: any): void {\n this.sendMessage(command, true, args);\n }\n\n request<K extends keyof TypeScriptRequestTypes>(\n command: K,\n args: TypeScriptRequestTypes[K][0],\n token?: CancellationToken\n ): Promise<TypeScriptRequestTypes[K][1]> {\n this.sendMessage(command, false, args);\n const seq = this.seq;\n const deferred = new Deferred<TypeScriptRequestTypes[K][1]>();\n this.deferreds[seq] = deferred;\n const request = deferred.promise;\n if (token) {\n const onCancelled = token.onCancellationRequested(() => {\n onCancelled.dispose();\n if (this.cancellationPipeName) {\n const requestCancellationPipeName = `${this.cancellationPipeName}${seq}`;\n fs.writeFile(requestCancellationPipeName, '', (err) => {\n if (!err) {\n // eslint-disable-next-line\n request.then(() =>\n fs.unlink(requestCancellationPipeName, () => {\n /* no-op */\n })\n );\n }\n });\n }\n });\n }\n return request;\n }\n\n kill() {\n this.tsServerProcess.kill();\n }\n\n private log(msg: string, obj: Record<string, any> = {}) {\n msg = `[tsserver] ${msg}`;\n if (this.options.logToConsole) {\n this.logger.console(`${msg} ${JSON.stringify(obj, undefined, 4)}`);\n } else {\n this.logger.debug(msg, obj);\n }\n }\n\n protected sendMessage(command: string, notification: boolean, args?: any): void {\n this.seq += 1;\n const request: protocol.Request = {\n command,\n seq: this.seq,\n type: 'request',\n };\n if (args) {\n request.arguments = args;\n }\n const serializedRequest = `${JSON.stringify(request)}\\n`;\n this.tsServerProcess.stdin?.write(serializedRequest);\n this.log(notification ? 'notify' : 'request', request);\n }\n\n protected processMessage(untrimmedMessageString: string): void {\n const messageString = untrimmedMessageString.trim();\n if (!messageString || messageString.startsWith('Content-Length:')) {\n return;\n }\n const message: protocol.Message = JSON.parse(messageString);\n this.log('processMessage', message);\n if (this.isResponse(message)) {\n this.resolveResponse(message, message.request_seq, message.success);\n } else if (this.isEvent(message)) {\n if (this.isRequestCompletedEvent(message)) {\n this.resolveResponse(message, message.body.request_seq, true);\n } else if (this.options.onEvent) {\n this.options.onEvent(message);\n }\n }\n }\n\n private resolveResponse(message: protocol.Message, request_seq: number, success: boolean) {\n const deferred = this.deferreds[request_seq];\n this.log('request completed', { request_seq, success });\n if (deferred) {\n if (success) {\n this.deferreds[request_seq].resolve(message);\n } else {\n this.deferreds[request_seq].reject(message);\n }\n delete this.deferreds[request_seq];\n }\n }\n\n private isEvent(message: protocol.Message): message is protocol.Event {\n return message.type === 'event';\n }\n\n private isResponse(message: protocol.Message): message is protocol.Response {\n return message.type === 'response';\n }\n\n private isRequestCompletedEvent(message: protocol.Message): message is protocol.RequestCompletedEvent {\n return this.isEvent(message) && message.event === 'requestCompleted';\n }\n}\n"]}
@@ -1,10 +1,11 @@
1
1
  import { Logger } from '@teambit/logger';
2
2
  import protocol from 'typescript/lib/protocol';
3
- import { Position } from 'vscode-languageserver-types';
3
+ import { CheckTypes } from '@teambit/workspace';
4
+ import type { Position } from 'vscode-languageserver-types';
4
5
  export declare type TsserverClientOpts = {
5
6
  verbose?: boolean;
6
7
  tsServerPath?: string;
7
- checkTypes?: boolean;
8
+ checkTypes?: CheckTypes;
8
9
  };
9
10
  export declare class TsserverClient {
10
11
  private projectPath;
@@ -12,11 +13,14 @@ export declare class TsserverClient {
12
13
  private options;
13
14
  private files;
14
15
  private tsServer;
16
+ private lastDiagnostics;
15
17
  constructor(projectPath: string, logger: Logger, options?: TsserverClientOpts, files?: string[]);
16
18
  init(): void;
19
+ private checkTypesIfNeeded;
20
+ private shouldCheckTypes;
17
21
  onFileChange(file: string): Promise<void>;
18
22
  killTsServer(): void;
19
- getDiagnostic(): Promise<any>;
23
+ getDiagnostic(files?: string[]): Promise<any>;
20
24
  getDiagnosticAllProject(requestedByFile: string): Promise<any>;
21
25
  getQuickInfo(file: string, position: Position): Promise<protocol.QuickInfoResponse | undefined>;
22
26
  getTypeDefinition(file: string, position: Position): Promise<protocol.TypeDefinitionResponse | undefined>;
@@ -39,6 +39,16 @@ function _path() {
39
39
  return data;
40
40
  }
41
41
 
42
+ function _workspace() {
43
+ const data = require("@teambit/workspace");
44
+
45
+ _workspace = function () {
46
+ return data;
47
+ };
48
+
49
+ return data;
50
+ }
51
+
42
52
  function _commandExists() {
43
53
  const data = _interopRequireDefault(require("command-exists"));
44
54
 
@@ -115,6 +125,7 @@ class TsserverClient {
115
125
  this.options = options;
116
126
  this.files = files;
117
127
  (0, _defineProperty2().default)(this, "tsServer", void 0);
128
+ (0, _defineProperty2().default)(this, "lastDiagnostics", []);
118
129
  }
119
130
  /**
120
131
  * start the ts-server and keep its process alive.
@@ -136,19 +147,35 @@ class TsserverClient {
136
147
  this.files.forEach(file => this.open(file));
137
148
  }
138
149
 
139
- if (this.options.checkTypes) {
140
- const start = Date.now();
141
- this.getDiagnostic().then(() => {
142
- const end = Date.now() - start;
143
- this.logger.console(`\ncompleted preliminary type checking (${end / 1000} sec)`);
144
- }).catch(err => {
145
- const msg = `failed getting the type errors from ts-server`;
146
- this.logger.console(msg);
147
- this.logger.error(msg, err);
148
- });
150
+ this.checkTypesIfNeeded();
151
+ this.logger.debug('TsserverClient.init completed');
152
+ }
153
+
154
+ checkTypesIfNeeded(files = this.files) {
155
+ if (!this.shouldCheckTypes()) {
156
+ return;
149
157
  }
150
158
 
151
- this.logger.debug('TsserverClient.init completed');
159
+ const start = Date.now();
160
+ this.getDiagnostic(files).then(() => {
161
+ const end = Date.now() - start;
162
+ const msg = `completed type checking (${end / 1000} sec)`;
163
+
164
+ if (this.lastDiagnostics.length) {
165
+ this.logger.consoleFailure(`${msg}. found errors in ${this.lastDiagnostics.length} files.`);
166
+ } else {
167
+ this.logger.consoleSuccess(`${msg}. no errors were found.`);
168
+ }
169
+ }).catch(err => {
170
+ const msg = `failed getting the type errors from ts-server`;
171
+ this.logger.console(msg);
172
+ this.logger.error(msg, err);
173
+ });
174
+ }
175
+
176
+ shouldCheckTypes() {
177
+ // this also covers this.options.checkTypes !== CheckTypes.None.
178
+ return Boolean(this.options.checkTypes);
152
179
  }
153
180
  /**
154
181
  * if `bit watch` or `bit start` are running in the background, this method is triggered.
@@ -157,18 +184,8 @@ class TsserverClient {
157
184
 
158
185
  async onFileChange(file) {
159
186
  await this.changed(file);
160
-
161
- if (this.options.checkTypes) {
162
- const start = Date.now();
163
- this.getDiagnostic().then(() => {
164
- const end = Date.now() - start;
165
- this.logger.console(`\ntype checking had been completed (${end / 1000} sec) for "${file}"`);
166
- }).catch(err => {
167
- const msg = `failed getting the type errors from ts-server for "${file}"`;
168
- this.logger.console(msg);
169
- this.logger.error(msg, err);
170
- });
171
- }
187
+ const files = this.options.checkTypes === _workspace().CheckTypes.ChangedFile ? [file] : undefined;
188
+ this.checkTypesIfNeeded(files);
172
189
  }
173
190
 
174
191
  killTsServer() {
@@ -186,10 +203,11 @@ class TsserverClient {
186
203
  */
187
204
 
188
205
 
189
- async getDiagnostic() {
206
+ async getDiagnostic(files = this.files) {
207
+ this.lastDiagnostics = [];
190
208
  return this.tsServer.request(_tspCommandTypes().CommandTypes.Geterr, {
191
209
  delay: 0,
192
- files: this.files
210
+ files
193
211
  });
194
212
  }
195
213
  /**
@@ -344,14 +362,15 @@ class TsserverClient {
344
362
  publishDiagnostic(message) {
345
363
  var _message$body;
346
364
 
347
- if (!((_message$body = message.body) !== null && _message$body !== void 0 && _message$body.diagnostics.length) || !this.options.checkTypes) {
365
+ if (!((_message$body = message.body) !== null && _message$body !== void 0 && _message$body.diagnostics.length) || !this.shouldCheckTypes()) {
348
366
  return;
349
367
  }
350
368
 
369
+ this.lastDiagnostics.push(message.body);
370
+
351
371
  const file = _path().default.relative(this.projectPath, message.body.file);
352
372
 
353
- const errorMsg = (0, _formatDiagnostics().formatDiagnostics)(message.body.diagnostics, file);
354
- this.logger.console(errorMsg);
373
+ message.body.diagnostics.forEach(diag => this.logger.console((0, _formatDiagnostics().formatDiagnostic)(diag, file)));
355
374
  }
356
375
  /**
357
376
  * copied over from https://github.com/typescript-language-server/typescript-language-server/blob/master/src/lsp-server.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["ts-server-client.ts"],"names":["TsserverClient","constructor","projectPath","logger","options","files","init","tsServer","ProcessBasedTsServer","tsserverPath","findTsserverPath","logToConsole","verbose","onEvent","onTsserverEvent","bind","start","length","forEach","file","open","checkTypes","Date","now","getDiagnostic","then","end","console","catch","err","msg","error","debug","onFileChange","changed","killTsServer","kill","request","CommandTypes","Geterr","delay","getDiagnosticAllProject","requestedByFile","GeterrForProject","getQuickInfo","position","absFile","convertFileToAbsoluteIfNeeded","openIfNeeded","Quickinfo","line","offset","character","getTypeDefinition","TypeDefinition","getReferences","References","getSignatureHelp","SignatureHelp","configure","configureArgs","Configure","includes","push","notify","Open","projectRootPath","close","Close","filter","openFile","Change","endLine","endOffset","insertString","content","fs","readFile","event","EventName","semanticDiag","syntaxDiag","publishDiagnostic","filepath","path","isAbsolute","join","message","body","diagnostics","relative","errorMsg","tsServerPath","sdk","executable","commandExists","sync","bundled","__dirname","Error"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAIA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAA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qCAAwB,sCAApD,CAAN;AACD;;AAtQyB","sourcesContent":["import fs from 'fs-extra';\nimport { Logger } from '@teambit/logger';\nimport path from 'path';\n// eslint-disable-next-line import/no-unresolved\nimport protocol from 'typescript/lib/protocol';\nimport { Position } from 'vscode-languageserver-types';\nimport commandExists from 'command-exists';\nimport { findPathToModule, findPathToYarnSdk } from './modules-resolver';\nimport { ProcessBasedTsServer } from './process-based-tsserver';\nimport { CommandTypes, EventName } from './tsp-command-types';\nimport { getTsserverExecutable } from './utils';\nimport { formatDiagnostics } from './format-diagnostics';\n\nexport type TsserverClientOpts = {\n verbose?: boolean; // print tsserver events to the console.\n tsServerPath?: string; // if not provided, it'll use findTsserverPath() strategies.\n checkTypes?: boolean; // whether errors/warnings are monitored and printed to the console.\n};\n\nexport class TsserverClient {\n private tsServer: ProcessBasedTsServer;\n constructor(\n /**\n * absolute root path of the project.\n */\n private projectPath: string,\n private logger: Logger,\n private options: TsserverClientOpts = {},\n /**\n * provide files if you want to check types on init. (options.checkTypes should be enabled).\n * paths should be absolute.\n */\n private files: string[] = []\n ) {}\n\n /**\n * start the ts-server and keep its process alive.\n * this methods returns pretty fast. if checkTypes is enabled, it runs the process in the background and\n * doesn't wait for it.\n */\n init() {\n this.tsServer = new ProcessBasedTsServer({\n logger: this.logger,\n tsserverPath: this.findTsserverPath(),\n logToConsole: this.options.verbose,\n onEvent: this.onTsserverEvent.bind(this),\n });\n this.tsServer.start();\n if (this.files.length) {\n this.files.forEach((file) => this.open(file));\n }\n if (this.options.checkTypes) {\n const start = Date.now();\n this.getDiagnostic()\n .then(() => {\n const end = Date.now() - start;\n this.logger.console(`\\ncompleted preliminary type checking (${end / 1000} sec)`);\n })\n .catch((err) => {\n const msg = `failed getting the type errors from ts-server`;\n this.logger.console(msg);\n this.logger.error(msg, err);\n });\n }\n this.logger.debug('TsserverClient.init completed');\n }\n\n /**\n * if `bit watch` or `bit start` are running in the background, this method is triggered.\n */\n async onFileChange(file: string) {\n await this.changed(file);\n if (this.options.checkTypes) {\n const start = Date.now();\n this.getDiagnostic()\n .then(() => {\n const end = Date.now() - start;\n this.logger.console(`\\ntype checking had been completed (${end / 1000} sec) for \"${file}\"`);\n })\n .catch((err) => {\n const msg = `failed getting the type errors from ts-server for \"${file}\"`;\n this.logger.console(msg);\n this.logger.error(msg, err);\n });\n }\n }\n\n killTsServer() {\n this.tsServer.kill();\n }\n\n /**\n * get diagnostic of all files opened in the project.\n * there is little to no value of getting diagnostic for a specific file, as\n * changing a type in one file may cause errors in different files.\n *\n * the errors/diagnostic info are sent as events, see this.onTsserverEvent() for more info.\n *\n * the return value here just shows whether the request was succeeded, it doesn't have any info about whether errors\n * were found or not.\n */\n async getDiagnostic(): Promise<any> {\n return this.tsServer.request(CommandTypes.Geterr, { delay: 0, files: this.files });\n }\n\n /**\n * avoid using this method, it takes longer than `getDiagnostic()` and shows errors from paths outside the project\n */\n async getDiagnosticAllProject(requestedByFile: string): Promise<any> {\n return this.tsServer.request(CommandTypes.GeterrForProject, { file: requestedByFile, delay: 0 });\n }\n\n /**\n * @param file can be absolute or relative to this.projectRoot.\n */\n async getQuickInfo(file: string, position: Position): Promise<protocol.QuickInfoResponse | undefined> {\n const absFile = this.convertFileToAbsoluteIfNeeded(file);\n this.openIfNeeded(absFile);\n return this.tsServer.request(CommandTypes.Quickinfo, {\n file: absFile,\n line: position.line,\n offset: position.character,\n });\n }\n\n /**\n * @param file can be absolute or relative to this.projectRoot.\n */\n async getTypeDefinition(file: string, position: Position): Promise<protocol.TypeDefinitionResponse | undefined> {\n const absFile = this.convertFileToAbsoluteIfNeeded(file);\n this.openIfNeeded(absFile);\n return this.tsServer.request(CommandTypes.TypeDefinition, {\n file: absFile,\n line: position.line,\n offset: position.character,\n });\n }\n\n /**\n * @param file can be absolute or relative to this.projectRoot.\n */\n async getReferences(file: string, position: Position): Promise<protocol.ReferencesResponse | undefined> {\n const absFile = this.convertFileToAbsoluteIfNeeded(file);\n this.openIfNeeded(absFile);\n return this.tsServer.request(CommandTypes.References, {\n file: absFile,\n line: position.line,\n offset: position.character,\n });\n }\n\n /**\n * @param file can be absolute or relative to this.projectRoot.\n */\n async getSignatureHelp(file: string, position: Position): Promise<protocol.SignatureHelpResponse | undefined> {\n const absFile = this.convertFileToAbsoluteIfNeeded(file);\n this.openIfNeeded(absFile);\n return this.tsServer.request(CommandTypes.SignatureHelp, {\n file: absFile,\n line: position.line,\n offset: position.character,\n });\n }\n\n private async configure(\n configureArgs: protocol.ConfigureRequestArguments = {}\n ): Promise<protocol.ConfigureResponse | undefined> {\n return this.tsServer.request(CommandTypes.Configure, configureArgs);\n }\n\n /**\n * ask tsserver to open a file if it was not opened before.\n * @param file absolute path of the file\n */\n openIfNeeded(file: string) {\n if (this.files.includes(file)) {\n return;\n }\n this.open(file);\n this.files.push(file);\n }\n\n private open(file: string) {\n this.tsServer.notify(CommandTypes.Open, {\n file,\n projectRootPath: this.projectPath,\n });\n }\n\n close(file: string) {\n this.tsServer.notify(CommandTypes.Close, {\n file,\n });\n this.files = this.files.filter((openFile) => openFile !== file);\n }\n\n /**\n * since Bit is not an IDE, it doesn't have the information such as the exact line/offset of the changes.\n * as a workaround, to tell tsserver what was changed, we pretend that the entire file was cleared and new text was\n * added. this is the only way I could find to tell tsserver about the change. otherwise, tsserver keep assuming that\n * the file content remained the same. (closing/re-opening the file doesn't help).\n */\n async changed(file: string) {\n // tell tsserver that all content was removed\n this.tsServer.notify(CommandTypes.Change, {\n file,\n line: 1,\n offset: 1,\n endLine: 99999,\n endOffset: 1,\n insertString: '',\n });\n\n const content = await fs.readFile(file, 'utf-8');\n\n // tell tsserver that all file content was added\n this.tsServer.notify(CommandTypes.Change, {\n file,\n line: 1,\n offset: 1,\n endLine: 1,\n endOffset: 1,\n insertString: content,\n });\n }\n\n protected onTsserverEvent(event: protocol.Event): void {\n switch (event.event) {\n case EventName.semanticDiag:\n case EventName.syntaxDiag:\n this.publishDiagnostic(event as protocol.DiagnosticEvent);\n break;\n default:\n this.logger.debug(`ignored TsServer event: ${event.event}`);\n }\n }\n\n private convertFileToAbsoluteIfNeeded(filepath: string): string {\n if (path.isAbsolute(filepath)) {\n return filepath;\n }\n return path.join(this.projectPath, filepath);\n }\n\n private publishDiagnostic(message: protocol.DiagnosticEvent) {\n if (!message.body?.diagnostics.length || !this.options.checkTypes) {\n return;\n }\n const file = path.relative(this.projectPath, message.body.file);\n const errorMsg = formatDiagnostics(message.body.diagnostics, file);\n this.logger.console(errorMsg);\n }\n\n /**\n * copied over from https://github.com/typescript-language-server/typescript-language-server/blob/master/src/lsp-server.ts\n */\n private findTsserverPath(): string {\n if (this.options.tsServerPath) {\n return this.options.tsServerPath;\n }\n const tsServerPath = path.join('typescript', 'lib', 'tsserver.js');\n // 1) look into .yarn/sdks of workspace root\n const sdk = findPathToYarnSdk(this.projectPath, tsServerPath);\n if (sdk) {\n return sdk;\n }\n // 2) look into node_modules of workspace root\n const executable = findPathToModule(this.projectPath, tsServerPath);\n if (executable) {\n return executable;\n }\n // 3) use globally installed tsserver\n if (commandExists.sync(getTsserverExecutable())) {\n return getTsserverExecutable();\n }\n // 4) look into node_modules of typescript-language-server\n const bundled = findPathToModule(__dirname, tsServerPath);\n if (bundled) {\n return bundled;\n }\n throw new Error(`Couldn't find '${getTsserverExecutable()}' executable or 'tsserver.js' module`);\n }\n}\n"]}
1
+ {"version":3,"sources":["ts-server-client.ts"],"names":["TsserverClient","constructor","projectPath","logger","options","files","init","tsServer","ProcessBasedTsServer","tsserverPath","findTsserverPath","logToConsole","verbose","onEvent","onTsserverEvent","bind","start","length","forEach","file","open","checkTypesIfNeeded","debug","shouldCheckTypes","Date","now","getDiagnostic","then","end","msg","lastDiagnostics","consoleFailure","consoleSuccess","catch","err","console","error","Boolean","checkTypes","onFileChange","changed","CheckTypes","ChangedFile","undefined","killTsServer","kill","request","CommandTypes","Geterr","delay","getDiagnosticAllProject","requestedByFile","GeterrForProject","getQuickInfo","position","absFile","convertFileToAbsoluteIfNeeded","openIfNeeded","Quickinfo","line","offset","character","getTypeDefinition","TypeDefinition","getReferences","References","getSignatureHelp","SignatureHelp","configure","configureArgs","Configure","includes","push","notify","Open","projectRootPath","close","Close","filter","openFile","Change","endLine","endOffset","insertString","content","fs","readFile","event","EventName","semanticDiag","syntaxDiag","publishDiagnostic","filepath","path","isAbsolute","join","message","body","diagnostics","relative","diag","tsServerPath","sdk","executable","commandExists","sync","bundled","__dirname","Error"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAQO,MAAMA,cAAN,CAAqB;AAG1BC,EAAAA,WAAW;AACT;AACJ;AACA;AACYC,EAAAA,WAJC,EAKDC,MALC,EAMDC,OAA2B,GAAG,EAN7B;AAOT;AACJ;AACA;AACA;AACYC,EAAAA,KAAe,GAAG,EAXjB,EAYT;AAAA,SARQH,WAQR,GARQA,WAQR;AAAA,SAPQC,MAOR,GAPQA,MAOR;AAAA,SANQC,OAMR,GANQA,OAMR;AAAA,SADQC,KACR,GADQA,KACR;AAAA;AAAA,6DAbwD,EAaxD;AAAE;AAEJ;AACF;AACA;AACA;AACA;;;AACEC,EAAAA,IAAI,GAAG;AACL,SAAKC,QAAL,GAAgB,KAAIC,4CAAJ,EAAyB;AACvCL,MAAAA,MAAM,EAAE,KAAKA,MAD0B;AAEvCM,MAAAA,YAAY,EAAE,KAAKC,gBAAL,EAFyB;AAGvCC,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MAAL,CAAYgC,OAAZ,CAAoB,2CAAiBiE,IAAjB,EAAuBjF,IAAvB,CAApB,CAA3C;AACD;AAED;AACF;AACA;;;AACUT,EAAAA,gBAAgB,GAAW;AACjC,QAAI,KAAKN,OAAL,CAAaiG,YAAjB,EAA+B;AAC7B,aAAO,KAAKjG,OAAL,CAAaiG,YAApB;AACD;;AACD,UAAMA,YAAY,GAAGR,gBAAKE,IAAL,CAAU,YAAV,EAAwB,KAAxB,EAA+B,aAA/B,CAArB,CAJiC,CAKjC;;;AACA,UAAMO,GAAG,GAAG,0CAAkB,KAAKpG,WAAvB,EAAoCmG,YAApC,CAAZ;;AACA,QAAIC,GAAJ,EAAS;AACP,aAAOA,GAAP;AACD,KATgC,CAUjC;;;AACA,UAAMC,UAAU,GAAG,yCAAiB,KAAKrG,WAAtB,EAAmCmG,YAAnC,CAAnB;;AACA,QAAIE,UAAJ,EAAgB;AACd,aAAOA,UAAP;AACD,KAdgC,CAejC;;;AACA,QAAIC,yBAAcC,IAAd,CAAmB,qCAAnB,CAAJ,EAAiD;AAC/C,aAAO,qCAAP;AACD,KAlBgC,CAmBjC;;;AACA,UAAMC,OAAO,GAAG,yCAAiBC,SAAjB,EAA4BN,YAA5B,CAAhB;;AACA,QAAIK,OAAJ,EAAa;AACX,aAAOA,OAAP;AACD;;AACD,UAAM,IAAIE,KAAJ,CAAW,kBAAiB,qCAAwB,sCAApD,CAAN;AACD;;AA5QyB","sourcesContent":["import fs from 'fs-extra';\nimport { Logger } from '@teambit/logger';\nimport path from 'path';\n// eslint-disable-next-line import/no-unresolved\nimport protocol from 'typescript/lib/protocol';\nimport { CheckTypes } from '@teambit/workspace';\nimport type { Position } from 'vscode-languageserver-types';\nimport commandExists from 'command-exists';\nimport { findPathToModule, findPathToYarnSdk } from './modules-resolver';\nimport { ProcessBasedTsServer } from './process-based-tsserver';\nimport { CommandTypes, EventName } from './tsp-command-types';\nimport { getTsserverExecutable } from './utils';\nimport { formatDiagnostic } from './format-diagnostics';\n\nexport type TsserverClientOpts = {\n verbose?: boolean; // print tsserver events to the console.\n tsServerPath?: string; // if not provided, it'll use findTsserverPath() strategies.\n checkTypes?: CheckTypes; // whether errors/warnings are monitored and printed to the console.\n};\n\nexport class TsserverClient {\n private tsServer: ProcessBasedTsServer;\n private lastDiagnostics: protocol.DiagnosticEventBody[] = [];\n constructor(\n /**\n * absolute root path of the project.\n */\n private projectPath: string,\n private logger: Logger,\n private options: TsserverClientOpts = {},\n /**\n * provide files if you want to check types on init. (options.checkTypes should be enabled).\n * paths should be absolute.\n */\n private files: string[] = []\n ) {}\n\n /**\n * start the ts-server and keep its process alive.\n * this methods returns pretty fast. if checkTypes is enabled, it runs the process in the background and\n * doesn't wait for it.\n */\n init() {\n this.tsServer = new ProcessBasedTsServer({\n logger: this.logger,\n tsserverPath: this.findTsserverPath(),\n logToConsole: this.options.verbose,\n onEvent: this.onTsserverEvent.bind(this),\n });\n this.tsServer.start();\n if (this.files.length) {\n this.files.forEach((file) => this.open(file));\n }\n this.checkTypesIfNeeded();\n this.logger.debug('TsserverClient.init completed');\n }\n\n private checkTypesIfNeeded(files = this.files) {\n if (!this.shouldCheckTypes()) {\n return;\n }\n const start = Date.now();\n this.getDiagnostic(files)\n .then(() => {\n const end = Date.now() - start;\n const msg = `completed type checking (${end / 1000} sec)`;\n if (this.lastDiagnostics.length) {\n this.logger.consoleFailure(`${msg}. found errors in ${this.lastDiagnostics.length} files.`);\n } else {\n this.logger.consoleSuccess(`${msg}. no errors were found.`);\n }\n })\n .catch((err) => {\n const msg = `failed getting the type errors from ts-server`;\n this.logger.console(msg);\n this.logger.error(msg, err);\n });\n }\n\n private shouldCheckTypes() {\n // this also covers this.options.checkTypes !== CheckTypes.None.\n return Boolean(this.options.checkTypes);\n }\n\n /**\n * if `bit watch` or `bit start` are running in the background, this method is triggered.\n */\n async onFileChange(file: string) {\n await this.changed(file);\n const files = this.options.checkTypes === CheckTypes.ChangedFile ? [file] : undefined;\n this.checkTypesIfNeeded(files);\n }\n\n killTsServer() {\n this.tsServer.kill();\n }\n\n /**\n * get diagnostic of all files opened in the project.\n * there is little to no value of getting diagnostic for a specific file, as\n * changing a type in one file may cause errors in different files.\n *\n * the errors/diagnostic info are sent as events, see this.onTsserverEvent() for more info.\n *\n * the return value here just shows whether the request was succeeded, it doesn't have any info about whether errors\n * were found or not.\n */\n async getDiagnostic(files = this.files): Promise<any> {\n this.lastDiagnostics = [];\n return this.tsServer.request(CommandTypes.Geterr, { delay: 0, files });\n }\n\n /**\n * avoid using this method, it takes longer than `getDiagnostic()` and shows errors from paths outside the project\n */\n async getDiagnosticAllProject(requestedByFile: string): Promise<any> {\n return this.tsServer.request(CommandTypes.GeterrForProject, { file: requestedByFile, delay: 0 });\n }\n\n /**\n * @param file can be absolute or relative to this.projectRoot.\n */\n async getQuickInfo(file: string, position: Position): Promise<protocol.QuickInfoResponse | undefined> {\n const absFile = this.convertFileToAbsoluteIfNeeded(file);\n this.openIfNeeded(absFile);\n return this.tsServer.request(CommandTypes.Quickinfo, {\n file: absFile,\n line: position.line,\n offset: position.character,\n });\n }\n\n /**\n * @param file can be absolute or relative to this.projectRoot.\n */\n async getTypeDefinition(file: string, position: Position): Promise<protocol.TypeDefinitionResponse | undefined> {\n const absFile = this.convertFileToAbsoluteIfNeeded(file);\n this.openIfNeeded(absFile);\n return this.tsServer.request(CommandTypes.TypeDefinition, {\n file: absFile,\n line: position.line,\n offset: position.character,\n });\n }\n\n /**\n * @param file can be absolute or relative to this.projectRoot.\n */\n async getReferences(file: string, position: Position): Promise<protocol.ReferencesResponse | undefined> {\n const absFile = this.convertFileToAbsoluteIfNeeded(file);\n this.openIfNeeded(absFile);\n return this.tsServer.request(CommandTypes.References, {\n file: absFile,\n line: position.line,\n offset: position.character,\n });\n }\n\n /**\n * @param file can be absolute or relative to this.projectRoot.\n */\n async getSignatureHelp(file: string, position: Position): Promise<protocol.SignatureHelpResponse | undefined> {\n const absFile = this.convertFileToAbsoluteIfNeeded(file);\n this.openIfNeeded(absFile);\n return this.tsServer.request(CommandTypes.SignatureHelp, {\n file: absFile,\n line: position.line,\n offset: position.character,\n });\n }\n\n private async configure(\n configureArgs: protocol.ConfigureRequestArguments = {}\n ): Promise<protocol.ConfigureResponse | undefined> {\n return this.tsServer.request(CommandTypes.Configure, configureArgs);\n }\n\n /**\n * ask tsserver to open a file if it was not opened before.\n * @param file absolute path of the file\n */\n openIfNeeded(file: string) {\n if (this.files.includes(file)) {\n return;\n }\n this.open(file);\n this.files.push(file);\n }\n\n private open(file: string) {\n this.tsServer.notify(CommandTypes.Open, {\n file,\n projectRootPath: this.projectPath,\n });\n }\n\n close(file: string) {\n this.tsServer.notify(CommandTypes.Close, {\n file,\n });\n this.files = this.files.filter((openFile) => openFile !== file);\n }\n\n /**\n * since Bit is not an IDE, it doesn't have the information such as the exact line/offset of the changes.\n * as a workaround, to tell tsserver what was changed, we pretend that the entire file was cleared and new text was\n * added. this is the only way I could find to tell tsserver about the change. otherwise, tsserver keep assuming that\n * the file content remained the same. (closing/re-opening the file doesn't help).\n */\n async changed(file: string) {\n // tell tsserver that all content was removed\n this.tsServer.notify(CommandTypes.Change, {\n file,\n line: 1,\n offset: 1,\n endLine: 99999,\n endOffset: 1,\n insertString: '',\n });\n\n const content = await fs.readFile(file, 'utf-8');\n\n // tell tsserver that all file content was added\n this.tsServer.notify(CommandTypes.Change, {\n file,\n line: 1,\n offset: 1,\n endLine: 1,\n endOffset: 1,\n insertString: content,\n });\n }\n\n protected onTsserverEvent(event: protocol.Event): void {\n switch (event.event) {\n case EventName.semanticDiag:\n case EventName.syntaxDiag:\n this.publishDiagnostic(event as protocol.DiagnosticEvent);\n break;\n default:\n this.logger.debug(`ignored TsServer event: ${event.event}`);\n }\n }\n\n private convertFileToAbsoluteIfNeeded(filepath: string): string {\n if (path.isAbsolute(filepath)) {\n return filepath;\n }\n return path.join(this.projectPath, filepath);\n }\n\n private publishDiagnostic(message: protocol.DiagnosticEvent) {\n if (!message.body?.diagnostics.length || !this.shouldCheckTypes()) {\n return;\n }\n this.lastDiagnostics.push(message.body);\n const file = path.relative(this.projectPath, message.body.file);\n message.body.diagnostics.forEach((diag) => this.logger.console(formatDiagnostic(diag, file)));\n }\n\n /**\n * copied over from https://github.com/typescript-language-server/typescript-language-server/blob/master/src/lsp-server.ts\n */\n private findTsserverPath(): string {\n if (this.options.tsServerPath) {\n return this.options.tsServerPath;\n }\n const tsServerPath = path.join('typescript', 'lib', 'tsserver.js');\n // 1) look into .yarn/sdks of workspace root\n const sdk = findPathToYarnSdk(this.projectPath, tsServerPath);\n if (sdk) {\n return sdk;\n }\n // 2) look into node_modules of workspace root\n const executable = findPathToModule(this.projectPath, tsServerPath);\n if (executable) {\n return executable;\n }\n // 3) use globally installed tsserver\n if (commandExists.sync(getTsserverExecutable())) {\n return getTsserverExecutable();\n }\n // 4) look into node_modules of typescript-language-server\n const bundled = findPathToModule(__dirname, tsServerPath);\n if (bundled) {\n return bundled;\n }\n throw new Error(`Couldn't find '${getTsserverExecutable()}' executable or 'tsserver.js' module`);\n }\n}\n"]}
@@ -18,14 +18,14 @@ export function formatDiagnostics(diagnostics: readonly Diagnostic[], filePath:
18
18
 
19
19
  const diagnosticCategoryName = (diagnostic: Diagnostic) => diagnostic.category;
20
20
 
21
- function formatDiagnostic(diagnostic: Diagnostic, filePath: string): string {
21
+ export function formatDiagnostic(diagnostic: Diagnostic, filePath: string): string {
22
22
  const errorMessage = `${diagnosticCategoryName(diagnostic)} TS${diagnostic.code}: ${flattenDiagnosticMessageText(
23
23
  diagnostic.text,
24
24
  '\n'
25
25
  )}${'\n'}`;
26
26
 
27
27
  const { line, offset } = diagnostic.start;
28
- return `${filePath}(${line + 1},${offset + 1}): ${errorMessage}`;
28
+ return `${filePath}(${line},${offset}): ${errorMessage}`;
29
29
  }
30
30
 
31
31
  function flattenDiagnosticMessageText(
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/ts-server",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "homepage": "https://bit.dev/teambit/typescript/ts-server",
5
5
  "main": "dist/index.js",
6
6
  "componentId": {
7
7
  "scope": "teambit.typescript",
8
8
  "name": "ts-server",
9
- "version": "0.0.2"
9
+ "version": "0.0.3"
10
10
  },
11
11
  "dependencies": {
12
12
  "typescript": "4.4.2",
@@ -1,6 +1,5 @@
1
1
  /**
2
- * copied over from https://github.com/typescript-language-server/typescript-language-server/blob/master/src/tsp-client.ts
3
- * modified to accommodate Bit needs
2
+ * part of this file was copied over from https://github.com/typescript-language-server/typescript-language-server/blob/master/src/tsp-client.ts
4
3
  */
5
4
 
6
5
  /*
@@ -3,22 +3,24 @@ import { Logger } from '@teambit/logger';
3
3
  import path from 'path';
4
4
  // eslint-disable-next-line import/no-unresolved
5
5
  import protocol from 'typescript/lib/protocol';
6
- import { Position } from 'vscode-languageserver-types';
6
+ import { CheckTypes } from '@teambit/workspace';
7
+ import type { Position } from 'vscode-languageserver-types';
7
8
  import commandExists from 'command-exists';
8
9
  import { findPathToModule, findPathToYarnSdk } from './modules-resolver';
9
10
  import { ProcessBasedTsServer } from './process-based-tsserver';
10
11
  import { CommandTypes, EventName } from './tsp-command-types';
11
12
  import { getTsserverExecutable } from './utils';
12
- import { formatDiagnostics } from './format-diagnostics';
13
+ import { formatDiagnostic } from './format-diagnostics';
13
14
 
14
15
  export type TsserverClientOpts = {
15
16
  verbose?: boolean; // print tsserver events to the console.
16
17
  tsServerPath?: string; // if not provided, it'll use findTsserverPath() strategies.
17
- checkTypes?: boolean; // whether errors/warnings are monitored and printed to the console.
18
+ checkTypes?: CheckTypes; // whether errors/warnings are monitored and printed to the console.
18
19
  };
19
20
 
20
21
  export class TsserverClient {
21
22
  private tsServer: ProcessBasedTsServer;
23
+ private lastDiagnostics: protocol.DiagnosticEventBody[] = [];
22
24
  constructor(
23
25
  /**
24
26
  * absolute root path of the project.
@@ -49,40 +51,44 @@ export class TsserverClient {
49
51
  if (this.files.length) {
50
52
  this.files.forEach((file) => this.open(file));
51
53
  }
52
- if (this.options.checkTypes) {
53
- const start = Date.now();
54
- this.getDiagnostic()
55
- .then(() => {
56
- const end = Date.now() - start;
57
- this.logger.console(`\ncompleted preliminary type checking (${end / 1000} sec)`);
58
- })
59
- .catch((err) => {
60
- const msg = `failed getting the type errors from ts-server`;
61
- this.logger.console(msg);
62
- this.logger.error(msg, err);
63
- });
64
- }
54
+ this.checkTypesIfNeeded();
65
55
  this.logger.debug('TsserverClient.init completed');
66
56
  }
67
57
 
58
+ private checkTypesIfNeeded(files = this.files) {
59
+ if (!this.shouldCheckTypes()) {
60
+ return;
61
+ }
62
+ const start = Date.now();
63
+ this.getDiagnostic(files)
64
+ .then(() => {
65
+ const end = Date.now() - start;
66
+ const msg = `completed type checking (${end / 1000} sec)`;
67
+ if (this.lastDiagnostics.length) {
68
+ this.logger.consoleFailure(`${msg}. found errors in ${this.lastDiagnostics.length} files.`);
69
+ } else {
70
+ this.logger.consoleSuccess(`${msg}. no errors were found.`);
71
+ }
72
+ })
73
+ .catch((err) => {
74
+ const msg = `failed getting the type errors from ts-server`;
75
+ this.logger.console(msg);
76
+ this.logger.error(msg, err);
77
+ });
78
+ }
79
+
80
+ private shouldCheckTypes() {
81
+ // this also covers this.options.checkTypes !== CheckTypes.None.
82
+ return Boolean(this.options.checkTypes);
83
+ }
84
+
68
85
  /**
69
86
  * if `bit watch` or `bit start` are running in the background, this method is triggered.
70
87
  */
71
88
  async onFileChange(file: string) {
72
89
  await this.changed(file);
73
- if (this.options.checkTypes) {
74
- const start = Date.now();
75
- this.getDiagnostic()
76
- .then(() => {
77
- const end = Date.now() - start;
78
- this.logger.console(`\ntype checking had been completed (${end / 1000} sec) for "${file}"`);
79
- })
80
- .catch((err) => {
81
- const msg = `failed getting the type errors from ts-server for "${file}"`;
82
- this.logger.console(msg);
83
- this.logger.error(msg, err);
84
- });
85
- }
90
+ const files = this.options.checkTypes === CheckTypes.ChangedFile ? [file] : undefined;
91
+ this.checkTypesIfNeeded(files);
86
92
  }
87
93
 
88
94
  killTsServer() {
@@ -99,8 +105,9 @@ export class TsserverClient {
99
105
  * the return value here just shows whether the request was succeeded, it doesn't have any info about whether errors
100
106
  * were found or not.
101
107
  */
102
- async getDiagnostic(): Promise<any> {
103
- return this.tsServer.request(CommandTypes.Geterr, { delay: 0, files: this.files });
108
+ async getDiagnostic(files = this.files): Promise<any> {
109
+ this.lastDiagnostics = [];
110
+ return this.tsServer.request(CommandTypes.Geterr, { delay: 0, files });
104
111
  }
105
112
 
106
113
  /**
@@ -243,12 +250,12 @@ export class TsserverClient {
243
250
  }
244
251
 
245
252
  private publishDiagnostic(message: protocol.DiagnosticEvent) {
246
- if (!message.body?.diagnostics.length || !this.options.checkTypes) {
253
+ if (!message.body?.diagnostics.length || !this.shouldCheckTypes()) {
247
254
  return;
248
255
  }
256
+ this.lastDiagnostics.push(message.body);
249
257
  const file = path.relative(this.projectPath, message.body.file);
250
- const errorMsg = formatDiagnostics(message.body.diagnostics, file);
251
- this.logger.console(errorMsg);
258
+ message.body.diagnostics.forEach((diag) => this.logger.console(formatDiagnostic(diag, file)));
252
259
  }
253
260
 
254
261
  /**