commandagi 0.6.10

The CommandAGI SDK for Rust: the platform client (agent threads, live sessions on a simulated world) and CommandAGI documents (a schematic, a 3D part …) declared as code. No dependencies.
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
//! A 3D DOCUMENT IN RUST — the document's own graph, declared element by element, so the 3D editor opens a `.3d.rs`
//! with all its tools and writes each edit back into the file. The same elements, node for node, as the TypeScript
//! SDK's JSX (`threed.ts`) and the Python SDK's (`threed.py`):
//!
//! ```
//! use commandagi::design::threed::*;
//!
//! fn document() -> El {
//!     part([
//!         parameter().name("depth").value(6).unit("mm").bindings(json(r#"[{"target": "extrude1", "field": "distance"}]"#)),
//!         sketch([
//!             point().id("p1").x(-30).y(-20),
//!             point().id("p2").x(30).y(-20),
//!             line().id("l1").a("p1").b("p2"),
//!             constraint().id("c1").kind("horizontal").entities(["l1"]),
//!         ])
//!         .id("sketch1")
//!         .name("Sketch1")
//!         .plane(json(r#"{"type": "datum", "plane": "plane_xy"}"#)),
//!         extrude().id("extrude1").name("Extrude1").profile(json(r#"{"sketch": "sketch1"}"#)).distance(6).operation("new"),
//!         body().id("extrude1").engineering(json(r#"{"material": "6061-T6", "process": "cnc-milling"}"#)),
//!     ])
//!     .name("Mounting plate")
//! }
//! # commandagi::design::declare(document()).unwrap();
//! ```
//!
//! The calls (each method is the field of the same name, in snake case: `.x_axis(…)` is `xAxis`):
//!
//! ```text
//! part([…]).name(…) | assembly([…]).name(…)     the document; an assembly opens in the assembly mode
//! part([…]).builtin_planes([…])                 the built-in planes the document has (absent: all three; []: none)
//! parameter().name().value().expression().unit().comment().min().max().step().bindings(json(r#"[{"target", "field"}]"#))
//! plane().id().name().origin().normal().x_axis()                      a datum plane
//! FEATURE().id().name() …fields                  a feature: the function is its type (extrude, revolve, fillet,
//!                                                chamfer, hole, linear_pattern, box_, import, …); `.suppressed(…)`,
//!                                                `.consumes([…])` as stored. THE ORDER OF THE ELEMENTS IS THE ORDER
//!                                                THE PART IS BUILT IN: a feature that acts on bodies (a cut, a hole,
//!                                                a fillet, a pattern) and names no `consumes` follows every
//!                                                body-making feature written before it
//! faces and edges                                where a feature takes them (`.edges()`, `.faces()`, `.face()`,
//!                                                `.edge()`): one picked by where it was, `{"kind", "signature":
//!                                                {"point", …}}`, or the ones a query chooses when the part is built,
//!                                                `{"kind", "select": {…}}`: normal, parallel, perpendicular, axis,
//!                                                geometry, length, radius, area, ofFace, createdBy, at, inBox, farthest,
//!                                                any, not. Every test present must hold
//! curve().id().name().kind().points() …         a curve in space (spline, polyline, helix), which makes no body; a
//!                                                sweep follows it: `.path(json(r#"{"curve": "<id>"}"#))`
//! hole().face(…).positions(…) | .sketch(…)       where the holes are: points in model coordinates, or a sketch of
//!                                                points; with neither, the face's centre. A face that chooses
//!                                                several drills each place in the one it lies on
//! feature().type_(…).id().name() …               a feature of a type the kernel does not know
//! sketch([…]).id().name().plane(…)              a sketch: point().id().x().y(), a segment by its type (line,
//!                                                circle, arc, spline, ellipse, ellipse_arc), constraint().id()
//!                                                .kind().entities([…]), projection().id().ref_().feature()
//! body().id().name().material(…).engineering(…) a body's own data (`bodyMeta[id]`): its name, its look (`material`)
//!                                                and what it is (`engineering`: the material grade by its id in a
//!                                                materials table, the process and how it is made, the finish, its
//!                                                suppliers and their terms, its inspection, compliance, shipping and
//!                                                lifecycle; docs/formats.md § logistics)
//! item().id().name().qty().ref_().engineering(…) a part of the product with no geometry here (`items`): a cable in
//!                                                the box, or another design by `ref` (a board's .pcb.rs)
//! assemble().id().order().parts([…]).fasteners([…]).tools([…]).fixture().by().minutes().rate_per_hour()
//!          .currency().instruction()             one assembly step (`assemblySteps`)
//! product().id().name().compliance(…).shipping(…) the product as it is sold (`products`): its certifications, its
//!                                                tariff heading, its packed size and mass
//! joint().id().kind().a().b().anchor().axis().limits() …   a joint between two bodies (`dynamics.joints`): fixed,
//!                                                revolute, prismatic, cylindrical, planar, screw, spherical, universal
//! contact().id().a().b().collide().friction().restitution().report([…])   a contact pair (`dynamics.contacts`): two
//!                                                sides of bodies named as a check names them (no `b`: the ground),
//!                                                whether they touch, their own friction and restitution, and what a
//!                                                run records of them
//! mate().id().kind().a().b().axis() …            a mate between two components of an assembly (`assembly.mates`)
//! sheet().id().size().scale().projection().views(…) …      an engineering drawing sheet of the document (`drawings`)
//! view().id().name().camera(…).ride(…)           a camera kept under a name (`views`): the Views menu applies it, and
//!                                                `ride` (`{"target", "view": chase | cockpit | orbit}`) is what it rides
//! check().id().kind().bodies().against().sweep(…) …      a check the design must pass (`checks`; a sweep moves joints)
//! accept().id().check().body().other().region().max_volume().reason()   a finding accepted on purpose (`accepted`)
//! permitted().id().check().body().process().edge_dir().region().reason()   findings a process or a purpose permits
//!                                                (`permitted`)
//! fastener().id().part().length().at().axis().clamped([…]).receiver().washer().nut() …   a fastener stack: a library
//!                                                screw placed through clamped bodies into a receiver (`fasteners`)
//! tactile().id().body().at().normal().along().rows().cols().pitch() …   a tactile skin: a grid of taxels on one face
//!                                                of a body (`tactile`), which a device definition's tactile channel records
//! port().id().body().at().axis().hold() …       where a rod's end can be held (`ports`): a pad, a joint, a socket, a row
//! library().id().match_().engineering(…).sizes(…)   the data of every library fastener piece whose designation
//!                                                matches (`library`): its supplier and price, given once
//! linear_dimension().id().a(…).b(…) … | radial_dimension() | size_dimension() | angular_dimension()
//!   | note().id().text().anchor(…) | datum_feature().id().letter().anchor(…) | datum_target()
//!   | feature_control_frame().id().characteristic().tolerance().datums(…).anchor(…) | surface_finish()
//!                                                an annotation (`annotations`): the function is its type, each
//!                                                method the field of the same name (`3d-core/annotations.ts`); an
//!                                                anchor is {"type": "point" | "topo" | "group" | "of" | "geometry", …}.
//!                                                The calls, whatever their types, are the list in the order written
//! slot().name(…).value(…)                       any other field of the document, whole
//! ```
//!
//! The declaration is the document's graph exactly: a feature is a node of its type with its fields as ports, a
//! plane a `plane` node, a parameter an `input` node whose `drives` are its bindings, a slot a `3d.<field>` node, the
//! bodies one `3d.bodyMeta` node. The order of the feature elements is the order of the left-hand list
//! (`presentation.order`). Every node carries the call it came from in `meta.source`; a sketch's entities and the
//! bodies are listed by key in `meta.sources`. Units are millimetres and radians, as stored. A field the methods do not
//! name is written `.with_attr("field", value)`. Anything else is refused by name, never guessed.
//!
//! A feature element is checked against its type's schema (`threed_schema.json`, generated from the `Feature` types;
//! the same fields are typed in [`super::threed_props`], `ExtrudeProps` …): the feature `{type: <tag>, id, name: <its
//! id when absent>, suppressed, …its fields}`, a sketch with the `sketch` its children make. A wrong field is refused
//! with the sentence the TypeScript reader and the op panel give: `extrude().id("e1"): distance: must be greater than 0
//! (got -1)`. A `feature().type_(…)` of an unknown type is not checked. A required field that declares a default may
//! be left out: it reads as that default (an `external_part()` without `placement` sits at the identity placement),
//! and the node's inputs hold it.

