Code Monkey home page Code Monkey logo

typescript-language-server's Introduction

Discord npm version npm downloads

TypeScript Language Server

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.

Installing

npm install -g typescript-language-server typescript

Running the language server

typescript-language-server --stdio

CLI Options

  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

Configuration

See configuration documentation.

Features

Code actions on save

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 interface
  • source.removeUnused.ts - removes declared but unused variables
  • source.addMissingImports.ts - adds imports for used but not imported symbols
  • source.removeUnusedImports.ts - removes unused imports
  • source.sortImports.ts - sorts imports
  • source.organizeImports.ts - organizes and removes unused imports

This 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 commands (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.

Go to Source Definition

  • Request:
    {
        command: `_typescript.goToSourceDefinition`
        arguments: [
            lsp.DocumentUri,  // String URI of the document
            lsp.Position,     // Line and character position (zero-based)
        ]
    }
  • Response:
    lsp.Location[] | null

(This command is supported from Typescript 4.7.)

Apply Workspace Edits

  • Request:
    {
        command: `_typescript.applyWorkspaceEdit`
        arguments: [lsp.WorkspaceEdit]
    }
  • Response:
    lsp.ApplyWorkspaceEditResult

Apply Code Action

  • Request:
    {
        command: `_typescript.applyCodeAction`
        arguments: [
            tsp.CodeAction,  // TypeScript Code Action object
        ]
    }
  • Response:
    void

Apply Refactoring

  • Request:
    {
        command: `_typescript.applyRefactoring`
        arguments: [
            tsp.GetEditsForRefactorRequestArgs,
        ]
    }
  • Response:
    void

Organize Imports

  • Request:
    {
        command: `_typescript.organizeImports`
        arguments: [
            // The "skipDestructiveCodeActions" argument is supported from Typescript 4.4+
            [string] | [string, { skipDestructiveCodeActions?: boolean }],
        ]
    }
  • Response:
    void

Rename File

  • Request:
    {
        command: `_typescript.applyRenameFile`
        arguments: [
            { sourceUri: string; targetUri: string; },
        ]
    }
  • Response:
    void

Configure plugin

  • Request:
    {
        command: `_typescript.configurePlugin`
        arguments: [pluginName: string, configuration: any]
    }
  • Response:
    void

Code Lenses (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,
                    },
                },
            },
        ],
    ],
}

Inlay hints (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;
}

TypeScript Version Notification

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)

Development

Build

yarn build

Dev

Build and rebuild on change.

yarn dev

Test

  • yarn test - run all tests in watch mode for developing
  • yarn test:commit - run all tests once

By 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.

Publishing

The project uses https://github.com/google-github-actions/release-please-action Github action to automatically release new version on merging a release PR.

typescript-language-server's People

Contributors

akosyakov avatar alextugarev avatar apexskier avatar cgnonofr avatar dependabot[bot] avatar djziegler avatar donniewest avatar entropitor avatar gins3000 avatar github-actions[bot] avatar jadestrong avatar keyboarddrummer avatar kristijanhusak avatar luckasranarison avatar lukehaas avatar mattlyons0 avatar mskelton avatar prabirshrestha avatar predragnikolic avatar pyvesb avatar rchl avatar rcjsuen avatar renovate[bot] avatar simark avatar stephank avatar svenefftinge avatar tapayne88 avatar tbo avatar yioneko avatar zewa666 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typescript-language-server's Issues

Get TypeScript version which consumes tsserver

As is exists 3 strategies to retrieve tsserver (workspace, global, used by typescript-language-server) It should be very nice if client (ex: Eclipse IDE) could display in a status bar (or other thing) the TypeScript version used to execute tsserver.

Perhaps a notification message like this:

NotificationMessage
{
  "jsonrpc": "2.0",
  "method": "window/showMessage",
  "params": {
    "type": 4,
    "message": "TypeScript 2.5"
  }
}

or with other kind of message?

"format" request to tsserver does not seem to respect options

Observed in version 1.11
Observed with tsserver both from typescript version 2.7.2 (specified in package.json) and current 2.8.x

In our project, we want the user to somehow configure their formatting preferences (e.g. tabs or spaces and their size), but the format request to tsserver seems to ignore the options that get passed in, regardless of if tsfmt is used, or the options coming in from the language server protocol (which we would prefer).

