Skip to main content

bitwarden_ffi/
wire.rs

1//! How a type crosses the wasm ABI.
2//!
3//! A proc macro cannot resolve types: seeing the token `CipherView`, `#[wasm_export]` has no way to
4//! know whether it is a serde DTO, which crosses as [`Ts<T>`](tsify::Ts), a `#[wasm_bindgen]`
5//! handle, which crosses as itself, or a type that crosses as a string. So each type declares its
6//! own wire form instead. [`FromWasm::Wire`] and [`ToWasm::Wire`] are what the generated shim puts
7//! in its signature, and `#[wasm_record]` / `#[wasm_object]` generate the impls.
8//!
9//! Conversion happens inside the shim body, where a failure is an ordinary `Err` and destructors
10//! run. `#[tsify(from_wasm_abi)]` instead converts inside `FromWasmAbi::from_abi`, which cannot
11//! report failure and so calls `wasm_bindgen::throw_str`
12//! ([tsify#65](https://github.com/madonoharu/tsify/issues/65)).
13
14use std::fmt::Display;
15
16use bitwarden_error::wasm::{CONVERSION_ERROR_NAME, SdkJsError};
17use tsify::{Ts, Tsify};
18use wasm_bindgen::JsValue;
19
20/// A value could not be converted across the wasm ABI.
21#[derive(Debug, thiserror::Error)]
22pub enum WireError {
23    /// A string did not parse as the type it crosses as.
24    #[error("Failed to parse `{type_name}`: {message}")]
25    Parse {
26        /// The type the string was parsed as.
27        type_name: &'static str,
28        /// The parser's error message.
29        message: String,
30    },
31    /// A serde DTO did not convert to or from its `Ts<T>` form.
32    #[error(transparent)]
33    Serde(#[from] tsify::Error),
34}
35
36/// A type that can be received from JavaScript, crossing the ABI as [`Self::Wire`].
37pub trait FromWasm: Sized {
38    /// The type JavaScript actually passes.
39    type Wire;
40
41    /// Recovers the Rust value from the wire value.
42    fn from_wire(wire: Self::Wire) -> Result<Self, WireError>;
43}
44
45/// A type that can be handed to JavaScript, crossing the ABI as [`Self::Wire`].
46pub trait ToWasm {
47    /// The type JavaScript actually receives.
48    type Wire;
49
50    /// Converts the Rust value into the wire value.
51    fn to_wire(self) -> Result<Self::Wire, WireError>;
52}
53
54/// Runs an `impl_wire_string!` parser. A function rather than inline macro code so the closure's
55/// argument type is inferred.
56#[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/// Runs an `impl_wire_string!` formatter; see [`parse_wire_string`].
69#[doc(hidden)]
70pub fn format_wire_string<T>(value: T, format: impl FnOnce(T) -> String) -> String {
71    format(value)
72}
73
74// The closed set of types wasm_bindgen carries natively. Being absent from it is a missing-impl
75// compile error at the use site.
76crate::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
98// JavaScript built-ins an import returns as a handle.
99crate::impl_wire_object!(js_sys::Array);
100
101/// `Vec<T>` crosses as a vector of `T`'s wire type, so `Vec<u8>` stays `Vec<u8>` and reaches
102/// JavaScript as a `Uint8Array`, while `Vec<CipherView>` becomes `Vec<Ts<CipherView>>`.
103///
104/// `Ts` sits on the element, never the vector: `Ts<Vec<T>>` is not something tsify supports.
105impl<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
137/// Lets a shim name `Ts<T>` in a signature it was handed already-wrapped, for the hand-written
138/// `extern "C"` blocks that construct the wrapper themselves.
139impl<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/// Stands in for the error of a shim whose underlying method cannot fail.
156#[derive(Debug)]
157pub enum Never {}
158
159impl From<Never> for JsValue {
160    fn from(value: Never) -> Self {
161        match value {}
162    }
163}
164
165/// Error of a generated shim.
166///
167/// `Inner` reaches JavaScript through `E`'s own `From<E> for JsValue`, so a `bitwarden_error` type
168/// keeps the `name` and `variant` it already had. Shims for infallible methods use the default `E`,
169/// leaving `Conversion` as the only reachable variant.
170#[derive(Debug)]
171pub enum TsError<E = Never> {
172    /// The underlying method failed.
173    Inner(E),
174    /// A value could not be converted across the boundary.
175    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/// The error a `#[wasm_import]` wrapper returns when an argument does not convert, matching what a
192/// `#[wasm_export]` shim throws for the same failure.
193#[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}