Skip to content

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

Agents and scripts: the linked-component commands describe their exact parameters and reply (#12277) (#12351)

PeppaWutza07b60cd8175
diff --git a/crates/engine/src/cmd/component_extract.rs b/crates/engine/src/cmd/component_extract.rs
index 8b63dbd924..e70ae44c9f 100644
--- a/crates/engine/src/cmd/component_extract.rs
+++ b/crates/engine/src/cmd/component_extract.rs
@@ -20,8 +20,9 @@ use serde_json::{Value, json};
use solidcore_record::Vec3;
use solidcraft_doc::{DesignLink, Document, FeatureKind, ModelBody, ModelState};
-use super::{absolute, component_key, file_sha256, inherit_properties, resolve, session_bodies, stored};
+use super::{absolute, component_key, file_sha256, inherit_properties, reply, resolve, session_bodies, stored};
use crate::params::{bad, str_};
+use crate::schema::component_link::{CopiesResult, CopyInfo, ExtractResult, ReplaceWithLinkResult};
use crate::{EngineError, Result, Session};
const CMD: &str = "component.extract";
@@ -649,8 +650,8 @@ fn copies_of(s: &Session, linked: u64) -> Result<Vec<u64>> {
Ok(out)
}
-fn named(s: &Session, ids: &[u64]) -> Vec<Value> {
- ids.iter().map(|id| json!({"component": id, "name": s.doc.components.iter().find(|c| c.id == *id).map(|c| c.name.clone())})).collect()
+fn named(s: &Session, ids: &[u64]) -> Vec<CopyInfo> {
+ ids.iter().map(|id| CopyInfo { component: *id, name: s.doc.components.iter().find(|c| c.id == *id).map(|c| c.name.clone()) }).collect()
}
impl Session {
@@ -723,8 +724,21 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result<Value> {
{
link.file_sha256 = Some(read);
}
- Ok(json!({"component": comp, "feature": id, "path": path, "file": shown, "bodies": sc.bodies, "notices": notices, "warnings": warnings,
- "copies": named(s, &copies)}))
+ let copies = named(s, &copies);
+ reply(
+ CMD,
+ ExtractResult {
+ component: comp,
+ feature: id,
+ path,
+ file: shown,
+ bodies: sc.bodies.iter().cloned().collect(),
+ notices,
+ warnings,
+ copies,
+ param_warnings: Vec::new(),
+ },
+ )
}
pub(super) fn copies(s: &mut Session, p: &Value) -> Result<Value> {
@@ -734,7 +748,7 @@ pub(super) fn copies(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "that component is not linked to a design"));
}
let found = copies_of(s, linked)?;
- Ok(json!({"copies": named(s, &found)}))
+ reply(cmd, CopiesResult { copies: named(s, &found), param_warnings: Vec::new() })
}
pub(super) fn replace_with_link(s: &mut Session, p: &Value) -> Result<Value> {
@@ -816,7 +830,7 @@ pub(super) fn replace_with_link(s: &mut Session, p: &Value) -> Result<Value> {
s.doc_mut().occurrences.retain(|x| x.id != o);
s.refresh();
}
- Ok(json!({"component": linked, "name": lname, "replaced": replaced, "warnings": warnings}))
+ reply(cmd, ReplaceWithLinkResult { component: linked, name: lname, replaced, warnings, param_warnings: Vec::new() })
}
#[cfg(test)]
diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs
index b2e0bedb64..007d6a6026 100644
--- a/crates/engine/src/cmd/component_link.rs
+++ b/crates/engine/src/cmd/component_link.rs
@@ -19,6 +19,12 @@ use solidcraft_doc::{DesignLink, Document, FeatureKind, LinkedBodyProperties, Us
use super::CommandSpec;
use super::design_link::{absolute, resolve, stored};
use crate::params::{bad, str_, vec3};
+use crate::schema::component_link::{
+ BreakLinkParams, BreakLinkResult, CopiesParams, CopiesResult, DesignInserted, ExtractParams, ExtractResult, InsertDesignParams,
+ InsertDesignResult, JointDiagnostic, LinkFailure, LinkInfo, LinksParams, LinksResult, RelinkParams, RelinkResult, ReplaceWithLinkParams,
+ ReplaceWithLinkResult, UpdateLinksParams, UpdateLinksResult,
+};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
#[path = "component_extract.rs"]
@@ -29,39 +35,81 @@ mod extract;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod relink_tests;
+const INSERT_DESIGN_CONTRACT: TypedContract<InsertDesignParams> = TypedContract::new();
+const UPDATE_LINKS_CONTRACT: TypedContract<UpdateLinksParams> = TypedContract::new();
+const RELINK_CONTRACT: TypedContract<RelinkParams> = TypedContract::new();
+const BREAK_LINK_CONTRACT: TypedContract<BreakLinkParams> = TypedContract::new();
+const EXTRACT_CONTRACT: TypedContract<ExtractParams> = TypedContract::new();
+const COPIES_CONTRACT: TypedContract<CopiesParams> = TypedContract::new();
+const REPLACE_WITH_LINK_CONTRACT: TypedContract<ReplaceWithLinkParams> = TypedContract::new();
+const LINKS_CONTRACT: TypedContract<LinksParams> = TypedContract::new();
+
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("component.insert_design", "Insert Design", insert_design).at("SOLID", "ASSEMBLE").icon("component").params(
+ CommandSpec::new("component.insert_design", "Insert Design", crate::checked!("component.insert_design", insert_design))
+ .at("SOLID", "ASSEMBLE")
+ .icon("component")
+ .contract(&INSERT_DESIGN_CONTRACT)
+ .output(output_schema_for::<InsertDesignResult>)
+ .params(
"path: a .sc design → a new component linked to it, holding its solid bodies as placed in that design and a copy of its design properties; \
name? (default: the design's name); parent?: component id or name (default: the active one); \
translate?: [x,y,z] in mm from the destination parent's origin (default [0,0,0], also with reuse); \
reuse?: bool (default false): insert a free occurrence, reusing an existing link to the same file when available",
),
- CommandSpec::new("component.update_links", "Update Links", update_links).icon("update").params(
+ CommandSpec::new("component.update_links", "Update Links", crate::checked!("component.update_links", update_links))
+ .icon("update")
+ .contract(&UPDATE_LINKS_CONTRACT)
+ .output(output_schema_for::<UpdateLinksResult>)
+ .params(
"component?: id or name (default: every linked component); components?: a list of ids or names, which goes on past a design it \
cannot read (that one keeps its bodies, is named in failed and gets a warning) — reads the linked designs again and replaces \
their bodies where they changed, as one undo step; → updated, unchanged, failed ([{component, name, error}]), warnings (also \
joints whose faces are gone or that no longer solve)",
),
- CommandSpec::new("component.relink", "Relink Source", relink).icon("update").params(
+ CommandSpec::new("component.relink", "Relink Source", crate::checked!("component.relink", relink))
+ .icon("update")
+ .contract(&RELINK_CONTRACT)
+ .output(output_schema_for::<RelinkResult>)
+ .params(
"component: id or name of a linked component; path: a saved design (.sc or .json) — replaces the source and linked bodies for all its occurrences, preserving identities and placements; returns path, previous_path, warnings, joint_errors and joint_conflicts",
),
- CommandSpec::new("component.break_link", "Break Link", break_link)
+ CommandSpec::new("component.break_link", "Break Link", crate::checked!("component.break_link", break_link))
.icon("break")
+ .contract(&BREAK_LINK_CONTRACT)
+ .output(output_schema_for::<BreakLinkResult>)
.params("component: id or name of a linked component — keeps its bodies as they are and forgets the design file"),
- CommandSpec::new("component.extract", "Extract to File", extract::extract).icon("export").params(
+ CommandSpec::new("component.extract", "Extract to File", crate::checked!("component.extract", extract::extract))
+ .icon("export")
+ .contract(&EXTRACT_CONTRACT)
+ .output(output_schema_for::<ExtractResult>)
+ .params(
"component: id or name of a component that is not linked; path: the .sc design to write → its history, subcomponents and their joints \
move to that design, and the component becomes linked to it (as component.insert_design makes it); returns path, file, feature, bodies, \
notices (what stays behind), warnings and copies (components that build the same bodies: see component.replace_with_link)",
),
- CommandSpec::new("component.copies", "Find Identical Copies", extract::copies).icon("inspect").noundo().params(
+ CommandSpec::new("component.copies", "Find Identical Copies", crate::checked!("component.copies", extract::copies))
+ .icon("inspect")
+ .noundo()
+ .contract(&COPIES_CONTRACT)
+ .output(output_schema_for::<CopiesResult>)
+ .params(
"component: id or name of a linked component → copies: [{component, name}], the components not linked whose own history builds the same bodies",
),
- CommandSpec::new("component.replace_with_link", "Replace with Link", extract::replace_with_link).icon("chain").params(
+ CommandSpec::new("component.replace_with_link", "Replace with Link", crate::checked!("component.replace_with_link", extract::replace_with_link))
+ .icon("chain")
+ .contract(&REPLACE_WITH_LINK_CONTRACT)
+ .output(output_schema_for::<ReplaceWithLinkResult>)
+ .params(
"component or components: [ids or names] of components that are not linked; with: a linked component, or path: a .sc design \
(its link here, else a new linked component) → each component's history goes and its placements become placements of the linked \
component; refused when its bodies are not the same as the link's; returns component, name, replaced and warnings",
),
- CommandSpec::new("component.links", "List Links", list_links).icon("chain").noundo().params(
+ CommandSpec::new("component.links", "List Links", crate::checked!("component.links", list_links))
+ .icon("chain")
+ .noundo()
+ .contract(&LINKS_CONTRACT)
+ .output(output_schema_for::<LinksResult>)
+ .params(
"→ linked components: component, name, path, file (resolved), found (null when the file is on a network location not allowed, \
or names a device: it is not looked for), changed (whether the file is no longer what this design last read: Update Links \
reads it again; null when not found or the link is older than this record), and then host (the network location) and reason",
@@ -493,6 +541,12 @@ fn component_key(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<u64> {
s.doc.find_component(&k).ok_or_else(|| bad(cmd, format!("no component `{k}`")))
}
+/// A command's reply as JSON: they 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 insert_design(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "component.insert_design";
let given = str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "`path` is required"))?;
@@ -515,7 +569,7 @@ fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
let mut transform = solidcraft_doc::IDENTITY;
transform[3] = [translate.x, translate.y, translate.z, 1.0];
let occurrence = s.doc_mut().add_occurrence(component, parent, transform)?;
- return Ok(json!({"occurrence": occurrence, "component": component}));
+ return reply(cmd, InsertDesignResult { inserted: DesignInserted::Reused { occurrence, component }, param_warnings: Vec::new() });
}
}
let ((design_name, sf, faces, metadata, properties), read) = linked_bodies_read(&file, s.path.as_deref(), s.validation())?;
@@ -555,10 +609,18 @@ fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
inherit_properties(s, comp, &properties)?;
s.refresh();
let st = s.model.state();
- let bodies: Vec<&str> = st.bodies.iter().filter(|b| b.feature == id).map(|b| b.name.as_str()).collect();
- Ok(
- json!({"component": comp, "occurrence": occ, "name": name, "feature": id, "path": path, "bodies": bodies, "created_bodies": bodies, "warnings": sf.warnings}),
- )
+ let bodies: Vec<String> = st.bodies.iter().filter(|b| b.feature == id).map(|b| b.name.clone()).collect();
+ let inserted = DesignInserted::New {
+ component: comp,
+ occurrence: occ,
+ name,
+ feature: id,
+ path,
+ created_bodies: bodies.clone(),
+ bodies,
+ warnings: sf.warnings,
+ };
+ reply(cmd, InsertDesignResult { inserted, param_warnings: Vec::new() })
}
fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
@@ -581,7 +643,8 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
let go_on = p.get("components").is_some();
let links: Vec<(u64, DesignLink)> =
s.doc.links.iter().filter(|(c, _)| only.as_ref().is_none_or(|o| o.contains(c))).map(|(c, l)| (*c, l.clone())).collect();
- let (mut updated, mut unchanged, mut warnings, mut failed) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
+ let (mut updated, mut unchanged, mut warnings): (Vec<String>, Vec<String>, Vec<String>) = (Vec::new(), Vec::new(), Vec::new());
+ let mut failed: Vec<LinkFailure> = Vec::new();
let count = links.len();
for (index, (comp, link)) in links.into_iter().enumerate() {
let cname = s.doc.components.iter().find(|c| c.id == comp).map(|c| c.name.clone());
@@ -595,7 +658,7 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
let (old, file, bytes) = match read_linked(s, comp, &link) {
Ok(read) => read,
Err(e) if go_on => {
- failed.push(json!({"component": comp, "name": cname, "error": e}));
+ failed.push(LinkFailure { component: comp, name: cname.clone(), error: e.clone() });
warnings.push(format!("{cname} keeps its bodies: {e}"));
continue;
}
@@ -634,7 +697,7 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(kept) = s.doc_mut().links.get_mut(&comp) {
kept.file_sha256.clone_from(&link.file_sha256);
}
- failed.push(json!({"component": comp, "name": cname, "error": e.to_string()}));
+ failed.push(LinkFailure { component: comp, name: cname.clone(), error: e.to_string() });
warnings.push(format!("{cname} keeps its bodies: {e}"));
continue;
}
@@ -679,8 +742,7 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
solidcraft_doc::progress::item(None);
// None could be read: nothing to take back either.
if updated.is_empty() && unchanged.is_empty() && !failed.is_empty() {
- let (name, why) = (failed[0]["name"].as_str().unwrap_or_default(), failed[0]["error"].as_str().unwrap_or_default());
- return Err(bad(cmd, format!("{name}: {why}")));
+ return Err(bad(cmd, format!("{}: {}", failed[0].name, failed[0].error)));
}
s.refresh();
if let Some(e) = s.doc.links.values().find_map(|l| s.model.result(l.feature).and_then(|r| r.error.clone())) {
@@ -691,7 +753,7 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state());
warnings.extend(sol.errors.iter().chain(&sol.conflicts).map(|(_, name, why)| format!("joint {name}: {why}")));
}
- Ok(json!({"updated": updated, "unchanged": unchanged, "warnings": warnings, "failed": failed}))
+ reply(cmd, UpdateLinksResult { updated, unchanged, warnings, failed, param_warnings: Vec::new() })
}
/// `comp`'s linked design as it was last read (its bodies) and as its file is now, read before
@@ -777,25 +839,39 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
// Report the solver's diagnostics. A resolved joint can still describe the wrong
// connection after a source edit; the reminder above does not depend on solve errors.
let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state());
- let diagnostics =
- |rows: &[(u64, String, String)]| rows.iter().map(|(id, name, why)| json!({"joint": id, "name": name, "why": why})).collect::<Vec<_>>();
+ let diagnostics = |rows: &[(u64, String, String)]| {
+ rows.iter().map(|(joint, name, why)| JointDiagnostic { joint: *joint, name: name.clone(), why: why.clone() }).collect::<Vec<_>>()
+ };
for (_, name, why) in sol.errors.iter().chain(&sol.conflicts) {
warnings.push(format!("joint {name}: {why}"));
}
let previous_path = stored(s.path.as_deref(), &resolve(s.path.as_deref(), &link.path));
- Ok(json!({"component": comp, "feature": link.feature, "path": path, "previous_path": previous_path, "geometry_changed": geometry_changed,
- "warnings": warnings, "joint_errors": diagnostics(&sol.errors), "joint_conflicts": diagnostics(&sol.conflicts)}))
+ reply(
+ cmd,
+ RelinkResult {
+ component: comp,
+ feature: link.feature,
+ path,
+ previous_path,
+ geometry_changed,
+ warnings,
+ joint_errors: diagnostics(&sol.errors),
+ joint_conflicts: diagnostics(&sol.conflicts),
+ param_warnings: Vec::new(),
+ },
+ )
}
fn break_link(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "component.break_link";
let comp = component_key(s, p, "component", cmd)?;
let link = s.doc_mut().links.remove(&comp).ok_or_else(|| bad(cmd, "that component is not linked to a design"))?;
- Ok(json!({"component": comp, "path": stored(s.path.as_deref(), &resolve(s.path.as_deref(), &link.path))}))
+ let path = stored(s.path.as_deref(), &resolve(s.path.as_deref(), &link.path));
+ reply(cmd, BreakLinkResult { component: comp, path, param_warnings: Vec::new() })
}
fn list_links(s: &mut Session, _p: &Value) -> Result<Value> {
- let links: Vec<Value> = s
+ let links: Vec<LinkInfo> = s
.doc
.links
.iter()
@@ -816,16 +892,24 @@ fn list_links(s: &mut Session, _p: &Value) -> Result<Value> {
.as_ref()
.filter(|_| found == Some(true))
.and_then(|kept| file_sha256(Path::new(file.as_ref()), s.path.as_deref()).map(|now| now != *kept));
- json!({"component": c, "name": name, "path": path, "file": file, "found": found, "changed": changed})
+ LinkInfo::Looked { component: *c, name, path, file: file.into_owned(), found, changed }
+ }
+ Some(solidcraft_io::vfs::Remote::Network(host)) => LinkInfo::Network {
+ component: *c,
+ name,
+ path,
+ file: file.into_owned(),
+ found: None,
+ reason: format!("on the network location \\\\{host}, which is not allowed"),
+ host,
+ },
+ Some(solidcraft_io::vfs::Remote::Device) => {
+ LinkInfo::Device { component: *c, name, path, file: file.into_owned(), found: None, reason: "names a device, not a file".into() }
}
- Some(solidcraft_io::vfs::Remote::Network(host)) => json!({"component": c, "name": name, "path": path, "file": file,
- "found": null, "host": host, "reason": format!("on the network location \\\\{host}, which is not allowed")}),
- Some(solidcraft_io::vfs::Remote::Device) => json!({"component": c, "name": name, "path": path, "file": file,
- "found": null, "reason": "names a device, not a file"}),
}
})
.collect();
- Ok(json!({"links": links}))
+ reply("component.links", LinksResult { links, param_warnings: Vec::new() })
}
#[cfg(test)]
diff --git a/crates/engine/src/schema/component_link.rs b/crates/engine/src/schema/component_link.rs
new file mode 100644
index 0000000000..724856d41f
--- /dev/null
+++ b/crates/engine/src/schema/component_link.rs
@@ -0,0 +1,639 @@
+//! Contracts and result types for the linked-component commands in `cmd/component_link.rs`:
+//! `component.insert_design`, `component.update_links`, `component.relink`,
+//! `component.break_link`, `component.links` and, from `cmd/component_extract.rs`,
+//! `component.extract`, `component.copies` and `component.replace_with_link` (#12277).
+//!
+//! 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 component, a design file or a link
+//! exists stays the handler's to check. A key the handler refuses when it is left out (a
+//! component, a path) is optional in the type and required in the schema, so that the handler's
+//! message, not the check's "is required", is what a caller sees.
+
+use std::borrow::Cow;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::{Value, json};
+use solidcore_record::Vec3;
+use solidcraft_geom::Vec3Geom as _;
+
+use super::check::{located, whole};
+use super::types::{not_blank_pattern, present};
+use crate::params;
+
+/// The most components `component.update_links` and `component.replace_with_link` read from a
+/// list, as the handlers do.
+const MAX_UPDATE: usize = 10_000;
+const MAX_REPLACE: usize = 1_000;
+
+/// A component by its id (a number) or its name, as `component_key` reads it.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ComponentRef(pub String);
+
+impl<'de> Deserialize<'de> for ComponentRef {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Number(n) => Ok(ComponentRef(n.to_string())),
+ Value::String(s) => Ok(ComponentRef(s)),
+ _ => Err(D::Error::custom("must be a component id or name")),
+ }
+ }
+}
+
+impl JsonSchema for ComponentRef {
+ fn schema_name() -> Cow<'static, str> {
+ "ComponentRef".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A component's id (a number) or its name.", "type": ["number", "string"]})
+ }
+}
+
+/// `key`, a component's id or name, with the handler's message for anything else, `null`
+/// included.
+fn component_key<'de, D: Deserializer<'de>>(d: D, key: &str) -> Result<Option<ComponentRef>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Number(n) => Ok(Some(ComponentRef(n.to_string()))),
+ Value::String(s) => Ok(Some(ComponentRef(s))),
+ _ => Err(D::Error::custom(whole(format!("`{key}` must be a component id or name")))),
+ }
+}
+
+fn component<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ComponentRef>, D::Error> {
+ component_key(d, "component")
+}
+
+fn parent<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ComponentRef>, D::Error> {
+ component_key(d, "parent")
+}
+
+fn with<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ComponentRef>, D::Error> {
+ component_key(d, "with")
+}
+
+/// A design file's path as the handlers read `path`: text with something in it, under 4096
+/// bytes. `message` is the handler's, for anything else, `null` included.
+fn design_path<'de, D: Deserializer<'de>>(d: D, message: &str) -> Result<Option<String>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(s) if !s.trim().is_empty() && s.len() < 4096 => Ok(Some(s)),
+ _ => Err(D::Error::custom(whole(message))),
+ }
+}
+
+fn path_required<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ design_path(d, "`path` is required")
+}
+
+fn with_or_path<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ design_path(d, "`with` or `path` is required")
+}
+
+fn path_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": "string", "pattern": not_blank_pattern(), "maxLength": 4095})
+}
+
+/// Adds `key` to the schema's `required` list: for a key the type has optional so that the
+/// handler, not the check, refuses it when it's left out.
+fn require(schema: &mut Schema, key: &str) {
+ match schema.get_mut("required") {
+ Some(Value::Array(required)) => {
+ if !required.iter().any(|k| k == key) {
+ required.push(key.into());
+ }
+ }
+ _ => {
+ schema.insert("required".into(), Value::Array(vec![key.into()]));
+ }
+ }
+}
+
+fn component_required(schema: &mut Schema) {
+ require(schema, "component");
+}
+
+fn component_and_path_required(schema: &mut Schema) {
+ require(schema, "component");
+ require(schema, "path");
+}
+
+fn path_only_required(schema: &mut Schema) {
+ require(schema, "path");
+}
+
+/// A component's `translate` as `component.insert_design` reads it: `[x, y, z]` or `{x, y, z}`
+/// in mm, finite and under 1e9 in length.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Translation(pub Vec3);
+
+impl<'de> Deserialize<'de> for Translation {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ params::vec3(&Value::deserialize(d)?)
+ .filter(|t| t.is_finite() && t.len() < 1e9)
+ .map(Translation)
+ .ok_or_else(|| D::Error::custom(whole("`translate` must be [x, y, z] in mm")))
+ }
+}
+
+impl JsonSchema for Translation {
+ fn schema_name() -> Cow<'static, str> {
+ "Translation".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ let c = json!({"type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9});
+ json_schema!({
+ "description": "A distance in mm, as [x, y, z] or {\"x\", \"y\", \"z\"}.",
+ "anyOf": [
+ {"type": "array", "items": c, "minItems": 3, "maxItems": 3},
+ {"type": "object", "properties": {"x": c, "y": c, "z": c}, "required": ["x", "y", "z"]}
+ ]
+ })
+ }
+}
+
+/// Insert a design file as a new component linked to it: its solid bodies as placed in that
+/// design, and a copy of its design properties. The link remembers the file, so
+/// `component.update_links` can read it again. One undo step. With `reuse`, a design already
+/// linked gets another placement instead of another link.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = path_only_required)]
+pub struct InsertDesignParams {
+ // Optional in the type and required in the schema (`path_only_required`).
+ /// The design (`.sc`) to link, by file path.
+ #[serde(default, deserialize_with = "path_required", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "path_schema")]
+ pub path: Option<String>,
+ /// The component's name. Default: the design's name.
+ #[serde(default)]
+ pub name: Option<String>,
+ /// The component to put it in, by id or name. Default: the active one.
+ #[serde(default, deserialize_with = "parent", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub parent: Option<ComponentRef>,
+ /// Where to place it, in mm from the parent's origin. Default: [0, 0, 0], also with `reuse`.
+ #[serde(default)]
+ pub translate: Option<Translation>,
+ /// Reuse an existing link to the same file when there is one, placing another occurrence of
+ /// it. Default: false.
+ #[serde(default)]
+ pub reuse: Option<bool>,
+}
+
+/// What `component.insert_design` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct InsertDesignResult {
+ #[serde(flatten)]
+ pub inserted: DesignInserted,
+ /// 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 an insertion made.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum DesignInserted {
+ /// With `reuse`, a link to the file existed: only a new placement of its component.
+ Reused {
+ /// The new placement, by id.
+ occurrence: u64,
+ /// The linked component, by id.
+ component: u64,
+ },
+ /// A new component, linked to the file.
+ New {
+ /// The new component, by id.
+ component: u64,
+ /// Its placement, by id.
+ occurrence: Option<u64>,
+ /// The component's name.
+ name: String,
+ /// The Import feature that holds the bodies, by id.
+ feature: u64,
+ /// The file as the link stores it (relative to this design's folder when it is saved).
+ path: String,
+ /// The bodies the link brought in.
+ bodies: Vec<String>,
+ /// The same bodies, as the commands that make bodies report them.
+ created_bodies: Vec<String>,
+ /// What the design file gave that did not come in (such as mesh bodies).
+ warnings: Vec<String>,
+ },
+}
+
+/// A list of components, as `component.update_links` reads `components`: one to 10000, each by
+/// id or name.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ComponentList(pub Vec<ComponentRef>);
+
+impl<'de> Deserialize<'de> for ComponentList {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let item = |v: Value| match v {
+ Value::Number(n) => Ok(ComponentRef(n.to_string())),
+ Value::String(s) => Ok(ComponentRef(s)),
+ _ => Err(D::Error::custom(whole("`component` must be a component id or name"))),
+ };
+ match Value::deserialize(d)? {
+ Value::Array(list) if !list.is_empty() && list.len() <= MAX_UPDATE => {
+ list.into_iter().map(item).collect::<Result<_, _>>().map(ComponentList)
+ }
+ _ => Err(D::Error::custom(whole("`components` must be a list of component ids or names"))),
+ }
+ }
+}
+
+impl JsonSchema for ComponentList {
+ fn schema_name() -> Cow<'static, str> {
+ "ComponentList".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let item = generator.subschema_for::<ComponentRef>();
+ json_schema!({
+ "description": "Components, each by id or name.",
+ "type": "array",
+ "items": item,
+ "minItems": 1,
+ "maxItems": MAX_UPDATE
+ })
+ }
+}
+
+/// Read the linked designs again and replace the bodies of the components whose file changed,
+/// as one undo step. Without `component` or `components`, every linked component is read. A
+/// component that is not linked is refused.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct UpdateLinksKeys {
+ /// One linked component, by id or name. Not with `components`.
+ #[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub component: Option<ComponentRef>,
+ /// Linked components, by id or name. Not with `component`. With a list, an update goes on
+ /// past a design it cannot read: that component keeps its bodies, is named in `failed` and
+ /// gets a warning.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentList")]
+ pub components: Option<ComponentList>,
+}
+
+/// `component.update_links`' parameters: [`UpdateLinksKeys`], with `component` and `components`
+/// together refused first, as the handler does.
+#[derive(Debug)]
+pub struct UpdateLinksParams(pub UpdateLinksKeys);
+
+impl<'de> Deserialize<'de> for UpdateLinksParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let value = Value::deserialize(d)?;
+ if value.get("component").is_some() && value.get("components").is_some() {
+ return Err(D::Error::custom(whole("give `component` or `components`, not both")));
+ }
+ serde_path_to_error::deserialize(&value).map(UpdateLinksParams).map_err(|e| D::Error::custom(located(&e)))
+ }
+}
+
+impl JsonSchema for UpdateLinksParams {
+ fn schema_name() -> Cow<'static, str> {
+ "UpdateLinksParams".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let mut schema = UpdateLinksKeys::json_schema(generator);
+ schema.insert("not".into(), json!({"required": ["component", "components"]}));
+ schema
+ }
+}
+
+/// What `component.update_links` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct UpdateLinksResult {
+ /// The components whose bodies changed, by name.
+ pub updated: Vec<String>,
+ /// The components read whose bodies did not change, by name.
+ pub unchanged: Vec<String>,
+ /// What the update noticed, also joints whose faces are gone or that no longer solve.
+ pub warnings: Vec<String>,
+ /// With a `components` list: the designs that could not be read.
+ pub failed: Vec<LinkFailure>,
+ /// 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 linked design `component.update_links` could not read: its component keeps its bodies.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct LinkFailure {
+ /// The component, by id.
+ pub component: u64,
+ pub name: String,
+ /// Why the design could not be read.
+ pub error: String,
+}
+
+/// Replace the source of a linked component with another saved design, for all its occurrences,
+/// keeping their identities and placements. The design is read and checked before anything
+/// changes; one undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = component_and_path_required)]
+pub struct RelinkParams {
+ // Optional in the type and required in the schema (`component_and_path_required`).
+ /// The linked component, by id or name.
+ #[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub component: Option<ComponentRef>,
+ /// The saved design to link instead, `.sc` or `.json`.
+ #[serde(default, deserialize_with = "path_required", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "path_schema")]
+ pub path: Option<String>,
+}
+
+/// What `component.relink` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct RelinkResult {
+ /// The component, by id.
+ pub component: u64,
+ /// The Import feature that holds the linked bodies, by id.
+ pub feature: u64,
+ /// The new file, as the link stores it.
+ pub path: String,
+ /// The file the link had.
+ pub previous_path: String,
+ /// Whether the linked bodies are not the ones the link had.
+ pub geometry_changed: bool,
+ /// What the new design gave that did not come in, and joints to check.
+ pub warnings: Vec<String>,
+ /// Joints that no longer solve.
+ pub joint_errors: Vec<JointDiagnostic>,
+ /// Joints that conflict with others.
+ pub joint_conflicts: Vec<JointDiagnostic>,
+ /// 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 joint the solver reports after a relink.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JointDiagnostic {
+ /// The joint, by id.
+ pub joint: u64,
+ pub name: String,
+ pub why: String,
+}
+
+/// Forget a component's link to its design file and keep its bodies as they are. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = component_required)]
+pub struct BreakLinkParams {
+ // Optional in the type and required in the schema (`component_required`).
+ /// The linked component, by id or name.
+ #[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub component: Option<ComponentRef>,
+}
+
+/// What `component.break_link` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BreakLinkResult {
+ /// The component, by id.
+ pub component: u64,
+ /// The file it was linked to, as the link stored it.
+ pub path: 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>,
+}
+
+/// `component.links` takes no parameters.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct LinksParams {}
+
+/// What `component.links` returns: every linked component and whether its file is there.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct LinksResult {
+ pub links: Vec<LinkInfo>,
+ /// 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>,
+}
+
+/// One linked component. A file that is looked for has `found` and `changed`; a refused one is
+/// not looked for and has `found` null and a `reason`.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum LinkInfo {
+ /// The file was looked for.
+ Looked {
+ /// The component, by id.
+ component: u64,
+ name: Option<String>,
+ /// The link as stored.
+ path: String,
+ /// The file it resolves to.
+ file: String,
+ /// Whether the file is there; null when that can't be told.
+ found: Option<bool>,
+ /// Whether the file is no longer what this design last read (`component.update_links`
+ /// reads it again); null when it is not found or the link is older than this record.
+ changed: Option<bool>,
+ },
+ /// The file is on a network location that is not allowed.
+ Network {
+ component: u64,
+ name: Option<String>,
+ path: String,
+ file: String,
+ /// Always null: it is not looked for.
+ found: Option<bool>,
+ /// The network location.
+ host: String,
+ reason: String,
+ },
+ /// The path names a device.
+ Device {
+ component: u64,
+ name: Option<String>,
+ path: String,
+ file: String,
+ /// Always null: it is not looked for.
+ found: Option<bool>,
+ reason: String,
+ },
+}
+
+/// Move a component's history, subcomponents and their joints into a design file of its own and
+/// link the component to that file, as `component.insert_design` would have made it. The
+/// component must not be linked already. Anything that crosses the component's boundary is
+/// refused. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = component_and_path_required)]
+pub struct ExtractParams {
+ // Optional in the type and required in the schema (`component_and_path_required`).
+ /// The component to extract, by id or name.
+ #[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub component: Option<ComponentRef>,
+ /// The design file to write, a `.sc`.
+ #[serde(default, deserialize_with = "path_required", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "path_schema")]
+ pub path: Option<String>,
+}
+
+/// What `component.extract` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ExtractResult {
+ /// The component, by id.
+ pub component: u64,
+ /// The Import feature that now holds its bodies, by id.
+ pub feature: u64,
+ /// The file as the link stores it.
+ pub path: String,
+ /// The file written.
+ pub file: String,
+ /// The component's bodies, by name.
+ pub bodies: Vec<String>,
+ /// What stays behind in this design.
+ pub notices: Vec<String>,
+ /// Joints to check.
+ pub warnings: Vec<String>,
+ /// Components that build the same bodies (see `component.replace_with_link`).
+ pub copies: Vec<CopyInfo>,
+ /// 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 component, by id and name.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CopyInfo {
+ /// The component, by id.
+ pub component: u64,
+ pub name: Option<String>,
+}
+
+/// Find the components, not linked, whose own history builds the same bodies as a linked
+/// component. The design is not changed.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = component_required)]
+pub struct CopiesParams {
+ // Optional in the type and required in the schema (`component_required`).
+ /// The linked component, by id or name.
+ #[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub component: Option<ComponentRef>,
+}
+
+/// What `component.copies` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CopiesResult {
+ /// The components that build the same bodies, not linked.
+ pub copies: Vec<CopyInfo>,
+ /// 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>,
+}
+
+/// `component.replace_with_link`'s `components`: each by id or name; the handler reads the
+/// first 1000 and ignores the rest.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ReplaceTargets(pub Vec<ComponentRef>);
+
+impl<'de> Deserialize<'de> for ReplaceTargets {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let item = |v: Value| match v {
+ Value::Number(n) => Ok(ComponentRef(n.to_string())),
+ Value::String(s) => Ok(ComponentRef(s)),
+ _ => Err(D::Error::custom(whole("`component` must be a component id or name"))),
+ };
+ match Value::deserialize(d)? {
+ Value::Array(list) => list.into_iter().take(MAX_REPLACE).map(item).collect::<Result<_, _>>().map(ReplaceTargets),
+ _ => Err(D::Error::custom(whole("`components` must be a list of component ids or names"))),
+ }
+ }
+}
+
+impl JsonSchema for ReplaceTargets {
+ fn schema_name() -> Cow<'static, str> {
+ "ReplaceTargets".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let item = generator.subschema_for::<ComponentRef>();
+ json_schema!({
+ "description": "Components, each by id or name; only the first 1000 are used.",
+ "type": "array",
+ "items": item
+ })
+ }
+}
+
+/// Make components that are not linked, and build the same bodies as a linked component, more
+/// placements of it: each one's history goes and its placements become placements of the linked
+/// component. One is refused when its bodies are not the same as the link's. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = replace_required)]
+pub struct ReplaceWithLinkKeys {
+ // The schema asks for `component` or `components`, and `with` or `path` (`replace_required`).
+ /// One component to replace, by id or name.
+ #[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub component: Option<ComponentRef>,
+ /// Components to replace, by id or name; used with `component`.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ReplaceTargets")]
+ pub components: Option<ReplaceTargets>,
+ /// The linked component to place instead, by id or name.
+ #[serde(default, deserialize_with = "with", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub with: Option<ComponentRef>,
+ /// Without `with`: a design file (`.sc`). The component linked to it here, or else a new
+ /// linked component.
+ #[serde(default, deserialize_with = "with_or_path", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "path_schema")]
+ pub path: Option<String>,
+}
+
+/// `component.replace_with_link`'s parameters: [`ReplaceWithLinkKeys`], with `path` left unread
+/// when `with` is given, as the handler leaves it.
+#[derive(Debug)]
+pub struct ReplaceWithLinkParams(pub ReplaceWithLinkKeys);
+
+impl<'de> Deserialize<'de> for ReplaceWithLinkParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let mut value = Value::deserialize(d)?;
+ if let Some(keys) = value.as_object_mut().filter(|o| o.contains_key("with")) {
+ keys.remove("path");
+ }
+ serde_path_to_error::deserialize(&value).map(ReplaceWithLinkParams).map_err(|e| D::Error::custom(located(&e)))
+ }
+}
+
+impl JsonSchema for ReplaceWithLinkParams {
+ fn schema_name() -> Cow<'static, str> {
+ "ReplaceWithLinkParams".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ ReplaceWithLinkKeys::json_schema(generator)
+ }
+}
+
+fn replace_required(schema: &mut Schema) {
+ let at_least_one = |keys: [&str; 2]| json!({"anyOf": keys.map(|k| json!({"required": [k]}))});
+ schema.insert("allOf".into(), json!([at_least_one(["component", "components"]), at_least_one(["with", "path"])]));
+}
+
+/// What `component.replace_with_link` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ReplaceWithLinkResult {
+ /// The linked component that now has the placements, by id.
+ pub component: u64,
+ pub name: String,
+ /// The components that went, by name.
+ pub replaced: Vec<String>,
+ /// Joints to check.
+ pub warnings: 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 = "component_link_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/component_link_tests.rs b/crates/engine/src/schema/component_link_tests.rs
new file mode 100644
index 0000000000..d21141c70a
--- /dev/null
+++ b/crates/engine/src/schema/component_link_tests.rs
@@ -0,0 +1,263 @@
+use std::path::{Path, PathBuf};
+
+use serde_json::{Value, json};
+use solidcraft_doc::DesignLink;
+
+use super::{
+ BreakLinkParams, BreakLinkResult, CopiesParams, CopiesResult, ExtractParams, ExtractResult, InsertDesignParams, InsertDesignResult, LinksParams,
+ LinksResult, RelinkParams, RelinkResult, ReplaceWithLinkParams, ReplaceWithLinkResult, UpdateLinksParams, UpdateLinksResult,
+};
+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::<InsertDesignParams>(), &["name", "parent", "path", "reuse", "translate"]);
+ assert_keys(input_schema_for::<UpdateLinksParams>(), &["component", "components"]);
+ assert_keys(input_schema_for::<RelinkParams>(), &["component", "path"]);
+ assert_keys(input_schema_for::<BreakLinkParams>(), &["component"]);
+ assert_keys(input_schema_for::<LinksParams>(), &[]);
+ assert_keys(input_schema_for::<ExtractParams>(), &["component", "path"]);
+ assert_keys(input_schema_for::<CopiesParams>(), &["component"]);
+ assert_keys(input_schema_for::<ReplaceWithLinkParams>(), &["component", "components", "path", "with"]);
+}
+
+#[test]
+fn strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[
+ ("component.insert_design", json!({})),
+ ("component.insert_design", json!({"path": ""})),
+ ("component.insert_design", json!({"path": " "})),
+ ("component.insert_design", json!({"path": 5})),
+ ("component.insert_design", json!({"path": null})),
+ ("component.insert_design", json!({"path": "x".repeat(4096)})),
+ ("component.insert_design", json!({"path": "plate.solidcraft", "translate": [1, 2]})),
+ ("component.insert_design", json!({"path": "plate.solidcraft", "translate": null})),
+ ("component.insert_design", json!({"path": "plate.solidcraft", "translate": [1e9, 0, 0]})),
+ ("component.update_links", json!({"component": 0, "components": [0]})),
+ ("component.update_links", json!({"component": true})),
+ ("component.update_links", json!({"component": null})),
+ ("component.update_links", json!({"components": "Plate"})),
+ ("component.update_links", json!({"components": []})),
+ ("component.update_links", json!({"components": [true]})),
+ ("component.update_links", json!({"component": "Nope"})),
+ ("component.relink", json!({})),
+ ("component.relink", json!({"component": null, "path": "plate.solidcraft"})),
+ ("component.relink", json!({"component": [1], "path": "plate.solidcraft"})),
+ ("component.break_link", json!({})),
+ ("component.break_link", json!({"component": [1]})),
+ ("component.extract", json!({})),
+ ("component.extract", json!({"component": 0})),
+ ("component.extract", json!({"component": true, "path": "plate.solidcraft"})),
+ ("component.copies", json!({})),
+ ("component.copies", json!({"component": false})),
+ ("component.replace_with_link", json!({})),
+ ("component.replace_with_link", json!({"component": true})),
+ ("component.replace_with_link", json!({"components": [true]})),
+ ("component.replace_with_link", json!({"component": 0})),
+ ("component.replace_with_link", json!({"component": 0, "with": true})),
+ ("component.replace_with_link", json!({"component": 0, "path": ""})),
+ ("component.replace_with_link", json!({"component": 0, "path": 7})),
+ ]);
+}
+
+/// `path` is not read when `with` is given, so a bad one is no problem for the check either.
+#[test]
+fn replace_with_link_ignores_path_when_with_is_given() {
+ let issues = |p: Value| crate::schema::issues("component.replace_with_link", &p).len();
+ assert_eq!(issues(json!({"component": 1, "with": "Plate", "path": ""})), 0);
+ assert_eq!(issues(json!({"component": 1, "path": ""})), 1);
+}
+
+/// The contracts say what the handlers need: the keys a handler refuses without are required in
+/// the schemas, though the types leave them to the handlers' messages, and a component is an id
+/// or a name.
+#[test]
+fn the_schemas_take_what_the_handlers_read() {
+ let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
+ let schema = schema.as_value();
+ for (p, takes) in cases {
+ assert_eq!(conforms(schema, schema, p), *takes, "{p}");
+ }
+ };
+ takes(
+ input_schema_for::<InsertDesignParams>(),
+ &[
+ (json!({"path": "plate.solidcraft"}), true),
+ (json!({"path": "plate.solidcraft", "name": "P", "parent": "Arm", "translate": [1, 2, 3], "reuse": true}), true),
+ (json!({"path": "plate.solidcraft", "parent": 4, "translate": {"x": 1, "y": 2, "z": 3}}), true),
+ (json!({}), false),
+ (json!({"path": "plate.solidcraft", "parent": true}), false),
+ (json!({"path": "plate.solidcraft", "translate": [1, 2]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<UpdateLinksParams>(),
+ &[
+ (json!({}), true),
+ (json!({"component": "Plate"}), true),
+ (json!({"components": ["Plate", 3]}), true),
+ (json!({"component": 1, "components": [1]}), false),
+ (json!({"components": []}), false),
+ (json!({"components": [true]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<RelinkParams>(),
+ &[
+ (json!({"component": "Plate", "path": "b.solidcraft"}), true),
+ (json!({"component": "Plate"}), false),
+ (json!({"path": "b.solidcraft"}), false),
+ ],
+ );
+ takes(input_schema_for::<BreakLinkParams>(), &[(json!({"component": 2}), true), (json!({}), false), (json!({"component": null}), false)]);
+ takes(
+ input_schema_for::<ExtractParams>(),
+ &[(json!({"component": "Plate", "path": "plate.solidcraft"}), true), (json!({"component": "Plate"}), false), (json!({"path": "p"}), false)],
+ );
+ takes(input_schema_for::<CopiesParams>(), &[(json!({"component": 2}), true), (json!({}), false)]);
+ takes(
+ input_schema_for::<ReplaceWithLinkParams>(),
+ &[
+ (json!({"component": "Copy", "with": "Plate"}), true),
+ (json!({"components": ["A", 2], "path": "plate.solidcraft"}), true),
+ (json!({"with": "Plate"}), false),
+ (json!({"component": "Copy"}), false),
+ (json!({"component": "Copy", "with": true}), false),
+ ],
+ );
+}
+
+/// The warning for what a key gets wrong, and the check that a list of components takes only
+/// what the handlers read.
+#[test]
+fn the_check_names_what_is_wrong_with_a_key() {
+ let issues = |id: &str, p: Value| crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect::<Vec<_>>();
+ assert_eq!(issues("component.insert_design", json!({"path": "p.solidcraft", "translate": [1]})), ["`translate` must be [x, y, z] in mm"]);
+ assert_eq!(issues("component.insert_design", json!({"path": "p.solidcraft", "parent": true})), ["`parent` must be a component id or name"]);
+ assert_eq!(issues("component.update_links", json!({"component": 1, "components": [1]})), ["give `component` or `components`, not both"]);
+ assert_eq!(issues("component.update_links", json!({"components": [true]})), ["`component` must be a component id or name"]);
+ assert_eq!(issues("component.replace_with_link", json!({"component": 1})), Vec::<String>::new());
+ assert_eq!(issues("component.replace_with_link", json!({"component": 1, "path": 3})), ["`with` or `path` is required"]);
+ assert_eq!(issues("component.relink", json!({"component": 1, "path": "b.solidcraft", "paths": 1})).len(), 1);
+}
+
+fn folder(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("solidcraft-link-schema-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}"));
+ dir
+}
+
+fn save_box(path: &Path, height: u32) {
+ let mut part = Session::default();
+ for (id, p) in [("solid.box", json!({"length": 10, "width": 20, "height": height, "body_name": "Plate"})), ("file.save", json!({"path": path}))] {
+ part.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));
+ }
+}
+
+fn matches(schema: schemars::Schema, id: &str, reply: &Value) {
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");
+ assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");
+}
+
+/// Insert (new, reused, in a parent, placed), list, update (with a design that can't be read
+/// named in `failed`), relink and break, in Warn: each real reply matches its output schema and
+/// carries no warning. A list the network or a device refuses has the other shapes of an entry.
+#[test]
+fn link_replies_match_the_output_schema() {
+ let dir = folder("links");
+ let (a, b, c) = (dir.join("a.solidcraft"), dir.join("b.solidcraft"), dir.join("c.solidcraft"));
+ for (file, height) in [(&a, 10), (&b, 20), (&c, 30)] {
+ save_box(file, height);
+ }
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let first = run("component.insert_design", json!({"path": a, "name": "A"}));
+ matches(output_schema_for::<InsertDesignResult>(), "component.insert_design", &first);
+ assert!(first["created_bodies"] == first["bodies"] && first["bodies"] == json!(["Plate"]), "{first}");
+ let reused = run("component.insert_design", json!({"path": a, "reuse": true, "translate": [50, 0, 0]}));
+ assert!(reused.get("name").is_none() && reused["component"] == first["component"], "{reused}");
+ matches(output_schema_for::<InsertDesignResult>(), "component.insert_design", &reused);
+ let second = run("component.insert_design", json!({"path": b, "name": "B", "parent": first["component"], "translate": {"x": 1, "y": 2, "z": 3}}));
+ matches(output_schema_for::<InsertDesignResult>(), "component.insert_design", &second);
+ let third = run("component.insert_design", json!({"path": c, "name": "C"}));
+ matches(output_schema_for::<InsertDesignResult>(), "component.insert_design", &third);
+
+ let listed = run("component.links", json!({}));
+ assert_eq!(listed["links"].as_array().map(Vec::len), Some(3), "{listed}");
+ assert!(listed["links"][0]["found"] == true && listed["links"][0]["changed"] == false, "{listed}");
+ matches(output_schema_for::<LinksResult>(), "component.links", &listed);
+
+ // The design B links changed, and C's file is gone: B updates, C is named in `failed`.
+ save_box(&b, 25);
+ std::fs::remove_file(&c).unwrap_or_else(|e| panic!("{e}"));
+ let update = run("component.update_links", json!({"components": ["B", "C", "A"]}));
+ assert!(update["updated"] == json!(["B"]) && update["unchanged"] == json!(["A"]), "{update}");
+ assert!(update["failed"][0]["name"] == "C" && update["failed"][0]["component"] == third["component"], "{update}");
+ matches(output_schema_for::<UpdateLinksResult>(), "component.update_links", &update);
+ save_box(&b, 30);
+ let all = run("component.update_links", json!({"component": "B"}));
+ assert_eq!(all["updated"], json!(["B"]), "{all}");
+ assert_eq!(all["failed"], json!([]), "{all}");
+ matches(output_schema_for::<UpdateLinksResult>(), "component.update_links", &all);
+ let nothing = run("component.update_links", json!({"component": "A"}));
+ assert_eq!(nothing["unchanged"], json!(["A"]), "{nothing}");
+ matches(output_schema_for::<UpdateLinksResult>(), "component.update_links", &nothing);
+
+ let moved = run("component.relink", json!({"component": "A", "path": b}));
+ assert!(moved["geometry_changed"] == true && moved["joint_errors"] == json!([]), "{moved}");
+ matches(output_schema_for::<RelinkResult>(), "component.relink", &moved);
+ let broken = run("component.break_link", json!({"component": "A"}));
+ assert_eq!(broken["component"], first["component"], "{broken}");
+ matches(output_schema_for::<BreakLinkResult>(), "component.break_link", &broken);
+
+ // A misspelt key still runs in Warn, and says so, with a reply that matches.
+ let warned = run("component.links", json!({"lnks": true}));
+ assert!(warned["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{warned}");
+ let schema = output_schema_for::<LinksResult>();
+ assert!(conforms(schema.as_value(), schema.as_value(), &warned), "{warned}");
+
+ // Links the network or a device refuses are not looked for, and say why.
+ let (feature, component) =
+ (s.doc.links[&third["component"].as_u64().unwrap_or_default()].feature, third["component"].as_u64().unwrap_or_default());
+ for (link, host) in [(r"\\evil.example\share\c.solidcraft", true), (r"\\.\COM1", false)] {
+ s.doc_mut().links.insert(component, DesignLink { path: link.to_string(), feature, ..Default::default() });
+ let listed = s.execute("component.links", &json!({})).unwrap_or_else(|e| panic!("{e}"));
+ let entry = listed["links"].as_array().and_then(|l| l.iter().find(|e| e["component"] == third["component"])).cloned().unwrap_or_default();
+ assert!(entry["found"].is_null() && entry["reason"].is_string() && entry.get("changed").is_none(), "{listed}");
+ assert_eq!(entry.get("host").is_some(), host, "{listed}");
+ matches(output_schema_for::<LinksResult>(), "component.links", &listed);
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// Extract a component to a file, find its identical copy, and replace the copy with a
+/// placement of the link, in Warn: each real reply matches its output schema without warnings.
+#[test]
+fn extract_copies_and_replace_replies_match_the_output_schema() {
+ let dir = folder("extract");
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let made = run("component.create", json!({"name": "Plate", "grounded": false}));
+ let (plate, occurrence) = (made["component"].clone(), made["occurrence"].clone());
+ run("solid.box", json!({"length": 40, "width": 30, "height": 12, "body_name": "PlateBody"}));
+ run("component.activate", json!({"component": 0}));
+ let copy = run("component.paste_new", json!({"component": plate, "occurrence": occurrence, "translate": [0, 80, 0]}));
+ let file = dir.join("plate.solidcraft");
+ let extracted = run("component.extract", json!({"component": "Plate", "path": file}));
+ assert_eq!(extracted["bodies"], json!(["PlateBody"]), "{extracted}");
+ assert_eq!(extracted["copies"].as_array().map(Vec::len), Some(1), "{extracted}");
+ assert_eq!(extracted["copies"][0]["component"], copy["component"], "{extracted}");
+ matches(output_schema_for::<ExtractResult>(), "component.extract", &extracted);
+ let found = run("component.copies", json!({"component": plate}));
+ assert_eq!(found["copies"], extracted["copies"], "{found}");
+ matches(output_schema_for::<CopiesResult>(), "component.copies", &found);
+ let replaced = run("component.replace_with_link", json!({"components": [copy["component"]], "with": plate}));
+ assert!(replaced["component"] == plate && replaced["replaced"].as_array().is_some_and(|r| r.len() == 1), "{replaced}");
+ matches(output_schema_for::<ReplaceWithLinkResult>(), "component.replace_with_link", &replaced);
+ assert_eq!(run("component.copies", json!({"component": plate}))["copies"], json!([]));
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 86d1efa2f4..4d1cfa1566 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -60,6 +60,7 @@ pub mod browser;
pub mod clearance;
pub mod compare;
pub mod component;
+pub mod component_link;
pub mod config;
pub mod construct;
pub mod diagnostics;
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 69e8f7d4e8..e7adf1804f 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -8,15 +8,10 @@ canvas.delete
canvas.edit
canvas.insert
component.activate
-component.break_link
component.capture_position
-component.copies
component.create
component.delete
-component.extract
component.from_bodies
-component.insert_design
-component.links
component.list
component.metadata
component.metadata.set
@@ -24,12 +19,9 @@ component.move_bodies
component.move_sketches
component.paste_new
component.properties
-component.relink
component.rename
-component.replace_with_link
component.revert_position
component.unlock
-component.update_links
doc.open
doc.recover
doc.recovery_discard