brepkit-wasm 3.2.16

WebAssembly bindings for brepkit — browser-native B-Rep solid modeling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
//! Boolean operation bindings.

#![allow(clippy::missing_errors_doc)]

use wasm_bindgen::prelude::*;

use brepkit_operations::boolean::{
    BooleanOp, BooleanOptions, boolean, boolean_with_options, mesh_fallback_count,
};
use brepkit_operations::compound_ops;

use crate::handles::solid_id_to_u32;
use crate::helpers::{build_triangle_mesh, panic_message, parse_boolean_op, triangle_mesh_to_js};
use crate::kernel::BrepKernel;
use crate::shapes::JsMesh;

/// Serialise a slice of `CoincidentFacePair` values to a JSON array.
///
/// Shared by both the direct WASM binding (`detectCoincidentFaces`)
/// and the batch dispatcher (`executeBatch` "detectCoincidentFaces"
/// arm) so the JSON shape is guaranteed identical across the two
/// paths — a field-name typo or boolean formatting drift in only one
/// copy would otherwise be silently shipped to JS callers.
///
/// Visibility note: `pub(crate)` triggers `clippy::redundant_pub_crate`
/// because `bindings` is a private module — the lint folds it to `pub`
/// in this scope. We keep `pub(crate)` to make the cross-module-but-
/// crate-internal sharing explicit.
#[allow(clippy::redundant_pub_crate)]
pub(crate) fn coincident_face_pairs_to_json(
    pairs: &[brepkit_algo::diagnostic::CoincidentFacePair],
) -> serde_json::Value {
    let arr: Vec<serde_json::Value> = pairs
        .iter()
        .map(|p| {
            serde_json::json!({
                "faceA": crate::handles::face_id_to_u32(p.face_a),
                "faceB": crate::handles::face_id_to_u32(p.face_b),
                "sameOrientation": p.same_orientation,
                "aabbOverlap": p.aabb_overlap,
            })
        })
        .collect();
    serde_json::Value::Array(arr)
}

#[wasm_bindgen]
impl BrepKernel {
    // ── Boolean operations ──────────────────────────────────────────

    /// Fuse (union) two solids into one.
    ///
    /// Returns a new solid handle (`u32`).
    ///
    /// # Errors
    ///
    /// Returns an error if either solid handle is invalid or the operation
    /// produces an empty or non-manifold result.
    #[wasm_bindgen(js_name = "fuse")]
    pub fn fuse(&mut self, a: u32, b: u32) -> Result<u32, JsError> {
        let a_id = self.resolve_solid(a)?;
        let b_id = self.resolve_solid(b)?;
        let result = boolean(self.topo_mut(), BooleanOp::Fuse, a_id, b_id)?;
        Ok(solid_id_to_u32(result))
    }

    /// Cut (subtract) solid `b` from solid `a`.
    ///
    /// Returns a new solid handle (`u32`).
    ///
    /// # Errors
    ///
    /// Returns an error if either solid handle is invalid or the operation
    /// produces an empty or non-manifold result.
    #[wasm_bindgen(js_name = "cut")]
    pub fn cut(&mut self, a: u32, b: u32) -> Result<u32, JsError> {
        let a_id = self.resolve_solid(a)?;
        let b_id = self.resolve_solid(b)?;
        let result = boolean(self.topo_mut(), BooleanOp::Cut, a_id, b_id)?;
        Ok(solid_id_to_u32(result))
    }

    /// Fuse (union) two solids with post-processing options.
    ///
    /// `simplify` merges co-surface face fragments after the boolean
    /// (the `BooleanOptions.simplify` request from brepjs).
    ///
    /// # Errors
    ///
    /// Returns an error if either solid handle is invalid or the operation
    /// produces an empty or non-manifold result.
    #[wasm_bindgen(js_name = "fuseWithOptions")]
    pub fn fuse_with_options(&mut self, a: u32, b: u32, simplify: bool) -> Result<u32, JsError> {
        self.boolean_with_options_impl(BooleanOp::Fuse, a, b, simplify)
    }