As an example, when putting a tsfmt.json file in the project root as described in [1], I have tracked that this file is properly read and the parsed options passed to tsserver at this point[2], but tsserver seems to ignore all options, in particular the tab and indent sizes. Instead it always goes with 4 spaces.

Is there an issue in the way you pass the options to tsserver or is tsserver at fault?

tsfmt.json file I used:

{
  "tabSize": 2,
  "indentSize": 2,
  "convertTabsToSpaces": true
}

[1] #10
[2] https://github.com/theia-ide/typescript-language-server/blob/92ccb07fec4fc8a4c76c89b061ab8a31f808c7a4/src/lsp-server.ts#L428

How to disable textDocument/publishDiagnostics message from tsserver?

Hi

First, thanks for typescript-language-server, it's awesome!!!
I can use it with Emacs for JavaScript auto-complete.

But typescript-language-server will send "textDocument/publishDiagnostics" message to Emacs that cause Emacs UI freeze seconds.

So how to config typescript-language-server that disable tsserver send "textDocument/publishDiagnostics" message ?

Thanks for help!

Below is lsp log from Emacs:

lsp--send-no-wait: Content-Length: 512

{
  "jsonrpc": "2.0",
  "method": "textDocument/didChange",
  "params": {
    "textDocument": {
      "uri": "file:///Users/andy/tower-ng/app/javascript/controllers/mission_controller.js",
      "version": 121
    },
    "contentChanges": [
      {
        "range": {
          "start": {
            "line": 19,
            "character": 1
          },
          "end": {
            "line": 19,
            "character": 12
          }
        },
        "rangeLength": 11,
        "text": ""
      }
    ]
  }
}
Output from language server: {
  "jsonrpc": "2.0",
  "method": "textDocument/publishDiagnostics",
  "params": {
    "uri": "file:///Users/andy/tower-ng/app/javascript/controllers/mission_controller.js",
    "diagnostics": [
      {
        "range": {
          "start": {
            "line": 247,
            "character": 34
          },
          "end": {
            "line": 247,
            "character": 40
          }
        },
        "message": "'result' is declared but its value is never read.",
        "severity": 4,
        "code": 6133,
        "source": "typescript"
      },
      {
        "range": {
          "start": {
            "line": 287,
            "character": 18
          },
          "end": {
            "line": 287,
            "character": 23
          }
        },
        "message": "'event' is declared but its value is never read.",
        "severity": 4,
        "code": 6133,
        "source": "typescript"
      },
      {
        "range": {
          "start": {
            "line": 297,
            "character": 23
          },
          "end": {
            "line": 297,
            "character": 29
          }
        },
        "message": "'result' is declared but its value is never read.",
        "severity": 4,
        "code": 6133,
        "source": "typescript"
      },
      {
        "range": {
          "start": {
            "line": 374,
            "character": 34
          },
          "end": {
            "line": 374,
            "character": 40
          }
        },
        "message": "'result' is declared but its value is never read.",
        "severity": 4,
        "code": 6133,
        "source": "typescript"
      },
      {
        "range": {
          "start": {
            "line": 479,
            "character": 34
          },
          "end": {
            "line": 479,
            "character": 40
          }
        },
        "message": "'result' is declared but its value is never read.",
        "severity": 4,
        "code": 6133,
        "source": "typescript"
      }
    ]
  }
}

Wrote /Users/andy/tower-ng/app/javascript/controllers/mission_controller.js
lsp--send-no-wait: Content-Length: 237

{
  "jsonrpc": "2.0",
  "method": "textDocument/didSave",
  "params": {
    "textDocument": {
      "uri": "file:///Users/andy/tower-ng/app/javascript/controllers/mission_controller.js",
      "version": 121
    },
    "text": null
  }
}

Add a shrinkwrap.json to prevent code injection when installing from npm

For npm packages that are intended to be used as command line tools, a shrinkwrap.json should be added to the package to prevent malicious code entering the package installation through dependencies. Using strict version numbers in specifying the dependencies in package.json is not enough, because that does not specify the entire dependency tree. A malicious or hacked NPM author of a dependency's dependency can update a new version of that package, and through that inject malicious code.

See the documentation: The recommended use-case for npm-shrinkwrap.json is applications deployed through the publishing process on the registry: for example, daemons and command-line tools intended as global installs or devDependencies.

Support LSP's workspaceFolders

Add support for LSP's workspaceFolders feature.