use super::element::{attributes, elements, fn_name, rust_name};
use super::ir::slug;
use super::schema::{describe_issue, validate, with_defaults};
use super::source::Sources;
use super::standards::sized_hole;
use super::{Declared, Family};
pub use super::threed_props::THREED_FEATURES;
pub use super::{fragment, json, El, Json, Value};
use std::sync::OnceLock;

elements! {
    /// A part: the document, its elements.
    part: children;
    /// An assembly: the document, opened in the assembly mode.
    assembly: children;
    /// A parameter: `parameter().name("depth").value(6).unit("mm")`.
    parameter: leaf;
    /// A datum plane: `plane().id(…).origin([0, 0, 0]).normal([0, 0, 1]).x_axis([1, 0, 0])`.
    plane: leaf;
    /// A body's own data: `body().id("extrude1").material(…)`.
    body: leaf;
    /// Any other field of the document, whole: `slot().name("environment").value(json(…))`.
    slot: leaf;
    /// A joint between two bodies: `joint().id("j1").kind("revolute").a("base").b("arm").anchor([0, 0, 40]).axis([0, 0, 1])`.
    joint: leaf;
    /// A contact pair: `contact().id("pad").a("Pad").b("Ramp").friction(0.9).restitution(0.1).report(["normal", "slip"])`.
    contact: leaf;
    /// A mate between two components of an assembly: `mate().id("m1").kind("concentric").a("p1").b("p2").axis("Z")`.
    mate: leaf;
    /// An engineering drawing sheet: `sheet().id("sheet1").views(json(r#"[{"id": "front", "view": "front"}]"#))`.
    sheet: leaf;
    /// A part of the product with no geometry here: `item().id("tape").name("Foam tape").qty(2).engineering(…)`.
    item: leaf;
    /// One assembly step: `assemble().id("s1").order(1).parts(["b", "tape"]).by("in-house").minutes(2)`.
    assemble: leaf;
    /// The product as it is sold: `product().id("cam").name("Camera").shipping(json(r#"{"hsCode": "8525.89"}"#))`.
    product: leaf;
    /// A device definition placed as a unit (`placements`): `unit().id("arm").name("arm").device("…/definition.tsx").position([0, 0, 0]).rotation(0)`.
    unit: leaf;
    /// A captured place drawn as Gaussian splats (`captures`): `capture().id("bridgeway").src("./bridgeway.ply").at(json(r#"{"latDeg": 37.8564, "lonDeg": -122.4796, "heightM": 4.1}"#))`.
    capture: leaf;
    /// A camera kept under a name (`views`), and what it rides when the view is applied: `view().id("ferry").name("Ride the ferry").camera(json(r#"{"target": [0, 0, 0], "radius": 3e6, "theta": 0.5, "phi": 1}"#)).ride(json(r#"{"target": "vessel-367123450", "view": "chase"}"#))`.
    view: leaf;
    /// A check the design must pass: `check().id("stroke").kind("interference").sweep(json(r#"{"joints": ["ramJ"]}"#))`.
    check: leaf;
    /// A finding accepted on purpose: `accept().id("a1").check("clash").body("Sleeve").other("Ram").max_volume(3200).reason(…)`.
    accept: leaf;
    /// Findings a process or a purpose permits: `permitted().id("cut").check("edges").body("Panel*").process("laser-cutting").reason(…)`.
    permitted: leaf;
    /// A fastener stack: `fastener().id("f1").part("iso-4762-m6").length(18).at([0, 0, 20]).clamped(["Lid"]).receiver("Base")`.
    fastener: leaf;
    /// A tactile skin: `tactile().id("pad").body("Jaw").at([-20, 0, 20]).normal([1, 0, 0]).along([0, 1, 0]).rows(4).cols(4).pitch(5)`.
    tactile: leaf;
    /// Where a rod's end can be held: `port().id("a").body("board").at([0, 0, 8.5]).axis([0, 0, -1]).hold("insert").depth(6).retention(1).count(63).pitch(2.54)`.
    port: leaf;
    /// The data of every library fastener piece whose designation matches: `library().id("shcs").match_("ISO 4762 * A2-70")`.
    library: leaf;
    /// A distance between two anchors: `linear_dimension().id("d1").a(json(…)).b(json(…)).axis("x")`.
    linear_dimension = "linearDimension": leaf;
    /// A diameter or a radius: `radial_dimension().id("d2").measure("diameter").center(json(…)).value(5)`.
    radial_dimension = "radialDimension": leaf;
    /// A size that is no diameter or radius (a thickness, a cone's angle): `size_dimension().id("t").measure("thickness").of(json(…)).value(10)`.
    size_dimension = "sizeDimension": leaf;
    /// An angle at a vertex, or between two features: `angular_dimension().id("d4").a(json(…)).b(json(…)).value(1.57)`.
    angular_dimension = "angularDimension": leaf;
    /// A note with an optional leader: `note().id("n1").text("BREAK SHARP EDGES").anchor(json(…))`.
    note: leaf;
    /// A datum feature label: `datum_feature().id("A").letter("A").anchor(json(…))`.
    datum_feature = "datumFeature": leaf;
    /// A datum target (A1): `datum_target().id("A1").letter("A").target("1").placed(json(…))`.
    datum_target = "datumTarget": leaf;
    /// A geometric tolerance: `feature_control_frame().id("f1").characteristic("position").tolerance(0.1).anchor(json(…))`.
    feature_control_frame = "featureControlFrame": leaf;
    /// A surface finish: `surface_finish().id("s1").roughness(1.6).anchor(json(…))`.
    surface_finish = "surfaceFinish": leaf;
    /// A feature of a type the kernel does not know: `feature().type_("rotate").id(…)`.
    feature: leaf;
    /// A sketch: its points, segments, constraints and projections.
    sketch: children;
    extrude: leaf;
    revolve: leaf;
    sweep: leaf;
    /// A curve in space, which makes no body and which a sweep follows: `curve().id("lead").points(json("[[0, 0, 0], [30, 10, 15]]"))`,
    /// then `sweep().path(json(r#"{"curve": "lead"}"#))`. A `spline` (the default), a `polyline` or a `helix`.
    curve: leaf;
    /// A rod (a wire, a lead, a string, a hair, a flat flex): `rod().id("j1").material("WIRE-22AWG-SOLID-PVC").from(json(r#"{"port": "bb/a3"}"#)).to(json(r#"{"port": "bb/a12"}"#))`.
    rod: leaf;
    loft: leaf;
    fillet: leaf;
    chamfer: leaf;
    shell: leaf;
    box_: leaf;
    import: leaf;
    external_part = "externalPart": leaf;
    cylinder: leaf;
    sphere: leaf;
    cone: leaf;
    make_human = "makeHuman": leaf;
    linear_pattern = "linearPattern": leaf;
    circular_pattern = "circularPattern": leaf;
    path_pattern = "pathPattern": leaf;
    mirror: leaf;
    datum_plane = "datumPlane": leaf;
    /// A construction axis: `datum_axis().id("a1").method("twoPoints").point(…).point2(…)`.
    datum_axis = "datumAxis": leaf;
    /// A construction point: `datum_point().id("q1").method("threePlanes").plane(…).plane2(…).plane3(…)`.
    datum_point = "datumPoint": leaf;
    draft: leaf;
    hole: leaf;
    thread: leaf;
    rib: leaf;
    coil: leaf;
    combine: leaf;
    offset_faces = "offsetFaces": leaf;
    thicken: leaf;
    /// A surface trimmed by a plane: `trim_surface().id("t").body("skin").tool(json(r#"{"type":"datum","plane":"p1"}"#))`.
    trim_surface = "trimSurface": leaf;
    /// A surface with the openings cut into it filled.
    untrim_surface = "untrimSurface": leaf;
    /// A surface grown past its open edges.
    extend_surface = "extendSurface": leaf;
    /// Surfaces joined into one body (a solid when they close).
    stitch: leaf;
    /// A solid's face replaced by a surface: `replace_face().id("r").face(…).surface("sheet")`.
    replace_face = "replaceFace": leaf;
    /// A surface offset along its normal.
    offset_surface = "offsetSurface": leaf;
    split: leaf;
    scale: leaf;
    dome: leaf;
    wrap_text = "wrapText": leaf;
    delete_face = "deleteFace": leaf;
    full_round = "fullRound": leaf;
    /// Sheet-metal rules: `sheet_metal().id("rules").thickness(2).bend_radius(2).k_factor(0.44).relief("rectangular")`.
    sheet_metal = "sheetMetal": leaf;
    /// One corner's relief: `sheet_corner().id("c1").flanges(json(r#"["front", "side"]"#)).relief("round")`.
    sheet_corner = "sheetCorner": leaf;
    /// A thin-walled part made sheet metal, from a face of its base wall.
    sheet_convert = "sheetConvert": leaf;
    /// The bends an unfold flattened, bent again: `sheet_refold().id("r").unfold("u")`.
    sheet_refold = "sheetRefold": leaf;
    /// A base flange: a closed sketch profile made as thick as the rules' sheet.
    sheet_base = "sheetBase": leaf;
    sheet_flange = "sheetFlange": leaf;
    sheet_hem = "sheetHem": leaf;
    sheet_fold = "sheetFold": leaf;
    unfold: leaf;
    /// Frame members along a sketch's lines: `frame_member().id("frame").sketch("s1").profile("squareTube").size("40x40x3")`.
    frame_member = "frameMember": leaf;
    end_cap = "endCap": leaf;
    copy_body = "copyBody": leaf;
    transform: leaf;
    subdiv_body = "subdivBody": leaf;
    mesh_body = "meshBody": leaf;
    mesh_modifier = "meshModifier": leaf;
    point_cloud = "pointCloud": leaf;
    gaussian_splat = "gaussianSplat": leaf;
    skeleton: leaf;
    volume: leaf;
    molecule: leaf;
    graph: leaf;
    generate: leaf;
    pcb_trace = "pcbTrace": leaf;
    copper_pour = "copperPour": leaf;
    generate_via = "generateVia": leaf;
    plated_hole = "platedHole": leaf;
    /// A part authored as code: `code().id(…).source("bracket.3d.py").inputs(json(…))`.
    code: leaf;
    /// A sketch point: `point().id("p1").x(0).y(0)`.
    point: leaf;
    /// A line between two points: `line().id("l1").a("p1").b("p2")`.
    line: leaf;
    /// A circle: `circle().id(…).center("p1").radius(3)`.
    circle: leaf;
    /// An arc: `arc().id(…).center(…).start(…).end(…).radius(…)`.
    arc: leaf;
    /// A spline through (or controlled by) its points.
    spline: leaf;
    /// An ellipse: `.center(…).focus(…).minor_radius(…)`.
    ellipse: leaf;
    /// An ellipse arc: `.center(…).focus(…).minor_radius(…).start(…).end(…)`.
    ellipse_arc = "ellipseArc": leaf;
    /// A constraint: `constraint().id("c1").kind("horizontal").entities(["l1"])`.
    constraint: leaf;
    /// A projection of a feature's edge into the sketch.
    projection: leaf;
    /// An equation curve: `.x("…").y("…").from(…).to(…).points(…)`, x and y arithmetic of t.
    equation: leaf;
    /// A text: `.text(…).font(…).anchor(…).along(…).contours(…)`, placed by two points of the sketch.
    text: leaf;
}

