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