The TypeFox LSP server together with a tsserver instance consume around 150MB of memory without even loading a project. An IDE user will generally have multiple TypeScript projects open, simply because even navigating to a dependency in node_modules already means navigating to a different TypeScript project. LSP's workspaceFolders feature allows re-using a single LSP server for multiple TypeScript projects, which would greatly reduce memory consumption.

Note that one problem with supporting workspaceFolders is that currently we try to start the tsserver that is located inside the node_modules of the opened project, see the code. With multiple projects, it becomes unclear which tsserver to start. In this scenario, I think the default should be to use the globally installed tsserver, and otherwise one that is bundled with this LSP server.

Customize formatting

tsserver gives the capability to customize formatting. It should be cool if typescript-lsp could provide this same feature. The formatting can be customized by client (eclispe preferences, editorconfig, etc).

reload projects

We should reload projects if tsconfig/jsconfig are changed or installed typescript version in projects's node_modules. Maybe also have a command to let a user to reload manually, i.e. if typescript is installed globally.

Error: geterr timeout

Unfortunately, I do not know how to reproduce. I got this in my Theia backend console:

root ERROR TypeScript: (node:61133) UnhandledPromiseRejectionWarning: Error: geterr timeout
    at Timeout.Deferred.timer.setTimeout (/Users/akos.kitta/git/theia/node_modules/typescript-language-server/lib/utils.js:24:25)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)

root ERROR TypeScript: (node:61133) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:61133) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:61133) UnhandledPromiseRejectionWarning: Error: geterr timeout
    at Timeout.Deferred.timer.setTimeout (/Users/akos.kitta/git/theia/node_modules/typescript-language-server/lib/utils.js:24:25)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)

root ERROR TypeScript: (node:61133) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:61133) UnhandledPromiseRejectionWarning: Error: geterr timeout
    at Timeout.Deferred.timer.setTimeout (/Users/akos.kitta/git/theia/node_modules/typescript-language-server/lib/utils.js:24:25)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)
(node:61133) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)

Please do not depend on exact typescript version

Currently, the typescript dependency is at a fixed version: https://github.com/theia-ide/typescript-language-server/blob/f9be84ff8deeae06169c8a69df4de0de307e9ba9/package.json#L35

This is bad for a few reasons:

  • it duplicates typescript on disk, which has a whooping X MB on disk (which is a WTF on its own)
  • you wonโ€™t get newer strict warnings in your IDE when you upgrade the typescript version inside your project.
  • it is obviously a maintenance burden, since you would have to bump and release on every upstream typescript release.

autocomplete broken in tsserver 2.6

Here is the log from vim-lsp.

11/5/2017 10:19:33 AM:["<---",1,"typescript-language-server",{"response":{"id":9,"jsonrpc":"2.0","error":{"code":-32603,"message":"Request textDocument/completion failed with message: Error processing request. Cannot read property 'kind' of undefined\nTypeError: Cannot read property 'kind' of undefined\n    at Object.isClassElement (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:9931:25)\n    at isFromClassElementDeclaration (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:65915:27)\n    at tryGetClassLikeCompletionContainer (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:65943:33)\n    at tryGetGlobalSymbols (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:65560:42)\n    at getCompletionData (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:65478:22)\n    at Object.getCompletionsAtPosition (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:65060:34)\n    at Object.getCompletionsAtPosition (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:79777:35)\n    at IOSession.Session.getCompletions (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:86199:64)\n    at Session.handlers.ts.createMapFromTemplate._a.(anonymous function) (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:85311:61)\n    at d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:86669:88\n    at IOSession.Session.executeWithRequestId (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:86660:28)\n    at IOSession.Session.executeCommand (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:86669:33)\n    at IOSession.Session.onMessage (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:86689:35)\n    at Interface.<anonymous> (d:\\tmp\\node_modules\\typescript\\lib\\tsserver.js:87881:27)\n    at emitOne (events.js:115:13)\n    at Interface.emit (events.js:210:7)\n    at Interface._onLine (readline.js:282:10)\n    at Interface._normalWrite (readline.js:424:12)\n    at Socket.ondata (readline.js:141:10)\n    at emitOne (events.js:115:13)\n    at Socket.emit (events.js:210:7)\n    at addChunk (_stream_readable.js:264:12)\n    at readableAddChunk (_stream_readable.js:251:11)\n    at Socket.Readable.push (_stream_readable.js:209:10)\n    at Pipe.onread (net.js:587:20)"}},"request":{"method":"textDocument/completion","jsonrpc":"2.0","id":9,"params":{"textDocument":{"uri":"file:///D:/tmp/file.ts"},"position":{"character":17,"line":122}}}}]

