day_script_protocol/
format.rs1use std::fmt;
7
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value};
10
11use crate::Step;
12
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum FailurePolicy {
17 #[default]
18 Continue,
19 Stop,
20}
21
22#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct FormatError(String);
25
26impl fmt::Display for FormatError {
27 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28 f.write_str(&self.0)
29 }
30}
31
32impl std::error::Error for FormatError {}
33
34#[derive(Clone, Debug, PartialEq)]
37pub struct ScriptStep {
38 pub step: Step,
39 pub annotations: Map<String, Value>,
40}
41
42impl ScriptStep {
43 pub fn from_value(value: Value) -> Result<Self, FormatError> {
52 let mut fields = normalize(value)?;
53 let step: Step = serde_json::from_value(Value::Object(fields.clone()))
54 .map_err(|e| FormatError(e.to_string()))?;
55 let duration = match &step {
57 Step::Pause { secs } => Some(*secs),
58 Step::ExpectExit { within } => *within,
59 _ => None,
60 };
61 if let Some(secs) = duration
62 && std::time::Duration::try_from_secs_f64(secs).is_err()
63 {
64 return Err(FormatError(format!(
65 "{}: duration must be finite, non-negative and representable",
66 step.op()
67 )));
68 }
69 for key in ["skip_on", "only_on"] {
70 if let Some(value) = fields.get(key)
71 && !value
72 .as_array()
73 .is_some_and(|a| a.iter().all(Value::is_string))
74 {
75 return Err(FormatError(format!("{key} must be a sequence of strings")));
76 }
77 }
78 if fields.get("animation").is_some_and(|v| !v.is_boolean()) {
79 return Err(FormatError("animation must be a boolean".into()));
80 }
81 for key in protocol_fields(&step).keys() {
82 fields.remove(key);
83 }
84 if matches!(step, Step::NavBack { .. }) {
86 fields.remove("native");
87 }
88 Ok(Self {
89 step,
90 annotations: fields,
91 })
92 }
93
94 #[must_use]
97 pub fn to_value(&self) -> Value {
98 let mut fields = self.annotations.clone();
99 if matches!(self.step, Step::NavBack { .. }) {
101 fields.remove("native");
102 }
103 fields.extend(protocol_fields(&self.step));
104 Value::Object(fields)
105 }
106}
107
108impl From<Step> for ScriptStep {
109 fn from(step: Step) -> Self {
110 Self {
111 step,
112 annotations: Map::new(),
113 }
114 }
115}
116
117#[derive(Clone, Debug, Default, PartialEq)]
119pub struct Script {
120 pub steps: Vec<ScriptStep>,
121 pub on_failure: FailurePolicy,
122 pub metadata: Map<String, Value>,
123}
124
125impl Script {
126 pub fn from_yaml(yaml: &str) -> Result<Self, FormatError> {
135 let yaml: serde_norway::Value = serde_norway::from_str(yaml.trim_start_matches('\u{feff}'))
139 .map_err(|e| FormatError(e.to_string()))?;
140 if !finite_numbers(&yaml) {
141 return Err(FormatError("script contains a non-finite number".into()));
142 }
143 let doc = serde_json::to_value(yaml).map_err(|e| FormatError(e.to_string()))?;
144 let Value::Object(mut metadata) = doc else {
145 return Err(FormatError("script must be a mapping".into()));
146 };
147 let on_failure = match metadata.remove("on_failure") {
148 None => FailurePolicy::Continue,
149 Some(value) => serde_json::from_value(value)
150 .map_err(|_| FormatError("on_failure must be stop or continue".into()))?,
151 };
152 let Some(Value::Array(flow)) = metadata.remove("flow") else {
153 return Err(FormatError("script has no `flow:` sequence".into()));
154 };
155 let mut steps = Vec::with_capacity(flow.len());
156 for (index, entry) in flow.into_iter().enumerate() {
157 if entry.as_object().is_none_or(|m| m.len() != 1) {
160 return Err(FormatError(format!(
161 "flow step {}: entries must be single-key mappings",
162 index + 1
163 )));
164 }
165 let fields = normalize_entry(entry)
166 .map_err(|e| FormatError(format!("flow step {}: {e}", index + 1)))?;
167 let step = ScriptStep::from_value(Value::Object(fields))
168 .map_err(|e| FormatError(format!("flow step {}: {e}", index + 1)))?;
169 steps.push(step);
170 }
171 if steps
172 .iter()
173 .take(steps.len().saturating_sub(1))
174 .any(|s| matches!(s.step, Step::ExpectExit { .. }))
175 {
176 return Err(FormatError("expect_exit must be the last step".into()));
177 }
178 Ok(Self {
179 steps,
180 on_failure,
181 metadata,
182 })
183 }
184
185 #[must_use]
193 pub fn to_yaml(&self) -> String {
194 let mut doc = self.metadata.clone();
195 doc.remove("on_failure");
196 if self.on_failure == FailurePolicy::Stop {
197 doc.insert("on_failure".into(), Value::String("stop".into()));
198 }
199 let flow = self
200 .steps
201 .iter()
202 .map(|step| {
203 let Value::Object(mut fields) = step.to_value() else {
204 unreachable!("script step is an object")
205 };
206 fields.remove("op");
207 fields.retain(|key, value| !value.is_null() || step.annotations.contains_key(key));
208 let params = if fields.is_empty() {
209 Value::Null
210 } else {
211 Value::Object(fields)
212 };
213 let mut entry = Map::new();
214 entry.insert(step.step.op().into(), params);
215 Value::Object(entry)
216 })
217 .collect();
218 doc.insert("flow".into(), Value::Array(flow));
219 serde_norway::to_string(&doc).expect("JSON dayscript document serializes as YAML")
221 }
222}
223
224pub fn steps_to_yaml(steps: &[Step]) -> String {
226 Script {
227 steps: steps.iter().cloned().map(ScriptStep::from).collect(),
228 ..Script::default()
229 }
230 .to_yaml()
231}
232
233pub fn steps_from_yaml(yaml: &str) -> Result<Vec<Step>, String> {
240 Script::from_yaml(yaml)
241 .map(|script| script.steps.into_iter().map(|s| s.step).collect())
242 .map_err(|e| e.to_string())
243}
244
245fn protocol_fields(step: &Step) -> Map<String, Value> {
246 match serde_json::to_value(step).expect("dayscript step serializes as JSON") {
247 Value::Object(fields) => fields,
248 _ => unreachable!("internally tagged step is an object"),
249 }
250}
251
252fn finite_numbers(value: &serde_norway::Value) -> bool {
253 use serde_norway::Value as Yaml;
254 match value {
255 Yaml::Number(n) => n.is_finite(),
256 Yaml::Sequence(values) => values.iter().all(finite_numbers),
257 Yaml::Mapping(fields) => fields
258 .iter()
259 .all(|(key, value)| finite_numbers(key) && finite_numbers(value)),
260 Yaml::Tagged(value) => finite_numbers(&value.value),
261 Yaml::Null | Yaml::Bool(_) | Yaml::String(_) => true,
262 }
263}
264
265fn normalize(value: Value) -> Result<Map<String, Value>, FormatError> {
266 if let Some(fields) = value.as_object()
267 && fields.contains_key("op")
268 {
269 return Ok(fields.clone());
270 }
271 normalize_entry(value)
272}
273
274fn normalize_entry(value: Value) -> Result<Map<String, Value>, FormatError> {
275 let Value::Object(entry) = value else {
276 return Err(FormatError("step must be a mapping".into()));
277 };
278 if entry.len() != 1 {
279 return Err(FormatError("step must be a single-key mapping".into()));
280 }
281 let (op, params) = entry.into_iter().next().expect("exactly one key");
282 let mut fields = match params {
283 Value::Object(fields) => fields,
284 Value::String(s) if op == "screenshot" => Map::from_iter([("name".into(), s.into())]),
285 Value::Number(n) if op == "pause" => Map::from_iter([("secs".into(), n.into())]),
286 Value::String(s) if op == "resize" && s == "auto" => {
287 Map::from_iter([("restore".into(), true.into())])
288 }
289 Value::Null => Map::new(),
290 other => {
291 return Err(FormatError(format!(
292 "step {op}: unsupported params {other}"
293 )));
294 }
295 };
296 if fields.contains_key("op") {
297 return Err(FormatError(format!(
298 "step {op}: params cannot override `op`"
299 )));
300 }
301 fields.insert("op".into(), op.into());
302 Ok(fields)
303}