Skip to main content

brep_kernel/feature_pipeline/assembly/
exports.rs

1//! The assembly SESSION + exported ABI: constraint CRUD with auto-solve,
2//! manual solve, per-constraint status JSON, DOF summary JSON,
3//! overlay-geometry JSON, and the generic document fold that writes the solved
4//! state + poses back into the history document.
5//!
6//! The session is installed by the history-execution tail
7//! ([`super::finish_history_run`]) after EVERY run: the post-solve constraint
8//! state, a clone of the final scene map (names + resident handles — the
9//! handles stay owned by the history cache), and the expression sheet for
10//! expression-capable params. Constraint mutations between runs operate on the
11//! session and AUTO-SOLVE against the live resident geometry; the app folds
12//! the result back into its document via [`assembly_apply_document_json`]
13//! before the next history run (the pose-authority contract).
14
15use std::cell::RefCell;
16use std::collections::BTreeMap;
17
18use wasm_bindgen::prelude::*;
19
20use super::lifecycle::{self, LifecycleOutcome};
21use super::{constraints, mapping, AssemblyState, ConstraintEntry};
22use crate::feature_pipeline::{Env, SceneMap};
23
24#[derive(Clone, serde::Serialize, serde::Deserialize)]
25struct Session {
26    state: AssemblyState,
27    scene: SceneMap,
28    expressions: String,
29    configurator: serde_json::Value,
30    /// Component id → solved `inputParams.transform` JSON. ACCUMULATES across
31    /// mutation solves (later solves overwrite per id); replaced wholesale by
32    /// the next history run.
33    pose_updates: BTreeMap<String, serde_json::Value>,
34    /// Component id → grounded write-back from a migrated legacy Fixed row
35    /// (`inputParams.isFixed`; an occurrence path `A:B` → `flexibleFixed[B]` on `A`).
36    fixed_updates: BTreeMap<String, bool>,
37    /// The last solve's report (`ok` + diagnostics, or `error`).
38    report: serde_json::Value,
39}
40
41thread_local! {
42    static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
43    /// Bumped by every install (a run's tail or an import): which session this
44    /// thread holds, so a holder can tell whether another document's run or
45    /// replay has replaced the one it installed.
46    static SESSION_SERIAL: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
47    /// Handles registered by the last [`assembly_session_import`]: owned by the
48    /// imported session alone, freed when any other session replaces it.
49    static IMPORTED: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
50}
51
52/// Replace this thread's session. What it replaces, and the solids a previous
53/// IMPORT owned (out of the registry already), are handed back for the caller
54/// to drop: freeing a few hundred solids costs milliseconds.
55fn replace_session(next: Session) -> RetiredSession {
56    let solids = IMPORTED
57        .with(|imported| std::mem::take(&mut *imported.borrow_mut()))
58        .into_iter()
59        .filter_map(crate::take_registered_solid)
60        .collect();
61    let session = SESSION.with(|session| session.borrow_mut().replace(next));
62    SESSION_SERIAL.with(|serial| serial.set(serial.get() + 1));
63    RetiredSession { _session: session, _solids: solids }
64}
65
66/// A replaced session and the solids only it owned, to drop where it costs
67/// nothing (another thread). Dropping it is all there is to do with it.
68pub struct RetiredSession {
69    _session: Option<Session>,
70    _solids: Vec<crate::BrepSolid>,
71}
72
73/// Which session this thread holds (see `SESSION_SERIAL`); 0 = none yet.
74pub fn assembly_session_serial() -> u64 {
75    SESSION_SERIAL.with(std::cell::Cell::get)
76}
77
78/// An owned, self-contained copy of a thread's assembly session: the session
79/// and a clone of every solid its scene names, keyed by the handle it had
80/// THERE. It shares nothing with the thread it came from, so that thread may
81/// free or reuse every handle afterwards ([`assembly_session_import`]).
82#[derive(serde::Serialize, serde::Deserialize)]
83pub struct SessionTransfer {
84    session: Session,
85    solids: Vec<(u32, crate::BrepSolid)>,
86}
87
88impl std::fmt::Debug for SessionTransfer {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.debug_struct("SessionTransfer").field("solids", &self.solids.len()).finish()
91    }
92}
93
94/// Copy this thread's session for another thread (`None` without one).
95pub fn assembly_session_export() -> Option<SessionTransfer> {
96    SESSION.with(|session| {
97        let session = session.borrow();
98        let session = session.as_ref()?;
99        let scene = &session.scene;
100        let mut handles: Vec<u32> = scene
101            .solids
102            .values()
103            .copied()
104            .chain(scene.faces.values().map(|face| face.handle))
105            .chain(scene.edges.values().map(|edge| edge.handle))
106            .chain(scene.weld_prepared.values().flatten().map(|link| link.prior))
107            .collect();
108        handles.sort_unstable();
109        handles.dedup();
110        let solids = handles
111            .into_iter()
112            .filter_map(|handle| {
113                crate::with_registered_solid_str(handle, |solid| Ok(solid.clone())).ok().map(|solid| (handle, solid))
114            })
115            .collect();
116        Some(SessionTransfer { session: session.clone(), solids })
117    })
118}
119
120/// Install a [`SessionTransfer`] as this thread's session: every solid is
121/// registered HERE under a fresh handle and the scene is re-pointed at it.
122/// Returns what it replaced (the previous session and the solids a previous
123/// import owned) for the caller to drop.
124pub fn assembly_session_import(transfer: SessionTransfer) -> RetiredSession {
125    let SessionTransfer { mut session, solids } = transfer;
126    let mut fresh = std::collections::HashMap::with_capacity(solids.len());
127    let mut owned = Vec::with_capacity(solids.len());
128    for (old, solid) in solids {
129        let handle = crate::register_solid_value(solid);
130        fresh.insert(old, handle);
131        owned.push(handle);
132    }
133    // A handle with no copy (its solid was gone there) must not alias a
134    // solid that happens to hold the same number here.
135    let remap = |handle: &mut u32| *handle = fresh.get(handle).copied().unwrap_or(u32::MAX);
136    let scene = &mut session.scene;
137    scene.solids.values_mut().for_each(remap);
138    scene.faces.values_mut().for_each(|face| remap(&mut face.handle));
139    scene.edges.values_mut().for_each(|edge| remap(&mut edge.handle));
140    scene.weld_prepared.values_mut().flatten().for_each(|link| remap(&mut link.prior));
141    let retired = replace_session(session);
142    IMPORTED.with(|imported| *imported.borrow_mut() = owned);
143    retired
144}
145
146/// Install the post-run session (the history tail). Pose/fixed updates start
147/// from THIS run's outcome — the previous session's pending updates are
148/// dropped (the run consumed the document they were meant for).
149pub(super) fn install_session(
150    state: AssemblyState,
151    scene: SceneMap,
152    expressions: String,
153    configurator: serde_json::Value,
154    outcome: LifecycleOutcome,
155) {
156    drop(replace_session(Session {
157        state,
158        scene,
159        expressions,
160        configurator,
161        pose_updates: outcome.pose_updates,
162        fixed_updates: outcome.fixed_updates,
163        report: outcome.report,
164    }));
165}
166
167/// Publish post-solve weld anchors and notify display consumers of in-place motion.
168pub(crate) fn publish_weld_scene(scene: &SceneMap, moved: &[(String, u32)]) {
169    SESSION.with(|slot| {
170        if let Some(session) = slot.borrow_mut().as_mut() {
171            session.scene = scene.clone();
172            let Some(report) = session.report.as_object_mut() else { return };
173            // A member a weld prepared in context was reported moved by the
174            // solve under the prepared body, which the weld's rebuild then
175            // freed (also when the rebuild failed and the member went back to
176            // its component's body): each entry names the body its name
177            // holds now, and a name no longer in the scene is not reported.
178            if let Some(entries) = report.get_mut("movedSolids").and_then(|entries| entries.as_array_mut()) {
179                entries.retain_mut(|entry| {
180                    let Some(name) = entry.get("name").and_then(|n| n.as_str()).map(str::to_string) else { return false };
181                    let Some(&handle) = scene.solids.get(&name) else { return false };
182                    entry["handle"] = serde_json::json!(handle);
183                    !moved.iter().any(|(moved, _)| moved == &name)
184                });
185            }
186            if !moved.is_empty() {
187                let entries = report.entry("movedSolids").or_insert_with(|| serde_json::json!([]));
188                if let Some(entries) = entries.as_array_mut() {
189                    entries.extend(moved.iter().map(|(name, handle)| serde_json::json!({"name": name, "handle": handle})));
190                }
191            }
192        }
193    });
194}
195
196/// The components of the last run whose members a weld prepared in context
197/// (`SceneMap::weld_prepared`): root component id -> the preparing welds. Read by
198/// the structured STEP export, which writes such an instance from its
199/// as-welded bodies instead of the shared part.
200pub(crate) fn context_prepared_components() -> BTreeMap<String, Vec<String>> {
201    SESSION.with(|slot| {
202        let mut prepared: BTreeMap<String, Vec<String>> = BTreeMap::new();
203        if let Some(session) = slot.borrow().as_ref() {
204            let scene = &session.scene;
205            for member in scene.weld_prepared.keys() {
206                let (Some(entry), Some(record)) = (scene.context_member(member), scene.owning_component(member)) else { continue };
207                // A flexible occurrence (`ACOMP1:ACOMP2`) is written with the
208                // root instance that places it.
209                let root = record.id.split(':').next().unwrap_or(&record.id).to_string();
210                let welds = prepared.entry(root).or_default();
211                if !welds.contains(&entry.weld) { welds.push(entry.weld.clone()); }
212            }
213        }
214        for welds in prepared.values_mut() { welds.sort(); }
215        prepared
216    })
217}
218
219
220fn with_session<T>(f: impl FnOnce(&mut Session) -> Result<T, String>) -> Result<T, String> {
221    SESSION.with(|session| {
222        let mut session = session.borrow_mut();
223        let session = session
224            .as_mut()
225            .ok_or_else(|| "no assembly session (run a history first)".to_string())?;
226        f(session)
227    })
228}
229
230/// Re-solve the session state against the session scene, merging the
231/// outcome's write-backs (the auto-solve every mutation triggers). The
232/// returned report carries `movedSolids` (built by the lifecycle) — the
233/// display lane re-tessellates exactly those in-place-moved resident solids.
234fn solve_session(session: &mut Session) -> serde_json::Value {
235    let env = Env::build(&session.expressions, &session.configurator)
236        .unwrap_or_else(Env::poisoned);
237    let outcome = lifecycle::run_constraints(&mut session.state, &mut session.scene, &env);
238    session.pose_updates.extend(outcome.pose_updates);
239    session.fixed_updates.extend(outcome.fixed_updates);
240    session.report = outcome.report.clone();
241    outcome.report
242}
243
244// ===========================================================================
245// Read surface
246// ===========================================================================
247
248/// The current `assembly` block (post-solve) as JSON — the panel's list source
249/// and the state the app folds back into its document.
250#[wasm_bindgen]
251pub fn assembly_state_json() -> String {
252    SESSION.with(|session| {
253        session
254            .borrow()
255            .as_ref()
256            .map(|session| serde_json::to_value(&session.state).unwrap_or_default())
257            .unwrap_or_else(|| serde_json::to_value(AssemblyState::default()).unwrap_or_default())
258            .to_string()
259    })
260}
261
262/// Per-constraint status rows: `[{id, type, enabled, open, status, message,
263/// satisfied, error}]`.
264#[wasm_bindgen]
265pub fn assembly_statuses_json() -> String {
266    SESSION.with(|session| {
267        let rows: Vec<serde_json::Value> = session
268            .borrow()
269            .as_ref()
270            .map(|session| {
271                session
272                    .state
273                    .constraints
274                    .iter()
275                    .map(|entry| {
276                        serde_json::json!({
277                            "id": entry.id(),
278                            "type": entry.constraint_type,
279                            "enabled": entry.enabled,
280                            "open": entry.open,
281                            "status": entry.status(),
282                            "message": entry
283                                .persistent("message")
284                                .and_then(|value| value.as_str())
285                                .unwrap_or(""),
286                            "satisfied": entry
287                                .persistent("satisfied")
288                                .and_then(|value| value.as_bool())
289                                .unwrap_or(false),
290                            "error": entry.persistent("error").cloned(),
291                            "conflictWith": entry.persistent("conflictWith").cloned().unwrap_or(serde_json::json!([])),
292                            "suppressSuggested": entry
293                                .persistent("suppressSuggested")
294                                .and_then(|value| value.as_bool())
295                                .unwrap_or(false),
296                        })
297                    })
298                    .collect()
299            })
300            .unwrap_or_default();
301        serde_json::Value::Array(rows).to_string()
302    })
303}
304
305/// The last solve's DOF/diagnostics summary (`{ok, dof, rank, redundant,
306/// status, strategy, iterations, maxResidual, ...}` or `{ok:false, error}`).
307#[wasm_bindgen]
308pub fn assembly_dof_json() -> String {
309    SESSION.with(|session| {
310        session
311            .borrow()
312            .as_ref()
313            .map(|session| with_nested_constraints(&session.report, &session.scene).to_string())
314            .unwrap_or_else(|| serde_json::json!({ "ok": true, "mates": 0 }).to_string())
315    })
316}
317
318/// `report` plus `nestedConstraints`: the rows of every sub-assembly's own
319/// constraints (namespaced, every level), which solved inside the sub-assembly
320/// and are reported, not re-solved, here. Read from the session scene's
321/// component records, so a mutation re-solve (which replaces `report`) keeps
322/// them. Absent when no component carries any.
323fn with_nested_constraints(report: &serde_json::Value, scene: &SceneMap) -> serde_json::Value {
324    let rows: Vec<&crate::feature_pipeline::component::NestedConstraint> = scene
325        .iter_components()
326        .flat_map(|record| &record.nested_constraints)
327        .collect();
328    let mut report = report.clone();
329    if let (false, Some(map)) = (rows.is_empty(), report.as_object_mut()) {
330        map.insert(
331            "nestedConstraints".into(),
332            serde_json::to_value(rows).unwrap_or_default(),
333        );
334    }
335    report
336}
337
338/// The pending generic feature write-backs: `{"poses": {componentId:
339/// transformParam}, "isFixed": {componentId: bool}}`. The transform param is
340/// `{translate, rotateEulerDeg (deg, intrinsic XYZ)}` — exactly the shape the
341/// ACOMP feature's `inputParams.transform` reader expects.
342#[wasm_bindgen]
343pub fn assembly_pose_updates_json() -> String {
344    SESSION.with(|session| {
345        session
346            .borrow()
347            .as_ref()
348            .map(|session| {
349                serde_json::json!({
350                    "poses": session.pose_updates,
351                    "isFixed": session.fixed_updates,
352                })
353                .to_string()
354            })
355            .unwrap_or_else(|| serde_json::json!({ "poses": {}, "isFixed": {} }).to_string())
356    })
357}
358
359/// Fold the session's solved state into a history DOCUMENT: replaces the
360/// top-level `assembly` block and writes each pending pose / grounded flag
361/// into the owning feature's `inputParams` (matched by `inputParams.id` —
362/// generic JSON, no dependency on the ACOMP feature shape). The app calls this
363/// on its document before persisting or re-running (the pose-authority
364/// write-back).
365#[wasm_bindgen]
366pub fn assembly_apply_document_json(document_json: &str) -> Result<String, JsValue> {
367    assembly_apply_document_impl(document_json).map_err(|error| JsValue::from_str(&error))
368}
369
370pub fn assembly_apply_document_impl(document_json: &str) -> Result<String, String> {
371    let mut document: serde_json::Value = serde_json::from_str(document_json)
372        .map_err(|error| format!("assembly document fold: bad document: {error}"))?;
373    with_session(|session| {
374        let object = document
375            .as_object_mut()
376            .ok_or_else(|| "assembly document fold: document must be an object".to_string())?;
377        object.insert(
378            "assembly".into(),
379            serde_json::to_value(&session.state)
380                .map_err(|error| format!("assembly state serialize: {error}"))?,
381        );
382        if let Some(features) = object.get_mut("features").and_then(|v| v.as_array_mut()) {
383            for feature in features {
384                let Some(params) = feature
385                    .get_mut("inputParams")
386                    .and_then(|value| value.as_object_mut())
387                else {
388                    continue;
389                };
390                let Some(id) = params.get("id").and_then(|value| value.as_str()) else {
391                    continue;
392                };
393                let id = id.to_string();
394                if let Some(pose) = session.pose_updates.get(&id) {
395                    // Numeric solver write-back must not erase authored motion
396                    // expressions. The evaluated component record owns that pose.
397                    fn has_expression(value: &serde_json::Value) -> bool {
398                        match value {
399                            serde_json::Value::String(_) => true,
400                            serde_json::Value::Array(a) => a.iter().any(has_expression),
401                            serde_json::Value::Object(o) => o.values().any(has_expression),
402                            _ => false,
403                        }
404                    }
405                    if !params.get("transform").is_some_and(has_expression) {
406                        params.insert("transform".into(), pose.clone());
407                    }
408                }
409                // A flexible instance's occurrence poses (`ACOMP1:ACOMP2`),
410                // part-local, persist on the instance — never in the child
411                // document.
412                let prefix = format!("{id}:");
413                for (key, pose) in session.pose_updates.range(prefix.clone()..) {
414                    let Some(path) = key.strip_prefix(&prefix) else { break };
415                    let poses = params
416                        .entry("flexiblePoses")
417                        .or_insert_with(|| serde_json::Value::Object(Default::default()));
418                    if let Some(poses) = poses.as_object_mut() {
419                        poses.insert(path.to_string(), pose.clone());
420                    }
421                }
422                if let Some(&fixed) = session.fixed_updates.get(&id) {
423                    params.insert("isFixed".into(), serde_json::Value::Bool(fixed));
424                }
425                // A migrated Fixed row on a flexible instance's occurrence
426                // (`ACOMP1:ACOMP2`) is that instance's `flexibleFixed[ACOMP2]`.
427                for (key, &fixed) in session.fixed_updates.range(prefix.clone()..) {
428                    let Some(path) = key.strip_prefix(&prefix) else { break };
429                    let overrides = params
430                        .entry("flexibleFixed")
431                        .or_insert_with(|| serde_json::Value::Object(Default::default()));
432                    if !overrides.is_object() {
433                        *overrides = serde_json::Value::Object(Default::default());
434                    }
435                    if let Some(overrides) = overrides.as_object_mut() {
436                        overrides.insert(path.to_string(), serde_json::Value::Bool(fixed));
437                    }
438                }
439            }
440        }
441        Ok(())
442    })?;
443    Ok(document.to_string())
444}
445
446/// Overlay geometry for the viewport graphics lane: per enabled constraint,
447/// the resolved WORLD anchor points/directions/geometry classes (post-solve),
448/// the status, the evaluated value, and (multi-element types) the element
449/// role groups — `[{id, type, status, message, anchors, directions, geoms,
450/// value, unit, target, groups}]`. Constraints whose selections do not
451/// resolve emit status/message only (no anchors).
452#[wasm_bindgen]
453pub fn assembly_overlay_json() -> String {
454    SESSION.with(|session| {
455        let session = session.borrow();
456        let Some(session) = session.as_ref() else {
457            return serde_json::Value::Array(Vec::new()).to_string();
458        };
459        let env = Env::build(&session.expressions, &session.configurator)
460            .unwrap_or_else(Env::poisoned);
461        let rows: Vec<serde_json::Value> = session
462            .state
463            .constraints
464            .iter()
465            .filter(|entry| entry.enabled)
466            .map(|entry| overlay_row(entry, &session.scene, &env))
467            .collect();
468        serde_json::Value::Array(rows).to_string()
469    })
470}
471
472fn overlay_row(entry: &ConstraintEntry, scene: &SceneMap, env: &Env) -> serde_json::Value {
473    let mut row = serde_json::json!({
474        "id": entry.id(),
475        "type": entry.constraint_type,
476        "status": entry.status(),
477        "message": entry
478            .persistent("message")
479            .and_then(|value| value.as_str())
480            .unwrap_or(""),
481    });
482    let elements = entry.elements();
483    let resolved: Vec<_> = elements
484        .iter()
485        .filter_map(|name| mapping::resolve_element(scene, name).ok())
486        .collect();
487    if resolved.len() != elements.len() || resolved.is_empty() {
488        return row;
489    }
490    let object = row.as_object_mut().expect("row is an object");
491    object.insert(
492        "anchors".into(),
493        serde_json::Value::Array(
494            resolved
495                .iter()
496                .map(|element| {
497                    let p = element.world.representative_point();
498                    serde_json::json!([p.x, p.y, p.z])
499                })
500                .collect(),
501        ),
502    );
503    object.insert(
504        "directions".into(),
505        serde_json::Value::Array(
506            resolved
507                .iter()
508                .map(|element| match mapping::direction_of(&element.world) {
509                    Some(direction) => serde_json::json!([direction.x, direction.y, direction.z]),
510                    None => serde_json::Value::Null,
511                })
512                .collect(),
513        ),
514    );
515    // Per-element geometry class, aligned index-wise with anchors/directions —
516    // the render-side distance-arrow builder needs to identify the BASE PLANE
517    // (the perpendicular-foot construction); a direction alone is ambiguous
518    // (lines and circles carry one too).
519    object.insert(
520        "geoms".into(),
521        serde_json::Value::Array(
522            resolved
523                .iter()
524                .map(|element| serde_json::json!(geometry_tag(&element.world)))
525                .collect(),
526        ),
527    );
528    // Measured value/target — and the element ROLE groups a multi-element type
529    // inferred (center's `[width pair, tab]`) — via the mapper on a THROWAWAY
530    // clone (the mapper maintains the orientation-preference cache; an
531    // overlay read must not mutate persisted state).
532    let mut scratch = entry.clone();
533    if let Ok(mapped) = mapping::map_constraint(&mut scratch, &resolved, env) {
534        if let Some((value, unit)) = mapped.measured {
535            object.insert("value".into(), serde_json::json!(value));
536            object.insert("unit".into(), serde_json::json!(unit));
537        }
538        if let Some(axis) = mapped.angle_axis {
539            object.insert("angleAxis".into(), serde_json::json!([axis.x, axis.y, axis.z]));
540        }
541        if let Some(target) = mapped.target {
542            object.insert("target".into(), serde_json::json!(target));
543        }
544        if !mapped.groups.is_empty() {
545            object.insert("groups".into(), serde_json::json!(mapped.groups));
546        }
547    }
548    row
549}
550
551/// One resolved element as the replace-component remap reads it: the geometry
552/// class plus the frame in the owning component's LOCAL space (a component
553/// swap keeps the ACOMP pose, so local frames of the old and the new part are
554/// directly comparable).
555fn local_element_json(element: &mapping::ResolvedElement) -> serde_json::Value {
556    let point = mapping::local_point(element);
557    let direction = mapping::direction_of(&element.local)
558        .map(|d| serde_json::json!([d.x, d.y, d.z]))
559        .unwrap_or(serde_json::Value::Null);
560    let radius = match element.local {
561        crate::SelectionGeometry::Axis { radius, .. } => radius,
562        crate::SelectionGeometry::Sphere { radius, .. }
563        | crate::SelectionGeometry::Circle { radius, .. } => Some(radius),
564        _ => None,
565    };
566    serde_json::json!({
567        "ref": element.name,
568        "component": element.component,
569        "geom": geometry_tag(&element.local),
570        "point": point,
571        "direction": direction,
572        "radius": radius,
573    })
574}
575
576/// Resolve selection refs against the live session WITHOUT touching any
577/// constraint: `refs_json` is `["ACOMP2:Part_PZ", …]`; the reply is one row
578/// per ref, `{ref, ok: true, component, geom, point, direction, radius}` in
579/// the owning component's local frame, or `{ref, ok: false, status, error}`.
580/// Read-only — the replace-component lane snapshots a mate's references
581/// before the swap with it.
582#[wasm_bindgen]
583pub fn assembly_resolve_refs_json(refs_json: &str) -> String {
584    let refs: Vec<String> = match serde_json::from_str(refs_json) {
585        Ok(refs) => refs,
586        Err(error) => return refusal(&format!("refs: {error}")),
587    };
588    SESSION.with(|session| {
589        let session = session.borrow();
590        let Some(session) = session.as_ref() else {
591            return refusal("no assembly session (run a history first)");
592        };
593        let rows: Vec<serde_json::Value> = refs
594            .iter()
595            .map(|name| match mapping::resolve_element(&session.scene, name) {
596                Ok(element) => {
597                    let mut row = local_element_json(&element);
598                    row["ok"] = serde_json::Value::Bool(true);
599                    row
600                }
601                Err(failure) => serde_json::json!({
602                    "ref": name,
603                    "ok": false,
604                    "status": failure.status,
605                    "error": failure.message,
606                }),
607            })
608            .collect();
609        serde_json::Value::Array(rows).to_string()
610    })
611}
612
613/// Every NAMED face and edge of one component, resolved like
614/// [`assembly_resolve_refs_json`] (component-local frames). Entities without
615/// an analytic frame are skipped: a mate could never have referenced them.
616/// An unknown component is an empty list.
617#[wasm_bindgen]
618pub fn assembly_component_entities_json(component_id: &str) -> String {
619    SESSION.with(|session| {
620        let session = session.borrow();
621        let Some(session) = session.as_ref() else {
622            return serde_json::Value::Array(Vec::new()).to_string();
623        };
624        let mut names: Vec<(&'static str, String)> = Vec::new();
625        for (_, handle) in session.scene.component_solids(component_id) {
626            let _ = crate::with_registered_solid_str(handle, |solid| {
627                for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
628                    if let Some(name) = &face.name {
629                        names.push(("face", name.clone()));
630                    }
631                }
632                for edge in &solid.edges {
633                    if let Some(name) = &edge.name {
634                        names.push(("edge", name.clone()));
635                    }
636                }
637                Ok(())
638            });
639        }
640        let rows: Vec<serde_json::Value> = names
641            .into_iter()
642            .filter_map(|(kind, name)| {
643                let element = mapping::resolve_element(&session.scene, &name).ok()?;
644                let mut row = local_element_json(&element);
645                row["kind"] = serde_json::Value::String(kind.into());
646                Some(row)
647            })
648            .collect();
649        serde_json::Value::Array(rows).to_string()
650    })
651}
652
653/// The coarse geometry class of a resolved selection (the overlay row's
654/// `geoms` vocabulary — lowercase `SelectionGeometry` variant names).
655fn geometry_tag(geometry: &crate::SelectionGeometry) -> &'static str {
656    match geometry {
657        crate::SelectionGeometry::Plane { .. } => "plane",
658        crate::SelectionGeometry::Line { .. } => "line",
659        crate::SelectionGeometry::Axis { .. } => "axis",
660        crate::SelectionGeometry::Circle { .. } => "circle",
661        crate::SelectionGeometry::Sphere { .. } => "sphere",
662        crate::SelectionGeometry::Point { .. } => "point",
663    }
664}
665
666// ===========================================================================
667// Mutation surface
668// ===========================================================================
669
670/// Add a constraint of `constraint_type` with the given `inputParams` JSON
671/// (elements etc.; `id` is minted from the type's short name + the persistent
672/// counter when absent). Auto-solves; returns `{id, report}`.
673#[wasm_bindgen]
674pub fn assembly_add_constraint_json(
675    constraint_type: &str,
676    params_json: &str,
677) -> Result<String, JsValue> {
678    assembly_add_constraint_impl(constraint_type, params_json).map_err(|error| JsValue::from_str(&error))
679}
680
681pub fn assembly_add_constraint_impl(constraint_type: &str, params_json: &str) -> Result<String, String> {
682    if constraint_type == "fixed" {
683        return Err(super::FIXED_IS_NOT_A_CONSTRAINT.to_string());
684    }
685    let def = constraints::constraint_type(constraint_type)
686        .ok_or_else(|| format!("Unknown constraint type: {constraint_type}"))?;
687    let mut params: serde_json::Value = serde_json::from_str(params_json)
688        .map_err(|error| format!("constraint params: {error}"))?;
689    if !params.is_object() {
690        return Err("constraint params must be a JSON object".to_string());
691    }
692    with_session(|session| {
693        let id = match params.get("id").and_then(|value| value.as_str()) {
694            Some(id) if !id.is_empty() => id.to_string(),
695            _ => {
696                session.state.id_counter += 1;
697                let id = format!("{}{}", def.short_name, session.state.id_counter);
698                params
699                    .as_object_mut()
700                    .expect("checked object above")
701                    .insert("id".into(), serde_json::Value::String(id.clone()));
702                id
703            }
704        };
705        session.state.constraints.push(ConstraintEntry {
706            constraint_type: constraint_type.to_string(),
707            input_params: params.clone(),
708            persistent_data: serde_json::Value::Object(serde_json::Map::new()),
709            enabled: true,
710            open: true,
711        });
712        let report = solve_session(session);
713        Ok(serde_json::json!({ "id": id, "report": report }).to_string())
714    })
715}
716
717/// Replace a constraint's `inputParams` (the dialog commit). Auto-solves;
718/// returns the solve report.
719#[wasm_bindgen]
720pub fn assembly_update_constraint_json(id: &str, params_json: &str) -> Result<String, JsValue> {
721    assembly_update_constraint_impl(id, params_json).map_err(|error| JsValue::from_str(&error))
722}
723
724pub fn assembly_update_constraint_impl(id: &str, params_json: &str) -> Result<String, String> {
725    let mut params: serde_json::Value = serde_json::from_str(params_json)
726        .map_err(|error| format!("constraint params: {error}"))?;
727    if !params.is_object() {
728        return Err("constraint params must be a JSON object".to_string());
729    }
730    if params.get("id").and_then(|value| value.as_str()).is_none() {
731        params
732            .as_object_mut()
733            .expect("checked object above")
734            .insert("id".into(), serde_json::Value::String(id.to_string()));
735    }
736    with_session(|session| {
737        let entry = find_entry(session, id)?;
738        entry.input_params = params.clone();
739        Ok(solve_session(session).to_string())
740    })
741}
742
743/// Delete a constraint. Auto-solves; returns the solve report.
744#[wasm_bindgen]
745pub fn assembly_remove_constraint_json(id: &str) -> Result<String, JsValue> {
746    assembly_remove_constraint_impl(id).map_err(|error| JsValue::from_str(&error))
747}
748
749pub fn assembly_remove_constraint_impl(id: &str) -> Result<String, String> {
750    with_session(|session| {
751        let index = find_index(session, id)?;
752        session.state.constraints.remove(index);
753        Ok(solve_session(session).to_string())
754    })
755}
756
757/// Enable/disable a constraint. Auto-solves; returns the solve report.
758#[wasm_bindgen]
759pub fn assembly_set_constraint_enabled_json(id: &str, enabled: bool) -> Result<String, JsValue> {
760    assembly_set_constraint_enabled_impl(id, enabled).map_err(|error| JsValue::from_str(&error))
761}
762
763pub fn assembly_set_constraint_enabled_impl(id: &str, enabled: bool) -> Result<String, String> {
764    with_session(|session| {
765        find_entry(session, id)?.enabled = enabled;
766        Ok(solve_session(session).to_string())
767    })
768}
769
770/// Persist a constraint row's dialog expansion state (view state — no solve).
771#[wasm_bindgen]
772pub fn assembly_set_constraint_open_json(id: &str, open: bool) -> Result<(), JsValue> {
773    assembly_set_constraint_open_impl(id, open).map_err(|error| JsValue::from_str(&error))
774}
775
776pub fn assembly_set_constraint_open_impl(id: &str, open: bool) -> Result<(), String> {
777    with_session(|session| {
778        find_entry(session, id)?.open = open;
779        Ok(())
780    })
781}
782
783/// Reorder a constraint to `index` (clamped). Auto-solves; returns the report.
784#[wasm_bindgen]
785pub fn assembly_move_constraint_json(id: &str, index: usize) -> Result<String, JsValue> {
786    assembly_move_constraint_impl(id, index).map_err(|error| JsValue::from_str(&error))
787}
788
789pub fn assembly_move_constraint_impl(id: &str, index: usize) -> Result<String, String> {
790    with_session(|session| {
791        let from = find_index(session, id)?;
792        let entry = session.state.constraints.remove(from);
793        let to = index.min(session.state.constraints.len());
794        session.state.constraints.insert(to, entry);
795        Ok(solve_session(session).to_string())
796    })
797}
798
799// ===========================================================================
800// Automatic inference (super::infer)
801// ===========================================================================
802
803/// The inferable constraint types, joined to the catalogue: `[{type, label,
804/// icon, longName, detects, defaultOn}]`. Session-free — the dialog can list
805/// what the button offers before any document is open.
806#[wasm_bindgen]
807pub fn assembly_inferable_types_json() -> String {
808    super::infer::inferable_types_json().to_string()
809}
810
811/// SCAN the live scene for constraints its component placement implies, without
812/// creating anything. `options_json` is `super::infer::InferOptions` (`{}` for
813/// the defaults). Never `Err`: a missing session or a bad options object comes
814/// back as `{ok: false, error}` — a `JsValue` error aborts a native build.
815#[wasm_bindgen]
816pub fn assembly_infer_constraints_json(options_json: &str) -> String {
817    match infer_scan(options_json) {
818        Ok(report) => report.to_string(),
819        Err(error) => refusal(&error),
820    }
821}
822
823/// Scan and CREATE: every accepted candidate becomes a constraint, then ONE
824/// solve runs for the whole batch (each inferred constraint is already
825/// satisfied at the pose it was read from, so a healthy assembly does not
826/// move). Returns `{ok, created: [id…], report, solve}`.
827#[wasm_bindgen]
828pub fn assembly_apply_inferred_constraints_json(options_json: &str) -> String {
829    match infer_apply(options_json) {
830        Ok(report) => report.to_string(),
831        Err(error) => refusal(&error),
832    }
833}
834
835fn refusal(error: &str) -> String {
836    serde_json::json!({ "ok": false, "error": error }).to_string()
837}
838
839fn infer_scan(options_json: &str) -> Result<serde_json::Value, String> {
840    let options = super::infer::InferOptions::parse(options_json)?;
841    with_session(|session| Ok(super::infer::scan(&session.state, &session.scene, &options).report()))
842}
843
844fn infer_apply(options_json: &str) -> Result<serde_json::Value, String> {
845    let options = super::infer::InferOptions::parse(options_json)?;
846    with_session(|session| {
847        let scan = super::infer::scan(&session.state, &session.scene, &options);
848        let report = scan.report();
849        let created = super::infer::apply(&mut session.state, &scan.candidates);
850        let solve = if created.is_empty() {
851            serde_json::Value::Null
852        } else {
853            solve_session(session)
854        };
855        Ok(serde_json::json!({
856            "ok": true,
857            "created": created,
858            "report": report,
859            "solve": solve,
860        }))
861    })
862}
863
864/// Manual solve (the panel's Solve button). Returns the solve report.
865#[wasm_bindgen]
866pub fn assembly_run_solve_json() -> Result<String, JsValue> {
867    assembly_run_solve_impl().map_err(|error| JsValue::from_str(&error))
868}
869
870pub fn assembly_run_solve_impl() -> Result<String, String> {
871    with_session(|session| Ok(solve_session(session).to_string()))
872}
873
874/// The live-drag dry run against the session (`lifecycle::drag_solve`).
875/// Request `{poses: {componentId: {translate, rotateEulerDeg}}, unfix?: [id],
876/// reference?: {componentId: pose}, explain?: bool}` — the dragged components at their
877/// dragged poses, and the last good live poses to re-base mechanical mates at. Reply `{ok: true, poses:
878/// {componentId: {translate, rotateEulerDeg}}, blocking: [constraintId]}` for every movable body
879/// (`blocking`: with `explain`, the constraints that would not let the dragged
880/// components reach the drag pose; empty otherwise);
881/// `Err` when the mates cannot hold at this drag. Nothing in the session (the
882/// state, the scene, the pending write-backs, the report) changes.
883#[wasm_bindgen]
884pub fn assembly_drag_solve_json(request_json: &str) -> Result<String, JsValue> {
885    assembly_drag_solve_impl(request_json).map_err(|error| JsValue::from_str(&error))
886}
887
888pub fn assembly_drag_solve_impl(request_json: &str) -> Result<String, String> {
889    let request: serde_json::Value =
890        serde_json::from_str(request_json).map_err(|error| format!("drag solve request: {error}"))?;
891    let mut drag = BTreeMap::new();
892    for (id, pose) in request
893        .get("poses")
894        .and_then(|poses| poses.as_object())
895        .ok_or("drag solve request: missing poses")?
896    {
897        drag.insert(id.clone(), mapping::pose_params_to_transform(pose)?);
898    }
899    let mut reference = BTreeMap::new();
900    for (id, pose) in request.get("reference").and_then(|poses| poses.as_object()).into_iter().flatten() {
901        reference.insert(id.clone(), mapping::pose_params_to_transform(pose)?);
902    }
903    let unfix: Vec<String> = request
904        .get("unfix")
905        .and_then(|unfix| unfix.as_array())
906        .map(|ids| ids.iter().filter_map(|id| id.as_str().map(str::to_string)).collect())
907        .unwrap_or_default();
908    let explain = request.get("explain").and_then(|explain| explain.as_bool()).unwrap_or(false);
909    with_session(|session| {
910        let env = Env::build(&session.expressions, &session.configurator)
911            .unwrap_or_else(Env::poisoned);
912        let (poses, blocking) =
913            lifecycle::drag_solve(&session.state, &mut session.scene, &env, &drag, &unfix, &reference, explain)?;
914        let poses: serde_json::Map<String, serde_json::Value> = poses
915            .iter()
916            .map(|(id, transform)| (id.clone(), mapping::transform_to_pose_params(transform)))
917            .collect();
918        Ok(serde_json::json!({ "ok": true, "poses": poses, "blocking": blocking }).to_string())
919    })
920}
921
922/// One frame of a motion study against the session (`lifecycle::frame_solve`).
923/// Request `{overrides: {constraintId: {value?: number, enabled?: bool}},
924/// reference?: {componentId: {translate, rotateEulerDeg}}}`: `value` drives a
925/// distance or angle constraint to it (model units or degrees; an angle may
926/// run past 360), `enabled` switches a constraint off or on for the frame, and
927/// `reference` is the previous frame's poses (the warm start). Reply `{ok:
928/// true, poses: {componentId: {translate, rotateEulerDeg}}}` for every movable
929/// body; `Err` when the mates cannot hold the frame or an override names a
930/// constraint the session lacks or drives one that is not a distance or angle.
931/// Nothing in the session changes.
932#[wasm_bindgen]
933pub fn assembly_frame_solve_json(request_json: &str) -> Result<String, JsValue> {
934    assembly_frame_solve_impl(request_json).map_err(|error| JsValue::from_str(&error))
935}
936
937pub fn assembly_frame_solve_impl(request_json: &str) -> Result<String, String> {
938    let request: serde_json::Value =
939        serde_json::from_str(request_json).map_err(|error| format!("frame solve request: {error}"))?;
940    let mut reference = BTreeMap::new();
941    for (id, pose) in request.get("reference").and_then(|poses| poses.as_object()).into_iter().flatten() {
942        reference.insert(id.clone(), mapping::pose_params_to_transform(pose)?);
943    }
944    with_session(|session| {
945        let mut overrides = BTreeMap::new();
946        for (id, change) in request.get("overrides").and_then(|o| o.as_object()).into_iter().flatten() {
947            let mut entry = lifecycle::FrameOverride::default();
948            if let Some(value) = change.get("value").filter(|v| !v.is_null()) {
949                let value = value.as_f64().ok_or_else(|| format!("frame solve: '{id}' value is not a number"))?;
950                let kind = session
951                    .state
952                    .constraints
953                    .iter()
954                    .find(|c| c.id() == id)
955                    .map(|c| c.constraint_type.as_str())
956                    .ok_or_else(|| format!("frame solve: unknown constraint '{id}'"))?;
957                let param = match kind {
958                    "distance" => "distance",
959                    "angle" => "angle",
960                    other => return Err(format!("frame solve: '{id}' is a {other} constraint; a motor drives a distance or angle")),
961                };
962                entry.value = Some((param.to_string(), value));
963            }
964            entry.enabled = change.get("enabled").and_then(|e| e.as_bool());
965            overrides.insert(id.clone(), entry);
966        }
967        let env = Env::build(&session.expressions, &session.configurator).unwrap_or_else(Env::poisoned);
968        let poses = lifecycle::frame_solve(&session.state, &mut session.scene, &env, &overrides, &reference)?;
969        let poses: serde_json::Map<String, serde_json::Value> = poses
970            .iter()
971            .map(|(id, transform)| (id.clone(), mapping::transform_to_pose_params(transform)))
972            .collect();
973        Ok(serde_json::json!({ "ok": true, "poses": poses }).to_string())
974    })
975}
976
977/// Refresh the mechanical mates' stored references at the released poses of
978/// a live drag (`lifecycle::rebase_mechanical`). Request `{poses:
979/// {componentId: {translate, rotateEulerDeg}}}`. Reply: the updated
980/// `assembly` block JSON when a mechanical mate was refreshed, else `null`.
981/// The caller writes the block in the SAME undo step as the poses, so the
982/// next run maps a multi-turn drag from where it ended.
983pub fn assembly_rebase_mechanical_impl(request_json: &str) -> Result<String, String> {
984    let request: serde_json::Value =
985        serde_json::from_str(request_json).map_err(|error| format!("rebase request: {error}"))?;
986    let mut poses = BTreeMap::new();
987    for (id, pose) in request.get("poses").and_then(|poses| poses.as_object()).into_iter().flatten() {
988        poses.insert(id.clone(), mapping::pose_params_to_transform(pose)?);
989    }
990    with_session(|session| {
991        let env = Env::build(&session.expressions, &session.configurator).unwrap_or_else(Env::poisoned);
992        let changed = lifecycle::rebase_mechanical(&mut session.state, &mut session.scene, &env, &poses);
993        Ok(if changed {
994            serde_json::to_string(&session.state).map_err(|error| error.to_string())?
995        } else {
996            "null".to_string()
997        })
998    })
999}
1000
1001/// What **Flip** would do to constraint `id`, read from the live session:
1002/// `{ok: true, patch, seed, elements: [{component, fixed, anchor, direction,
1003/// geom}], value, angleAxis}` (world frame, pick order), or `{ok: false,
1004/// reason}` for a type with no other solution. Read-only: the caller writes the
1005/// patch and the seeded pose as one edit (`constraints::flip_rule`).
1006#[wasm_bindgen]
1007pub fn assembly_flip_plan_json(id: &str) -> String {
1008    SESSION.with(|session| {
1009        let session = session.borrow();
1010        let Some(session) = session.as_ref() else {
1011            return refusal("no assembly session (run a history first)");
1012        };
1013        let Some(entry) = session.state.constraints.iter().find(|entry| entry.id() == id) else {
1014            return refusal(&format!("unknown constraint '{id}'"));
1015        };
1016        let env = Env::build(&session.expressions, &session.configurator).unwrap_or_else(Env::poisoned);
1017        let row = overlay_row(entry, &session.scene, &env);
1018        let geoms: Vec<&str> = row["geoms"].as_array().into_iter().flatten().filter_map(|g| g.as_str()).collect();
1019        let (patch, seed) = match constraints::flip_rule(&entry.constraint_type, &entry.input_params, &geoms) {
1020            Ok(rule) => rule,
1021            Err(reason) => return serde_json::json!({ "ok": false, "reason": reason }).to_string(),
1022        };
1023        let elements: Vec<serde_json::Value> = entry
1024            .elements()
1025            .iter()
1026            .enumerate()
1027            .map(|(index, name)| {
1028                let component = mapping::resolve_element(&session.scene, name).map(|element| element.component).unwrap_or_default();
1029                serde_json::json!({
1030                    "component": component,
1031                    "fixed": session.scene.component_fixed(&component).unwrap_or(false),
1032                    "anchor": row["anchors"].get(index).cloned().unwrap_or(serde_json::Value::Null),
1033                    "direction": row["directions"].get(index).cloned().unwrap_or(serde_json::Value::Null),
1034                    "geom": row["geoms"].get(index).cloned().unwrap_or(serde_json::Value::Null),
1035                })
1036            })
1037            .collect();
1038        serde_json::json!({
1039            "ok": true,
1040            "patch": patch,
1041            "seed": seed,
1042            "elements": elements,
1043            "value": row["value"],
1044            "angleAxis": row["angleAxis"],
1045        })
1046        .to_string()
1047    })
1048}
1049
1050fn find_index(session: &Session, id: &str) -> Result<usize, String> {
1051    session
1052        .state
1053        .constraints
1054        .iter()
1055        .position(|entry| entry.id() == id)
1056        .ok_or_else(|| format!("unknown constraint '{id}'"))
1057}
1058
1059fn find_entry<'a>(session: &'a mut Session, id: &str) -> Result<&'a mut ConstraintEntry, String> {
1060    let index = find_index(session, id)?;
1061    Ok(&mut session.state.constraints[index])
1062}