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