1pub mod account_order;
4pub mod schema;
5
6use nomiscript::{Reader, Value, format_value_display, list_to_vec};
7use thiserror::Error;
8
9use rpc::{EnvelopeError, ErrorCode, ResponsePayload, parse_response, try_expr_to_value};
10
11#[derive(Debug, Clone, PartialEq)]
12pub enum WireValue {
13 Value(Value),
14}
15
16#[derive(Debug, Clone, PartialEq)]
21pub struct ListRow {
22 pub id: Option<String>,
24 pub cells: Vec<String>,
26}
27
28#[derive(Debug, Error)]
29pub enum RenderError {
30 #[error("envelope parse failed: {0}")]
31 Envelope(#[from] EnvelopeError),
32 #[error("wire error from server: [{}] {}", .0.code, .0.message)]
33 Server(ErrorReply),
34 #[error("re-parse of printed list failed: {0}")]
35 ListReparse(String),
36}
37
38pub fn parse_wire(wire: &str) -> Result<WireValue, RenderError> {
46 let response = parse_response(wire)?;
47 match response.payload {
48 ResponsePayload::Error {
49 code,
50 message,
51 detail,
52 } => Err(RenderError::Server(ErrorReply {
53 code: code.as_symbol().to_string(),
54 message,
55 detail,
56 })),
57 ResponsePayload::Value(v) => Ok(WireValue::Value(v)),
58 }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct FieldError {
64 pub field: String,
66 pub message: String,
67}
68
69#[derive(Debug, Clone, PartialEq)]
71pub struct ErrorReply {
72 pub code: String,
73 pub message: String,
74 pub detail: Option<Value>,
75}
76
77impl ErrorReply {
78 #[must_use]
81 pub fn field_errors(&self) -> Vec<FieldError> {
82 let Some(detail) = self
83 .detail
84 .as_ref()
85 .filter(|_| self.code == ErrorCode::FORM_INVALID)
86 else {
87 return Vec::new();
88 };
89 list_to_vec(detail)
90 .unwrap_or_default()
91 .iter()
92 .filter_map(|item| {
93 Some(FieldError {
94 field: crate::eval::plist_field(item, ":field")?,
95 message: crate::eval::plist_field(item, ":message")?,
96 })
97 })
98 .collect()
99 }
100}
101
102const MAX_REPARSE_DEPTH: usize = 64;
105
106fn max_nesting_depth(s: &str) -> usize {
109 let (mut depth, mut max) = (0usize, 0usize);
110 let (mut in_string, mut escaped) = (false, false);
111 for ch in s.chars() {
112 if in_string {
113 match (escaped, ch) {
114 (true, _) => escaped = false,
115 (false, '\\') => escaped = true,
116 (false, '"') => in_string = false,
117 _ => {}
118 }
119 continue;
120 }
121 match ch {
122 '"' => in_string = true,
123 '(' => {
124 depth += 1;
125 max = max.max(depth);
126 }
127 ')' => depth = depth.saturating_sub(1),
128 _ => {}
129 }
130 }
131 max
132}
133
134pub fn reparse_list(s: &str) -> Result<Value, RenderError> {
141 if max_nesting_depth(s) > MAX_REPARSE_DEPTH {
146 return Err(RenderError::ListReparse(format!(
147 "printed list nested beyond {MAX_REPARSE_DEPTH}"
148 )));
149 }
150 let program = Reader::parse(s).map_err(|e| RenderError::ListReparse(e.to_string()))?;
151 let mut iter = program.exprs.into_iter();
152 let Some(expr) = iter.next() else {
153 return Ok(Value::Nil);
154 };
155 if iter.next().is_some() {
156 return Err(RenderError::ListReparse(
157 "printed list string contains multiple top-level expressions".into(),
158 ));
159 }
160 try_expr_to_value(expr).map_err(|e| RenderError::ListReparse(e.to_string()))
161}
162
163pub fn value_to_rows(value: &Value) -> Vec<Vec<String>> {
170 match value {
171 Value::Nil => vec![],
172 Value::Pair(_) => {
173 if let Some(row) = try_plist_values(value) {
174 vec![row]
175 } else if let Some(elements) = list_to_vec(value) {
176 elements.iter().map(element_to_row).collect()
177 } else {
178 vec![vec![format_value_display(value)]]
179 }
180 }
181 other => vec![vec![format_value_display(other)]],
182 }
183}
184
185pub fn rows_with_ids(value: &Value) -> Vec<ListRow> {
192 match value {
193 Value::Nil => vec![],
194 Value::Pair(_) => {
195 if let Some(cells) = try_plist_values(value) {
196 vec![ListRow {
197 id: row_id(value),
198 cells,
199 }]
200 } else if let Some(elements) = list_to_vec(value) {
201 elements.iter().map(element_to_list_row).collect()
202 } else {
203 vec![ListRow {
204 id: None,
205 cells: vec![format_value_display(value)],
206 }]
207 }
208 }
209 other => vec![ListRow {
210 id: None,
211 cells: vec![format_value_display(other)],
212 }],
213 }
214}
215
216fn element_to_list_row(element: &Value) -> ListRow {
217 match element {
218 Value::Pair(_) => {
219 let cells =
220 try_plist_values(element).unwrap_or_else(|| vec![format_value_display(element)]);
221 ListRow {
222 id: row_id(element),
223 cells,
224 }
225 }
226 other => ListRow {
227 id: None,
228 cells: vec![format_value_display(other)],
229 },
230 }
231}
232
233fn row_id(value: &Value) -> Option<String> {
239 crate::eval::plist_field(value, ":id")
240}
241
242fn element_to_row(element: &Value) -> Vec<String> {
243 match element {
244 Value::Pair(_) => {
245 if let Some(cells) = try_plist_values(element) {
246 return cells;
247 }
248 vec![format_value_display(element)]
249 }
250 other => vec![format_value_display(other)],
251 }
252}
253
254fn is_plist_key(v: &Value) -> bool {
255 matches!(v, Value::Symbol(s) if s.starts_with(':'))
256}
257
258fn try_plist_values(value: &Value) -> Option<Vec<String>> {
259 let items = list_to_vec(value)?;
260 if items.len() < 2 || !items.len().is_multiple_of(2) {
261 return None;
262 }
263 if !items.iter().step_by(2).all(is_plist_key) {
264 return None;
265 }
266 Some(
267 items
268 .into_iter()
269 .skip(1)
270 .step_by(2)
271 .map(|v| format_value_display(&v))
272 .collect(),
273 )
274}
275
276#[cfg(test)]
277mod tests;