attributes! {
    /// The fields of a 3D document's entities, chained on its elements (each the field of the same name).
    pub trait ThreedAttrs {
        a; actuator; african; age; align_to_path; anchor; angle; animation; annotations; area; armatures; asian; assembly;
        at; axis; axis_b; b; base; bend_radius; bias; bindings; bodies; body_id; bond_orders; bonds; both_sides;
        break_after; builtin; builtin_planes; by; cap; caucasian; cell; center; centreline; chains; closed; collapsed;
        colormap; colors; comment; component; conductor; construction; consumes; contours; control_points; corner; count; count2;
        cupsize; currency; data; decals; depth; diameter; dims; dir; directed; direction; direction2; distance; distance2;
        draft_angle; drill_mm; dynamics; edge; edge_weights; edges; efficiency; electrical; electron; elements; end; engineering; entities;
        environment; expression; fabrication; face; faces; factor; fasteners; feature; file_id; file_name; firmness; fixed; fixture; focus; font;
        footprint; format; from; gender; graph; groups; head_depth; head_diameter; height; hidden_lines; hole_callouts; home; home_travel; host; id; importer; indices;
        input; inputs; instruction; internal; iso; join; k_factor; keep_original; kind; knots; label; layer; layers; length;
        level; lib_id; limits; local_placement; material; material_groups; mates; max; members; min; minor_radius; minutes; mode;
        model_id; modifier; muscle; name; node_colors; node_groups; node_positions; node_sizes; node_types; normal;
        normals; nucleus; nurbs; offset; operation; optimization; order; origin; outward; overall_dimensions; pad; pad_diameter_mm;
        pads; paint; params; parents; part; parts; parts_list; path; pin; pitch; placement; planar; plane; point; point_size; points;
        polygons; position; positions; profile; profiles; projection; proportions; provenance; pull_direction; qty; quaternion;
        radii; radius; radius1; radius2; rate_per_hour; ref_; ref_a; ref_b; reference; refs; regions; render; representation; requires; reverse;
        right_handed; rings; rotate_angle; rotate_axis; rotation_deg; rotations; rule; ruled; scale; scale_x_y_z;
        scales; scene_constraints; seed_feature; semantic_visibility; sh; sh_degree; side; signature; size; sketch;
        skins; source; source_materials; source_uv; spacing; spacing2; standard_parts; start; step; style;
        subdivision; suppressed; symmetric; target; terminal; thickness; through; title; token; tools; transform; translate;
        travel; turns; type_; u; unit; unit_scale_mm; up_to_face; uv; v; value; views; visible; weight; width; x; x_axis; y;
        /// A spline curve's end directions, its inner directions by index in `points`, and how hard they hold.
        start_tangent; end_tangent; tangents; tangent_scale;
        /// How a sweep's profile turns along its path: its frame, the `up` of that frame, the `guide` curve's id, and its twist.
        frame; up; guide; twist;
        /// A size's tolerance: `json(r#"{"class": "H7"}"#)`, `{"upper": 0.05, "lower": -0.05}` or `{"basic": true}`.
        tolerance;
        /// A fit check's hole, shaft and intended fit (clearance, transition, interference).
        hole; shaft; intent;
        /// A stack-up check's chain (`["+pocket", "-width"]`), limit (`{"min": 0.05, "max": 0.5}`), method, samples and seed.
        chain; limit; method; samples; seed;
        /// A check's bodies compared against others, its smallest shared volume (mm³), and its sweep over its joints'
        /// ranges: `sweep(json(r#"{"joints": ["X", "Z"], "step": 10}"#))`.
        against; min_volume; sweep;
        /// A registered check's own fields (a printer's nozzle, a tool's radius), as that check reads them.
        options;
        /// An accept's or a permit's check, body, other body of a pair, largest shared volume (mm³) and reason.
        check; body; other; max_volume; reason; region; severity;
        /// A product's number, compliance and shipping: `product().id("kit").shipping(json(r#"{"hsCode": "8525.89"}"#))`.
        compliance; shipping;
        /// A placed unit's definition, heading, tilt (degrees), box (mm) and its tuning of its channels.
        device; rotation; channels; tilt_deg = "tilt_deg"; size_mm = "size_mm";
        /// A capture's file, the day its photos were taken, its licence, credit, terms page and cameras (its pose is `at`, its page `source`).
        src; captured; licence; credit; terms; devices;
        /// A saved view's camera and what it rides (`{"target", "view": chase | cockpit | orbit}`).
        camera; ride;
        /// A permit's process and the direction of the edges it permits.
        process; edge_dir;
        /// A fastener stack's clamped bodies, receiver, washer, nut, grip, fit, least thread engagement, torque and part number.
        clamped; receiver; washer; nut; grip; fit; min_engagement; torque; part_number;
        /// A tactile skin's direction along its rows, its rows and columns of taxels, and the pressure it saturates at (kPa).
        along; rows; cols; saturation;
        /// A rod's strands, the file it reads them from, its section, its far end, its slack and its node spacing; a
        /// port's hold, a socket's retention and the number a row's first port is called by; a placement's rods' ends.
        strands; file; section; to; slack; segment; hold; retention; first; ends;
        /// A library entry's designation pattern and its sizes.
        match_; sizes;
        /// A contact pair's touch, its own friction and restitution, and what a run records of it.
        collide; friction; restitution; report;
        /// An annotation's fields (`3d-core/annotations.ts`): where its text sits, a dimension's limits, notes, formats,
        /// measure, rim, vertex and angle, a note's text, leader and property, a datum's letter and target, a frame's
        /// characteristic, zone, datums and modifiers, a finish's roughness and requirement.
        text_at; notes; formats; measure; spherical; of; datum; rim; angle_selection; vertex; text; leader_to; property;
        letter; placed; on; characteristic; diameter_zone; datums; modifiers; zone; unequal; projected; per_unit; maximum;
        segment_of; roughness; requirement;
        /// A construction plane's second plane, edge and points; a construction axis's or point's second and third
        /// planes; a hole's thread; a surface feature's surface flag, tool and side; the left-hand list's rollback.
        base2; edge2; point2; point3; plane2; plane3; surface; thread; thread_depth; thread_kind; tool; tool_body; keep_front; rollback;
    }
}

