typescript.rs

  1use anyhow::{anyhow, Context as _, Result};
  2use async_compression::futures::bufread::GzipDecoder;
  3use async_tar::Archive;
  4use async_trait::async_trait;
  5use collections::HashMap;
  6use gpui::AsyncAppContext;
  7use http_client::github::{build_asset_url, AssetKind, GitHubLspBinaryVersion};
  8use language::{LanguageToolchainStore, LspAdapter, LspAdapterDelegate};
  9use lsp::{CodeActionKind, LanguageServerBinary, LanguageServerName};
 10use node_runtime::NodeRuntime;
 11use project::lsp_store::language_server_settings;
 12use project::ContextProviderWithTasks;
 13use serde_json::{json, Value};
 14use smol::{fs, io::BufReader, stream::StreamExt};
 15use std::{
 16    any::Any,
 17    ffi::OsString,
 18    path::{Path, PathBuf},
 19    sync::Arc,
 20};
 21use task::{TaskTemplate, TaskTemplates, VariableName};
 22use util::{fs::remove_matching, maybe, ResultExt};
 23
 24pub(super) fn typescript_task_context() -> ContextProviderWithTasks {
 25    ContextProviderWithTasks::new(TaskTemplates(vec![
 26        TaskTemplate {
 27            label: "jest file test".to_owned(),
 28            command: "npx jest".to_owned(),
 29            args: vec![VariableName::File.template_value()],
 30            ..TaskTemplate::default()
 31        },
 32        TaskTemplate {
 33            label: "jest test $ZED_SYMBOL".to_owned(),
 34            command: "npx jest".to_owned(),
 35            args: vec![
 36                "--testNamePattern".into(),
 37                format!("\"{}\"", VariableName::Symbol.template_value()),
 38                VariableName::File.template_value(),
 39            ],
 40            tags: vec!["ts-test".into(), "js-test".into(), "tsx-test".into()],
 41            ..TaskTemplate::default()
 42        },
 43        TaskTemplate {
 44            label: "execute selection $ZED_SELECTED_TEXT".to_owned(),
 45            command: "node".to_owned(),
 46            args: vec![
 47                "-e".into(),
 48                format!("\"{}\"", VariableName::SelectedText.template_value()),
 49            ],
 50            ..TaskTemplate::default()
 51        },
 52    ]))
 53}
 54
 55fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 56    vec![server_path.into(), "--stdio".into()]
 57}
 58
 59fn eslint_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 60    vec![
 61        "--max-old-space-size=8192".into(),
 62        server_path.into(),
 63        "--stdio".into(),
 64    ]
 65}
 66
 67pub struct TypeScriptLspAdapter {
 68    node: NodeRuntime,
 69}
 70
 71impl TypeScriptLspAdapter {
 72    const OLD_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.js";
 73    const NEW_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.mjs";
 74    const SERVER_NAME: LanguageServerName =
 75        LanguageServerName::new_static("typescript-language-server");
 76    const PACKAGE_NAME: &str = "typescript";
 77    pub fn new(node: NodeRuntime) -> Self {
 78        TypeScriptLspAdapter { node }
 79    }
 80    async fn tsdk_path(adapter: &Arc<dyn LspAdapterDelegate>) -> &'static str {
 81        let is_yarn = adapter
 82            .read_text_file(PathBuf::from(".yarn/sdks/typescript/lib/typescript.js"))
 83            .await
 84            .is_ok();
 85
 86        if is_yarn {
 87            ".yarn/sdks/typescript/lib"
 88        } else {
 89            "node_modules/typescript/lib"
 90        }
 91    }
 92}
 93
 94struct TypeScriptVersions {
 95    typescript_version: String,
 96    server_version: String,
 97}
 98
 99#[async_trait(?Send)]
