1use crate::wasm_host::{WasmState, wit::ToWasmtimeResult};
2use ::http_client::{AsyncBody, HttpRequestExt};
3use ::settings::{Settings, WorktreeId};
4use anyhow::{Context as _, Result, bail};
5use async_compression::futures::bufread::GzipDecoder;
6use async_tar::Archive;
7use extension::{ExtensionLanguageServerProxy, KeyValueStoreDelegate, WorktreeDelegate};
8use futures::{AsyncReadExt, lock::Mutex};
9use futures::{FutureExt as _, io::BufReader};
10use gpui::BackgroundExecutor;
11use language::LanguageName;
12use language::{BinaryStatus, language_settings::AllLanguageSettings};
13use project::project_settings::ProjectSettings;
14use semantic_version::SemanticVersion;
15use std::{
16 path::{Path, PathBuf},
17 sync::{Arc, OnceLock},
18};
19use util::{archive::extract_zip, fs::make_file_executable, 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(executor: &BackgroundExecutor) -> &'static Linker<WasmState> {
52 static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
53 LINKER.get_or_init(|| super::new_linker(executor, 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
231impl HostKeyValueStore for WasmState {
232 async fn insert(
233 &mut self,
234 kv_store: Resource<ExtensionKeyValueStore>,
235 key: String,
236 value: String,
237 ) -> wasmtime::Result<Result<(), String>> {
238 let kv_store = self.table.get(&kv_store)?;
239 kv_store.insert(key, value).await.to_wasmtime_result()
240 }
241
242 async fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
243 // We only ever hand out borrows of key-value stores.
244 Ok(())
245 }
246}
247
248impl HostWorktree for WasmState {
249 async fn id(&mut self, delegate: Resource<Arc<dyn WorktreeDelegate>>) -> wasmtime::Result<u64> {
250 latest::HostWorktree::id(self, delegate).await
251 }
252
253 async fn root_path(
254 &mut self,
255 delegate: Resource<Arc<dyn WorktreeDelegate>>,
256 ) -> wasmtime::Result<String> {
257 latest::HostWorktree::root_path(self, delegate).await
258 }
259
260 async fn read_text_file(
261 &mut self,
262 delegate: Resource<Arc<dyn WorktreeDelegate>>,
263 path: String,
264 ) -> wasmtime::Result<Result<String, String>> {
265 latest::HostWorktree::read_text_file(self, delegate, path).await
266 }
267
268 async fn shell_env(
269 &mut self,
270 delegate: Resource<Arc<dyn WorktreeDelegate>>,
271 ) -> wasmtime::Result<EnvVars> {
272 latest::HostWorktree::shell_env(self, delegate).await
273 }
274
275 async fn which(
276 &mut self,
277 delegate: Resource<Arc<dyn WorktreeDelegate>>,
278 binary_name: String,
279 ) -> wasmtime::Result<Option<String>> {
280 latest::HostWorktree::which(self, delegate, binary_name).await
281 }
282
283 async fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
284 // We only ever hand out borrows of worktrees.
285 Ok(())
286 }
287}
288
289impl common::Host for WasmState {}
290
291impl http_client::Host for WasmState {
292 async fn fetch(
293 &mut self,
294 request: http_client::HttpRequest,
295 ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
296 maybe!(async {
297 let url = &request.url;
298 let request = convert_request(&request)?;
299 let mut response = self.host.http_client.send(request).await?;
300
301 if response.status().is_client_error() || response.status().is_server_error() {
302 bail!("failed to fetch '{url}': status code {}", response.status())
303 }
304 convert_response(&mut response).await
305 })
306 .await
307 .to_wasmtime_result()
308 }
309
310 async fn fetch_stream(
311 &mut self,
312 request: http_client::HttpRequest,
313 ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
314 let request = convert_request(&request)?;
315 let response = self.host.http_client.send(request);
316 maybe!(async {
317 let response = response.await?;
318 let stream = Arc::new(Mutex::new(response));
319 let resource = self.table.push(stream)?;
320 Ok(resource)
321 })
322 .await
323 .to_wasmtime_result()
324 }
325}
326
327impl http_client::HostHttpResponseStream for WasmState {
328 async fn next_chunk(
329 &mut self,
330 resource: Resource<ExtensionHttpResponseStream>,
331 ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
332 let stream = self.table.get(&resource)?.clone();
333 maybe!(async move {
334 let mut response = stream.lock().await;
335 let mut buffer = vec![0; 8192]; // 8KB buffer
336 let bytes_read = response.body_mut().read(&mut buffer).await?;
337 if bytes_read == 0 {
338 Ok(None)
339 } else {
340 buffer.truncate(bytes_read);
341 Ok(Some(buffer))
342 }
343 })
344 .await
345 .to_wasmtime_result()
346 }
347
348 async fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
349 Ok(())
350 }
351}
352
353impl From<http_client::HttpMethod> for ::http_client::Method {
354 fn from(value: http_client::HttpMethod) -> Self {
355 match value {
356 http_client::HttpMethod::Get => Self::GET,
357 http_client::HttpMethod::Post => Self::POST,
358 http_client::HttpMethod::Put => Self::PUT,
359 http_client::HttpMethod::Delete => Self::DELETE,
360 http_client::HttpMethod::Head => Self::HEAD,
361 http_client::HttpMethod::Options => Self::OPTIONS,
362 http_client::HttpMethod::Patch => Self::PATCH,
363 }
364 }
365}
366
367fn convert_request(
368 extension_request: &http_client::HttpRequest,
369) -> anyhow::Result<::http_client::Request<AsyncBody>> {
370 let mut request = ::http_client::Request::builder()
371 .method(::http_client::Method::from(extension_request.method))
372 .uri(&extension_request.url)
373 .follow_redirects(match extension_request.redirect_policy {
374 http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
375 http_client::RedirectPolicy::FollowLimit(limit) => {
376 ::http_client::RedirectPolicy::FollowLimit(limit)
377 }
378 http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
379 });
380 for (key, value) in &extension_request.headers {
381 request = request.header(key, value);
382 }
383 let body = extension_request
384 .body
385 .clone()
386 .map(AsyncBody::from)
387 .unwrap_or_default();
388 request.body(body).map_err(anyhow::Error::from)
389}
390
391async fn convert_response(
392 response: &mut ::http_client::Response<AsyncBody>,
393) -> anyhow::Result<http_client::HttpResponse> {
394 let mut extension_response = http_client::HttpResponse {
395 body: Vec::new(),
396 headers: Vec::new(),
397 };
398
399 for (key, value) in response.headers() {
400 extension_response
401 .headers
402 .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
403 }
404
405 response
406 .body_mut()
407 .read_to_end(&mut extension_response.body)
408 .await?;
409
410 Ok(extension_response)
411}
412
413impl lsp::Host for WasmState {}
414
415impl ExtensionImports for WasmState {
416 async fn get_settings(
417 &mut self,
418 location: Option<self::SettingsLocation>,
419 category: String,
420 key: Option<String>,
421 ) -> wasmtime::Result<Result<String, String>> {
422 self.on_main_thread(|cx| {
423 async move {
424 let location = location
425 .as_ref()
426 .map(|location| ::settings::SettingsLocation {
427 worktree_id: WorktreeId::from_proto(location.worktree_id),
428 path: Path::new(&location.path),
429 });
430
431 cx.update(|cx| match category.as_str() {
432 "language" => {
433 let key = key.map(|k| LanguageName::new(&k));
434 let settings = AllLanguageSettings::get(location, cx).language(
435 location,
436 key.as_ref(),
437 cx,
438 );
439 Ok(serde_json::to_string(&settings::LanguageSettings {
440 tab_size: settings.tab_size,
441 })?)
442 }
443 "lsp" => {
444 let settings = key
445 .and_then(|key| {
446 ProjectSettings::get(location, cx)
447 .lsp
448 .get(&::lsp::LanguageServerName(key.into()))
449 })
450 .cloned()
451 .unwrap_or_default();
452 Ok(serde_json::to_string(&settings::LspSettings {
453 binary: settings.binary.map(|binary| settings::BinarySettings {
454 path: binary.path,
455 arguments: binary.arguments,
456 }),
457 settings: settings.settings,
458 initialization_options: settings.initialization_options,
459 })?)
460 }
461 _ => {
462 bail!("Unknown settings category: {}", category);
463 }
464 })
465 }
466 .boxed_local()
467 })
468 .await?
469 .to_wasmtime_result()
470 }
471
472 async fn set_language_server_installation_status(
473 &mut self,
474 server_name: String,
475 status: LanguageServerInstallationStatus,
476 ) -> wasmtime::Result<()> {
477 let status = match status {
478 LanguageServerInstallationStatus::CheckingForUpdate => BinaryStatus::CheckingForUpdate,
479 LanguageServerInstallationStatus::Downloading => BinaryStatus::Downloading,
480 LanguageServerInstallationStatus::None => BinaryStatus::None,
481 LanguageServerInstallationStatus::Failed(error) => BinaryStatus::Failed { error },
482 };
483
484 self.host
485 .proxy
486 .update_language_server_status(::lsp::LanguageServerName(server_name.into()), status);
487
488 Ok(())
489 }
490
491 async fn download_file(
492 &mut self,
493 url: String,
494 path: String,
495 file_type: DownloadedFileType,
496 ) -> wasmtime::Result<Result<(), String>> {
497 maybe!(async {
498 let path = PathBuf::from(path);
499 let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
500
501 self.host.fs.create_dir(&extension_work_dir).await?;
502
503 let destination_path = self
504 .host
505 .writeable_path_from_extension(&self.manifest.id, &path)?;
506
507 let mut response = self
508 .host
509 .http_client
510 .get(&url, Default::default(), true)
511 .await
512 .context("downloading release")?;
513
514 anyhow::ensure!(
515 response.status().is_success(),
516 "download failed with status {}",
517 response.status().to_string()
518 );
519 let body = BufReader::new(response.body_mut());
520
521 match file_type {
522 DownloadedFileType::Uncompressed => {
523 futures::pin_mut!(body);
524 self.host
525 .fs
526 .create_file_with(&destination_path, body)
527 .await?;
528 }
529 DownloadedFileType::Gzip => {
530 let body = GzipDecoder::new(body);
531 futures::pin_mut!(body);
532 self.host
533 .fs
534 .create_file_with(&destination_path, body)
535 .await?;
536 }
537 DownloadedFileType::GzipTar => {
538 let body = GzipDecoder::new(body);
539 futures::pin_mut!(body);
540 self.host
541 .fs
542 .extract_tar_file(&destination_path, Archive::new(body))
543 .await?;
544 }
545 DownloadedFileType::Zip => {
546 futures::pin_mut!(body);
547 extract_zip(&destination_path, body)
548 .await
549 .with_context(|| format!("unzipping {path:?} archive"))?;
550 }
551 }
552
553 Ok(())
554 })
555 .await
556 .to_wasmtime_result()
557 }
558
559 async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
560 let path = self
561 .host
562 .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
563
564 make_file_executable(&path)
565 .await
566 .with_context(|| format!("setting permissions for path {path:?}"))
567 .to_wasmtime_result()
568 }
569}