pub(crate) const FAMILY: Family = Family { module: "threed", roots: &["part", "assembly"], declare };

/// The schema of the 3D features (`roots`: tag → definition, `$defs`), generated from the `Feature` types.
pub fn threed_schema() -> &'static Json {
    static SCHEMA: OnceLock<Json> = OnceLock::new();
    SCHEMA.get_or_init(|| Json::parse(include_str!("threed_schema.json")).expect("threed_schema.json is JSON"))
}

/// The feature with each required field it leaves out filled with its declared default ([`with_defaults`]), checked
/// against its type's schema; refused with every issue when it does not fit.
fn check_feature(el: &El, feature: Json) -> Result<Json, String> {
    let schema = threed_schema();
    let Some(def) = feature.get("type").and_then(|t| schema.get("roots")?.get(t.as_str()?)).and_then(Json::as_str) else { return Ok(feature) };
    let defs = schema.get("$defs").cloned().unwrap_or_else(Json::obj);
    let root = Json::obj().with("$ref", format!("#/$defs/{def}"));
    let filled = with_defaults(&root, &feature, &defs)?;
    let issues = validate(&root, &filled, &defs, "")?;
    if issues.is_empty() {
        return Ok(filled);
    }
    Err(format!("{}: {}", at(el), issues.iter().map(describe_issue).collect::<Vec<_>>().join("; ")))
}
/// A value checked against a definition of the schema (a body's engineering data, a joint, a mate, a sheet), with each
/// required field it leaves out filled with its declared default; refused with every issue when it does not fit.
fn check_value(el: &El, def: &str, value: &Json, path: &str) -> Result<Json, String> {
    let schema = threed_schema();
    let defs = schema.get("$defs").cloned().unwrap_or_else(Json::obj);
    let root = Json::obj().with("$ref", format!("#/$defs/{def}"));
    let filled = with_defaults(&root, value, &defs)?;
    let issues = validate(&root, &filled, &defs, path)?;
    if issues.is_empty() {
        return Ok(filled);
    }
    Err(format!("{}: {}", at(el), issues.iter().map(describe_issue).collect::<Vec<_>>().join("; ")))
}
/// What is wrong with a sheet's section and detail views, one sentence each, as the 3D core's `sheetViewProblems`
/// says it (packages/domain/3d-core/drawing-sheet.ts); the TypeScript and Python SDKs say the same sentences.
fn sheet_view_problems(sheet: &Json) -> Vec<String> {
    let Some(Json::Arr(views)) = sheet.get("views") else { return Vec::new() };
    let text = |v: &Json, k: &str| v.get(k).and_then(Json::as_str).unwrap_or_default().to_string();
    let given = |v: &Json, k: &str| v.get(k).is_some_and(|x| !matches!(x, Json::Null));
    let mut out = Vec::new();
    for v in views {
        let (id, view) = (text(v, "id"), text(v, "view"));
        if view == "section" && !given(v, "section") {
            out.push(format!("view {id} is a section view with no section: give its cutting plane (point and normal)"));
        }
        if view != "detail" {
            continue;
        }
        let Some(detail) = v.get("detail").filter(|_| given(v, "detail")) else {
            out.push(format!("view {id} is a detail view with no detail: give the view it enlarges, its centre and its radius"));
            continue;
        };
        let of = text(detail, "of");
        match views.iter().find(|w| text(w, "id") == of) {
            None => out.push(format!("view {id} is a detail of {of}, which is no view of this sheet")),
            Some(w) if text(w, "view") == "detail" => out.push(format!("view {id} is a detail of {of}, which is a detail itself")),
            Some(_) => {}
        }
    }
    out
}
/// Elements that are the items of a list the document holds: the tag, the document field (its node), the port of that
/// node that holds the list, the definition each item is checked against (`threed_schema()` `$defs`), and its kind.
/// Several tags may make one list: the kind then names its items, each tag is its item's `type` (`note()` is
/// `{"type": "note", …}`), and the items are in the order their elements are written, whatever their tags.
pub const THREED_LISTS: &[(&str, &str, &str, &str, Option<&str>)] =
    &[
        ("joint", "dynamics", "joints", "DynamicsJoint", None),
        ("contact", "dynamics", "contacts", "DynamicsContact", None),
        ("mate", "assembly", "mates", "Mate", None),
        ("sheet", "drawings", "value", "DrawingSheet", None),
        ("check", "checks", "value", "DesignCheck", None),
        ("accept", "accepted", "value", "AcceptedFinding", None),
        ("permitted", "permitted", "value", "PermittedFinding", None),
        ("fastener", "fasteners", "value", "FastenerStack", None),
        ("tactile", "tactile", "value", "TactileSkin", None),
        ("port", "ports", "value", "Port", None),
        ("item", "items", "value", "ProductItem", None),
        ("assemble", "assemblySteps", "value", "AssemblyStep", None),
        ("library", "library", "value", "LibraryData", None),
        ("product", "products", "value", "ProductFacts", None),
        ("unit", "placements", "value", "PlacedUnit", None),
        ("capture", "captures", "value", "PlacedCapture", None),
        ("view", "views", "value", "NamedView", None),
        ("linearDimension", "annotations", "value", "LinearDimension", Some("annotation")),
        ("radialDimension", "annotations", "value", "RadialDimension", Some("annotation")),
        ("sizeDimension", "annotations", "value", "SizeDimension", Some("annotation")),
        ("angularDimension", "annotations", "value", "AngularDimension", Some("annotation")),
        ("note", "annotations", "value", "Note", Some("annotation")),
        ("datumFeature", "annotations", "value", "DatumFeature", Some("annotation")),
        ("datumTarget", "annotations", "value", "DatumTarget", Some("annotation")),
        ("featureControlFrame", "annotations", "value", "FeatureControlFrame", Some("annotation")),
        ("surfaceFinish", "annotations", "value", "SurfaceFinish", Some("annotation")),
    ];
