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