@rulecad/cad 0.7.25 → 0.7.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/EXAMPLES.md ADDED
@@ -0,0 +1,386 @@
1
+ # Worked examples: from parts to a mechanism
2
+
3
+ [The tutorial](TUTORIAL.md) ends with a wall hook checked against its screw. These examples carry on from there, one
4
+ for each thing the [README](README.md) describes after that: parts, variants and releases, joints and poses, a model
5
+ from elsewhere, an optimised part, a board, and a mechanism printed flat. Each is a few files and the commands to run
6
+ them. The tests write every file here and run every command, so what you read is what works.
7
+
8
+ They start from a workspace `npm create rulecad my-designs` makes, as the tutorial does, and run in order: later
9
+ examples use earlier files where it saves repeating them.
10
+
11
+ ## 1. Parts: a support that breaks away, and a second filament
12
+
13
+ A tag with a raised legend on top, printed as one object in two filaments, standing on a breakaway brim. `main`
14
+ returns named parts; the `.json` says what each is for.
15
+
16
+ ```json projects/home/objects/tag.json
17
+ {
18
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
19
+ "name": "tag",
20
+ "title": "Name tag",
21
+ "version": "0.1.0",
22
+ "uses": ["x1c"],
23
+ "material": "PLA",
24
+ "orientation": "Flat, legend up, on a brim that snaps off",
25
+ "parts": {
26
+ "base": { "label": "Tag" },
27
+ "legend": { "label": "Raised legend", "filament": "legend" },
28
+ "brim": { "role": "support", "label": "Breakaway brim" }
29
+ },
30
+ "variables": {
31
+ "length": { "value": 50, "unit": "mm", "rule": "Room for a short name", "label": "Length", "show": true, "tweak": { "min": 30, "max": 90 } },
32
+ "width": { "value": 20, "unit": "mm", "rule": "Two lines of text", "label": "Width", "show": true },
33
+ "thick": { "value": "x1c.layer * 8", "unit": "mm", "rule": "Eight layers: stiff enough to pin to a coat" },
34
+ "raise": { "value": "x1c.layer * 3", "unit": "mm", "rule": "The legend stands three layers proud, so the second filament has layers of its own" },
35
+ "inset": { "value": "x1c.line * 4", "unit": "mm", "rule": "The legend's border, in from the edge" },
36
+ "brim": { "value": 4, "unit": "mm", "rule": "A brim this wide holds a thin tag flat while it prints" },
37
+ "brim_gap": { "value": "x1c.support_gap", "unit": "mm", "rule": "The gap a breakaway support leaves, so it snaps off" }
38
+ }
39
+ }
40
+ ```
41
+
42
+ The brim is a frame round the tag one layer tall, a support gap below the tag's edge; the check knows a `support`
43
+ part is printed and removed, so the tag resting on it is not an overhang.
44
+
45
+ ```js projects/home/objects/tag.js
46
+ // A name tag: a slab, a raised legend in a second filament, on a breakaway brim.
47
+ import jscad from '@jscad/modeling'
48
+ const { cuboid } = jscad.primitives
49
+ const { subtract } = jscad.booleans
50
+
51
+ export function main (v) {
52
+ const base = cuboid({ size: [v.length, v.width, v.thick], center: [0, 0, v.thick / 2] })
53
+ const legend = cuboid({ size: [v.length - 2 * v.inset, v.width - 2 * v.inset, v.raise], center: [0, 0, v.thick + v.raise / 2] })
54
+ const ring = subtract(cuboid({ size: [v.length + 2 * v.brim, v.width + 2 * v.brim, v.thick], center: [0, 0, v.thick / 2] }), cuboid({ size: [v.length - 2 * v.brim, v.width - 2 * v.brim, v.thick], center: [0, 0, v.thick / 2] }))
55
+ const brim = subtract(ring, cuboid({ size: [v.length + 2 * v.brim, v.width + 2 * v.brim, v.thick], center: [0, 0, v.thick / 2 + v.brim_gap + v.x1c.layer] }))
56
+ return { base, legend, brim }
57
+ }
58
+ ```
59
+
60
+ The second filament is named in the project: a slot in the AMS.
61
+
62
+ ```json projects/home/project.json
63
+ {
64
+ "name": "home",
65
+ "title": "Things for the house",
66
+ "printer": "x1c",
67
+ "filaments": { "base": { "slot": 1 }, "legend": { "slot": 2 } }
68
+ }
69
+ ```
70
+
71
+ ```sh
72
+ npx cad check home/tag
73
+ npx cad export home/tag
74
+ ```
75
+
76
+ The print file groups the three parts as one object, the legend on its own slot, the brim marked as support.
77
+
78
+ ## 2. Variants, then a release
79
+
80
+ A variant is a named set of inputs, kept beside the design rather than as a copy: a long tag next to the standard
81
+ one, a short one beside it. They are `variants` entries in the `.json` (values a variable's `tweak` range allows),
82
+ built as `home/tag:long`.
83
+
84
+ ```json projects/home/objects/tag.json
85
+ {
86
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
87
+ "name": "tag",
88
+ "title": "Name tag",
89
+ "version": "0.1.0",
90
+ "uses": ["x1c"],
91
+ "material": "PLA",
92
+ "orientation": "Flat, legend up, on a brim that snaps off",
93
+ "parts": {
94
+ "base": { "label": "Tag" },
95
+ "legend": { "label": "Raised legend", "filament": "legend" },
96
+ "brim": { "role": "support", "label": "Breakaway brim" }
97
+ },
98
+ "variants": { "long": { "length": 80 }, "short": { "length": 35 } },
99
+ "variables": {
100
+ "length": { "value": 50, "unit": "mm", "rule": "Room for a short name", "label": "Length", "show": true, "tweak": { "min": 30, "max": 90 } },
101
+ "width": { "value": 20, "unit": "mm", "rule": "Two lines of text", "label": "Width", "show": true },
102
+ "thick": { "value": "x1c.layer * 8", "unit": "mm", "rule": "Eight layers: stiff enough to pin to a coat" },
103
+ "raise": { "value": "x1c.layer * 3", "unit": "mm", "rule": "The legend stands three layers proud, so the second filament has layers of its own" },
104
+ "inset": { "value": "x1c.line * 4", "unit": "mm", "rule": "The legend's border, in from the edge" },
105
+ "brim": { "value": 4, "unit": "mm", "rule": "A brim this wide holds a thin tag flat while it prints" },
106
+ "brim_gap": { "value": "x1c.support_gap", "unit": "mm", "rule": "The gap a breakaway support leaves, so it snaps off" }
107
+ }
108
+ }
109
+ ```
110
+
111
+ ```sh
112
+ npx cad variants home/tag
113
+ npx cad check home/tag:long
114
+ npx cad compare home/tag short long
115
+ ```
116
+
117
+ `compare` puts two variants (or two releases) side by side: what differs in their values and their sizes.
118
+
119
+ Versions are git tags, so a release needs the workspace in git. `--dry-run` shows the bump a change would need
120
+ without making it: here the first release of a new object is `0.1.0` as written.
121
+
122
+ ```sh
123
+ npx cad release home/tag -m "First tag" --dry-run
124
+ ```
125
+
126
+ ## 3. Joints and poses: a lid on a hinge
127
+
128
+ A box with a lid is one assembly, with the lid on a revolute joint between two anchors. The base and the lid name
129
+ their anchors in their `.json`; the poses say where the joint stands.
130
+
131
+ ```json projects/home/objects/base.json
132
+ {
133
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
134
+ "name": "base",
135
+ "title": "Box base",
136
+ "version": "0.1.0",
137
+ "uses": ["x1c"],
138
+ "anchors": { "hinge": { "at": [0, "depth / 2", "height"], "axis": [1, 0, 0] } },
139
+ "variables": {
140
+ "width": { "value": 40, "unit": "mm", "rule": "The box's width", "label": "Width", "show": true },
141
+ "depth": { "value": 30, "unit": "mm", "rule": "Its depth", "label": "Depth", "show": true },
142
+ "height": { "value": 16, "unit": "mm", "rule": "Its height", "label": "Height", "show": true },
143
+ "wall": { "value": "x1c.line * 3", "unit": "mm", "rule": "Three lines" }
144
+ }
145
+ }
146
+ ```
147
+
148
+ ```js projects/home/objects/base.js
149
+ // An open box: a tray with walls, the hinge along the middle of its back edge.
150
+ import jscad from '@jscad/modeling'
151
+ const { cuboid } = jscad.primitives
152
+ const { subtract } = jscad.booleans
153
+
154
+ export function main (v) {
155
+ const outer = cuboid({ size: [v.width, v.depth, v.height], center: [0, 0, v.height / 2] })
156
+ const inner = cuboid({ size: [v.width - 2 * v.wall, v.depth - 2 * v.wall, v.height], center: [0, 0, v.height / 2 + v.wall] })
157
+ return subtract(outer, inner)
158
+ }
159
+ ```
160
+
161
+ ```json projects/home/objects/lid.json
162
+ {
163
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
164
+ "name": "lid",
165
+ "title": "Box lid",
166
+ "version": "0.1.0",
167
+ "uses": ["x1c"],
168
+ "anchors": { "hinge": { "at": [0, "depth / 2", 0], "axis": [1, 0, 0] } },
169
+ "variables": {
170
+ "width": { "value": 40, "unit": "mm", "rule": "The box's width", "label": "Width", "show": true },
171
+ "depth": { "value": 30, "unit": "mm", "rule": "Its depth", "label": "Depth", "show": true },
172
+ "thick": { "value": "x1c.layer * 10", "unit": "mm", "rule": "Ten layers" }
173
+ }
174
+ }
175
+ ```
176
+
177
+ ```js projects/home/objects/lid.js
178
+ // A flat lid, hinged along its back edge.
179
+ import jscad from '@jscad/modeling'
180
+
181
+ export function main (v) {
182
+ return jscad.primitives.cuboid({ size: [v.width, v.depth, v.thick], center: [0, 0, v.thick / 2] })
183
+ }
184
+ ```
185
+
186
+ The assembly: the lid's hinge anchor sits on the base's, and the joint turns it from there. Angle 0 is shut; the lid
187
+ opens by turning back over the hinge, so the open pose is negative.
188
+
189
+ ```json projects/home/assemblies/box.json
190
+ {
191
+ "title": "Box with its lid",
192
+ "kind": "fit",
193
+ "items": [
194
+ { "id": "base", "object": "base" },
195
+ { "id": "lid", "object": "lid" }
196
+ ],
197
+ "joints": [
198
+ { "id": "hinge", "type": "revolute", "parent": "base.hinge", "child": "lid.hinge", "min": -120, "max": 0, "label": "Lid" }
199
+ ],
200
+ "poses": { "shut": { "hinge": 0 }, "open": { "hinge": -110 } }
201
+ }
202
+ ```
203
+
204
+ ```sh
205
+ npx cad check home/box
206
+ npx cad check home/box --pose open
207
+ npx cad check home/box --sweep --steps 12
208
+ ```
209
+
210
+ Every pose is checked for parts overlapping; the sweep turns the hinge through its range and names where anything
211
+ collides on the way. The link carries the joint as a slider: `npx cad link home/box --md`.
212
+
213
+ ## 4. A model from elsewhere: measured into rules, and matched
214
+
215
+ Something you must fit (a socket, a maker's part) is best measured from its model, not guessed. Here the model is the
216
+ box base exported as a 3MF, standing in for a file from a model site: `cad measure` reads its sections into a draft
217
+ rule set, and `cad match` lays the model over a design and reports how far apart their surfaces are.
218
+
219
+ ```sh
220
+ npx cad export home/base
221
+ npx cad measure exports/home/base@0.1.0.3mf --rules basemodel --source "exports/home/base@0.1.0.3mf" --licence "CC0" --no-pictures
222
+ npx cad match home/base exports/home/base@0.1.0.3mf --no-pictures --samples 3000
223
+ ```
224
+
225
+ The rule set `rules/basemodel.json` has every value as `kind: derived` with the file it came from: rename its
226
+ placeholder names (`size_x`, `sectionA_w`) for what they are before a design uses them. The match of the design
227
+ against its own export is exact; against someone else's model, a deliberate clearance shows as an even offset.
228
+
229
+ ## 5. An optimised part, analysed
230
+
231
+ A lever arm: where to put material so it bends least under a load, with bosses kept round the bolt and the pin. The
232
+ problem is a file in the project's `problems/`.
233
+
234
+ ```json projects/home/problems/arm.json
235
+ {
236
+ "title": "Lever arm",
237
+ "uses": ["m4", "x1c"],
238
+ "material": "pla",
239
+ "thickness": 4,
240
+ "cell": 1.5,
241
+ "volume": 0.4,
242
+ "filter": 3,
243
+ "space": { "at": [25, 0], "size": [62, 24] },
244
+ "keep": [{ "at": [0, 0], "r": 5 }, { "at": [50, 0], "r": 4 }],
245
+ "avoid": [{ "at": [0, 0], "r": "m4.clearance / 2" }, { "at": [50, 0], "r": 1.6 }],
246
+ "supports": [{ "at": [0, 0], "r": "m4.clearance / 2" }],
247
+ "loads": [{ "at": [50, 0], "r": 1.6, "force": [0, -10], "case": "down" }]
248
+ }
249
+ ```
250
+
251
+ The design reads the result through a `problem` variable and draws it; `analysis` has `cad check` report its
252
+ stiffness and peak stress on finer cells.
253
+
254
+ ```json projects/home/objects/arm.json
255
+ {
256
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
257
+ "name": "arm",
258
+ "title": "Lever arm",
259
+ "version": "0.1.0",
260
+ "uses": ["x1c"],
261
+ "material": "PLA",
262
+ "orientation": "Flat on the bed",
263
+ "variables": {
264
+ "problem": { "type": "problem", "value": "arm", "choice": ["arm"] },
265
+ "thick": { "value": 4, "unit": "mm", "rule": "As the problem's thickness" }
266
+ },
267
+ "analysis": [{ "problem": "arm", "cell": 0.5, "max_deflection": 1 }]
268
+ }
269
+ ```
270
+
271
+ ```js projects/home/objects/arm.js
272
+ // The optimised arm, extruded to its thickness: the holes come out true, cut from the outline.
273
+ import jscad from '@jscad/modeling'
274
+
275
+ export function main (v) {
276
+ return jscad.extrusions.extrudeLinear({ height: v.thick }, v.shapes.optimisedOutline(v.problems[v.problem]))
277
+ }
278
+ ```
279
+
280
+ ```sh
281
+ npx cad optimise home/arm
282
+ npx cad check home/arm
283
+ ```
284
+
285
+ `optimise` draws the layout in `.preview/` and reports how far the load moves; the result is kept until the problem
286
+ or the solver changes. `check` analyses the part as drawn, on cells half the size and again a quarter bigger, and says
287
+ whether the stiffness has settled.
288
+
289
+ ## 6. A board, and a case that reads it
290
+
291
+ A four-key pad: keys in a matrix, one diode each, and a Pico beside them. Every track is drawn by rule; the
292
+ checks run the fab's design rules.
293
+
294
+ ```json projects/home/objects/pad.json
295
+ {
296
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
297
+ "name": "pad",
298
+ "title": "Four-key pad",
299
+ "version": "0.1.0",
300
+ "engine": "pcb",
301
+ "uses": ["mx", "pico", "sod123", "m2", "jlcpcb"],
302
+ "variables": {
303
+ "rows": { "value": 2, "rule": "Two rows" },
304
+ "cols": { "value": 2, "rule": "Two columns" },
305
+ "track": { "value": "jlcpcb.track_min * 2.5", "unit": "mm", "rule": "Tracks well over the fab's least" },
306
+ "clear": { "value": "jlcpcb.gap_min * 2.5", "unit": "mm", "rule": "Clearance well over the fab's least" },
307
+ "thickness": { "value": "jlcpcb.thickness", "unit": "mm", "rule": "The usual board" },
308
+ "margin": { "value": 5, "unit": "mm", "rule": "Board edge beyond the keys" },
309
+ "mcu_gap": { "value": 2, "unit": "mm", "rule": "Between the keys and the Pico" },
310
+ "mcu_side": { "value": "left", "choice": ["left", "right"], "rule": "Which way the Pico's USB faces" },
311
+ "mcu_row": { "value": 0, "rule": "Which key row the Pico sits beside" },
312
+ "mount_holes": { "value": 1, "rule": "M2 holes in the corners" },
313
+ "controller": { "value": "beside", "choice": ["beside", "under"], "rule": "The Pico beside the keys" }
314
+ }
315
+ }
316
+ ```
317
+
318
+ ```js projects/home/objects/pad.js
319
+ // A key matrix on the keyboard recipe: the board and its matrix (rows, columns, GPIO) for the firmware.
320
+ export function main (v) {
321
+ const keys = v.pcb.grid(v.rows, v.cols, v.mx.pitch)
322
+ return v.pcb.keyboard(v, keys)
323
+ }
324
+ ```
325
+
326
+ ```sh
327
+ npx cad check home/pad
328
+ npx cad export home/pad
329
+ ```
330
+
331
+ A case reads the board rather than copying its numbers: `"uses": ["home/pad"]`, then `v.pad.board_w` and
332
+ `v.pad.board_holes` are the board's own.
333
+
334
+ ## 7. A mechanism printed flat
335
+
336
+ A leaf spring and a block that flicks, drawn in one plane and printed on its side. The lamina's checks come out with
337
+ the print checks: it prints free, its sequence is clear, and a hard stop catches the leaf before its strain limit.
338
+
339
+ ```json projects/home/objects/flick.json
340
+ {
341
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
342
+ "name": "flick",
343
+ "title": "Flicker",
344
+ "version": "0.1.0",
345
+ "uses": ["x1c", "pla"],
346
+ "material": "PLA",
347
+ "orientation": "On its side: the plane of the drawing is the bed",
348
+ "variables": {
349
+ "len": { "value": 20, "unit": "mm", "rule": "The leaf's length", "label": "Leaf", "show": true },
350
+ "t": { "value": "x1c.line * 2", "unit": "mm", "rule": "Two lines thick: it bends within its layers" },
351
+ "fillet": { "value": "x1c.line * 2", "unit": "mm", "rule": "Rounded where it meets its blocks: a square corner is where a print yields" },
352
+ "h": { "value": 10, "unit": "mm", "rule": "The print's height, the leaf's width: tall, so the tip can't flex out of the plane" },
353
+ "gap": { "value": "x1c.print_gap", "unit": "mm", "rule": "The gap that prints apart" },
354
+ "post": { "value": "x1c.print_gap + x1c.line", "unit": "mm", "rule": "How far the stop's lip stands over the tip block" },
355
+ "bend": { "value": 0.3, "unit": "mm", "rule": "How far the state bends it" },
356
+ "block": { "value": 4, "unit": "mm", "rule": "The tip block, the root, the frame's bars" }
357
+ }
358
+ }
359
+ ```
360
+
361
+ ```js projects/home/objects/flick.js
362
+ // A leaf from a root block to a tip block, bent by a state. The frame is one piece: the root, a floor under
363
+ // everything, and a post past the tip with a lip over it, the hard stop.
364
+ import jscad from '@jscad/modeling'
365
+ const rect = (x0, y0, x1, y1) => jscad.primitives.polygon({ points: [[x0, y0], [x1, y0], [x1, y1], [x0, y1]] })
366
+
367
+ export function main (v) {
368
+ const f = v.flexures, b = v.block, tipTop = b / 2, floor = 0 - b - b, postX = v.len + b + v.gap
369
+ return f.lamina({
370
+ height: v.h, gap: v.gap, material: f.flexureMaterial({ modulus: v.pla.modulus, strength: v.pla.strength }),
371
+ ground: [rect(0 - b, floor, 0, b), rect(0 - b, floor, postX + b, floor + b), rect(postX, floor, postX + b, tipTop + v.post + b), rect(v.len, tipTop + v.post, postX + b, tipTop + v.post + b)],
372
+ bodies: { tip: rect(v.len - b / 2, 0 - b / 2, v.len + b, tipTop) },
373
+ joints: { leaf: { kind: 'leaf', params: { length: v.len, thickness: v.t, fillet: v.fillet }, at: [0 - 1, 0], from: 'ground', to: 'tip' } },
374
+ states: { bent: { leaf: v.bend } }, sequence: ['rest', 'bent', 'rest']
375
+ })
376
+ }
377
+ ```
378
+
379
+ ```sh
380
+ npx cad check home/flick
381
+ npx cad animate home/flick
382
+ ```
383
+
384
+ `animate` writes the sequence as an animated SVG in `.preview/`, the leaf drawn bent, and a page that plays it with
385
+ the force on each step. The launcher in `examples/bench/projects/launcher` is the same idea at full size: a flooded
386
+ frame, catches, a trigger, and a shot.
package/README.md CHANGED
@@ -18,7 +18,8 @@ npx cad link bathroom/soap-tray # a link that opens the model in a browser
18
18
  ```
19
19
 
20
20
  **New here?** [The tutorial](TUTORIAL.md) walks from an empty folder to a part of your own, checked against the thing
21
- it fits, in about twenty minutes. This page is the reference.
21
+ it fits, in about twenty minutes. This page is the reference. [The worked examples](EXAMPLES.md) go on from there: parts, variants and a release, a lid on a hinge, a model
22
+ measured into rules, an optimised arm, a board, and a mechanism printed flat, each tested as written.
22
23
 
23
24
  ```
24
25
  rules/ shared facts, one file per set: x1c.json (printer), mx.json (Cherry MX). A set from
package/TUTORIAL.md CHANGED
@@ -213,7 +213,8 @@ itself: nothing is uploaded.
213
213
 
214
214
  ## Where next
215
215
 
216
- Each of these is a section of [the README](README.md):
216
+ [The worked examples](EXAMPLES.md) carry on from here, one for each of these, with the files to write and the
217
+ commands to run, tested the same way as this page. Each is also a section of [the README](README.md):
217
218
 
218
219
  - **Parts**: a design that returns several named parts, supports that break away, a second colour.
219
220
  - **Variants**: named sets of inputs, side by side (`home/hook:long`).
package/bin/cad.mjs CHANGED
@@ -17,6 +17,7 @@ import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, motionData } f
17
17
  import { valuesOf, why } from '../lib/explain.mjs';
18
18
  import { errorData, near } from '../lib/errors.mjs';
19
19
  import { schemaFindings } from '../lib/schema.mjs';
20
+ import { readJson } from '../lib/host.mjs';
20
21
  import { optimised, readProblem, analysePart, picture, problemFile } from '../lib/optimise.mjs';
21
22
  import { evaluate } from '../lib/rules.mjs';
22
23
  import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
@@ -134,6 +135,15 @@ const showProgress = (e) => {
134
135
  process.stderr.write(`\r\x1b[K${e.stage === 'sweep' ? `sweeping ${e.joint} ${e.step}/${e.steps}` : `building ${e.item} (${e.done})`}`);
135
136
  };
136
137
  // Findings: as text (a mark and the words), or with --json as data: { ...about, findings: [{ level, text, code, values, refs, at }] }
138
+ // Every measurement says why it is what it is, and every object its name: a variable with a value and no rule (or an
139
+ // object with no name) is a warning, not a failure, so an older design still builds
140
+ function unruled(object, file) {
141
+ const out = [], none = Object.entries(object.variables || {}).filter(([, v]) => v && v.value !== undefined && !v.type && !v.rule).map(([n]) => n);
142
+ if (none.length) out.push({ level: 'warn', text: `${none.length === 1 ? 'a variable has' : `${none.length} variables have`} no rule saying why ${none.length === 1 ? 'it is' : 'they are'} what ${none.length === 1 ? 'it is' : 'they are'}: ${none.slice(0, 6).join(', ')}${none.length > 6 ? ', …' : ''}`, code: 'var.no-rule', refs: { file, variables: none } });
143
+ if (!object.name) out.push({ level: 'warn', text: 'the object has no "name": give it the file\'s name, so links and releases say what it is', code: 'object.no-name', refs: { file } });
144
+ return out;
145
+ }
146
+
137
147
  function report(findings, about = {}) {
138
148
  if (opt('json')) console.log(JSON.stringify({ ...about, findings }, null, 2));
139
149
  else { const mark = { pass: '✓', warn: '!', fail: '✗', info: '·' }; for (const r of findings) console.log(` ${mark[r.level]} ${r.text}`); }
@@ -327,8 +337,13 @@ async function main() {
327
337
  }
328
338
 
329
339
  if (cmd === 'agents') { // the notes for AI agents, into this workspace (AGENTS.md, and CLAUDE.md pointing at it)
330
- const to = path.join(WS, 'AGENTS.md');
331
- fs.copyFileSync(path.join(TOOL, 'AGENTS.md'), to);
340
+ const to = path.join(WS, 'AGENTS.md'), ours = fs.readFileSync(path.join(TOOL, 'AGENTS.md'), 'utf8'), record = paths.cache('agents.md');
341
+ // An AGENTS.md as cad agents last wrote it (or, with no record of that, one that is an earlier copy of ours) is
342
+ // brought up to date; one edited here is kept, unless --force
343
+ const mine = fs.existsSync(to) ? fs.readFileSync(to, 'utf8') : null, last = fs.existsSync(record) ? fs.readFileSync(record, 'utf8') : null;
344
+ const ourCopy = mine === null || mine === ours || (last !== null ? mine === last : mine.startsWith(ours.split('\n')[0]));
345
+ if (!ourCopy && !opt('force')) throw new Error('AGENTS.md here has been edited (or isn\'t rulecad\'s): it is kept as it is (cad agents --force replaces it)');
346
+ fs.writeFileSync(to, ours); fs.mkdirSync(path.dirname(record), { recursive: true }); fs.writeFileSync(record, ours);
332
347
  const claude = path.join(WS, 'CLAUDE.md');
333
348
  if (!fs.existsSync(claude)) fs.writeFileSync(claude, '@AGENTS.md\n');
334
349
  else if (!fs.readFileSync(claude, 'utf8').includes('@AGENTS.md')) fs.appendFileSync(claude, '\n@AGENTS.md\n');
@@ -367,6 +382,11 @@ async function main() {
367
382
  if (isAssembly(ref)) return assembly(cmd, ref);
368
383
  const [base, at] = ref.split('@');
369
384
  const d = at ? materialise(locate(base), at) : locate(ref), set = sets();
385
+ // A check reads the files against their schemas first: a broken .json is said as that, before a build fails on it
386
+ if (cmd === 'check' && !at && fs.existsSync(d.json)) {
387
+ const bad = schemaFindings(readJson(d.json), 'object', path.relative(WS, d.json)).filter((f) => f.level === 'fail'); // (readJson: broken JSON is named with its file)
388
+ if (bad.length) { say(`${d.project}/${d.name}`); report(bad, { object: `${d.project}/${d.name}` }); process.exitCode = 1; return; }
389
+ }
370
390
  const b = opt('part') ? pick(await build(d, set), { part: opt('part') }) : await build(d, set);
371
391
  const tag = `${d.variant ? `-${d.variant}` : ''}${suffix(set)}${opt('part') ? `-${opt('part')}` : ''}`; // in file names
372
392
  const title = `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`, version = b.object.version || '0.0.0';
@@ -390,6 +410,7 @@ async function main() {
390
410
  }
391
411
 
392
412
  if (cmd === 'rules') {
413
+ if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, variables: b.entries.map((e) => ({ name: e.name, value: e.value, unit: e.unit || null, expr: e.expr || null, rule: e.rule || null, ...(e.source ? { source: e.source, kind: e.kind || null } : {}) })) }, null, 2));
393
414
  for (const e of b.entries) console.log(`${e.name.padEnd(18)} ${`${fmt(e.value)} ${e.unit || ''}`.padEnd(14)} ${e.expr ? `= ${e.expr} ` : ''}${e.rule || ''}${e.source ? ` [${e.kind ? `${e.kind}: ` : ''}${e.source}]` : ''}${e.set ? ' (set)' : ''}`);
394
415
  return;
395
416
  }
@@ -405,6 +426,7 @@ async function main() {
405
426
  const failed = report([
406
427
  ...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
407
428
  ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
429
+ ...unruled(b.object, own(d.json)),
408
430
  raw.length ? { level: 'fail', text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}`, code: 'lint.numbers', refs: { file, numbers: raw } }
409
431
  : { level: 'pass', text: 'every measurement is a variable', code: 'lint.numbers', refs: { file } },
410
432
  ...(b.object.role === 'reference'
@@ -444,8 +466,10 @@ async function main() {
444
466
  fs.mkdirSync(path.dirname(out), { recursive: true });
445
467
  const fil = filaments(d.project); // one object, a part per part, each in its filament
446
468
  fs.writeFileSync(out, await threemf([{ name: `${d.name}${d.variant ? ` ${d.variant}` : ''}`, parts: b.parts.map((p) => ({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) })) }], { filaments: slots(fil) }));
447
- report(filamentNotes(b.parts, fil));
469
+ const notes = filamentNotes(b.parts, fil);
448
470
  if (opt('open')) openInSlicer(out);
471
+ if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, version, file: path.relative(WS, out), findings: notes }, null, 2)); // (one object: the file is in it, not a line after)
472
+ report(notes);
449
473
  return console.log(out);
450
474
  }
451
475
 
@@ -520,7 +544,7 @@ async function explainValue(ref) {
520
544
  async function board(cmd, d, b, { title, version, tag }) {
521
545
  const pcb = await pcbEngine(), name = `${d.name}@${version}${tag}`;
522
546
  if (cmd === 'check') {
523
- console.log(`${title} ${version}`);
547
+ say(`${title} ${version}`);
524
548
  const raw = lint(fs.readFileSync(d.js, 'utf8'));
525
549
  // The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
526
550
  const own = (f) => path.relative(WS, f), ruleFiles = (b.object.uses || []).filter((u) => !u.includes('/')).map((u) => path.join(WS, 'rules', `${u}.json`)).filter((f) => fs.existsSync(f));
@@ -532,8 +556,8 @@ async function board(cmd, d, b, { title, version, tag }) {
532
556
  ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
533
557
  raw.length ? { level: 'fail', text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}` } : { level: 'pass', text: 'every measurement is a variable' },
534
558
  ...(await pcb.checks(b.circuit, b.values, b.matrix, b.source)),
535
- ]);
536
- if (b.object.orientation) console.log(` ${b.object.orientation}`);
559
+ ], { object: `${d.project}/${d.name}`, title, version });
560
+ if (b.object.orientation) say(` ${b.object.orientation}`);
537
561
  process.exitCode = failed ? 1 : 0;
