1use crate::wasm_host::wit::since_v0_5_0::slash_command::SlashCommandOutputSection;
2use crate::wasm_host::wit::{CompletionKind, CompletionLabelDetails, InsertTextFormat, SymbolKind};
3use crate::wasm_host::{WasmState, wit::ToWasmtimeResult};
4use ::http_client::{AsyncBody, HttpRequestExt};
5use ::settings::{Settings, WorktreeId};
6use anyhow::{Context, Result, anyhow, bail};
7use async_compression::futures::bufread::GzipDecoder;
8use async_tar::Archive;
9use async_trait::async_trait;
10use context_server_settings::ContextServerSettings;
11use extension::{
12 ExtensionLanguageServerProxy, KeyValueStoreDelegate, ProjectDelegate, WorktreeDelegate,
13};
14use futures::{AsyncReadExt, lock::Mutex};
15use futures::{FutureExt as _, io::BufReader};
16use language::{BinaryStatus, LanguageName, language_settings::AllLanguageSettings};
17use project::project_settings::ProjectSettings;
18use semantic_version::SemanticVersion;
19use std::{
20 env,
21 path::{Path, PathBuf},
22 sync::{Arc, OnceLock},
23};
24use util::maybe;
25use wasmtime::component::{Linker, Resource};
26
27pub const MIN_VERSION: SemanticVersion = SemanticVersion::new(0, 5, 0);
28pub const MAX_VERSION: SemanticVersion = SemanticVersion::new(0, 5, 0);
29
30wasmtime::component::bindgen!({
31 async: true,
32 trappable_imports: true,
33 path: "../extension_api/wit/since_v0.5.0",
34 with: {
35 "worktree": ExtensionWorktree,
36 "project": ExtensionProject,
37 "key-value-store": ExtensionKeyValueStore,
38 "zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream
39 },
40});
41
42pub use self::zed::extension::*;
43
44mod settings {
45 include!(concat!(env!("OUT_DIR"), "/since_v0.5.0/settings.rs"));
46}
47
48pub type ExtensionWorktree = Arc<dyn WorktreeDelegate>;
49pub type ExtensionProject = Arc<dyn ProjectDelegate>;
50pub type ExtensionKeyValueStore = Arc<dyn KeyValueStoreDelegate>;
51pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBody>>>;
52
53pub fn linker() -> &'static Linker<WasmState> {
54 static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
55 LINKER.get_or_init(|| super::new_linker(Extension::add_to_linker))
56}
57
58impl From<Range> for std::ops::Range<usize> {
59 fn from(range: Range) -> Self {
60 let start = range.start as usize;
61 let end = range.end as usize;
62 start..end
63 }
64}
65
66impl From<Command> for extension::Command {
67 fn from(value: Command) -> Self {
68 Self {
69 command: value.command,
70 args: value.args,
71 env: value.env,
72 }
73 }
74}
75
76impl From<CodeLabel> for extension::CodeLabel {
77 fn from(value: CodeLabel) -> Self {
78 Self {
79 code: value.code,
80 spans: value.spans.into_iter().map(Into::into).collect(),
81 filter_range: value.filter_range.into(),
82 }
83 }
84}
85
86impl From<CodeLabelSpan> for extension::CodeLabelSpan {
87 fn from(value: CodeLabelSpan) -> Self {
88 match value {
89 CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
90 CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
91 }
92 }
93}
94
95impl From<CodeLabelSpanLiteral> for extension::CodeLabelSpanLiteral {
96 fn from(value: CodeLabelSpanLiteral) -> Self {
97 Self {
98 text: value.text,
99 highlight_name: value.highlight_name,
100 }
101 }
102}
103
104impl From<extension::Completion> for Completion {
105 fn from(value: extension::Completion) -> Self {
106 Self {
107 label: value.label,
108 label_details: value.label_details.map(Into::into),
109 detail: value.detail,
110 kind: value.kind.map(Into::into),
111 insert_text_format: value.insert_text_format.map(Into::into),
112 }
113 }
114}
115
116impl From<extension::CompletionLabelDetails> for CompletionLabelDetails {
117 fn from(value: extension::CompletionLabelDetails) -> Self {
118 Self {
119 detail: value.detail,
120 description: value.description,
121 }
122 }
123}
124
125impl From<extension::CompletionKind> for CompletionKind {
126 fn from(value: extension::CompletionKind) -> Self {
127 match value {
128 extension::CompletionKind::Text => Self::Text,
129 extension::CompletionKind::Method => Self::Method,
130 extension::CompletionKind::Function => Self::Function,
131 extension::CompletionKind::Constructor => Self::Constructor,
132 extension::CompletionKind::Field => Self::Field,
133 extension::CompletionKind::Variable => Self::Variable,
134 extension::CompletionKind::Class => Self::Class,
135 extension::CompletionKind::Interface => Self::Interface,
136 extension::CompletionKind::Module => Self::Module,
137 extension::CompletionKind::Property => Self::Property,
138 extension::CompletionKind::Unit => Self::Unit,
139 extension::CompletionKind::Value => Self::Value,
140 extension::CompletionKind::Enum => Self::Enum,
141 extension::CompletionKind::Keyword => Self::Keyword,
142 extension::CompletionKind::Snippet => Self::Snippet,
143 extension::CompletionKind::Color => Self::Color,
144 extension::CompletionKind::File => Self::File,
145 extension::CompletionKind::Reference => Self::Reference,
146 extension::CompletionKind::Folder => Self::Folder,
147 extension::CompletionKind::EnumMember => Self::EnumMember,
148 extension::CompletionKind::Constant => Self::Constant,
149 extension::CompletionKind::Struct => Self::Struct,
150 extension::CompletionKind::Event => Self::Event,
151 extension::CompletionKind::Operator => Self::Operator,
152 extension::CompletionKind::TypeParameter => Self::TypeParameter,
153 extension::CompletionKind::Other(value) => Self::Other(value),
154 }
155 }
156}
157
158impl From<extension::InsertTextFormat> for InsertTextFormat {
159 fn from(value: extension::InsertTextFormat) -> Self {
160 match value {
161 extension::InsertTextFormat::PlainText => Self::PlainText,
162 extension::InsertTextFormat::Snippet => Self::Snippet,
163 extension::InsertTextFormat::Other(value) => Self::Other(value),
164 }
165 }
166}
167
168impl From<extension::Symbol> for Symbol {
169 fn from(value: extension::Symbol) -> Self {
170 Self {
171 kind: value.kind.into(),
172 name: value.name,
173 }
174 }
175}
176
177impl From<extension::SymbolKind> for SymbolKind {
178 fn from(value: extension::SymbolKind) -> Self {
179 match value {
180 extension::SymbolKind::File => Self::File,
181 extension::SymbolKind::Module => Self::Module,
182 extension::SymbolKind::Namespace => Self::Namespace,
183 extension::SymbolKind::Package => Self::Package,
184 extension::SymbolKind::Class => Self::Class,
185 extension::SymbolKind::Method => Self::Method,
186 extension::SymbolKind::Property => Self::Property,
187 extension::SymbolKind::Field => Self::Field,
188 extension::SymbolKind::Constructor => Self::Constructor,
189 extension::SymbolKind::Enum => Self::Enum,
190 extension::SymbolKind::Interface => Self::Interface,
191 extension::SymbolKind::Function => Self::Function,
192 extension::SymbolKind::Variable => Self::Variable,
193 extension::SymbolKind::Constant => Self::Constant,
194 extension::SymbolKind::String => Self::String,
195 extension::SymbolKind::Number => Self::Number,
196 extension::SymbolKind::Boolean => Self::Boolean,
197 extension::SymbolKind::Array => Self::Array,
198 extension::SymbolKind::Object => Self::Object,
199 extension::SymbolKind::Key => Self::Key,
200 extension::SymbolKind::Null => Self::Null,
201 extension::SymbolKind::EnumMember => Self::EnumMember,
202 extension::SymbolKind::Struct => Self::Struct,
203 extension::SymbolKind::Event => Self::Event,
204 extension::SymbolKind::Operator => Self::Operator,
205 extension::SymbolKind::TypeParameter => Self::TypeParameter,
206 extension::SymbolKind::Other(value) => Self::Other(value),
207 }
208 }
209}
210
211impl From<extension::SlashCommand> for SlashCommand {
212 fn from(value: extension::SlashCommand) -> Self {
213 Self {
214 name: value.name,
215 description: value.description,
216 tooltip_text: value.tooltip_text,
217 requires_argument: value.requires_argument,
218 }
219 }
220}
221
222impl From<SlashCommandOutput> for extension::SlashCommandOutput {
223 fn from(value: SlashCommandOutput) -> Self {
224 Self {
225 text: value.text,
226 sections: value.sections.into_iter().map(Into::into).collect(),
227 }
228 }
229}
230
231impl From<SlashCommandOutputSection> for extension::SlashCommandOutputSection {
232 fn from(value: SlashCommandOutputSection) -> Self {
233 Self {
234 range: value.range.start as usize..value.range.end as usize,
235 label: value.label,
236 }
237 }
238}
239
240impl From<SlashCommandArgumentCompletion> for extension::SlashCommandArgumentCompletion {
241 fn from(value: SlashCommandArgumentCompletion) -> Self {
242 Self {
243 label: value.label,
244 new_text: value.new_text,
245 run_command: value.run_command,
246 }
247 }
248}
249
250impl HostKeyValueStore for WasmState {
251 async fn insert(
252 &mut self,
253 kv_store: Resource<ExtensionKeyValueStore>,
254 key: String,
255 value: String,
256 ) -> wasmtime::Result<Result<(), String>> {
257 let kv_store = self.table.get(&kv_store)?;
258 kv_store.insert(key, value).await.to_wasmtime_result()
259 }
260
261 async fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
262 // We only ever hand out borrows of key-value stores.
263 Ok(())
264 }
265}
266
267impl HostProject for WasmState {
268 async fn worktree_ids(
269 &mut self,
270 project: Resource<ExtensionProject>,
271 ) -> wasmtime::Result<Vec<u64>> {
272 let project = self.table.get(&project)?;
273 Ok(project.worktree_ids())
274 }
275
276 async fn drop(&mut self, _project: Resource<Project>) -> Result<()> {
277 // We only ever hand out borrows of projects.
278 Ok(())
279 }
280}
281
282impl HostWorktree for WasmState {
283 async fn id(&mut self, delegate: Resource<Arc<dyn WorktreeDelegate>>) -> wasmtime::Result<u64> {
284 let delegate = self.table.get(&delegate)?;
285 Ok(delegate.id())
286 }
287
288 async fn root_path(
289 &mut self,
290 delegate: Resource<Arc<dyn WorktreeDelegate>>,
291 ) -> wasmtime::Result<String> {
292 let delegate = self.table.get(&delegate)?;
293 Ok(delegate.root_path())
294 }
295
296 async fn read_text_file(
297 &mut self,
298 delegate: Resource<Arc<dyn WorktreeDelegate>>,
299 path: String,
300 ) -> wasmtime::Result<Result<String, String>> {
301 let delegate = self.table.get(&delegate)?;
302 Ok(delegate
303 .read_text_file(path.into())
304 .await
305 .map_err(|error| error.to_string()))
306 }
307
308 async fn shell_env(
309 &mut self,
310 delegate: Resource<Arc<dyn WorktreeDelegate>>,
311 ) -> wasmtime::Result<EnvVars> {
312 let delegate = self.table.get(&delegate)?;
313 Ok(delegate.shell_env().await.into_iter().collect())
314 }
315
316 async fn which(
317 &mut self,
318 delegate: Resource<Arc<dyn WorktreeDelegate>>,
319 binary_name: String,
320 ) -> wasmtime::Result<Option<String>> {
321 let delegate = self.table.get(&delegate)?;
322 Ok(delegate.which(binary_name).await)
323 }
324
325 async fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
326 // We only ever hand out borrows of worktrees.
327 Ok(())
328 }
329}
330
331impl common::Host for WasmState {}
332
333impl http_client::Host for WasmState {
334 async fn fetch(
335 &mut self,
336 request: http_client::HttpRequest,
337 ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
338 maybe!(async {
339 let url = &request.url;
340 let request = convert_request(&request)?;
341 let mut response = self.host.http_client.send(request).await?;
342
343 if response.status().is_client_error() || response.status().is_server_error() {
344 bail!("failed to fetch '{url}': status code {}", response.status())
345 }
346 convert_response(&mut response).await
347 })
348 .await
349 .to_wasmtime_result()
350 }
351
352 async fn fetch_stream(
353 &mut self,
354 request: http_client::HttpRequest,
355 ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
356 let request = convert_request(&request)?;
357 let response = self.host.http_client.send(request);
358 maybe!(async {
359 let response = response.await?;
360 let stream = Arc::new(Mutex::new(response));
361 let resource = self.table.push(stream)?;
362 Ok(resource)
363 })
364 .await
365 .to_wasmtime_result()
366 }
367}
368
369impl http_client::HostHttpResponseStream for WasmState {
370 async fn next_chunk(
371 &mut self,
372 resource: Resource<ExtensionHttpResponseStream>,
373 ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
374 let stream = self.table.get(&resource)?.clone();
375 maybe!(async move {
376 let mut response = stream.lock().await;
377 let mut buffer = vec![0; 8192]; // 8KB buffer
378 let bytes_read = response.body_mut().read(&mut buffer).await?;
379 if bytes_read == 0 {
380 Ok(None)
381 } else {
382 buffer.truncate(bytes_read);
383 Ok(Some(buffer))
384 }
385 })
386 .await
387 .to_wasmtime_result()
388 }
389
390 async fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
391 Ok(())
392 }
393}
394
395impl From<http_client::HttpMethod> for ::http_client::Method {
396 fn from(value: http_client::HttpMethod) -> Self {
397 match value {
398 http_client::HttpMethod::Get => Self::GET,
399 http_client::HttpMethod::Post => Self::POST,
400 http_client::HttpMethod::Put => Self::PUT,
401 http_client::HttpMethod::Delete => Self::DELETE,
402 http_client::HttpMethod::Head => Self::HEAD,
403 http_client::HttpMethod::Options => Self::OPTIONS,
404 http_client::HttpMethod::Patch => Self::PATCH,
405 }
406 }
407}
408
409fn convert_request(
410 extension_request: &http_client::HttpRequest,
411) -> Result<::http_client::Request<AsyncBody>, anyhow::Error> {
412 let mut request = ::http_client::Request::builder()
413 .method(::http_client::Method::from(extension_request.method))
414 .uri(&extension_request.url)
415 .follow_redirects(match extension_request.redirect_policy {
416 http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
417 http_client::RedirectPolicy::FollowLimit(limit) => {
418 ::http_client::RedirectPolicy::FollowLimit(limit)
419 }
420 http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
421 });
422 for (key, value) in &extension_request.headers {
423 request = request.header(key, value);
424 }
425 let body = extension_request
426 .body
427 .clone()
428 .map(AsyncBody::from)
429 .unwrap_or_default();
430 request.body(body).map_err(anyhow::Error::from)
431}
432
433async fn convert_response(
434 response: &mut ::http_client::Response<AsyncBody>,
435) -> Result<http_client::HttpResponse, anyhow::Error> {
436 let mut extension_response = http_client::HttpResponse {
437 body: Vec::new(),
438 headers: Vec::new(),
439 };
440
441 for (key, value) in response.headers() {
442 extension_response
443 .headers
444 .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
445 }
446
447 response
448 .body_mut()
449 .read_to_end(&mut extension_response.body)
450 .await?;
451
452 Ok(extension_response)
453}
454
455impl nodejs::Host for WasmState {
456 async fn node_binary_path(&mut self) -> wasmtime::Result<Result<String, String>> {
457 self.host
458 .node_runtime
459 .binary_path()
460 .await
461 .map(|path| path.to_string_lossy().to_string())
462 .to_wasmtime_result()
463 }
464
465 async fn npm_package_latest_version(
466 &mut self,
467 package_name: String,
468 ) -> wasmtime::Result<Result<String, String>> {
469 self.host
470 .node_runtime
471 .npm_package_latest_version(&package_name)
472 .await
473 .to_wasmtime_result()
474 }
475
476 async fn npm_package_installed_version(
477 &mut self,
478 package_name: String,
479 ) -> wasmtime::Result<Result<Option<String>, String>> {
480 self.host
481 .node_runtime
482 .npm_package_installed_version(&self.work_dir(), &package_name)
483 .await
484 .to_wasmtime_result()
485 }
486
487 async fn npm_install_package(
488 &mut self,
489 package_name: String,
490 version: String,
491 ) -> wasmtime::Result<Result<(), String>> {
492 self.host
493 .node_runtime
494 .npm_install_packages(&self.work_dir(), &[(&package_name, &version)])
495 .await
496 .to_wasmtime_result()
497 }
498}
499
500#[async_trait]
501impl lsp::Host for WasmState {}
502
503impl From<::http_client::github::GithubRelease> for github::GithubRelease {
504 fn from(value: ::http_client::github::GithubRelease) -> Self {
505 Self {
506 version: value.tag_name,
507 assets: value.assets.into_iter().map(Into::into).collect(),
508 }
509 }
510}
511
512impl From<::http_client::github::GithubReleaseAsset> for github::GithubReleaseAsset {
513 fn from(value: ::http_client::github::GithubReleaseAsset) -> Self {
514 Self {
515 name: value.name,
516 download_url: value.browser_download_url,
517 }
518 }
519}
520
521impl github::Host for WasmState {
522 async fn latest_github_release(
523 &mut self,
524 repo: String,
525 options: github::GithubReleaseOptions,
526 ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
527 maybe!(async {
528 let release = ::http_client::github::latest_github_release(
529 &repo,
530 options.require_assets,
531 options.pre_release,
532 self.host.http_client.clone(),
533 )
534 .await?;
535 Ok(release.into())
536 })
537 .await
538 .to_wasmtime_result()
539 }
540
541 async fn github_release_by_tag_name(
542 &mut self,
543 repo: String,
544 tag: String,
545 ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
546 maybe!(async {
547 let release = ::http_client::github::get_release_by_tag_name(
548 &repo,
549 &tag,
550 self.host.http_client.clone(),
551 )
552 .await?;
553 Ok(release.into())
554 })
555 .await
556 .to_wasmtime_result()
557 }
558}
559
560impl platform::Host for WasmState {
561 async fn current_platform(&mut self) -> Result<(platform::Os, platform::Architecture)> {
562 Ok((
563 match env::consts::OS {
564 "macos" => platform::Os::Mac,
565 "linux" => platform::Os::Linux,
566 "windows" => platform::Os::Windows,
567 _ => panic!("unsupported os"),
568 },
569 match env::consts::ARCH {
570 "aarch64" => platform::Architecture::Aarch64,
571 "x86" => platform::Architecture::X86,
572 "x86_64" => platform::Architecture::X8664,
573 _ => panic!("unsupported architecture"),
574 },
575 ))
576 }
577}
578
579impl From<std::process::Output> for process::Output {
580 fn from(output: std::process::Output) -> Self {
581 Self {
582 status: output.status.code(),
583 stdout: output.stdout,
584 stderr: output.stderr,
585 }
586 }
587}
588
589impl process::Host for WasmState {
590 async fn run_command(
591 &mut self,
592 command: process::Command,
593 ) -> wasmtime::Result<Result<process::Output, String>> {
594 maybe!(async {
595 self.manifest.allow_exec(&command.command, &command.args)?;
596
597 let output = util::command::new_smol_command(command.command.as_str())
598 .args(&command.args)
599 .envs(command.env)
600 .output()
601 .await?;
602
603 Ok(output.into())
604 })
605 .await
606 .to_wasmtime_result()
607 }
608}
609
610#[async_trait]
611impl slash_command::Host for WasmState {}
612
613impl ExtensionImports for WasmState {
614 async fn get_settings(
615 &mut self,
616 location: Option<self::SettingsLocation>,
617 category: String,
618 key: Option<String>,
619 ) -> wasmtime::Result<Result<String, String>> {
620 self.on_main_thread(|cx| {
621 async move {
622 let location = location
623 .as_ref()
624 .map(|location| ::settings::SettingsLocation {
625 worktree_id: WorktreeId::from_proto(location.worktree_id),
626 path: Path::new(&location.path),
627 });
628
629 cx.update(|cx| match category.as_str() {
630 "language" => {
631 let key = key.map(|k| LanguageName::new(&k));
632 let settings = AllLanguageSettings::get(location, cx).language(
633 location,
634 key.as_ref(),
635 cx,
636 );
637 Ok(serde_json::to_string(&settings::LanguageSettings {
638 tab_size: settings.tab_size,
639 })?)
640 }
641 "lsp" => {
642 let settings = key
643 .and_then(|key| {
644 ProjectSettings::get(location, cx)
645 .lsp
646 .get(&::lsp::LanguageServerName::from_proto(key))
647 })
648 .cloned()
649 .unwrap_or_default();
650 Ok(serde_json::to_string(&settings::LspSettings {
651 binary: settings.binary.map(|binary| settings::CommandSettings {
652 path: binary.path,
653 arguments: binary.arguments,
654 env: binary.env,
655 }),
656 settings: settings.settings,
657 initialization_options: settings.initialization_options,
658 })?)
659 }
660 "context_servers" => {
661 let settings = key
662 .and_then(|key| {
663 ContextServerSettings::get(location, cx)
664 .context_servers
665 .get(key.as_str())
666 })
667 .cloned()
668 .unwrap_or_default();
669 Ok(serde_json::to_string(&settings::ContextServerSettings {
670 command: settings.command.map(|command| settings::CommandSettings {
671 path: Some(command.path),
672 arguments: Some(command.args),
673 env: command.env.map(|env| env.into_iter().collect()),
674 }),
675 settings: settings.settings,
676 })?)
677 }
678 _ => {
679 bail!("Unknown settings category: {}", category);
680 }
681 })
682 }
683 .boxed_local()
684 })
685 .await?
686 .to_wasmtime_result()
687 }
688
689 async fn set_language_server_installation_status(
690 &mut self,
691 server_name: String,
692 status: LanguageServerInstallationStatus,
693 ) -> wasmtime::Result<()> {
694 let status = match status {
695 LanguageServerInstallationStatus::CheckingForUpdate => BinaryStatus::CheckingForUpdate,
696 LanguageServerInstallationStatus::Downloading => BinaryStatus::Downloading,
697 LanguageServerInstallationStatus::None => BinaryStatus::None,
698 LanguageServerInstallationStatus::Failed(error) => BinaryStatus::Failed { error },
699 };
700
701 self.host
702 .proxy
703 .update_language_server_status(::lsp::LanguageServerName(server_name.into()), status);
704
705 Ok(())
706 }
707
708 async fn download_file(
709 &mut self,
710 url: String,
711 path: String,
712 file_type: DownloadedFileType,
713 ) -> wasmtime::Result<Result<(), String>> {
714 maybe!(async {
715 let path = PathBuf::from(path);
716 let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
717
718 self.host.fs.create_dir(&extension_work_dir).await?;
719
720 let destination_path = self
721 .host
722 .writeable_path_from_extension(&self.manifest.id, &path)?;
723
724 let mut response = self
725 .host
726 .http_client
727 .get(&url, Default::default(), true)
728 .await
729 .map_err(|err| anyhow!("error downloading release: {}", err))?;
730
731 if !response.status().is_success() {
732 Err(anyhow!(
733 "download failed with status {}",
734 response.status().to_string()
735 ))?;
736 }
737 let body = BufReader::new(response.body_mut());
738
739 match file_type {
740 DownloadedFileType::Uncompressed => {
741 futures::pin_mut!(body);
742 self.host
743 .fs
744 .create_file_with(&destination_path, body)
745 .await?;
746 }
747 DownloadedFileType::Gzip => {
748 let body = GzipDecoder::new(body);
749 futures::pin_mut!(body);
750 self.host
751 .fs
752 .create_file_with(&destination_path, body)
753 .await?;
754 }
755 DownloadedFileType::GzipTar => {
756 let body = GzipDecoder::new(body);
757 futures::pin_mut!(body);
758 self.host
759 .fs
760 .extract_tar_file(&destination_path, Archive::new(body))
761 .await?;
762 }
763 DownloadedFileType::Zip => {
764 futures::pin_mut!(body);
765 node_runtime::extract_zip(&destination_path, body)
766 .await
767 .with_context(|| format!("failed to unzip {} archive", path.display()))?;
768 }
769 }
770
771 Ok(())
772 })
773 .await
774 .to_wasmtime_result()
775 }
776
777 async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
778 #[allow(unused)]
779 let path = self
780 .host
781 .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
782
783 #[cfg(unix)]
784 {
785 use std::fs::{self, Permissions};
786 use std::os::unix::fs::PermissionsExt;
787
788 return fs::set_permissions(&path, Permissions::from_mode(0o755))
789 .map_err(|error| anyhow!("failed to set permissions for path {path:?}: {error}"))
790 .to_wasmtime_result();
791 }
792
793 #[cfg(not(unix))]
794 Ok(Ok(()))
795 }
796}