Here is the formatted stack trace.

Request textDocument/completion failed with message: Error processing request. Cannot read property 'kind' of undefined
TypeError: Cannot read property 'kind' of undefined
    at Object.isClassElement (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:9931:25)
    at isFromClassElementDeclaration (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:65915:27)
    at tryGetClassLikeCompletionContainer (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:65943:33)
    at tryGetGlobalSymbols (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:65560:42)
    at getCompletionData (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:65478:22)
    at Object.getCompletionsAtPosition (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:65060:34)
    at Object.getCompletionsAtPosition (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:79777:35)
    at IOSession.Session.getCompletions (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:86199:64)
    at Session.handlers.ts.createMapFromTemplate._a.(anonymous function) (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:85311:61)
    at d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:86669:88
    at IOSession.Session.executeWithRequestId (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:86660:28)
    at IOSession.Session.executeCommand (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:86669:33)
    at IOSession.Session.onMessage (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:86689:35)
    at Interface.<anonymous> (d:\\tmp\node_modules\\typescript\\lib\\tsserver.js:87881:27)
    at emitOne (events.js:115:13)
    at Interface.emit (events.js:210:7)
    at Interface._onLine (readline.js:282:10)
    at Interface._normalWrite (readline.js:424:12)
    at Socket.ondata (readline.js:141:10)
    at emitOne (events.js:115:13)
    at Socket.emit (events.js:210:7)
    at addChunk (_stream_readable.js:264:12)
    at readableAddChunk (_stream_readable.js:251:11)
    at Socket.Readable.push (_stream_readable.js:209:10)
    at Pipe.onread (net.js:587:20)"}}

I have been unblocking myself by using ts 2.5.3

Seems like even others are having issues: mhartington/nvim-typescript#89

testing against latest TS

We run tests only against the typescript declared in packages.jon. It does not guarantee that it is going to work against other versions.

We should run tests against at least against the latest but for the backward compatibility probably against previous versions as well.

False positive items in completion list.

I am using Monaco editor with this language server. And I am seeing false positives on the completion list.

The code snippet I use looks like:

class Order {
    constructor(store, amount) {
        this.store = store;
        this.amount = amount;
    }
    print() {
        console.log(this.store);
    }
}

var order = new Order("Office Max", 20);
order.print();
console.

At the bottom of the snippet, I try to trigger the completion list by entering console., the list pops up, I scroll down the list, then I see a screenshot like this:

screen shot 2018-09-24 at 6 57 45 am

As you can see, the gray items at the bottom of the list don't belong to console object, yet they appear in the list, which is not correct.

Ideas?

Thanks!

lang server not preserving casing for drive in windows

I'm opening a file with file:///D:/project/app.ts, but the diagnostics response I'm getting is file:///d:/project/app.ts. Notice the casing the drive letter d. Since I'm using hash map which is case sensitive I'm not able to extract the document diagnostics when the user wants to see the list of diagnostics using :LspDocumentDiagnostics.

Would it be possible to preserve the drive letter casing? I could have a fallback logic in vim-lsp, but seems more like a bug here.

Can't use language server with Node IPC

Version: 0.1.5

> npm install -g typescript-language-server
C:\Users\X\AppData\Roaming\npm\typescript-language-server -> C:\Users\X\AppData\Roaming\npm\node_modules\typescript-language-server\lib\cli.js
C:\Users\X\AppData\Roaming\npm
`-- [email protected]
  +-- [email protected]
  +-- [email protected]
  +-- [email protected]
  +-- [email protected]
  | `-- [email protected]
  |   +-- [email protected]
  |   `-- [email protected]
  `-- [email protected]

> typescript-language-server --node-ipc
Connection type required (stdio, node-ipc, socket). Refer to --help for more details.

allow to set null logger

It would be good if we can use null logger.

In vim json_encode() and json_decode() happens in the UI thread unlike in VS where it runs in worker thread which slows down vim quite a lot.

Also shouldn't the ConsoleLogger only use stderr?

Error: No Project. When starting LS from a bundled electron Theia application

I am not sure whether this issue belongs here or Theia.

