Skip to content

server API

phoenixide edited this page Dec 29, 2023 · 12 revisions

createTSServerInstance

Creates a new instance of TypeScript Server.

Returns Object An object containing methods to interact with TypeScript Server.

initTSServer

Initializes the TypeScript Server instance.

This function starts a new process for the TypeScript Server using Node's child_process.spawn. It sets up listeners for the 'stdout' and 'stderr' streams of the TypeScript Server process, handling incoming data and errors respectively. It also handles the 'close' event of the process. The function configures a timeout to reject the promise if the server does not start within a specified time.

Parameters

  • node string The path to the Node.js executable. If not provided, defaults to 'node'. (optional, default "")
  • tsServer string The path to the TypeScript Server executable. If not provided, defaults to the 'tsserver' path in the 'node_modules' directory. (optional, default "")

Returns Promise<void> A promise that resolves when the TypeScript Server is ready, or rejects if there is an error or timeout.

onData

Handles incoming data from the TypeScript Server.

Parameters

  • rawData string Raw data received from tsserver.

processMessage

Processes a complete message from tsserver.

Parameters

  • message string A complete message in JSON format.

hasCompleteMessage

Checks if the buffer has a complete message based on Content-Length.

Returns boolean True if a complete message is present in the buffer.

sendCommand

Sends a command to the TypeScript Server. Special handling for 'open' command as it does not receive a response.

Parameters

  • command Object The command object to send.
  • timeout number The timeout in milliseconds for the command. (optional, default 5000)

Returns Promise<Object> A promise that resolves with the response from tsserver.

openFile

Sends an 'open file' command to the TypeScript Server.

Parameters

  • filePath string The path to the TypeScript file to open.
  • timeout number The timeout in milliseconds for the command. (optional, default 5000)

Returns Promise<Object> A promise that resolves with the response from tsserver.

sendChange

Sends a 'change' command to the TypeScript Server.

Parameters

  • filePath string The path to the file.
  • start Object The start position of the change (line and offset).
  • end Object The end position of the change (line and offset).
  • newText string The new text to replace in the range.

closeFile

Sends a 'close' command to the TypeScript Server.

Parameters

  • filePath string The path to the file being closed.

getDefinition

Sends a 'definition' request to the TypeScript Server.

Parameters

  • filePath string The path to the file.
  • line number The line number of the position.
  • offset number The offset in the line of the position.

Returns Promise<Object> A promise that resolves with the response from tsserver.

getQuickInfo

Sends a 'quickinfo' request to the TypeScript Server.

Parameters

  • filePath string The path to the file.
  • line number The line number of the position.
  • offset number The offset in the line of the position.

Returns Promise<Object> A promise that resolves with the response from tsserver.

findReferences

Sends a 'references' request to the TypeScript Server.

Parameters

  • filePath string The path to the file.
  • line number The line number of the position.
  • offset number The offset in the line of the position.

Returns Promise<Object> A promise that resolves with the response from tsserver.

findSourceDefinition

Sends a 'FindSourceDefinition' request to the TypeScript Server.

Parameters

  • filePath string The path to the file.
  • line number The line number of the position.
  • offset number The offset in the line of the position.

Returns Promise<Object> A promise that resolves with the response from tsserver.

getCompletionInfo

Sends a 'completionInfo' command to the TypeScript Server.

Parameters

  • filePath string The path to the file.
  • line number The line number of the position.
  • offset number The offset in the line of the position.

Returns Promise<Object> A promise that resolves with the response from tsserver.

getCompletionDetails

Sends a 'completionEntryDetails' request to the TypeScript Server.

Parameters

  • filePath string The path to the file.
  • line number The line number of the position.
  • offset number The offset in the line of the position.
  • entryName string The name of the completion entry.

Returns Promise<Object> A promise that resolves with the response from tsserver.

getCompileOnSaveAffectedFileList

Sends a 'compileOnSaveAffectedFileList' request to the TypeScript Server.

Parameters

  • filePath string The path to the file.

Returns Promise<Object> A promise that resolves with the response from tsserver.

compileOnSaveEmitFile

Sends a 'compileOnSaveEmitFile' command to the TypeScript Server.

Parameters

  • filePath string The path to the TypeScript file.
  • forced boolean Force emit even if there are errors. (optional, default false)
  • includeLinePosition boolean Include line position in the response. (optional, default false)
  • richResponse boolean If true, returns response as an object with detailed emit results. (optional, default false)

Returns Promise<(boolean | EmitResult)> A promise that resolves with a boolean indicating success or an EmitResult object containing detailed information about the emit process. - If a boolean: true if the emit was successful, false otherwise. - If an EmitResult object: - emitSkipped: A boolean indicating whether the emit was skipped. - diagnostics: An array of Diagnostic or DiagnosticWithLinePosition objects, providing detailed information about each diagnostic message. - Diagnostic: An object representing a diagnostic message, typically containing: - start: The starting position of the diagnostic message. - length: The length of the diagnostic message. - text: The text of the diagnostic message. - DiagnosticWithLinePosition: An extended version of Diagnostic, including line and character position information: - start: The starting position of the diagnostic message (line and character). - end: The ending position of the diagnostic message (line and character). - text: The text of the diagnostic message.

getDefinitionAndBoundSpan

Sends a 'definitionAndBoundSpan' request to the TypeScript Server.

Parameters

  • filePath string The path to the file.
  • line number The line number of the position.
  • offset number The offset in the line of the position.

Returns Promise<Object> A promise that resolves with the response from tsserver.

getImplementations

Sends an 'implementation' request to the TypeScript Server.

Parameters

  • filePath string The path to the file.
  • line number The line number of the position.
  • offset number The offset in the line of the position.

Returns Promise<Object> A promise that resolves with the response from tsserver.