538
562
  return;
539
563
  }
@@ -554,7 +578,9 @@ async function board(cmd, d, b, { title, version, tag }) {
554
578
  const written = [zip];
555
579
  for (const [f, t] of Object.entries(await pcb.kicadFiles(b.circuit, name))) { fs.writeFileSync(path.join(dir, f), t); written.push(path.join(dir, f)); }
556
580
  if (b.matrix) { const f = path.join(dir, `${name}-matrix.json`); fs.writeFileSync(f, JSON.stringify(b.matrix, null, 2) + '\n'); written.push(f); }
557
- report([{ level: 'pass', text: `fab zip: ${Object.keys(fab).length} files (${Object.keys(fab).filter((f) => !/\.(csv|DRL)$/.test(f)).length} Gerber layers, 2 drill files, BOM, placement)` }]);
581
+ const done = [{ level: 'pass', text: `fab zip: ${Object.keys(fab).length} files (${Object.keys(fab).filter((f) => !/\.(csv|DRL)$/.test(f)).length} Gerber layers, 2 drill files, BOM, placement)` }];
582
+ if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, version, files: written.map((f) => path.relative(WS, f)), findings: done }, null, 2));
583
+ report(done);
558
584
  for (const f of written) console.log(f);
559
585
  }
560
586
 