When I open a Theia workspace with installed typescript npm dependency I get the following error. Few more things to note:

Terminal from Theia:

prprpr:theia akos.kitta$ pwd
/Users/akos.kitta/Desktop/theia
prprpr:theia akos.kitta$ which tsserver
prprpr:theia akos.kitta$ ./node_modules/.bin/tsserver --version
Content-Length: 76

{"seq":0,"type":"event","event":"typingsInstallerPid","body":{"pid":29149}}
^C
prprpr:theia akos.kitta$ tsserver --version
bash: tsserver: command not found
prprpr:theia akos.kitta$

Error:

root ERROR Error from definitions request: file:///Users/akos.kitta/Desktop/theia/packages/core/src/common/os.ts#32/16 Error: Request textDocument/definition failed with message: Error processing request. No Project.
Error: No Project.
    at Object.ThrowNoProject (/Users/akos.kitta/Desktop/theia/node_modules/typescript/lib/tsserver.js:92289:23)
    at ProjectService.getDefaultProjectForFile (/Users/akos.kitta/Desktop/theia/node_modules/typescript/lib/tsserver.js:94518:46)
    at IOSession.Session.getFileAndProjectWorker (/Users/akos.kitta/Desktop/theia/node_modules/typescript/lib/tsserver.js:96934:87)
    at IOSession.Session.getFileAndProject (/Users/akos.kitta/Desktop/theia/node_modules/typescript/lib/tsserver.js:96919:29)
    at IOSession.Session.getDefinition (/Users/akos.kitta/Desktop/theia/node_modules/typescript/lib/tsserver.js:96572:31)
    at Session.handlers.ts.createMapFromTemplate._a.(anonymous function) (/Users/akos.kitta/Desktop/theia/node_modules/typescript/lib/tsserver.js:96044:61)
    at /Users/akos.kitta/Desktop/theia/node_modules/typescript/lib/tsserver.js:97580:88
    at IOSession.Session.executeWithRequestId (/Users/akos.kitta/Desktop/theia/node_modules/typescript/lib/tsserver.js:97571:28)
    at IOSession.Session.executeCommand (/Users/akos.kitta/Desktop/theia/node_modules/typescript/lib/tsserver.js:97580:33)
    at IOSession.Session.onMessage (/Users/akos.kitta/Desktop/theia/node_modules/typescript/lib/tsserver.js:97600:35)
    at Interface.<anonymous> (/Users/akos.kitta/Desktop/theia/node_modules/typescript/lib/tsserver.js:98831:27)
    at emitOne (events.js:116:13)
    at Interface.emit (events.js:211:7)
    at Interface._onLine (readline.js:280:10)
    at Interface._normalWrite (readline.js:422:12)
    at Socket.ondata (readline.js:139:10)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at Socket.Readable.push (_stream_readable.js:208:10)
    at Pipe.onread (net.js:597:20)
    at new ResponseError (file:///Users/akos.kitta/Desktop/theia-apps/theia-electron/dist/mac/Theia.app/Contents/Resources/app/lib/bundle.js:95354:28)
    at handleResponse (file:///Users/akos.kitta/Desktop/theia-apps/theia-electron/dist/mac/Theia.app/Contents/Resources/app/lib/bundle.js:94338:48)
    at processMessageQueue (file:///Users/akos.kitta/Desktop/theia-apps/theia-electron/dist/mac/Theia.app/Contents/Resources/app/lib/bundle.js:94166:17)
    at Immediate._onImmediate (file:///Users/akos.kitta/Desktop/theia-apps/theia-electron/dist/mac/Theia.app/Contents/Resources/app/lib/bundle.js:94150:13)
    at runCallback (timers.js:781:20)
    at tryOnImmediate (timers.js:743:5)
    at processImmediate [as _immediateCallback] (timers.js:714:5)

[windows] It does not work on Windows with Theia

This is from the backend log:

root ERROR TypeScript: (node:10160) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Err
or: geterr timeout

root ERROR TypeScript: (node:10160) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the fu
ture, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:10160) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: geterr timeout
(node:10160) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): Error: geterr timeout
(node:10160) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): Error: geterr timeout
(node:10160) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 5): Error: geterr timeout
(node:10160) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 6): Error: geterr timeout

root ERROR TypeScript: (node:10160) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 7): Err
or: geterr timeout

root ERROR TypeScript: (node:10160) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 8): Err
or: geterr timeout

