1use crate::wasm_host::wit::since_v0_6_0::{
2 dap::{
3 BuildTaskDefinition, BuildTaskDefinitionTemplatePayload, StartDebuggingRequestArguments,
4 TcpArguments, TcpArgumentsTemplate,
5 },
6 slash_command::SlashCommandOutputSection,
7};
8use crate::wasm_host::wit::{CompletionKind, CompletionLabelDetails, InsertTextFormat, SymbolKind};
9use crate::wasm_host::{WasmState, wit::ToWasmtimeResult};
10use ::http_client::{AsyncBody, HttpRequestExt};
11use ::settings::{Settings, WorktreeId};
12use anyhow::{Context as _, Result, bail};
13use async_compression::futures::bufread::GzipDecoder;
14use async_tar::Archive;
15use async_trait::async_trait;
16use extension::{
17 ExtensionLanguageServerProxy, KeyValueStoreDelegate, ProjectDelegate, WorktreeDelegate,
18};
19use futures::{AsyncReadExt, lock::Mutex};
20use futures::{FutureExt as _, io::BufReader};
21use gpui::{BackgroundExecutor, SharedString};
22use language::{BinaryStatus, LanguageName, language_settings::AllLanguageSettings};
23use project::project_settings::ProjectSettings;
24use semver::Version;
25use std::{
26 env,
27 net::Ipv4Addr,
28 path::{Path, PathBuf},
29 str::FromStr,
30 sync::{Arc, OnceLock},
31};
32use task::{SpawnInTerminal, ZedDebugConfig};
33use url::Url;
34use util::{
35 archive::extract_zip, fs::make_file_executable, maybe, paths::PathStyle, rel_path::RelPath,
36};
37use wasmtime::component::{Linker, Resource};
38
39pub const MIN_VERSION: Version = Version::new(0, 8, 0);
40pub const MAX_VERSION: Version = Version::new(0, 8, 0);
41
42wasmtime::component::bindgen!({
43 async: true,
44 trappable_imports: true,
45 path: "../extension_api/wit/since_v0.8.0",
46 with: {
47 "worktree": ExtensionWorktree,
48 "project": ExtensionProject,
49 "key-value-store": ExtensionKeyValueStore,
50 "zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream
51 },
52});
53
54pub use self::zed::extension::*;
55
56mod settings {
57 #![allow(dead_code)]
58 include!(concat!(env!("OUT_DIR"), "/since_v0.8.0/settings.rs"));
59}
60
61pub type ExtensionWorktree = Arc<dyn WorktreeDelegate>;
62pub type ExtensionProject = Arc<dyn ProjectDelegate>;
63pub type ExtensionKeyValueStore = Arc<dyn KeyValueStoreDelegate>;
64pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBody>>>;
65
66pub fn linker(executor: &BackgroundExecutor) -> &'static Linker<WasmState> {
67 static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
68 LINKER.get_or_init(|| super::new_linker(executor, Extension::add_to_linker))
69}
70
71impl From<Range> for std::ops::Range<usize> {
72 fn from(range: Range) -> Self {
73 let start = range.start as usize;
74 let end = range.end as usize;
75 start..end
76 }
77}
78
79impl From<Command> for extension::Command {
80 fn from(value: Command) -> Self {
81 Self {
82 command: value.command.into(),
83 args: value.args,
84 env: value.env,
85 }
86 }
87}
88
89impl From<StartDebuggingRequestArgumentsRequest>
90 for extension::StartDebuggingRequestArgumentsRequest
91{
92 fn from(value: StartDebuggingRequestArgumentsRequest) -> Self {
93 match value {
94 StartDebuggingRequestArgumentsRequest::Launch => Self::Launch,
95 StartDebuggingRequestArgumentsRequest::Attach => Self::Attach,
96 }
97 }
98}
99impl TryFrom<StartDebuggingRequestArguments> for extension::StartDebuggingRequestArguments {
100 type Error = anyhow::Error;
101
102 fn try_from(value: StartDebuggingRequestArguments) -> Result<Self, Self::Error> {
103 Ok(Self {
104 configuration: serde_json::from_str(&value.configuration)?,
105 request: value.request.into(),
106 })
107 }
108}
109impl From<TcpArguments> for extension::TcpArguments {
110 fn from(value: TcpArguments) -> Self {
111 Self {
112 host: value.host.into(),
113 port: value.port,
114 timeout: value.timeout,
115 }
116 }
117}
118
119impl From<extension::TcpArgumentsTemplate> for TcpArgumentsTemplate {
120 fn from(value: extension::TcpArgumentsTemplate) -> Self {
121 Self {
122 host: value.host.map(Ipv4Addr::to_bits),
123 port: value.port,
124 timeout: value.timeout,
125 }
126 }
127}
128
129impl From<TcpArgumentsTemplate> for extension::TcpArgumentsTemplate {
130 fn from(value: TcpArgumentsTemplate) -> Self {
131 Self {
132 host: value.host.map(Ipv4Addr::from_bits),
133 port: value.port,
134 timeout: value.timeout,
135 }
136 }
137}
138
139impl TryFrom<extension::DebugTaskDefinition> for DebugTaskDefinition {
140 type Error = anyhow::Error;
141 fn try_from(value: extension::DebugTaskDefinition) -> Result<Self, Self::Error> {
142 Ok(Self {
143 label: value.label.to_string(),
144 adapter: value.adapter.to_string(),
145 config: value.config.to_string(),
146 tcp_connection: value.tcp_connection.map(Into::into),
147 })
148 }
149}
150
151impl From<task::DebugRequest> for DebugRequest {
152 fn from(value: task::DebugRequest) -> Self {
153 match value {
154 task::DebugRequest::Launch(launch_request) => Self::Launch(launch_request.into()),
155 task::DebugRequest::Attach(attach_request) => Self::Attach(attach_request.into()),
156 }
157 }
158}
159
160impl From<DebugRequest> for task::DebugRequest {
161 fn from(value: DebugRequest) -> Self {
162 match value {
163 DebugRequest::Launch(launch_request) => Self::Launch(launch_request.into()),
164 DebugRequest::Attach(attach_request) => Self::Attach(attach_request.into()),
165 }
166 }
167}
168
169impl From<task::LaunchRequest> for LaunchRequest {
170 fn from(value: task::LaunchRequest) -> Self {
171 Self {
172 program: value.program,
173 cwd: value.cwd.map(|p| p.to_string_lossy().into_owned()),
174 args: value.args,
175 envs: value.env.into_iter().collect(),
176 }
177 }
178}
179
180impl From<task::AttachRequest> for AttachRequest {
181 fn from(value: task::AttachRequest) -> Self {
182 Self {
183 process_id: value.process_id,
184 }
185 }
186}
187
188impl From<LaunchRequest> for task::LaunchRequest {
189 fn from(value: LaunchRequest) -> Self {
190 Self {
191 program: value.program,
192 cwd: value.cwd.map(|p| p.into()),
193 args: value.args,
194 env: value.envs.into_iter().collect(),
195 }
196 }
197}
198impl From<AttachRequest> for task::AttachRequest {
199 fn from(value: AttachRequest) -> Self {
200 Self {
201 process_id: value.process_id,
202 }
203 }
204}
205
206impl From<ZedDebugConfig> for DebugConfig {
207 fn from(value: ZedDebugConfig) -> Self {
208 Self {
209 label: value.label.into(),
210 adapter: value.adapter.into(),
211 request: value.request.into(),
212 stop_on_entry: value.stop_on_entry,
213 }
214 }
215}
216impl TryFrom<DebugAdapterBinary> for extension::DebugAdapterBinary {
217 type Error = anyhow::Error;
218 fn try_from(value: DebugAdapterBinary) -> Result<Self, Self::Error> {
219 Ok(Self {
220 command: value.command,
221 arguments: value.arguments,
222 envs: value.envs.into_iter().collect(),
223 cwd: value.cwd.map(|s| s.into()),
224 connection: value.connection.map(Into::into),
225 request_args: value.request_args.try_into()?,
226 })
227 }
228}
229
230impl From<BuildTaskDefinition> for extension::BuildTaskDefinition {
231 fn from(value: BuildTaskDefinition) -> Self {
232 match value {
233 BuildTaskDefinition::ByName(name) => Self::ByName(name.into()),
234 BuildTaskDefinition::Template(build_task_template) => Self::Template {
235 task_template: build_task_template.template.into(),
236 locator_name: build_task_template.locator_name.map(SharedString::from),
237 },
238 }
239 }
240}
241
242impl From<extension::BuildTaskDefinition> for BuildTaskDefinition {
243 fn from(value: extension::BuildTaskDefinition) -> Self {
244 match value {
245 extension::BuildTaskDefinition::ByName(name) => Self::ByName(name.into()),
246 extension::BuildTaskDefinition::Template {
247 task_template,
248 locator_name,
249 } => Self::Template(BuildTaskDefinitionTemplatePayload {
250 template: task_template.into(),
251 locator_name: locator_name.map(String::from),
252 }),
253 }
254 }
255}
256impl From<BuildTaskTemplate> for extension::BuildTaskTemplate {
257 fn from(value: BuildTaskTemplate) -> Self {
258 Self {
259 label: value.label,
260 command: value.command,
261 args: value.args,
262 env: value.env.into_iter().collect(),
263 cwd: value.cwd,
264 ..Default::default()
265 }
266 }
267}
268impl From<extension::BuildTaskTemplate> for BuildTaskTemplate {
269 fn from(value: extension::BuildTaskTemplate) -> Self {
270 Self {
271 label: value.label,
272 command: value.command,
273 args: value.args,
274 env: value.env.into_iter().collect(),
275 cwd: value.cwd,
276 }
277 }
278}
279
280impl TryFrom<DebugScenario> for extension::DebugScenario {
281 type Error = anyhow::Error;
282
283 fn try_from(value: DebugScenario) -> std::result::Result<Self, Self::Error> {
284 Ok(Self {
285 adapter: value.adapter.into(),
286 label: value.label.into(),
287 build: value.build.map(Into::into),
288 config: serde_json::Value::from_str(&value.config)?,
289 tcp_connection: value.tcp_connection.map(Into::into),
290 })
291 }
292}
293
294impl From<extension::DebugScenario> for DebugScenario {
295 fn from(value: extension::DebugScenario) -> Self {
296 Self {
297 adapter: value.adapter.into(),
298 label: value.label.into(),
299 build: value.build.map(Into::into),
300 config: value.config.to_string(),
301 tcp_connection: value.tcp_connection.map(Into::into),
302 }
303 }
304}
305
306impl TryFrom<SpawnInTerminal> for ResolvedTask {
307 type Error = anyhow::Error;
308
309 fn try_from(value: SpawnInTerminal) -> Result<Self, Self::Error> {
310 Ok(Self {
311 label: value.label,
312 command: value.command.context("missing command")?,
313 args: value.args,
314 env: value.env.into_iter().collect(),
315 cwd: value.cwd.map(|s| {
316 let s = s.to_string_lossy();
317 if cfg!(target_os = "windows") {
318 s.replace('\\', "/")
319 } else {
320 s.into_owned()
321 }
322 }),
323 })
324 }
325}
326
327impl From<CodeLabel> for extension::CodeLabel {
328 fn from(value: CodeLabel) -> Self {
329 Self {
330 code: value.code,
331 spans: value.spans.into_iter().map(Into::into).collect(),
332 filter_range: value.filter_range.into(),
333 }
334 }
335}
336
337impl From<CodeLabelSpan> for extension::CodeLabelSpan {
338 fn from(value: CodeLabelSpan) -> Self {
339 match value {
340 CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
341 CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
342 }
343 }
344}
345
346impl From<CodeLabelSpanLiteral> for extension::CodeLabelSpanLiteral {
347 fn from(value: CodeLabelSpanLiteral) -> Self {
348 Self {
349 text: value.text,
350 highlight_name: value.highlight_name,
351 }
352 }
353}
354
355impl From<extension::Completion> for Completion {
356 fn from(value: extension::Completion) -> Self {
357 Self {
358 label: value.label,
359 label_details: value.label_details.map(Into::into),
360 detail: value.detail,
361 kind: value.kind.map(Into::into),
362 insert_text_format: value.insert_text_format.map(Into::into),
363 }
364 }
365}
366
367impl From<extension::CompletionLabelDetails> for CompletionLabelDetails {
368 fn from(value: extension::CompletionLabelDetails) -> Self {
369 Self {
370 detail: value.detail,
371 description: value.description,
372 }
373 }
374}
375
376impl From<extension::CompletionKind> for CompletionKind {
377 fn from(value: extension::CompletionKind) -> Self {
378 match value {
379 extension::CompletionKind::Text => Self::Text,
380 extension::CompletionKind::Method => Self::Method,
381 extension::CompletionKind::Function => Self::Function,
382 extension::CompletionKind::Constructor => Self::Constructor,
383 extension::CompletionKind::Field => Self::Field,
384 extension::CompletionKind::Variable => Self::Variable,
385 extension::CompletionKind::Class => Self::Class,
386 extension::CompletionKind::Interface => Self::Interface,
387 extension::CompletionKind::Module => Self::Module,
388 extension::CompletionKind::Property => Self::Property,
389 extension::CompletionKind::Unit => Self::Unit,
390 extension::CompletionKind::Value => Self::Value,
391 extension::CompletionKind::Enum => Self::Enum,
392 extension::CompletionKind::Keyword => Self::Keyword,
393 extension::CompletionKind::Snippet => Self::Snippet,
394 extension::CompletionKind::Color => Self::Color,
395 extension::CompletionKind::File => Self::File,
396 extension::CompletionKind::Reference => Self::Reference,
397 extension::CompletionKind::Folder => Self::Folder,
398 extension::CompletionKind::EnumMember => Self::EnumMember,
399 extension::CompletionKind::Constant => Self::Constant,
400 extension::CompletionKind::Struct => Self::Struct,
401 extension::CompletionKind::Event => Self::Event,
402 extension::CompletionKind::Operator => Self::Operator,
403 extension::CompletionKind::TypeParameter => Self::TypeParameter,
404 extension::CompletionKind::Other(value) => Self::Other(value),
405 }
406 }
407}
408
409impl From<extension::InsertTextFormat> for InsertTextFormat {
410 fn from(value: extension::InsertTextFormat) -> Self {
411 match value {
412 extension::InsertTextFormat::PlainText => Self::PlainText,
413 extension::InsertTextFormat::Snippet => Self::Snippet,
414 extension::InsertTextFormat::Other(value) => Self::Other(value),
415 }
416 }
417}
418
419impl From<extension::Symbol> for Symbol {
420 fn from(value: extension::Symbol) -> Self {
421 Self {
422 kind: value.kind.into(),
423 name: value.name,
424 container_name: value.container_name,
425 }
426 }
427}
428
429impl From<extension::SymbolKind> for SymbolKind {
430 fn from(value: extension::SymbolKind) -> Self {
431 match value {
432 extension::SymbolKind::File => Self::File,
433 extension::SymbolKind::Module => Self::Module,
434 extension::SymbolKind::Namespace => Self::Namespace,
435 extension::SymbolKind::Package => Self::Package,
436 extension::SymbolKind::Class => Self::Class,
437 extension::SymbolKind::Method => Self::Method,
438 extension::SymbolKind::Property => Self::Property,
439 extension::SymbolKind::Field => Self::Field,
440 extension::SymbolKind::Constructor => Self::Constructor,
441 extension::SymbolKind::Enum => Self::Enum,
442 extension::SymbolKind::Interface => Self::Interface,
443 extension::SymbolKind::Function => Self::Function,
444 extension::SymbolKind::Variable => Self::Variable,
445 extension::SymbolKind::Constant => Self::Constant,
446 extension::SymbolKind::String => Self::String,
447 extension::SymbolKind::Number => Self::Number,
448 extension::SymbolKind::Boolean => Self::Boolean,
449 extension::SymbolKind::Array => Self::Array,
450 extension::SymbolKind::Object => Self::Object,
451 extension::SymbolKind::Key => Self::Key,
452 extension::SymbolKind::Null => Self::Null,
453 extension::SymbolKind::EnumMember => Self::EnumMember,
454 extension::SymbolKind::Struct => Self::Struct,
455 extension::SymbolKind::Event => Self::Event,
456 extension::SymbolKind::Operator => Self::Operator,
457 extension::SymbolKind::TypeParameter => Self::TypeParameter,
458 extension::SymbolKind::Other(value) => Self::Other(value),
459 }
460 }
461}
462
463impl From<extension::SlashCommand> for SlashCommand {
464 fn from(value: extension::SlashCommand) -> Self {
465 Self {
466 name: value.name,
467 description: value.description,
468 tooltip_text: value.tooltip_text,
469 requires_argument: value.requires_argument,
470 }
471 }
472}
473
474impl From<SlashCommandOutput> for extension::SlashCommandOutput {
475 fn from(value: SlashCommandOutput) -> Self {
476 Self {
477 text: value.text,
478 sections: value.sections.into_iter().map(Into::into).collect(),
479 }
480 }
481}
482
483impl From<SlashCommandOutputSection> for extension::SlashCommandOutputSection {
484 fn from(value: SlashCommandOutputSection) -> Self {
485 Self {
486 range: value.range.start as usize..value.range.end as usize,
487 label: value.label,
488 }
489 }
490}
491
492impl From<SlashCommandArgumentCompletion> for extension::SlashCommandArgumentCompletion {
493 fn from(value: SlashCommandArgumentCompletion) -> Self {
494 Self {
495 label: value.label,
496 new_text: value.new_text,
497 run_command: value.run_command,
498 }
499 }
500}
501
502impl TryFrom<ContextServerConfiguration> for extension::ContextServerConfiguration {
503 type Error = anyhow::Error;
504
505 fn try_from(value: ContextServerConfiguration) -> Result<Self, Self::Error> {
506 let settings_schema: serde_json::Value = serde_json::from_str(&value.settings_schema)
507 .context("Failed to parse settings_schema")?;
508
509 Ok(Self {
510 installation_instructions: value.installation_instructions,
511 default_settings: value.default_settings,
512 settings_schema,
513 })
514 }
515}
516
517impl HostKeyValueStore for WasmState {
518 async fn insert(
519 &mut self,
520 kv_store: Resource<ExtensionKeyValueStore>,
521 key: String,
522 value: String,
523 ) -> wasmtime::Result<Result<(), String>> {
524 let kv_store = self.table.get(&kv_store)?;
525 kv_store.insert(key, value).await.to_wasmtime_result()
526 }
527
528 async fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
529 // We only ever hand out borrows of key-value stores.
530 Ok(())
531 }
532}
533
534impl HostProject for WasmState {
535 async fn worktree_ids(
536 &mut self,
537 project: Resource<ExtensionProject>,
538 ) -> wasmtime::Result<Vec<u64>> {
539 let project = self.table.get(&project)?;
540 Ok(project.worktree_ids())
541 }
542
543 async fn drop(&mut self, _project: Resource<Project>) -> Result<()> {
544 // We only ever hand out borrows of projects.
545 Ok(())
546 }
547}
548
549impl HostWorktree for WasmState {
550 async fn id(&mut self, delegate: Resource<Arc<dyn WorktreeDelegate>>) -> wasmtime::Result<u64> {
551 let delegate = self.table.get(&delegate)?;
552 Ok(delegate.id())
553 }
554
555 async fn root_path(
556 &mut self,
557 delegate: Resource<Arc<dyn WorktreeDelegate>>,
558 ) -> wasmtime::Result<String> {
559 let delegate = self.table.get(&delegate)?;
560 Ok(delegate.root_path())
561 }
562
563 async fn read_text_file(
564 &mut self,
565 delegate: Resource<Arc<dyn WorktreeDelegate>>,
566 path: String,
567 ) -> wasmtime::Result<Result<String, String>> {
568 let delegate = self.table.get(&delegate)?;
569 Ok(delegate
570 .read_text_file(&RelPath::new(Path::new(&path), PathStyle::Posix)?)
571 .await
572 .map_err(|error| error.to_string()))
573 }
574
575 async fn shell_env(
576 &mut self,
577 delegate: Resource<Arc<dyn WorktreeDelegate>>,
578 ) -> wasmtime::Result<EnvVars> {
579 let delegate = self.table.get(&delegate)?;
580 Ok(delegate.shell_env().await.into_iter().collect())
581 }
582
583 async fn which(
584 &mut self,
585 delegate: Resource<Arc<dyn WorktreeDelegate>>,
586 binary_name: String,
587 ) -> wasmtime::Result<Option<String>> {
588 let delegate = self.table.get(&delegate)?;
589 Ok(delegate.which(binary_name).await)
590 }
591
592 async fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
593 // We only ever hand out borrows of worktrees.
594 Ok(())
595 }
596}
597
598impl common::Host for WasmState {}
599
600impl http_client::Host for WasmState {
601 async fn fetch(
602 &mut self,
603 request: http_client::HttpRequest,
604 ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
605 maybe!(async {
606 let url = &request.url;
607 let request = convert_request(&request)?;
608 let mut response = self.host.http_client.send(request).await?;
609
610 if response.status().is_client_error() || response.status().is_server_error() {
611 bail!("failed to fetch '{url}': status code {}", response.status())
612 }
613 convert_response(&mut response).await
614 })
615 .await
616 .to_wasmtime_result()
617 }
618
619 async fn fetch_stream(
620 &mut self,
621 request: http_client::HttpRequest,
622 ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
623 let request = convert_request(&request)?;
624 let response = self.host.http_client.send(request);
625 maybe!(async {
626 let response = response.await?;
627 let stream = Arc::new(Mutex::new(response));
628 let resource = self.table.push(stream)?;
629 Ok(resource)
630 })
631 .await
632 .to_wasmtime_result()
633 }
634}
635
636impl http_client::HostHttpResponseStream for WasmState {
637 async fn next_chunk(
638 &mut self,
639 resource: Resource<ExtensionHttpResponseStream>,
640 ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
641 let stream = self.table.get(&resource)?.clone();
642 maybe!(async move {
643 let mut response = stream.lock().await;
644 let mut buffer = vec![0; 8192]; // 8KB buffer
645 let bytes_read = response.body_mut().read(&mut buffer).await?;
646 if bytes_read == 0 {
647 Ok(None)
648 } else {
649 buffer.truncate(bytes_read);
650 Ok(Some(buffer))
651 }
652 })
653 .await
654 .to_wasmtime_result()
655 }
656
657 async fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
658 Ok(())
659 }
660}
661
662impl From<http_client::HttpMethod> for ::http_client::Method {
663 fn from(value: http_client::HttpMethod) -> Self {
664 match value {
665 http_client::HttpMethod::Get => Self::GET,
666 http_client::HttpMethod::Post => Self::POST,
667 http_client::HttpMethod::Put => Self::PUT,
668 http_client::HttpMethod::Delete => Self::DELETE,
669 http_client::HttpMethod::Head => Self::HEAD,
670 http_client::HttpMethod::Options => Self::OPTIONS,
671 http_client::HttpMethod::Patch => Self::PATCH,
672 }
673 }
674}
675
676fn convert_request(
677 extension_request: &http_client::HttpRequest,
678) -> anyhow::Result<::http_client::Request<AsyncBody>> {
679 let mut request = ::http_client::Request::builder()
680 .method(::http_client::Method::from(extension_request.method))
681 .uri(&extension_request.url)
682 .follow_redirects(match extension_request.redirect_policy {
683 http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
684 http_client::RedirectPolicy::FollowLimit(limit) => {
685 ::http_client::RedirectPolicy::FollowLimit(limit)
686 }
687 http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
688 });
689 for (key, value) in &extension_request.headers {
690 request = request.header(key, value);
691 }
692 let body = extension_request
693 .body
694 .clone()
695 .map(AsyncBody::from)
696 .unwrap_or_default();
697 request.body(body).map_err(anyhow::Error::from)
698}
699
700async fn convert_response(
701 response: &mut ::http_client::Response<AsyncBody>,
702) -> anyhow::Result<http_client::HttpResponse> {
703 let mut extension_response = http_client::HttpResponse {
704 body: Vec::new(),
705 headers: Vec::new(),
706 };
707
708 for (key, value) in response.headers() {
709 extension_response
710 .headers
711 .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
712 }
713
714 response
715 .body_mut()
716 .read_to_end(&mut extension_response.body)
717 .await?;
718
719 Ok(extension_response)
720}
721
722impl nodejs::Host for WasmState {
723 async fn node_binary_path(&mut self) -> wasmtime::Result<Result<String, String>> {
724 self.host
725 .node_runtime
726 .binary_path()
727 .await
728 .map(|path| path.to_string_lossy().into_owned())
729 .to_wasmtime_result()
730 }
731
732 async fn npm_package_latest_version(
733 &mut self,
734 package_name: String,
735 ) -> wasmtime::Result<Result<String, String>> {
736 self.host
737 .node_runtime
738 .npm_package_latest_version(&package_name)
739 .await
740 .map(|v| v.to_string())
741 .to_wasmtime_result()
742 }
743
744 async fn npm_package_installed_version(
745 &mut self,
746 package_name: String,
747 ) -> wasmtime::Result<Result<Option<String>, String>> {
748 self.host
749 .node_runtime
750 .npm_package_installed_version(&self.work_dir(), &package_name)
751 .await
752 .map(|option| option.map(|version| version.to_string()))
753 .to_wasmtime_result()
754 }
755
756 async fn npm_install_package(
757 &mut self,
758 package_name: String,
759 version: String,
760 ) -> wasmtime::Result<Result<(), String>> {
761 self.capability_granter
762 .grant_npm_install_package(&package_name)?;
763
764 self.host
765 .node_runtime
766 .npm_install_packages(&self.work_dir(), &[(&package_name, &version)])
767 .await
768 .to_wasmtime_result()
769 }
770}
771
772#[async_trait]
773impl lsp::Host for WasmState {}
774
775impl From<::http_client::github::GithubRelease> for github::GithubRelease {
776 fn from(value: ::http_client::github::GithubRelease) -> Self {
777 Self {
778 version: value.tag_name,
779 assets: value.assets.into_iter().map(Into::into).collect(),
780 }
781 }
782}
783
784impl From<::http_client::github::GithubReleaseAsset> for github::GithubReleaseAsset {
785 fn from(value: ::http_client::github::GithubReleaseAsset) -> Self {
786 Self {
787 name: value.name,
788 download_url: value.browser_download_url,
789 digest: value.digest,
790 }
791 }
792}
793
794impl github::Host for WasmState {
795 async fn latest_github_release(
796 &mut self,
797 repo: String,
798 options: github::GithubReleaseOptions,
799 ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
800 maybe!(async {
801 let release = ::http_client::github::latest_github_release(
802 &repo,
803 options.require_assets,
804 options.pre_release,
805 self.host.http_client.clone(),
806 )
807 .await?;
808 Ok(release.into())
809 })
810 .await
811 .to_wasmtime_result()
812 }
813
814 async fn github_release_by_tag_name(
815 &mut self,
816 repo: String,
817 tag: String,
818 ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
819 maybe!(async {
820 let release = ::http_client::github::get_release_by_tag_name(
821 &repo,
822 &tag,
823 self.host.http_client.clone(),
824 )
825 .await?;
826 Ok(release.into())
827 })
828 .await
829 .to_wasmtime_result()
830 }
831}
832
833impl platform::Host for WasmState {
834 async fn current_platform(&mut self) -> Result<(platform::Os, platform::Architecture)> {
835 Ok((
836 match env::consts::OS {
837 "macos" => platform::Os::Mac,
838 "linux" => platform::Os::Linux,
839 "windows" => platform::Os::Windows,
840 _ => panic!("unsupported os"),
841 },
842 match env::consts::ARCH {
843 "aarch64" => platform::Architecture::Aarch64,
844 "x86" => platform::Architecture::X86,
845 "x86_64" => platform::Architecture::X8664,
846 _ => panic!("unsupported architecture"),
847 },
848 ))
849 }
850}
851
852impl From<std::process::Output> for process::Output {
853 fn from(output: std::process::Output) -> Self {
854 Self {
855 status: output.status.code(),
856 stdout: output.stdout,
857 stderr: output.stderr,
858 }
859 }
860}
861
862impl process::Host for WasmState {
863 async fn run_command(
864 &mut self,
865 command: process::Command,
866 ) -> wasmtime::Result<Result<process::Output, String>> {
867 maybe!(async {
868 self.capability_granter
869 .grant_exec(&command.command, &command.args)?;
870
871 let output = util::command::new_command(command.command.as_str())
872 .args(&command.args)
873 .envs(command.env)
874 .output()
875 .await?;
876
877 Ok(output.into())
878 })
879 .await
880 .to_wasmtime_result()
881 }
882}
883
884#[async_trait]
885impl slash_command::Host for WasmState {}
886
887#[async_trait]
888impl context_server::Host for WasmState {}
889
890impl dap::Host for WasmState {
891 async fn resolve_tcp_template(
892 &mut self,
893 template: TcpArgumentsTemplate,
894 ) -> wasmtime::Result<Result<TcpArguments, String>> {
895 maybe!(async {
896 let (host, port, timeout) =
897 ::dap::configure_tcp_connection(task::TcpArgumentsTemplate {
898 port: template.port,
899 host: template.host.map(Ipv4Addr::from_bits),
900 timeout: template.timeout,
901 })
902 .await?;
903 Ok(TcpArguments {
904 port,
905 host: host.to_bits(),
906 timeout,
907 })
908 })
909 .await
910 .to_wasmtime_result()
911 }
912}
913
914impl ExtensionImports for WasmState {
915 async fn get_settings(
916 &mut self,
917 location: Option<self::SettingsLocation>,
918 category: String,
919 key: Option<String>,
920 ) -> wasmtime::Result<Result<String, String>> {
921 self.on_main_thread(|cx| {
922 async move {
923 let path = location.as_ref().and_then(|location| {
924 RelPath::new(Path::new(&location.path), PathStyle::Posix).ok()
925 });
926 let location = path
927 .as_ref()
928 .zip(location.as_ref())
929 .map(|(path, location)| ::settings::SettingsLocation {
930 worktree_id: WorktreeId::from_proto(location.worktree_id),
931 path,
932 });
933
934 cx.update(|cx| match category.as_str() {
935 "language" => {
936 let key = key.map(|k| LanguageName::new(&k));
937 let settings = AllLanguageSettings::get(location, cx).language(
938 location,
939 key.as_ref(),
940 cx,
941 );
942 Ok(serde_json::to_string(&settings::LanguageSettings {
943 tab_size: settings.tab_size,
944 })?)
945 }
946 "lsp" => {
947 let settings = key
948 .and_then(|key| {
949 ProjectSettings::get(location, cx)
950 .lsp
951 .get(&::lsp::LanguageServerName::from_proto(key))
952 })
953 .cloned()
954 .unwrap_or_default();
955 Ok(serde_json::to_string(&settings::LspSettings {
956 binary: settings.binary.map(|binary| settings::CommandSettings {
957 path: binary.path,
958 arguments: binary.arguments,
959 env: binary.env.map(|env| env.into_iter().collect()),
960 }),
961 settings: settings.settings,
962 initialization_options: settings.initialization_options,
963 })?)
964 }
965 "context_servers" => {
966 let settings = key
967 .and_then(|key| {
968 ProjectSettings::get(location, cx)
969 .context_servers
970 .get(key.as_str())
971 })
972 .cloned()
973 .unwrap_or_else(|| {
974 project::project_settings::ContextServerSettings::default_extension(
975 )
976 });
977
978 match settings {
979 project::project_settings::ContextServerSettings::Stdio {
980 enabled: _,
981 command,
982 ..
983 } => Ok(serde_json::to_string(&settings::ContextServerSettings {
984 command: Some(settings::CommandSettings {
985 path: command.path.to_str().map(|path| path.to_string()),
986 arguments: Some(command.args),
987 env: command.env.map(|env| env.into_iter().collect()),
988 }),
989 settings: None,
990 })?),
991 project::project_settings::ContextServerSettings::Extension {
992 enabled: _,
993 settings,
994 ..
995 } => Ok(serde_json::to_string(&settings::ContextServerSettings {
996 command: None,
997 settings: Some(settings),
998 })?),
999 project::project_settings::ContextServerSettings::Http { .. } => {
1000 bail!("remote context server settings not supported in 0.6.0")
1001 }
1002 }
1003 }
1004 _ => {
1005 bail!("Unknown settings category: {}", category);
1006 }
1007 })
1008 }
1009 .boxed_local()
1010 })
1011 .await
1012 .to_wasmtime_result()
1013 }
1014
1015 async fn set_language_server_installation_status(
1016 &mut self,
1017 server_name: String,
1018 status: LanguageServerInstallationStatus,
1019 ) -> wasmtime::Result<()> {
1020 let status = match status {
1021 LanguageServerInstallationStatus::CheckingForUpdate => BinaryStatus::CheckingForUpdate,
1022 LanguageServerInstallationStatus::Downloading => BinaryStatus::Downloading,
1023 LanguageServerInstallationStatus::None => BinaryStatus::None,
1024 LanguageServerInstallationStatus::Failed(error) => BinaryStatus::Failed { error },
1025 };
1026
1027 self.host
1028 .proxy
1029 .update_language_server_status(::lsp::LanguageServerName(server_name.into()), status);
1030
1031 Ok(())
1032 }
1033
1034 async fn download_file(
1035 &mut self,
1036 url: String,
1037 path: String,
1038 file_type: DownloadedFileType,
1039 ) -> wasmtime::Result<Result<(), String>> {
1040 maybe!(async {
1041 let parsed_url = Url::parse(&url)?;
1042 self.capability_granter.grant_download_file(&parsed_url)?;
1043
1044 let path = PathBuf::from(path);
1045 let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
1046
1047 self.host.fs.create_dir(&extension_work_dir).await?;
1048
1049 let destination_path = self
1050 .host
1051 .writeable_path_from_extension(&self.manifest.id, &path)
1052 .await?;
1053
1054 let mut response = self
1055 .host
1056 .http_client
1057 .get(&url, Default::default(), true)
1058 .await
1059 .context("downloading release")?;
1060
1061 anyhow::ensure!(
1062 response.status().is_success(),
1063 "download failed with status {}",
1064 response.status()
1065 );
1066 let body = BufReader::new(response.body_mut());
1067
1068 match file_type {
1069 DownloadedFileType::Uncompressed => {
1070 futures::pin_mut!(body);
1071 self.host
1072 .fs
1073 .create_file_with(&destination_path, body)
1074 .await?;
1075 }
1076 DownloadedFileType::Gzip => {
1077 let body = GzipDecoder::new(body);
1078 futures::pin_mut!(body);
1079 self.host
1080 .fs
1081 .create_file_with(&destination_path, body)
1082 .await?;
1083 }
1084 DownloadedFileType::GzipTar => {
1085 let body = GzipDecoder::new(body);
1086 futures::pin_mut!(body);
1087 self.host
1088 .fs
1089 .extract_tar_file(&destination_path, Archive::new(body))
1090 .await?;
1091 }
1092 DownloadedFileType::Zip => {
1093 futures::pin_mut!(body);
1094 extract_zip(&destination_path, body)
1095 .await
1096 .with_context(|| format!("unzipping {path:?} archive"))?;
1097 }
1098 }
1099
1100 Ok(())
1101 })
1102 .await
1103 .to_wasmtime_result()
1104 }
1105
1106 async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
1107 let path = self
1108 .host
1109 .writeable_path_from_extension(&self.manifest.id, Path::new(&path))
1110 .await?;
1111
1112 make_file_executable(&path)
1113 .await
1114 .with_context(|| format!("setting permissions for path {path:?}"))
1115 .to_wasmtime_result()
1116 }
1117}