@@ -799,6 +825,7 @@ async function releaseAll(project) {
799
825
  // The object's variants, one a line: name, then its inputs
800
826
  function variants(d) {
801
827
  const v = readObject(d).variants || {};
828
+ if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, variants: v }, null, 2));
802
829
  if (!Object.keys(v).length) return console.log(`${d.name} has no variants: add "variants": { "name": { …inputs } } to its .json`);
803
830
  for (const [n, set] of Object.entries(v)) console.log(`${`${d.project}/${d.name}:${n}`.padEnd(32)} ${Object.entries(set).map(([k, x]) => `${k}=${x}`).join(', ')}`);
804
831
  }
@@ -832,11 +859,13 @@ async function status(project) {
832
859
  async function history(ref) {
833
860
  const [project, name] = ref.split('/');
834
861
  if (!name) {
862
+ if (opt('json')) return console.log(JSON.stringify({ project, releases: tags(project).reverse() }, null, 2));
835
863
  for (const t of tags(project).reverse()) console.log(`${t.tag} ${t.date} ${t.kind} ${t.message}`);
836
864
  return status(project);
837
865
  }
838
866
  const d = locate(ref), done = prints(d);
839
867
  const s = await since(d);
868
+ if (opt('json')) return console.log(JSON.stringify({ object: ref, unreleased: s.kind && s.last ? { kind: s.kind, reasons: s.reasons.map((r) => r.text) } : null, releases: tags(d.project, d.name).reverse().map((t) => ({ ...t, prints: done.filter((x) => x.version === t.version) })) }, null, 2));
840
869
  if (s.kind && s.last) { console.log(`unreleased (needs ${s.kind}):`); for (const r of s.reasons) console.log(` ${r.text}`); }
841
870
  for (const t of tags(d.project, d.name).reverse()) {
842
871
  console.log(`${t.version.padEnd(8)} ${t.date} ${t.kind.padEnd(5)} ${t.message}`);
package/lib/edit.mjs CHANGED
@@ -39,7 +39,14 @@ export async function setVariables(ref, changes, { create = false } = {}) {
39
39
  }
40
40
  const json = write(d.json, text, 'object');
41
41
  try { // the variables must still resolve: an unknown name or a loop puts the file back as it was
42
- resolve(json, { sets: (await objectSets(d, readObject(d))).sets });
42
+ const { values } = resolve(json, { sets: (await objectSets(d, readObject(d))).sets });
43
+ // and each changed value must lie within the variable's own range, where it has one (a tweak's min and max)
44
+ for (const name of Object.keys(changes)) {
45
+ const t = json.variables?.[name]?.tweak, v = values[name];
46
+ if (!t || typeof v !== 'number') continue;
47
+ const lo = typeof t.min === 'number' ? t.min : -Infinity, hi = typeof t.max === 'number' ? t.max : Infinity;
48
+ if (v < lo || v > hi) throw new CadError('edit.range', `${name} = ${v} is outside its range, ${t.min ?? '…'} to ${t.max ?? '…'} (change the range first if it should go there)`, { file: d.json, path: `variables.${name}` });
49
+ }
43
50
  } catch (e) { fs.writeFileSync(d.json, before); throw Object.assign(e, { file: d.json, message: `not changed: ${e.message}` }); }
44
51
  return { file: d.json, changed: Object.keys(changes) };
45
52
  }
@@ -66,6 +73,17 @@ export function addToAssembly(ref, what, entry) {
66
73
  if (getAt(text, [list]) === undefined) text = setAt(text, [list], []);
67
74
  const ids = (getAt(text, [list]) || []).map((x) => x.id).filter(Boolean);
68
75
  if (entry.id && ids.includes(entry.id)) throw new CadError('edit.duplicate', `${ref} already has a ${what} "${entry.id}"`, { file });
76
+ // a fit names parts as item.part: the item must be in the assembly, and the part one its object declares (or body)
77
+ if (what === 'fit') for (const side of ['a', 'b']) {
78
+ const named = entry[side]; if (typeof named !== 'string') continue;
79
+ const [item, part = 'body'] = named.split('@')[0].split('.'), it = (getAt(text, ['items']) || []).find((x) => x.id === item);
80
+ if (!it) throw new CadError('edit.part', `fit ${side}: no item "${item}" in ${ref} (items: ${(getAt(text, ['items']) || []).map((x) => x.id).join(', ') || 'none'})`, { file });
81
+ if (it.object) {
82
+ const [project] = ref.split('/'), obj = path.join(paths.project(project), 'objects', `${String(it.object).split(/[@:]/)[0]}.json`);
83
+ const parts = fs.existsSync(obj) ? Object.keys(JSON.parse(fs.readFileSync(obj, 'utf8')).parts || { body: {} }) : null;
84
+ if (parts && !parts.includes(part)) throw new CadError('edit.part', `fit ${side}: ${it.object} has no part "${part}" (parts: ${parts.join(', ')})`, { file });
85
+ }
86
+ }
69
87
  text = appendAt(text, [list], entry);
70
88
  }
71
89
  write(file, text, 'assembly');
package/lib/live.mjs CHANGED
@@ -221,7 +221,13 @@ if (!isMainThread && workerData?.flag) {
221
221
  } else if (req.url.startsWith('/three/') && fs.existsSync(path.join(THREE, path.basename(req.url)))) {
222
222
  res.writeHead(200, { 'content-type': 'text/javascript' }); res.end(fs.readFileSync(path.join(THREE, path.basename(req.url))));
223
223
  } else if (req.url.startsWith('/frame/') && frames[Number(req.url.slice(7))]) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(frames[Number(req.url.slice(7))]));
224
- } else if (req.url === '/stop' && req.method === 'POST') { Atomics.store(flag, 0, 1); res.end('stopping'); }
224
+ } else if (req.url === '/stop' && req.method === 'POST') {
225
+ // Only this page may stop the run: a request from another page (any site open in the browser can post here) comes
226
+ // with that page's Origin, and is refused
227
+ const origin = req.headers.origin, host = req.headers.host;
228
+ if (origin && origin !== `http://${host}`) { res.writeHead(403); return res.end('not from the live view'); }
229
+ Atomics.store(flag, 0, 1); res.end('stopping');
230
+ }
225
231
  else if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page(title)); }