root ERROR TypeScript: (node:10160) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 9): Err
or: geterr timeout

Support for typescript.tsdk with tsserverPath

Like I had written at prabirshrestha/typescript-language-server#6

IMHO I think there are 2 problems with the tsserverPath:

  • By default tsserver.bat / tsserver is searched in the %PATH (when you install TypeScript in global npm registry). In my case I had a very old installed TypeScript and I was not able to consume navtree. I think tsserver.bat / tsserver should be searched at first time with require.resolve like this:
try {
    var tsserverPath = require.resolve(".bin/" + (utils.isWindows() ? 'tsserver.cmd' : 'tsserver'));
    this.options.tsserverPath = tsserverPath;        	
}
catch(error) {}

 this.tsServerClient = new tsServerClient_1.TsServerClient({
            tsserverPath: this.options.tsserverPath || (utils.isWindows() ? 'tsserver.cmd' : 'tsserver'),
            logFile: this.options.tsserverLogFile,
            logger: this.logger
        });

It will be more easy to use it with VSCode.

Allow a client to configure typescript.tsdk (similar to VS Code)

Have you considered using the Session class inside the LSP server process, instead of starting a separate tsserver process?

Pros:

  • Less processes, less communication overhead
  • The LSP server now has access to the internal state of tsserver, so you don't have to store duplicate state in the LSP server, which is done here to store the state of open documents. Note that I believe this is done incorrectly, see this issue.

Cons:

  • Less reliable contract of the dependency, since tsserver's contract is less likely to change than that of Session. This also means that you should always use the Session class that is bundled with the typescript-language-server installation, so you know for sure that it works well. The downside here is that you won't get automatic TypeScript upgrades if the user installs a newer global version of TypeScript. However, I think that behavior was a bit risky to begin with, since the contract of tsserver can also change.

Clear diagnostics when closing file

If a file is closed in the frontend while it has some errors/warnings, these diagnostics are kept. These diagnostics will remain even after they become stale because:

  • The file is modified externally (e.g. git checkout)
  • Another file that this file depends on is modified, fixing the errors/warnings

When the file is closed, if the server is unable to provide diagnostics for closed files, it should send an empty publishDiagnostics to clear those diagnostics.

Support detail & insertText for completionItem/resolve

Take a simple usecase:

let a = "";
a. // open completion

When tsserver is used directly (in typescript.java), I can display information with signature:

image

Here the JSON response:

{
	"seq": 0,
	"type": "response",
	"command": "completionEntryDetails",
	"request_seq": 47,
	"success": true,
	"body": [
		{
			"name": "charAt",
			"kindModifiers": "declare",
			"kind": "method",
			"displayParts": [
				{
					"text": "(",
					"kind": "punctuation"
				},
				{
					"text": "method",
					"kind": "text"
				},
				{
					"text": ")",
					"kind": "punctuation"
				},
				{
					"text": " ",
					"kind": "space"
				},
				{
					"text": "String",
					"kind": "localName"
				},
				{
					"text": ".",
					"kind": "punctuation"
				},
				{
					"text": "charAt",
					"kind": "methodName"
				},
				{
					"text": "(",
					"kind": "punctuation"
				},
				{
					"text": "pos",
					"kind": "parameterName"
				},
				{
					"text": ":",
					"kind": "punctuation"
				},
				{
					"text": " ",
					"kind": "space"
				},
				{
					"text": "number",
					"kind": "keyword"
				},
				{
					"text": ")",
					"kind": "punctuation"
				},
				{
					"text": ":",
					"kind": "punctuation"
				},
				{
					"text": " ",
					"kind": "space"
				},
				{
					"text": "string",
					"kind": "keyword"
				}
			],
			"documentation": [
				{
					"text": "Returns the character at the specified index.",
					"kind": "text"
				}
			],
			"tags": []
		}
	]
}

When I use lsp typescript-language-server, I have not this signature information:

image

Here the JSON response:

{
  "jsonrpc": "2.0",
  "id": "20",
  "result": {
    "label": "charAt",
    "kind": 2,
    "documentation": "Returns the character at the specified index.",
    "data": {
      "file": "c:\\Users\\azerr\\WS2\\test-tslint\\a.ts",
      "line": 2.0,
      "offset": 3.0
    }
  }
}

https://github.com/sourcegraph/javascript-typescript-langserver which supports that returns the LSP JSON response:

