since_v0_2_0.rs

  1use crate::wasm_host::wit::since_v0_2_0::slash_command::SlashCommandOutputSection;
  2use crate::wasm_host::wit::{CompletionKind, CompletionLabelDetails, InsertTextFormat, SymbolKind};
  3use crate::wasm_host::{wit::ToWasmtimeResult, WasmState};
  4use ::http_client::{AsyncBody, HttpRequestExt};
  5use ::settings::{Settings, WorktreeId};
  6use anyhow::{anyhow, bail, Context, Result};
  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::{io::BufReader, FutureExt as _};
 15use futures::{lock::Mutex, AsyncReadExt};
 16use language::{language_settings::AllLanguageSettings, LanguageName, LanguageServerBinaryStatus};
 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, 2, 0);
 28pub const MAX_VERSION: SemanticVersion = SemanticVersion::new(0, 2, 0);
 29
 30wasmtime::component::bindgen!({
 31    async: true,
 32    trappable_imports: true,
 33    path: "../extension_api/wit/since_v0.2.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.2.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
250#[async_trait]
251impl HostKeyValueStore for WasmState {
252    async fn insert(
253        &mut self,
254        kv_store: Resource<ExtensionKeyValueStore>,
255        key: String,
256        value: String,
257    ) -> wasmtime::Result<Result<(), String>> {
258        let kv_store = self.table.get(&kv_store)?;
259        kv_store.insert(key, value).await.to_wasmtime_result()
260    }
261
262    fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
263        // We only ever hand out borrows of key-value stores.
264        Ok(())
265    }
266}
267
268#[async_trait]
269impl HostProject for WasmState {
270    async fn worktree_ids(
271        &mut self,
272        project: Resource<ExtensionProject>,
273    ) -> wasmtime::Result<Vec<u64>> {
274        let project = self.table.get(&project)?;
275        Ok(project.worktree_ids())
276    }
277
278    fn drop(&mut self, _project: Resource<Project>) -> Result<()> {
279        // We only ever hand out borrows of projects.
280        Ok(())
281    }
282}
283
284#[async_trait]
285impl HostWorktree for WasmState {
286    async fn id(&mut self, delegate: Resource<Arc<dyn WorktreeDelegate>>) -> wasmtime::Result<u64> {
287        let delegate = self.table.get(&delegate)?;
288        Ok(delegate.id())
289    }
290
291    async fn root_path(
292        &mut self,
293        delegate: Resource<Arc<dyn WorktreeDelegate>>,
294    ) -> wasmtime::Result<String> {
295        let delegate = self.table.get(&delegate)?;
296        Ok(delegate.root_path())
297    }
298
299    async fn read_text_file(
300        &mut self,
301        delegate: Resource<Arc<dyn WorktreeDelegate>>,
302        path: String,
303    ) -> wasmtime::Result<Result<String, String>> {
304        let delegate = self.table.get(&delegate)?;
305        Ok(delegate
306            .read_text_file(path.into())
307            .await
308            .map_err(|error| error.to_string()))
309    }
310
311    async fn shell_env(
312        &mut self,
313        delegate: Resource<Arc<dyn WorktreeDelegate>>,
314    ) -> wasmtime::Result<EnvVars> {
315        let delegate = self.table.get(&delegate)?;
316        Ok(delegate.shell_env().await.into_iter().collect())
317    }
318
319    async fn which(
320        &mut self,
321        delegate: Resource<Arc<dyn WorktreeDelegate>>,
322        binary_name: String,
323    ) -> wasmtime::Result<Option<String>> {
324        let delegate = self.table.get(&delegate)?;
325        Ok(delegate.which(binary_name).await)
326    }
327
328    fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
329        // We only ever hand out borrows of worktrees.
330        Ok(())
331    }
332}
333
334#[async_trait]
335impl common::Host for WasmState {}
336
337#[async_trait]
338impl http_client::Host for WasmState {
339    async fn fetch(
340        &mut self,
341        request: http_client::HttpRequest,
342    ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
343        maybe!(async {
344            let url = &request.url;
345            let request = convert_request(&request)?;
346            let mut response = self.host.http_client.send(request).await?;
347
348            if response.status().is_client_error() || response.status().is_server_error() {
349                bail!("failed to fetch '{url}': status code {}", response.status())
350            }
351            convert_response(&mut response).await
352        })
353        .await
354        .to_wasmtime_result()
355    }
356
357    async fn fetch_stream(
358        &mut self,
359        request: http_client::HttpRequest,
360    ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
361        let request = convert_request(&request)?;
362        let response = self.host.http_client.send(request);
363        maybe!(async {
364            let response = response.await?;
365            let stream = Arc::new(Mutex::new(response));
366            let resource = self.table.push(stream)?;
367            Ok(resource)
368        })
369        .await
370        .to_wasmtime_result()
371    }
372}
373
374#[async_trait]
375impl http_client::HostHttpResponseStream for WasmState {
376    async fn next_chunk(
377        &mut self,
378        resource: Resource<ExtensionHttpResponseStream>,
379    ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
380        let stream = self.table.get(&resource)?.clone();
381        maybe!(async move {
382            let mut response = stream.lock().await;
383            let mut buffer = vec![0; 8192]; // 8KB buffer
384            let bytes_read = response.body_mut().read(&mut buffer).await?;
385            if bytes_read == 0 {
386                Ok(None)
387            } else {
388                buffer.truncate(bytes_read);
389                Ok(Some(buffer))
390            }
391        })
392        .await
393        .to_wasmtime_result()
394    }
395
396    fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
397        Ok(())
398    }
399}
400
401impl From<http_client::HttpMethod> for ::http_client::Method {
402    fn from(value: http_client::HttpMethod) -> Self {
403        match value {
404            http_client::HttpMethod::Get => Self::GET,
405            http_client::HttpMethod::Post => Self::POST,
406            http_client::HttpMethod::Put => Self::PUT,
407            http_client::HttpMethod::Delete => Self::DELETE,
408            http_client::HttpMethod::Head => Self::HEAD,
409            http_client::HttpMethod::Options => Self::OPTIONS,
410            http_client::HttpMethod::Patch => Self::PATCH,
411        }
412    }
413}
414
415fn convert_request(
416    extension_request: &http_client::HttpRequest,
417) -> Result<::http_client::Request<AsyncBody>, anyhow::Error> {
418    let mut request = ::http_client::Request::builder()
419        .method(::http_client::Method::from(extension_request.method))
420        .uri(&extension_request.url)
421        .follow_redirects(match extension_request.redirect_policy {
422            http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
423            http_client::RedirectPolicy::FollowLimit(limit) => {
424                ::http_client::RedirectPolicy::FollowLimit(limit)
425            }
426            http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
427        });
428    for (key, value) in &extension_request.headers {
429        request = request.header(key, value);
430    }
431    let body = extension_request
432        .body
433        .clone()
434        .map(AsyncBody::from)
435        .unwrap_or_default();
436    request.body(body).map_err(anyhow::Error::from)
437}
438
439async fn convert_response(
440    response: &mut ::http_client::Response<AsyncBody>,
441) -> Result<http_client::HttpResponse, anyhow::Error> {
442    let mut extension_response = http_client::HttpResponse {
443        body: Vec::new(),
444        headers: Vec::new(),
445    };
446
447    for (key, value) in response.headers() {
448        extension_response
449            .headers
450            .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
451    }
452
453    response
454        .body_mut()
455        .read_to_end(&mut extension_response.body)
456        .await?;
457
458    Ok(extension_response)
459}
460
461#[async_trait]
462impl nodejs::Host for WasmState {
463    async fn node_binary_path(&mut self) -> wasmtime::Result<Result<String, String>> {
464        self.host
465            .node_runtime
466            .binary_path()
467            .await
468            .map(|path| path.to_string_lossy().to_string())
469            .to_wasmtime_result()
470    }
471
472    async fn npm_package_latest_version(
473        &mut self,
474        package_name: String,
475    ) -> wasmtime::Result<Result<String, String>> {
476        self.host
477            .node_runtime
478            .npm_package_latest_version(&package_name)
479            .await
480            .to_wasmtime_result()
481    }
482
483    async fn npm_package_installed_version(
484        &mut self,
485        package_name: String,
486    ) -> wasmtime::Result<Result<Option<String>, String>> {
487        self.host
488            .node_runtime
489            .npm_package_installed_version(&self.work_dir(), &package_name)
490            .await
491            .to_wasmtime_result()
492    }
493
494    async fn npm_install_package(
495        &mut self,
496        package_name: String,
497        version: String,
498    ) -> wasmtime::Result<Result<(), String>> {
499        self.host
500            .node_runtime
501            .npm_install_packages(&self.work_dir(), &[(&package_name, &version)])
502            .await
503            .to_wasmtime_result()
504    }
505}
506
507#[async_trait]
508impl lsp::Host for WasmState {}
509
510impl From<::http_client::github::GithubRelease> for github::GithubRelease {
511    fn from(value: ::http_client::github::GithubRelease) -> Self {
512        Self {
513            version: value.tag_name,
514            assets: value.assets.into_iter().map(Into::into).collect(),
515        }
516    }
517}
518
519impl From<::http_client::github::GithubReleaseAsset> for github::GithubReleaseAsset {
520    fn from(value: ::http_client::github::GithubReleaseAsset) -> Self {
521        Self {
522            name: value.name,
523            download_url: value.browser_download_url,
524        }
525    }
526}
527
528#[async_trait]
529impl github::Host for WasmState {
530    async fn latest_github_release(
531        &mut self,
532        repo: String,
533        options: github::GithubReleaseOptions,
534    ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
535        maybe!(async {
536            let release = ::http_client::github::latest_github_release(
537                &repo,
538                options.require_assets,
539                options.pre_release,
540                self.host.http_client.clone(),
541            )
542            .await?;
543            Ok(release.into())
544        })
545        .await
546        .to_wasmtime_result()
547    }
548
549    async fn github_release_by_tag_name(
550        &mut self,
551        repo: String,
552        tag: String,
553    ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
554        maybe!(async {
555            let release = ::http_client::github::get_release_by_tag_name(
556                &repo,
557                &tag,
558                self.host.http_client.clone(),
559            )
560            .await?;
561            Ok(release.into())
562        })
563        .await
564        .to_wasmtime_result()
565    }
566}
567
568#[async_trait]
569impl platform::Host for WasmState {
570    async fn current_platform(&mut self) -> Result<(platform::Os, platform::Architecture)> {
571        Ok((
572            match env::consts::OS {
573                "macos" => platform::Os::Mac,
574                "linux" => platform::Os::Linux,
575                "windows" => platform::Os::Windows,
576                _ => panic!("unsupported os"),
577            },
578            match env::consts::ARCH {
579                "aarch64" => platform::Architecture::Aarch64,
580                "x86" => platform::Architecture::X86,
581                "x86_64" => platform::Architecture::X8664,
582                _ => panic!("unsupported architecture"),
583            },
584        ))
585    }
586}
587
588#[async_trait]
589impl slash_command::Host for WasmState {}
590
591#[async_trait]
592impl ExtensionImports for WasmState {
593    async fn get_settings(
594        &mut self,
595        location: Option<self::SettingsLocation>,
596        category: String,
597        key: Option<String>,
598    ) -> wasmtime::Result<Result<String, String>> {
599        self.on_main_thread(|cx| {
600            async move {
601                let location = location
602                    .as_ref()
603                    .map(|location| ::settings::SettingsLocation {
604                        worktree_id: WorktreeId::from_proto(location.worktree_id),
605                        path: Path::new(&location.path),
606                    });
607
608                cx.update(|cx| match category.as_str() {
609                    "language" => {
610                        let key = key.map(|k| LanguageName::new(&k));
611                        let settings = AllLanguageSettings::get(location, cx).language(
612                            location,
613                            key.as_ref(),
614                            cx,
615                        );
616                        Ok(serde_json::to_string(&settings::LanguageSettings {
617                            tab_size: settings.tab_size,
618                        })?)
619                    }
620                    "lsp" => {
621                        let settings = key
622                            .and_then(|key| {
623                                ProjectSettings::get(location, cx)
624                                    .lsp
625                                    .get(&::lsp::LanguageServerName::from_proto(key))
626                            })
627                            .cloned()
628                            .unwrap_or_default();
629                        Ok(serde_json::to_string(&settings::LspSettings {
630                            binary: settings.binary.map(|binary| settings::CommandSettings {
631                                path: binary.path,
632                                arguments: binary.arguments,
633                                env: None,
634                            }),
635                            settings: settings.settings,
636                            initialization_options: settings.initialization_options,
637                        })?)
638                    }
639                    "context_servers" => {
640                        let settings = key
641                            .and_then(|key| {
642                                ContextServerSettings::get(location, cx)
643                                    .context_servers
644                                    .get(key.as_str())
645                            })
646                            .cloned()
647                            .unwrap_or_default();
648                        Ok(serde_json::to_string(&settings::ContextServerSettings {
649                            command: settings.command.map(|command| settings::CommandSettings {
650                                path: Some(command.path),
651                                arguments: Some(command.args),
652                                env: command.env.map(|env| env.into_iter().collect()),
653                            }),
654                            settings: settings.settings,
655                        })?)
656                    }
657                    _ => {
658                        bail!("Unknown settings category: {}", category);
659                    }
660                })
661            }
662            .boxed_local()
663        })
664        .await?
665        .to_wasmtime_result()
666    }
667
668    async fn set_language_server_installation_status(
669        &mut self,
670        server_name: String,
671        status: LanguageServerInstallationStatus,
672    ) -> wasmtime::Result<()> {
673        let status = match status {
674            LanguageServerInstallationStatus::CheckingForUpdate => {
675                LanguageServerBinaryStatus::CheckingForUpdate
676            }
677            LanguageServerInstallationStatus::Downloading => {
678                LanguageServerBinaryStatus::Downloading
679            }
680            LanguageServerInstallationStatus::None => LanguageServerBinaryStatus::None,
681            LanguageServerInstallationStatus::Failed(error) => {
682                LanguageServerBinaryStatus::Failed { error }
683            }
684        };
685
686        self.host
687            .proxy
688            .update_language_server_status(::lsp::LanguageServerName(server_name.into()), status);
689
690        Ok(())
691    }
692
693    async fn download_file(
694        &mut self,
695        url: String,
696        path: String,
697        file_type: DownloadedFileType,
698    ) -> wasmtime::Result<Result<(), String>> {
699        maybe!(async {
700            let path = PathBuf::from(path);
701            let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
702
703            self.host.fs.create_dir(&extension_work_dir).await?;
704
705            let destination_path = self
706                .host
707                .writeable_path_from_extension(&self.manifest.id, &path)?;
708
709            let mut response = self
710                .host
711                .http_client
712                .get(&url, Default::default(), true)
713                .await
714                .map_err(|err| anyhow!("error downloading release: {}", err))?;
715
716            if !response.status().is_success() {
717                Err(anyhow!(
718                    "download failed with status {}",
719                    response.status().to_string()
720                ))?;
721            }
722            let body = BufReader::new(response.body_mut());
723
724            match file_type {
725                DownloadedFileType::Uncompressed => {
726                    futures::pin_mut!(body);
727                    self.host
728                        .fs
729                        .create_file_with(&destination_path, body)
730                        .await?;
731                }
732                DownloadedFileType::Gzip => {
733                    let body = GzipDecoder::new(body);
734                    futures::pin_mut!(body);
735                    self.host
736                        .fs
737                        .create_file_with(&destination_path, body)
738                        .await?;
739                }
740                DownloadedFileType::GzipTar => {
741                    let body = GzipDecoder::new(body);
742                    futures::pin_mut!(body);
743                    self.host
744                        .fs
745                        .extract_tar_file(&destination_path, Archive::new(body))
746                        .await?;
747                }
748                DownloadedFileType::Zip => {
749                    futures::pin_mut!(body);
750                    node_runtime::extract_zip(&destination_path, body)
751                        .await
752                        .with_context(|| format!("failed to unzip {} archive", path.display()))?;
753                }
754            }
755
756            Ok(())
757        })
758        .await
759        .to_wasmtime_result()
760    }
761
762    async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
763        #[allow(unused)]
764        let path = self
765            .host
766            .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
767
768        #[cfg(unix)]
769        {
770            use std::fs::{self, Permissions};
771            use std::os::unix::fs::PermissionsExt;
772
773            return fs::set_permissions(&path, Permissions::from_mode(0o755))
774                .map_err(|error| anyhow!("failed to set permissions for path {path:?}: {error}"))
775                .to_wasmtime_result();
776        }
777
778        #[cfg(not(unix))]
779        Ok(Ok(()))
780    }
781}