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 = match &item.detail {
216 Some(detail) => format!("{} {}", item.label, detail),
217 None => item.label.clone(),
218 };
219
220 Some(language::CodeLabel {
221 text,
222 runs: vec![(0..len, highlight_id)],
223 filter_range: 0..len,
224 })
225 }
226
227 async fn initialization_options(
228 self: Arc<Self>,
229 adapter: &Arc<dyn LspAdapterDelegate>,
230 ) -> Result<Option<serde_json::Value>> {
231 let tsdk_path = Self::tsdk_path(adapter).await;
232 Ok(Some(json!({
233 "provideFormatter": true,
234 "hostInfo": "zed",
235 "tsserver": {
236 "path": tsdk_path,
237 },
238 "preferences": {
239 "includeInlayParameterNameHints": "all",
240 "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
241 "includeInlayFunctionParameterTypeHints": true,
242 "includeInlayVariableTypeHints": true,
243 "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
244 "includeInlayPropertyDeclarationTypeHints": true,
245 "includeInlayFunctionLikeReturnTypeHints": true,
246 "includeInlayEnumMemberValueHints": true,
247 }
248 })))
249 }
250
251 async fn workspace_configuration(
252 self: Arc<Self>,
253 delegate: &Arc<dyn LspAdapterDelegate>,
254 _: Arc<dyn LanguageToolchainStore>,
255 cx: &mut AsyncAppContext,
256 ) -> Result<Value> {
257 let override_options = cx.update(|cx| {
258 language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
259 .and_then(|s| s.settings.clone())
260 })?;
261 if let Some(options) = override_options {
262 return Ok(options);
263 }
264 Ok(json!({
265 "completions": {
266 "completeFunctionCalls": true
267 }
268 }))
269 }
270
271 fn language_ids(&self) -> HashMap<String, String> {
272 HashMap::from_iter([
273 ("TypeScript".into(), "typescript".into()),
274 ("JavaScript".into(), "javascript".into()),
275 ("TSX".into(), "typescriptreact".into()),
276 ])
277 }
278}
279
280async fn get_cached_ts_server_binary(
281 container_dir: PathBuf,
282 node: &NodeRuntime,
283) -> Option<LanguageServerBinary> {
284 maybe!(async {
285 let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
286 let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
287 if new_server_path.exists() {
288 Ok(LanguageServerBinary {
289 path: node.binary_path().await?,
290 env: None,
291 arguments: typescript_server_binary_arguments(&new_server_path),
292 })
293 } else if old_server_path.exists() {
294 Ok(LanguageServerBinary {
295 path: node.binary_path().await?,
296 env: None,
297 arguments: typescript_server_binary_arguments(&old_server_path),
298 })
299 } else {
300 Err(anyhow!(
301 "missing executable in directory {:?}",
302 container_dir
303 ))
304 }
305 })
306 .await
307 .log_err()
308}
309
310pub struct EsLintLspAdapter {
311 node: NodeRuntime,
312}
313
314impl EsLintLspAdapter {
315 const CURRENT_VERSION: &'static str = "2.4.4";
316 const CURRENT_VERSION_TAG_NAME: &'static str = "release/2.4.4";
317
318 #[cfg(not(windows))]
319 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
320 #[cfg(windows)]
321 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
322
323 const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
324 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("eslint");
325
326 const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] =
327 &["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs"];
328
329 pub fn new(node: NodeRuntime) -> Self {
330 EsLintLspAdapter { node }
331 }
332
333 fn build_destination_path(container_dir: &Path) -> PathBuf {
334 container_dir.join(format!("vscode-eslint-{}", Self::CURRENT_VERSION))
335 }
336}
337
338#[async_trait(?Send)]
339impl LspAdapter for EsLintLspAdapter {
340 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
341 Some(vec![
342 CodeActionKind::QUICKFIX,
343 CodeActionKind::new("source.fixAll.eslint"),
344 ])
345 }
346
347 async fn workspace_configuration(
348 self: Arc<Self>,
349 delegate: &Arc<dyn LspAdapterDelegate>,
350 _: Arc<dyn LanguageToolchainStore>,
351 cx: &mut AsyncAppContext,
352 ) -> Result<Value> {
353 let workspace_root = delegate.worktree_root_path();
354
355 let eslint_user_settings = cx.update(|cx| {
356 language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
357 .and_then(|s| s.settings.clone())
358 .unwrap_or_default()
359 })?;
360
361 let mut code_action_on_save = json!({
362 // We enable this, but without also configuring `code_actions_on_format`
363 // in the Zed configuration, it doesn't have an effect.
364 "enable": true,
365 });
366
367 if let Some(code_action_settings) = eslint_user_settings
368 .get("codeActionOnSave")
369 .and_then(|settings| settings.as_object())
370 {
371 if let Some(enable) = code_action_settings.get("enable") {
372 code_action_on_save["enable"] = enable.clone();
373 }
374 if let Some(mode) = code_action_settings.get("mode") {
375 code_action_on_save["mode"] = mode.clone();
376 }
377 if let Some(rules) = code_action_settings.get("rules") {
378 code_action_on_save["rules"] = rules.clone();
379 }
380 }
381
382 let working_directory = eslint_user_settings
383 .get("workingDirectory")
384 .cloned()
385 .unwrap_or_else(|| json!({"mode": "auto"}));
386
387 let problems = eslint_user_settings
388 .get("problems")
389 .cloned()
390 .unwrap_or_else(|| json!({}));
391
392 let rules_customizations = eslint_user_settings
393 .get("rulesCustomizations")
394 .cloned()
395 .unwrap_or_else(|| json!([]));
396
397 let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
398 let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
399 .iter()
400 .any(|file| workspace_root.join(file).is_file());
401
402 Ok(json!({
403 "": {
404 "validate": "on",
405 "rulesCustomizations": rules_customizations,
406 "run": "onType",
407 "nodePath": node_path,
408 "workingDirectory": working_directory,
409 "workspaceFolder": {
410 "uri": workspace_root,
411 "name": workspace_root.file_name()
412 .unwrap_or(workspace_root.as_os_str()),
413 },
414 "problems": problems,
415 "codeActionOnSave": code_action_on_save,
416 "codeAction": {
417 "disableRuleComment": {
418 "enable": true,
419 "location": "separateLine",
420 },
421 "showDocumentation": {
422 "enable": true
423 }
424 },
425 "experimental": {
426 "useFlatConfig": use_flat_config,
427 },
428 }
429 }))
430 }
431
432 fn name(&self) -> LanguageServerName {
433 Self::SERVER_NAME.clone()
434 }
435
436 async fn fetch_latest_server_version(
437 &self,
438 _delegate: &dyn LspAdapterDelegate,
439 ) -> Result<Box<dyn 'static + Send + Any>> {
440 let url = build_asset_url(
441 "zed-industries/vscode-eslint",
442 Self::CURRENT_VERSION_TAG_NAME,
443 Self::GITHUB_ASSET_KIND,
444 )?;
445
446 Ok(Box::new(GitHubLspBinaryVersion {
447 name: Self::CURRENT_VERSION.into(),
448 url,
449 }))
450 }
451
452 async fn fetch_server_binary(
453 &self,
454 version: Box<dyn 'static + Send + Any>,
455 container_dir: PathBuf,
456 delegate: &dyn LspAdapterDelegate,
457 ) -> Result<LanguageServerBinary> {
458 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
459 let destination_path = Self::build_destination_path(&container_dir);
460 let server_path = destination_path.join(Self::SERVER_PATH);
461
462 if fs::metadata(&server_path).await.is_err() {
463 remove_matching(&container_dir, |entry| entry != destination_path).await;
464
465 let mut response = delegate
466 .http_client()
467 .get(&version.url, Default::default(), true)
468 .await
469 .map_err(|err| anyhow!("error downloading release: {}", err))?;
470 match Self::GITHUB_ASSET_KIND {
471 AssetKind::TarGz => {
472 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
473 let archive = Archive::new(decompressed_bytes);
474 archive.unpack(&destination_path).await.with_context(|| {
475 format!("extracting {} to {:?}", version.url, destination_path)
476 })?;
477 }
478 AssetKind::Gz => {
479 let mut decompressed_bytes =
480 GzipDecoder::new(BufReader::new(response.body_mut()));
481 let mut file =
482 fs::File::create(&destination_path).await.with_context(|| {
483 format!(
484 "creating a file {:?} for a download from {}",
485 destination_path, version.url,
486 )
487 })?;
488 futures::io::copy(&mut decompressed_bytes, &mut file)
489 .await
490 .with_context(|| {
491 format!("extracting {} to {:?}", version.url, destination_path)
492 })?;
493 }
494 AssetKind::Zip => {
495 node_runtime::extract_zip(
496 &destination_path,
497 BufReader::new(response.body_mut()),
498 )
499 .await
500 .with_context(|| {
501 format!("unzipping {} to {:?}", version.url, destination_path)
502 })?;
503 }
504 }
505
506 let mut dir = fs::read_dir(&destination_path).await?;
507 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
508 let repo_root = destination_path.join("vscode-eslint");
509 fs::rename(first.path(), &repo_root).await?;
510
511 #[cfg(target_os = "windows")]
512 {
513 handle_symlink(
514 repo_root.join("$shared"),
515 repo_root.join("client").join("src").join("shared"),
516 )
517 .await?;
518 handle_symlink(
519 repo_root.join("$shared"),
520 repo_root.join("server").join("src").join("shared"),
521 )
522 .await?;
523 }
524
525 self.node
526 .run_npm_subcommand(&repo_root, "install", &[])
527 .await?;
528
529 self.node
530 .run_npm_subcommand(&repo_root, "run-script", &["compile"])
531 .await?;
532 }
533
534 Ok(LanguageServerBinary {
535 path: self.node.binary_path().await?,
536 env: None,
537 arguments: eslint_server_binary_arguments(&server_path),
538 })
539 }
540
541 async fn cached_server_binary(
542 &self,
543 container_dir: PathBuf,
544 _: &dyn LspAdapterDelegate,
545 ) -> Option<LanguageServerBinary> {
546 let server_path =
547 Self::build_destination_path(&container_dir).join(EsLintLspAdapter::SERVER_PATH);
548 Some(LanguageServerBinary {
549 path: self.node.binary_path().await.ok()?,
550 env: None,
551 arguments: eslint_server_binary_arguments(&server_path),
552 })
553 }
554}
555
556#[cfg(target_os = "windows")]
557async fn handle_symlink(src_dir: PathBuf, dest_dir: PathBuf) -> Result<()> {
558 if fs::metadata(&src_dir).await.is_err() {
559 return Err(anyhow!("Directory {} not present.", src_dir.display()));
560 }
561 if fs::metadata(&dest_dir).await.is_ok() {
562 fs::remove_file(&dest_dir).await?;
563 }
564 fs::create_dir_all(&dest_dir).await?;
565 let mut entries = fs::read_dir(&src_dir).await?;
566 while let Some(entry) = entries.try_next().await? {
567 let entry_path = entry.path();
568 let entry_name = entry.file_name();
569 let dest_path = dest_dir.join(&entry_name);
570 fs::copy(&entry_path, &dest_path).await?;
571 }
572 Ok(())
573}
574
575#[cfg(test)]
576mod tests {
577 use gpui::{Context, TestAppContext};
578 use unindent::Unindent;
579
580 #[gpui::test]
581 async fn test_outline(cx: &mut TestAppContext) {
582 let language = crate::language(
583 "typescript",
584 tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
585 );
586
587 let text = r#"
588 function a() {
589 // local variables are omitted
590 let a1 = 1;
591 // all functions are included
592 async function a2() {}
593 }
594 // top-level variables are included
595 let b: C
596 function getB() {}
597 // exported variables are included
598 export const d = e;
599 "#
600 .unindent();
601
602 let buffer =
603 cx.new_model(|cx| language::Buffer::local(text, cx).with_language(language, cx));
604 let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
605 assert_eq!(
606 outline
607 .items
608 .iter()
609 .map(|item| (item.text.as_str(), item.depth))
610 .collect::<Vec<_>>(),
611 &[
612 ("function a()", 0),
613 ("async function a2()", 1),
614 ("let b", 0),
615 ("function getB()", 0),
616 ("const d", 0),
617 ]
618 );
619 }
620}