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::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: Arc<dyn 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    pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
 77        TypeScriptLspAdapter { node }
 78    }
 79    async fn tsdk_path(adapter: &Arc<dyn LspAdapterDelegate>) -> &'static str {
 80        let is_yarn = adapter
 81            .read_text_file(PathBuf::from(".yarn/sdks/typescript/lib/typescript.js"))
 82            .await
 83            .is_ok();
 84
 85        if is_yarn {
 86            ".yarn/sdks/typescript/lib"
 87        } else {
 88            "node_modules/typescript/lib"
 89        }
 90    }
 91}
 92
 93struct TypeScriptVersions {
 94    typescript_version: String,
 95    server_version: String,
 96}
 97
 98#[async_trait(?Send)]
 99impl LspAdapter for TypeScriptLspAdapter {
100    fn name(&self) -> LanguageServerName {
101        Self::SERVER_NAME.clone()
102    }
103
104    async fn fetch_latest_server_version(
105        &self,
106        _: &dyn LspAdapterDelegate,
107    ) -> Result<Box<dyn 'static + Send + Any>> {
108        Ok(Box::new(TypeScriptVersions {
109            typescript_version: self.node.npm_package_latest_version("typescript").await?,
110            server_version: self
111                .node
112                .npm_package_latest_version("typescript-language-server")
113                .await?,
114        }) as Box<_>)
115    }
116
117    async fn fetch_server_binary(
118        &self,
119        latest_version: Box<dyn 'static + Send + Any>,
120        container_dir: PathBuf,
121        _: &dyn LspAdapterDelegate,
122    ) -> Result<LanguageServerBinary> {
123        let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
124        let server_path = container_dir.join(Self::NEW_SERVER_PATH);
125        let package_name = "typescript";
126
127        let should_install_language_server = self
128            .node
129            .should_install_npm_package(
130                package_name,
131                &server_path,
132                &container_dir,
133                latest_version.typescript_version.as_str(),
134            )
135            .await;
136
137        if should_install_language_server {
138            self.node
139                .npm_install_packages(
140                    &container_dir,
141                    &[
142                        (package_name, latest_version.typescript_version.as_str()),
143                        (
144                            "typescript-language-server",
145                            latest_version.server_version.as_str(),
146                        ),
147                    ],
148                )
149                .await?;
150        }
151
152        Ok(LanguageServerBinary {
153            path: self.node.binary_path().await?,
154            env: None,
155            arguments: typescript_server_binary_arguments(&server_path),
156        })
157    }
158
159    async fn cached_server_binary(
160        &self,
161        container_dir: PathBuf,
162        _: &dyn LspAdapterDelegate,
163    ) -> Option<LanguageServerBinary> {
164        get_cached_ts_server_binary(container_dir, &*self.node).await
165    }
166
167    async fn installation_test_binary(
168        &self,
169        container_dir: PathBuf,
170    ) -> Option<LanguageServerBinary> {
171        get_cached_ts_server_binary(container_dir, &*self.node).await
172    }
173
174    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
175        Some(vec![
176            CodeActionKind::QUICKFIX,
177            CodeActionKind::REFACTOR,
178            CodeActionKind::REFACTOR_EXTRACT,
179            CodeActionKind::SOURCE,
180        ])
181    }
182
183    async fn label_for_completion(
184        &self,
185        item: &lsp::CompletionItem,
186        language: &Arc<language::Language>,
187    ) -> Option<language::CodeLabel> {
188        use lsp::CompletionItemKind as Kind;
189        let len = item.label.len();
190        let grammar = language.grammar()?;
191        let highlight_id = match item.kind? {
192            Kind::CLASS | Kind::INTERFACE | Kind::ENUM => grammar.highlight_id_for_name("type"),
193            Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
194            Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
195            Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
196            Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
197            Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
198            _ => None,
199        }?;
200
201        let text = match &item.detail {
202            Some(detail) => format!("{} {}", item.label, detail),
203            None => item.label.clone(),
204        };
205
206        Some(language::CodeLabel {
207            text,
208            runs: vec![(0..len, highlight_id)],
209            filter_range: 0..len,
210        })
211    }
212
213    async fn initialization_options(
214        self: Arc<Self>,
215        adapter: &Arc<dyn LspAdapterDelegate>,
216    ) -> Result<Option<serde_json::Value>> {
217        let tsdk_path = Self::tsdk_path(adapter).await;
218        Ok(Some(json!({
219            "provideFormatter": true,
220            "hostInfo": "zed",
221            "tsserver": {
222                "path": tsdk_path,
223            },
224            "preferences": {
225                "includeInlayParameterNameHints": "all",
226                "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
227                "includeInlayFunctionParameterTypeHints": true,
228                "includeInlayVariableTypeHints": true,
229                "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
230                "includeInlayPropertyDeclarationTypeHints": true,
231                "includeInlayFunctionLikeReturnTypeHints": true,
232                "includeInlayEnumMemberValueHints": true,
233            }
234        })))
235    }
236
237    async fn workspace_configuration(
238        self: Arc<Self>,
239        delegate: &Arc<dyn LspAdapterDelegate>,
240        cx: &mut AsyncAppContext,
241    ) -> Result<Value> {
242        let override_options = cx.update(|cx| {
243            language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
244                .and_then(|s| s.settings.clone())
245        })?;
246        if let Some(options) = override_options {
247            return Ok(options);
248        }
249        Ok(json!({
250            "completions": {
251              "completeFunctionCalls": true
252            }
253        }))
254    }
255
256    fn language_ids(&self) -> HashMap<String, String> {
257        HashMap::from_iter([
258            ("TypeScript".into(), "typescript".into()),
259            ("JavaScript".into(), "javascript".into()),
260            ("TSX".into(), "typescriptreact".into()),
261        ])
262    }
263}
264
265async fn get_cached_ts_server_binary(
266    container_dir: PathBuf,
267    node: &dyn NodeRuntime,
268) -> Option<LanguageServerBinary> {
269    maybe!(async {
270        let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
271        let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
272        if new_server_path.exists() {
273            Ok(LanguageServerBinary {
274                path: node.binary_path().await?,
275                env: None,
276                arguments: typescript_server_binary_arguments(&new_server_path),
277            })
278        } else if old_server_path.exists() {
279            Ok(LanguageServerBinary {
280                path: node.binary_path().await?,
281                env: None,
282                arguments: typescript_server_binary_arguments(&old_server_path),
283            })
284        } else {
285            Err(anyhow!(
286                "missing executable in directory {:?}",
287                container_dir
288            ))
289        }
290    })
291    .await
292    .log_err()
293}
294
295pub struct EsLintLspAdapter {
296    node: Arc<dyn NodeRuntime>,
297}
298
299impl EsLintLspAdapter {
300    const CURRENT_VERSION: &'static str = "release/2.4.4";
301
302    #[cfg(not(windows))]
303    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
304    #[cfg(windows)]
305    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
306
307    const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
308    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("eslint");
309
310    const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] =
311        &["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs"];
312
313    pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
314        EsLintLspAdapter { node }
315    }
316}
317
318#[async_trait(?Send)]
319impl LspAdapter for EsLintLspAdapter {
320    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
321        Some(vec![
322            CodeActionKind::QUICKFIX,
323            CodeActionKind::new("source.fixAll.eslint"),
324        ])
325    }
326
327    async fn workspace_configuration(
328        self: Arc<Self>,
329        delegate: &Arc<dyn LspAdapterDelegate>,
330        cx: &mut AsyncAppContext,
331    ) -> Result<Value> {
332        let workspace_root = delegate.worktree_root_path();
333
334        let eslint_user_settings = cx.update(|cx| {
335            language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
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        Self::SERVER_NAME.clone()
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(
560            "typescript",
561            tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
562        );
563
564        let text = r#"
565            function a() {
566              // local variables are omitted
567              let a1 = 1;
568              // all functions are included
569              async function a2() {}
570            }
571            // top-level variables are included
572            let b: C
573            function getB() {}
574            // exported variables are included
575            export const d = e;
576        "#
577        .unindent();
578
579        let buffer =
580            cx.new_model(|cx| language::Buffer::local(text, cx).with_language(language, cx));
581        let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
582        assert_eq!(
583            outline
584                .items
585                .iter()
586                .map(|item| (item.text.as_str(), item.depth))
587                .collect::<Vec<_>>(),
588            &[
589                ("function a()", 0),
590                ("async function a2()", 1),
591                ("let b", 0),
592                ("function getB()", 0),
593                ("const d", 0),
594            ]
595        );
596    }
597}