226
232
  else { res.writeHead(404); res.end(); }
227
233
  });
package/lib/optimise.mjs CHANGED
@@ -84,7 +84,9 @@ export async function readProblem(project, ref) {
84
84
  if (dim === 2 && !(problem.thickness > 0)) throw new Error(`${path.basename(file)}: a flat (2D) problem needs a thickness`);
85
85
  const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2, fine: p.outline?.fine != null ? ev(p.outline.fine) : 1.25 }; // fine: the cells a printable solid is cleaned and drawn on, mm (its own cells if smaller)
86
86
  // A printable solid's surface is kept within the printer's overhang limit too (smoothing can tip faces past it)
87
- if (dim === 3 && problem.overhang) { const n = printerOf(project), pr = resolve({ uses: [n] }).values[n]; outline.overhang = { up: problem.overhang, angle: pr?.overhang ?? 45, bridge: pr?.bridge ?? 5, layer: pr?.layer ?? 0.2, line: pr?.line ?? 0.42 }; problem.bridge = outline.overhang.bridge; } // (the optimiser bridges half that)
87
+ // (outline.tip: faces the smoothing left steeper than the limit are tipped back to it too; off unless asked, since
88
+ // tipped corners leave dips that slice as islands, and the layers step out no further for it)
89
+ if (dim === 3 && problem.overhang) { const n = printerOf(project), pr = resolve({ uses: [n] }).values[n]; outline.overhang = { up: problem.overhang, angle: pr?.overhang ?? 45, bridge: pr?.bridge ?? 5, layer: pr?.layer ?? 0.2, line: pr?.line ?? 0.42, ...(p.outline?.tip ? { tip: true } : {}) }; problem.bridge = outline.overhang.bridge; } // (the optimiser bridges half that)
88
90
  return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline, critical: !!p.critical };
