Skip to main content

trailbase_wasm_common/
lib.rs

1#![forbid(unsafe_code, clippy::unwrap_used)]
2#![allow(clippy::needless_return)]
3#![warn(clippy::await_holding_lock, clippy::inefficient_to_string)]
4
5use serde::{Deserialize, Serialize};
6use trailbase_sqlvalue::SqlValue;
7use ts_rs::TS;
8
9pub mod manifest;
10
11#[derive(Clone, Debug, Deserialize, Serialize, TS)]
12#[ts(export)]
13pub struct SqliteRequest {
14  pub query: String,
15  pub params: Vec<SqlValue>,
16}
17
18#[derive(Clone, Debug, Deserialize, Serialize, TS)]
19#[ts(export)]
20pub enum SqliteResponse {
21  Query { rows: Vec<Vec<SqlValue>> },
22  Execute { rows_affected: usize },
23  Error(String),
24  TxBegin,
25  TxCommit,
26  TxRollback,
27}
28
29#[derive(Clone, Debug, Deserialize, Serialize)]
30pub enum PrefsRequest {
31  Get { key: String },
32  Set { key: String, value: Option<String> },
33}
34
35#[derive(Clone, Debug, Deserialize, Serialize, TS)]
36pub enum PrefsResponse {
37  Ok,
38  Value(Option<String>),
39  Error(String),
40}
41
42/// Used to pass extra information from host to guest via an HTTP request header "__context".
43#[derive(Clone, Debug, Deserialize, Serialize, TS)]
44#[ts(export)]
45pub struct HttpContext {
46  pub kind: HttpContextKind,
47  pub registered_path: String,
48  pub path_params: Vec<(String, String)>,
49  pub user: Option<HttpContextUser>,
50}
51
52#[derive(Clone, Debug, Deserialize, Serialize, TS)]
53pub enum HttpContextKind {
54  /// An incoming http request.
55  Http,
56  /// An incoming job request.
57  Job,
58  // Fallback
59  #[serde(other)]
60  Unknown,
61}
62
63#[derive(Clone, Debug, Deserialize, Serialize, TS)]
64pub struct HttpContextUser {
65  // Host encodes with padded BASE64_URL_SAFE, but the guest's `is_admin` decodes
66  // with URL_SAFE_NO_PAD which rejects trailing `=`. Strip on deserialize.
67  pub id: String,
68  /// E-mail of the current user.
69  pub email: Option<String>,
70  /// Username of the current user.
71  pub username: Option<String>,
72  /// The "expected" CSRF token as included in the auth token claims [User] was constructed from.
73  pub csrf_token: String,
74}
75
76#[inline]
77pub fn component_path_to_name(path: &std::path::Path) -> Result<String, String> {
78  return Ok(
79    path
80      .file_stem()
81      .and_then(|s| s.to_str())
82      .ok_or_else(|| format!("failed to get component name from '{path:?}'"))?
83      .to_string(),
84  );
85}