    /// Cut (subtract) solid `b` from solid `a` with post-processing options.
    ///
    /// # Errors
    ///
    /// Returns an error if either solid handle is invalid or the operation
    /// produces an empty or non-manifold result.
    #[wasm_bindgen(js_name = "cutWithOptions")]
    pub fn cut_with_options(&mut self, a: u32, b: u32, simplify: bool) -> Result<u32, JsError> {
        self.boolean_with_options_impl(BooleanOp::Cut, a, b, simplify)
    }

    /// Intersect two solids with post-processing options.
    ///
    /// # Errors
    ///
    /// Returns an error if either solid handle is invalid or the operation
    /// produces an empty or non-manifold result.
    #[wasm_bindgen(js_name = "intersectWithOptions")]
    pub fn intersect_with_options(
        &mut self,
        a: u32,
        b: u32,
        simplify: bool,
    ) -> Result<u32, JsError> {
        self.boolean_with_options_impl(BooleanOp::Intersect, a, b, simplify)
    }

    /// Number of boolean operations that have used the mesh (co-refinement)
    /// fallback since module load.
    ///
    /// The counter is process-wide: it is shared across all `BrepKernel`
    /// instances in the same wasm module and never resets. Snapshot it
    /// before an operation chain and compare after — a relative check, so
    /// the shared scope does not matter to single-threaded callers. If it
    /// grew, the chain contains at least one approximate result (analytic
    /// surface types lost, watertightness not guaranteed), and an export
    /// pipeline can refuse the output.
    #[wasm_bindgen(js_name = "meshFallbackCount")]
    #[must_use]
    // &self keeps this an instance method on the JS kernel object.
    #[allow(clippy::cast_precision_loss, clippy::unused_self)]
    pub fn mesh_fallback_count(&self) -> f64 {
        mesh_fallback_count() as f64
    }

    /// Detect surface-level coincident face pairs between two solids
    /// without performing a boolean operation.
    ///
    /// Useful for warning users about same-domain configurations
    /// (face stacks, coaxial cylinders, concentric spheres) before a
    /// boolean. Returns a JSON array string of objects:
    /// `[{"faceA": <u32>, "faceB": <u32>, "sameOrientation": <bool>, "aabbOverlap": <bool>}, ...]`.
    ///
    /// `sameOrientation` is `true` when the surface normals point the
    /// same way at corresponding parametric points (e.g., two coplanar
    /// faces with the same `+z` normal). `aabbOverlap` filters pairs
    /// that are same-domain on the surface but geometrically disjoint.
    ///
    /// # Errors
    ///
    /// Returns an error if either solid handle is invalid or any face /
    /// edge / vertex lookup fails internally.
    #[wasm_bindgen(js_name = "detectCoincidentFaces")]
    pub fn detect_coincident_faces(&self, a: u32, b: u32) -> Result<String, JsError> {
        let a_id = self.resolve_solid(a)?;
        let b_id = self.resolve_solid(b)?;
        let pairs = brepkit_algo::diagnostic::detect_coincident_faces(
            self.topo(),
            a_id,
            b_id,
            brepkit_math::tolerance::Tolerance::default(),
        )
        .map_err(|e| JsError::new(&format!("{e}")))?;
        Ok(coincident_face_pairs_to_json(&pairs).to_string())
    }

    /// Fuse (union) many solids into one in a single call.
    ///
    /// Faster than a left-fold over `fuse`: overlapping solids are reduced
    /// pairwise in a balanced tree while disjoint groups are merged directly
    /// without a boolean.
    ///
    /// Returns a new solid handle (`u32`).
    ///
    /// # Errors
    ///
    /// Returns an error if any solid handle is invalid, the list is empty,
    /// or a boolean operation produces an empty or non-manifold result.
    #[wasm_bindgen(js_name = "fuseAll")]
    pub fn fuse_all(&mut self, solid_handles: Vec<u32>) -> Result<u32, JsError> {
        let solid_ids = solid_handles
            .iter()
            .map(|&h| self.resolve_solid(h))
            .collect::<Result<Vec<_>, _>>()?;
        let compound = self
            .topo_mut()
            .add_compound(brepkit_topology::compound::Compound::new(solid_ids));
        let result = compound_ops::fuse_all(self.topo_mut(), compound)?;
        Ok(solid_id_to_u32(result))
    }