/// The annotations of a 3D document, by tag: each tag is its annotation's `type` (`3d-core/annotations.ts`).
pub const THREED_ANNOTATIONS: &[&str] =
    &["linearDimension", "radialDimension", "sizeDimension", "angularDimension", "note", "datumFeature", "datumTarget", "featureControlFrame", "surfaceFinish"];
/// Tags with a meaning of their own: never a `feature().type_(…)`.
const NOT_FEATURES: &[&str] = &[
    "feature", "part", "assembly", "parameter", "plane", "body", "slot", "joint", "contact", "mate", "sheet", "check", "accept", "permitted", "fastener", "tactile", "port", "item", "assemble", "library", "product", "unit", "capture", "view", "point", "constraint",
    "projection", "equation", "text", "line", "circle", "arc", "spline", "ellipse", "ellipseArc", "input", "linearDimension", "radialDimension", "sizeDimension",
    "angularDimension", "note", "datumFeature", "datumTarget", "featureControlFrame", "surfaceFinish",
];
/// A sketch's segment kinds, by tag.
pub const SKETCH_SEGMENTS: &[&str] = &["line", "circle", "arc", "spline", "ellipse", "ellipseArc"];
/// The datum planes every 3D document has (`3d-core/document.ts` basePlanes): id, name, origin, normal, xAxis, builtin.
pub const BUILTIN_PLANES: &[(&str, &str, [f64; 3], [f64; 3], [f64; 3], &str)] = &[
    ("plane_xy", "Top (XY)", [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], "XY"),
    ("plane_xz", "Front (XZ)", [0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0], "XZ"),
    ("plane_yz", "Right (YZ)", [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], "YZ"),
];
/// The document's view fields a root element may hold (the graph's `meta`), beside `name`.
const VIEW_ATTRS: &[&str] = &["semanticVisibility"];
const PARAM_FIELDS: &[&str] = &["value", "expression", "unit", "comment", "min", "max", "step", "tolerance"];
/// Document fields a slot may not hold: they have elements of their own, or are the graph itself.
const NOT_SLOTS: &[&str] = &[
    "id", "name", "units", "planes", "features", "parameters", "presentation", "isAssembly", "bodyMeta", "semanticVisibility", "drawings", "checks",
    "accepted", "permitted", "fasteners", "tactile", "ports", "items", "assemblySteps", "library", "products", "placements", "captures", "views", "annotations",
];
/// Slots whose value is an object: each field is a port of the slot's node; any other slot holds its value whole.
const OBJECT_SLOTS: &[&str] = &["environment", "assembly", "sceneConstraints", "dynamics", "animation", "optimization", "standardParts"];

/// Whether a root is a 3D document: one `part` or `assembly`.
pub fn is_threed(root: &El) -> bool {
    root.tag == "part" || root.tag == "assembly"
}

/// How a message names an element: `sketch().id("sketch1")`, `slot().name("environment")`, `box_()`.
fn at(el: &El) -> String {
    for k in ["id", "name"] {
        if let Some(v @ Json::Str(_)) = el.attr_of(k) {
            return format!("{}().{k}({})", fn_name(el.tag), v.text());
        }
    }
    format!("{}()", fn_name(el.tag))
}

/// A number as JavaScript writes it in a message.
fn js_number(n: f64) -> String {
    if n.is_nan() {
        "NaN".into()
    } else if n.is_infinite() {
        if n > 0.0 { "Infinity".into() } else { "-Infinity".into() }
    } else {
        Json::Num(n).text()
    }
}

/// A value is plain data with finite numbers.
fn plain(v: &Json, what: &str) -> Result<(), String> {
    match v {
        Json::Num(n) if !n.is_finite() => Err(format!("{what} is {}, not a finite number", js_number(*n))),
        Json::Arr(items) => items.iter().enumerate().try_for_each(|(i, x)| plain(x, &format!("{what}[{i}]"))),
        Json::Obj(entries) => entries.iter().try_for_each(|(k, x)| plain(x, &format!("{what}.{k}"))),
        _ => Ok(()),
    }
}

/// The element's attributes as fields, without the names in `skip`, each plain data.
fn fields(el: &El, skip: &[&str]) -> Result<Vec<(String, Json)>, String> {
    let mut out = Vec::new();
    for (k, v) in &el.attrs {
        if skip.contains(&k.as_str()) {
            continue;
        }
        plain(v, &format!("{} {}", at(el), rust_name(k)))?;
        out.push((k.clone(), v.clone()));
    }
    Ok(out)
}

fn take(fields: &mut Vec<(String, Json)>, name: &str) -> Option<Json> {
    fields.iter().position(|(k, _)| k == name).map(|i| fields.remove(i).1)
}

fn word_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_'
}

/// An id: letters, digits, `_ . -`, with `/` between them (a merged code part's features are `<code id>/<id>`).
fn id_ok(id: &str) -> bool {
    id.split('/').all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')))
}

fn id_of(el: &El) -> Result<String, String> {
    match el.attr_of("id") {
        Some(Json::Str(id)) if !id.is_empty() => {
            if !id_ok(id) {
                return Err(format!("{}: an id is letters, digits, _ . - with / between them ({})", at(el), Json::from(id.as_str()).text()));
            }
            Ok(id.clone())
        }
        _ => Err(format!("{} needs an id", at(el))),
    }
}

fn no_children(el: &El) -> Result<(), String> {
    if el.child_elements().next().is_some() {
        return Err(format!("{} has no child elements", at(el)));
    }
    Ok(())
}

fn source_meta(el: &El) -> Option<Json> {
    el.source_json().map(|s| Json::obj().with("source", s))
}

fn keys(entries: &[(String, Json)]) -> Json {
    Json::Arr(entries.iter().map(|(k, _)| Json::from(k.as_str())).collect())
}