format

Sends a 'format' request to the TypeScript Server.

Parameters

  • filePath string The path to the file.
  • startLine number The starting line number of the format range.
  • startOffset number The starting offset in the start line.
  • endLine number The ending line number of the format range.
  • endOffset number The ending offset in the end line.
  • formatOptions object? Optional formatting options. (optional, default {})

Returns Promise<Object> A promise that resolves with the response from tsserver.

exitServer

Sends an 'exit' command to the TypeScript Server to gracefully shut it down.

formatOnKey

Sends a 'formatonkey' request to the TypeScript Server. This command is used for formatting code at a specific position in a file, typically in response to a keystroke. It's commonly used for auto-formatting a line of code when a specific key (like a closing brace or semi-colon) is pressed.

Parameters

  • filePath string The path to the TypeScript file. The path should be absolute or relative to the TypeScript server's current working directory.
  • line number The 1-based line number in the file where the key was pressed. This and the offset together point to the specific position in the file.
  • offset number The 1-based character offset in the line where the key was pressed. This is typically the position right after where the key was pressed.
  • key string The character corresponding to the key pressed. This is typically a single character like ';' or '}' that triggers the formatting action.
  • formatOptions object? Optional formatting options to customize the formatting behavior. These options might include settings like tab size, indent size, whether to insert spaces, and so on. Example: { tabSize: 4, indentSize: 4, insertSpace: true } (optional, default {})

Returns Promise<Object> A promise that resolves with the response from tsserver. The response typically includes an array of code edits that should be applied to the file to achieve the desired formatting. Each edit suggests changes like text insertions, deletions, or replacements.

getErrors

Sends a 'geterr' request to the TypeScript Server. This command instructs the server to compute and return errors (diagnostics) for the specified files. The diagnostics are not returned directly by this function but are instead sent back by the server as separate events or messages. This function is useful for asynchronously obtaining diagnostic information like errors and warnings from the server.

Parameters

  • filePaths Array<string> An array of paths to the files for which to get errors. Each path should be either absolute or relative to the TypeScript server's current working directory.
  • delay number The delay in milliseconds to wait before the server processes the request. This delay can be used to batch or throttle error requests, especially when dealing with a large number of file changes or edits.

Returns Promise<void> A promise that resolves when the command has been sent to the server. The resolution of this promise indicates that the request was successfully dispatched, but it does not imply that the errors have been received. The actual errors (diagnostics) will be sent back by the server asynchronously as separate events or messages, which should be handled separately in the client's message handling logic.Example usage: getErrors(['path/to/file1.ts', 'path/to/file2.ts'], 500).then(() => { console.log('Error request sent. Waiting for diagnostics...'); });Note: The client should implement additional logic to listen for and handle the diagnostic events or messages sent by the server in response to this request.

getErrorsForProject

Sends a 'geterrForProject' request to the TypeScript Server. This command instructs the server to compute and return errors (diagnostics) for all files in a specific project. The diagnostics are not returned directly by this function but are instead sent back by the server as separate events or messages. This function is useful for asynchronously obtaining a comprehensive diagnostic overview of an entire project.

Parameters

  • filePath string The path to any file within the project. The server uses this file to identify the project context. The path should be absolute or relative to the TypeScript server's current working directory.
  • delay number The delay in milliseconds before the server processes the request. This delay can be used to batch or throttle diagnostic requests, especially useful when dealing with large projects or numerous file changes.

Returns Promise<void> A promise that resolves when the command has been sent to the server. The resolution of this promise indicates that the request was successfully dispatched, but it does not imply that the errors have been received. The actual errors (diagnostics) for the entire project will be sent back by the server asynchronously as separate events or messages, which should be handled separately in the client's message handling logic.Example usage: getErrorsForProject('path/to/anyFileInProject.ts', 500).then(() => { console.log('Project error request sent. Waiting for diagnostics...'); });Note: The client should implement additional logic to listen for and handle the diagnostic events or messages sent by the server in response to this request. These diagnostics will cover the entire scope of the project associated with the provided file path.

getSemanticDiagnosticsSync

Sends a 'semanticDiagnosticsSync' request to the TypeScript Server. This command is used to synchronously request semantic diagnostics (such as type errors) for a specific file. It's useful when immediate and up-to-date semantic error information is needed for a file, such as during file saves or build operations.

Parameters

  • filePath string The path to the TypeScript file for which semantic diagnostics are requested. The path should be absolute or relative to the TypeScript server's current working directory.
  • includeLinePosition boolean If set to true, the response will include detailed line and character position information for each diagnostic. This is useful for integrations that require precise location data, such as IDEs or advanced text editors. (optional, default false)

Returns Promise<Object> A promise that resolves with the semantic diagnostics response from tsserver. The response includes an array of diagnostic objects, each representing a semantic error or warning found in the file. Each diagnostic object typically contains the following information: - start: The starting position of the error (line and character). - length: The length of the error in characters. - text: The error message text. - category: The error category ('error', 'warning', or 'suggestion'). - code: The error code (useful for further reference or lookups). If includeLinePosition is true, additional line and character position information will be included in each diagnostic.Example usage: getSemanticDiagnosticsSync('path/to/file.ts', true).then(response => { console.log('Semantic diagnostics with line positions:', response); }).catch(error => { console.error('Error getting semantic diagnostics:', error); });Note: This function performs a synchronous request, meaning it waits for the TypeScript server to compute and return the diagnostics. The response is directly related to the current state of the file at the time of the request.

killTSServer

  • See: exitServer - Sends an 'exit' command to the TypeScript Server for a graceful shutdown.

Terminates the TypeScript Server process. Warning: Use this function with caution. Prefer using the exitServer function for a graceful shutdown.

Clone this wiki locally