since_v0_6_0.rs

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