89
91
  }
90
92
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.25",
3
+ "version": "0.7.29",
4
4
  "description": "The cad command: JSCAD designs from traceable rules, checked for printing and fit, versioned by what fits, shared as links and exported as Bambu 3MF.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -31,6 +31,7 @@
31
31
  "templates",
32
32
  "README.md",
33
33
  "TUTORIAL.md",
34
+ "EXAMPLES.md",
34
35
  "LICENSE",
35
36
  "AGENTS.md"
36
37
  ],
@@ -51,8 +52,12 @@
51
52
  "url": "git+https://github.com/JoniBach/rulecad.git",
52
53
  "directory": "packages/cad"
53
54
  },
55
+ "homepage": "https://github.com/JoniBach/rulecad/tree/main/packages/cad#readme",
56
+ "bugs": {
57
+ "url": "https://github.com/JoniBach/rulecad/issues"
58
+ },
54
59
  "dependencies": {
55
- "@rulecad/variables": "^0.2.2",
60
+ "@rulecad/variables": "^0.3.0",
56
61
  "@rulecad/keyboard-layout": "^0.1.2",
57
62
  "@rulecad/printcheck": "^0.2.0",
58
63
  "@rulecad/fit": "^0.3.0",
@@ -63,11 +68,11 @@
63
68
  "@jscad/modeling": "^2.12.0",
64
69
  "three": "^0.186.1",
65
70
  "@rulecad/fea": "^0.2.1",
66
- "@rulecad/topopt": "^0.2.2",
67
- "@rulecad/flexures": "^0.3.0"
71
+ "@rulecad/topopt": "^0.3.0",
72
+ "@rulecad/flexures": "^0.4.0"
68
73
  },