    /// Intersect two solids, keeping only their common volume.
    ///
    /// Returns a new solid handle (`u32`).
    ///
    /// # Errors
    ///
    /// Returns an error if either solid handle is invalid or the operation
    /// produces an empty result.
    #[wasm_bindgen(js_name = "intersect")]
    pub fn intersect_solids(&mut self, a: u32, b: u32) -> Result<u32, JsError> {
        let a_id = self.resolve_solid(a)?;
        let b_id = self.resolve_solid(b)?;
        let result = boolean(self.topo_mut(), BooleanOp::Intersect, a_id, b_id)?;
        Ok(solid_id_to_u32(result))
    }

    // ── Boolean operations with evolution tracking ─────────────────

    /// Fuse (union) two solids and return evolution tracking data.
    ///
    /// Returns a JSON string: `{"solid": <u32>, "evolution": {...}}`.
    ///
    /// # Errors
    ///
    /// Returns an error if either solid handle is invalid or the operation
    /// produces an empty or non-manifold result.
    #[wasm_bindgen(js_name = "fuseWithEvolution")]
    pub fn fuse_with_evolution(&mut self, a: u32, b: u32) -> Result<JsValue, JsError> {
        let a_id = self.resolve_solid(a)?;
        let b_id = self.resolve_solid(b)?;
        let (result, evo) = brepkit_operations::boolean::boolean_with_evolution(
            self.topo_mut(),
            BooleanOp::Fuse,
            a_id,
            b_id,
        )?;
        let json = format!(
            "{{\"solid\":{},\"evolution\":{}}}",
            solid_id_to_u32(result),
            evo.to_json()
        );
        Ok(JsValue::from_str(&json))
    }

    /// Cut (subtract) solid `b` from solid `a` and return evolution tracking data.
    ///
    /// Returns a JSON string: `{"solid": <u32>, "evolution": {...}}`.
    ///
    /// # Errors
    ///
    /// Returns an error if either solid handle is invalid or the operation
    /// produces an empty or non-manifold result.
    #[wasm_bindgen(js_name = "cutWithEvolution")]
    pub fn cut_with_evolution(&mut self, a: u32, b: u32) -> Result<JsValue, JsError> {
        let a_id = self.resolve_solid(a)?;
        let b_id = self.resolve_solid(b)?;
        let (result, evo) = brepkit_operations::boolean::boolean_with_evolution(
            self.topo_mut(),
            BooleanOp::Cut,
            a_id,
            b_id,
        )?;
        let json = format!(
            "{{\"solid\":{},\"evolution\":{}}}",
            solid_id_to_u32(result),
            evo.to_json()
        );
        Ok(JsValue::from_str(&json))
    }

    /// Intersect two solids and return evolution tracking data.
    ///
    /// Returns a JSON string: `{"solid": <u32>, "evolution": {...}}`.
    ///
    /// # Errors
    ///
    /// Returns an error if either solid handle is invalid or the operation
    /// produces an empty result.
    #[wasm_bindgen(js_name = "intersectWithEvolution")]
    pub fn intersect_with_evolution(&mut self, a: u32, b: u32) -> Result<JsValue, JsError> {
        let a_id = self.resolve_solid(a)?;
        let b_id = self.resolve_solid(b)?;
        let (result, evo) = brepkit_operations::boolean::boolean_with_evolution(
            self.topo_mut(),
            BooleanOp::Intersect,
            a_id,
            b_id,
        )?;
        let json = format!(
            "{{\"solid\":{},\"evolution\":{}}}",
            solid_id_to_u32(result),
            evo.to_json()
        );
        Ok(JsValue::from_str(&json))
    }