/// The sketch a sketch element's children declare, and where each entity was written.
fn sketch_of(el: &El) -> Result<(Json, Sources), String> {
    let (mut points, mut segments, mut constraints, mut projections) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
    let (mut equations, mut texts): (Vec<(String, Json)>, Vec<(String, Json)>) = (Vec::new(), Vec::new());
    let mut sources = Sources::new();
    let mut taken: Vec<String> = Vec::new();
    for child in el.child_elements() {
        let mut claim = |kind: &str| -> Result<String, String> {
            let id = id_of(child)?;
            if taken.contains(&id) {
                return Err(format!("{}: two entities are called {id}", at(el)));
            }
            taken.push(id.clone());
            sources.put(format!("{kind}:{id}"), child);
            no_children(child)?;
            Ok(id)
        };
        if child.tag == "point" {
            let id = claim("point")?;
            let f = fields(child, &[])?;
            let num = |k: &str| matches!(f.iter().find(|(n, _)| n == k), Some((_, Json::Num(_))));
            if !num("x") || !num("y") {
                return Err(format!("{} {}: a point has x and y (mm)", at(el), at(child)));
            }
            points.push((id, Json::Obj(f)));
        } else if SKETCH_SEGMENTS.contains(&child.tag) {
            let id = claim("segment")?;
            if child.attr_of("type").is_some() {
                return Err(format!("{} {}: the tag is the segment's type", at(el), at(child)));
            }
            let mut s = vec![("id".to_string(), Json::from(id.as_str())), ("type".to_string(), Json::from(child.tag))];
            s.extend(fields(child, &["id"])?);
            segments.push((id, Json::Obj(s)));
        } else if child.tag == "constraint" {
            let id = claim("constraint")?;
            let f = fields(child, &[])?;
            let get = |k: &str| f.iter().find(|(n, _)| n == k).map(|(_, v)| v);
            if !matches!(get("kind"), Some(Json::Str(_))) || !matches!(get("entities"), Some(Json::Arr(_))) {
                return Err(format!("{} {}: a constraint has a kind and its entities", at(el), at(child)));
            }
            constraints.push((id, Json::Obj(f)));
        } else if child.tag == "projection" {
            let id = claim("projection")?;
            projections.push((id, Json::Obj(fields(child, &[])?)));
        } else if child.tag == "equation" {
            let id = claim("equation")?;
            let f = fields(child, &[])?;
            let get = |k: &str| f.iter().find(|(n, _)| n == k).map(|(_, v)| v);
            let num = |k: &str| matches!(get(k), Some(Json::Num(_)));
            if !matches!(get("x"), Some(Json::Str(_))) || !matches!(get("y"), Some(Json::Str(_))) || !num("from") || !num("to") || !num("points") {
                return Err(format!("{} {}: an equation curve has x and y (arithmetic of t), from, to and points", at(el), at(child)));
            }
            let mut e = vec![("id".to_string(), Json::from(id.as_str()))];
            e.extend(f);
            equations.push((id, Json::Obj(e)));
        } else if child.tag == "text" {
            let id = claim("text")?;
            let f = fields(child, &[])?;
            let get = |k: &str| f.iter().find(|(n, _)| n == k).map(|(_, v)| v);
            if !matches!(get("text"), Some(Json::Str(_))) || !matches!(get("anchor"), Some(Json::Str(_))) || !matches!(get("along"), Some(Json::Str(_))) || !matches!(get("contours"), Some(Json::Arr(_))) {
                return Err(format!("{} {}: a text has its words, its anchor and along points and its contours", at(el), at(child)));
            }
            let mut e = vec![("id".to_string(), Json::from(id.as_str()))];
            e.extend(f);
            texts.push((id, Json::Obj(e)));
        } else {
            let segs: Vec<String> = SKETCH_SEGMENTS.iter().map(|s| fn_name(s)).collect();
            return Err(format!("{}: {}() is not read in a sketch (point, {}, constraint, projection, equation, text)", at(el), fn_name(child.tag), segs.join(", ")));
        }
    }
    for (id, s) in &segments {
        for k in ["a", "b", "center", "start", "end", "focus"] {
            if let Some(p) = s.get(k) {
                if !p.as_str().is_some_and(|p| points.iter().any(|(q, _)| q == p)) {
                    return Err(format!("{}: segment {id}'s {k} names no point of the sketch ({})", at(el), p.text()));
                }
            }
        }
    }
    let mut sketch = Json::obj()
        .with("points", Json::Obj(points.clone()))
        .with("segments", Json::Obj(segments.clone()))
        .with("constraints", Json::Obj(constraints.clone()))
        .with("pointOrder", keys(&points))
        .with("segmentOrder", keys(&segments))
        .with("constraintOrder", keys(&constraints));
    if !projections.is_empty() {
        sketch.set("projectionOrder", keys(&projections));
        // `projections` stands before `projectionOrder`, as TypeScript sets them.
        if let Json::Obj(entries) = &mut sketch {
            let at = entries.len() - 1;
            entries.insert(at, ("projections".into(), Json::Obj(projections)));
        }
    }
    for (group, order, list) in [("equations", "equationOrder", equations), ("texts", "textOrder", texts)] {
        if list.is_empty() {
            continue;
        }
        if group == "texts" {
            for (id, t) in &list {
                for k in ["anchor", "along"] {
                    let p = t.get(k).and_then(|p| p.as_str());
                    if !p.is_some_and(|p| points.iter().any(|(q, _)| q == p)) {
                        return Err(format!("{}: text {id}'s {k} names no point of the sketch", at(el)));
                    }
                }
            }
        }
        sketch.set(order, keys(&list));
        if let Json::Obj(entries) = &mut sketch {
            let at = entries.len() - 1;
            entries.insert(at, (group.into(), Json::Obj(list)));
        }
    }
    Ok((sketch, sources))
}

/// The built-in planes a root says the document has (`builtin_planes`); absent: all three.
fn builtin_planes_of(root: &El) -> Result<Vec<&'static str>, String> {
    let all: Vec<&'static str> = BUILTIN_PLANES.iter().map(|p| p.0).collect();
    let Some(v) = root.attr_of("builtinPlanes") else { return Ok(all) };
    let refused = || format!("{}: builtin_planes lists built-in planes ({})", at(root), all.join(", "));
    let Json::Arr(items) = v else { return Err(refused()) };
    let mut out = Vec::new();
    for x in items {
        let p = x.as_str().and_then(|s| all.iter().find(|a| **a == s).copied()).ok_or_else(refused)?;
        if out.contains(&p) {
            return Err(format!("{}: builtin_planes names a plane twice", at(root)));
        }
        out.push(p);
    }
    Ok(out)
}

/// The left-hand list: the order of the feature calls, the root's `groups` (named bands of features, each
/// `{ id, name, members, collapsed? }`) and its `rollback` (the feature the history is rolled back to). A member or a
/// rollback that names no feature is refused by name.
fn presentation_of(root: &El, order: Vec<Json>) -> Result<Option<Json>, String> {
    let features: Vec<String> = order.iter().filter_map(|j| j.as_str().map(String::from)).collect();
    let mut out = Json::obj();
    let mut any = false;
    if !order.is_empty() {
        out.set("order", order);
        any = true;
    }
    if let Some(groups) = root.attr_of("groups") {
        let Json::Arr(items) = groups else { return Err(format!("{} groups: a list of {{ id, name, members, collapsed? }}", at(root))) };
        let mut made = Vec::new();
        for (i, g) in items.iter().enumerate() {
            let here = format!("{} groups[{i}]", at(root));
            let (Some(Json::Str(id)), Some(Json::Str(name)), Some(Json::Arr(members))) = (g.get("id"), g.get("name"), g.get("members")) else {
                return Err(format!("{here}: a group is {{ id, name, members, collapsed? }}"));
            };
            if id.is_empty() {
                return Err(format!("{here}: a group is {{ id, name, members, collapsed? }}"));
            }
            for m in members {
                if !m.as_str().is_some_and(|m| features.iter().any(|f| f == m)) {
                    return Err(format!("{here}: member {} is not a feature of this document", m.text()));
                }
            }
            let mut group = Json::obj().with("id", id.as_str()).with("name", name.as_str()).with("members", Json::Arr(members.clone()));
            if matches!(g.get("collapsed"), Some(Json::Bool(true))) {
                group.set("collapsed", true);
            }
            made.push(group);
        }
        out.set("groups", Json::Arr(made));
        any = true;
    }
    if let Some(rollback) = root.attr_of("rollback") {
        match rollback.as_str() {
            Some(r) if features.iter().any(|f| f == r) => {
                out.set("rollback", r);
                any = true;
            }
            _ => return Err(format!("{} rollback: {} is not a feature of this document", at(root), rollback.text())),
        }
    }
    Ok(if any { Some(out) } else { None })
}

fn declare(root: El) -> Result<Declared, String> {
    declare_threed(&root, &super::source::stem().unwrap_or_else(|| "Part".into())).map(Declared::Graph)
}

