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| s.to_string_lossy().into_owned()),
 313        })
 314    }
 315}
 316
 317impl From<CodeLabel> for extension::CodeLabel {
 318    fn from(value: CodeLabel) -> Self {
 319        Self {
 320            code: value.code,
 321            spans: value.spans.into_iter().map(Into::into).collect(),
 322            filter_range: value.filter_range.into(),
 323        }
 324    }
 325}
 326
 327impl From<CodeLabelSpan> for extension::CodeLabelSpan {
 328    fn from(value: CodeLabelSpan) -> Self {
 329        match value {
 330            CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
 331            CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
 332        }
 333    }
 334}
 335
 336impl From<CodeLabelSpanLiteral> for extension::CodeLabelSpanLiteral {
 337    fn from(value: CodeLabelSpanLiteral) -> Self {
 338        Self {
 339            text: value.text,
 340            highlight_name: value.highlight_name,
 341        }
 342    }
 343}
 344
 345impl From<extension::Completion> for Completion {
 346    fn from(value: extension::Completion) -> Self {
 347        Self {
 348            label: value.label,
 349            label_details: value.label_details.map(Into::into),
 350            detail: value.detail,
 351            kind: value.kind.map(Into::into),
 352            insert_text_format: value.insert_text_format.map(Into::into),
 353        }
 354    }
 355}
 356
 357impl From<extension::CompletionLabelDetails> for CompletionLabelDetails {
 358    fn from(value: extension::CompletionLabelDetails) -> Self {
 359        Self {
 360            detail: value.detail,
 361            description: value.description,
 362        }
 363    }
 364}
 365
 366impl From<extension::CompletionKind> for CompletionKind {
 367    fn from(value: extension::CompletionKind) -> Self {
 368        match value {
 369            extension::CompletionKind::Text => Self::Text,
 370            extension::CompletionKind::Method => Self::Method,
 371            extension::CompletionKind::Function => Self::Function,
 372            extension::CompletionKind::Constructor => Self::Constructor,
 373            extension::CompletionKind::Field => Self::Field,
 374            extension::CompletionKind::Variable => Self::Variable,
 375            extension::CompletionKind::Class => Self::Class,
 376            extension::CompletionKind::Interface => Self::Interface,
 377            extension::CompletionKind::Module => Self::Module,
 378            extension::CompletionKind::Property => Self::Property,
 379            extension::CompletionKind::Unit => Self::Unit,
 380            extension::CompletionKind::Value => Self::Value,
 381            extension::CompletionKind::Enum => Self::Enum,
 382            extension::CompletionKind::Keyword => Self::Keyword,
 383            extension::CompletionKind::Snippet => Self::Snippet,
 384            extension::CompletionKind::Color => Self::Color,
 385            extension::CompletionKind::File => Self::File,
 386            extension::CompletionKind::Reference => Self::Reference,
 387            extension::CompletionKind::Folder => Self::Folder,
 388            extension::CompletionKind::EnumMember => Self::EnumMember,
 389            extension::CompletionKind::Constant => Self::Constant,
 390            extension::CompletionKind::Struct => Self::Struct,
 391            extension::CompletionKind::Event => Self::Event,
 392            extension::CompletionKind::Operator => Self::Operator,
 393            extension::CompletionKind::TypeParameter => Self::TypeParameter,
 394            extension::CompletionKind::Other(value) => Self::Other(value),
 395        }
 396    }
 397}
 398
 399impl From<extension::InsertTextFormat> for InsertTextFormat {
 400    fn from(value: extension::InsertTextFormat) -> Self {
 401        match value {
 402            extension::InsertTextFormat::PlainText => Self::PlainText,
 403            extension::InsertTextFormat::Snippet => Self::Snippet,
 404            extension::InsertTextFormat::Other(value) => Self::Other(value),
 405        }
 406    }
 407}
 408
 409impl From<extension::Symbol> for Symbol {
 410    fn from(value: extension::Symbol) -> Self {
 411        Self {
 412            kind: value.kind.into(),
 413            name: value.name,
 414        }
 415    }
 416}
 417
 418impl From<extension::SymbolKind> for SymbolKind {
 419    fn from(value: extension::SymbolKind) -> Self {
 420        match value {
 421            extension::SymbolKind::File => Self::File,
 422            extension::SymbolKind::Module => Self::Module,
 423            extension::SymbolKind::Namespace => Self::Namespace,
 424            extension::SymbolKind::Package => Self::Package,
 425            extension::SymbolKind::Class => Self::Class,
 426            extension::SymbolKind::Method => Self::Method,
 427            extension::SymbolKind::Property => Self::Property,
 428            extension::SymbolKind::Field => Self::Field,
 429            extension::SymbolKind::Constructor => Self::Constructor,
 430            extension::SymbolKind::Enum => Self::Enum,
 431            extension::SymbolKind::Interface => Self::Interface,
 432            extension::SymbolKind::Function => Self::Function,
 433            extension::SymbolKind::Variable => Self::Variable,
 434            extension::SymbolKind::Constant => Self::Constant,
 435            extension::SymbolKind::String => Self::String,
 436            extension::SymbolKind::Number => Self::Number,
 437            extension::SymbolKind::Boolean => Self::Boolean,
 438            extension::SymbolKind::Array => Self::Array,
 439            extension::SymbolKind::Object => Self::Object,
 440            extension::SymbolKind::Key => Self::Key,
 441            extension::SymbolKind::Null => Self::Null,
 442            extension::SymbolKind::EnumMember => Self::EnumMember,
 443            extension::SymbolKind::Struct => Self::Struct,
 444            extension::SymbolKind::Event => Self::Event,
 445            extension::SymbolKind::Operator => Self::Operator,
 446            extension::SymbolKind::TypeParameter => Self::TypeParameter,
 447            extension::SymbolKind::Other(value) => Self::Other(value),
 448        }
 449    }
 450}
 451
 452impl From<extension::SlashCommand> for SlashCommand {
 453    fn from(value: extension::SlashCommand) -> Self {
 454        Self {
 455            name: value.name,
 456            description: value.description,
 457            tooltip_text: value.tooltip_text,
 458            requires_argument: value.requires_argument,
 459        }
 460    }
 461}
 462
 463impl From<SlashCommandOutput> for extension::SlashCommandOutput {
 464    fn from(value: SlashCommandOutput) -> Self {
 465        Self {
 466            text: value.text,
 467            sections: value.sections.into_iter().map(Into::into).collect(),
 468        }
 469    }
 470}
 471
 472impl From<SlashCommandOutputSection> for extension::SlashCommandOutputSection {
 473    fn from(value: SlashCommandOutputSection) -> Self {
 474        Self {
 475            range: value.range.start as usize..value.range.end as usize,
 476            label: value.label,
 477        }
 478    }
 479}
 480
 481impl From<SlashCommandArgumentCompletion> for extension::SlashCommandArgumentCompletion {
 482    fn from(value: SlashCommandArgumentCompletion) -> Self {
 483        Self {
 484            label: value.label,
 485            new_text: value.new_text,
 486            run_command: value.run_command,
 487        }
 488    }
 489}
 490
 491impl TryFrom<ContextServerConfiguration> for extension::ContextServerConfiguration {
 492    type Error = anyhow::Error;
 493
 494    fn try_from(value: ContextServerConfiguration) -> Result<Self, Self::Error> {
 495        let settings_schema: serde_json::Value = serde_json::from_str(&value.settings_schema)
 496            .context("Failed to parse settings_schema")?;
 497
 498        Ok(Self {
 499            installation_instructions: value.installation_instructions,
 500            default_settings: value.default_settings,
 501            settings_schema,
 502        })
 503    }
 504}
 505
 506impl HostKeyValueStore for WasmState {
 507    async fn insert(
 508        &mut self,
 509        kv_store: Resource<ExtensionKeyValueStore>,
 510        key: String,
 511        value: String,
 512    ) -> wasmtime::Result<Result<(), String>> {
 513        let kv_store = self.table.get(&kv_store)?;
 514        kv_store.insert(key, value).await.to_wasmtime_result()
 515    }
 516
 517    async fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
 518        // We only ever hand out borrows of key-value stores.
 519        Ok(())
 520    }
 521}
 522
 523impl HostProject for WasmState {
 524    async fn worktree_ids(
 525        &mut self,
 526        project: Resource<ExtensionProject>,
 527    ) -> wasmtime::Result<Vec<u64>> {
 528        let project = self.table.get(&project)?;
 529        Ok(project.worktree_ids())
 530    }
 531
 532    async fn drop(&mut self, _project: Resource<Project>) -> Result<()> {
 533        // We only ever hand out borrows of projects.
 534        Ok(())
 535    }
 536}
 537
 538impl HostWorktree for WasmState {
 539    async fn id(&mut self, delegate: Resource<Arc<dyn WorktreeDelegate>>) -> wasmtime::Result<u64> {
 540        let delegate = self.table.get(&delegate)?;
 541        Ok(delegate.id())
 542    }
 543
 544    async fn root_path(
 545        &mut self,
 546        delegate: Resource<Arc<dyn WorktreeDelegate>>,
 547    ) -> wasmtime::Result<String> {
 548        let delegate = self.table.get(&delegate)?;
 549        Ok(delegate.root_path())
 550    }
 551
 552    async fn read_text_file(
 553        &mut self,
 554        delegate: Resource<Arc<dyn WorktreeDelegate>>,
 555        path: String,
 556    ) -> wasmtime::Result<Result<String, String>> {
 557        let delegate = self.table.get(&delegate)?;
 558        Ok(delegate
 559            .read_text_file(path.into())
 560            .await
 561            .map_err(|error| error.to_string()))
 562    }
 563
 564    async fn shell_env(
 565        &mut self,
 566        delegate: Resource<Arc<dyn WorktreeDelegate>>,
 567    ) -> wasmtime::Result<EnvVars> {
 568        let delegate = self.table.get(&delegate)?;
 569        Ok(delegate.shell_env().await.into_iter().collect())
 570    }
 571
 572    async fn which(
 573        &mut self,
 574        delegate: Resource<Arc<dyn WorktreeDelegate>>,
 575        binary_name: String,
 576    ) -> wasmtime::Result<Option<String>> {
 577        let delegate = self.table.get(&delegate)?;
 578        Ok(delegate.which(binary_name).await)
 579    }
 580
 581    async fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
 582        // We only ever hand out borrows of worktrees.
 583        Ok(())
 584    }
 585}
 586
 587impl common::Host for WasmState {}
 588
 589impl http_client::Host for WasmState {
 590    async fn fetch(
 591        &mut self,
 592        request: http_client::HttpRequest,
 593    ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
 594        maybe!(async {
 595            let url = &request.url;
 596            let request = convert_request(&request)?;
 597            let mut response = self.host.http_client.send(request).await?;
 598
 599            if response.status().is_client_error() || response.status().is_server_error() {
 600                bail!("failed to fetch '{url}': status code {}", response.status())
 601            }
 602            convert_response(&mut response).await
 603        })
 604        .await
 605        .to_wasmtime_result()
 606    }
 607
 608    async fn fetch_stream(
 609        &mut self,
 610        request: http_client::HttpRequest,
 611    ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
 612        let request = convert_request(&request)?;
 613        let response = self.host.http_client.send(request);
 614        maybe!(async {
 615            let response = response.await?;
 616            let stream = Arc::new(Mutex::new(response));
 617            let resource = self.table.push(stream)?;
 618            Ok(resource)
 619        })
 620        .await
 621        .to_wasmtime_result()
 622    }
 623}
 624
 625impl http_client::HostHttpResponseStream for WasmState {
 626    async fn next_chunk(
 627        &mut self,
 628        resource: Resource<ExtensionHttpResponseStream>,
 629    ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
 630        let stream = self.table.get(&resource)?.clone();
 631        maybe!(async move {
 632            let mut response = stream.lock().await;
 633            let mut buffer = vec![0; 8192]; // 8KB buffer
 634            let bytes_read = response.body_mut().read(&mut buffer).await?;
 635            if bytes_read == 0 {
 636                Ok(None)
 637            } else {
 638                buffer.truncate(bytes_read);
 639                Ok(Some(buffer))
 640            }
 641        })
 642        .await
 643        .to_wasmtime_result()
 644    }
 645
 646    async fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
 647        Ok(())
 648    }
 649}
 650
 651impl From<http_client::HttpMethod> for ::http_client::Method {
 652    fn from(value: http_client::HttpMethod) -> Self {
 653        match value {
 654            http_client::HttpMethod::Get => Self::GET,
 655            http_client::HttpMethod::Post => Self::POST,
 656            http_client::HttpMethod::Put => Self::PUT,
 657            http_client::HttpMethod::Delete => Self::DELETE,
 658            http_client::HttpMethod::Head => Self::HEAD,
 659            http_client::HttpMethod::Options => Self::OPTIONS,
 660            http_client::HttpMethod::Patch => Self::PATCH,
 661        }
 662    }
 663}
 664
 665fn convert_request(
 666    extension_request: &http_client::HttpRequest,
 667) -> anyhow::Result<::http_client::Request<AsyncBody>> {
 668    let mut request = ::http_client::Request::builder()
 669        .method(::http_client::Method::from(extension_request.method))
 670        .uri(&extension_request.url)
 671        .follow_redirects(match extension_request.redirect_policy {
 672            http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
 673            http_client::RedirectPolicy::FollowLimit(limit) => {
 674                ::http_client::RedirectPolicy::FollowLimit(limit)
 675            }
 676            http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
 677        });
 678    for (key, value) in &extension_request.headers {
 679        request = request.header(key, value);
 680    }
 681    let body = extension_request
 682        .body
 683        .clone()
 684        .map(AsyncBody::from)
 685        .unwrap_or_default();
 686    request.body(body).map_err(anyhow::Error::from)
 687}
 688
 689async fn convert_response(
 690    response: &mut ::http_client::Response<AsyncBody>,
 691) -> anyhow::Result<http_client::HttpResponse> {
 692    let mut extension_response = http_client::HttpResponse {
 693        body: Vec::new(),
 694        headers: Vec::new(),
 695    };
 696
 697    for (key, value) in response.headers() {
 698        extension_response
 699            .headers
 700            .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
 701    }
 702
 703    response
 704        .body_mut()
 705        .read_to_end(&mut extension_response.body)
 706        .await?;
 707
 708    Ok(extension_response)
 709}
 710
 711impl nodejs::Host for WasmState {
 712    async fn node_binary_path(&mut self) -> wasmtime::Result<Result<String, String>> {
 713        self.host
 714            .node_runtime
 715            .binary_path()
 716            .await
 717            .map(|path| path.to_string_lossy().to_string())
 718            .to_wasmtime_result()
 719    }
 720
 721    async fn npm_package_latest_version(
 722        &mut self,
 723        package_name: String,
 724    ) -> wasmtime::Result<Result<String, String>> {
 725        self.host
 726            .node_runtime
 727            .npm_package_latest_version(&package_name)
 728            .await
 729            .to_wasmtime_result()
 730    }
 731
 732    async fn npm_package_installed_version(
 733        &mut self,
 734        package_name: String,
 735    ) -> wasmtime::Result<Result<Option<String>, String>> {
 736        self.host
 737            .node_runtime
 738            .npm_package_installed_version(&self.work_dir(), &package_name)
 739            .await
 740            .to_wasmtime_result()
 741    }
 742
 743    async fn npm_install_package(
 744        &mut self,
 745        package_name: String,
 746        version: String,
 747    ) -> wasmtime::Result<Result<(), String>> {
 748        self.host
 749            .node_runtime
 750            .npm_install_packages(&self.work_dir(), &[(&package_name, &version)])
 751            .await
 752            .to_wasmtime_result()
 753    }
 754}
 755
 756#[async_trait]
 757impl lsp::Host for WasmState {}
 758
 759impl From<::http_client::github::GithubRelease> for github::GithubRelease {
 760    fn from(value: ::http_client::github::GithubRelease) -> Self {
 761        Self {
 762            version: value.tag_name,
 763            assets: value.assets.into_iter().map(Into::into).collect(),
 764        }
 765    }
 766}
 767
 768impl From<::http_client::github::GithubReleaseAsset> for github::GithubReleaseAsset {
 769    fn from(value: ::http_client::github::GithubReleaseAsset) -> Self {
 770        Self {
 771            name: value.name,
 772            download_url: value.browser_download_url,
 773        }
 774    }
 775}
 776
 777impl github::Host for WasmState {
 778    async fn latest_github_release(
 779        &mut self,
 780        repo: String,
 781        options: github::GithubReleaseOptions,
 782    ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
 783        maybe!(async {
 784            let release = ::http_client::github::latest_github_release(
 785                &repo,
 786                options.require_assets,
 787                options.pre_release,
 788                self.host.http_client.clone(),
 789            )
 790            .await?;
 791            Ok(release.into())
 792        })
 793        .await
 794        .to_wasmtime_result()
 795    }
 796
 797    async fn github_release_by_tag_name(
 798        &mut self,
 799        repo: String,
 800        tag: String,
 801    ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
 802        maybe!(async {
 803            let release = ::http_client::github::get_release_by_tag_name(
 804                &repo,
 805                &tag,
 806                self.host.http_client.clone(),
 807            )
 808            .await?;
 809            Ok(release.into())
 810        })
 811        .await
 812        .to_wasmtime_result()
 813    }
 814}
 815
 816impl platform::Host for WasmState {
 817    async fn current_platform(&mut self) -> Result<(platform::Os, platform::Architecture)> {
 818        Ok((
 819            match env::consts::OS {
 820                "macos" => platform::Os::Mac,
 821                "linux" => platform::Os::Linux,
 822                "windows" => platform::Os::Windows,
 823                _ => panic!("unsupported os"),
 824            },
 825            match env::consts::ARCH {
 826                "aarch64" => platform::Architecture::Aarch64,
 827                "x86" => platform::Architecture::X86,
 828                "x86_64" => platform::Architecture::X8664,
 829                _ => panic!("unsupported architecture"),
 830            },
 831        ))
 832    }
 833}
 834
 835impl From<std::process::Output> for process::Output {
 836    fn from(output: std::process::Output) -> Self {
 837        Self {
 838            status: output.status.code(),
 839            stdout: output.stdout,
 840            stderr: output.stderr,
 841        }
 842    }
 843}
 844
 845impl process::Host for WasmState {
 846    async fn run_command(
 847        &mut self,
 848        command: process::Command,
 849    ) -> wasmtime::Result<Result<process::Output, String>> {
 850        maybe!(async {
 851            self.capability_granter
 852                .grant_exec(&command.command, &command.args)?;
 853
 854            let output = util::command::new_smol_command(command.command.as_str())
 855                .args(&command.args)
 856                .envs(command.env)
 857                .output()
 858                .await?;
 859
 860            Ok(output.into())
 861        })
 862        .await
 863        .to_wasmtime_result()
 864    }
 865}
 866
 867#[async_trait]
 868impl slash_command::Host for WasmState {}
 869
 870#[async_trait]
 871impl context_server::Host for WasmState {}
 872
 873impl dap::Host for WasmState {
 874    async fn resolve_tcp_template(
 875        &mut self,
 876        template: TcpArgumentsTemplate,
 877    ) -> wasmtime::Result<Result<TcpArguments, String>> {
 878        maybe!(async {
 879            let (host, port, timeout) =
 880                ::dap::configure_tcp_connection(task::TcpArgumentsTemplate {
 881                    port: template.port,
 882                    host: template.host.map(Ipv4Addr::from_bits),
 883                    timeout: template.timeout,
 884                })
 885                .await?;
 886            Ok(TcpArguments {
 887                port,
 888                host: host.to_bits(),
 889                timeout,
 890            })
 891        })
 892        .await
 893        .to_wasmtime_result()
 894    }
 895}
 896
 897impl ExtensionImports for WasmState {
 898    async fn get_settings(
 899        &mut self,
 900        location: Option<self::SettingsLocation>,
 901        category: String,
 902        key: Option<String>,
 903    ) -> wasmtime::Result<Result<String, String>> {
 904        self.on_main_thread(|cx| {
 905            async move {
 906                let location = location
 907                    .as_ref()
 908                    .map(|location| ::settings::SettingsLocation {
 909                        worktree_id: WorktreeId::from_proto(location.worktree_id),
 910                        path: Path::new(&location.path),
 911                    });
 912
 913                cx.update(|cx| match category.as_str() {
 914                    "language" => {
 915                        let key = key.map(|k| LanguageName::new(&k));
 916                        let settings = AllLanguageSettings::get(location, cx).language(
 917                            location,
 918                            key.as_ref(),
 919                            cx,
 920                        );
 921                        Ok(serde_json::to_string(&settings::LanguageSettings {
 922                            tab_size: settings.tab_size,
 923                        })?)
 924                    }
 925                    "lsp" => {
 926                        let settings = key
 927                            .and_then(|key| {
 928                                ProjectSettings::get(location, cx)
 929                                    .lsp
 930                                    .get(&::lsp::LanguageServerName::from_proto(key))
 931                            })
 932                            .cloned()
 933                            .unwrap_or_default();
 934                        Ok(serde_json::to_string(&settings::LspSettings {
 935                            binary: settings.binary.map(|binary| settings::CommandSettings {
 936                                path: binary.path,
 937                                arguments: binary.arguments,
 938                                env: binary.env,
 939                            }),
 940                            settings: settings.settings,
 941                            initialization_options: settings.initialization_options,
 942                        })?)
 943                    }
 944                    "context_servers" => {
 945                        let settings = key
 946                            .and_then(|key| {
 947                                ProjectSettings::get(location, cx)
 948                                    .context_servers
 949                                    .get(key.as_str())
 950                            })
 951                            .cloned()
 952                            .unwrap_or_else(|| {
 953                                project::project_settings::ContextServerSettings::default_extension(
 954                                )
 955                            });
 956
 957                        match settings {
 958                            project::project_settings::ContextServerSettings::Custom {
 959                                enabled: _,
 960                                command,
 961                            } => Ok(serde_json::to_string(&settings::ContextServerSettings {
 962                                command: Some(settings::CommandSettings {
 963                                    path: command.path.to_str().map(|path| path.to_string()),
 964                                    arguments: Some(command.args),
 965                                    env: command.env.map(|env| env.into_iter().collect()),
 966                                }),
 967                                settings: None,
 968                            })?),
 969                            project::project_settings::ContextServerSettings::Extension {
 970                                enabled: _,
 971                                settings,
 972                            } => Ok(serde_json::to_string(&settings::ContextServerSettings {
 973                                command: None,
 974                                settings: Some(settings),
 975                            })?),
 976                        }
 977                    }
 978                    _ => {
 979                        bail!("Unknown settings category: {}", category);
 980                    }
 981                })
 982            }
 983            .boxed_local()
 984        })
 985        .await?
 986        .to_wasmtime_result()
 987    }
 988
 989    async fn set_language_server_installation_status(
 990        &mut self,
 991        server_name: String,
 992        status: LanguageServerInstallationStatus,
 993    ) -> wasmtime::Result<()> {
 994        let status = match status {
 995            LanguageServerInstallationStatus::CheckingForUpdate => BinaryStatus::CheckingForUpdate,
 996            LanguageServerInstallationStatus::Downloading => BinaryStatus::Downloading,
 997            LanguageServerInstallationStatus::None => BinaryStatus::None,
 998            LanguageServerInstallationStatus::Failed(error) => BinaryStatus::Failed { error },
 999        };
1000
1001        self.host
1002            .proxy
1003            .update_language_server_status(::lsp::LanguageServerName(server_name.into()), status);
1004
1005        Ok(())
1006    }
1007
1008    async fn download_file(
1009        &mut self,
1010        url: String,
1011        path: String,
1012        file_type: DownloadedFileType,
1013    ) -> wasmtime::Result<Result<(), String>> {
1014        maybe!(async {
1015            let parsed_url = Url::parse(&url)?;
1016            self.capability_granter.grant_download_file(&parsed_url)?;
1017
1018            let path = PathBuf::from(path);
1019            let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
1020
1021            self.host.fs.create_dir(&extension_work_dir).await?;
1022
1023            let destination_path = self
1024                .host
1025                .writeable_path_from_extension(&self.manifest.id, &path)?;
1026
1027            let mut response = self
1028                .host
1029                .http_client
1030                .get(&url, Default::default(), true)
1031                .await
1032                .context("downloading release")?;
1033
1034            anyhow::ensure!(
1035                response.status().is_success(),
1036                "download failed with status {}",
1037                response.status().to_string()
1038            );
1039            let body = BufReader::new(response.body_mut());
1040
1041            match file_type {
1042                DownloadedFileType::Uncompressed => {
1043                    futures::pin_mut!(body);
1044                    self.host
1045                        .fs
1046                        .create_file_with(&destination_path, body)
1047                        .await?;
1048                }
1049                DownloadedFileType::Gzip => {
1050                    let body = GzipDecoder::new(body);
1051                    futures::pin_mut!(body);
1052                    self.host
1053                        .fs
1054                        .create_file_with(&destination_path, body)
1055                        .await?;
1056                }
1057                DownloadedFileType::GzipTar => {
1058                    let body = GzipDecoder::new(body);
1059                    futures::pin_mut!(body);
1060                    self.host
1061                        .fs
1062                        .extract_tar_file(&destination_path, Archive::new(body))
1063                        .await?;
1064                }
1065                DownloadedFileType::Zip => {
1066                    futures::pin_mut!(body);
1067                    extract_zip(&destination_path, body)
1068                        .await
1069                        .with_context(|| format!("unzipping {path:?} archive"))?;
1070                }
1071            }
1072
1073            Ok(())
1074        })
1075        .await
1076        .to_wasmtime_result()
1077    }
1078
1079    async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
1080        let path = self
1081            .host
1082            .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
1083
1084        make_file_executable(&path)
1085            .await
1086            .with_context(|| format!("setting permissions for path {path:?}"))
1087            .to_wasmtime_result()
1088    }
1089}