Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Agents and scripts: Add, Rename, Delete, Comment, Favorite and Move Parameter describe their exact parameters and reply (#11941) (#11943)

austin62jake202b775de42c
diff --git a/crates/engine/src/cmd/parameters.rs b/crates/engine/src/cmd/parameters.rs
index cda10522b7..79adc68691 100644
--- a/crates/engine/src/cmd/parameters.rs
+++ b/crates/engine/src/cmd/parameters.rs
@@ -9,8 +9,20 @@ use solidcraft_sketch::{Analysis, ConstraintKind, CurveKind, Hold, Sketch, solve
use super::{CommandSpec, sketch_store};
use crate::params::{bad, bool_, str_};
+use crate::schema::parameters::{
+ AddedValue, ParamAddParams, ParamAdded, ParamCommentParams, ParamCommented, ParamDeleted, ParamFavoriteParams, ParamFavorited, ParamMoveParams,
+ ParamMoved, ParamNameParams, ParamRenameParams, ParamRenamed,
+};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
+const ADD_CONTRACT: TypedContract<ParamAddParams> = TypedContract::new();
+const RENAME_CONTRACT: TypedContract<ParamRenameParams> = TypedContract::new();
+const NAME_CONTRACT: TypedContract<ParamNameParams> = TypedContract::new();
+const COMMENT_CONTRACT: TypedContract<ParamCommentParams> = TypedContract::new();
+const FAVORITE_CONTRACT: TypedContract<ParamFavoriteParams> = TypedContract::new();
+const MOVE_CONTRACT: TypedContract<ParamMoveParams> = TypedContract::new();
+
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("parameters.change", "Change Parameters", change_param).at("SOLID", "MODIFY").icon("params").params(
"name, expression (number or text), unit?: mm|cm|m|in|ft|deg|rad|\"\"|text (new parameters default to their value's unit, a length the design's units; \
@@ -26,20 +38,36 @@ pub static COMMANDS: &[CommandSpec] = &[
"favorites?: bool (only favourites), filter?: all|user|sketch|feature|favorites → parameters (name, expression, unit, value (mm/deg in every \
reply), display_value (in its own unit), source, feature/input, comment, favorite, uses, used_by, error) and cycles",
),
- CommandSpec::new("parameters.add", "Add User Parameter", add)
+ CommandSpec::new("parameters.add", "Add User Parameter", crate::checked!("parameters.add", add))
.icon("new")
+ .contract(&ADD_CONTRACT)
+ .output(output_schema_for::<ParamAdded>)
.params("name, expression, unit?: as parameters.change (text: a text parameter, its expression the text), comment?, favorite?: bool"),
- CommandSpec::new("parameters.rename", "Rename Parameter", rename)
+ CommandSpec::new("parameters.rename", "Rename Parameter", crate::checked!("parameters.rename", rename))
.icon("rename")
+ .contract(&RENAME_CONTRACT)
+ .output(output_schema_for::<ParamRenamed>)
.params("name, new_name (expressions, feature inputs and dimensions that use it follow)"),
- CommandSpec::new("parameters.delete", "Delete Parameter", delete)
+ CommandSpec::new("parameters.delete", "Delete Parameter", crate::checked!("parameters.delete", delete))
.icon("delete")
+ .contract(&NAME_CONTRACT)
+ .output(output_schema_for::<ParamDeleted>)
.params("name (refused while something uses it; the error lists the users)"),
- CommandSpec::new("parameters.favorite", "Favorite Parameter", favorite).icon("star").params("name, favorite?: bool (default true)"),
- CommandSpec::new("parameters.move", "Move Parameter", move_param)
+ CommandSpec::new("parameters.favorite", "Favorite Parameter", crate::checked!("parameters.favorite", favorite))
+ .icon("star")
+ .contract(&FAVORITE_CONTRACT)
+ .output(output_schema_for::<ParamFavorited>)
+ .params("name, favorite?: bool (default true)"),
+ CommandSpec::new("parameters.move", "Move Parameter", crate::checked!("parameters.move", move_param))
.icon("reorder")
+ .contract(&MOVE_CONTRACT)
+ .output(output_schema_for::<ParamMoved>)
.params("name, before | after: another user parameter; the user parameter is listed just before or after it"),
- CommandSpec::new("parameters.comment", "Comment Parameter", comment).icon("text").params("name, comment"),
+ CommandSpec::new("parameters.comment", "Comment Parameter", crate::checked!("parameters.comment", comment))
+ .icon("text")
+ .contract(&COMMENT_CONTRACT)
+ .output(output_schema_for::<ParamCommented>)
+ .params("name, comment"),
CommandSpec::new("parameters.users", "Parameter Users", users)
.icon("graph")
.noundo()
@@ -340,35 +368,46 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
s.doc_mut().set_favorite(&name, f)?;
}
let (vals, _) = s.doc.param_values();
- if let Some(t) = s.doc.text_param(&name) {
- return Ok(json!({"name": name, "unit": solidcraft_doc::text_params::TEXT_UNIT, "text": t.text, "value": null}));
- }
- Ok(
- json!({"name": name, "unit": s.doc.param(&name).map(|x| x.unit.clone()), "value": vals.get(&name).map(|v| expr::round_reported(expr::reported_value(*v))), "display_value": s.doc.param_display_value(&vals, &name).map(expr::round_reported)}),
- )
+ let value = match s.doc.text_param(&name) {
+ Some(t) => AddedValue::Text { unit: solidcraft_doc::text_params::TEXT_UNIT.into(), text: t.text.clone(), value: None },
+ None => AddedValue::Number {
+ unit: s.doc.param(&name).map(|x| x.unit.clone()),
+ value: vals.get(&name).map(|v| expr::round_reported(expr::reported_value(*v))),
+ display_value: s.doc.param_display_value(&vals, &name).map(expr::round_reported),
+ },
+ };
+ reply(cmd, ParamAdded { name, value, param_warnings: Vec::new() })
+}
+
+/// A reply as JSON: these commands build their replies from the types their output schemas
+/// describe, so the two can't drift apart.
+fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
}
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "parameters.rename";
let name = param_name(cmd, p)?.to_string();
let new = str_(p, "new_name").ok_or_else(|| bad(cmd, "`new_name` is required"))?;
- let n = s.doc_mut().rename_param(&name, new)?;
- Ok(json!({"from": name, "to": new.trim(), "references_updated": n}))
+ let references_updated = s.doc_mut().rename_param(&name, new)?;
+ reply(cmd, ParamRenamed { from: name, to: new.trim().to_string(), references_updated, param_warnings: Vec::new() })
}
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
- let name = param_name("parameters.delete", p)?.to_string();
+ let cmd = "parameters.delete";
+ let name = param_name(cmd, p)?.to_string();
let solved = s.solved_sketches();
s.doc_mut().remove_param(&name)?;
s.settle_value_edit(&solved)?;
- Ok(json!({"deleted": name}))
+ reply(cmd, ParamDeleted { deleted: name, param_warnings: Vec::new() })
}
fn favorite(s: &mut Session, p: &Value) -> Result<Value> {
- let name = param_name("parameters.favorite", p)?.to_string();
- let on = bool_(p, "favorite").unwrap_or(true);
- s.doc_mut().set_favorite(&name, on)?;
- Ok(json!({"name": name, "favorite": on}))
+ let cmd = "parameters.favorite";
+ let name = param_name(cmd, p)?.to_string();
+ let favorite = bool_(p, "favorite").unwrap_or(true);
+ s.doc_mut().set_favorite(&name, favorite)?;
+ reply(cmd, ParamFavorited { name, favorite, param_warnings: Vec::new() })
}
fn move_param(s: &mut Session, p: &Value) -> Result<Value> {
@@ -380,8 +419,8 @@ fn move_param(s: &mut Session, p: &Value) -> Result<Value> {
_ => return Err(bad(cmd, "give one of `before` or `after`: another user parameter")),
};
s.doc_mut().move_user_param(&name, &target, after)?;
- let order: Vec<&str> = s.doc.params.iter().filter(|q| !q.model).map(|q| q.name.as_str()).collect();
- Ok(json!({"name": name, "order": order}))
+ let order = s.doc.params.iter().filter(|q| !q.model).map(|q| q.name.clone()).collect();
+ reply(cmd, ParamMoved { name, order, param_warnings: Vec::new() })
}
fn comment(s: &mut Session, p: &Value) -> Result<Value> {
@@ -389,7 +428,7 @@ fn comment(s: &mut Session, p: &Value) -> Result<Value> {
let name = param_name(cmd, p)?.to_string();
let c = str_(p, "comment").ok_or_else(|| bad(cmd, "`comment` must be text"))?;
s.doc_mut().set_param_comment(&name, c)?;
- Ok(json!({"name": name, "comment": c}))
+ reply(cmd, ParamCommented { name, comment: c.to_string(), param_warnings: Vec::new() })
}
fn users(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 09494d6286..86d1efa2f4 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -76,6 +76,7 @@ pub mod metadata;
pub mod motion;
pub mod panels;
pub mod parameter_sweep;
+pub mod parameters;
pub mod parts;
pub mod print_face;
pub mod render;
diff --git a/crates/engine/src/schema/parameters.rs b/crates/engine/src/schema/parameters.rs
new file mode 100644
index 0000000000..01450f844d
--- /dev/null
+++ b/crates/engine/src/schema/parameters.rs
@@ -0,0 +1,301 @@
+//! Contracts and result types for the commands in `cmd/parameters.rs` that manage the design's
+//! user parameters by name (#11941): `parameters.add`, `.rename`, `.delete`, `.comment`,
+//! `.favorite` and `.move`.
+//!
+//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
+//! reads it and fails with the handler's message. Whether a parameter exists, and whether a new
+//! name, unit or expression is valid, stays the document's to check, with its messages.
+
+use schemars::{JsonSchema, Schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::Value;
+
+use super::check::whole;
+
+/// A parameter's name, as `cmd/parameters.rs`'s `param_name` reads `name`: text that isn't blank,
+/// with its message for anything else. Spaces at either end are dropped.
+fn param_name<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(name) if !name.trim().is_empty() => Ok(name),
+ _ => Err(D::Error::custom(whole("`name` is required"))),
+ }
+}
+
+/// Add a user parameter: a named number with a unit, or a named text. Features, sketches and
+/// other parameters can use it by name. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = expression_or_value)]
+pub struct ParamAddParams {
+ /// The new parameter's name: a letter or `_`, then letters, digits or `_`; not a unit's,
+ /// function's or constant's name, nor another parameter's.
+ #[serde(deserialize_with = "param_name")]
+ #[schemars(length(min = 1))]
+ pub name: String,
+ #[serde(default, deserialize_with = "expression")]
+ #[schemars(schema_with = "expression_schema")]
+ pub expression: Option<Value>,
+ /// Another name for `expression`, read when `expression` isn't a number or text.
+ #[serde(default, deserialize_with = "expression")]
+ #[schemars(schema_with = "expression_schema")]
+ pub value: Option<Value>,
+ /// The unit: `mm`, `cm`, `m`, `in`, `ft`, `deg`, `rad`, `""` (no unit) or `text` (a text
+ /// parameter, whose expression is its text). Default: the expression's own unit, a length
+ /// in the design's units.
+ #[serde(default)]
+ pub unit: Option<String>,
+ /// A note to show with it.
+ #[serde(default)]
+ pub comment: Option<String>,
+ /// List it with the favourites, first. Default: false.
+ #[serde(default)]
+ pub favorite: Option<bool>,
+}
+
+/// `expression` and `value`: a number or text, as `expr_arg` reads them. `null` is left out, as
+/// the reader reads it; anything else gets the handler's message.
+fn expression<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Value>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Null => Ok(None),
+ v @ (Value::String(_) | Value::Number(_)) => Ok(Some(v)),
+ _ => Err(D::Error::custom(whole("`expression` must be a number or text"))),
+ }
+}
+
+fn expression_schema(_: &mut schemars::SchemaGenerator) -> Schema {
+ schemars::json_schema!({
+ "description": "The value: a number, or an expression as text (`25 mm`, `W / 2`). For a text parameter, its text; quotes round it are optional.",
+ "type": ["number", "string", "null"]
+ })
+}
+
+/// `parameters.add` needs `expression`, or `value` in its place, as a number or text. Given
+/// isn't enough: `expr_arg` reads a `null` one as left out, so each alternative also needs its
+/// key's type.
+fn expression_or_value(schema: &mut Schema) {
+ schema.insert(
+ "anyOf".into(),
+ serde_json::json!([
+ {"required": ["expression"], "properties": {"expression": {"type": ["number", "string"]}}},
+ {"required": ["value"], "properties": {"value": {"type": ["number", "string"]}}}
+ ]),
+ );
+}
+
+/// Rename a parameter, a user parameter or a feature's named input. The expressions, feature
+/// inputs and dimensions that use it follow. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ParamRenameParams {
+ /// The parameter, by name.
+ #[serde(deserialize_with = "param_name")]
+ #[schemars(length(min = 1))]
+ pub name: String,
+ /// Its new name, as for a new parameter. Spaces at either end are dropped.
+ #[serde(deserialize_with = "new_name")]
+ pub new_name: String,
+}
+
+/// `new_name`: text, with the handler's message for anything else.
+fn new_name<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(name) => Ok(name),
+ _ => Err(D::Error::custom(whole("`new_name` is required"))),
+ }
+}
+
+/// Delete a user parameter. It's refused while an expression, a feature input or a dimension
+/// uses it; the message lists them. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ParamNameParams {
+ /// The parameter, by name.
+ #[serde(deserialize_with = "param_name")]
+ #[schemars(length(min = 1))]
+ pub name: String,
+}
+
+/// Set a parameter's comment, a note shown with it. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = comment_required)]
+pub struct ParamCommentParams {
+ /// The parameter, by name.
+ #[serde(deserialize_with = "param_name")]
+ #[schemars(length(min = 1))]
+ pub name: String,
+ /// The comment; empty text clears it.
+ // Optional in the type and required in the schema (`comment_required`): left out, the
+ // handler refuses it with its own message ("`comment` must be text"), not the check's "is
+ // required". `skip_serializing_if` keeps schemars from publishing `default: null`, which
+ // the schema refuses.
+ #[serde(default, deserialize_with = "comment_text", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "String")]
+ pub comment: Option<String>,
+}
+
+/// `parameters.comment` needs `comment`, though its type has it optional.
+fn comment_required(schema: &mut Schema) {
+ if let Some(Value::Array(required)) = schema.get_mut("required")
+ && !required.contains(&Value::from("comment"))
+ {
+ required.push("comment".into());
+ }
+}
+
+/// `comment`: text, with the handler's message for anything else, `null` included.
+fn comment_text<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(comment) => Ok(Some(comment)),
+ _ => Err(D::Error::custom(whole("`comment` must be text"))),
+ }
+}
+
+/// Mark a parameter as a favourite, listed first, or unmark it. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ParamFavoriteParams {
+ /// The parameter, by name.
+ #[serde(deserialize_with = "param_name")]
+ #[schemars(length(min = 1))]
+ pub name: String,
+ /// Whether it's a favourite. Default: true.
+ #[serde(default)]
+ pub favorite: Option<bool>,
+}
+
+/// Move a user parameter just before or after another, in the order the user parameters are
+/// listed. Give exactly one of `before` and `after`. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = before_or_after)]
+pub struct ParamMoveParams {
+ /// The user parameter, by name.
+ #[serde(deserialize_with = "param_name")]
+ #[schemars(length(min = 1))]
+ pub name: String,
+ /// Another user parameter, by name: the parameter is listed just before it.
+ #[serde(default, deserialize_with = "neighbour")]
+ pub before: Option<String>,
+ /// Another user parameter, by name: the parameter is listed just after it.
+ #[serde(default, deserialize_with = "neighbour")]
+ pub after: Option<String>,
+}
+
+/// `before` and `after`: text; `null` is left out, as the handler reads it. Anything else gets
+/// the message the handler gives when it finds neither.
+fn neighbour<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Null => Ok(None),
+ Value::String(name) => Ok(Some(name)),
+ _ => Err(D::Error::custom(whole("give one of `before` or `after`: another user parameter"))),
+ }
+}
+
+/// `parameters.move` needs exactly one of `before` and `after` as text. Each alternative needs
+/// its key to be text, so a `null` one, which the handler reads as left out, matches neither:
+/// `oneOf` then counts the keys as the handler does, and both or neither is refused.
+fn before_or_after(schema: &mut Schema) {
+ schema.insert(
+ "oneOf".into(),
+ serde_json::json!([
+ {"required": ["before"], "properties": {"before": {"type": "string"}}},
+ {"required": ["after"], "properties": {"after": {"type": "string"}}}
+ ]),
+ );
+}
+
+/// What `parameters.add` returns: the new parameter.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ParamAdded {
+ pub name: String,
+ #[serde(flatten)]
+ pub value: AddedValue,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// A new parameter's value: a number's, or a text parameter's text.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum AddedValue {
+ /// A text parameter.
+ Text {
+ /// Always `text`.
+ unit: String,
+ /// Its text.
+ text: String,
+ /// Always `null`: a text has no number.
+ value: Option<f64>,
+ },
+ /// A number.
+ Number {
+ /// Its unit; `""` for none.
+ unit: Option<String>,
+ /// Its value in mm for a length and degrees for an angle, as in every reply; `null` if
+ /// it can't be worked out.
+ value: Option<f64>,
+ /// Its value in its own unit; `null` if it can't be worked out.
+ display_value: Option<f64>,
+ },
+}
+
+/// What `parameters.rename` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ParamRenamed {
+ /// The old name.
+ pub from: String,
+ /// The new name.
+ pub to: String,
+ /// How many expressions, feature inputs and dimensions were changed to use the new name.
+ pub references_updated: usize,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `parameters.delete` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ParamDeleted {
+ /// The deleted parameter's name.
+ pub deleted: String,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `parameters.comment` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ParamCommented {
+ pub name: String,
+ /// The comment as given.
+ pub comment: String,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `parameters.favorite` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ParamFavorited {
+ pub name: String,
+ /// Whether it's now a favourite.
+ pub favorite: bool,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `parameters.move` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ParamMoved {
+ pub name: String,
+ /// The user parameters' names, in their new order.
+ pub order: Vec<String>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+#[cfg(test)]
+#[path = "parameters_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/parameters_tests.rs b/crates/engine/src/schema/parameters_tests.rs
new file mode 100644
index 0000000000..06c3925bbe
--- /dev/null
+++ b/crates/engine/src/schema/parameters_tests.rs
@@ -0,0 +1,146 @@
+use serde_json::{Value, json};
+
+use super::{
+ ParamAddParams, ParamAdded, ParamCommentParams, ParamCommented, ParamDeleted, ParamFavoriteParams, ParamFavorited, ParamMoveParams, ParamMoved,
+ ParamNameParams, ParamRenameParams, ParamRenamed,
+};
+use crate::Session;
+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<ParamAddParams>(), &["comment", "expression", "favorite", "name", "unit", "value"]);
+ assert_keys(input_schema_for::<ParamRenameParams>(), &["name", "new_name"]);
+ assert_keys(input_schema_for::<ParamNameParams>(), &["name"]);
+ assert_keys(input_schema_for::<ParamCommentParams>(), &["comment", "name"]);
+ assert_keys(input_schema_for::<ParamFavoriteParams>(), &["favorite", "name"]);
+ assert_keys(input_schema_for::<ParamMoveParams>(), &["after", "before", "name"]);
+}
+
+/// The calls fail on a design without parameters, with the handlers' messages or the
+/// document's.
+#[test]
+fn strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[
+ ("parameters.add", json!({})),
+ ("parameters.add", json!({"name": " ", "expression": 1})),
+ ("parameters.add", json!({"name": 5, "expression": 1})),
+ ("parameters.add", json!({"name": "W"})),
+ ("parameters.add", json!({"name": "W", "expression": true})),
+ ("parameters.add", json!({"name": "W", "expression": null})),
+ ("parameters.add", json!({"name": "W", "value": [1]})),
+ ("parameters.add", json!({"name": "1W", "expression": 1})),
+ ("parameters.add", json!({"name": "W", "expression": "1 +"})),
+ ("parameters.add", json!({"name": "W", "expression": 1, "unit": "furlong"})),
+ ("parameters.rename", json!({"new_name": "X"})),
+ ("parameters.rename", json!({"name": "Nope", "new_name": "X"})),
+ ("parameters.rename", json!({"name": "W"})),
+ ("parameters.rename", json!({"name": "W", "new_name": 5})),
+ ("parameters.delete", json!({})),
+ ("parameters.delete", json!({"name": "Nope"})),
+ ("parameters.comment", json!({"name": "Nope", "comment": "x"})),
+ ("parameters.comment", json!({"name": "W"})),
+ ("parameters.comment", json!({"name": "W", "comment": null})),
+ ("parameters.comment", json!({"name": "W", "comment": 5})),
+ ("parameters.favorite", json!({"name": []})),
+ ("parameters.favorite", json!({"name": "Nope"})),
+ ("parameters.move", json!({"name": "W"})),
+ ("parameters.move", json!({"name": "W", "before": "A", "after": "B"})),
+ ("parameters.move", json!({"name": "W", "before": 5})),
+ ("parameters.move", json!({"name": "Nope", "before": "A"})),
+ ]);
+}
+
+/// The schemas take what the handlers read: `expression` or `value` as a number or text (`null`
+/// is read as left out, so it doesn't count), a non-blank name, and exactly one of `before` and
+/// `after` as text.
+#[test]
+fn the_schemas_take_what_the_handlers_read() {
+ let add = input_schema_for::<ParamAddParams>();
+ let add = add.as_value();
+ for (p, takes) in [
+ (json!({"name": "W", "expression": "10 mm"}), true),
+ (json!({"name": "W", "expression": 10, "unit": "mm", "comment": "Wall", "favorite": true}), true),
+ (json!({"name": "W", "value": 10}), true),
+ (json!({"name": "W", "expression": null, "value": 3}), true),
+ (json!({"name": "W", "expression": null}), false),
+ (json!({"name": "W", "expression": true}), false),
+ (json!({"name": "", "expression": 10}), false),
+ ] {
+ assert_eq!(conforms(add, add, &p), takes, "{p}");
+ }
+ assert_eq!(
+ add["anyOf"],
+ json!([
+ {"required": ["expression"], "properties": {"expression": {"type": ["number", "string"]}}},
+ {"required": ["value"], "properties": {"value": {"type": ["number", "string"]}}}
+ ]),
+ "{add}"
+ );
+ let comment = input_schema_for::<ParamCommentParams>();
+ let comment = comment.as_value();
+ assert!(!conforms(comment, comment, &json!({"name": "W"})), "{comment}");
+ assert!(!conforms(comment, comment, &json!({"name": "W", "comment": null})), "{comment}");
+ // `conforms` doesn't read `oneOf`, so `parameters.move`'s is pinned, and counted here.
+ let moved = input_schema_for::<ParamMoveParams>();
+ let moved = moved.as_value();
+ assert_eq!(
+ moved["oneOf"],
+ json!([
+ {"required": ["before"], "properties": {"before": {"type": "string"}}},
+ {"required": ["after"], "properties": {"after": {"type": "string"}}}
+ ]),
+ "{moved}"
+ );
+ let one_of = |p: &Value| moved["oneOf"].as_array().into_iter().flatten().filter(|b| conforms(moved, b, p)).count() == 1;
+ for (p, takes) in [
+ (json!({"name": "W", "before": "A"}), true),
+ (json!({"name": "W", "after": "A"}), true),
+ (json!({"name": "W", "before": null, "after": "B"}), true),
+ (json!({"name": "W"}), false),
+ (json!({"name": "W", "before": null}), false),
+ (json!({"name": "W", "before": "A", "after": "B"}), false),
+ (json!({"name": "W", "before": 5}), false),
+ ] {
+ assert_eq!(conforms(moved, moved, &p) && one_of(&p), takes, "{p}");
+ }
+}
+
+/// #11941: adding a number and a text parameter, then commenting, favouriting, moving,
+/// renaming and deleting, reply as the output schemas say, in Warn without warnings. A
+/// misspelt key gets `param_warnings` in Warn, since the handlers ignore unknown keys, and
+/// strict refuses it.
+#[test]
+fn parameter_edits_reply_with_their_schemas() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let mut run = |id: &str, p: Value, schema: schemars::Schema| {
+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
+ assert!(r.get("param_warnings").is_none(), "{r}");
+ r
+ };
+ let r = run("parameters.add", json!({"name": "W", "expression": "10 mm", "comment": "Wall"}), output_schema_for::<ParamAdded>());
+ assert_eq!((r["unit"].as_str(), r["value"].as_f64(), r["display_value"].as_f64()), (Some("mm"), Some(10.0), Some(10.0)), "{r}");
+ let r = run("parameters.add", json!({"name": "Label", "expression": "Rev A", "unit": "text"}), output_schema_for::<ParamAdded>());
+ assert!(r["text"] == "Rev A" && r["value"].is_null() && r.get("display_value").is_none(), "{r}");
+ run("parameters.add", json!({"name": "H", "value": 5, "unit": "mm", "favorite": true}), output_schema_for::<ParamAdded>());
+ run("parameters.comment", json!({"name": "H", "comment": "Height"}), output_schema_for::<ParamCommented>());
+ let r = run("parameters.favorite", json!({"name": "H", "favorite": false}), output_schema_for::<ParamFavorited>());
+ assert_eq!(r["favorite"], false, "{r}");
+ let r = run("parameters.move", json!({"name": "H", "before": "W"}), output_schema_for::<ParamMoved>());
+ let at = |name: &str| r["order"].as_array().and_then(|order| order.iter().position(|n| n == name));
+ assert!(at("H").is_some() && at("H") < at("W"), "{r}");
+ let r = run("parameters.rename", json!({"name": "W", "new_name": " Width "}), output_schema_for::<ParamRenamed>());
+ assert_eq!((r["from"].as_str(), r["to"].as_str()), (Some("W"), Some("Width")), "{r}");
+ run("parameters.delete", json!({"name": "Label"}), output_schema_for::<ParamDeleted>());
+ let p = json!({"name": "Width", "favourite": true});
+ let mut warned = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ warned.execute("parameters.add", &json!({"name": "Width", "expression": 3})).unwrap_or_else(|e| panic!("{e}"));
+ let r = warned.execute("parameters.favorite", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
+ assert!(r["param_warnings"].to_string().contains("favourite"), "{r}");
+ warned.param_check = ParamCheck::Strict;
+ let error = warned.execute("parameters.favorite", &p).err().map(|e| e.to_string()).unwrap_or_default();
+ assert!(error.contains("`favourite`"), "{error}");
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 9a0d24bec9..69e8f7d4e8 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -91,18 +91,12 @@ occurrence.drag
occurrence.ground
occurrence.move
occurrence.properties
-parameters.add
parameters.change
-parameters.comment
parameters.complete
-parameters.delete
parameters.export
-parameters.favorite
parameters.graph
parameters.import
parameters.list
-parameters.move
-parameters.rename
parameters.users
plastic.assign_rule
plastic.boss