1use crate::wasm_host::{wit::ToWasmtimeResult, WasmState};
2use ::http_client::{AsyncBody, HttpRequestExt};
3use ::settings::{Settings, WorktreeId};
4use anyhow::{anyhow, bail, Context, Result};
5use async_compression::futures::bufread::GzipDecoder;
6use async_tar::Archive;
7use async_trait::async_trait;
8use extension::{ExtensionLanguageServerProxy, KeyValueStoreDelegate, WorktreeDelegate};
9use futures::{io::BufReader, FutureExt as _};
10use futures::{lock::Mutex, AsyncReadExt};
11use language::LanguageName;
12use language::{language_settings::AllLanguageSettings, LanguageServerBinaryStatus};
13use project::project_settings::ProjectSettings;
14use semantic_version::SemanticVersion;
15use std::{
16 path::{Path, PathBuf},
17 sync::{Arc, OnceLock},
18};
19use util::maybe;
20use wasmtime::component::{Linker, Resource};
21
22use super::latest;
23
24pub const MIN_VERSION: SemanticVersion = SemanticVersion::new(0, 1, 0);
25
26wasmtime::component::bindgen!({
27 async: true,
28 trappable_imports: true,
29 path: "../extension_api/wit/since_v0.1.0",
30 with: {
31 "worktree": ExtensionWorktree,
32 "key-value-store": ExtensionKeyValueStore,
33 "zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream,
34 "zed:extension/github": latest::zed::extension::github,
35 "zed:extension/nodejs": latest::zed::extension::nodejs,
36 "zed:extension/platform": latest::zed::extension::platform,
37 "zed:extension/slash-command": latest::zed::extension::slash_command,
38 },
39});
40
41pub use self::zed::extension::*;
42
43mod settings {
44 include!(concat!(env!("OUT_DIR"), "/since_v0.1.0/settings.rs"));
45}
46
47pub type ExtensionWorktree = Arc<dyn WorktreeDelegate>;
48pub type ExtensionKeyValueStore = Arc<dyn KeyValueStoreDelegate>;
49pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBody>>>;
50
51pub fn linker() -> &'static Linker<WasmState> {
52 static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
53 LINKER.get_or_init(|| super::new_linker(Extension::add_to_linker))
54}
55
56impl From<Command> for latest::Command {
57 fn from(value: Command) -> Self {
58 Self {
59 command: value.command,
60 args: value.args,
61 env: value.env,
62 }
63 }
64}
65
66impl From<SettingsLocation> for latest::SettingsLocation {
67 fn from(value: SettingsLocation) -> Self {
68 Self {
69 worktree_id: value.worktree_id,
70 path: value.path,
71 }
72 }
73}
74
75impl From<LanguageServerInstallationStatus> for latest::LanguageServerInstallationStatus {
76 fn from(value: LanguageServerInstallationStatus) -> Self {
77 match value {
78 LanguageServerInstallationStatus::None => Self::None,
79 LanguageServerInstallationStatus::Downloading => Self::Downloading,
80 LanguageServerInstallationStatus::CheckingForUpdate => Self::CheckingForUpdate,
81 LanguageServerInstallationStatus::Failed(message) => Self::Failed(message),
82 }
83 }
84}
85
86impl From<DownloadedFileType> for latest::DownloadedFileType {
87 fn from(value: DownloadedFileType) -> Self {
88 match value {
89 DownloadedFileType::Gzip => Self::Gzip,
90 DownloadedFileType::GzipTar => Self::GzipTar,
91 DownloadedFileType::Zip => Self::Zip,
92 DownloadedFileType::Uncompressed => Self::Uncompressed,
93 }
94 }
95}
96
97impl From<Range> for latest::Range {
98 fn from(value: Range) -> Self {
99 Self {
100 start: value.start,
101 end: value.end,
102 }
103 }
104}
105
106impl From<CodeLabelSpan> for latest::CodeLabelSpan {
107 fn from(value: CodeLabelSpan) -> Self {
108 match value {
109 CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
110 CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
111 }
112 }
113}
114
115impl From<CodeLabelSpanLiteral> for latest::CodeLabelSpanLiteral {
116 fn from(value: CodeLabelSpanLiteral) -> Self {
117 Self {
118 text: value.text,
119 highlight_name: value.highlight_name,
120 }
121 }
122}
123
124impl From<CodeLabel> for latest::CodeLabel {
125 fn from(value: CodeLabel) -> Self {
126 Self {
127 code: value.code,
128 spans: value.spans.into_iter().map(Into::into).collect(),
129 filter_range: value.filter_range.into(),
130 }
131 }
132}
133
134impl From<latest::Completion> for Completion {
135 fn from(value: latest::Completion) -> Self {
136 Self {
137 label: value.label,
138 detail: value.detail,
139 kind: value.kind.map(Into::into),
140 insert_text_format: value.insert_text_format.map(Into::into),
141 }
142 }
143}
144
145impl From<latest::lsp::CompletionKind> for lsp::CompletionKind {
146 fn from(value: latest::lsp::CompletionKind) -> Self {
147 match value {
148 latest::lsp::CompletionKind::Text => Self::Text,
149 latest::lsp::CompletionKind::Method => Self::Method,
150 latest::lsp::CompletionKind::Function => Self::Function,
151 latest::lsp::CompletionKind::Constructor => Self::Constructor,
152 latest::lsp::CompletionKind::Field => Self::Field,
153 latest::lsp::CompletionKind::Variable => Self::Variable,
154 latest::lsp::CompletionKind::Class => Self::Class,
155 latest::lsp::CompletionKind::Interface => Self::Interface,
156 latest::lsp::CompletionKind::Module => Self::Module,
157 latest::lsp::CompletionKind::Property => Self::Property,
158 latest::lsp::CompletionKind::Unit => Self::Unit,
159 latest::lsp::CompletionKind::Value => Self::Value,
160 latest::lsp::CompletionKind::Enum => Self::Enum,
161 latest::lsp::CompletionKind::Keyword => Self::Keyword,
162 latest::lsp::CompletionKind::Snippet => Self::Snippet,
163 latest::lsp::CompletionKind::Color => Self::Color,
164 latest::lsp::CompletionKind::File => Self::File,
165 latest::lsp::CompletionKind::Reference => Self::Reference,
166 latest::lsp::CompletionKind::Folder => Self::Folder,
167 latest::lsp::CompletionKind::EnumMember => Self::EnumMember,
168 latest::lsp::CompletionKind::Constant => Self::Constant,
169 latest::lsp::CompletionKind::Struct => Self::Struct,
170 latest::lsp::CompletionKind::Event => Self::Event,
171 latest::lsp::CompletionKind::Operator => Self::Operator,
172 latest::lsp::CompletionKind::TypeParameter => Self::TypeParameter,
173 latest::lsp::CompletionKind::Other(kind) => Self::Other(kind),
174 }
175 }
176}
177
178impl From<latest::lsp::InsertTextFormat> for lsp::InsertTextFormat {
179 fn from(value: latest::lsp::InsertTextFormat) -> Self {
180 match value {
181 latest::lsp::InsertTextFormat::PlainText => Self::PlainText,
182 latest::lsp::InsertTextFormat::Snippet => Self::Snippet,
183 latest::lsp::InsertTextFormat::Other(value) => Self::Other(value),
184 }
185 }
186}
187
188impl From<latest::lsp::Symbol> for lsp::Symbol {
189 fn from(value: latest::lsp::Symbol) -> Self {
190 Self {
191 name: value.name,
192 kind: value.kind.into(),
193 }
194 }
195}
196
197impl From<latest::lsp::SymbolKind> for lsp::SymbolKind {
198 fn from(value: latest::lsp::SymbolKind) -> Self {
199 match value {
200 latest::lsp::SymbolKind::File => Self::File,
201 latest::lsp::SymbolKind::Module => Self::Module,
202 latest::lsp::SymbolKind::Namespace => Self::Namespace,
203 latest::lsp::SymbolKind::Package => Self::Package,
204 latest::lsp::SymbolKind::Class => Self::Class,
205 latest::lsp::SymbolKind::Method => Self::Method,
206 latest::lsp::SymbolKind::Property => Self::Property,
207 latest::lsp::SymbolKind::Field => Self::Field,
208 latest::lsp::SymbolKind::Constructor => Self::Constructor,
209 latest::lsp::SymbolKind::Enum => Self::Enum,
210 latest::lsp::SymbolKind::Interface => Self::Interface,
211 latest::lsp::SymbolKind::Function => Self::Function,
212 latest::lsp::SymbolKind::Variable => Self::Variable,
213 latest::lsp::SymbolKind::Constant => Self::Constant,
214 latest::lsp::SymbolKind::String => Self::String,
215 latest::lsp::SymbolKind::Number => Self::Number,
216 latest::lsp::SymbolKind::Boolean => Self::Boolean,
217 latest::lsp::SymbolKind::Array => Self::Array,
218 latest::lsp::SymbolKind::Object => Self::Object,
219 latest::lsp::SymbolKind::Key => Self::Key,
220 latest::lsp::SymbolKind::Null => Self::Null,
221 latest::lsp::SymbolKind::EnumMember => Self::EnumMember,
222 latest::lsp::SymbolKind::Struct => Self::Struct,
223 latest::lsp::SymbolKind::Event => Self::Event,
224 latest::lsp::SymbolKind::Operator => Self::Operator,
225 latest::lsp::SymbolKind::TypeParameter => Self::TypeParameter,
226 latest::lsp::SymbolKind::Other(kind) => Self::Other(kind),
227 }
228 }
229}
230
231#[async_trait]
232impl HostKeyValueStore for WasmState {
233 async fn insert(
234 &mut self,
235 kv_store: Resource<ExtensionKeyValueStore>,
236 key: String,
237 value: String,
238 ) -> wasmtime::Result<Result<(), String>> {
239 let kv_store = self.table.get(&kv_store)?;
240 kv_store.insert(key, value).await.to_wasmtime_result()
241 }
242
243 fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
244 // We only ever hand out borrows of key-value stores.
245 Ok(())
246 }
247}
248
249#[async_trait]
250impl HostWorktree for WasmState {
251 async fn id(&mut self, delegate: Resource<Arc<dyn WorktreeDelegate>>) -> wasmtime::Result<u64> {
252 latest::HostWorktree::id(self, delegate).await
253 }
254
255 async fn root_path(
256 &mut self,
257 delegate: Resource<Arc<dyn WorktreeDelegate>>,
258 ) -> wasmtime::Result<String> {
259 latest::HostWorktree::root_path(self, delegate).await
260 }
261
262 async fn read_text_file(
263 &mut self,
264 delegate: Resource<Arc<dyn WorktreeDelegate>>,
265 path: String,
266 ) -> wasmtime::Result<Result<String, String>> {
267 latest::HostWorktree::read_text_file(self, delegate, path).await
268 }
269
270 async fn shell_env(
271 &mut self,
272 delegate: Resource<Arc<dyn WorktreeDelegate>>,
273 ) -> wasmtime::Result<EnvVars> {
274 latest::HostWorktree::shell_env(self, delegate).await
275 }
276
277 async fn which(
278 &mut self,
279 delegate: Resource<Arc<dyn WorktreeDelegate>>,
280 binary_name: String,
281 ) -> wasmtime::Result<Option<String>> {
282 latest::HostWorktree::which(self, delegate, binary_name).await
283 }
284
285 fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
286 // We only ever hand out borrows of worktrees.
287 Ok(())
288 }
289}
290
291#[async_trait]
292impl common::Host for WasmState {}
293
294#[async_trait]
295impl http_client::Host for WasmState {
296 async fn fetch(
297 &mut self,
298 request: http_client::HttpRequest,
299 ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
300 maybe!(async {
301 let url = &request.url;
302 let request = convert_request(&request)?;
303 let mut response = self.host.http_client.send(request).await?;
304
305 if response.status().is_client_error() || response.status().is_server_error() {
306 bail!("failed to fetch '{url}': status code {}", response.status())
307 }
308 convert_response(&mut response).await
309 })
310 .await
311 .to_wasmtime_result()
312 }
313
314 async fn fetch_stream(
315 &mut self,
316 request: http_client::HttpRequest,
317 ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
318 let request = convert_request(&request)?;
319 let response = self.host.http_client.send(request);
320 maybe!(async {
321 let response = response.await?;
322 let stream = Arc::new(Mutex::new(response));
323 let resource = self.table.push(stream)?;
324 Ok(resource)
325 })
326 .await
327 .to_wasmtime_result()
328 }
329}
330
331#[async_trait]
332impl http_client::HostHttpResponseStream for WasmState {
333 async fn next_chunk(
334 &mut self,
335 resource: Resource<ExtensionHttpResponseStream>,
336 ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
337 let stream = self.table.get(&resource)?.clone();
338 maybe!(async move {
339 let mut response = stream.lock().await;
340 let mut buffer = vec![0; 8192]; // 8KB buffer
341 let bytes_read = response.body_mut().read(&mut buffer).await?;
342 if bytes_read == 0 {
343 Ok(None)
344 } else {
345 buffer.truncate(bytes_read);
346 Ok(Some(buffer))
347 }
348 })
349 .await
350 .to_wasmtime_result()
351 }
352
353 fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
354 Ok(())
355 }
356}
357
358impl From<http_client::HttpMethod> for ::http_client::Method {
359 fn from(value: http_client::HttpMethod) -> Self {
360 match value {
361 http_client::HttpMethod::Get => Self::GET,
362 http_client::HttpMethod::Post => Self::POST,
363 http_client::HttpMethod::Put => Self::PUT,
364 http_client::HttpMethod::Delete => Self::DELETE,
365 http_client::HttpMethod::Head => Self::HEAD,
366 http_client::HttpMethod::Options => Self::OPTIONS,
367 http_client::HttpMethod::Patch => Self::PATCH,
368 }
369 }
370}
371
372fn convert_request(
373 extension_request: &http_client::HttpRequest,
374) -> Result<::http_client::Request<AsyncBody>, anyhow::Error> {
375 let mut request = ::http_client::Request::builder()
376 .method(::http_client::Method::from(extension_request.method))
377 .uri(&extension_request.url)
378 .follow_redirects(match extension_request.redirect_policy {
379 http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
380 http_client::RedirectPolicy::FollowLimit(limit) => {
381 ::http_client::RedirectPolicy::FollowLimit(limit)
382 }
383 http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
384 });
385 for (key, value) in &extension_request.headers {
386 request = request.header(key, value);
387 }
388 let body = extension_request
389 .body
390 .clone()
391 .map(AsyncBody::from)
392 .unwrap_or_default();
393 request.body(body).map_err(anyhow::Error::from)
394}
395
396async fn convert_response(
397 response: &mut ::http_client::Response<AsyncBody>,
398) -> Result<http_client::HttpResponse, anyhow::Error> {
399 let mut extension_response = http_client::HttpResponse {
400 body: Vec::new(),
401 headers: Vec::new(),
402 };
403
404 for (key, value) in response.headers() {
405 extension_response
406 .headers
407 .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
408 }
409
410 response
411 .body_mut()
412 .read_to_end(&mut extension_response.body)
413 .await?;
414
415 Ok(extension_response)
416}
417
418#[async_trait]
419impl lsp::Host for WasmState {}
420
421#[async_trait]
422impl ExtensionImports for WasmState {
423 async fn get_settings(
424 &mut self,
425 location: Option<self::SettingsLocation>,
426 category: String,
427 key: Option<String>,
428 ) -> wasmtime::Result<Result<String, String>> {
429 self.on_main_thread(|cx| {
430 async move {
431 let location = location
432 .as_ref()
433 .map(|location| ::settings::SettingsLocation {
434 worktree_id: WorktreeId::from_proto(location.worktree_id),
435 path: Path::new(&location.path),
436 });
437
438 cx.update(|cx| match category.as_str() {
439 "language" => {
440 let key = key.map(|k| LanguageName::new(&k));
441 let settings = AllLanguageSettings::get(location, cx).language(
442 location,
443 key.as_ref(),
444 cx,
445 );
446 Ok(serde_json::to_string(&settings::LanguageSettings {
447 tab_size: settings.tab_size,
448 })?)
449 }
450 "lsp" => {
451 let settings = key
452 .and_then(|key| {
453 ProjectSettings::get(location, cx)
454 .lsp
455 .get(&::lsp::LanguageServerName(key.into()))
456 })
457 .cloned()
458 .unwrap_or_default();
459 Ok(serde_json::to_string(&settings::LspSettings {
460 binary: settings.binary.map(|binary| settings::BinarySettings {
461 path: binary.path,
462 arguments: binary.arguments,
463 }),
464 settings: settings.settings,
465 initialization_options: settings.initialization_options,
466 })?)
467 }
468 _ => {
469 bail!("Unknown settings category: {}", category);
470 }
471 })
472 }
473 .boxed_local()
474 })
475 .await?
476 .to_wasmtime_result()
477 }
478
479 async fn set_language_server_installation_status(
480 &mut self,
481 server_name: String,
482 status: LanguageServerInstallationStatus,
483 ) -> wasmtime::Result<()> {
484 let status = match status {
485 LanguageServerInstallationStatus::CheckingForUpdate => {
486 LanguageServerBinaryStatus::CheckingForUpdate
487 }
488 LanguageServerInstallationStatus::Downloading => {
489 LanguageServerBinaryStatus::Downloading
490 }
491 LanguageServerInstallationStatus::None => LanguageServerBinaryStatus::None,
492 LanguageServerInstallationStatus::Failed(error) => {
493 LanguageServerBinaryStatus::Failed { error }
494 }
495 };
496
497 self.host
498 .proxy
499 .update_language_server_status(::lsp::LanguageServerName(server_name.into()), status);
500
501 Ok(())
502 }
503
504 async fn download_file(
505 &mut self,
506 url: String,
507 path: String,
508 file_type: DownloadedFileType,
509 ) -> wasmtime::Result<Result<(), String>> {
510 maybe!(async {
511 let path = PathBuf::from(path);
512 let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
513
514 self.host.fs.create_dir(&extension_work_dir).await?;
515
516 let destination_path = self
517 .host
518 .writeable_path_from_extension(&self.manifest.id, &path)?;
519
520 let mut response = self
521 .host
522 .http_client
523 .get(&url, Default::default(), true)
524 .await
525 .map_err(|err| anyhow!("error downloading release: {}", err))?;
526
527 if !response.status().is_success() {
528 Err(anyhow!(
529 "download failed with status {}",
530 response.status().to_string()
531 ))?;
532 }
533 let body = BufReader::new(response.body_mut());
534
535 match file_type {
536 DownloadedFileType::Uncompressed => {
537 futures::pin_mut!(body);
538 self.host
539 .fs
540 .create_file_with(&destination_path, body)
541 .await?;
542 }
543 DownloadedFileType::Gzip => {
544 let body = GzipDecoder::new(body);
545 futures::pin_mut!(body);
546 self.host
547 .fs
548 .create_file_with(&destination_path, body)
549 .await?;
550 }
551 DownloadedFileType::GzipTar => {
552 let body = GzipDecoder::new(body);
553 futures::pin_mut!(body);
554 self.host
555 .fs
556 .extract_tar_file(&destination_path, Archive::new(body))
557 .await?;
558 }
559 DownloadedFileType::Zip => {
560 futures::pin_mut!(body);
561 node_runtime::extract_zip(&destination_path, body)
562 .await
563 .with_context(|| format!("failed to unzip {} archive", path.display()))?;
564 }
565 }
566
567 Ok(())
568 })
569 .await
570 .to_wasmtime_result()
571 }
572
573 async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
574 #[allow(unused)]
575 let path = self
576 .host
577 .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
578
579 #[cfg(unix)]
580 {
581 use std::fs::{self, Permissions};
582 use std::os::unix::fs::PermissionsExt;
583
584 return fs::set_permissions(&path, Permissions::from_mode(0o755))
585 .map_err(|error| anyhow!("failed to set permissions for path {path:?}: {error}"))
586 .to_wasmtime_result();
587 }
588
589 #[cfg(not(unix))]
590 Ok(Ok(()))
591 }
592}