typescript.rs

  1use anyhow::{anyhow, Result};
  2use async_compression::futures::bufread::GzipDecoder;
  3use async_tar::Archive;
  4use async_trait::async_trait;
  5use collections::HashMap;
  6use gpui::AppContext;
  7use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};
  8use lsp::{CodeActionKind, LanguageServerBinary};
  9use node_runtime::NodeRuntime;
 10use project::project_settings::ProjectSettings;
 11use serde_json::{json, Value};
 12use settings::Settings;
 13use smol::{fs, io::BufReader, stream::StreamExt};
 14use std::{
 15    any::Any,
 16    ffi::OsString,
 17    path::{Path, PathBuf},
 18    sync::Arc,
 19};
 20use util::{
 21    fs::remove_matching,
 22    github::{build_tarball_url, GitHubLspBinaryVersion},
 23    maybe, ResultExt,
 24};
 25
 26fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 27    vec![server_path.into(), "--stdio".into()]
 28}
 29
 30fn eslint_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 31    vec![server_path.into(), "--stdio".into()]
 32}
 33
 34pub struct TypeScriptLspAdapter {
 35    node: Arc<dyn NodeRuntime>,
 36}
 37
 38impl TypeScriptLspAdapter {
 39    const OLD_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.js";
 40    const NEW_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.mjs";
 41
 42    pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
 43        TypeScriptLspAdapter { node }
 44    }
 45}
 46
 47struct TypeScriptVersions {
 48    typescript_version: String,
 49    server_version: String,
 50}
 51
 52#[async_trait(?Send)]
 53impl LspAdapter for TypeScriptLspAdapter {
 54    fn name(&self) -> LanguageServerName {
 55        LanguageServerName("typescript-language-server".into())
 56    }
 57
 58    async fn fetch_latest_server_version(
 59        &self,
 60        _: &dyn LspAdapterDelegate,
 61    ) -> Result<Box<dyn 'static + Send + Any>> {
 62        Ok(Box::new(TypeScriptVersions {
 63            typescript_version: self.node.npm_package_latest_version("typescript").await?,
 64            server_version: self
 65                .node
 66                .npm_package_latest_version("typescript-language-server")
 67                .await?,
 68        }) as Box<_>)
 69    }
 70
 71    async fn fetch_server_binary(
 72        &self,
 73        latest_version: Box<dyn 'static + Send + Any>,
 74        container_dir: PathBuf,
 75        _: &dyn LspAdapterDelegate,
 76    ) -> Result<LanguageServerBinary> {
 77        let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
 78        let server_path = container_dir.join(Self::NEW_SERVER_PATH);
 79        let package_name = "typescript";
 80
 81        let should_install_language_server = self
 82            .node
 83            .should_install_npm_package(
 84                package_name,
 85                &server_path,
 86                &container_dir,
 87                latest_version.typescript_version.as_str(),
 88            )
 89            .await;
 90
 91        if should_install_language_server {
 92            self.node
 93                .npm_install_packages(
 94                    &container_dir,
 95                    &[
 96                        (package_name, latest_version.typescript_version.as_str()),
 97                        (
 98                            "typescript-language-server",
 99                            latest_version.server_version.as_str(),
100                        ),
101                    ],
102                )
103                .await?;
104        }
105
106        Ok(LanguageServerBinary {
107            path: self.node.binary_path().await?,
108            env: None,
109            arguments: typescript_server_binary_arguments(&server_path),
110        })
111    }
112
113    async fn cached_server_binary(
114        &self,
115        container_dir: PathBuf,
116        _: &dyn LspAdapterDelegate,
117    ) -> Option<LanguageServerBinary> {
118        get_cached_ts_server_binary(container_dir, &*self.node).await
119    }
120
121    async fn installation_test_binary(
122        &self,
123        container_dir: PathBuf,
124    ) -> Option<LanguageServerBinary> {
125        get_cached_ts_server_binary(container_dir, &*self.node).await
126    }
127
128    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
129        Some(vec![
130            CodeActionKind::QUICKFIX,
131            CodeActionKind::REFACTOR,
132            CodeActionKind::REFACTOR_EXTRACT,
133            CodeActionKind::SOURCE,
134        ])
135    }
136
137    async fn label_for_completion(
138        &self,
139        item: &lsp::CompletionItem,
140        language: &Arc<language::Language>,
141    ) -> Option<language::CodeLabel> {
142        use lsp::CompletionItemKind as Kind;
143        let len = item.label.len();
144        let grammar = language.grammar()?;
145        let highlight_id = match item.kind? {
146            Kind::CLASS | Kind::INTERFACE => grammar.highlight_id_for_name("type"),
147            Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
148            Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
149            Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
150            Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
151            _ => None,
152        }?;
153
154        let text = match &item.detail {
155            Some(detail) => format!("{} {}", item.label, detail),
156            None => item.label.clone(),
157        };
158
159        Some(language::CodeLabel {
160            text,
161            runs: vec![(0..len, highlight_id)],
162            filter_range: 0..len,
163        })
164    }
165
166    async fn initialization_options(
167        self: Arc<Self>,
168        _: &Arc<dyn LspAdapterDelegate>,
169    ) -> Result<Option<serde_json::Value>> {
170        Ok(Some(json!({
171            "provideFormatter": true,
172            "tsserver": {
173                "path": "node_modules/typescript/lib",
174            },
175            "preferences": {
176                "includeInlayParameterNameHints": "all",
177                "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
178                "includeInlayFunctionParameterTypeHints": true,
179                "includeInlayVariableTypeHints": true,
180                "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
181                "includeInlayPropertyDeclarationTypeHints": true,
182                "includeInlayFunctionLikeReturnTypeHints": true,
183                "includeInlayEnumMemberValueHints": true,
184            }
185        })))
186    }
187
188    fn language_ids(&self) -> HashMap<String, String> {
189        HashMap::from_iter([
190            ("TypeScript".into(), "typescript".into()),
191            ("JavaScript".into(), "javascript".into()),
192            ("TSX".into(), "typescriptreact".into()),
193        ])
194    }
195}
196
197async fn get_cached_ts_server_binary(
198    container_dir: PathBuf,
199    node: &dyn NodeRuntime,
200) -> Option<LanguageServerBinary> {
201    maybe!(async {
202        let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
203        let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
204        if new_server_path.exists() {
205            Ok(LanguageServerBinary {
206                path: node.binary_path().await?,
207                env: None,
208                arguments: typescript_server_binary_arguments(&new_server_path),
209            })
210        } else if old_server_path.exists() {
211            Ok(LanguageServerBinary {
212                path: node.binary_path().await?,
213                env: None,
214                arguments: typescript_server_binary_arguments(&old_server_path),
215            })
216        } else {
217            Err(anyhow!(
218                "missing executable in directory {:?}",
219                container_dir
220            ))
221        }
222    })
223    .await
224    .log_err()
225}
226
227pub struct EsLintLspAdapter {
228    node: Arc<dyn NodeRuntime>,
229}
230
231impl EsLintLspAdapter {
232    const CURRENT_VERSION: &'static str = "release/2.4.4";
233
234    const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
235    const SERVER_NAME: &'static str = "eslint";
236
237    const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] =
238        &["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs"];
239
240    pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
241        EsLintLspAdapter { node }
242    }
243}
244
245#[async_trait(?Send)]
246impl LspAdapter for EsLintLspAdapter {
247    fn workspace_configuration(&self, workspace_root: &Path, cx: &mut AppContext) -> Value {
248        let eslint_user_settings = ProjectSettings::get_global(cx)
249            .lsp
250            .get(Self::SERVER_NAME)
251            .and_then(|s| s.settings.clone())
252            .unwrap_or_default();
253
254        let mut code_action_on_save = json!({
255            // We enable this, but without also configuring `code_actions_on_format`
256            // in the Zed configuration, it doesn't have an effect.
257            "enable": true,
258        });
259
260        if let Some(code_action_settings) = eslint_user_settings
261            .get("codeActionOnSave")
262            .and_then(|settings| settings.as_object())
263        {
264            if let Some(enable) = code_action_settings.get("enable") {
265                code_action_on_save["enable"] = enable.clone();
266            }
267            if let Some(mode) = code_action_settings.get("mode") {
268                code_action_on_save["mode"] = mode.clone();
269            }
270            if let Some(rules) = code_action_settings.get("rules") {
271                code_action_on_save["rules"] = rules.clone();
272            }
273        }
274
275        let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
276        let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
277            .iter()
278            .any(|file| workspace_root.join(file).is_file());
279
280        json!({
281            "": {
282                "validate": "on",
283                "rulesCustomizations": [],
284                "run": "onType",
285                "nodePath": node_path,
286                "workingDirectory": {"mode": "auto"},
287                "workspaceFolder": {
288                    "uri": workspace_root,
289                    "name": workspace_root.file_name()
290                        .unwrap_or_else(|| workspace_root.as_os_str()),
291                },
292                "problems": {},
293                "codeActionOnSave": code_action_on_save,
294                "experimental": {
295                    "useFlatConfig": use_flat_config,
296                },
297            }
298        })
299    }
300
301    fn name(&self) -> LanguageServerName {
302        LanguageServerName(Self::SERVER_NAME.into())
303    }
304
305    async fn fetch_latest_server_version(
306        &self,
307        _delegate: &dyn LspAdapterDelegate,
308    ) -> Result<Box<dyn 'static + Send + Any>> {
309        let url = build_tarball_url("microsoft/vscode-eslint", Self::CURRENT_VERSION)?;
310
311        Ok(Box::new(GitHubLspBinaryVersion {
312            name: Self::CURRENT_VERSION.into(),
313            url,
314        }))
315    }
316
317    async fn fetch_server_binary(
318        &self,
319        version: Box<dyn 'static + Send + Any>,
320        container_dir: PathBuf,
321        delegate: &dyn LspAdapterDelegate,
322    ) -> Result<LanguageServerBinary> {
323        let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
324        let destination_path = container_dir.join(format!("vscode-eslint-{}", version.name));
325        let server_path = destination_path.join(Self::SERVER_PATH);
326
327        if fs::metadata(&server_path).await.is_err() {
328            remove_matching(&container_dir, |entry| entry != destination_path).await;
329
330            let mut response = delegate
331                .http_client()
332                .get(&version.url, Default::default(), true)
333                .await
334                .map_err(|err| anyhow!("error downloading release: {}", err))?;
335            let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
336            let archive = Archive::new(decompressed_bytes);
337            archive.unpack(&destination_path).await?;
338
339            let mut dir = fs::read_dir(&destination_path).await?;
340            let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
341            let repo_root = destination_path.join("vscode-eslint");
342            fs::rename(first.path(), &repo_root).await?;
343
344            self.node
345                .run_npm_subcommand(Some(&repo_root), "install", &[])
346                .await?;
347
348            self.node
349                .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
350                .await?;
351        }
352
353        Ok(LanguageServerBinary {
354            path: self.node.binary_path().await?,
355            env: None,
356            arguments: eslint_server_binary_arguments(&server_path),
357        })
358    }
359
360    async fn cached_server_binary(
361        &self,
362        container_dir: PathBuf,
363        _: &dyn LspAdapterDelegate,
364    ) -> Option<LanguageServerBinary> {
365        get_cached_eslint_server_binary(container_dir, &*self.node).await
366    }
367
368    async fn installation_test_binary(
369        &self,
370        container_dir: PathBuf,
371    ) -> Option<LanguageServerBinary> {
372        get_cached_eslint_server_binary(container_dir, &*self.node).await
373    }
374}
375
376async fn get_cached_eslint_server_binary(
377    container_dir: PathBuf,
378    node: &dyn NodeRuntime,
379) -> Option<LanguageServerBinary> {
380    maybe!(async {
381        // This is unfortunate but we don't know what the version is to build a path directly
382        let mut dir = fs::read_dir(&container_dir).await?;
383        let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
384        if !first.file_type().await?.is_dir() {
385            return Err(anyhow!("First entry is not a directory"));
386        }
387        let server_path = first.path().join(EsLintLspAdapter::SERVER_PATH);
388
389        Ok(LanguageServerBinary {
390            path: node.binary_path().await?,
391            env: None,
392            arguments: eslint_server_binary_arguments(&server_path),
393        })
394    })
395    .await
396    .log_err()
397}
398
399#[cfg(test)]
400mod tests {
401    use gpui::{Context, TestAppContext};
402    use text::BufferId;
403    use unindent::Unindent;
404
405    #[gpui::test]
406    async fn test_outline(cx: &mut TestAppContext) {
407        let language = crate::language("typescript", tree_sitter_typescript::language_typescript());
408
409        let text = r#"
410            function a() {
411              // local variables are omitted
412              let a1 = 1;
413              // all functions are included
414              async function a2() {}
415            }
416            // top-level variables are included
417            let b: C
418            function getB() {}
419            // exported variables are included
420            export const d = e;
421        "#
422        .unindent();
423
424        let buffer = cx.new_model(|cx| {
425            language::Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), text)
426                .with_language(language, cx)
427        });
428        let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
429        assert_eq!(
430            outline
431                .items
432                .iter()
433                .map(|item| (item.text.as_str(), item.depth))
434                .collect::<Vec<_>>(),
435            &[
436                ("function a()", 0),
437                ("async function a2()", 1),
438                ("let b", 0),
439                ("function getB()", 0),
440                ("const d", 0),
441            ]
442        );
443    }
444}