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::github::{build_tarball_url, 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 const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
301 const SERVER_NAME: &'static str = "eslint";
302
303 const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] =
304 &["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs"];
305
306 pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
307 EsLintLspAdapter { node }
308 }
309}
310
311#[async_trait(?Send)]
312impl LspAdapter for EsLintLspAdapter {
313 async fn workspace_configuration(
314 self: Arc<Self>,
315 delegate: &Arc<dyn LspAdapterDelegate>,
316 cx: &mut AsyncAppContext,
317 ) -> Result<Value> {
318 let workspace_root = delegate.worktree_root_path();
319
320 let eslint_user_settings = cx.update(|cx| {
321 ProjectSettings::get_global(cx)
322 .lsp
323 .get(Self::SERVER_NAME)
324 .and_then(|s| s.settings.clone())
325 .unwrap_or_default()
326 })?;
327
328 let mut code_action_on_save = json!({
329 // We enable this, but without also configuring `code_actions_on_format`
330 // in the Zed configuration, it doesn't have an effect.
331 "enable": true,
332 });
333
334 if let Some(code_action_settings) = eslint_user_settings
335 .get("codeActionOnSave")
336 .and_then(|settings| settings.as_object())
337 {
338 if let Some(enable) = code_action_settings.get("enable") {
339 code_action_on_save["enable"] = enable.clone();
340 }
341 if let Some(mode) = code_action_settings.get("mode") {
342 code_action_on_save["mode"] = mode.clone();
343 }
344 if let Some(rules) = code_action_settings.get("rules") {
345 code_action_on_save["rules"] = rules.clone();
346 }
347 }
348
349 let problems = eslint_user_settings
350 .get("problems")
351 .cloned()
352 .unwrap_or_else(|| json!({}));
353
354 let rules_customizations = eslint_user_settings
355 .get("rulesCustomizations")
356 .cloned()
357 .unwrap_or_else(|| json!([]));
358
359 let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
360 let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
361 .iter()
362 .any(|file| workspace_root.join(file).is_file());
363
364 Ok(json!({
365 "": {
366 "validate": "on",
367 "rulesCustomizations": rules_customizations,
368 "run": "onType",
369 "nodePath": node_path,
370 "workingDirectory": {"mode": "auto"},
371 "workspaceFolder": {
372 "uri": workspace_root,
373 "name": workspace_root.file_name()
374 .unwrap_or_else(|| workspace_root.as_os_str()),
375 },
376 "problems": problems,
377 "codeActionOnSave": code_action_on_save,
378 "codeAction": {
379 "disableRuleComment": {
380 "enable": true,
381 "location": "separateLine",
382 },
383 "showDocumentation": {
384 "enable": true
385 }
386 },
387 "experimental": {
388 "useFlatConfig": use_flat_config,
389 },
390 }
391 }))
392 }
393
394 fn name(&self) -> LanguageServerName {
395 LanguageServerName(Self::SERVER_NAME.into())
396 }
397
398 async fn fetch_latest_server_version(
399 &self,
400 _delegate: &dyn LspAdapterDelegate,
401 ) -> Result<Box<dyn 'static + Send + Any>> {
402 let url = build_tarball_url("microsoft/vscode-eslint", Self::CURRENT_VERSION)?;
403
404 Ok(Box::new(GitHubLspBinaryVersion {
405 name: Self::CURRENT_VERSION.into(),
406 url,
407 }))
408 }
409
410 async fn fetch_server_binary(
411 &self,
412 version: Box<dyn 'static + Send + Any>,
413 container_dir: PathBuf,
414 delegate: &dyn LspAdapterDelegate,
415 ) -> Result<LanguageServerBinary> {
416 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
417 let destination_path = container_dir.join(format!("vscode-eslint-{}", version.name));
418 let server_path = destination_path.join(Self::SERVER_PATH);
419
420 if fs::metadata(&server_path).await.is_err() {
421 remove_matching(&container_dir, |entry| entry != destination_path).await;
422
423 let mut response = delegate
424 .http_client()
425 .get(&version.url, Default::default(), true)
426 .await
427 .map_err(|err| anyhow!("error downloading release: {}", err))?;
428 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
429 let archive = Archive::new(decompressed_bytes);
430 archive.unpack(&destination_path).await?;
431
432 let mut dir = fs::read_dir(&destination_path).await?;
433 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
434 let repo_root = destination_path.join("vscode-eslint");
435 fs::rename(first.path(), &repo_root).await?;
436
437 self.node
438 .run_npm_subcommand(Some(&repo_root), "install", &[])
439 .await?;
440
441 self.node
442 .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
443 .await?;
444 }
445
446 Ok(LanguageServerBinary {
447 path: self.node.binary_path().await?,
448 env: None,
449 arguments: eslint_server_binary_arguments(&server_path),
450 })
451 }
452
453 async fn cached_server_binary(
454 &self,
455 container_dir: PathBuf,
456 _: &dyn LspAdapterDelegate,
457 ) -> Option<LanguageServerBinary> {
458 get_cached_eslint_server_binary(container_dir, &*self.node).await
459 }
460
461 async fn installation_test_binary(
462 &self,
463 container_dir: PathBuf,
464 ) -> Option<LanguageServerBinary> {
465 get_cached_eslint_server_binary(container_dir, &*self.node).await
466 }
467}
468
469async fn get_cached_eslint_server_binary(
470 container_dir: PathBuf,
471 node: &dyn NodeRuntime,
472) -> Option<LanguageServerBinary> {
473 maybe!(async {
474 // This is unfortunate but we don't know what the version is to build a path directly
475 let mut dir = fs::read_dir(&container_dir).await?;
476 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
477 if !first.file_type().await?.is_dir() {
478 return Err(anyhow!("First entry is not a directory"));
479 }
480 let server_path = first.path().join(EsLintLspAdapter::SERVER_PATH);
481
482 Ok(LanguageServerBinary {
483 path: node.binary_path().await?,
484 env: None,
485 arguments: eslint_server_binary_arguments(&server_path),
486 })
487 })
488 .await
489 .log_err()
490}
491
492#[cfg(test)]
493mod tests {
494 use gpui::{Context, TestAppContext};
495 use unindent::Unindent;
496
497 #[gpui::test]
498 async fn test_outline(cx: &mut TestAppContext) {
499 let language = crate::language("typescript", tree_sitter_typescript::language_typescript());
500
501 let text = r#"
502 function a() {
503 // local variables are omitted
504 let a1 = 1;
505 // all functions are included
506 async function a2() {}
507 }
508 // top-level variables are included
509 let b: C
510 function getB() {}
511 // exported variables are included
512 export const d = e;
513 "#
514 .unindent();
515
516 let buffer =
517 cx.new_model(|cx| language::Buffer::local(text, cx).with_language(language, cx));
518 let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
519 assert_eq!(
520 outline
521 .items
522 .iter()
523 .map(|item| (item.text.as_str(), item.depth))
524 .collect::<Vec<_>>(),
525 &[
526 ("function a()", 0),
527 ("async function a2()", 1),
528 ("let b", 0),
529 ("function getB()", 0),
530 ("const d", 0),
531 ]
532 );
533 }
534}