Security News
Node.js EOL Versions CVE Dubbed the "Worst CVE of the Year" by Security Experts
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
typescript-language-server
Advanced tools
Language Server Protocol (LSP) implementation for TypeScript using tsserver
The typescript-language-server is an implementation of the Language Server Protocol (LSP) for TypeScript. It provides a range of features to enhance the development experience in editors and IDEs by offering functionalities like auto-completion, go-to-definition, and more.
Auto-completion
This code sets up a basic TypeScript Language Server that provides auto-completion suggestions. When the user types, the server can suggest completions like 'console.log'.
const { createConnection, TextDocuments } = require('vscode-languageserver');
const connection = createConnection();
const documents = new TextDocuments();
connection.onInitialize(() => {
return {
capabilities: {
textDocumentSync: documents.syncKind,
completionProvider: {
resolveProvider: true
}
}
};
});
connection.onCompletion(() => {
return [
{
label: 'console.log',
kind: 1,
data: 1
}
];
});
connection.listen();
Go-to-definition
This code sets up a TypeScript Language Server that provides go-to-definition functionality. When the user requests the definition of a symbol, the server responds with the location of the definition.
const { createConnection, TextDocuments } = require('vscode-languageserver');
const connection = createConnection();
const documents = new TextDocuments();
connection.onInitialize(() => {
return {
capabilities: {
textDocumentSync: documents.syncKind,
definitionProvider: true
}
};
});
connection.onDefinition((params) => {
return {
uri: params.textDocument.uri,
range: {
start: { line: 0, character: 0 },
end: { line: 0, character: 10 }
}
};
});
connection.listen();
Diagnostics
This code sets up a TypeScript Language Server that provides diagnostics. It scans the document for 'TODO' comments and reports them as warnings.
const { createConnection, TextDocuments, Diagnostic, DiagnosticSeverity } = require('vscode-languageserver');
const connection = createConnection();
const documents = new TextDocuments();
connection.onInitialize(() => {
return {
capabilities: {
textDocumentSync: documents.syncKind
}
};
});
documents.onDidChangeContent((change) => {
const diagnostics = [];
const text = change.document.getText();
const pattern = /TODO/g;
let match;
while ((match = pattern.exec(text))) {
diagnostics.push({
severity: DiagnosticSeverity.Warning,
range: {
start: change.document.positionAt(match.index),
end: change.document.positionAt(match.index + match[0].length)
},
message: `TODO found: ${match[0]}`,
source: 'ex'
});
}
connection.sendDiagnostics({ uri: change.document.uri, diagnostics });
});
connection.listen();
The vscode-json-languageserver is a Language Server Protocol implementation for JSON. It provides similar functionalities like auto-completion, go-to-definition, and diagnostics but is specifically tailored for JSON files. Compared to typescript-language-server, it is focused on JSON rather than TypeScript.
The vscode-css-languageserver-bin is a Language Server Protocol implementation for CSS. It offers features like auto-completion, go-to-definition, and diagnostics for CSS files. While typescript-language-server is for TypeScript, this package is specialized for CSS.
The vscode-html-languageserver-bin is a Language Server Protocol implementation for HTML. It provides functionalities such as auto-completion, go-to-definition, and diagnostics for HTML files. This package is similar to typescript-language-server but is designed for HTML.
Language Server Protocol implementation for TypeScript wrapping tsserver
.
Based on concepts and ideas from https://github.com/prabirshrestha/typescript-language-server and originally maintained by TypeFox.
Maintained by a community of contributors like you.
npm install -g typescript-language-server typescript
typescript-language-server --stdio
Usage: typescript-language-server [options]
Options:
-V, --version output the version number
--stdio use stdio (required option)
--log-level <log-level> A number indicating the log level (4 = log, 3 = info, 2 = warn, 1 = error). Defaults to `3`.
-h, --help output usage information
See configuration documentation.
Server announces support for the following code action kinds:
source.fixAll.ts
- despite the name, fixes a couple of specific issues: unreachable code, await in non-async functions, incorrectly implemented interfacesource.removeUnused.ts
- removes declared but unused variablessource.addMissingImports.ts
- adds imports for used but not imported symbolssource.removeUnusedImports.ts
- removes unused importssource.sortImports.ts
- sorts importssource.organizeImports.ts
- organizes and removes unused importsThis allows editors that support running code actions on save to automatically run fixes associated with those kinds.
Those code actions, if they apply in the current code, should also be presented in the list of "Source Actions" if the editor exposes those.
The user can enable it with a setting similar to (can vary per-editor):
"codeActionsOnSave": {
"source.organizeImports.ts": true,
// or just
"source.organizeImports": true,
}
workspace/executeCommand
)See LSP specification.
Most of the time, you'll execute commands with arguments retrieved from another request like textDocument/codeAction
. There are some use cases for calling them manually.
lsp
refers to the language server protocol types, tsp
refers to the typescript server protocol types.
{
command: `_typescript.goToSourceDefinition`
arguments: [
lsp.DocumentUri, // String URI of the document
lsp.Position, // Line and character position (zero-based)
]
}
lsp.Location[] | null
(This command is supported from Typescript 4.7.)
{
command: `_typescript.applyWorkspaceEdit`
arguments: [lsp.WorkspaceEdit]
}
lsp.ApplyWorkspaceEditResult
{
command: `_typescript.applyCodeAction`
arguments: [
tsp.CodeAction, // TypeScript Code Action object
]
}
void
{
command: `_typescript.applyRefactoring`
arguments: [
tsp.GetEditsForRefactorRequestArgs,
]
}
void
{
command: `_typescript.organizeImports`
arguments: [
// The "skipDestructiveCodeActions" argument is supported from Typescript 4.4+
[string] | [string, { skipDestructiveCodeActions?: boolean }],
]
}
void
{
command: `_typescript.applyRenameFile`
arguments: [
{ sourceUri: string; targetUri: string; },
]
}
void
{
command: `_typescript.configurePlugin`
arguments: [pluginName: string, configuration: any]
}
void
textDocument/codeLens
)Code lenses can be enabled using the implementationsCodeLens
and referencesCodeLens
workspace configuration options.
Code lenses provide a count of references and/or implemenations for symbols in the document. For clients that support it it's also possible to click on those to navigate to the relevant locations in the the project. Do note that clicking those trigger a editor.action.showReferences
command which is something that client needs to have explicit support for. Many do by default but some don't. An example command will look like this:
command: {
title: '1 reference',
command: 'editor.action.showReferences',
arguments: [
'file://project/foo.ts', // URI
{ line: 1, character: 1 }, // Position
[ // A list of Location objects.
{
uri: 'file://project/bar.ts',
range: {
start: {
line: 7,
character: 24,
},
end: {
line: 7,
character: 28,
},
},
},
],
],
}
textDocument/inlayHint
)For the request to return any results, some or all of the following options need to be enabled through preferences
:
export interface InlayHintsOptions extends UserPreferences {
includeInlayParameterNameHints: 'none' | 'literals' | 'all';
includeInlayParameterNameHintsWhenArgumentMatchesName: boolean;
includeInlayFunctionParameterTypeHints: boolean;
includeInlayVariableTypeHints: boolean;
includeInlayVariableTypeHintsWhenTypeMatchesName: boolean;
includeInlayPropertyDeclarationTypeHints: boolean;
includeInlayFunctionLikeReturnTypeHints: boolean;
includeInlayEnumMemberValueHints: boolean;
}
Right after initializing, the server sends a custom $/typescriptVersion
notification that carries information about the version of TypeScript that is utilized by the server. The editor can then display that information in the UI.
The $/typescriptVersion
notification params include two properties:
version
- a semantic version (for example 4.8.4
)source
- a string specifying whether used TypeScript version comes from the local workspace (workspace
), is explicitly specified through a initializationOptions.tsserver.path
setting (user-setting
) or was bundled with the server (bundled
)yarn build
Build and rebuild on change.
yarn dev
yarn test
- run all tests in watch mode for developingyarn test:commit
- run all tests onceBy default only console logs of level warning
and higher are printed to the console. You can override the CONSOLE_LOG_LEVEL
level in package.json
to either log
, info
, warning
or error
to log other levels.
The project uses https://github.com/google-github-actions/release-please-action Github action to automatically release new version on merging a release PR.
FAQs
Language Server Protocol (LSP) implementation for TypeScript using tsserver
The npm package typescript-language-server receives a total of 407,233 weekly downloads. As such, typescript-language-server popularity was classified as popular.
We found that typescript-language-server demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
Security News
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.