69
74
  "peerDependencies": {
70
- "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0 || ^0.4.0"
75
+ "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0 || ^0.4.0 || ^0.5.0"
71
76
  },
72
77
  "peerDependenciesMeta": {
73
78
  "@rulecad/pcb": {
@@ -48,7 +48,7 @@
48
48
  "required": ["value"],
49
49
  "additionalProperties": false,
50
50
  "properties": {
51
- "value": { "description": "A number, an expression (x1c.line * 3), or for typed variables a name or text" },
51
+ "value": { "description": "A number, an expression (x1c.line * 3), or for typed variables a name or text", "type": ["number", "string", "boolean", "array", "object"] },
52
52
  "unit": { "type": "string" },
53
53
  "rule": { "type": "string", "description": "Why the value is what it is" },
54
54
  "label": { "type": "string" },
@@ -136,6 +136,14 @@
136
136
  "min_area": {
137
137
  "$ref": "#/$defs/expr",
138
138
  "description": "Holes and islands smaller than this (mm²) are dropped"
139
+ },
140
+ "fine": {
141
+ "$ref": "#/$defs/expr",
142
+ "description": "3D: the surface drawn on cells this many times finer than the problem's (default 1.25)"
143
+ },
144
+ "tip": {
145
+ "type": "boolean",
146
+ "description": "3D with an overhang direction: faces the smoothing left steeper than the printer's limit are tipped back to it as well (off by default: tipped corners can leave dips that slice as islands, and the sliced overhang is no smaller for it; the bracket example's 160 mm² of lean is the same either way)"
139
147
  }
140
148
  }
141
149
  },