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
72 pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
73 TypeScriptLspAdapter { node }
74 }
75}
76
77struct TypeScriptVersions {
78 typescript_version: String,
79 server_version: String,
80}
81
82#[async_trait(?Send)]
83impl LspAdapter for TypeScriptLspAdapter {
84 fn name(&self) -> LanguageServerName {
85 LanguageServerName("typescript-language-server".into())
86 }
87
88 async fn fetch_latest_server_version(
89 &self,
90 _: &dyn LspAdapterDelegate,
91 ) -> Result<Box<dyn 'static + Send + Any>> {
92 Ok(Box::new(TypeScriptVersions {
93 typescript_version: self.node.npm_package_latest_version("typescript").await?,
94 server_version: self
95 .node
96 .npm_package_latest_version("typescript-language-server")
97 .await?,
98 }) as Box<_>)
99 }
100
101 async fn fetch_server_binary(
102 &self,
103 latest_version: Box<dyn 'static + Send + Any>,
104 container_dir: PathBuf,
105 _: &dyn LspAdapterDelegate,
106 ) -> Result<LanguageServerBinary> {
107 let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
108 let server_path = container_dir.join(Self::NEW_SERVER_PATH);
109 let package_name = "typescript";
110
111 let should_install_language_server = self
112 .node
113 .should_install_npm_package(
114 package_name,
115 &server_path,
116 &container_dir,
117 latest_version.typescript_version.as_str(),
118 )
119 .await;
120
121 if should_install_language_server {
122 self.node
123 .npm_install_packages(
124 &container_dir,
125 &[
126 (package_name, latest_version.typescript_version.as_str()),
127 (
128 "typescript-language-server",
129 latest_version.server_version.as_str(),
130 ),
131 ],
132 )
133 .await?;
134 }
135
136 Ok(LanguageServerBinary {
137 path: self.node.binary_path().await?,
138 env: None,
139 arguments: typescript_server_binary_arguments(&server_path),
140 })
141 }
142
143 async fn cached_server_binary(
144 &self,
145 container_dir: PathBuf,
146 _: &dyn LspAdapterDelegate,
147 ) -> Option<LanguageServerBinary> {
148 get_cached_ts_server_binary(container_dir, &*self.node).await
149 }
150
151 async fn installation_test_binary(
152 &self,
153 container_dir: PathBuf,
154 ) -> Option<LanguageServerBinary> {
155 get_cached_ts_server_binary(container_dir, &*self.node).await
156 }
157
158 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
159 Some(vec![
160 CodeActionKind::QUICKFIX,
161 CodeActionKind::REFACTOR,
162 CodeActionKind::REFACTOR_EXTRACT,
163 CodeActionKind::SOURCE,
164 ])
165 }
166
167 async fn label_for_completion(
168 &self,
169 item: &lsp::CompletionItem,
170 language: &Arc<language::Language>,
171 ) -> Option<language::CodeLabel> {
172 use lsp::CompletionItemKind as Kind;
173 let len = item.label.len();
174 let grammar = language.grammar()?;
175 let highlight_id = match item.kind? {
176 Kind::CLASS | Kind::INTERFACE | Kind::ENUM => grammar.highlight_id_for_name("type"),
177 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
178 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
179 Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
180 Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
181 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
182 _ => None,
183 }?;
184
185 let text = match &item.detail {
186 Some(detail) => format!("{} {}", item.label, detail),
187 None => item.label.clone(),
188 };
189
190 Some(language::CodeLabel {
191 text,
192 runs: vec![(0..len, highlight_id)],
193 filter_range: 0..len,
194 })
195 }
196
197 async fn initialization_options(
198 self: Arc<Self>,
199 _: &Arc<dyn LspAdapterDelegate>,
200 ) -> Result<Option<serde_json::Value>> {
201 Ok(Some(json!({
202 "provideFormatter": true,
203 "tsserver": {
204 "path": "node_modules/typescript/lib",
205 },
206 "preferences": {
207 "includeInlayParameterNameHints": "all",
208 "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
209 "includeInlayFunctionParameterTypeHints": true,
210 "includeInlayVariableTypeHints": true,
211 "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
212 "includeInlayPropertyDeclarationTypeHints": true,
213 "includeInlayFunctionLikeReturnTypeHints": true,
214 "includeInlayEnumMemberValueHints": true,
215 }
216 })))
217 }
218
219 async fn workspace_configuration(
220 self: Arc<Self>,
221 _: &Arc<dyn LspAdapterDelegate>,
222 _cx: &mut AsyncAppContext,
223 ) -> Result<Value> {
224 Ok(json!({
225 "completions": {
226 "completeFunctionCalls": true
227 }
228 }))
229 }
230
231 fn language_ids(&self) -> HashMap<String, String> {
232 HashMap::from_iter([
233 ("TypeScript".into(), "typescript".into()),
234 ("JavaScript".into(), "javascript".into()),
235 ("TSX".into(), "typescriptreact".into()),
236 ])
237 }
238}
239
240async fn get_cached_ts_server_binary(
241 container_dir: PathBuf,
242 node: &dyn NodeRuntime,
243) -> Option<LanguageServerBinary> {
244 maybe!(async {
245 let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
246 let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
247 if new_server_path.exists() {
248 Ok(LanguageServerBinary {
249 path: node.binary_path().await?,
250 env: None,
251 arguments: typescript_server_binary_arguments(&new_server_path),
252 })
253 } else if old_server_path.exists() {
254 Ok(LanguageServerBinary {
255 path: node.binary_path().await?,
256 env: None,
257 arguments: typescript_server_binary_arguments(&old_server_path),
258 })
259 } else {
260 Err(anyhow!(
261 "missing executable in directory {:?}",
262 container_dir
263 ))
264 }
265 })
266 .await
267 .log_err()
268}
269
270pub struct EsLintLspAdapter {
271 node: Arc<dyn NodeRuntime>,
272}
273
274impl EsLintLspAdapter {
275 const CURRENT_VERSION: &'static str = "release/2.4.4";
276
277 const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
278 const SERVER_NAME: &'static str = "eslint";
279
280 const FLAT_CONFIG_FILE_NAMES: &'static [&'static str] =
281 &["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs"];
282
283 pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
284 EsLintLspAdapter { node }
285 }
286}
287
288#[async_trait(?Send)]
289impl LspAdapter for EsLintLspAdapter {
290 async fn workspace_configuration(
291 self: Arc<Self>,
292 delegate: &Arc<dyn LspAdapterDelegate>,
293 cx: &mut AsyncAppContext,
294 ) -> Result<Value> {
295 let workspace_root = delegate.worktree_root_path();
296
297 let eslint_user_settings = cx.update(|cx| {
298 ProjectSettings::get_global(cx)
299 .lsp
300 .get(Self::SERVER_NAME)
301 .and_then(|s| s.settings.clone())
302 .unwrap_or_default()
303 })?;
304
305 let mut code_action_on_save = json!({
306 // We enable this, but without also configuring `code_actions_on_format`
307 // in the Zed configuration, it doesn't have an effect.
308 "enable": true,
309 });
310
311 if let Some(code_action_settings) = eslint_user_settings
312 .get("codeActionOnSave")
313 .and_then(|settings| settings.as_object())
314 {
315 if let Some(enable) = code_action_settings.get("enable") {
316 code_action_on_save["enable"] = enable.clone();
317 }
318 if let Some(mode) = code_action_settings.get("mode") {
319 code_action_on_save["mode"] = mode.clone();
320 }
321 if let Some(rules) = code_action_settings.get("rules") {
322 code_action_on_save["rules"] = rules.clone();
323 }
324 }
325
326 let problems = eslint_user_settings
327 .get("problems")
328 .cloned()
329 .unwrap_or_else(|| json!({}));
330
331 let rules_customizations = eslint_user_settings
332 .get("rulesCustomizations")
333 .cloned()
334 .unwrap_or_else(|| json!([]));
335
336 let node_path = eslint_user_settings.get("nodePath").unwrap_or(&Value::Null);
337 let use_flat_config = Self::FLAT_CONFIG_FILE_NAMES
338 .iter()
339 .any(|file| workspace_root.join(file).is_file());
340
341 Ok(json!({
342 "": {
343 "validate": "on",
344 "rulesCustomizations": rules_customizations,
345 "run": "onType",
346 "nodePath": node_path,
347 "workingDirectory": {"mode": "auto"},
348 "workspaceFolder": {
349 "uri": workspace_root,
350 "name": workspace_root.file_name()
351 .unwrap_or_else(|| workspace_root.as_os_str()),
352 },
353 "problems": problems,
354 "codeActionOnSave": code_action_on_save,
355 "codeAction": {
356 "disableRuleComment": {
357 "enable": true,
358 "location": "separateLine",
359 },
360 "showDocumentation": {
361 "enable": true
362 }
363 },
364 "experimental": {
365 "useFlatConfig": use_flat_config,
366 },
367 }
368 }))
369 }
370
371 fn name(&self) -> LanguageServerName {
372 LanguageServerName(Self::SERVER_NAME.into())
373 }
374
375 async fn fetch_latest_server_version(
376 &self,
377 _delegate: &dyn LspAdapterDelegate,
378 ) -> Result<Box<dyn 'static + Send + Any>> {
379 let url = build_tarball_url("microsoft/vscode-eslint", Self::CURRENT_VERSION)?;
380
381 Ok(Box::new(GitHubLspBinaryVersion {
382 name: Self::CURRENT_VERSION.into(),
383 url,
384 }))
385 }
386
387 async fn fetch_server_binary(
388 &self,
389 version: Box<dyn 'static + Send + Any>,
390 container_dir: PathBuf,
391 delegate: &dyn LspAdapterDelegate,
392 ) -> Result<LanguageServerBinary> {
393 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
394 let destination_path = container_dir.join(format!("vscode-eslint-{}", version.name));
395 let server_path = destination_path.join(Self::SERVER_PATH);
396
397 if fs::metadata(&server_path).await.is_err() {
398 remove_matching(&container_dir, |entry| entry != destination_path).await;
399
400 let mut response = delegate
401 .http_client()
402 .get(&version.url, Default::default(), true)
403 .await
404 .map_err(|err| anyhow!("error downloading release: {}", err))?;
405 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
406 let archive = Archive::new(decompressed_bytes);
407 archive.unpack(&destination_path).await?;
408
409 let mut dir = fs::read_dir(&destination_path).await?;
410 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
411 let repo_root = destination_path.join("vscode-eslint");
412 fs::rename(first.path(), &repo_root).await?;
413
414 self.node
415 .run_npm_subcommand(Some(&repo_root), "install", &[])
416 .await?;
417
418 self.node
419 .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
420 .await?;
421 }
422
423 Ok(LanguageServerBinary {
424 path: self.node.binary_path().await?,
425 env: None,
426 arguments: eslint_server_binary_arguments(&server_path),
427 })
428 }
429
430 async fn cached_server_binary(
431 &self,
432 container_dir: PathBuf,
433 _: &dyn LspAdapterDelegate,
434 ) -> Option<LanguageServerBinary> {
435 get_cached_eslint_server_binary(container_dir, &*self.node).await
436 }
437
438 async fn installation_test_binary(
439 &self,
440 container_dir: PathBuf,
441 ) -> Option<LanguageServerBinary> {
442 get_cached_eslint_server_binary(container_dir, &*self.node).await
443 }
444}
445
446async fn get_cached_eslint_server_binary(
447 container_dir: PathBuf,
448 node: &dyn NodeRuntime,
449) -> Option<LanguageServerBinary> {
450 maybe!(async {
451 // This is unfortunate but we don't know what the version is to build a path directly
452 let mut dir = fs::read_dir(&container_dir).await?;
453 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
454 if !first.file_type().await?.is_dir() {
455 return Err(anyhow!("First entry is not a directory"));
456 }
457 let server_path = first.path().join(EsLintLspAdapter::SERVER_PATH);
458
459 Ok(LanguageServerBinary {
460 path: node.binary_path().await?,
461 env: None,
462 arguments: eslint_server_binary_arguments(&server_path),
463 })
464 })
465 .await
466 .log_err()
467}
468
469#[cfg(test)]
470mod tests {
471 use gpui::{Context, TestAppContext};
472 use unindent::Unindent;
473
474 #[gpui::test]
475 async fn test_outline(cx: &mut TestAppContext) {
476 let language = crate::language("typescript", tree_sitter_typescript::language_typescript());
477
478 let text = r#"
479 function a() {
480 // local variables are omitted
481 let a1 = 1;
482 // all functions are included
483 async function a2() {}
484 }
485 // top-level variables are included
486 let b: C
487 function getB() {}
488 // exported variables are included
489 export const d = e;
490 "#
491 .unindent();
492
493 let buffer =
494 cx.new_model(|cx| language::Buffer::local(text, cx).with_language(language, cx));
495 let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
496 assert_eq!(
497 outline
498 .items
499 .iter()
500 .map(|item| (item.text.as_str(), item.depth))
501 .collect::<Vec<_>>(),
502 &[
503 ("function a()", 0),
504 ("async function a2()", 1),
505 ("let b", 0),
506 ("function getB()", 0),
507 ("const d", 0),
508 ]
509 );
510 }
511}