diff --git a/packages/cli-rs/crates/api-types/src/call.rs b/packages/cli-rs/crates/api-types/src/call.rs index b226c8b8290..a2d9582d458 100644 --- a/packages/cli-rs/crates/api-types/src/call.rs +++ b/packages/cli-rs/crates/api-types/src/call.rs @@ -7,12 +7,11 @@ use std::marker::PhantomData; use bytes::Bytes; -use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode}; use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::Value; -use crate::js::js_string; +use crate::js::{encode_component, js_string}; /// One request of the API, whose reply decodes as `T` ([`Call::decode`]). A builder never fails: an input that does not /// serialize is kept as [`Call::error`], which whoever sends the call reports instead of sending it. @@ -82,9 +81,7 @@ impl Call { /// A path parameter: `String(value)` encoded like `encodeURIComponent`. pub fn param(&mut self, value: &V) -> String { - self.value(value) - .map(|value| utf8_percent_encode(&js_string(&value), COMPONENT).to_string()) - .unwrap_or_default() + self.value(value).map(|value| encode_component(&js_string(&value))).unwrap_or_default() } /// Adds a query value, bracket-encoded like `appendQuery`. @@ -187,22 +184,10 @@ pub fn encode(pairs: &[(String, String)]) -> String { /// A path parameter: `String(value)` encoded like `encodeURIComponent`. pub fn path_param(value: &V) -> Result { let value = serde_json::to_value(value).map_err(|error| format!("encode request: {error}"))?; - Ok(utf8_percent_encode(&js_string(&value), COMPONENT).to_string()) + Ok(encode_component(&js_string(&value))) } /// A trailing wildcard path, each segment encoded like `encodeURIComponent`. pub fn path_wildcard(value: &str) -> String { - value.split('/').map(|segment| utf8_percent_encode(segment, COMPONENT).to_string()).collect::>().join("/") + value.split('/').map(encode_component).collect::>().join("/") } - -/// The characters `encodeURIComponent` escapes: everything except `A-Z a-z 0-9 - _ . ! ~ * ' ( )`. -const COMPONENT: &AsciiSet = &NON_ALPHANUMERIC - .remove(b'-') - .remove(b'_') - .remove(b'.') - .remove(b'!') - .remove(b'~') - .remove(b'*') - .remove(b'\'') - .remove(b'(') - .remove(b')'); diff --git a/packages/cli-rs/crates/api-types/src/js.rs b/packages/cli-rs/crates/api-types/src/js.rs index 5b5e143eac7..b87a60bc99a 100644 --- a/packages/cli-rs/crates/api-types/src/js.rs +++ b/packages/cli-rs/crates/api-types/src/js.rs @@ -2,6 +2,23 @@ use std::cmp::Ordering; +use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode}; + +/// `encodeURIComponent`, for both path parameters and the location header. +pub fn encode_component(value: &str) -> String { + const COMPONENT: &AsciiSet = &NON_ALPHANUMERIC + .remove(b'-') + .remove(b'_') + .remove(b'.') + .remove(b'!') + .remove(b'~') + .remove(b'*') + .remove(b'\'') + .remove(b'(') + .remove(b')'); + utf8_percent_encode(value, COMPONENT).to_string() +} + /// `a.localeCompare(b)` for the root locale, as Bun's ICU orders ASCII: punctuation and symbols /// first in ICU's order, then digits, then letters without regard to case; ties go to lowercase /// first, then to code points. Other characters sort after letters by code point. diff --git a/packages/cli-rs/crates/cli/src/commands/api.rs b/packages/cli-rs/crates/cli/src/commands/api.rs index 4ea55b0b821..14149df8e05 100644 --- a/packages/cli-rs/crates/cli/src/commands/api.rs +++ b/packages/cli-rs/crates/cli/src/commands/api.rs @@ -160,7 +160,7 @@ fn interpolate(path: &str, params: &[(String, String)]) -> error::Result }; used.push(key); pathname.push_str(&rest[..open]); - pathname.push_str(&encode_uri_component(value)); + pathname.push_str(&opencode_api::js::encode_component(value)); rest = &rest[open + close + 2..]; } pathname.push_str(rest); @@ -175,19 +175,6 @@ fn interpolate(path: &str, params: &[(String, String)]) -> error::Result Ok(format!("{pathname}?{query}")) } -// `encodeURIComponent`. -fn encode_uri_component(value: &str) -> String { - value - .bytes() - .map(|byte| match byte { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')' => { - (byte as char).to_string() - } - byte => format!("%{byte:02X}"), - }) - .collect() -} - #[cfg(test)] mod tests { use super::*; @@ -217,10 +204,10 @@ mod tests { "delete": { "operationId": "session.message.delete" }, }, }}); - let params = pairs(&[("sessionID", "ses 1/2"), ("limit", "5"), ("messageID", "msg_1"), ("q", "a b&c")]); + let params = pairs(&[("sessionID", "ses 1/é(x)!&="), ("limit", "5"), ("messageID", "msg_1"), ("q", "a b&c")]); assert_eq!( resolve_operation(&spec, "session.message.delete", ¶ms).unwrap(), - ("DELETE", "/api/session/ses%201%2F2/message/msg_1?limit=5&q=a+b%26c".to_owned()) + ("DELETE", "/api/session/ses%201%2F%C3%A9(x)!%26%3D/message/msg_1?limit=5&q=a+b%26c".to_owned()) ); assert_eq!( resolve_operation(&spec, "session.get", &pairs(&[("sessionID", "ses/a"), ("workspace", "work")])).unwrap(), diff --git a/packages/cli-rs/crates/cli/src/run/prompt.rs b/packages/cli-rs/crates/cli/src/run/prompt.rs index 3f1a1a6a659..d6e8dc8c1eb 100644 --- a/packages/cli-rs/crates/cli/src/run/prompt.rs +++ b/packages/cli-rs/crates/cli/src/run/prompt.rs @@ -583,7 +583,7 @@ impl Run { })?; // A global form is found through its location. if session == "global" { - call.header("x-opencode-directory", &opencode_api::client::path_param(&self.input.directory)?)?; + call.header("x-opencode-directory", &opencode_api::js::encode_component(&self.input.directory))?; } self.input.client.empty(call).await }; diff --git a/packages/cli-rs/crates/mini/src/footers/mod.rs b/packages/cli-rs/crates/mini/src/footers/mod.rs index 04096b62c0a..567a8cd3086 100644 --- a/packages/cli-rs/crates/mini/src/footers/mod.rs +++ b/packages/cli-rs/crates/mini/src/footers/mod.rs @@ -1868,18 +1868,7 @@ fn form_client(target: &Target, form: &FormInfo) -> Client { if form.session_id != GLOBAL { return target.client.clone(); } - // `encodeURIComponent`. - let directory: String = target - .directory - .bytes() - .map(|byte| match byte { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')' => { - char::from(byte).to_string() - } - _ => format!("%{byte:02X}"), - }) - .collect(); - target.client.with_header("x-opencode-directory", directory) + target.client.with_header("x-opencode-directory", opencode_api::js::encode_component(&target.directory)) } /// `openUrl`: a form's URL is not trusted to name a web link, so anything else fails before a process starts. diff --git a/packages/cli-rs/crates/store/src/forms.rs b/packages/cli-rs/crates/store/src/forms.rs index a5cefb5d333..055c2daff09 100644 --- a/packages/cli-rs/crates/store/src/forms.rs +++ b/packages/cli-rs/crates/store/src/forms.rs @@ -209,28 +209,9 @@ impl Data { /// Global forms name their location in a header (`formRequestOptions`). fn form_client(client: &Client, owner: &str, location: Option<&Location>) -> Client { match (owner, location) { - (GLOBAL, Some(location)) => client.with_header("x-opencode-directory", encode_component(&location.directory)), + (GLOBAL, Some(location)) => { + client.with_header("x-opencode-directory", opencode_api::js::encode_component(&location.directory)) + } _ => client.clone(), } } - -/// `encodeURIComponent`. -fn encode_component(value: &str) -> String { - value - .bytes() - .map(|byte| match byte { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')' => { - (byte as char).to_string() - } - _ => format!("%{byte:02X}"), - }) - .collect() -} - -#[cfg(test)] -mod tests { - #[test] - fn encodes_like_encode_uri_component() { - assert_eq!(super::encode_component("/tmp/a b&c=d/é(x)!"), "%2Ftmp%2Fa%20b%26c%3Dd%2F%C3%A9(x)!"); - } -}