    /// Perform a mesh boolean on raw triangle data.
    ///
    /// Returns a `JsMesh` with the result.
    #[wasm_bindgen(js_name = "meshBoolean")]
    #[allow(
        clippy::needless_pass_by_value,
        clippy::too_many_arguments,
        clippy::unused_self
    )]
    pub fn mesh_boolean(
        &self,
        positions_a: Vec<f64>,
        indices_a: Vec<u32>,
        positions_b: Vec<f64>,
        indices_b: Vec<u32>,
        op: &str,
        tolerance: f64,
    ) -> Result<JsMesh, JsError> {
        let mesh_a = build_triangle_mesh(&positions_a, &indices_a)?;
        let mesh_b = build_triangle_mesh(&positions_b, &indices_b)?;
        let bool_op = parse_boolean_op(op)?;
        let result =
            brepkit_operations::mesh_boolean::mesh_boolean(&mesh_a, &mesh_b, bool_op, tolerance)?;
        Ok(triangle_mesh_to_js(&result.mesh))
    }
}

impl BrepKernel {
    fn boolean_with_options_impl(
        &mut self,
        op: BooleanOp,
        a: u32,
        b: u32,
        simplify: bool,
    ) -> Result<u32, JsError> {
        let a_id = self.resolve_solid(a)?;
        let b_id = self.resolve_solid(b)?;
        let opts = BooleanOptions {
            unify_faces: simplify,
            ..Default::default()
        };
        let result = boolean_with_options(self.topo_mut(), op, a_id, b_id, opts)?;
        Ok(solid_id_to_u32(result))
    }
}

