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 problems = eslint_user_settings
383 .get("problems")
384 .cloned()
385 .unwrap_or_else(|| json!({}));
386
387 let rules_customizations = eslint_user_settings
388 .get("rulesCustomizations")
389 .cloned()
390 .unwrap_or_else(|| json!([]));
391
392 let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
393 let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
394 .iter()
395 .any(|file| workspace_root.join(file).is_file());
396
397 Ok(json!({
398 "": {
399 "validate": "on",
400 "rulesCustomizations": rules_customizations,
401 "run": "onType",
402 "nodePath": node_path,
403 "workingDirectory": {"mode": "auto"},
404 "workspaceFolder": {
405 "uri": workspace_root,
406 "name": workspace_root.file_name()
407 .unwrap_or(workspace_root.as_os_str()),
408 },
409 "problems": problems,
410 "codeActionOnSave": code_action_on_save,
411 "codeAction": {
412 "disableRuleComment": {
413 "enable": true,
414 "location": "separateLine",
415 },
416 "showDocumentation": {
417 "enable": true
418 }
419 },
420 "experimental": {
421 "useFlatConfig": use_flat_config,
422 },
423 }
424 }))
425 }
426
427 fn name(&self) -> LanguageServerName {
428 Self::SERVER_NAME.clone()
429 }
430
431 async fn fetch_latest_server_version(
432 &self,
433 _delegate: &dyn LspAdapterDelegate,
434 ) -> Result<Box<dyn 'static + Send + Any>> {
435 let url = build_asset_url(
436 "zed-industries/vscode-eslint",
437 Self::CURRENT_VERSION_TAG_NAME,
438 Self::GITHUB_ASSET_KIND,
439 )?;
440
441 Ok(Box::new(GitHubLspBinaryVersion {
442 name: Self::CURRENT_VERSION.into(),
443 url,
444 }))
445 }
446
447 async fn fetch_server_binary(
448 &self,
449 version: Box<dyn 'static + Send + Any>,
450 container_dir: PathBuf,
451 delegate: &dyn LspAdapterDelegate,
452 ) -> Result<LanguageServerBinary> {
453 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
454 let destination_path = Self::build_destination_path(&container_dir);
455 let server_path = destination_path.join(Self::SERVER_PATH);
456
457 if fs::metadata(&server_path).await.is_err() {
458 remove_matching(&container_dir, |entry| entry != destination_path).await;
459
460 let mut response = delegate
461 .http_client()
462 .get(&version.url, Default::default(), true)
463 .await
464 .map_err(|err| anyhow!("error downloading release: {}", err))?;
465 match Self::GITHUB_ASSET_KIND {
466 AssetKind::TarGz => {
467 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
468 let archive = Archive::new(decompressed_bytes);
469 archive.unpack(&destination_path).await.with_context(|| {
470 format!("extracting {} to {:?}", version.url, destination_path)
471 })?;
472 }
473 AssetKind::Gz => {
474 let mut decompressed_bytes =
475 GzipDecoder::new(BufReader::new(response.body_mut()));
476 let mut file =
477 fs::File::create(&destination_path).await.with_context(|| {
478 format!(
479 "creating a file {:?} for a download from {}",
480 destination_path, version.url,
481 )
482 })?;
483 futures::io::copy(&mut decompressed_bytes, &mut file)
484 .await
485 .with_context(|| {
486 format!("extracting {} to {:?}", version.url, destination_path)
487 })?;
488 }
489 AssetKind::Zip => {
490 node_runtime::extract_zip(
491 &destination_path,
492 BufReader::new(response.body_mut()),
493 )
494 .await
495 .with_context(|| {
496 format!("unzipping {} to {:?}", version.url, destination_path)
497 })?;
498 }
499 }
500
501 let mut dir = fs::read_dir(&destination_path).await?;
502 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
503 let repo_root = destination_path.join("vscode-eslint");
504 fs::rename(first.path(), &repo_root).await?;
505
506 #[cfg(target_os = "windows")]
507 {
508 handle_symlink(
509 repo_root.join("$shared"),
510 repo_root.join("client").join("src").join("shared"),
511 )
512 .await?;
513 handle_symlink(
514 repo_root.join("$shared"),
515 repo_root.join("server").join("src").join("shared"),
516 )
517 .await?;
518 }
519
520 self.node
521 .run_npm_subcommand(&repo_root, "install", &[])
522 .await?;
523
524 self.node
525 .run_npm_subcommand(&repo_root, "run-script", &["compile"])
526 .await?;
527 }
528
529 Ok(LanguageServerBinary {
530 path: self.node.binary_path().await?,
531 env: None,
532 arguments: eslint_server_binary_arguments(&server_path),
533 })
534 }
535
536 async fn cached_server_binary(
537 &self,
538 container_dir: PathBuf,
539 _: &dyn LspAdapterDelegate,
540 ) -> Option<LanguageServerBinary> {
541 let server_path =
542 Self::build_destination_path(&container_dir).join(EsLintLspAdapter::SERVER_PATH);
543 Some(LanguageServerBinary {
544 path: self.node.binary_path().await.ok()?,
545 env: None,
546 arguments: eslint_server_binary_arguments(&server_path),
547 })
548 }
549}
550
551#[cfg(target_os = "windows")]
552async fn handle_symlink(src_dir: PathBuf, dest_dir: PathBuf) -> Result<()> {
553 if fs::metadata(&src_dir).await.is_err() {
554 return Err(anyhow!("Directory {} not present.", src_dir.display()));
555 }
556 if fs::metadata(&dest_dir).await.is_ok() {
557 fs::remove_file(&dest_dir).await?;
558 }
559 fs::create_dir_all(&dest_dir).await?;
560 let mut entries = fs::read_dir(&src_dir).await?;
561 while let Some(entry) = entries.try_next().await? {
562 let entry_path = entry.path();
563 let entry_name = entry.file_name();
564 let dest_path = dest_dir.join(&entry_name);
565 fs::copy(&entry_path, &dest_path).await?;
566 }
567 Ok(())
568}
569
570#[cfg(test)]
571mod tests {
572 use gpui::{Context, TestAppContext};
573 use unindent::Unindent;
574
575 #[gpui::test]
576 async fn test_outline(cx: &mut TestAppContext) {
577 let language = crate::language(
578 "typescript",
579 tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
580 );
581
582 let text = r#"
583 function a() {
584 // local variables are omitted
585 let a1 = 1;
586 // all functions are included
587 async function a2() {}
588 }
589 // top-level variables are included
590 let b: C
591 function getB() {}
592 // exported variables are included
593 export const d = e;
594 "#
595 .unindent();
596
597 let buffer =
598 cx.new_model(|cx| language::Buffer::local(text, cx).with_language(language, cx));
599 let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
600 assert_eq!(
601 outline
602 .items
603 .iter()
604 .map(|item| (item.text.as_str(), item.depth))
605 .collect::<Vec<_>>(),
606 &[
607 ("function a()", 0),
608 ("async function a2()", 1),
609 ("let b", 0),
610 ("function getB()", 0),
611 ("const d", 0),
612 ]
613 );
614 }
615}