100impl LspAdapter for TypeScriptLspAdapter {
101    fn name(&self) -> LanguageServerName {
102        Self::SERVER_NAME.clone()
103    }
104
105    async fn fetch_latest_server_version(
106        &self,
107        _: &dyn LspAdapterDelegate,
108    ) -> Result<Box<dyn 'static + Send + Any>> {
109        Ok(Box::new(TypeScriptVersions {
110            typescript_version: self.node.npm_package_latest_version("typescript").await?,
111            server_version: self
112                .node
113                .npm_package_latest_version("typescript-language-server")
114                .await?,
115        }) as Box<_>)
116    }
117
118    async fn check_if_version_installed(
119        &self,
120        version: &(dyn 'static + Send + Any),
121        container_dir: &PathBuf,
122        _: &dyn LspAdapterDelegate,
123    ) -> Option<LanguageServerBinary> {
124        let version = version.downcast_ref::<TypeScriptVersions>().unwrap();
125        let server_path = container_dir.join(Self::NEW_SERVER_PATH);
126
127        let should_install_language_server = self
128            .node
129            .should_install_npm_package(
130                Self::PACKAGE_NAME,
131                &server_path,
132                &container_dir,
133                version.typescript_version.as_str(),
134            )
135            .await;
136
137        if should_install_language_server {
138            None
139        } else {
140            Some(LanguageServerBinary {
141                path: self.node.binary_path().await.ok()?,
142                env: None,
143                arguments: typescript_server_binary_arguments(&server_path),
144            })
145        }
146    }
147
148    async fn fetch_server_binary(
149        &self,
150        latest_version: Box<dyn 'static + Send + Any>,
151        container_dir: PathBuf,
152        _: &dyn LspAdapterDelegate,
153    ) -> Result<LanguageServerBinary> {
154        let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
155        let server_path = container_dir.join(Self::NEW_SERVER_PATH);
156
157        self.node
158            .npm_install_packages(
159                &container_dir,
160                &[
161                    (
162                        Self::PACKAGE_NAME,
163                        latest_version.typescript_version.as_str(),
164                    ),
165                    (
166                        "typescript-language-server",
167                        latest_version.server_version.as_str(),
168                    ),
169                ],
170            )
171            .await?;
172
173        Ok(LanguageServerBinary {
174            path: self.node.binary_path().await?,
175            env: None,
176            arguments: typescript_server_binary_arguments(&server_path),
177        })
178    }
179
180    async fn cached_server_binary(
181        &self,
182        container_dir: PathBuf,
183        _: &dyn LspAdapterDelegate,
184    ) -> Option<LanguageServerBinary> {
185        get_cached_ts_server_binary(container_dir, &self.node).await
186    }
187
188    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
189        Some(vec![
190            CodeActionKind::QUICKFIX,
191            CodeActionKind::REFACTOR,
192            CodeActionKind::REFACTOR_EXTRACT,
193            CodeActionKind::SOURCE,
194        ])
195    }
196
197    async fn label_for_completion(
198        &self,
199        item: &lsp::CompletionItem,
200        language: &Arc<language::Language>,
201    ) -> Option<language::CodeLabel> {
202        use lsp::CompletionItemKind as Kind;
203        let len = item.label.len();
204        let grammar = language.grammar()?;
205        let highlight_id = match item.kind? {
206            Kind::CLASS | Kind::INTERFACE | Kind::ENUM => grammar.highlight_id_for_name("type"),
207            Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
208            Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
209            Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
210            Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
211            Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
212            _ => None,
213        }?;
214
215        let text = if let Some(description) = item
216            .label_details
217            .as_ref()
218            .and_then(|label_details| label_details.description.as_ref())
219        {
220            format!("{} {}", item.label, description)
221        } else if let Some(detail) = &item.detail {
222            format!("{} {}", item.label, detail)
223        } else {
224            item.label.clone()
225        };
226
227        Some(language::CodeLabel {
228            text,
229            runs: vec![(0..len, highlight_id)],
230            filter_range: 0..len,
231        })
232    }
233
234    async fn initialization_options(
235        self: Arc<Self>,
236        adapter: &Arc<dyn LspAdapterDelegate>,
237    ) -> Result<Option<serde_json::Value>> {
238        let tsdk_path = Self::tsdk_path(adapter).await;
239        Ok(Some(json!({
240            "provideFormatter": true,
241            "hostInfo": "zed",
242            "tsserver": {
243                "path": tsdk_path,
244            },
245            "preferences": {
246                "includeInlayParameterNameHints": "all",
247                "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
248                "includeInlayFunctionParameterTypeHints": true,
249                "includeInlayVariableTypeHints": true,
250                "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
251                "includeInlayPropertyDeclarationTypeHints": true,
252                "includeInlayFunctionLikeReturnTypeHints": true,
253                "includeInlayEnumMemberValueHints": true,
254            }
255        })))
256    }
257
258    async fn workspace_configuration(
259        self: Arc<Self>,
260        delegate: &Arc<dyn LspAdapterDelegate>,
261        _: Arc<dyn LanguageToolchainStore>,
262        cx: &mut AsyncAppContext,
263    ) -> Result<Value> {
264        let override_options = cx.update(|cx| {
265            language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
266                .and_then(|s| s.settings.clone())
267        })?;
268        if let Some(options) = override_options {
269            return Ok(options);
270        }
271        Ok(json!({
272            "completions": {
273              "completeFunctionCalls": true
274            }
275        }))
276    }
277
278    fn language_ids(&self) -> HashMap<String, String> {
279        HashMap::from_iter([
280            ("TypeScript".into(), "typescript".into()),
281            ("JavaScript".into(), "javascript".into()),
282            ("TSX".into(), "typescriptreact".into()),
283        ])
284    }
285}
286
287async fn get_cached_ts_server_binary(
288    container_dir: PathBuf,
289    node: &NodeRuntime,
290) -> Option<LanguageServerBinary> {
291    maybe!(async {
292        let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
293        let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
294        if new_server_path.exists() {
295            Ok(LanguageServerBinary {
296                path: node.binary_path().await?,
297                env: None,
298                arguments: typescript_server_binary_arguments(&new_server_path),
299            })
300        } else if old_server_path.exists() {
301            Ok(LanguageServerBinary {
302                path: node.binary_path().await?,
303                env: None,
304                arguments: typescript_server_binary_arguments(&old_server_path),
305            })
306        } else {
307            Err(anyhow!(
308                "missing executable in directory {:?}",
309                container_dir
310            ))
311        }
312    })
313    .await
314    .log_err()
315}
316
317pub struct EsLintLspAdapter {
318    node: NodeRuntime,
319}
320
321impl EsLintLspAdapter {
322    const CURRENT_VERSION: &'static str = "2.4.4";
323    const CURRENT_VERSION_TAG_NAME: &'static str = "release/2.4.4";
324
325    #[cfg(not(windows))]
326    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
327    #[cfg(windows)]
328    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
329
330    const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
331    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("eslint");
332
333    const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] =
334        &["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs"];
335
336    pub fn new(node: NodeRuntime) -> Self {
337        EsLintLspAdapter { node }
338    }
339
340    fn build_destination_path(container_dir: &Path) -> PathBuf {
341        container_dir.join(format!("vscode-eslint-{}", Self::CURRENT_VERSION))
342    }
343}
344
345#[async_trait(?Send)]
346impl LspAdapter for EsLintLspAdapter {
347    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
348        Some(vec![
349            CodeActionKind::QUICKFIX,
350            CodeActionKind::new("source.fixAll.eslint"),
351        ])
352    }
353
354    async fn workspace_configuration(
355        self: Arc<Self>,
356        delegate: &Arc<dyn LspAdapterDelegate>,
357        _: Arc<dyn LanguageToolchainStore>,
358        cx: &mut AsyncAppContext,
359    ) -> Result<Value> {
360        let workspace_root = delegate.worktree_root_path();
361
362        let eslint_user_settings = cx.update(|cx| {
363            language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
364                .and_then(|s| s.settings.clone())
365                .unwrap_or_default()
366        })?;
367
368        let mut code_action_on_save = json!({
369            // We enable this, but without also configuring `code_actions_on_format`
370            // in the Zed configuration, it doesn't have an effect.
371            "enable": true,
372        });
373
374        if let Some(code_action_settings) = eslint_user_settings
375            .get("codeActionOnSave")
376            .and_then(|settings| settings.as_object())
377        {
378            if let Some(enable) = code_action_settings.get("enable") {
379                code_action_on_save["enable"] = enable.clone();
380            }
381            if let Some(mode) = code_action_settings.get("mode") {
382                code_action_on_save["mode"] = mode.clone();
383            }
384            if let Some(rules) = code_action_settings.get("rules") {
385                code_action_on_save["rules"] = rules.clone();
386            }
387        }
388
389        let working_directory = eslint_user_settings
390            .get("workingDirectory")
391            .cloned()
392            .unwrap_or_else(|| json!({"mode": "auto"}));
393
394        let problems = eslint_user_settings
395            .get("problems")
396            .cloned()
397            .unwrap_or_else(|| json!({}));
398
399        let rules_customizations = eslint_user_settings
400            .get("rulesCustomizations")
401            .cloned()
402            .unwrap_or_else(|| json!([]));
403
404        let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
405        let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
406            .iter()
407            .any(|file| workspace_root.join(file).is_file());
408
409        Ok(json!({
410            "": {
411                "validate": "on",
412                "rulesCustomizations": rules_customizations,
413                "run": "onType",
414                "nodePath": node_path,
415                "workingDirectory": working_directory,
416                "workspaceFolder": {
417                    "uri": workspace_root,
418                    "name": workspace_root.file_name()
419                        .unwrap_or(workspace_root.as_os_str()),
420                },
421                "problems": problems,
422                "codeActionOnSave": code_action_on_save,
423                "codeAction": {
424                    "disableRuleComment": {
425                        "enable": true,
426                        "location": "separateLine",
427                    },
428                    "showDocumentation": {
429                        "enable": true
430                    }
431                },
432                "experimental": {
433                    "useFlatConfig": use_flat_config,
434                },
435            }
436        }))
437    }
438
439    fn name(&self) -> LanguageServerName {
440        Self::SERVER_NAME.clone()
441    }
442
443    async fn fetch_latest_server_version(
444        &self,
445        _delegate: &dyn LspAdapterDelegate,
446    ) -> Result<Box<dyn 'static + Send + Any>> {
447        let url = build_asset_url(
448            "zed-industries/vscode-eslint",
449            Self::CURRENT_VERSION_TAG_NAME,
450            Self::GITHUB_ASSET_KIND,
451        )?;
452
453        Ok(Box::new(GitHubLspBinaryVersion {
454            name: Self::CURRENT_VERSION.into(),
455            url,
456        }))
457    }
458
459    async fn fetch_server_binary(
460        &self,
461        version: Box<dyn 'static + Send + Any>,
462        container_dir: PathBuf,
463        delegate: &dyn LspAdapterDelegate,
464    ) -> Result<LanguageServerBinary> {
465        let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
466        let destination_path = Self::build_destination_path(&container_dir);
467        let server_path = destination_path.join(Self::SERVER_PATH);
468
469        if fs::metadata(&server_path).await.is_err() {
470            remove_matching(&container_dir, |entry| entry != destination_path).await;
471
472            let mut response = delegate
473                .http_client()
474                .get(&version.url, Default::default(), true)
475                .await
476                .map_err(|err| anyhow!("error downloading release: {}", err))?;
477            match Self::GITHUB_ASSET_KIND {
478                AssetKind::TarGz => {
479                    let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
480                    let archive = Archive::new(decompressed_bytes);
481                    archive.unpack(&destination_path).await.with_context(|| {
482                        format!("extracting {} to {:?}", version.url, destination_path)
483                    })?;
484                }
485                AssetKind::Gz => {
486                    let mut decompressed_bytes =
487                        GzipDecoder::new(BufReader::new(response.body_mut()));
488                    let mut file =
489                        fs::File::create(&destination_path).await.with_context(|| {
490                            format!(
491                                "creating a file {:?} for a download from {}",
492                                destination_path, version.url,
493                            )
494                        })?;
495                    futures::io::copy(&mut decompressed_bytes, &mut file)
496                        .await
497                        .with_context(|| {
498                            format!("extracting {} to {:?}", version.url, destination_path)
499                        })?;
500                }
501                AssetKind::Zip => {
502                    node_runtime::extract_zip(
503                        &destination_path,
504                        BufReader::new(response.body_mut()),
505                    )
506                    .await
507                    .with_context(|| {
508                        format!("unzipping {} to {:?}", version.url, destination_path)
509                    })?;
510                }
511            }
512
513            let mut dir = fs::read_dir(&destination_path).await?;
514            let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
515            let repo_root = destination_path.join("vscode-eslint");
516            fs::rename(first.path(), &repo_root).await?;
517
518            #[cfg(target_os = "windows")]
519            {
520                handle_symlink(
521                    repo_root.join("$shared"),
522                    repo_root.join("client").join("src").join("shared"),
523                )
524                .await?;
525                handle_symlink(
526                    repo_root.join("$shared"),
527                    repo_root.join("server").join("src").join("shared"),
528                )
529                .await?;
530            }
531
532            self.node
533                .run_npm_subcommand(&repo_root, "install", &[])
534                .await?;
535
536            self.node
537                .run_npm_subcommand(&repo_root, "run-script", &["compile"])
538                .await?;
539        }
540
541        Ok(LanguageServerBinary {
542            path: self.node.binary_path().await?,
543            env: None,
544            arguments: eslint_server_binary_arguments(&server_path),
545        })
546    }
547
548    async fn cached_server_binary(
549        &self,
550        container_dir: PathBuf,
551        _: &dyn LspAdapterDelegate,
552    ) -> Option<LanguageServerBinary> {
553        let server_path =
554            Self::build_destination_path(&container_dir).join(EsLintLspAdapter::SERVER_PATH);
555        Some(LanguageServerBinary {
556            path: self.node.binary_path().await.ok()?,
557            env: None,
558            arguments: eslint_server_binary_arguments(&server_path),
559        })
560    }
561}
562
563#[cfg(target_os = "windows")]
564async fn handle_symlink(src_dir: PathBuf, dest_dir: PathBuf) -> Result<()> {
565    if fs::metadata(&src_dir).await.is_err() {
566        return Err(anyhow!("Directory {} not present.", src_dir.display()));
567    }
568    if fs::metadata(&dest_dir).await.is_ok() {
569        fs::remove_file(&dest_dir).await?;
570    }
571    fs::create_dir_all(&dest_dir).await?;
572    let mut entries = fs::read_dir(&src_dir).await?;
573    while let Some(entry) = entries.try_next().await? {
574        let entry_path = entry.path();
575        let entry_name = entry.file_name();
576        let dest_path = dest_dir.join(&entry_name);
577        fs::copy(&entry_path, &dest_path).await?;
578    }
579    Ok(())
580}
581
582#[cfg(test)]
583mod tests {
584    use gpui::{Context, TestAppContext};
585    use unindent::Unindent;
586
587    #[gpui::test]
588    async fn test_outline(cx: &mut TestAppContext) {
589        let language = crate::language(
590            "typescript",
591            tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
592        );
593
594        let text = r#"
595            function a() {
596              // local variables are omitted
597              let a1 = 1;
598              // all functions are included
599              async function a2() {}
600            }
601            // top-level variables are included
602            let b: C
603            function getB() {}
604            // exported variables are included
605            export const d = e;
606        "#
607        .unindent();
608
609        let buffer =
610            cx.new_model(|cx| language::Buffer::local(text, cx).with_language(language, cx));
611        let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
612        assert_eq!(
613            outline
614                .items
615                .iter()
616                .map(|item| (item.text.as_str(), item.depth))
617                .collect::<Vec<_>>(),
618            &[
619                ("function a()", 0),
620                ("async function a2()", 1),
621                ("let b", 0),
622                ("function getB()", 0),
623                ("const d", 0),
624            ]
625        );
626    }
627}