// Separate impl block: `compound_cut` uses manual `catch_unwind` for panic
// safety — any panic that unwinds across the wasm-bindgen boundary leaves
// its internal RefCell borrowed, breaking all subsequent JS calls.
#[wasm_bindgen]
impl BrepKernel {
    /// Cut a target solid by multiple tool solids in a single pass.
    ///
    /// This is more efficient than sequential `cut()` calls when many tools
    /// are applied to the same target — it avoids re-processing unchanged
    /// faces at each step.
    ///
    /// `tool_ids` is a JS `Uint32Array` or array of solid handles.
    ///
    /// # Errors
    ///
    /// Returns an error if any handle is invalid or the operation fails.
    #[wasm_bindgen(js_name = "compoundCut")]
    pub fn compound_cut(&mut self, target: u32, tool_ids: &[u32]) -> Result<u32, JsError> {
        if self.poisoned {
            return Err(JsError::new(
                "Kernel poisoned after panic. Create a new BrepKernel instance.",
            ));
        }
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let target_id = self.resolve_solid(target)?;
            let tools: Vec<brepkit_topology::solid::SolidId> = tool_ids
                .iter()
                .map(|&h| self.resolve_solid(h))
                .collect::<Result<Vec<_>, _>>()?;
            let result = brepkit_operations::boolean::compound_cut(
                self.topo_mut(),
                target_id,
                &tools,
                brepkit_operations::boolean::BooleanOptions::default(),
            )?;
            Ok(solid_id_to_u32(result))
        }));
        match result {
            Ok(inner) => inner.map_err(|e: crate::error::WasmError| JsError::new(&e.to_string())),
            Err(panic_info) => {
                self.poisoned = true;
                Err(JsError::new(&panic_message(&panic_info, "compoundCut")))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use crate::kernel::BrepKernel;

    /// Helper: parse batch result and check a single op returned ok or error.
    fn batch_has_ok(result: &str, idx: usize) -> bool {
        let parsed: serde_json::Value = serde_json::from_str(result).unwrap();
        parsed[idx]["ok"].is_number()
    }

    fn batch_has_error(result: &str, idx: usize) -> bool {
        let parsed: serde_json::Value = serde_json::from_str(result).unwrap();
        parsed[idx]["error"].is_string()
    }

    /// Create two overlapping boxes via batch, return the raw JSON result.
    fn two_boxes_batch() -> (BrepKernel, String) {
        let mut k = BrepKernel::new();
        let r = k.execute_batch(
            r#"[
                {"op": "makeBox", "args": {"width": 2, "height": 2, "depth": 2}},
                {"op": "makeBox", "args": {"width": 1, "height": 1, "depth": 1}}
            ]"#,
        );
        (k, r)
    }

    // ── fuse ─────────────────────────────────────────────────────────

    #[test]
    fn batch_fuse_simplify_flag_and_fallback_count() {
        let mut k = BrepKernel::new();
        // Overlapping boxes fuse analytically; the optional simplify flag
        // must be accepted, and meshFallbackCount must report a number
        // that does not grow across a clean chain.
        let r = k.execute_batch(
            r#"[
                {"op": "meshFallbackCount", "args": {}},
                {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 10}},
                {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 10}},
                {"op": "transform", "args": {"solid": 1, "matrix": [1,0,0,5, 0,1,0,5, 0,0,1,5, 0,0,0,1]}},
                {"op": "fuse", "args": {"solidA": 0, "solidB": 1, "simplify": true}},
                {"op": "volume", "args": {"solid": 2}},
                {"op": "meshFallbackCount", "args": {}}
            ]"#,
        );
        let parsed: serde_json::Value = serde_json::from_str(&r).unwrap();
        assert!(batch_has_ok(&r, 4), "fuse with simplify must succeed: {r}");
        let vol = parsed[5]["ok"].as_f64().unwrap();
        assert!((vol - 1875.0).abs() < 5.0, "union volume ~1875, got {vol}");
        let before = parsed[0]["ok"].as_f64().unwrap();
        let after = parsed[6]["ok"].as_f64().unwrap();
        assert!(
            (after - before).abs() < 0.5,
            "clean chain must not grow the fallback count: {before} -> {after}"
        );
    }

    #[test]
    fn fuse_two_boxes_returns_valid_handle() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let a = parsed[0]["ok"].as_u64().unwrap();
        let b = parsed[1]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "fuse", "args": {{"solidA": {a}, "solidB": {b}}}}}]"#
        ));
        assert!(batch_has_ok(&r, 0), "fuse must return ok: {r}");
    }

    #[test]
    fn fuse_invalid_handle_a_errors() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let b = parsed[1]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "fuse", "args": {{"solidA": 9999, "solidB": {b}}}}}]"#
        ));
        assert!(batch_has_error(&r, 0));
    }

    #[test]
    fn fuse_invalid_handle_b_errors() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let a = parsed[0]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "fuse", "args": {{"solidA": {a}, "solidB": 9999}}}}]"#
        ));
        assert!(batch_has_error(&r, 0));
    }

    // ── cut ──────────────────────────────────────────────────────────

    #[test]
    fn cut_two_boxes_returns_valid_handle() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let a = parsed[0]["ok"].as_u64().unwrap();
        let b = parsed[1]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "cut", "args": {{"solidA": {a}, "solidB": {b}}}}}]"#
        ));
        assert!(batch_has_ok(&r, 0), "cut must return ok: {r}");
    }

    #[test]
    fn cut_invalid_target_errors() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let b = parsed[1]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "cut", "args": {{"solidA": 9999, "solidB": {b}}}}}]"#
        ));
        assert!(batch_has_error(&r, 0));
    }

    #[test]
    fn cut_invalid_tool_errors() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let a = parsed[0]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "cut", "args": {{"solidA": {a}, "solidB": 9999}}}}]"#
        ));
        assert!(batch_has_error(&r, 0));
    }

    // ── intersect ────────────────────────────────────────────────────

    #[test]
    fn intersect_two_boxes_returns_valid_handle() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let a = parsed[0]["ok"].as_u64().unwrap();
        let b = parsed[1]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "intersect", "args": {{"solidA": {a}, "solidB": {b}}}}}]"#
        ));
        assert!(batch_has_ok(&r, 0), "intersect must return ok: {r}");
    }

    #[test]
    fn intersect_invalid_handle_errors() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let a = parsed[0]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "intersect", "args": {{"solidA": {a}, "solidB": 9999}}}}]"#
        ));
        assert!(batch_has_error(&r, 0));
    }

    // ── compound_cut ─────────────────────────────────────────────────

    #[test]
    fn compound_cut_single_tool() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let a = parsed[0]["ok"].as_u64().unwrap();
        let b = parsed[1]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "compoundCut", "args": {{"target": {a}, "tools": [{b}]}}}}]"#
        ));
        assert!(batch_has_ok(&r, 0), "compound_cut must return ok: {r}");
    }

    #[test]
    fn compound_cut_multiple_tools() {
        let mut k = BrepKernel::new();
        let r = k.execute_batch(
            r#"[
                {"op": "makeBox", "args": {"width": 4, "height": 4, "depth": 4}},
                {"op": "makeBox", "args": {"width": 1, "height": 1, "depth": 1}},
                {"op": "makeBox", "args": {"width": 0.5, "height": 0.5, "depth": 0.5}},
                {"op": "compoundCut", "args": {"target": 0, "tools": [1, 2]}}
            ]"#,
        );
        assert!(
            batch_has_ok(&r, 3),
            "compound_cut with two tools must return ok: {r}"
        );
    }

    #[test]
    fn compound_cut_invalid_target_errors() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let b = parsed[1]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "compoundCut", "args": {{"target": 9999, "tools": [{b}]}}}}]"#
        ));
        assert!(batch_has_error(&r, 0));
    }

    #[test]
    fn compound_cut_invalid_tool_errors() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let a = parsed[0]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "compoundCut", "args": {{"target": {a}, "tools": [9999]}}}}]"#
        ));
        assert!(batch_has_error(&r, 0));
    }

    #[test]
    fn compound_cut_empty_tool_list_is_identity() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let a = parsed[0]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "compoundCut", "args": {{"target": {a}, "tools": []}}}}]"#
        ));
        assert!(batch_has_ok(&r, 0));
    }

    // ── detectCoincidentFaces ────────────────────────────────────────

    #[test]
    fn detect_coincident_faces_overlapping_boxes_returns_sd_pairs() {
        // `two_boxes_batch()` creates two axis-aligned boxes (2×2×2 and
        // 1×1×1) both at the origin — the smaller is fully contained in
        // the larger. Each pair of axis-aligned faces shares a parallel
        // plane normal, so the SD detector reports several same-domain
        // pairs. We verify (a) the JSON shape and (b) at least one pair
        // is reported with a valid `aabbOverlap` flag.
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let a = parsed[0]["ok"].as_u64().unwrap();
        let b = parsed[1]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "detectCoincidentFaces", "args": {{"solidA": {a}, "solidB": {b}}}}}]"#
        ));
        let parsed: serde_json::Value = serde_json::from_str(&r).unwrap();
        let arr = parsed[0]["ok"].as_array().unwrap();
        assert!(!arr.is_empty(), "overlapping boxes produce SD pairs: {r}");
        for pair in arr {
            assert!(pair["faceA"].is_u64());
            assert!(pair["faceB"].is_u64());
            assert!(pair["sameOrientation"].is_boolean());
            assert!(pair["aabbOverlap"].is_boolean());
        }
    }

    #[test]
    fn detect_coincident_faces_invalid_handle_errors() {
        let (mut k, setup) = two_boxes_batch();
        let parsed: serde_json::Value = serde_json::from_str(&setup).unwrap();
        let a = parsed[0]["ok"].as_u64().unwrap();
        let r = k.execute_batch(&format!(
            r#"[{{"op": "detectCoincidentFaces", "args": {{"solidA": {a}, "solidB": 9999}}}}]"#
        ));
        assert!(batch_has_error(&r, 0));
    }

    // ── mesh_boolean ─────────────────────────────────────────────────
    // mesh_boolean is not in the batch dispatcher, but its happy-path
    // works on native (JsError is only constructed on the error path).
    // For error paths, we test the internal operations layer directly.

    #[test]
    fn mesh_boolean_fuse_returns_non_empty_mesh() {
        let k = BrepKernel::new();
        #[rustfmt::skip]
        let positions = vec![
            0.0, 0.0, 0.0,
            1.0, 0.0, 0.0,
            0.0, 1.0, 0.0,
            0.0, 0.0, 1.0,
        ];
        let indices = vec![0, 2, 1, 0, 1, 3, 0, 3, 2, 1, 2, 3];
        let mesh = k
            .mesh_boolean(
                positions.clone(),
                indices.clone(),
                positions,
                indices,
                "fuse",
                1e-7,
            )
            .unwrap();
        assert!(
            !mesh.positions().is_empty(),
            "fused mesh must have vertices"
        );
        assert!(!mesh.indices().is_empty(), "fused mesh must have triangles");
        assert_eq!(mesh.positions().len() % 3, 0);
        assert_eq!(mesh.indices().len() % 3, 0);
    }

    #[test]
    fn mesh_boolean_unknown_op_is_not_valid() {
        // Verify the operation string validation logic without calling
        // JsError-returning helpers (JsError panics on non-wasm).
        let valid = [
            "fuse",
            "union",
            "cut",
            "difference",
            "intersect",
            "intersection",
        ];
        assert!(
            !valid.contains(&"explode"),
            "explode should not be a valid op"
        );
    }

    #[test]
    fn mesh_boolean_bad_positions_length_is_invalid() {
        // Verify the validation condition directly: positions must be multiple of 3.
        let bad_len = 2;
        assert_ne!(
            bad_len % 3,
            0,
            "length 2 should fail the multiple-of-3 check"
        );
    }

    // ── boolean volume check ─────────────────────────────────────────

    #[test]
    fn cut_reduces_volume() {
        let mut k = BrepKernel::new();
        let r = k.execute_batch(
            r#"[
                {"op": "makeBox", "args": {"width": 2, "height": 2, "depth": 2}},
                {"op": "makeBox", "args": {"width": 1, "height": 1, "depth": 1}},
                {"op": "volume", "args": {"solid": 0}},
                {"op": "cut", "args": {"solidA": 0, "solidB": 1}},
                {"op": "volume", "args": {"solid": 2}}
            ]"#,
        );
        let parsed: serde_json::Value = serde_json::from_str(&r).unwrap();
        let vol_before = parsed[2]["ok"].as_f64().unwrap();
        let vol_after = parsed[4]["ok"].as_f64().unwrap();
        assert!(
            vol_after < vol_before,
            "cut must reduce volume: {vol_before} -> {vol_after}"
        );
    }

    // ── compound_cut volume regression ───────────────────────────────

    #[test]
    fn compound_cut_volume_decreases() {
        let mut k = BrepKernel::new();
        // Target: 10x10x10 box at origin. Tool: 1x1x1 box at origin.
        // The tool overlaps one corner, so volume decreases.
        let r = k.execute_batch(
            r#"[
                {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 10}},
                {"op": "makeBox", "args": {"width": 1, "height": 1, "depth": 1}},
                {"op": "volume", "args": {"solid": 0}},
                {"op": "compoundCut", "args": {"target": 0, "tools": [1]}},
                {"op": "volume", "args": {"solid": 2}}
            ]"#,
        );
        let parsed: serde_json::Value = serde_json::from_str(&r).unwrap();
        let vol_before = parsed[2]["ok"].as_f64().unwrap();
        assert!(batch_has_ok(&r, 3), "compoundCut must succeed: {r}");
        let vol_after = parsed[4]["ok"].as_f64().unwrap();
        assert!(
            vol_after < vol_before && vol_after > 0.0,
            "compound_cut must reduce volume: {vol_before} -> {vol_after}"
        );
    }
}