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