/// The graph a part or assembly element declares: an op graph whose nodes are its parameters, planes, features and
/// slots (docs/formats.md § the 3D document's body).
pub fn declare_threed(root: &El, fallback_name: &str) -> Result<Json, String> {
    if !is_threed(root) {
        return Err("a 3D document is one part() or assembly() element".into());
    }
    for (k, _) in &root.attrs {
        if !["name", "id", "builtinPlanes", "groups", "rollback"].contains(&k.as_str()) && !VIEW_ATTRS.contains(&k.as_str()) {
            return Err(format!("{}: {} is not read on a 3D document", at(root), rust_name(k)));
        }
    }
    let builtins = builtin_planes_of(root)?;
    let name = match root.attr_of("name") {
        Some(Json::Str(n)) if !n.is_empty() => n.clone(),
        _ => fallback_name.to_string(),
    };
    let mut nodes: Vec<(String, Json)> = Vec::new();
    let mut owner: Vec<(String, String)> = Vec::new();
    fn claim(owner: &mut Vec<(String, String)>, id: &str, what: String) -> Result<(), String> {
        if let Some((_, prev)) = owner.iter().find(|(o, _)| o == id) {
            return Err(format!("the id \"{id}\" is both {prev} and {what}; a node id is used once"));
        }
        owner.push((id.to_string(), what));
        Ok(())
    }
    let node = |id: &str, kind: &str, label: Option<&str>, inputs: Json, meta: Option<Json>| {
        let mut n = Json::obj().with("id", id).with("type", kind);
        if let Some(l) = label {
            n.set("label", l);
        }
        n.set("inputs", inputs);
        if let Some(m) = meta {
            n.set("meta", m);
        }
        n
    };
    let mut order: Vec<Json> = Vec::new();
    let mut bodies: Vec<(String, Json)> = Vec::new();
    let mut body_sources = Sources::new();
    let mut declared: Vec<&El> = Vec::new();
    let mut lists: Vec<(usize, Vec<Json>, Sources)> = Vec::new();
    // Every element is read, and every one refused is named together: a file with ten mistakes needs one run, not ten.
    let mut refused: Vec<String> = Vec::new();
    for el in root.child_elements() {
        let read = (|| -> Result<(), String> {
            match el.tag {
                "parameter" => {
                    no_children(el)?;
                    let pname = match el.attr_of("name") {
                        Some(Json::Str(p)) if !p.is_empty() && slug(p) == *p => p.clone(),
                        _ => return Err(format!("{} needs a name (letters, digits, _ . -)", at(el))),
                    };
                    for (k, _) in &el.attrs {
                        if !["name", "bindings"].contains(&k.as_str()) && !PARAM_FIELDS.contains(&k.as_str()) {
                            return Err(format!("{}: {} is not read on a parameter", at(el), rust_name(k)));
                        }
                    }
                    if !matches!(el.attr_of("value"), Some(Json::Num(_))) {
                        return Err(format!("{}: value is a number", at(el)));
                    }
                    if let Some(tol) = el.attr_of("tolerance") {
                        if let Some(problem) = super::tolerances::tolerance_problem(tol) {
                            return Err(format!("{}: tolerance: {problem}", at(el)));
                        }
                    }
                    claim(&mut owner, &pname, format!("parameter \"{pname}\""))?;
                    let mut inputs = fields(el, &["name", "bindings"])?;
                    let bindings = match el.attr_of("bindings") {
                        None => Json::Arr(Vec::new()),
                        Some(b) => {
                            plain(b, &format!("{} bindings", at(el)))?;
                            b.clone()
                        }
                    };
                    let ok = match &bindings {
                        Json::Arr(list) => list.iter().all(|b| matches!(b.get("target"), Some(Json::Str(_))) && matches!(b.get("field"), Some(Json::Str(_)))),
                        _ => false,
                    };
                    if !ok {
                        return Err(format!("{}: bindings are [{{ target, field }}]", at(el)));
                    }
                    if matches!(&bindings, Json::Arr(l) if !l.is_empty()) {
                        inputs.retain(|(k, _)| k != "drives");
                        inputs.push(("drives".into(), bindings));
                    }
                    nodes.push((pname.clone(), node(&pname, "input", Some(&pname), Json::Obj(inputs), source_meta(el))));
                }
                "plane" => {
                    no_children(el)?;
                    let id = id_of(el)?;
                    claim(&mut owner, &id, format!("plane \"{id}\""))?;
                    let mut rest = fields(el, &["id"])?;
                    let label = take(&mut rest, "name");
                    nodes.push((id.clone(), node(&id, "plane", label.as_ref().and_then(Json::as_str), Json::Obj(rest), source_meta(el))));
                }
                "body" => {
                    no_children(el)?;
                    let id = id_of(el)?;
                    if bodies.iter().any(|(b, _)| *b == id) {
                        return Err(format!("two body() elements are called {id}"));
                    }
                    let mut body = fields(el, &["id"])?;
                    for (k, v) in body.iter_mut() {
                        if k == "engineering" {
                            *v = check_value(el, "PartEngineering", v, "engineering")?;
                        }
                        if k == "material" {
                            *v = check_value(el, "BodyMaterial", v, "material")?;
                        }
                    }
                    bodies.push((id.clone(), Json::Obj(body)));
                    body_sources.put(id, el);
                }
                t if THREED_LISTS.iter().any(|l| l.0 == t) => {
                    no_children(el)?;
                    let id = id_of(el)?;
                    let row = THREED_LISTS.iter().position(|l| l.0 == t).unwrap_or_default();
                    let (_, node, port, def, kind) = THREED_LISTS[row];
                    // Each list by its node and port: the tags that share one (the annotations) fill it in the order written.
                    if !lists.iter().any(|l| THREED_LISTS[l.0].1 == node && THREED_LISTS[l.0].2 == port) {
                        lists.push((row, Vec::new(), Sources::new()));
                    }
                    let Some(held) = lists.iter_mut().find(|l| THREED_LISTS[l.0].1 == node && THREED_LISTS[l.0].2 == port) else { return Ok(()) };
                    if held.1.iter().any(|x| x.get("id").and_then(Json::as_str) == Some(id.as_str())) {
                        return Err(match kind {
                            Some(k) => format!("two {k}s are called {id}"),
                            None => format!("two {}() elements are called {id}", fn_name(t)),
                        });
                    }
                    let mut said = fields(el, &[])?;
                    if let Some(k) = kind {
                        if el.attr_of("type").is_some() {
                            return Err(format!("{}: the tag is the {k}'s type", at(el)));
                        }
                        said.insert(0, ("type".into(), Json::from(t)));
                    }
                    let item = check_value(el, def, &Json::Obj(said), "")?;
                    if t == "sheet" {
                        let problems = sheet_view_problems(&item);
                        if !problems.is_empty() {
                            return Err(format!("{}: {}", at(el), problems.join("; ")));
                        }
                    }
                    held.1.push(item);
                    held.2.put(format!("{}:{id}", kind.unwrap_or(t)), el);
                }
                "slot" => {
                    no_children(el)?;
                    let field = match el.attr_of("name") {
                        Some(Json::Str(f)) if f.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && f.chars().all(word_char) => f.clone(),
                        _ => return Err(format!("{} needs the name of a document field", at(el))),
                    };
                    if NOT_SLOTS.contains(&field.as_str()) {
                        let tags: Vec<String> = THREED_LISTS.iter().filter(|l| l.1 == field && l.2 == "value").map(|l| format!("{}()", fn_name(l.0))).collect();
                        let said = if tags.is_empty() { "(it has its own element or attribute)".to_string() } else { format!("(its items are written as their own elements: {})", tags.join(", ")) };
                        return Err(format!("{}: {field} is not a slot {said}", at(el)));
                    }
                    for (k, _) in &el.attrs {
                        if k != "name" && k != "value" {
                            return Err(format!("{}: {} is not read on a slot (its value is value)", at(el), rust_name(k)));
                        }
                    }
                    claim(&mut owner, &field, format!("the document's {field}"))?;
                    // An absent value is `undefined` in TypeScript, which the node's JSON leaves out.
                    let value = el.attr_of("value").cloned();
                    if let Some(v) = &value {
                        plain(v, &format!("{} value", at(el)))?;
                    }
                    let inputs = if OBJECT_SLOTS.contains(&field.as_str()) {
                        match &value {
                            Some(v @ Json::Obj(_)) => {
                                if let Some(l) = THREED_LISTS.iter().find(|l| l.1 == field && v.get(l.2).is_some()) {
                                    return Err(format!("{}: {} are written as {}() elements", at(el), l.2, fn_name(l.0)));
                                }
                                v.clone()
                            }
                            _ => return Err(format!("{}: the document's {field} is an object", at(el))),
                        }
                    } else {
                        match value {
                            Some(v) => Json::obj().with("value", v),
                            None => Json::obj(),
                        }
                    };
                    nodes.push((field.clone(), node(&field, &format!("3d.{field}"), None, inputs, source_meta(el))));
                }
                t if THREED_FEATURES.contains(&t) => declared.push(el),
                "feature" => {
                    let t = match el.attr_of("type") {
                        Some(Json::Str(t))
                            if t.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && t.chars().all(|c| word_char(c) || c == '.' || c == '-') =>
                        {
                            t.clone()
                        }
                        _ => return Err(format!("{} needs the feature's type", at(el))),
                    };
                    if THREED_FEATURES.contains(&t.as_str()) || NOT_FEATURES.contains(&t.as_str()) {
                        return Err(format!("{}: a {t} is written {}(…)", at(el), fn_name(&t)));
                    }
                    declared.push(el);
                }
                "part" | "assembly" => {
                    return Err(format!("{}() is a document of its own: place its file with external_part() (file_name, importer \"3d\"; its bodies keep their names under the placement)", fn_name(el.tag)))
                }
                _ => return Err(format!("{}() is not read in a 3D document (see commandagi::design::threed)", fn_name(el.tag))),
            }
            Ok(())
        })();
        if let Err(e) = read {
            refused.push(e);
        }
    }
    for el in declared {
        let read = (|| -> Result<(), String> {
            let id = id_of(el)?;
            claim(&mut owner, &id, format!("feature \"{id}\""))?;
            let generic = el.tag == "feature";
            if !generic && el.attr_of("type").is_some() {
                return Err(format!("{}: the tag is the feature's type", at(el)));
            }
            let kind = if generic { el.attr_of("type").and_then(Json::as_str).unwrap_or_default().to_string() } else { el.tag.to_string() };
            let mut rest = fields(el, if generic { &["id", "type"] } else { &["id"] })?;
            let label = take(&mut rest, "name");
            let suppressed = take(&mut rest, "suppressed");
            if suppressed.as_ref().is_some_and(|s| !matches!(s, Json::Bool(_))) {
                return Err(format!("{}: suppressed is true or false", at(el)));
            }
            let mut inputs = rest;
            let mut sources = Sources::new();
            if el.tag == "sketch" {
                if inputs.iter().any(|(k, _)| k == "sketch") {
                    return Err(format!("{}: a sketch's points, segments and constraints are its child elements", at(el)));
                }
                let (sketch, s) = sketch_of(el)?;
                inputs.push(("sketch".into(), sketch));
                sources = s;
            }
            // A hole that names a standard size ("M4 close fit") has that size's diameter and head (standards.rs).
            if el.tag == "hole" && inputs.iter().any(|(k, v)| k == "size" && matches!(v, Json::Str(_))) {
                if let Json::Obj(sized) = sized_hole(&Json::Obj(inputs.clone())).map_err(|e| format!("{}: {e}", at(el)))? {
                    inputs = sized;
                }
            }
            if !generic {
                let mut feature = vec![("type".to_string(), Json::from(kind.as_str())), ("id".to_string(), Json::from(id.as_str()))];
                feature.push(("name".into(), label.clone().unwrap_or_else(|| Json::from(id.as_str()))));
                if let Some(s) = &suppressed {
                    feature.push(("suppressed".into(), s.clone()));
                }
                feature.extend(inputs.iter().cloned());
                if let Json::Obj(filled) = check_feature(el, Json::Obj(feature))? {
                    inputs = filled.into_iter().filter(|(k, _)| !matches!(k.as_str(), "type" | "id" | "name" | "suppressed")).collect();
                }
            }
            if el.tag != "sketch" {
                no_children(el)?;
                if el.tag == "code" {
                    // A code feature's `inputs` are ports of its node, beside `source`, `host` and `consumes` (the document graph's rule).
                    let code_inputs = take(&mut inputs, "inputs");
                    if code_inputs.as_ref().is_some_and(|c| !matches!(c, Json::Obj(_))) {
                        return Err(format!("{}: inputs is an object", at(el)));
                    }
                    if let Some((k, _)) = inputs.iter().find(|(k, _)| k != "source" && k != "host" && k != "consumes") {
                        return Err(format!("{}: a code feature has source, inputs, host and consumes, not {}", at(el), rust_name(k)));
                    }
                    if let Some(Json::Obj(entries)) = code_inputs {
                        for (k, v) in entries {
                            inputs.retain(|(n, _)| *n != k);
                            inputs.push((k, v));
                        }
                    }
                }
            }
            let mut n = Json::obj().with("id", id.as_str()).with("type", kind.as_str());
            n.set("label", match &label {
                Some(Json::Str(l)) => l.as_str(),
                _ => id.as_str(),
            });
            if let Some(s) = suppressed {
                n.set("disabled", s);
            }
            n.set("inputs", Json::Obj(inputs));
            let mut meta = Json::obj();
            if let Some(s) = el.source_json() {
                meta.set("source", s);
            }
            if !sources.is_empty() {
                meta.set("sources", sources.json());
            }
            if meta != Json::obj() {
                n.set("meta", meta);
            }
            nodes.push((id.clone(), n));
            order.push(Json::from(id.as_str()));
            Ok(())
        })();
        if let Err(e) = read {
            refused.push(e);
        }
    }
    if !refused.is_empty() {
        return Err(refused.join("\n"));
    }
    for (id, label, origin, normal, x_axis, builtin) in BUILTIN_PLANES {
        if owner.iter().any(|(o, _)| o == id) || !builtins.contains(id) {
            continue;
        }
        let v3 = |v: &[f64; 3]| Json::Arr(v.iter().map(|n| Json::Num(*n)).collect());
        let inputs = Json::obj().with("origin", v3(origin)).with("normal", v3(normal)).with("xAxis", v3(x_axis)).with("builtin", *builtin);
        nodes.push((id.to_string(), node(id, "plane", Some(label), inputs, None)));
    }
    for (row, items, sources) in lists {
        let (tag, field, port, _, _) = THREED_LISTS[row];
        if !nodes.iter().any(|(id, _)| id == field) {
            claim(&mut owner, field, format!("the document's {field} ({}())", fn_name(tag)))?;
            nodes.push((field.to_string(), node(field, &format!("3d.{field}"), None, Json::obj(), None)));
        }
        let Some((_, n)) = nodes.iter_mut().find(|(id, _)| id == field) else { continue };
        let mut inputs = n.get("inputs").cloned().unwrap_or_else(Json::obj);
        inputs.set(port, Json::Arr(items));
        n.set("inputs", inputs);
        if !sources.is_empty() {
            let mut meta = n.get("meta").cloned().unwrap_or_else(Json::obj);
            let mut all = meta.get("sources").cloned().unwrap_or_else(Json::obj);
            if let Json::Obj(entries) = sources.json() {
                for (k, v) in entries {
                    all.set(&k, v);
                }
            }
            meta.set("sources", all);
            n.set("meta", meta);
        }
    }
    if !bodies.is_empty() {
        claim(&mut owner, "bodyMeta", "the bodies (body())".into())?;
        let meta = (!body_sources.is_empty()).then(|| Json::obj().with("sources", body_sources.json()));
        nodes.push(("bodyMeta".into(), node("bodyMeta", "3d.bodyMeta", None, Json::Obj(bodies), meta)));
    }
    let mut view = Json::obj().with("name", name.as_str()).with("units", "mm");
    for k in VIEW_ATTRS {
        if let Some(v) = root.attr_of(k) {
            plain(v, &format!("{} {}", at(root), rust_name(k)))?;
            view.set(k, v.clone());
        }
    }
    if root.tag == "assembly" {
        view.set("isAssembly", true);
    }
    if let Some(presentation) = presentation_of(root, order)? {
        view.set("presentation", presentation);
    }
    let id = match root.attr_of("id") {
        Some(Json::Str(i)) if !i.is_empty() => i.clone(),
        _ => format!("3d-{}", slug(&name).to_lowercase()),
    };
    Ok(Json::obj().with("id", id.as_str()).with("nodes", Json::Obj(nodes)).with("meta", view))
}