1use anyhow::{Context as _, Result};
2use async_compression::futures::bufread::GzipDecoder;
3use async_tar::Archive;
4use async_trait::async_trait;
5use chrono::{DateTime, Local};
6use collections::HashMap;
7use futures::future::join_all;
8use gpui::{App, AppContext, AsyncApp, Task};
9use http_client::github::{AssetKind, GitHubLspBinaryVersion, build_asset_url};
10use language::{
11 Buffer, ContextLocation, ContextProvider, File, LanguageToolchainStore, LspAdapter,
12 LspAdapterDelegate,
13};
14use lsp::{CodeActionKind, LanguageServerBinary, LanguageServerId, LanguageServerName};
15use node_runtime::NodeRuntime;
16use project::{Fs, lsp_store::language_server_settings};
17use serde_json::{Value, json};
18use smol::{fs, io::BufReader, lock::RwLock, stream::StreamExt};
19use std::{
20 any::Any,
21 borrow::Cow,
22 ffi::OsString,
23 path::{Path, PathBuf},
24 sync::Arc,
25};
26use task::{TaskTemplate, TaskTemplates, VariableName};
27use util::archive::extract_zip;
28use util::merge_json_value_into;
29use util::{ResultExt, fs::remove_matching, maybe};
30
31use crate::{PackageJson, PackageJsonData};
32
33#[derive(Debug)]
34pub(crate) struct TypeScriptContextProvider {
35 last_package_json: PackageJsonContents,
36}
37
38const TYPESCRIPT_RUNNER_VARIABLE: VariableName =
39 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_RUNNER"));
40
41const TYPESCRIPT_JEST_TEST_NAME_VARIABLE: VariableName =
42 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_JEST_TEST_NAME"));
43
44const TYPESCRIPT_VITEST_TEST_NAME_VARIABLE: VariableName =
45 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_VITEST_TEST_NAME"));
46
47const TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE: VariableName =
48 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_JEST_PACKAGE_PATH"));
49
50const TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE: VariableName =
51 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_MOCHA_PACKAGE_PATH"));
52
53const TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE: VariableName =
54 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_VITEST_PACKAGE_PATH"));
55
56const TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE: VariableName =
57 VariableName::Custom(Cow::Borrowed("TYPESCRIPT_JASMINE_PACKAGE_PATH"));
58
59#[derive(Clone, Debug, Default)]
60struct PackageJsonContents(Arc<RwLock<HashMap<PathBuf, PackageJson>>>);
61
62impl PackageJsonData {
63 fn fill_task_templates(&self, task_templates: &mut TaskTemplates) {
64 if self.jest_package_path.is_some() {
65 task_templates.0.push(TaskTemplate {
66 label: "jest file test".to_owned(),
67 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
68 args: vec![
69 "exec".to_owned(),
70 "--".to_owned(),
71 "jest".to_owned(),
72 "--runInBand".to_owned(),
73 VariableName::File.template_value(),
74 ],
75 cwd: Some(TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE.template_value()),
76 ..TaskTemplate::default()
77 });
78 task_templates.0.push(TaskTemplate {
79 label: format!("jest test {}", VariableName::Symbol.template_value()),
80 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
81 args: vec![
82 "exec".to_owned(),
83 "--".to_owned(),
84 "jest".to_owned(),
85 "--runInBand".to_owned(),
86 "--testNamePattern".to_owned(),
87 format!(
88 "\"{}\"",
89 TYPESCRIPT_JEST_TEST_NAME_VARIABLE.template_value()
90 ),
91 VariableName::File.template_value(),
92 ],
93 tags: vec![
94 "ts-test".to_owned(),
95 "js-test".to_owned(),
96 "tsx-test".to_owned(),
97 ],
98 cwd: Some(TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE.template_value()),
99 ..TaskTemplate::default()
100 });
101 }
102
103 if self.vitest_package_path.is_some() {
104 task_templates.0.push(TaskTemplate {
105 label: format!("{} file test", "vitest".to_owned()),
106 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
107 args: vec![
108 "exec".to_owned(),
109 "--".to_owned(),
110 "vitest".to_owned(),
111 "run".to_owned(),
112 "--poolOptions.forks.minForks=0".to_owned(),
113 "--poolOptions.forks.maxForks=1".to_owned(),
114 VariableName::File.template_value(),
115 ],
116 cwd: Some(TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE.template_value()),
117 ..TaskTemplate::default()
118 });
119 task_templates.0.push(TaskTemplate {
120 label: format!(
121 "{} test {}",
122 "vitest".to_owned(),
123 VariableName::Symbol.template_value(),
124 ),
125 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
126 args: vec![
127 "exec".to_owned(),
128 "--".to_owned(),
129 "vitest".to_owned(),
130 "run".to_owned(),
131 "--poolOptions.forks.minForks=0".to_owned(),
132 "--poolOptions.forks.maxForks=1".to_owned(),
133 "--testNamePattern".to_owned(),
134 format!(
135 "\"{}\"",
136 TYPESCRIPT_VITEST_TEST_NAME_VARIABLE.template_value()
137 ),
138 VariableName::File.template_value(),
139 ],
140 tags: vec![
141 "ts-test".to_owned(),
142 "js-test".to_owned(),
143 "tsx-test".to_owned(),
144 ],
145 cwd: Some(TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE.template_value()),
146 ..TaskTemplate::default()
147 });
148 }
149
150 if self.mocha_package_path.is_some() {
151 task_templates.0.push(TaskTemplate {
152 label: format!("{} file test", "mocha".to_owned()),
153 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
154 args: vec![
155 "exec".to_owned(),
156 "--".to_owned(),
157 "mocha".to_owned(),
158 VariableName::File.template_value(),
159 ],
160 cwd: Some(TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE.template_value()),
161 ..TaskTemplate::default()
162 });
163 task_templates.0.push(TaskTemplate {
164 label: format!(
165 "{} test {}",
166 "mocha".to_owned(),
167 VariableName::Symbol.template_value(),
168 ),
169 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
170 args: vec![
171 "exec".to_owned(),
172 "--".to_owned(),
173 "mocha".to_owned(),
174 "--grep".to_owned(),
175 format!("\"{}\"", VariableName::Symbol.template_value()),
176 VariableName::File.template_value(),
177 ],
178 tags: vec![
179 "ts-test".to_owned(),
180 "js-test".to_owned(),
181 "tsx-test".to_owned(),
182 ],
183 cwd: Some(TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE.template_value()),
184 ..TaskTemplate::default()
185 });
186 }
187
188 if self.jasmine_package_path.is_some() {
189 task_templates.0.push(TaskTemplate {
190 label: format!("{} file test", "jasmine".to_owned()),
191 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
192 args: vec![
193 "exec".to_owned(),
194 "--".to_owned(),
195 "jasmine".to_owned(),
196 VariableName::File.template_value(),
197 ],
198 cwd: Some(TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE.template_value()),
199 ..TaskTemplate::default()
200 });
201 task_templates.0.push(TaskTemplate {
202 label: format!(
203 "{} test {}",
204 "jasmine".to_owned(),
205 VariableName::Symbol.template_value(),
206 ),
207 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
208 args: vec![
209 "exec".to_owned(),
210 "--".to_owned(),
211 "jasmine".to_owned(),
212 format!("--filter={}", VariableName::Symbol.template_value()),
213 VariableName::File.template_value(),
214 ],
215 tags: vec![
216 "ts-test".to_owned(),
217 "js-test".to_owned(),
218 "tsx-test".to_owned(),
219 ],
220 cwd: Some(TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE.template_value()),
221 ..TaskTemplate::default()
222 });
223 }
224
225 let script_name_counts: HashMap<_, usize> =
226 self.scripts
227 .iter()
228 .fold(HashMap::default(), |mut acc, (_, script)| {
229 *acc.entry(script).or_default() += 1;
230 acc
231 });
232 for (path, script) in &self.scripts {
233 let label = if script_name_counts.get(script).copied().unwrap_or_default() > 1
234 && let Some(parent) = path.parent().and_then(|parent| parent.file_name())
235 {
236 let parent = parent.to_string_lossy();
237 format!("{parent}/package.json > {script}")
238 } else {
239 format!("package.json > {script}")
240 };
241 task_templates.0.push(TaskTemplate {
242 label,
243 command: TYPESCRIPT_RUNNER_VARIABLE.template_value(),
244 args: vec!["run".to_owned(), script.to_owned()],
245 tags: vec!["package-script".into()],
246 cwd: Some(
247 path.parent()
248 .unwrap_or(Path::new("/"))
249 .to_string_lossy()
250 .to_string(),
251 ),
252 ..TaskTemplate::default()
253 });
254 }
255 }
256}
257
258impl TypeScriptContextProvider {
259 pub fn new() -> Self {
260 Self {
261 last_package_json: PackageJsonContents::default(),
262 }
263 }
264
265 fn combined_package_json_data(
266 &self,
267 fs: Arc<dyn Fs>,
268 worktree_root: &Path,
269 file_relative_path: &Path,
270 cx: &App,
271 ) -> Task<anyhow::Result<PackageJsonData>> {
272 let new_json_data = file_relative_path
273 .ancestors()
274 .map(|path| worktree_root.join(path))
275 .map(|parent_path| {
276 self.package_json_data(&parent_path, self.last_package_json.clone(), fs.clone(), cx)
277 })
278 .collect::<Vec<_>>();
279
280 cx.background_spawn(async move {
281 let mut package_json_data = PackageJsonData::default();
282 for new_data in join_all(new_json_data).await.into_iter().flatten() {
283 package_json_data.merge(new_data);
284 }
285 Ok(package_json_data)
286 })
287 }
288
289 fn package_json_data(
290 &self,
291 directory_path: &Path,
292 existing_package_json: PackageJsonContents,
293 fs: Arc<dyn Fs>,
294 cx: &App,
295 ) -> Task<anyhow::Result<PackageJsonData>> {
296 let package_json_path = directory_path.join("package.json");
297 let metadata_check_fs = fs.clone();
298 cx.background_spawn(async move {
299 let metadata = metadata_check_fs
300 .metadata(&package_json_path)
301 .await
302 .with_context(|| format!("getting metadata for {package_json_path:?}"))?
303 .with_context(|| format!("missing FS metadata for {package_json_path:?}"))?;
304 let mtime = DateTime::<Local>::from(metadata.mtime.timestamp_for_user());
305 let existing_data = {
306 let contents = existing_package_json.0.read().await;
307 contents
308 .get(&package_json_path)
309 .filter(|package_json| package_json.mtime == mtime)
310 .map(|package_json| package_json.data.clone())
311 };
312 match existing_data {
313 Some(existing_data) => Ok(existing_data),
314 None => {
315 let package_json_string =
316 fs.load(&package_json_path).await.with_context(|| {
317 format!("loading package.json from {package_json_path:?}")
318 })?;
319 let package_json: HashMap<String, serde_json_lenient::Value> =
320 serde_json_lenient::from_str(&package_json_string).with_context(|| {
321 format!("parsing package.json from {package_json_path:?}")
322 })?;
323 let new_data =
324 PackageJsonData::new(package_json_path.as_path().into(), package_json);
325 {
326 let mut contents = existing_package_json.0.write().await;
327 contents.insert(
328 package_json_path,
329 PackageJson {
330 mtime,
331 data: new_data.clone(),
332 },
333 );
334 }
335 Ok(new_data)
336 }
337 }
338 })
339 }
340}
341
342async fn detect_package_manager(
343 worktree_root: PathBuf,
344 fs: Arc<dyn Fs>,
345 package_json_data: Option<PackageJsonData>,
346) -> &'static str {
347 if let Some(package_json_data) = package_json_data {
348 if let Some(package_manager) = package_json_data.package_manager {
349 return package_manager;
350 }
351 }
352 if fs.is_file(&worktree_root.join("pnpm-lock.yaml")).await {
353 return "pnpm";
354 }
355 if fs.is_file(&worktree_root.join("yarn.lock")).await {
356 return "yarn";
357 }
358 "npm"
359}
360
361impl ContextProvider for TypeScriptContextProvider {
362 fn associated_tasks(
363 &self,
364 fs: Arc<dyn Fs>,
365 file: Option<Arc<dyn File>>,
366 cx: &App,
367 ) -> Task<Option<TaskTemplates>> {
368 let Some(file) = project::File::from_dyn(file.as_ref()).cloned() else {
369 return Task::ready(None);
370 };
371 let Some(worktree_root) = file.worktree.read(cx).root_dir() else {
372 return Task::ready(None);
373 };
374 let file_relative_path = file.path().clone();
375 let package_json_data =
376 self.combined_package_json_data(fs.clone(), &worktree_root, &file_relative_path, cx);
377
378 cx.background_spawn(async move {
379 let mut task_templates = TaskTemplates(Vec::new());
380 task_templates.0.push(TaskTemplate {
381 label: format!(
382 "execute selection {}",
383 VariableName::SelectedText.template_value()
384 ),
385 command: "node".to_owned(),
386 args: vec![
387 "-e".to_owned(),
388 format!("\"{}\"", VariableName::SelectedText.template_value()),
389 ],
390 ..TaskTemplate::default()
391 });
392
393 match package_json_data.await {
394 Ok(package_json) => {
395 package_json.fill_task_templates(&mut task_templates);
396 }
397 Err(e) => {
398 log::error!(
399 "Failed to read package.json for worktree {file_relative_path:?}: {e:#}"
400 );
401 }
402 }
403
404 Some(task_templates)
405 })
406 }
407
408 fn build_context(
409 &self,
410 current_vars: &task::TaskVariables,
411 location: ContextLocation<'_>,
412 _project_env: Option<HashMap<String, String>>,
413 _toolchains: Arc<dyn LanguageToolchainStore>,
414 cx: &mut App,
415 ) -> Task<Result<task::TaskVariables>> {
416 let mut vars = task::TaskVariables::default();
417
418 if let Some(symbol) = current_vars.get(&VariableName::Symbol) {
419 vars.insert(
420 TYPESCRIPT_JEST_TEST_NAME_VARIABLE,
421 replace_test_name_parameters(symbol),
422 );
423 vars.insert(
424 TYPESCRIPT_VITEST_TEST_NAME_VARIABLE,
425 replace_test_name_parameters(symbol),
426 );
427 }
428 let file_path = location
429 .file_location
430 .buffer
431 .read(cx)
432 .file()
433 .map(|file| file.path());
434
435 let args = location.worktree_root.zip(location.fs).zip(file_path).map(
436 |((worktree_root, fs), file_path)| {
437 (
438 self.combined_package_json_data(fs.clone(), &worktree_root, file_path, cx),
439 worktree_root,
440 fs,
441 )
442 },
443 );
444 cx.background_spawn(async move {
445 if let Some((task, worktree_root, fs)) = args {
446 let package_json_data = task.await.log_err();
447 vars.insert(
448 TYPESCRIPT_RUNNER_VARIABLE,
449 detect_package_manager(worktree_root, fs, package_json_data.clone())
450 .await
451 .to_owned(),
452 );
453
454 if let Some(package_json_data) = package_json_data {
455 if let Some(path) = package_json_data.jest_package_path {
456 vars.insert(
457 TYPESCRIPT_JEST_PACKAGE_PATH_VARIABLE,
458 path.parent()
459 .unwrap_or(Path::new(""))
460 .to_string_lossy()
461 .to_string(),
462 );
463 }
464
465 if let Some(path) = package_json_data.mocha_package_path {
466 vars.insert(
467 TYPESCRIPT_MOCHA_PACKAGE_PATH_VARIABLE,
468 path.parent()
469 .unwrap_or(Path::new(""))
470 .to_string_lossy()
471 .to_string(),
472 );
473 }
474
475 if let Some(path) = package_json_data.vitest_package_path {
476 vars.insert(
477 TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE,
478 path.parent()
479 .unwrap_or(Path::new(""))
480 .to_string_lossy()
481 .to_string(),
482 );
483 }
484
485 if let Some(path) = package_json_data.jasmine_package_path {
486 vars.insert(
487 TYPESCRIPT_JASMINE_PACKAGE_PATH_VARIABLE,
488 path.parent()
489 .unwrap_or(Path::new(""))
490 .to_string_lossy()
491 .to_string(),
492 );
493 }
494 }
495 }
496 Ok(vars)
497 })
498 }
499}
500
501fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
502 vec![server_path.into(), "--stdio".into()]
503}
504
505fn eslint_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
506 vec![
507 "--max-old-space-size=8192".into(),
508 server_path.into(),
509 "--stdio".into(),
510 ]
511}
512
513fn replace_test_name_parameters(test_name: &str) -> String {
514 let pattern = regex::Regex::new(r"(%|\$)[0-9a-zA-Z]+").unwrap();
515
516 pattern.replace_all(test_name, "(.+?)").to_string()
517}
518
519pub struct TypeScriptLspAdapter {
520 node: NodeRuntime,
521}
522
523impl TypeScriptLspAdapter {
524 const OLD_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.js";
525 const NEW_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.mjs";
526 const SERVER_NAME: LanguageServerName =
527 LanguageServerName::new_static("typescript-language-server");
528 const PACKAGE_NAME: &str = "typescript";
529 pub fn new(node: NodeRuntime) -> Self {
530 TypeScriptLspAdapter { node }
531 }
532 async fn tsdk_path(fs: &dyn Fs, adapter: &Arc<dyn LspAdapterDelegate>) -> Option<&'static str> {
533 let is_yarn = adapter
534 .read_text_file(PathBuf::from(".yarn/sdks/typescript/lib/typescript.js"))
535 .await
536 .is_ok();
537
538 let tsdk_path = if is_yarn {
539 ".yarn/sdks/typescript/lib"
540 } else {
541 "node_modules/typescript/lib"
542 };
543
544 if fs
545 .is_dir(&adapter.worktree_root_path().join(tsdk_path))
546 .await
547 {
548 Some(tsdk_path)
549 } else {
550 None
551 }
552 }
553}
554
555struct TypeScriptVersions {
556 typescript_version: String,
557 server_version: String,
558}
559
560#[async_trait(?Send)]
561impl LspAdapter for TypeScriptLspAdapter {
562 fn name(&self) -> LanguageServerName {
563 Self::SERVER_NAME.clone()
564 }
565
566 async fn fetch_latest_server_version(
567 &self,
568 _: &dyn LspAdapterDelegate,
569 ) -> Result<Box<dyn 'static + Send + Any>> {
570 Ok(Box::new(TypeScriptVersions {
571 typescript_version: self.node.npm_package_latest_version("typescript").await?,
572 server_version: self
573 .node
574 .npm_package_latest_version("typescript-language-server")
575 .await?,
576 }) as Box<_>)
577 }
578
579 async fn check_if_version_installed(
580 &self,
581 version: &(dyn 'static + Send + Any),
582 container_dir: &PathBuf,
583 _: &dyn LspAdapterDelegate,
584 ) -> Option<LanguageServerBinary> {
585 let version = version.downcast_ref::<TypeScriptVersions>().unwrap();
586 let server_path = container_dir.join(Self::NEW_SERVER_PATH);
587
588 let should_install_language_server = self
589 .node
590 .should_install_npm_package(
591 Self::PACKAGE_NAME,
592 &server_path,
593 &container_dir,
594 version.typescript_version.as_str(),
595 )
596 .await;
597
598 if should_install_language_server {
599 None
600 } else {
601 Some(LanguageServerBinary {
602 path: self.node.binary_path().await.ok()?,
603 env: None,
604 arguments: typescript_server_binary_arguments(&server_path),
605 })
606 }
607 }
608
609 // >>> https://zed.dev/cla <<<
610 async fn fetch_server_binary(
611 &self,
612 latest_version: Box<dyn 'static + Send + Any>,
613 container_dir: PathBuf,
614 _: &dyn LspAdapterDelegate,
615 ) -> Result<LanguageServerBinary> {
616 let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
617 let server_path = container_dir.join(Self::NEW_SERVER_PATH);
618
619 self.node
620 .npm_install_packages(
621 &container_dir,
622 &[
623 (
624 Self::PACKAGE_NAME,
625 latest_version.typescript_version.as_str(),
626 ),
627 (
628 "typescript-language-server",
629 latest_version.server_version.as_str(),
630 ),
631 ],
632 )
633 .await?;
634
635 Ok(LanguageServerBinary {
636 path: self.node.binary_path().await?,
637 env: None,
638 arguments: typescript_server_binary_arguments(&server_path),
639 })
640 }
641
642 async fn cached_server_binary(
643 &self,
644 container_dir: PathBuf,
645 _: &dyn LspAdapterDelegate,
646 ) -> Option<LanguageServerBinary> {
647 get_cached_ts_server_binary(container_dir, &self.node).await
648 }
649
650 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
651 Some(vec![
652 CodeActionKind::QUICKFIX,
653 CodeActionKind::REFACTOR,
654 CodeActionKind::REFACTOR_EXTRACT,
655 CodeActionKind::SOURCE,
656 ])
657 }
658
659 async fn label_for_completion(
660 &self,
661 item: &lsp::CompletionItem,
662 language: &Arc<language::Language>,
663 ) -> Option<language::CodeLabel> {
664 use lsp::CompletionItemKind as Kind;
665 let len = item.label.len();
666 let grammar = language.grammar()?;
667 let highlight_id = match item.kind? {
668 Kind::CLASS | Kind::INTERFACE | Kind::ENUM => grammar.highlight_id_for_name("type"),
669 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
670 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
671 Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
672 Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
673 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
674 _ => None,
675 }?;
676
677 let text = if let Some(description) = item
678 .label_details
679 .as_ref()
680 .and_then(|label_details| label_details.description.as_ref())
681 {
682 format!("{} {}", item.label, description)
683 } else if let Some(detail) = &item.detail {
684 format!("{} {}", item.label, detail)
685 } else {
686 item.label.clone()
687 };
688 let filter_range = item
689 .filter_text
690 .as_deref()
691 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
692 .unwrap_or(0..len);
693 Some(language::CodeLabel {
694 text,
695 runs: vec![(0..len, highlight_id)],
696 filter_range,
697 })
698 }
699
700 async fn initialization_options(
701 self: Arc<Self>,
702 fs: &dyn Fs,
703 adapter: &Arc<dyn LspAdapterDelegate>,
704 ) -> Result<Option<serde_json::Value>> {
705 let tsdk_path = Self::tsdk_path(fs, adapter).await;
706 Ok(Some(json!({
707 "provideFormatter": true,
708 "hostInfo": "zed",
709 "tsserver": {
710 "path": tsdk_path,
711 },
712 "preferences": {
713 "includeInlayParameterNameHints": "all",
714 "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
715 "includeInlayFunctionParameterTypeHints": true,
716 "includeInlayVariableTypeHints": true,
717 "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
718 "includeInlayPropertyDeclarationTypeHints": true,
719 "includeInlayFunctionLikeReturnTypeHints": true,
720 "includeInlayEnumMemberValueHints": true,
721 }
722 })))
723 }
724
725 async fn workspace_configuration(
726 self: Arc<Self>,
727 _: &dyn Fs,
728 delegate: &Arc<dyn LspAdapterDelegate>,
729 _: Arc<dyn LanguageToolchainStore>,
730 cx: &mut AsyncApp,
731 ) -> Result<Value> {
732 let override_options = cx.update(|cx| {
733 language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
734 .and_then(|s| s.settings.clone())
735 })?;
736 if let Some(options) = override_options {
737 return Ok(options);
738 }
739 Ok(json!({
740 "completions": {
741 "completeFunctionCalls": true
742 }
743 }))
744 }
745
746 fn language_ids(&self) -> HashMap<String, String> {
747 HashMap::from_iter([
748 ("TypeScript".into(), "typescript".into()),
749 ("JavaScript".into(), "javascript".into()),
750 ("TSX".into(), "typescriptreact".into()),
751 ])
752 }
753
754 fn process_diagnostics(
755 &self,
756 d: &mut lsp::PublishDiagnosticsParams,
757 _: LanguageServerId,
758 _: Option<&'_ Buffer>,
759 ) {
760 dbg!("called with ", d);
761 }
762}
763
764async fn get_cached_ts_server_binary(
765 container_dir: PathBuf,
766 node: &NodeRuntime,
767) -> Option<LanguageServerBinary> {
768 maybe!(async {
769 let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
770 let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
771 if new_server_path.exists() {
772 Ok(LanguageServerBinary {
773 path: node.binary_path().await?,
774 env: None,
775 arguments: typescript_server_binary_arguments(&new_server_path),
776 })
777 } else if old_server_path.exists() {
778 Ok(LanguageServerBinary {
779 path: node.binary_path().await?,
780 env: None,
781 arguments: typescript_server_binary_arguments(&old_server_path),
782 })
783 } else {
784 anyhow::bail!("missing executable in directory {container_dir:?}")
785 }
786 })
787 .await
788 .log_err()
789}
790
791pub struct EsLintLspAdapter {
792 node: NodeRuntime,
793}
794
795impl EsLintLspAdapter {
796 const CURRENT_VERSION: &'static str = "2.4.4";
797 const CURRENT_VERSION_TAG_NAME: &'static str = "release/2.4.4";
798
799 #[cfg(not(windows))]
800 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
801 #[cfg(windows)]
802 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
803
804 const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
805 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("eslint");
806
807 const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] = &[
808 "eslint.config.js",
809 "eslint.config.mjs",
810 "eslint.config.cjs",
811 "eslint.config.ts",
812 "eslint.config.cts",
813 "eslint.config.mts",
814 ];
815
816 pub fn new(node: NodeRuntime) -> Self {
817 EsLintLspAdapter { node }
818 }
819
820 fn build_destination_path(container_dir: &Path) -> PathBuf {
821 container_dir.join(format!("vscode-eslint-{}", Self::CURRENT_VERSION))
822 }
823}
824
825#[async_trait(?Send)]
826impl LspAdapter for EsLintLspAdapter {
827 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
828 Some(vec![
829 CodeActionKind::QUICKFIX,
830 CodeActionKind::new("source.fixAll.eslint"),
831 ])
832 }
833
834 async fn workspace_configuration(
835 self: Arc<Self>,
836 _: &dyn Fs,
837 delegate: &Arc<dyn LspAdapterDelegate>,
838 _: Arc<dyn LanguageToolchainStore>,
839 cx: &mut AsyncApp,
840 ) -> Result<Value> {
841 let workspace_root = delegate.worktree_root_path();
842 let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
843 .iter()
844 .any(|file| workspace_root.join(file).is_file());
845
846 let mut default_workspace_configuration = json!({
847 "validate": "on",
848 "rulesCustomizations": [],
849 "run": "onType",
850 "nodePath": null,
851 "workingDirectory": {
852 "mode": "auto"
853 },
854 "workspaceFolder": {
855 "uri": workspace_root,
856 "name": workspace_root.file_name()
857 .unwrap_or(workspace_root.as_os_str())
858 .to_string_lossy(),
859 },
860 "problems": {},
861 "codeActionOnSave": {
862 // We enable this, but without also configuring code_actions_on_format
863 // in the Zed configuration, it doesn't have an effect.
864 "enable": true,
865 },
866 "codeAction": {
867 "disableRuleComment": {
868 "enable": true,
869 "location": "separateLine",
870 },
871 "showDocumentation": {
872 "enable": true
873 }
874 },
875 "experimental": {
876 "useFlatConfig": use_flat_config,
877 },
878 });
879
880 let override_options = cx.update(|cx| {
881 language_server_settings(delegate.as_ref(), &Self::SERVER_NAME, cx)
882 .and_then(|s| s.settings.clone())
883 })?;
884
885 if let Some(override_options) = override_options {
886 merge_json_value_into(override_options, &mut default_workspace_configuration);
887 }
888
889 Ok(json!({
890 "": default_workspace_configuration
891 }))
892 }
893
894 fn name(&self) -> LanguageServerName {
895 Self::SERVER_NAME.clone()
896 }
897
898 async fn fetch_latest_server_version(
899 &self,
900 _delegate: &dyn LspAdapterDelegate,
901 ) -> Result<Box<dyn 'static + Send + Any>> {
902 let url = build_asset_url(
903 "zed-industries/vscode-eslint",
904 Self::CURRENT_VERSION_TAG_NAME,
905 Self::GITHUB_ASSET_KIND,
906 )?;
907
908 Ok(Box::new(GitHubLspBinaryVersion {
909 name: Self::CURRENT_VERSION.into(),
910 url,
911 }))
912 }
913
914 async fn fetch_server_binary(
915 &self,
916 version: Box<dyn 'static + Send + Any>,
917 container_dir: PathBuf,
918 delegate: &dyn LspAdapterDelegate,
919 ) -> Result<LanguageServerBinary> {
920 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
921 let destination_path = Self::build_destination_path(&container_dir);
922 let server_path = destination_path.join(Self::SERVER_PATH);
923
924 if fs::metadata(&server_path).await.is_err() {
925 remove_matching(&container_dir, |entry| entry != destination_path).await;
926
927 let mut response = delegate
928 .http_client()
929 .get(&version.url, Default::default(), true)
930 .await
931 .context("downloading release")?;
932 match Self::GITHUB_ASSET_KIND {
933 AssetKind::TarGz => {
934 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
935 let archive = Archive::new(decompressed_bytes);
936 archive.unpack(&destination_path).await.with_context(|| {
937 format!("extracting {} to {:?}", version.url, destination_path)
938 })?;
939 }
940 AssetKind::Gz => {
941 let mut decompressed_bytes =
942 GzipDecoder::new(BufReader::new(response.body_mut()));
943 let mut file =
944 fs::File::create(&destination_path).await.with_context(|| {
945 format!(
946 "creating a file {:?} for a download from {}",
947 destination_path, version.url,
948 )
949 })?;
950 futures::io::copy(&mut decompressed_bytes, &mut file)
951 .await
952 .with_context(|| {
953 format!("extracting {} to {:?}", version.url, destination_path)
954 })?;
955 }
956 AssetKind::Zip => {
957 extract_zip(&destination_path, response.body_mut())
958 .await
959 .with_context(|| {
960 format!("unzipping {} to {:?}", version.url, destination_path)
961 })?;
962 }
963 }
964
965 let mut dir = fs::read_dir(&destination_path).await?;
966 let first = dir.next().await.context("missing first file")??;
967 let repo_root = destination_path.join("vscode-eslint");
968 fs::rename(first.path(), &repo_root).await?;
969
970 #[cfg(target_os = "windows")]
971 {
972 handle_symlink(
973 repo_root.join("$shared"),
974 repo_root.join("client").join("src").join("shared"),
975 )
976 .await?;
977 handle_symlink(
978 repo_root.join("$shared"),
979 repo_root.join("server").join("src").join("shared"),
980 )
981 .await?;
982 }
983
984 self.node
985 .run_npm_subcommand(&repo_root, "install", &[])
986 .await?;
987
988 self.node
989 .run_npm_subcommand(&repo_root, "run-script", &["compile"])
990 .await?;
991 }
992
993 Ok(LanguageServerBinary {
994 path: self.node.binary_path().await?,
995 env: None,
996 arguments: eslint_server_binary_arguments(&server_path),
997 })
998 }
999
1000 async fn cached_server_binary(
1001 &self,
1002 container_dir: PathBuf,
1003 _: &dyn LspAdapterDelegate,
1004 ) -> Option<LanguageServerBinary> {
1005 let server_path =
1006 Self::build_destination_path(&container_dir).join(EsLintLspAdapter::SERVER_PATH);
1007 Some(LanguageServerBinary {
1008 path: self.node.binary_path().await.ok()?,
1009 env: None,
1010 arguments: eslint_server_binary_arguments(&server_path),
1011 })
1012 }
1013}
1014
1015#[cfg(target_os = "windows")]
1016async fn handle_symlink(src_dir: PathBuf, dest_dir: PathBuf) -> Result<()> {
1017 anyhow::ensure!(
1018 fs::metadata(&src_dir).await.is_ok(),
1019 "Directory {src_dir:?} is not present"
1020 );
1021 if fs::metadata(&dest_dir).await.is_ok() {
1022 fs::remove_file(&dest_dir).await?;
1023 }
1024 fs::create_dir_all(&dest_dir).await?;
1025 let mut entries = fs::read_dir(&src_dir).await?;
1026 while let Some(entry) = entries.try_next().await? {
1027 let entry_path = entry.path();
1028 let entry_name = entry.file_name();
1029 let dest_path = dest_dir.join(&entry_name);
1030 fs::copy(&entry_path, &dest_path).await?;
1031 }
1032 Ok(())
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037 use std::path::Path;
1038
1039 use gpui::{AppContext as _, BackgroundExecutor, TestAppContext};
1040 use language::language_settings;
1041 use project::{FakeFs, Project};
1042 use serde_json::json;
1043 use task::TaskTemplates;
1044 use unindent::Unindent;
1045 use util::path;
1046
1047 use crate::typescript::{PackageJsonData, TypeScriptContextProvider};
1048
1049 #[gpui::test]
1050 async fn test_outline(cx: &mut TestAppContext) {
1051 let language = crate::language(
1052 "typescript",
1053 tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
1054 );
1055
1056 let text = r#"
1057 function a() {
1058 // local variables are omitted
1059 let a1 = 1;
1060 // all functions are included
1061 async function a2() {}
1062 }
1063 // top-level variables are included
1064 let b: C
1065 function getB() {}
1066 // exported variables are included
1067 export const d = e;
1068 "#
1069 .unindent();
1070
1071 let buffer = cx.new(|cx| language::Buffer::local(text, cx).with_language(language, cx));
1072 let outline = buffer.read_with(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
1073 assert_eq!(
1074 outline
1075 .items
1076 .iter()
1077 .map(|item| (item.text.as_str(), item.depth))
1078 .collect::<Vec<_>>(),
1079 &[
1080 ("function a()", 0),
1081 ("async function a2()", 1),
1082 ("let b", 0),
1083 ("function getB()", 0),
1084 ("const d", 0),
1085 ]
1086 );
1087 }
1088
1089 #[gpui::test]
1090 async fn test_package_json_discovery(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1091 cx.update(|cx| {
1092 settings::init(cx);
1093 Project::init_settings(cx);
1094 language_settings::init(cx);
1095 });
1096
1097 let package_json_1 = json!({
1098 "dependencies": {
1099 "mocha": "1.0.0",
1100 "vitest": "1.0.0"
1101 },
1102 "scripts": {
1103 "test": ""
1104 }
1105 })
1106 .to_string();
1107
1108 let package_json_2 = json!({
1109 "devDependencies": {
1110 "vitest": "2.0.0"
1111 },
1112 "scripts": {
1113 "test": ""
1114 }
1115 })
1116 .to_string();
1117
1118 let fs = FakeFs::new(executor);
1119 fs.insert_tree(
1120 path!("/root"),
1121 json!({
1122 "package.json": package_json_1,
1123 "sub": {
1124 "package.json": package_json_2,
1125 "file.js": "",
1126 }
1127 }),
1128 )
1129 .await;
1130
1131 let provider = TypeScriptContextProvider::new();
1132 let package_json_data = cx
1133 .update(|cx| {
1134 provider.combined_package_json_data(
1135 fs.clone(),
1136 path!("/root").as_ref(),
1137 "sub/file1.js".as_ref(),
1138 cx,
1139 )
1140 })
1141 .await
1142 .unwrap();
1143 pretty_assertions::assert_eq!(
1144 package_json_data,
1145 PackageJsonData {
1146 jest_package_path: None,
1147 mocha_package_path: Some(Path::new(path!("/root/package.json")).into()),
1148 vitest_package_path: Some(Path::new(path!("/root/sub/package.json")).into()),
1149 jasmine_package_path: None,
1150 scripts: [
1151 (
1152 Path::new(path!("/root/package.json")).into(),
1153 "test".to_owned()
1154 ),
1155 (
1156 Path::new(path!("/root/sub/package.json")).into(),
1157 "test".to_owned()
1158 )
1159 ]
1160 .into_iter()
1161 .collect(),
1162 package_manager: None,
1163 }
1164 );
1165
1166 let mut task_templates = TaskTemplates::default();
1167 package_json_data.fill_task_templates(&mut task_templates);
1168 let task_templates = task_templates
1169 .0
1170 .into_iter()
1171 .map(|template| (template.label, template.cwd))
1172 .collect::<Vec<_>>();
1173 pretty_assertions::assert_eq!(
1174 task_templates,
1175 [
1176 (
1177 "vitest file test".into(),
1178 Some("$ZED_CUSTOM_TYPESCRIPT_VITEST_PACKAGE_PATH".into()),
1179 ),
1180 (
1181 "vitest test $ZED_SYMBOL".into(),
1182 Some("$ZED_CUSTOM_TYPESCRIPT_VITEST_PACKAGE_PATH".into()),
1183 ),
1184 (
1185 "mocha file test".into(),
1186 Some("$ZED_CUSTOM_TYPESCRIPT_MOCHA_PACKAGE_PATH".into()),
1187 ),
1188 (
1189 "mocha test $ZED_SYMBOL".into(),
1190 Some("$ZED_CUSTOM_TYPESCRIPT_MOCHA_PACKAGE_PATH".into()),
1191 ),
1192 (
1193 "root/package.json > test".into(),
1194 Some(path!("/root").into())
1195 ),
1196 (
1197 "sub/package.json > test".into(),
1198 Some(path!("/root/sub").into())
1199 ),
1200 ]
1201 );
1202 }
1203}