1use std::fmt::Display;
15
16use bitwarden_error::wasm::{CONVERSION_ERROR_NAME, SdkJsError};
17use tsify::{Ts, Tsify};
18use wasm_bindgen::JsValue;
19
20#[derive(Debug, thiserror::Error)]
22pub enum WireError {
23 #[error("Failed to parse `{type_name}`: {message}")]
25 Parse {
26 type_name: &'static str,
28 message: String,
30 },
31 #[error(transparent)]
33 Serde(#[from] tsify::Error),
34}
35
36pub trait FromWasm: Sized {
38 type Wire;
40
41 fn from_wire(wire: Self::Wire) -> Result<Self, WireError>;
43}
44
45pub trait ToWasm {
47 type Wire;
49
50 fn to_wire(self) -> Result<Self::Wire, WireError>;
52}
53
54#[doc(hidden)]
57pub fn parse_wire_string<T, E: Display>(
58 type_name: &'static str,
59 wire: String,
60 parse: impl FnOnce(String) -> Result<T, E>,
61) -> Result<T, WireError> {
62 parse(wire).map_err(|err| WireError::Parse {
63 type_name,
64 message: err.to_string(),
65 })
66}
67
68#[doc(hidden)]
70pub fn format_wire_string<T>(value: T, format: impl FnOnce(T) -> String) -> String {
71 format(value)
72}
73
74crate::impl_wire_object!(
77 bool,
78 char,
79 f32,
80 f64,
81 i8,
82 i16,
83 i32,
84 i64,
85 i128,
86 isize,
87 u8,
88 u16,
89 u32,
90 u64,
91 u128,
92 usize,
93 (),
94 String,
95 JsValue,
96);
97
98crate::impl_wire_object!(js_sys::Array);
100
101impl<T: FromWasm> FromWasm for Vec<T> {
106 type Wire = Vec<T::Wire>;
107
108 fn from_wire(wire: Self::Wire) -> Result<Self, WireError> {
109 wire.into_iter().map(T::from_wire).collect()
110 }
111}
112
113impl<T: ToWasm> ToWasm for Vec<T> {
114 type Wire = Vec<T::Wire>;
115
116 fn to_wire(self) -> Result<Self::Wire, WireError> {
117 self.into_iter().map(T::to_wire).collect()
118 }
119}
120
121impl<T: FromWasm> FromWasm for Option<T> {
122 type Wire = Option<T::Wire>;
123
124 fn from_wire(wire: Self::Wire) -> Result<Self, WireError> {
125 wire.map(T::from_wire).transpose()
126 }
127}
128
129impl<T: ToWasm> ToWasm for Option<T> {
130 type Wire = Option<T::Wire>;
131
132 fn to_wire(self) -> Result<Self::Wire, WireError> {
133 self.map(T::to_wire).transpose()
134 }
135}
136
137impl<T: Tsify> FromWasm for Ts<T> {
140 type Wire = Ts<T>;
141
142 fn from_wire(wire: Self::Wire) -> Result<Self, WireError> {
143 Ok(wire)
144 }
145}
146
147impl<T: Tsify> ToWasm for Ts<T> {
148 type Wire = Ts<T>;
149
150 fn to_wire(self) -> Result<Self::Wire, WireError> {
151 Ok(self)
152 }
153}
154
155#[derive(Debug)]
157pub enum Never {}
158
159impl From<Never> for JsValue {
160 fn from(value: Never) -> Self {
161 match value {}
162 }
163}
164
165#[derive(Debug)]
171pub enum TsError<E = Never> {
172 Inner(E),
174 Conversion(WireError),
176}
177
178impl<E: Into<JsValue>> From<TsError<E>> for JsValue {
179 fn from(value: TsError<E>) -> Self {
180 match value {
181 TsError::Inner(inner) => inner.into(),
182 TsError::Conversion(err) => {
183 let js_error = SdkJsError::new(err.to_string());
184 js_error.set_name(CONVERSION_ERROR_NAME.to_owned());
185 js_error.into()
186 }
187 }
188 }
189}
190
191#[doc(hidden)]
194pub fn import_conversion_error(err: WireError) -> JsValue {
195 TsError::<Never>::Conversion(err).into()
196}
197
198#[cfg(test)]
199mod tests {
200 use std::convert::Infallible;
201
202 use super::*;
203
204 #[derive(Debug, PartialEq)]
205 struct Digit(u8);
206
207 impl std::str::FromStr for Digit {
208 type Err = String;
209
210 fn from_str(s: &str) -> Result<Self, Self::Err> {
211 s.parse()
212 .map(Digit)
213 .map_err(|_| format!("not a digit: {s}"))
214 }
215 }
216
217 impl Display for Digit {
218 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219 write!(f, "{}", self.0)
220 }
221 }
222
223 crate::impl_wire_string!(Digit);
224
225 struct Shout(String);
226
227 crate::impl_wire_string!(
228 Shout,
229 parse = |wire: String| Ok::<_, Infallible>(Shout(wire.to_uppercase())),
230 format = |value: Shout| value.0,
231 );
232
233 struct InputOnly(String);
234
235 crate::impl_wire_string!(
236 InputOnly,
237 parse = |wire| Ok::<_, Infallible>(InputOnly(wire))
238 );
239
240 #[test]
241 fn default_form_round_trips() {
242 let digit = Digit::from_wire("7".to_owned()).unwrap();
243 assert_eq!(digit, Digit(7));
244 assert_eq!(digit.to_wire().unwrap(), "7");
245 }
246
247 #[test]
248 fn malformed_string_is_a_parse_error() {
249 let err = Digit::from_wire("x".to_owned()).unwrap_err();
250 assert_eq!(err.to_string(), "Failed to parse `Digit`: not a digit: x");
251 }
252
253 #[test]
254 fn custom_form_uses_the_given_functions() {
255 let shout = Shout::from_wire("hi".to_owned()).unwrap();
256 assert_eq!(shout.to_wire().unwrap(), "HI");
257 assert_eq!(InputOnly::from_wire("hi".to_owned()).unwrap().0, "hi");
258 }
259
260 #[test]
261 fn a_bad_element_fails_the_whole_vec() {
262 let wire = vec!["1".to_owned(), "x".to_owned()];
263 assert!(Vec::<Digit>::from_wire(wire).is_err());
264 assert_eq!(Option::<Digit>::from_wire(None).unwrap(), None);
265 }
266}