mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 08:39:02 +03:00
refactor(cli-rs): use one encoder for URL components
Mini and the store each rebuilt encodeURIComponent for global form headers. The CLI built it again for operation parameters, and encoded a directory through a fallible JSON serialization. Use the generated client's existing byte set for all of them. Query encoding stays apart. operations_fill_path_parameters_and_query now includes non-ASCII bytes, reserved characters and unescaped punctuation. The API request oracle and keeps_global_forms_per_location_and_settles_them_with_the_location_header cover the API and store paths.
This commit is contained in:
@@ -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<T> Call<T> {
|
||||
|
||||
/// A path parameter: `String(value)` encoded like `encodeURIComponent`.
|
||||
pub fn param<V: Serialize + ?Sized>(&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<V: Serialize + ?Sized>(value: &V) -> Result<String, String> {
|
||||
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::<Vec<_>>().join("/")
|
||||
value.split('/').map(encode_component).collect::<Vec<_>>().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')');
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -160,7 +160,7 @@ fn interpolate(path: &str, params: &[(String, String)]) -> error::Result<String>
|
||||
};
|
||||
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<String>
|
||||
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(),
|
||||
|
||||
@@ -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
|
||||
};
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)!");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user