{
  "jsonrpc": "2.0",
  "id": "31",
  "result": {
    "label": "charAt",
    "kind": 2,
    "detail": "(method) String.charAt(pos: number): string",
    "documentation": "Returns the character at the specified index.",
    "sortText": "0",
    "insertText": "charAt(${1:pos})",
    "insertTextFormat": 2
  }
}

It provides 2 cool features:

  • display signature with detail
  • support snippet

Here a demo:

lspcompletionsnippetdemo

It should be cool if typescript-language-serve could support:

  • display signature with detail
  • support snippet with insertText (perhaps provide a settings to disable it)

cli options broken

The follwing cli options don't seem to work for me:

--log-level
--tsserver-logFile 
--tsserver-path

I had a look at src/cli.js and I cannot see how this could have ever worked. My findings:

  • log-level is interpreted as boolean flag, because it has no parameter assigned
  • Typo at line at line 29: program['leg-level']
  • The description for --tsserver-logFile is spelled differently: --tsServerLogFile=ts-logs.txt (both don't work)

I tried to build a PR for this, but encountered additional problems. Even if I hard-code my configuration in cli.js and pass it directly to createLspConnection, no logs a being created. I think, that the server options aren't properly set in the constructor of LspServer. Some methods are using this.options, but I cannot find where it is being set.

This part still works in @prabirshrestha's repo.

The contents of documents in `this.openedDocumentUris` are never updated

On didChange requests, it seems like you don't update the contents of the document you store in memory, see the code.

Since you are using the document contents in several places, this seems like it would lead to bugs.

This is somewhat confirmed because I'm seeing faulty behavior when sending non-incremental didChange requests, which trigger calls to the contents of the stored document, here.

Support for completion auto import

Since today with npm install typescript@next you can support completion with auto import that I'm implementing inside typescript.java

autoimportdemo

It should be fantastic if typescript-language-server could support it. Here tsserver traces:

TypeScript request#completionEntryDetails:

{
	"command": "completionEntryDetails",
	"arguments": {
		"entryNames": [
			"PI"
		],
		"line": 1,
		"offset": 3,
		"file": "C:/Users/azerr/WS2/___aa/b.ts"
	},
	"seq": 9,
	"type": "request"
}

TypeScript response#completionEntryDetails with 61ms:

{
	"seq": 0,
	"type": "response",
	"command": "completionEntryDetails",
	"request_seq": 9,
	"success": true,
	"body": [
		{
			"name": "PI",
			"kindModifiers": "export",
			"kind": "const",
			"displayParts": [
				{
					"text": "const",
					"kind": "keyword"
				},
				{
					"text": " ",
					"kind": "space"
				},
				{
					"text": "PI",
					"kind": "localName"
				},
				{
					"text": ":",
					"kind": "punctuation"
				},
				{
					"text": " ",
					"kind": "space"
				},
				{
					"text": "3.14",
					"kind": "stringLiteral"
				}
			],
			"documentation": [],
			"tags": [],
			"codeActions": [
				{
					"description": "Import 'PI' from \"./a\".",
					"changes": [
						{
							"fileName": "C:/Users/azerr/WS2/___aa/b.ts",
							"textChanges": [
								{
									"start": {
										"line": 1,
										"offset": 1
									},
									"end": {
										"line": 1,
										"offset": 1
									},
									"newText": "import { PI } from \"./a\";\r\n\r\n"
								}
							]
						}
					]
				}
			]
		}
	]
}

Consider replacing timeout logic with appropriate request cancellation

I'm getting following errors:

[Error - 00:15:15] Request textDocument/foldingRange failed.
Message: Request textDocument/foldingRange failed with message: getOutliningSpans timeout
Code: -32603
[Error - 00:15:16] Request textDocument/foldingRange failed.
Message: Request textDocument/foldingRange failed with message: getOutliningSpans timeout
Code: -32603

Usage with Sublime LSP

I managed to get this working with plain javascript in Sublime using the tomv564/LSP plugin.

demo with plain JS

Here are the settings:

{
  "jsts": {
    "command": ["typescript-language-server", "--stdio"],
    "enabled": true,
    "languageId": "javascript",
    "scopes": ["source.js"],
    "syntaxes": ["Packages/JavaScript/JavaScript.sublime-syntax"]
  }
}

This works with plain JavaScript with no tsconfig file. It will also parse the @types in your node_modules.

Basically, this means you can get a much better experience in Sublime with javascript using this language server and the LSP plugin.

For general TypeScript usage, the Sublime TypeScript plugin seems to do a fine job. But for plain javascript project (not written in .ts files) this is excellent.

I wasn't sure where to put this as it isn't an issue. Just that I found this project while trying to get things working in Sublime. Sorry to spam your issue list.

VS Code Language Client

So I'm interested in using this language server for VS Code extensions development (which seems to be one of the natural use-cases) but try as I might I can't seem to get this server to run with VS Code's language client. I can't find any examples of others doing it either. I was hoping you could either point me to one or give me some pointers or something of that sort

0.1.10 postinstall script failing

147 silly postinstall [email protected]
148 info lifecycle [email protected]~postinstall: [email protected]
149 silly postinstall [email protected]
150 info lifecycle [email protected]~postinstall: [email protected]
151 verbose lifecycle [email protected]~postinstall: unsafe-perm in lifecycle true
152 verbose lifecycle [email protected]~postinstall: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/dsifford/.local/share/npm/lib/node_modules/typescript-language-server/node_modules/.bin:/home/dsifford/.local/share/npm/lib/node_modules/.bin:/home/dsifford/.local/share/npm/lib/node_modules/node_modules/.bin:/home/dsifford/.local/share/npm/lib/node_modules/.bin:/home/dsifford/.local/share/npm/node_modules/.bin:/home/dsifford/.local/share/node_modules/.bin:/home/dsifford/.local/node_modules/.bin:/home/dsifford/node_modules/.bin:/home/node_modules/.bin:/node_modules/.bin:/usr/bin:/home/dsifford/.local/bin:/home/dsifford/.local/share/npm/bin:/home/dsifford/gocode/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/bin:/home/dsifford/.dotfiles/vim/_plugins/fzf/bin
153 verbose lifecycle [email protected]~postinstall: CWD: /home/dsifford/.local/share/npm/lib/node_modules/typescript-language-server
154 silly lifecycle [email protected]~postinstall: Args: [ '-c', 'yarn run build' ]
155 silly lifecycle [email protected]~postinstall: Returned: code: 1  signal: null
156 info lifecycle [email protected]~postinstall: Failed to exec postinstall script
157 verbose unlock done using /home/dsifford/.cache/npm/_locks/staging-4fbf0f0616f3d71e.lock for /home/dsifford/.local/share/npm/lib/node_modules/.staging
158 verbose stack Error: [email protected] postinstall: `yarn run build`
158 verbose stack Exit status 1
158 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:283:16)
158 verbose stack     at EventEmitter.emit (events.js:180:13)
158 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
158 verbose stack     at ChildProcess.emit (events.js:180:13)
158 verbose stack     at maybeClose (internal/child_process.js:936:16)
158 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)
159 verbose pkgid [email protected]
160 verbose cwd /home/dsifford/.local/share/npm/lib/node_modules
161 verbose Linux 4.16.3-1-ARCH
162 verbose argv "/usr/bin/node" "/usr/bin/npm" "install" "--global" "[email protected]" "--color=always"
163 verbose node v9.11.1
164 verbose npm  v5.8.0
165 error code ELIFECYCLE
166 error errno 1
167 error [email protected] postinstall: `yarn run build`
167 error Exit status 1
168 error Failed at the [email protected] postinstall script.
168 error This is probably not a problem with npm. There is likely additional logging output above.
169 verbose exit [ 1, true ]

Possibly related: The postinstall script has a yarn dependency. Is that fragile? Should this instead by an explicit command?

Have a change log for each release

It would be nice to know what changed when a new version is released. I don't mind if you don't create a change log for the current release, as long as they are created for future releases

eslint/tslint support

There's currently no linting on the LS. Would be happy to send a PR for this, let m know.

Hierarchical document symbols in textDocument/documentSymbol is incomplete

It seems in order to support hierarchical outlines (in the Atom-IDE plugin at least) the property containerName is needed which is missing from your responses.

For reference, if you clone mattlyons0/ide-typescript-theia@713eae1 and open the file lib/main.js
The SourceGraph implementation gives following response to textDocument/documentSymbol: https://pastebin.com/cN4jqdn4
While Theia gives: https://pastebin.com/SD6LqFwe

The only difference is that Theia gives no containerName property and that is what is used to display the hierarchy:
Example
The image is truncated, it scrolls further

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.