@rulecad/cad 0.7.97 → 0.9.0

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.
Files changed (86) hide show
  1. package/AGENTS.md +26 -10
  2. package/CHANGELOG.md +442 -2
  3. package/EXAMPLES.md +48 -42
  4. package/README.md +226 -73
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2253 -514
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1854 -437
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +734 -113
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +900 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2710 -502
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +792 -176
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +149 -18
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +3 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1022 -212
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +41 -0
  57. package/lib/optimise.mjs +979 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +224 -36
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +38 -4
  68. package/lib/sandbox-hooks.mjs +154 -12
  69. package/lib/sandbox-preload.mjs +2 -2
  70. package/lib/sandbox-run.mjs +127 -12
  71. package/lib/sandbox.mjs +632 -35
  72. package/lib/schema.mjs +43 -11
  73. package/lib/seats.mjs +227 -49
  74. package/lib/services.mjs +261 -52
  75. package/lib/sheet.mjs +851 -178
  76. package/lib/slotnuts.mjs +213 -34
  77. package/lib/targets/gist.mjs +4 -1
  78. package/lib/targets.mjs +42 -6
  79. package/lib/task.mjs +376 -79
  80. package/lib/versions.mjs +113 -28
  81. package/lib/wires.mjs +228 -45
  82. package/lib/workspace.mjs +216 -17
  83. package/package.json +19 -19
  84. package/schemas/assembly.schema.json +2 -2
  85. package/schemas/object.schema.json +1 -1
  86. package/schemas/project.schema.json +1 -1
package/bin/cad.mjs CHANGED
@@ -3,41 +3,99 @@
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { execFileSync } from 'node:child_process';
6
- import { fmt, loadRuleSet } from '../lib/rules.mjs';
7
- import { WS, TOOL, paths, config, configError, printerOf, asks, trust, trusted } from '../lib/workspace.mjs';
6
+ import { fmt, loadRuleSet, insideWorkspace } from '../lib/rules.mjs';
7
+ import { WS, TOOL, paths, configError, printerOf, asks, trust } from '../lib/workspace.mjs';
8
+ import { isPlainName, plainName } from '../lib/names.mjs';
8
9
  import { fromKLE } from '@rulecad/keyboard-layout';
9
10
  import { target, hasTarget } from '../lib/targets.mjs';
10
- import { locate, build, pick, lint, readObject, printer, pcbEngine, objectSets } from '../lib/design.mjs';
11
- import { git, tags, bump, bigger, newer, compare, snapshot, materialise, files, prints, printsFile, engineId } from '../lib/versions.mjs';
11
+ import {
12
+ locate,
13
+ locateIn,
14
+ build,
15
+ pick,
16
+ lint,
17
+ readObject,
18
+ printer,
19
+ pcbEngine,
20
+ objectSets,
21
+ boardChecks,
22
+ } from '../lib/design.mjs';
23
+ import {
24
+ git,
25
+ tags,
26
+ bump,
27
+ bigger,
28
+ newer,
29
+ compare,
30
+ snapshot,
31
+ materialise,
32
+ files,
33
+ prints,
34
+ printsFile,
35
+ engineId,
36
+ } from '../lib/versions.mjs';
12
37
  import { check } from '@rulecad/printcheck';
13
38
  import { preview } from '../lib/preview.mjs';
14
39
  import { measure, match } from '../lib/meshcmd.mjs';
15
40
  import { cloneBoard } from '../lib/clone.mjs';
16
- import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, motionData, wireTubesOf } from '../lib/assembly.mjs';
41
+ import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, wireTubesOf } from '../lib/assembly.mjs';
17
42
  import { valuesOf, why } from '../lib/explain.mjs';
18
43
  import { errorData, near } from '../lib/errors.mjs';
19
44
  import { schemaFindings } from '../lib/schema.mjs';
20
- import { readJson } from '../lib/host.mjs';
21
- import { optimised, readProblem, analysePart, picture, problemFile, densitiesKey } from '../lib/optimise.mjs';
45
+ import { readJson, readOwnText, cached } from '../lib/host.mjs';
46
+ import {
47
+ optimised,
48
+ ownResults,
49
+ readProblem,
50
+ analysePart,
51
+ picture,
52
+ problemFile,
53
+ densitiesKey,
54
+ settledFinding,
55
+ } from '../lib/optimise.mjs';
22
56
  import { evaluate } from '../lib/rules.mjs';
23
- import { setVariables, addToAssembly, fastenFromFitsEdit, parseValue, parseSetting, newProject, setProject, newAssembly, newObject, setInAssembly, removeFromAssembly, moveInAssembly } from '../lib/edit.mjs';
57
+ import {
58
+ setVariables,
59
+ addToAssembly,
60
+ fastenFromFitsEdit,
61
+ parseValue,
62
+ parseSetting,
63
+ newProject,
64
+ setProject,
65
+ newAssembly,
66
+ newObject,
67
+ setInAssembly,
68
+ removeFromAssembly,
69
+ moveInAssembly,
70
+ } from '../lib/edit.mjs';
24
71
  import { setAt } from '../lib/jsonedit.mjs';
25
72
  import { threemf, slotOf } from '../lib/threemf.mjs';
26
73
  import { liveView, recorder, endOnly } from '../lib/live.mjs';
27
74
  import { checkSets, drawSet, draftSet, draftPart, draftParts } from '../lib/sheet.mjs';
28
- import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
75
+ import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW, viewNote } from '../lib/links.mjs';
29
76
 
30
77
  // What the print file asks of the AMS: which filament each kind of part prints in
31
78
  function filamentNotes(parts, fil) {
32
79
  const used = [...new Set(parts.map((p) => p.filament || 'base'))];
33
80
  const missing = used.filter((f) => f !== 'base' && !fil[f]);
34
- if (missing.length) return [{ level: 'fail', text: `parts print in ${missing.join(', ')}, which project.json's filaments don't list` }];
35
- return [{ level: 'pass', text: used.length > 1 ? `${used.length} filaments: ${used.map((f) => `${f} in AMS slot ${slotOf(fil, f)}${fil[f]?.name ? ` (${fil[f].name})` : ''}`).join(', ')}` : 'one filament' }];
81
+ if (missing.length)
82
+ return [{ level: 'fail', text: `parts print in ${missing.join(', ')}, which project.json's filaments don't list` }];
83
+ return [
84
+ {
85
+ level: 'pass',
86
+ text:
87
+ used.length > 1
88
+ ? `${used.length} filaments: ${used.map((f) => `${f} in AMS slot ${slotOf(fil, f)}${fil[f]?.name ? ` (${fil[f].name})` : ''}`).join(', ')}`
89
+ : 'one filament',
90
+ },
91
+ ];
36
92
  }
37
93
 
38
94
  // --open: the 3MF in Bambu Studio (macOS), else whatever opens .3mf files
39
- const openInSlicer = (f) => (process.platform === 'darwin' ? execFileSync('open', ['-a', 'Bambu Studio', f])
40
- : execFileSync(process.platform === 'win32' ? 'explorer' : 'xdg-open', [f]));
95
+ const openInSlicer = (f) =>
96
+ process.platform === 'darwin'
97
+ ? execFileSync('open', ['-a', 'Bambu Studio', f])
98
+ : execFileSync(process.platform === 'win32' ? 'explorer' : 'xdg-open', [f]);
41
99
 
42
100
  const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
43
101
 
@@ -87,10 +145,11 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
87
145
  assembly with a motor or gears: the drive turning them, cut across the shafts [--turns n]
88
146
  cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
89
147
  variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
90
- [--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button];
148
+ [--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button]
149
+ [--allow-host <name>: open the live view by that name too, a Tailscale name say];
91
150
  each run is kept to watch again: <problem>-run.html in .preview/
92
151
  cad preview <project>/problems/<problem> a problem's result and its run, step by step, as a page that needs no
93
- server (or the run live, with --watch [port])
152
+ server (or the run live, with --watch [port], and --allow-host as for cad optimise)
94
153
  cad export <project>/<object> a 3MF for Bambu Studio in exports/ [--open: open it in Bambu Studio]
95
154
  cad show <project>/<object> the model on display through your show target, with its rules [--ttl 10m]
96
155
  cad link <project>/<object> links to open the model in a browser, and to download its STL or 3MF
@@ -164,30 +223,214 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
164
223
  cad --version this tool's version`;
165
224
 
166
225
  // Every command and option there is: a misspelt one is refused by name, not passed over
167
- const COMMANDS = ['new', 'remove', 'move', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
168
- 'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'beams', 'frame', 'wires', 'machine', 'plot', 'plates', 'order', 'kit', 'match', 'variants', 'compare', 'help'];
169
- const OPTIONS = ['table', 'calibrate', 'check', 'turns', 'preview', 'gap', 'no-steps', 'all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
170
- 'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'profile', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
171
- 'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
172
- 'unit', 'rule', 'label', 'from', 'out', 'jigs', 'no-jigs', 'expand', 'size', 'write', 'pictures', 'cycles', 'period', // cad set, cad rules, cad beams, cad frame, cad plates, cad kit, cad plot
173
- 'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate', 'to', 'roll', // cad add
174
- 'screw', 'through', 'into', 'holes', 'nut', 'washer', 'length', 'torque', 'from-fits', // cad add fasten
175
- 'kind', 'fitting', // cad add join
176
- 'title', 'description', 'printer', 'frame', 'inside', 'outside', 'join', 'feet', 'caps', 'with-refs', 'mass', 'joint']; // cad new, cad remove, cad add load
226
+ const COMMANDS = [
227
+ 'new',
228
+ 'remove',
229
+ 'move',
230
+ 'import-kle',
231
+ 'clone',
232
+ 'agents',
233
+ 'trust',
234
+ 'rules',
235
+ 'values',
236
+ 'set',
237
+ 'add',
238
+ 'why',
239
+ 'check',
240
+ 'preview',
241
+ 'animate',
242
+ 'optimise',
243
+ 'optimize',
244
+ 'export',
245
+ 'show',
246
+ 'link',
247
+ 'status',
248
+ 'release',
249
+ 'history',
250
+ 'diff',
251
+ 'printed',
252
+ 'measure',
253
+ 'measured',
254
+ 'list',
255
+ 'beams',
256
+ 'frame',
257
+ 'wires',
258
+ 'machine',
259
+ 'plot',
260
+ 'plates',
261
+ 'order',
262
+ 'kit',
263
+ 'match',
264
+ 'variants',
265
+ 'compare',
266
+ 'help',
267
+ ];
268
+ const OPTIONS = [
269
+ 'table',
270
+ 'calibrate',
271
+ 'check',
272
+ 'turns',
273
+ 'preview',
274
+ 'gap',
275
+ 'no-steps',
276
+ 'all',
277
+ 'along',
278
+ 'at',
279
+ 'bump',
280
+ 'depth',
281
+ 'dry-run',
282
+ 'explode',
283
+ 'force',
284
+ 'fresh',
285
+ 'json',
286
+ 'licence',
287
+ 'license',
288
+ 'long',
289
+ 'm',
290
+ 'material',
291
+ 'md',
292
+ 'name',
293
+ 'new',
294
+ 'no-models',
295
+ 'no-pictures',
296
+ 'no-rules',
297
+ 'note',
298
+ 'open',
299
+ 'part',
300
+ 'place',
301
+ 'pose',
302
+ 'profile',
303
+ 'progress',
304
+ 'push',
305
+ 'result',
306
+ 'rules',
307
+ 'samples',
308
+ 'set',
309
+ 'short',
310
+ 'source',
311
+ 'steps',
312
+ 'sweep',
313
+ 'tol',
314
+ 'trailer',
315
+ 'ttl',
316
+ 'version',
317
+ 'watch',
318
+ 'allow-host',
319
+ 'line',
320
+ 'unit',
321
+ 'rule',
322
+ 'label',
323
+ 'from',
324
+ 'out',
325
+ 'jigs',
326
+ 'no-jigs',
327
+ 'expand',
328
+ 'size',
329
+ 'write',
330
+ 'pictures',
331
+ 'cycles',
332
+ 'period', // cad set, cad rules, cad beams, cad frame, cad plates, cad kit, cad plot
333
+ 'a',
334
+ 'b',
335
+ 'min',
336
+ 'max',
337
+ 'poses',
338
+ 'id',
339
+ 'type',
340
+ 'parent',
341
+ 'child',
342
+ 'follow',
343
+ 'value',
344
+ 'ratio',
345
+ 'object',
346
+ 'assembly',
347
+ 'variant',
348
+ 'rotate',
349
+ 'to',
350
+ 'roll', // cad add
351
+ 'screw',
352
+ 'through',
353
+ 'into',
354
+ 'holes',
355
+ 'nut',
356
+ 'washer',
357
+ 'length',
358
+ 'torque',
359
+ 'from-fits', // cad add fasten
360
+ 'kind',
361
+ 'fitting', // cad add join
362
+ 'title',
363
+ 'description',
364
+ 'printer',
365
+ 'frame',
366
+ 'inside',
367
+ 'outside',
368
+ 'join',
369
+ 'feet',
370
+ 'caps',
371
+ 'with-refs',
372
+ 'mass',
373
+ 'joint',
374
+ ]; // cad new, cad remove, cad add load
177
375
  // The commands that take --dry-run (each checks its edit and writes nothing); any other is refused with it, as a flag
178
376
  // it passed over would let the command write
179
- const takesDryRun = (cmd) => ['new', 'set', 'add', 'remove', 'move', 'release'].includes(cmd) || (cmd === 'frame' && (opt('expand') || (opt('size') && opt('write'))));
180
- const DRY_RUNS = 'the commands that take one are cad new, set, add, remove, move, release, frame --expand and frame --size --write';
377
+ const takesDryRun = (cmd) =>
378
+ ['new', 'set', 'add', 'remove', 'move', 'release'].includes(cmd) ||
379
+ (cmd === 'frame' && (opt('expand') || (opt('size') && opt('write'))));
380
+ const DRY_RUNS =
381
+ 'the commands that take one are cad new, set, add, remove, move, release, frame --expand and frame --size --write';
181
382
  // What a command takes, where that isn't <project>/<object>
182
- const USAGE = { add: 'fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …, <project>/<assembly> <address>=<value> …, or <project> field=value …',
183
- remove: '<project>/<assembly> <id | list.n | id.field> [--with-refs] [--dry-run]', move: '<project>/<assembly> <id> --at x,y,z | --to <address> [--rotate x,y,z] [--dry-run]',
184
- optimise: '<project>/<problem>', optimize: '<project>/<problem>', history: '<project>[/<object>]', release: '<project>[/<object>] -m "what changed"',
185
- diff: '<project>/<object> <from> [<to>]', compare: '<project>/<object> <a> <b>', match: '<project>/<object> <model.stl|model.3mf>', clone: '<board.kicad_pcb | GitHub link> <name>' };
383
+ const USAGE = {
384
+ add: 'fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]',
385
+ why: '<project>/<object>.<variable>',
386
+ set: '<project>/<object> name=value …, <project>/<assembly> <address>=<value> …, or <project> field=value …',
387
+ remove: '<project>/<assembly> <id | list.n | id.field> [--with-refs] [--dry-run]',
388
+ move: '<project>/<assembly> <id> --at x,y,z | --to <address> [--rotate x,y,z] [--dry-run]',
389
+ optimise: '<project>/<problem>',
390
+ optimize: '<project>/<problem>',
391
+ history: '<project>[/<object>]',
392
+ release: '<project>[/<object>] -m "what changed"',
393
+ diff: '<project>/<object> <from> [<to>]',
394
+ compare: '<project>/<object> <a> <b>',
395
+ match: '<project>/<object> <model.stl|model.3mf>',
396
+ clone: '<board.kicad_pcb | GitHub link> <name>',
397
+ };
186
398
 
187
399
  const args = process.argv.slice(2);
188
400
  // Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
189
401
  // (--sweep, --watch and --nut take one or not).
190
- const FLAGS = ['with-refs', 'table', 'calibrate', 'check', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short', 'washer', 'from-fits', 'jigs', 'no-jigs', 'pictures', 'expand', 'size', 'write'];
402
+ const FLAGS = [
403
+ 'with-refs',
404
+ 'table',
405
+ 'calibrate',
406
+ 'check',
407
+ 'preview',
408
+ 'no-steps',
409
+ 'all',
410
+ 'dry-run',
411
+ 'explode',
412
+ 'force',
413
+ 'fresh',
414
+ 'json',
415
+ 'long',
416
+ 'md',
417
+ 'new',
418
+ 'no-models',
419
+ 'no-pictures',
420
+ 'no-rules',
421
+ 'open',
422
+ 'progress',
423
+ 'push',
424
+ 'short',
425
+ 'washer',
426
+ 'from-fits',
427
+ 'jigs',
428
+ 'no-jigs',
429
+ 'pictures',
430
+ 'expand',
431
+ 'size',
432
+ 'write',
433
+ ];
191
434
  // The options whose value may be left out; a field=value after one is a field to set, not its value (cad new
192
435
  // frame/box --assembly title=Box)
193
436
  const OPTIONAL = ['sweep', 'watch', 'nut', 'assembly'];
@@ -195,75 +438,167 @@ const opt = (k) => {
195
438
  const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
196
439
  if (i < 0) return undefined;
197
440
  if (FLAGS.includes(k)) return true;
198
- if (args[i + 1] && !args[i + 1].startsWith('--') && !(OPTIONAL.includes(k) && args[i + 1].includes('='))) return args[i + 1];
441
+ if (args[i + 1] && !args[i + 1].startsWith('--') && !(OPTIONAL.includes(k) && args[i + 1].includes('=')))
442
+ return args[i + 1];
199
443
  if (OPTIONAL.includes(k)) return true;
200
444
  throw new Error(`${args[i]} needs a value after it`);
201
445
  };
202
446
  // The arguments that aren't options or an option's value: cad values keyboard/case depth width --json
203
- const takesValue = (a, next) => a === '-m' || (a.startsWith('--') && !FLAGS.includes(a.slice(2)) && !(OPTIONAL.includes(a.slice(2)) && String(next).includes('=')));
204
- const positional = () => args.filter((a, i) => !a.startsWith('--') && a !== '-m' && !(i > 0 && takesValue(args[i - 1], a)));
447
+ const takesValue = (a, next) =>
448
+ a === '-m' ||
449
+ (a.startsWith('--') && !FLAGS.includes(a.slice(2)) && !(OPTIONAL.includes(a.slice(2)) && String(next).includes('=')));
450
+ const positional = () =>
451
+ args.filter((a, i) => !a.startsWith('--') && a !== '-m' && !(i > 0 && takesValue(args[i - 1], a)));
452
+ // --allow-host name[,name …], as often as wanted: the names a live view (--watch) answers to beside this computer's own
453
+ // (lib/live-guard.mjs), such as a Tailscale name. A name only: a scheme, a path or a port is refused, as a typo.
454
+ const allowedHosts = () => {
455
+ const names = args
456
+ .flatMap((a, i) => (a === '--allow-host' ? [args[i + 1]] : []))
457
+ .flatMap((v) => (v === undefined || v.startsWith('--') ? [undefined] : v.split(',').map((n) => n.trim())));
458
+ if (names.length && !opt('watch'))
459
+ throw new Error('--allow-host goes with --watch: it names the live view by another name, so watch the run too');
460
+ for (const n of names)
461
+ if (!n || !/^[\w.-]+$/.test(n))
462
+ throw new Error(
463
+ `--allow-host takes a computer's name, such as my-laptop or my-laptop.tail0000.ts.net (got "${n ?? ''}")`,
464
+ );
465
+ return names;
466
+ };
205
467
  // --set name=value,name=value (a value may hold an = of its own)
206
- const sets = () => Object.fromEntries(String(opt('set') || '').split(',').filter(Boolean).map((p) => { const i = p.indexOf('='); return i < 0 ? [p.trim(), undefined] : [p.slice(0, i).trim(), p.slice(i + 1).trim()]; }));
207
- const suffix = (set) => Object.entries(set).map(([k, v]) => `-${k}=${v}`).join('').replace(/[^\w.=+-]/g, '_'); // in file names: nothing that could name another folder
468
+ const sets = () =>
469
+ Object.fromEntries(
470
+ String(opt('set') || '')
471
+ .split(',')
472
+ .filter(Boolean)
473
+ .map((p) => {
474
+ const i = p.indexOf('=');
475
+ return i < 0 ? [p.trim(), undefined] : [p.slice(0, i).trim(), p.slice(i + 1).trim()];
476
+ }),
477
+ );
478
+ const suffix = (set) =>
479
+ Object.entries(set)
480
+ .map(([k, v]) => `-${k}=${v}`)
481
+ .join('')
482
+ .replace(/[^\w.=+-]/g, '_'); // in file names: nothing that could name another folder
208
483
 
209
484
  // --progress: what a long build or sweep is doing, on one line of stderr
210
485
  const showProgress = (e) => {
211
486
  if (!opt('progress')) return;
212
- process.stderr.write(`\r\x1b[K${e.stage === 'sweep' ? `sweeping ${e.joint} ${e.step}/${e.steps}` : `building ${e.item} (${e.done})`}`);
487
+ process.stderr.write(
488
+ `\r\x1b[K${e.stage === 'sweep' ? `sweeping ${e.joint} ${e.step}/${e.steps}` : `building ${e.item} (${e.done})`}`,
489
+ );
213
490
  };
214
491
  // Findings: as text (a mark and the words), or with --json as data: { ...about, findings: [{ level, text, code, values, refs, at }] }
215
492
  // Every measurement says why it is what it is, and every object its name: a variable with a value and no rule (or an
216
493
  // object with no name) is a warning, not a failure, so an older design still builds
217
494
  function unruled(object, file) {
218
- const out = [], none = Object.entries(object.variables || {}).filter(([, v]) => v && v.value !== undefined && !v.type && !v.rule).map(([n]) => n);
219
- 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 } });
220
- 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 } });
495
+ const out = [],
496
+ none = Object.entries(object.variables || {})
497
+ .filter(([, v]) => v && v.value !== undefined && !v.type && !v.rule)
498
+ .map(([n]) => n);
499
+ if (none.length)
500
+ out.push({
501
+ level: 'warn',
502
+ 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 ? ', …' : ''}`,
503
+ code: 'var.no-rule',
504
+ refs: { file, variables: none },
505
+ });
506
+ if (!object.name)
507
+ out.push({
508
+ level: 'warn',
509
+ text: 'the object has no "name": give it the file\'s name, so links and releases say what it is',
510
+ code: 'object.no-name',
511
+ refs: { file },
512
+ });
221
513
  return out;
222
514
  }
223
515
 
224
516
  function report(findings, about = {}) {
225
517
  if (opt('json')) console.log(JSON.stringify({ ...about, findings }, null, 2));
226
- else { const mark = { pass: '✓', warn: '!', fail: '✗', info: '·' }; for (const r of findings) console.log(` ${mark[r.level]} ${r.text}`); }
518
+ else {
519
+ const mark = { pass: '✓', warn: '!', fail: '✗', info: '·' };
520
+ for (const r of findings) console.log(` ${mark[r.level]} ${r.text}`);
521
+ }
227
522
  return findings.some((r) => r.level === 'fail');
228
523
  }
229
- const say = (...a) => { if (!opt('json')) console.log(...a); }; // text output that --json leaves out
524
+ const say = (...a) => {
525
+ if (!opt('json')) console.log(...a);
526
+ }; // text output that --json leaves out
230
527
 
231
528
  const sig = (n) => (Number.isFinite(n) ? String(Number(n.toPrecision(3))) : String(n)); // three significant figures
232
529
  // A case's stiffness, and in words: a twist turns (degrees under N·m, N·m a degree), anything else moves along its load
233
530
  const stiffOf = (c) => (c.moment ? c.torsion : c.stiffness);
234
- const howFar = (c) => (c.moment ? `turns ${sig(c.angle * 180 / Math.PI)}° under ${sig(c.moment / 1000)} N·m, ${sig(c.torsion / 1000 * Math.PI / 180)} N·m a degree` : `moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
531
+ const howFar = (c) =>
532
+ c.moment
533
+ ? `turns ${sig((c.angle * 180) / Math.PI)}° under ${sig(c.moment / 1000)} N·m, ${sig(((c.torsion / 1000) * Math.PI) / 180)} N·m a degree`
534
+ : `moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`;
235
535
  // cad optimise: run a problem (with a progress line), then report it and draw it: a 2D layout as an SVG of its
236
536
  // densities, a 3D one as the preview's views of its surface
237
537
  async function optimiseProblem(ref, { preview: previewing = false } = {}) {
238
538
  const [project, name] = String(ref).split('/');
239
539
  if (!project || !name) throw new Error('usage: cad optimise <project>/<problem>[:variant]');
540
+ const allowHosts = allowedHosts();
240
541
  const file = problemFile(project, name.split(':')[0]);
241
542
  if (fs.existsSync(file)) {
242
- const bad = schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'problem', path.relative(WS, file));
243
- if (bad.length) { report(bad); process.exitCode = 1; return; }
543
+ const bad = schemaFindings(readJson(file), 'problem', path.relative(WS, file));
544
+ if (bad.length) {
545
+ report(bad);
546
+ process.exitCode = 1;
547
+ return;
548
+ }
244
549
  }
245
550
  const live = !opt('json') && process.stderr.isTTY;
246
551
  // --watch [port]: the live view, served while it runs (a watched run is always run afresh, so there is something to watch)
247
552
  const watch = opt('watch');
248
- if (watch && watch !== true && !(Number(watch) > 0 && Number(watch) < 65536)) throw new Error(`--watch takes a port number (got "${watch}")`);
249
- const view = watch ? await liveView({ port: watch === true ? 8090 : Number(watch), title: `cad optimise ${ref}` }) : null;
553
+ if (watch && watch !== true && !(Number(watch) > 0 && Number(watch) < 65536))
554
+ throw new Error(`--watch takes a port number (got "${watch}")`);
555
+ const view = watch
556
+ ? await liveView({ port: watch === true ? 8090 : Number(watch), title: `cad optimise ${ref}`, allowHosts })
557
+ : null;
250
558
  if (view) say(`watching at ${view.url}`);
251
559
  let r;
252
560
  const rec = recorder(); // each step kept, so the run can be watched again (cad preview <project>/problems/<name>)
253
561
  try {
254
- r = await optimised(project, name, { fresh: !!opt('fresh') || !!view, onStep: (s) => {
255
- rec.step(s);
256
- if (live) process.stderr.write(`\r\x1b[Kstep ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm change ${s.change.toFixed(3)} sharpness ${s.beta}`);
257
- if (view) { view.step(s); if (view.stopped()) throw new Error(`stopped from the live view at step ${s.step}`); }
258
- } });
259
- } catch (e) { await view?.close(e.message); throw e; } finally { if (live) process.stderr.write('\r\x1b[K'); }
562
+ ownResults();
563
+ r = await optimised(project, name, {
564
+ fresh: !!opt('fresh') || !!view,
565
+ onStep: (s) => {
566
+ rec.step(s);
567
+ if (live)
568
+ process.stderr.write(
569
+ `\r\x1b[Kstep ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm change ${s.change.toFixed(3)} sharpness ${s.beta}`,
570
+ );
571
+ if (view) {
572
+ view.step(s);
573
+ if (view.stopped()) throw new Error(`stopped from the live view at step ${s.step}`);
574
+ }
575
+ },
576
+ });
577
+ } catch (e) {
578
+ await view?.close(e.message);
579
+ throw e;
580
+ } finally {
581
+ if (live) process.stderr.write('\r\x1b[K');
582
+ }
260
583
  // The page keeps showing the end for ten minutes (the process waits for it), so a finished run isn't a dead link
261
- if (view) { view.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, { hold: 10 * 60e3 }); say(`the live view shows the result for ten more minutes (Ctrl-C to stop it)`); }
262
- const p = await readProblem(project, name), cells = r.dim === 3 ? `${r.grid.nx} × ${r.grid.ny} × ${r.grid.nz}` : `${r.grid.nx} × ${r.grid.ny}`;
263
- const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => c.moment ? `${c.name} ${sig(c.angle * 180 / Math.PI)}° (${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°)` : `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
584
+ if (view) {
585
+ view.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, { hold: 10 * 60e3 });
586
+ say(`the live view shows the result for ten more minutes (Ctrl-C to stop it)`);
587
+ }
588
+ const p = await readProblem(project, name),
589
+ cells = r.dim === 3 ? `${r.grid.nx} × ${r.grid.ny} × ${r.grid.nz}` : `${r.grid.nx} × ${r.grid.ny}`;
590
+ const lines = [
591
+ `${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => (c.moment ? `${c.name} ${sig((c.angle * 180) / Math.PI)}° (${sig(((c.torsion / 1000) * Math.PI) / 180)} N·m/°)` : `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`)).join(', ')}`,
264
592
  `${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}${r.dropped ? `; ${r.dropped.length} loose ${r.dropped.length === 1 ? 'piece' : 'pieces'} dropped (${sig(r.dropped.reduce((t, v) => t + v, 0))} mm³)` : ''}${r.emptied ? `; ${r.emptied} ${r.emptied === 1 ? 'cell' : 'cells'} that wouldn't print emptied` : ''}${r.cleared ? `; sliced as the printer will, ${r.cleared} ${r.cleared === 1 ? 'cell' : 'cells'} under islands emptied` : ''}`,
265
- ...(r.unsupported > 0.01 ? [`${fmt(r.unsupported * 100)}% of the kept regions has nothing holding it up (at ${r.overhang ? 'the printer\'s overhang limit' : '45°'} or less): give the part more material to stand them on, or keep less`] : []),
266
- ...(r.process ? [processLine(r)] : []), ...(r.feature ? [featureLine(r)] : []), ...(r.voids?.length ? [voidsLine(r)] : [])];
593
+ ...(r.unsupported > 0.01
594
+ ? [
595
+ `${fmt(r.unsupported * 100)}% of the kept regions has nothing holding it up (at ${r.overhang ? "the printer's overhang limit" : '45°'} or less): give the part more material to stand them on, or keep less`,
596
+ ]
597
+ : []),
598
+ ...(r.process ? [processLine(r)] : []),
599
+ ...(r.feature ? [featureLine(r)] : []),
600
+ ...(r.voids?.length ? [voidsLine(r)] : []),
601
+ ];
267
602
  let out;
268
603
  if (r.dim === 3) {
269
604
  out = paths.preview(project, `${name.replace(':', '-')}-optimised.png`);
@@ -275,46 +610,115 @@ async function optimiseProblem(ref, { preview: previewing = false } = {}) {
275
610
  fs.writeFileSync(out, picture(r, { title: r.title, lines }));
276
611
  }
277
612
  // The run, to watch again: kept by the densities' key when it was recorded here, else its end alone
278
- const done = `finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, kept = paths.cache('runs', `${densitiesKey(p.problem)}.html`);
279
- if (rec.steps()) { fs.mkdirSync(path.dirname(kept), { recursive: true }); fs.writeFileSync(kept, rec.page(`cad optimise ${ref}`, done)); }
280
- const run = paths.preview(project, `${name.replace(':', '-')}-run.html`), recorded = fs.existsSync(kept);
613
+ const done = `finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`,
614
+ kept = paths.cache('runs', `${densitiesKey(p.problem)}.html`);
615
+ if (rec.steps()) {
616
+ fs.mkdirSync(path.dirname(kept), { recursive: true });
617
+ fs.writeFileSync(kept, rec.page(`cad optimise ${ref}`, done));
618
+ }
619
+ const run = paths.preview(project, `${name.replace(':', '-')}-run.html`),
620
+ recorded = cached(kept);
281
621
  fs.mkdirSync(path.dirname(run), { recursive: true });
282
- fs.writeFileSync(run, recorded ? fs.readFileSync(kept, 'utf8') : endOnly(`cad optimise ${ref}`, r, `${done} (its steps weren't recorded: run it again with --fresh to watch them)`));
622
+ fs.writeFileSync(
623
+ run,
624
+ recorded
625
+ ? fs.readFileSync(kept, 'utf8')
626
+ : endOnly(
627
+ `cad optimise ${ref}`,
628
+ r,
629
+ `${done} (its steps weren't recorded: run it again with --fresh to watch them)`,
630
+ ),
631
+ );
283
632
  if (opt('json')) return console.log(JSON.stringify((({ density, history, mesh, ...x }) => x)(r), null, 2));
284
633
  console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
285
634
  for (const c of r.cases) console.log(` ${c.name}: ${howFar(c)}`);
286
- if (r.mechanism) console.log(` the output moves ${sig(r.mechanism.travel)} mm its way for ${sig(r.mechanism.input)} mm of push: an advantage of ${sig(r.mechanism.advantage)}`);
287
- if (r.stress && r.mechanism) console.log(` peak stress ${sig(r.stress.peak)} MPa at its input force${r.stress.strain != null ? ` (strain ${sig(r.stress.strain * 100)}%)` : ''}, the limit ${sig(r.stress.limit)} MPa${r.stress.strainLimit != null ? ` (${sig(r.stress.strainLimit * 100)}%)` : ''}: it reaches the limit at ${sig(r.stress.force)} N of push, its output then ${sig(r.stress.travel)} mm along`);
288
- else if (r.stress) console.log(` peak stress ${sig(r.stress.peak)} MPa, the limit ${sig(r.stress.limit)} MPa${r.stress.peak > r.stress.limit * 1.02 ? ': over it (raise the volume, ease the limit, or use a smaller cell)' : ''}`);
289
- if (r.stress?.copies) console.log(` made a little thin, peak stress ${sig(r.stress.copies.eroded)} MPa; a little thick, ${sig(r.stress.copies.dilated)} MPa${Math.max(r.stress.copies.eroded, r.stress.copies.dilated) > r.stress.limit * 1.02 ? ` (over the limit: ${p.problem?.robust ? 'a smaller cell or a looser limit' : 'give the problem robust: true'})` : ''}`);
290
- if (r.mechanism?.copies) console.log(` made a little thin, its output moves ${sig(r.mechanism.copies.eroded)} mm; a little thick, ${sig(r.mechanism.copies.dilated)} mm`);
291
- if (r.dim === 3) console.log(` ${fmt(r.volume * 100)}% of the space filled: ${fmt(r.solid / 1000)} cm³ (${fmt(r.solid / 1000 * (p.material.density || 0))} g of ${p.material.name})${r.overhang ? `, printable built ${r.overhang}` : ''}`);
292
- else console.log(` ${fmt(r.volume * 100)}% of the space filled, outline ${fmt(r.area)} mm² (${fmt(r.area * r.thickness / 1000)} cm³ before bosses and holes are made exact)`);
293
- if (r.reduced) console.log(` ${r.reduced.before} triangles reduced to ${r.reduced.after} (${fmt(r.reduced.after / r.reduced.before * 100)}%), the surface kept within ${fmt(r.reduced.tolerance)} mm`);
294
- console.log(` ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`);
635
+ if (r.mechanism)
636
+ console.log(
637
+ ` the output moves ${sig(r.mechanism.travel)} mm its way for ${sig(r.mechanism.input)} mm of push: an advantage of ${sig(r.mechanism.advantage)}`,
638
+ );
639
+ if (r.stress && r.mechanism)
640
+ console.log(
641
+ ` peak stress ${sig(r.stress.peak)} MPa at its input force${r.stress.strain != null ? ` (strain ${sig(r.stress.strain * 100)}%)` : ''}, the limit ${sig(r.stress.limit)} MPa${r.stress.strainLimit != null ? ` (${sig(r.stress.strainLimit * 100)}%)` : ''}: it reaches the limit at ${sig(r.stress.force)} N of push, its output then ${sig(r.stress.travel)} mm along`,
642
+ );
643
+ else if (r.stress)
644
+ console.log(
645
+ ` peak stress ${sig(r.stress.peak)} MPa, the limit ${sig(r.stress.limit)} MPa${r.stress.peak > r.stress.limit * 1.02 ? ': over it (raise the volume, ease the limit, or use a smaller cell)' : ''}`,
646
+ );
647
+ if (r.stress?.copies)
648
+ console.log(
649
+ ` made a little thin, peak stress ${sig(r.stress.copies.eroded)} MPa; a little thick, ${sig(r.stress.copies.dilated)} MPa${Math.max(r.stress.copies.eroded, r.stress.copies.dilated) > r.stress.limit * 1.02 ? ` (over the limit: ${p.problem?.robust ? 'a smaller cell or a looser limit' : 'give the problem robust: true'})` : ''}`,
650
+ );
651
+ if (r.mechanism?.copies)
652
+ console.log(
653
+ ` made a little thin, its output moves ${sig(r.mechanism.copies.eroded)} mm; a little thick, ${sig(r.mechanism.copies.dilated)} mm`,
654
+ );
655
+ if (r.dim === 3)
656
+ console.log(
657
+ ` ${fmt(r.volume * 100)}% of the space filled: ${fmt(r.solid / 1000)} cm³ (${fmt((r.solid / 1000) * (p.material.density || 0))} g of ${p.material.name})${r.overhang ? `, printable built ${r.overhang}` : ''}`,
658
+ );
659
+ else
660
+ console.log(
661
+ ` ${fmt(r.volume * 100)}% of the space filled, outline ${fmt(r.area)} mm² (${fmt((r.area * r.thickness) / 1000)} cm³ before bosses and holes are made exact)`,
662
+ );
663
+ if (r.reduced)
664
+ console.log(
665
+ ` ${r.reduced.before} triangles reduced to ${r.reduced.after} (${fmt((r.reduced.after / r.reduced.before) * 100)}%), the surface kept within ${fmt(r.reduced.tolerance)} mm`,
666
+ );
667
+ console.log(
668
+ ` ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`,
669
+ );
295
670
  if (r.process) console.log(` ${processLine(r)}`);
296
- if (r.symmetry || r.extrude) console.log(` ${[r.symmetry?.mirror ? `mirrored across ${[...r.symmetry.mirror].join(' and ')}` : '', r.symmetry?.turns ? `the same each ${r.symmetry.turns === 4 ? 'quarter' : 'half'} turn about ${r.symmetry.axis || 'z'}` : '', r.extrude ? `one section along ${r.extrude}` : ''].filter(Boolean).join(', ')}`);
671
+ if (r.symmetry || r.extrude)
672
+ console.log(
673
+ ` ${[r.symmetry?.mirror ? `mirrored across ${[...r.symmetry.mirror].join(' and ')}` : '', r.symmetry?.turns ? `the same each ${r.symmetry.turns === 4 ? 'quarter' : 'half'} turn about ${r.symmetry.axis || 'z'}` : '', r.extrude ? `one section along ${r.extrude}` : ''].filter(Boolean).join(', ')}`,
674
+ );
297
675
  if (r.feature) console.log(` ${r.feature.thin ? 'warning: ' : ''}${featureLine(r)}`);
298
676
  if (r.grey > 0.1) console.log(` warning: ${greyLine(r)}`);
299
- if (r.voids?.length) { console.log(` error: ${voidsLine(r)}`); process.exitCode = 1; } else if (r.vented) console.log(' voids prevented: none enclosed, every empty pocket open to the outside');
677
+ if (r.voids?.length) {
678
+ console.log(` error: ${voidsLine(r)}`);
679
+ process.exitCode = 1;
680
+ } else if (r.vented) console.log(' voids prevented: none enclosed, every empty pocket open to the outside');
300
681
  console.log(out);
301
- if (previewing) console.log(`${run}\n ${recorded ? `the run, step by step: open it to watch it again (${r.steps} steps)` : 'the run\'s end only: its steps weren\'t recorded (cad preview --fresh runs it again and records them)'}`);
682
+ if (previewing)
683
+ console.log(
684
+ `${run}\n ${recorded ? `the run, step by step: open it to watch it again (${r.steps} steps)` : "the run's end only: its steps weren't recorded (cad preview --fresh runs it again and records them)"}`,
685
+ );
302
686
  }
303
687
  // How a milled or cast result is made, and its undercuts (none, unless an avoid region or the space's own shape sits
304
688
  // behind material: the optimiser keeps every cell as solid as those on its way out, but can't fill a cell it mustn't)
305
689
  function processLine(r) {
306
- const p = r.process, sides = [p.mill].flat(), tool = p.tool ? ` by a tool of ${fmt(p.tool)} mm radius` : '';
690
+ const p = r.process,
691
+ sides = [p.mill].flat(),
692
+ tool = p.tool ? ` by a tool of ${fmt(p.tool)} mm radius` : '';
307
693
  const draft = p.draft ? ` with a ${fmt(p.draft)}° draft (a step out every ${p.every} layers: ${fmt(p.made)}°)` : '';
308
- const how = p.mill ? `milled from ${sides.length > 1 ? `${sides.slice(0, -1).join(', ')} and ${sides.at(-1)}` : sides[0]}${tool}` : typeof p.cast === 'string' ? `cast, drawn off ${p.cast}${draft}` : `cast in two halves drawn off along ${p.cast.draw} from ${fmt(p.cast.parting)} mm${draft}`;
309
- const n = r.narrow, narrow = !n ? '' : [n.design ? `${n.design} ${n.design === 1 ? 'cell' : 'cells'} of the design too narrow for the tool` : '', n.avoided ? `${n.avoided} ${n.avoided === 1 ? 'cell' : 'cells'} of avoid regions narrower than the tool: drill those holes, or give a smaller tool` : ''].filter(Boolean).join('; ');
694
+ const how = p.mill
695
+ ? `milled from ${sides.length > 1 ? `${sides.slice(0, -1).join(', ')} and ${sides.at(-1)}` : sides[0]}${tool}`
696
+ : typeof p.cast === 'string'
697
+ ? `cast, drawn off ${p.cast}${draft}`
698
+ : `cast in two halves drawn off along ${p.cast.draw} from ${fmt(p.cast.parting)} mm${draft}`;
699
+ const n = r.narrow,
700
+ narrow = !n
701
+ ? ''
702
+ : [
703
+ n.design ? `${n.design} ${n.design === 1 ? 'cell' : 'cells'} of the design too narrow for the tool` : '',
704
+ n.avoided
705
+ ? `${n.avoided} ${n.avoided === 1 ? 'cell' : 'cells'} of avoid regions narrower than the tool: drill those holes, or give a smaller tool`
706
+ : '',
707
+ ]
708
+ .filter(Boolean)
709
+ .join('; ');
310
710
  const tail = narrow ? `; ${narrow}` : n ? ', and nothing narrower than the tool' : '';
311
- return r.undercuts ? `${how}: ${r.undercuts} ${r.undercuts === 1 ? 'cell is' : 'cells are'} undercut (an avoid region, or the edge of the space, with material between it and the ${p.mill ? 'tool' : 'draw'}: move it, or make it from that side)${tail}` : `${how}: no undercuts${tail}`;
711
+ return r.undercuts
712
+ ? `${how}: ${r.undercuts} ${r.undercuts === 1 ? 'cell is' : 'cells are'} undercut (an avoid region, or the edge of the space, with material between it and the ${p.mill ? 'tool' : 'draw'}: move it, or make it from that side)${tail}`
713
+ : `${how}: no undercuts${tail}`;
312
714
  }
313
715
  // The thinnest member asked (a printer's two lines): met by the grid itself, or held to three cells, with any cells left
314
716
  // in members narrower
315
717
  function featureLine(r) {
316
- const f = r.feature, h = f.holds / (2 * f.cells + 1);
317
- if (!f.cells) return `thinnest member ${fmt(f.asked)} mm: every member is at least a cell (${fmt(h)} mm), so the grid holds it`;
718
+ const f = r.feature,
719
+ h = f.holds / (2 * f.cells + 1);
720
+ if (!f.cells)
721
+ return `thinnest member ${fmt(f.asked)} mm: every member is at least a cell (${fmt(h)} mm), so the grid holds it`;
318
722
  return `thinnest member ${fmt(f.asked)} mm: held to three cells (${fmt(f.holds)} mm)${f.thin ? `, and ${f.thin} solid ${f.thin === 1 ? 'cell is' : 'cells are'} still in a narrower member or a square outside corner: give a bigger filter radius` : ', none narrower'}`;
319
723
  }
320
724
  // A grey result (warned of above a tenth): its design cells between a tenth and nine tenths solid. A clear design has
@@ -330,106 +734,291 @@ function voidsLine(r) {
330
734
 
331
735
  // An object's analyses for cad check: each problem's load cases on the part, and its volume against a target
332
736
  function place(triangles, [rx, ry, rz], move) {
333
- const [cx, sx, cy, sy, cz, sz] = [rx, ry, rz].flatMap((deg) => [Math.cos((deg * Math.PI) / 180), Math.sin((deg * Math.PI) / 180)]);
334
- return triangles.map((t) => t.map((p) => {
335
- let [x, y, z = 0] = p;
336
- [y, z] = [y * cx - z * sx, y * sx + z * cx];
337
- [x, z] = [x * cy + z * sy, -x * sy + z * cy];
338
- [x, y] = [x * cz - y * sz, x * sz + y * cz];
339
- return [x + move[0], y + move[1], z + (move[2] || 0)].slice(0, p.length);
340
- }));
737
+ const [cx, sx, cy, sy, cz, sz] = [rx, ry, rz].flatMap((deg) => [
738
+ Math.cos((deg * Math.PI) / 180),
739
+ Math.sin((deg * Math.PI) / 180),
740
+ ]);
741
+ return triangles.map((t) =>
742
+ t.map((p) => {
743
+ let [x, y, z = 0] = p;
744
+ [y, z] = [y * cx - z * sx, y * sx + z * cx];
745
+ [x, z] = [x * cy + z * sy, -x * sy + z * cy];
746
+ [x, y] = [x * cz - y * sz, x * sz + y * cz];
747
+ return [x + move[0], y + move[1], z + (move[2] || 0)].slice(0, p.length);
748
+ }),
749
+ );
341
750
  }
342
751
 
343
752
  // A part's analysis report, in Markdown: what was analysed, how, each load case's numbers and where, and what it
344
753
  // doesn't cover
345
- function reportText({ turn, object, title, version, a, r, m, strength, weaker, grid, limit, minSafety, records, found }) {
754
+ function reportText({
755
+ turn,
756
+ object,
757
+ title,
758
+ version,
759
+ a,
760
+ r,
761
+ m,
762
+ strength,
763
+ weaker,
764
+ grid,
765
+ limit,
766
+ minSafety,
767
+ records,
768
+ found,
769
+ }) {
346
770
  const at = (p) => `(${p.map(fmt).join(', ')})`;
347
771
  const pct = (x) => `${x >= 0 ? '+' : ''}${fmt(x * 100)}%`;
348
- const rows = r.cases.map((c) => `| ${c.name} | ${c.moment ? `${sig(c.moment / 1000)} N·m | ${sig(c.angle * 180 / Math.PI)}° | ${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°` : `${fmt(c.force)} | ${sig(c.deflection)} | ${sig(c.stiffness)}`}${c.change ? ` (${pct(c.change.stiffness)})` : ''} | ${sig(c.stress)}${c.change ? ` (${pct(c.change.stress)})` : ''} at ${at(c.stressAt)} | ${strength ? `${sig(strength / c.stress)}×` : '–'}${m.fatigue ? ` (fatigue ${sig(m.fatigue / c.stress)}×)` : ''} | ${sig(c.movement)} at ${at(c.movementAt)} |`);
772
+ const rows = r.cases.map(
773
+ (c) =>
774
+ `| ${c.name} | ${c.moment ? `${sig(c.moment / 1000)} N·m | ${sig((c.angle * 180) / Math.PI)}° | ${sig(((c.torsion / 1000) * Math.PI) / 180)} N·m/°` : `${fmt(c.force)} | ${sig(c.deflection)} | ${sig(c.stiffness)}`}${c.change ? ` (${pct(c.change.stiffness)})` : ''} | ${sig(c.stress)}${c.change ? ` (${pct(c.change.stress)})` : ''} at ${at(c.stressAt)} | ${strength ? `${sig(strength / c.stress)}×` : '–'}${m.fatigue ? ` (fatigue ${sig(m.fatigue / c.stress)}×)` : ''} | ${sig(c.movement)} at ${at(c.movementAt)} |`,
775
+ );
349
776
  return [
350
- `# ${title}: analysed under ${a.problem}`, '',
351
- `${object} ${version || ''}. Analysed on ${grid}, ${m.name} (modulus ${fmt(m.modulus)} MPa${strength ? `, strength ${fmt(strength)} MPa${weaker ? ' across its layers' : ''}` : ''}${m.fatigue ? `, fatigue strength ${fmt(m.fatigue)} MPa` : ''}). Positions are in mm, in the problem's frame${turn ? ' (the part turned back from how it prints)' : ''}.${r.cases[0]?.change ? ` In brackets: the change from ${fmt(r.cases[0].change.cell)} mm cells. Stiffness that changes by 5% or less has settled; peak stress at a sharp inside corner keeps rising as cells shrink, so read it with its change.` : ' On the problem\'s own cells: a quick check. Give the analysis a smaller cell to verify it.'}`, '',
777
+ `# ${title}: analysed under ${a.problem}`,
778
+ '',
779
+ `${object} ${version || ''}. Analysed on ${grid}, ${m.name} (modulus ${fmt(m.modulus)} MPa${strength ? `, strength ${fmt(strength)} MPa${weaker ? ' across its layers' : ''}` : ''}${m.fatigue ? `, fatigue strength ${fmt(m.fatigue)} MPa` : ''}). Positions are in mm, in the problem's frame${turn ? ' (the part turned back from how it prints)' : ''}.${r.cases[0]?.change ? ` In brackets: the change from ${fmt(r.cases[0].change.cell)} mm cells. Stiffness that changes by 5% or less has settled${minSafety != null ? ', and with a least safety factor asked, the peak stress must too' : ''}; peak stress at a sharp inside corner, or beside a support or load held at a few points, keeps rising as cells shrink, so read it with its change.` : " On the problem's own cells: a quick check. Give the analysis a smaller cell to verify it."}`,
780
+ '',
352
781
  '| Load case | Force (N) | Moves its load (mm) | Stiffness (N/mm) | Peak stress (MPa) | Safety factor | Largest movement (mm) |',
353
- '|---|---|---|---|---|---|---|', ...rows, '',
354
- `Volume ${fmt(r.volume)} mm³.${limit != null ? ` Limit on movement: ${fmt(limit)} mm.` : ''}${minSafety != null ? ` Least safety factor: ${fmt(minSafety)}×.` : ''}`, '',
355
- '## Findings', '', ...found.map((f) => `- ${f.level}: ${f.text}`), '',
356
- '## Verification', '',
357
- ...(records.length ? records.map((v) => `- ${v.kind}, ${v.date}${v.by ? `, by ${v.by}` : ''}: ${v.summary}${v.source ? ` (${v.source})` : ''}`) : [r.critical ? '**Unverified.** This part is safety-critical: do not rely on it until a test or an independent analysis is recorded.' : 'None recorded.']), '',
358
- '## What this doesn\'t cover', '',
782
+ '|---|---|---|---|---|---|---|',
783
+ ...rows,
784
+ '',
785
+ `Volume ${fmt(r.volume)} mm³.${limit != null ? ` Limit on movement: ${fmt(limit)} mm.` : ''}${minSafety != null ? ` Least safety factor: ${fmt(minSafety)}×.` : ''}`,
786
+ '',
787
+ '## Findings',
788
+ '',
789
+ ...found.map((f) => `- ${f.level}: ${f.text}`),
790
+ '',
791
+ '## Verification',
792
+ '',
793
+ ...(records.length
794
+ ? records.map(
795
+ (v) => `- ${v.kind}, ${v.date}${v.by ? `, by ${v.by}` : ''}: ${v.summary}${v.source ? ` (${v.source})` : ''}`,
796
+ )
797
+ : [
798
+ r.critical
799
+ ? '**Unverified.** This part is safety-critical: do not rely on it until a test or an independent analysis is recorded.'
800
+ : 'None recorded.',
801
+ ]),
802
+ '',
803
+ "## What this doesn't cover",
804
+ '',
359
805
  '- The analysis is linear and static, on cubes: a design aid, not engineering sign-off. Stress at sharp inside corners, and where supports and loads are applied, depends on the cell size; compare a finer cell before trusting a peak.',
360
806
  '- Material values are data-sheet figures. Printed parts vary with the printer, settings and spool, and are weaker across their layers; measure your own.',
361
- '- Buckling, impact, creep, heat and wear are not checked.', '',
807
+ '- Buckling, impact, creep, heat and wear are not checked.',
808
+ '',
362
809
  ].join('\n');
363
810
  }
364
811
 
365
812
  async function analyses(b, d, tag) {
366
- const lookup = (n) => { const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), b.values); if (typeof v !== 'number') throw new Error(`analysis: "${n}" isn't a number`); return v; };
813
+ const lookup = (n) => {
814
+ const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), b.values);
815
+ if (typeof v !== 'number') throw new Error(`analysis: "${n}" isn't a number`);
816
+ return v;
817
+ };
367
818
  const all = [];
368
- for (const a of b.object.analysis || []) all.push(...await (async () => {
369
- const part = a.part ? b.parts.find((p) => p.name === a.part) : b.parts.find((p) => p.role !== 'support');
370
- if (!part) return [{ level: 'fail', text: `analysis: no part "${a.part}"`, code: 'fea.part' }];
371
- // A part drawn in its print orientation, turned back into the problem's frame: rotated (degrees about x, then y,
372
- // then z, as JSCAD's rotate), then moved
373
- const turn = (a.rotate || []).map((x) => evaluate(x, lookup)).some(Boolean) || (a.move || []).map((x) => evaluate(x, lookup)).some(Boolean);
374
- const turned = turn ? place(part.triangles, (a.rotate || [0, 0, 0]).map((x) => evaluate(x, lookup)), (a.move || [0, 0, 0]).map((x) => evaluate(x, lookup))) : part.triangles;
375
- const cell = a.cell != null ? evaluate(a.cell, lookup) : undefined;
376
- const r = await analysePart(turned, d.project, a.problem, { cell }), m = r.material;
377
- // A check of the check: with a cell given, the part is analysed again on cells a quarter bigger, and how much each
378
- // number changes says whether the cells are small enough. Peak stress at a sharp inside corner never settles (in
379
- // theory it's endless there), so it's reported, not judged.
380
- if (cell) {
381
- const coarser = await analysePart(turned, d.project, a.problem, { cell: cell * 1.25 });
382
- r.cases.forEach((c, n) => { const o = coarser.cases[n]; c.change = { stiffness: stiffOf(c) / stiffOf(o) - 1, stress: c.stress / o.stress - 1, cell: coarser.grid.h }; });
383
- }
384
- const limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
385
- const minSafety = a.min_safety != null ? evaluate(a.min_safety, lookup) : null;
386
- let out = null;
387
- if (r.dim !== 3) { // a flat part's picture: its cells as analysed, with the supports and loads
388
- out = paths.preview(d.project, `${d.name}${tag}-analysis-${a.problem.replace(':', '-')}.svg`);
389
- fs.mkdirSync(path.dirname(out), { recursive: true });
390
- fs.writeFileSync(out, picture({ ...r, ...(await readProblem(d.project, a.problem)).problem }, { title: `${b.object.title || d.name}: ${a.problem}`, lines: r.cases.map((c) => `${c.name}: ${sig(c.deflection)} mm, ${sig(c.stiffness)} N/mm, peak stress ${sig(c.stress)} MPa`) }));
391
- }
392
- // Safety factors: against the material's strength (its weaker one across a print's layers, where it has one), and
393
- // its fatigue strength where it has one
394
- const strength = m.strength ? Math.min(m.strength, m.strength_z ?? Infinity) : null, weaker = m.strength_z != null && m.strength_z < m.strength;
395
- const grid = `${[r.grid.nx, r.grid.ny, r.grid.nz].filter(Boolean).join(' × ')} cells of ${fmt(r.grid.h)} mm`;
396
- const at = (p) => `(${p.map(fmt).join(', ')})`;
397
- const found = r.cases.flatMap((c) => {
398
- const safety = strength ? strength / c.stress : null, fatigue = m.fatigue ? m.fatigue / c.stress : null;
399
- const text = c.moment ? `${a.problem} ${c.name}: ${howFar(c)}` : `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm`;
400
- const values = { ...(c.moment ? { angle: c.angle, moment: c.moment, torsion: c.torsion } : { deflection: c.deflection, force: c.force, stiffness: c.stiffness }), stress: c.stress, ...(limit != null ? { limit } : {}) };
401
- const refs = { problem: a.problem, part: part.name, ...(out ? { picture: path.relative(WS, out) } : {}) };
402
- const strong = `peak stress ${sig(c.stress)} MPa at ${at(c.stressAt)}${safety != null ? `: ${sig(safety)}× under ${m.name}'s ${weaker ? 'strength across its layers' : 'strength'}${fatigue != null ? `, ${sig(fatigue)}× under its fatigue strength` : ''}` : ''}`;
403
- const least = Math.min(safety ?? Infinity, fatigue ?? Infinity);
404
- const settled = c.change ? [{ level: Math.abs(c.change.stiffness) <= 0.05 ? 'pass' : 'warn', code: 'fea.settled', values: c.change,
405
- text: `${a.problem} ${c.name}: stiffness ${c.change.stiffness >= 0 ? '+' : ''}${fmt(c.change.stiffness * 100)}% from ${fmt(c.change.cell)} mm cells${Math.abs(c.change.stiffness) <= 0.05 ? ', settled (within 5%)' : ': not settled, use a smaller cell'}` }] : [];
406
- return [
407
- { level: limit == null || c.moment ? 'info' : c.deflection <= limit ? 'pass' : 'fail', text: limit == null ? text : `${text} (at most ${fmt(limit)})`, code: 'fea.deflection', values, refs }, ...settled,
408
- { level: minSafety == null ? 'info' : least >= minSafety ? 'pass' : 'fail', text: `${a.problem} ${c.name}: ${strong}${minSafety != null ? ` (at least ${fmt(minSafety)}×)` : ''}`, code: 'fea.strength',
409
- values: { stress: c.stress, at: c.stressAt, ...(safety != null ? { safety } : {}), ...(fatigue != null ? { fatigue } : {}), ...(minSafety != null ? { min: minSafety } : {}) }, refs },
410
- ];
411
- });
412
- // Members the grid is too coarse for: under four cells thick, a cell's stiffness is a rough figure
413
- if (r.thin && r.thin.share > 0.05) found.push({ level: 'warn', code: 'fea.coarse', values: { share: r.thin.share, cells: r.thin.cells, cell: r.grid.h }, refs: { problem: a.problem, part: part.name },
414
- text: `${a.problem}: ${fmt(r.thin.share * 100)}% of the part is in members under ${r.thin.cells} cells (${fmt(r.thin.cells * r.grid.h)} mm) thick, where the stiffness is rough: use a smaller cell (${fmt(r.grid.h / 2)} mm) and see that it settles` });
415
- const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
416
- if (a.volume != null) {
417
- const want = evaluate(a.volume, lookup), tol = a.tolerance ?? 0.01, off = (r.volume - want) / want;
418
- found.push({ level: Math.abs(off) <= tol ? 'pass' : 'fail', text: `volume ${fmt(r.volume)} mm³${grams}: ${off >= 0 ? '+' : ''}${fmt(off * 100)}% from ${fmt(want)} (within ${fmt(tol * 100)}%)`, code: 'fea.volume', values: { volume: r.volume, target: want, off } });
419
- } else found.push({ level: 'info', text: `volume ${fmt(r.volume)} mm³${grams}`, code: 'fea.volume', values: { volume: r.volume } });
420
- // A safety-critical part stays unverified until a test or an independent analysis is recorded against it
421
- const records = b.object.verification || [];
422
- if (r.critical) found.push(records.length
423
- ? { level: 'pass', text: `${a.problem} is safety-critical: verified by ${records.map((v) => `${v.kind} (${v.date})`).join(', ')}`, code: 'fea.verified', values: { records } }
424
- : { level: 'warn', text: `${a.problem} is safety-critical and unverified: rulecad's analysis is a design aid. Test it, or have it analysed independently, and record that under "verification"`, code: 'fea.unverified' });
425
- // The report: everything above, with where, written next to the previews
426
- const report = paths.preview(d.project, `${d.name}${tag}-report-${a.problem.replace(':', '-')}.md`);
427
- fs.mkdirSync(path.dirname(report), { recursive: true });
428
- fs.writeFileSync(report, reportText({ turn, object: `${d.project}/${d.name}${tag}`, title: b.object.title || d.name, version: b.object.version, a, r, m, strength, weaker, grid, limit, minSafety, records, found }));
429
- fs.writeFileSync(report.replace(/\.md$/, '.json'), JSON.stringify({ object: `${d.project}/${d.name}${tag}`, version: b.object.version, problem: a.problem, critical: r.critical, verification: records, material: { name: m.name, modulus: m.modulus, strength: m.strength, ...(m.strength_z != null ? { strength_z: m.strength_z } : {}), ...(m.fatigue != null ? { fatigue: m.fatigue } : {}) }, grid: r.grid, volume: r.volume, cases: r.cases, findings: found.map(({ level, code, text }) => ({ level, code, text })) }, null, 2) + '\n');
430
- found.push({ level: 'info', text: `report (${grid}): ${path.relative(WS, report)}`, code: 'fea.report', refs: { report: path.relative(WS, report) } });
431
- return found;
432
- })());
819
+ for (const a of b.object.analysis || [])
820
+ all.push(
821
+ ...(await (async () => {
822
+ const part = a.part ? b.parts.find((p) => p.name === a.part) : b.parts.find((p) => p.role !== 'support');
823
+ if (!part) return [{ level: 'fail', text: `analysis: no part "${a.part}"`, code: 'fea.part' }];
824
+ // A part drawn in its print orientation, turned back into the problem's frame: rotated (degrees about x, then y,
825
+ // then z, as JSCAD's rotate), then moved
826
+ const turn =
827
+ (a.rotate || []).map((x) => evaluate(x, lookup)).some(Boolean) ||
828
+ (a.move || []).map((x) => evaluate(x, lookup)).some(Boolean);
829
+ const turned = turn
830
+ ? place(
831
+ part.triangles,
832
+ (a.rotate || [0, 0, 0]).map((x) => evaluate(x, lookup)),
833
+ (a.move || [0, 0, 0]).map((x) => evaluate(x, lookup)),
834
+ )
835
+ : part.triangles;
836
+ const cell = a.cell != null ? evaluate(a.cell, lookup) : undefined;
837
+ const r = await analysePart(turned, d.project, a.problem, { cell }),
838
+ m = r.material;
839
+ // A check of the check: with a cell given, the part is analysed again on cells a quarter bigger, and how much each
840
+ // number changes says whether the cells are small enough (settledFinding). The peak stress is judged only where
841
+ // the part is held to a safety factor (min_safety): at a sharp inside corner it never settles (in theory it's
842
+ // endless there), so elsewhere it's reported, not judged.
843
+ if (cell) {
844
+ const coarser = await analysePart(turned, d.project, a.problem, { cell: cell * 1.25 });
845
+ r.cases.forEach((c, n) => {
846
+ const o = coarser.cases[n];
847
+ c.change = {
848
+ stiffness: stiffOf(c) / stiffOf(o) - 1,
849
+ stress: c.stress / o.stress - 1,
850
+ cell: coarser.grid.h,
851
+ };
852
+ });
853
+ }
854
+ const limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
855
+ const minSafety = a.min_safety != null ? evaluate(a.min_safety, lookup) : null;
856
+ let out = null;
857
+ if (r.dim !== 3) {
858
+ // a flat part's picture: its cells as analysed, with the supports and loads
859
+ out = paths.preview(d.project, `${d.name}${tag}-analysis-${a.problem.replace(':', '-')}.svg`);
860
+ fs.mkdirSync(path.dirname(out), { recursive: true });
861
+ fs.writeFileSync(
862
+ out,
863
+ picture(
864
+ { ...r, ...(await readProblem(d.project, a.problem)).problem },
865
+ {
866
+ title: `${b.object.title || d.name}: ${a.problem}`,
867
+ lines: r.cases.map(
868
+ (c) =>
869
+ `${c.name}: ${sig(c.deflection)} mm, ${sig(c.stiffness)} N/mm, peak stress ${sig(c.stress)} MPa`,
870
+ ),
871
+ },
872
+ ),
873
+ );
874
+ }
875
+ // Safety factors: against the material's strength (its weaker one across a print's layers, where it has one), and
876
+ // its fatigue strength where it has one
877
+ const strength = m.strength ? Math.min(m.strength, m.strength_z ?? Infinity) : null,
878
+ weaker = m.strength_z != null && m.strength_z < m.strength;
879
+ const grid = `${[r.grid.nx, r.grid.ny, r.grid.nz].filter(Boolean).join(' × ')} cells of ${fmt(r.grid.h)} mm`;
880
+ const at = (p) => `(${p.map(fmt).join(', ')})`;
881
+ const found = r.cases.flatMap((c) => {
882
+ const safety = strength ? strength / c.stress : null,
883
+ fatigue = m.fatigue ? m.fatigue / c.stress : null;
884
+ const text = c.moment
885
+ ? `${a.problem} ${c.name}: ${howFar(c)}`
886
+ : `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm`;
887
+ const values = {
888
+ ...(c.moment
889
+ ? { angle: c.angle, moment: c.moment, torsion: c.torsion }
890
+ : { deflection: c.deflection, force: c.force, stiffness: c.stiffness }),
891
+ stress: c.stress,
892
+ ...(limit != null ? { limit } : {}),
893
+ };
894
+ const refs = { problem: a.problem, part: part.name, ...(out ? { picture: path.relative(WS, out) } : {}) };
895
+ const strong = `peak stress ${sig(c.stress)} MPa at ${at(c.stressAt)}${safety != null ? `: ${sig(safety)}× under ${m.name}'s ${weaker ? 'strength across its layers' : 'strength'}${fatigue != null ? `, ${sig(fatigue)}× under its fatigue strength` : ''}` : ''}`;
896
+ const least = Math.min(safety ?? Infinity, fatigue ?? Infinity);
897
+ const settled = c.change ? [settledFinding(a.problem, c.name, c.change, minSafety != null)] : [];
898
+ return [
899
+ {
900
+ level: limit == null || c.moment ? 'info' : c.deflection <= limit ? 'pass' : 'fail',
901
+ text: limit == null ? text : `${text} (at most ${fmt(limit)})`,
902
+ code: 'fea.deflection',
903
+ values,
904
+ refs,
905
+ },
906
+ ...settled,
907
+ {
908
+ level: minSafety == null ? 'info' : least >= minSafety ? 'pass' : 'fail',
909
+ text: `${a.problem} ${c.name}: ${strong}${minSafety != null ? ` (at least ${fmt(minSafety)}×)` : ''}`,
910
+ code: 'fea.strength',
911
+ values: {
912
+ stress: c.stress,
913
+ at: c.stressAt,
914
+ ...(safety != null ? { safety } : {}),
915
+ ...(fatigue != null ? { fatigue } : {}),
916
+ ...(minSafety != null ? { min: minSafety } : {}),
917
+ },
918
+ refs,
919
+ },
920
+ ];
921
+ });
922
+ // Members the grid is too coarse for: under four cells thick, a cell's stiffness is a rough figure
923
+ if (r.thin && r.thin.share > 0.05)
924
+ found.push({
925
+ level: 'warn',
926
+ code: 'fea.coarse',
927
+ values: { share: r.thin.share, cells: r.thin.cells, cell: r.grid.h },
928
+ refs: { problem: a.problem, part: part.name },
929
+ text: `${a.problem}: ${fmt(r.thin.share * 100)}% of the part is in members under ${r.thin.cells} cells (${fmt(r.thin.cells * r.grid.h)} mm) thick, where the stiffness is rough: use a smaller cell (${fmt(r.grid.h / 2)} mm) and see that it settles`,
930
+ });
931
+ const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
932
+ if (a.volume != null) {
933
+ const want = evaluate(a.volume, lookup),
934
+ tol = a.tolerance ?? 0.01,
935
+ off = (r.volume - want) / want;
936
+ found.push({
937
+ level: Math.abs(off) <= tol ? 'pass' : 'fail',
938
+ text: `volume ${fmt(r.volume)} mm³${grams}: ${off >= 0 ? '+' : ''}${fmt(off * 100)}% from ${fmt(want)} (within ${fmt(tol * 100)}%)`,
939
+ code: 'fea.volume',
940
+ values: { volume: r.volume, target: want, off },
941
+ });
942
+ } else
943
+ found.push({
944
+ level: 'info',
945
+ text: `volume ${fmt(r.volume)} mm³${grams}`,
946
+ code: 'fea.volume',
947
+ values: { volume: r.volume },
948
+ });
949
+ // A safety-critical part stays unverified until a test or an independent analysis is recorded against it
950
+ const records = b.object.verification || [];
951
+ if (r.critical)
952
+ found.push(
953
+ records.length
954
+ ? {
955
+ level: 'pass',
956
+ text: `${a.problem} is safety-critical: verified by ${records.map((v) => `${v.kind} (${v.date})`).join(', ')}`,
957
+ code: 'fea.verified',
958
+ values: { records },
959
+ }
960
+ : {
961
+ level: 'warn',
962
+ text: `${a.problem} is safety-critical and unverified: rulecad's analysis is a design aid. Test it, or have it analysed independently, and record that under "verification"`,
963
+ code: 'fea.unverified',
964
+ },
965
+ );
966
+ // The report: everything above, with where, written next to the previews
967
+ const report = paths.preview(d.project, `${d.name}${tag}-report-${a.problem.replace(':', '-')}.md`);
968
+ fs.mkdirSync(path.dirname(report), { recursive: true });
969
+ fs.writeFileSync(
970
+ report,
971
+ reportText({
972
+ turn,
973
+ object: `${d.project}/${d.name}${tag}`,
974
+ title: b.object.title || d.name,
975
+ version: b.object.version,
976
+ a,
977
+ r,
978
+ m,
979
+ strength,
980
+ weaker,
981
+ grid,
982
+ limit,
983
+ minSafety,
984
+ records,
985
+ found,
986
+ }),
987
+ );
988
+ fs.writeFileSync(
989
+ report.replace(/\.md$/, '.json'),
990
+ JSON.stringify(
991
+ {
992
+ object: `${d.project}/${d.name}${tag}`,
993
+ version: b.object.version,
994
+ problem: a.problem,
995
+ critical: r.critical,
996
+ verification: records,
997
+ material: {
998
+ name: m.name,
999
+ modulus: m.modulus,
1000
+ strength: m.strength,
1001
+ ...(m.strength_z != null ? { strength_z: m.strength_z } : {}),
1002
+ ...(m.fatigue != null ? { fatigue: m.fatigue } : {}),
1003
+ },
1004
+ grid: r.grid,
1005
+ volume: r.volume,
1006
+ cases: r.cases,
1007
+ findings: found.map(({ level, code, text }) => ({ level, code, text })),
1008
+ },
1009
+ null,
1010
+ 2,
1011
+ ) + '\n',
1012
+ );
1013
+ found.push({
1014
+ level: 'info',
1015
+ text: `report (${grid}): ${path.relative(WS, report)}`,
1016
+ code: 'fea.report',
1017
+ refs: { report: path.relative(WS, report) },
1018
+ });
1019
+ return found;
1020
+ })()),
1021
+ );
433
1022
  return all;
434
1023
  }
435
1024
 
@@ -437,108 +1026,220 @@ async function analyses(b, d, tag) {
437
1026
  function ruleSheets(what, names) {
438
1027
  if (what === 'check') {
439
1028
  // a set fails on a finding of level fail; a warning or a note is said and the set still passes
440
- const results = checkSets(names), fails = (r) => r.findings.filter((x) => x.level === 'fail').length, bad = results.filter(fails), noted = results.filter((r) => r.findings.length && !fails(r));
441
- if (opt('json')) console.log(JSON.stringify(results.map((r) => ({ name: r.name, findings: r.findings, ...(r.notes ? { notes: r.notes } : {}) })), null, 2));
1029
+ const results = checkSets(names),
1030
+ fails = (r) => r.findings.filter((x) => x.level === 'fail').length,
1031
+ bad = results.filter(fails),
1032
+ noted = results.filter((r) => r.findings.length && !fails(r));
1033
+ if (opt('json'))
1034
+ console.log(
1035
+ JSON.stringify(
1036
+ results.map((r) => ({ name: r.name, findings: r.findings, ...(r.notes ? { notes: r.notes } : {}) })),
1037
+ null,
1038
+ 2,
1039
+ ),
1040
+ );
442
1041
  else {
443
- for (const r of results.filter((x) => x.findings.length)) { console.log(`${r.name}: ${fails(r) ? `${fails(r)} to fix` : `passes, ${r.findings.length} to know`}`); for (const x of r.findings) console.log(` ${{ fail: 'FAIL', warn: 'WARN', info: 'NOTE' }[x.level] ?? 'FAIL'} ${x.text} (${x.code})`); }
1042
+ for (const r of results.filter((x) => x.findings.length)) {
1043
+ console.log(`${r.name}: ${fails(r) ? `${fails(r)} to fix` : `passes, ${r.findings.length} to know`}`);
1044
+ for (const x of r.findings)
1045
+ console.log(` ${{ fail: 'FAIL', warn: 'WARN', info: 'NOTE' }[x.level] ?? 'FAIL'} ${x.text} (${x.code})`);
1046
+ }
444
1047
  // notes never fail: an alias names one line per set, what a copy lacks of the kit's set says it whole
445
1048
  for (const r of results.filter((x) => x.notes)) {
446
- const alias = r.notes.filter((x) => x.code === 'rules.alias'), rest = r.notes.filter((x) => x.code !== 'rules.alias');
447
- if (alias.length) console.log(`${r.name}: NOTE ${alias.map((x) => `${x.rule} is also read as ${x.values.alias}`).join(', ')} (rules.alias)`);
1049
+ const alias = r.notes.filter((x) => x.code === 'rules.alias'),
1050
+ rest = r.notes.filter((x) => x.code !== 'rules.alias');
1051
+ if (alias.length)
1052
+ console.log(
1053
+ `${r.name}: NOTE ${alias.map((x) => `${x.rule} is also read as ${x.values.alias}`).join(', ')} (rules.alias)`,
1054
+ );
448
1055
  for (const x of rest) console.log(`${r.name}: NOTE ${x.text} (${x.code})`);
449
1056
  }
450
- console.log(`${results.length - bad.length} of ${results.length} rule sets pass${noted.length ? ` (${noted.length} with something to know)` : ''}`);
1057
+ console.log(
1058
+ `${results.length - bad.length} of ${results.length} rule sets pass${noted.length ? ` (${noted.length} with something to know)` : ''}`,
1059
+ );
451
1060
  }
452
1061
  process.exitCode = bad.length ? 1 : 0;
453
1062
  return;
454
1063
  }
455
1064
  const name = names[0];
456
- if (!name) throw new Error(`usage: cad rules ${what} <set>${what === 'draft' ? ` --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>` : ''}`);
457
- if (what === 'draw') { const to = opt('out') || `${name}.svg`; fs.writeFileSync(to, drawSet(name)); return console.log(`drew ${to}: compare it with the datasheet`); }
1065
+ if (!name)
1066
+ throw new Error(
1067
+ `usage: cad rules ${what} <set>${what === 'draft' ? ` --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>` : ''}`,
1068
+ );
1069
+ if (what === 'draw') {
1070
+ const to = opt('out') || `${name}.svg`;
1071
+ fs.writeFileSync(to, drawSet(name));
1072
+ return console.log(`drew ${to}: compare it with the datasheet`);
1073
+ }
458
1074
  const save = (as, set) => {
459
- const to = path.join(paths.rules ? paths.rules() : path.join(WS, 'rules'), `${as}.json`);
460
- if (fs.existsSync(to) && !opt('force')) throw new Error(`${path.relative(WS, to)} already exists (--force replaces it)`);
461
- fs.mkdirSync(path.dirname(to), { recursive: true }); fs.writeFileSync(to, JSON.stringify(set, null, 2) + '\n');
1075
+ const to = insideWorkspace(
1076
+ path.join(paths.rules ? paths.rules() : path.join(WS, 'rules'), `${plainName(as, 'rule set name')}.json`),
1077
+ ); // (from the command line: never ../, nor through a link out of rules/)
1078
+ if (fs.existsSync(to) && !opt('force'))
1079
+ throw new Error(`${path.relative(WS, to)} already exists (--force replaces it)`);
1080
+ fs.mkdirSync(path.dirname(to), { recursive: true });
1081
+ fs.writeFileSync(to, JSON.stringify(set, null, 2) + '\n');
462
1082
  return to;
463
1083
  };
464
1084
  // cad rules draft profile <name>: every field of the vocabulary for that part, to fill from a sheet
465
1085
  if (draftParts().includes(name) && !opt('from')) {
466
- const part = name, as = names[1];
1086
+ const part = name,
1087
+ as = names[1];
467
1088
  if (!as) throw new Error(`usage: cad rules draft ${part} <name>`);
468
1089
  const to = save(as, draftPart(part, as));
469
- return console.log(`a draft ${part.replace('_', ' ')} in ${path.relative(WS, to)}, every figure an estimate: fill it from the maker's sheet (source, page, date), then cad rules check ${as} and cad rules draw ${as}`);
1090
+ return console.log(
1091
+ `a draft ${part.replace('_', ' ')} in ${path.relative(WS, to)}, every figure an estimate: fill it from the maker's sheet (source, page, date), then cad rules check ${as} and cad rules draw ${as}`,
1092
+ );
470
1093
  }
471
- if (!opt('from')) throw new Error(`usage: cad rules draft <name> --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>`);
1094
+ if (!opt('from'))
1095
+ throw new Error(
1096
+ `usage: cad rules draft <name> --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>`,
1097
+ );
472
1098
  const { set, found } = draftSet(name, opt('from'));
473
- if (!found) return console.log(`no figures in ${opt('from')}'s text: it's probably a picture of a drawing, so read it by eye and write rules/${name}.json by hand`);
1099
+ if (!found)
1100
+ return console.log(
1101
+ `no figures in ${opt('from')}'s text: it's probably a picture of a drawing, so read it by eye and write rules/${name}.json by hand`,
1102
+ );
474
1103
  const to = save(name, set);
475
- return console.log(`${found} figures in ${path.relative(WS, to)}, every one an estimate: name them from the vocabulary, check them against the datasheet, then cad rules check ${name}`);
1104
+ return console.log(
1105
+ `${found} figures in ${path.relative(WS, to)}, every one an estimate: name them from the vocabulary, check them against the datasheet, then cad rules check ${name}`,
1106
+ );
476
1107
  }
477
1108
 
478
1109
  async function main() {
479
- const first = args[0], pos = positional(), [cmd = first, ref] = pos; // names first or options first: cad check --json keyboard/case
1110
+ const first = args[0],
1111
+ pos = positional(),
1112
+ [cmd = first, ref] = pos; // names first or options first: cad check --json keyboard/case
480
1113
  if (!first || ['help', '--help', '-h'].includes(first)) return console.log(HELP);
481
- if (['--version', '-v', 'version'].includes(first)) return console.log(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
482
- if (!COMMANDS.includes(cmd)) { const guess = near(cmd, COMMANDS); throw new Error(`no command "${cmd}"${guess ? ` (did you mean "${guess}"?)` : ''}: cad help lists them`); }
1114
+ if (['--version', '-v', 'version'].includes(first))
1115
+ return console.log(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
1116
+ if (!COMMANDS.includes(cmd)) {
1117
+ const guess = near(cmd, COMMANDS);
1118
+ throw new Error(`no command "${cmd}"${guess ? ` (did you mean "${guess}"?)` : ''}: cad help lists them`);
1119
+ }
483
1120
  const odd = args.find((a) => a.startsWith('--') && !OPTIONS.includes(a.slice(2)));
484
- if (odd) { const guess = near(odd.slice(2), OPTIONS); throw new Error(`no option ${odd}${guess ? ` (did you mean --${guess}?)` : ''}: cad help lists them`); }
1121
+ if (odd) {
1122
+ const guess = near(odd.slice(2), OPTIONS);
1123
+ throw new Error(`no option ${odd}${guess ? ` (did you mean --${guess}?)` : ''}: cad help lists them`);
1124
+ }
485
1125
  if (configError) throw configError;
486
- if (opt('dry-run') && !takesDryRun(cmd)) throw new Error(`cad ${cmd}${opt('size') ? ' --size' : ''} takes no --dry-run, so nothing is run: ${DRY_RUNS}`);
487
-
488
- if (cmd === 'new' && (opt('assembly') || !String(ref || '').includes('/'))) return newCommand(ref ?? (typeof opt('assembly') === 'string' ? opt('assembly') : undefined));
489
- if (cmd === 'new') { // an object, from the template; --dry-run and --json as the other edits
490
- const r = newObject(ref, { dryRun: !!opt('dry-run') }), [project, name] = String(ref).split('/');
1126
+ if (opt('dry-run') && !takesDryRun(cmd))
1127
+ throw new Error(`cad ${cmd}${opt('size') ? ' --size' : ''} takes no --dry-run, so nothing is run: ${DRY_RUNS}`);
1128
+
1129
+ if (cmd === 'new' && (opt('assembly') || !String(ref || '').includes('/')))
1130
+ return newCommand(ref ?? (typeof opt('assembly') === 'string' ? opt('assembly') : undefined));
1131
+ if (cmd === 'new') {
1132
+ // an object, from the template; --dry-run and --json as the other edits
1133
+ const r = newObject(ref, { dryRun: !!opt('dry-run') }),
1134
+ [project, name] = String(ref).split('/');
491
1135
  return edited(r, 'new', {}, `${r.dryRun ? 'would make' : 'made'} projects/${project}/objects/${name}.{js,json}`);
492
1136
  }
493
1137
 
494
1138
  if (cmd === 'rules' && ['check', 'draw', 'draft'].includes(ref)) return ruleSheets(ref, pos.slice(2));
495
1139
 
496
- if (cmd === 'trust') { // this workspace may do what its cad.config.json asks (designs outside the sandbox, its own targets)
1140
+ if (cmd === 'trust') {
1141
+ // this workspace may do what its cad.config.json asks (designs outside the sandbox, its own targets)
497
1142
  const what = asks();
498
1143
  if (!what.length) return console.log('this workspace asks for nothing outside the sandbox: nothing to trust');
499
1144
  trust();
500
- return console.log(`trusted ${WS} for ${what.join(' and ')} (kept in your own list; a workspace that asks for more is asked again)`);
1145
+ return console.log(
1146
+ `trusted ${WS} for ${what.join(' and ')} (kept in your own list; a workspace that asks for more is asked again)`,
1147
+ );
501
1148
  }
502
1149
 
503
- if (cmd === 'agents') { // the notes for AI agents, into this workspace (AGENTS.md, and CLAUDE.md pointing at it)
504
- const to = path.join(WS, 'AGENTS.md'), ours = fs.readFileSync(path.join(TOOL, 'AGENTS.md'), 'utf8'), record = paths.cache('agents.md');
1150
+ if (cmd === 'agents') {
1151
+ // the notes for AI agents, into this workspace (AGENTS.md, and CLAUDE.md pointing at it)
1152
+ const to = path.join(WS, 'AGENTS.md'),
1153
+ ours = fs.readFileSync(path.join(TOOL, 'AGENTS.md'), 'utf8'),
1154
+ record = paths.cache('agents.md');
505
1155
  // An AGENTS.md as cad agents last wrote it (or, with no record of that, one that is an earlier copy of ours) is
506
1156
  // brought up to date; one edited here is kept, unless --force
507
- const mine = fs.existsSync(to) ? fs.readFileSync(to, 'utf8') : null, last = fs.existsSync(record) ? fs.readFileSync(record, 'utf8') : null;
508
- const ourCopy = mine === null || mine === ours || (last !== null ? mine === last : mine.startsWith(ours.split('\n')[0]));
509
- 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)');
510
- fs.writeFileSync(to, ours); fs.mkdirSync(path.dirname(record), { recursive: true }); fs.writeFileSync(record, ours);
1157
+ const mine = fs.existsSync(to) ? fs.readFileSync(to, 'utf8') : null,
1158
+ last = fs.existsSync(record) ? fs.readFileSync(record, 'utf8') : null;
1159
+ const ourCopy =
1160
+ mine === null || mine === ours || (last !== null ? mine === last : mine.startsWith(ours.split('\n')[0]));
1161
+ if (!ourCopy && !opt('force'))
1162
+ throw new Error(
1163
+ "AGENTS.md here has been edited (or isn't rulecad's): it is kept as it is (cad agents --force replaces it)",
1164
+ );
1165
+ fs.writeFileSync(to, ours);
1166
+ fs.mkdirSync(path.dirname(record), { recursive: true });
1167
+ fs.writeFileSync(record, ours);
511
1168
  const claude = path.join(WS, 'CLAUDE.md');
512
1169
  if (!fs.existsSync(claude)) fs.writeFileSync(claude, '@AGENTS.md\n');
513
1170
  else if (!fs.readFileSync(claude, 'utf8').includes('@AGENTS.md')) fs.appendFileSync(claude, '\n@AGENTS.md\n');
514
- return console.log(`wrote ${path.relative(process.cwd(), to) || 'AGENTS.md'}: how an AI agent should design here (CLAUDE.md includes it)`);
1171
+ return console.log(
1172
+ `wrote ${path.relative(process.cwd(), to) || 'AGENTS.md'}: how an AI agent should design here (CLAUDE.md includes it)`,
1173
+ );
515
1174
  }
516
- if (cmd === 'import-kle') { // a layout from keyboard-layout-editor.com into a project's layouts/
1175
+ if (cmd === 'import-kle') {
1176
+ // a layout from keyboard-layout-editor.com into a project's layouts/
517
1177
  const [project, name] = String(pos[2] || '').split('/');
518
- if (!ref || !fs.existsSync(ref) || !project || !/^[a-z][a-z0-9-]*$/.test(name || '')) throw new Error('usage: cad import-kle <layout.json> <project>/<name> (the JSON download, or a file with its Raw data)');
1178
+ if (!ref || !fs.existsSync(ref) || !project || !/^[a-z][a-z0-9-]*$/.test(name || ''))
1179
+ throw new Error(
1180
+ 'usage: cad import-kle <layout.json> <project>/<name> (the JSON download, or a file with its Raw data)',
1181
+ );
519
1182
  const { layout, notes } = fromKLE(fs.readFileSync(ref, 'utf8'));
520
1183
  const to = path.join(paths.project(project), 'layouts', `${name}.json`);
521
- if (fs.existsSync(to) && !opt('force')) throw new Error(`${path.relative(WS, to)} already exists (--force to replace it)`);
1184
+ if (fs.existsSync(to) && !opt('force'))
1185
+ throw new Error(`${path.relative(WS, to)} already exists (--force to replace it)`);
522
1186
  fs.mkdirSync(path.dirname(to), { recursive: true });
523
1187
  fs.writeFileSync(to, `${JSON.stringify({ title: layout.title || name, ...layout }, null, 1)}\n`);
524
- console.log(`made ${path.relative(WS, to)}: ${layout.rows.length} rows, ${layout.rows.flat().filter((k) => !k.gap).length} keys`);
1188
+ console.log(
1189
+ `made ${path.relative(WS, to)}: ${layout.rows.length} rows, ${layout.rows.flat().filter((k) => !k.gap).length} keys`,
1190
+ );
525
1191
  for (const n of notes) console.log(` note: ${n}`);
526
1192
  return;
527
1193
  }
528
- if (cmd === 'clone') return cloneBoard(ref, pos[2], { source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), noModels: !!opt('no-models') });
1194
+ if (cmd === 'clone')
1195
+ return cloneBoard(ref, pos[2], {
1196
+ source: opt('source'),
1197
+ licence: opt('licence') || opt('license'),
1198
+ force: !!opt('force'),
1199
+ noModels: !!opt('no-models'),
1200
+ });
529
1201
  if (cmd === 'status') return status(ref);
530
1202
  if (cmd === 'measure') {
531
- if (!ref) throw new Error('usage: cad measure <model.stl|model.3mf> [--along x] [--at 10,50] [--line 0.6,2.5] [--rules <name>], or cad measure <beam.stl|3mf|section.dxf> --profile <name>');
1203
+ if (!ref)
1204
+ throw new Error(
1205
+ 'usage: cad measure <model.stl|model.3mf> [--along x] [--at 10,50] [--line 0.6,2.5] [--rules <name>], or cad measure <beam.stl|3mf|section.dxf> --profile <name>',
1206
+ );
532
1207
  if (opt('profile')) {
533
1208
  const { measureProfile } = await import('../lib/profilemeasure.mjs');
534
- return measureProfile(ref, { profile: opt('profile'), along: opt('along'), tol: opt('tol') && opt('tol') !== true ? opt('tol') : undefined, source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), pictures: !opt('no-pictures') });
1209
+ return measureProfile(ref, {
1210
+ profile: opt('profile'),
1211
+ along: opt('along'),
1212
+ tol: opt('tol') && opt('tol') !== true ? opt('tol') : undefined,
1213
+ source: opt('source'),
1214
+ licence: opt('licence') || opt('license'),
1215
+ force: !!opt('force'),
1216
+ pictures: !opt('no-pictures'),
1217
+ });
535
1218
  }
536
- if (/\.dxf$/i.test(ref)) throw new Error('a DXF is a drawing of a section, not a model: cad measure <section.dxf> --profile <name> reads a beam\'s profile from it');
537
- const list = (k) => (opt(k) && opt(k) !== true ? String(opt(k)).split(k === 'line' ? ';' : ',').filter(Boolean) : []);
538
- return measure(ref, { along: opt('along'), at: list('at'), line: list('line'), rules: opt('rules'), source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), pictures: !opt('no-pictures') });
1219
+ if (/\.dxf$/i.test(ref))
1220
+ throw new Error(
1221
+ "a DXF is a drawing of a section, not a model: cad measure <section.dxf> --profile <name> reads a beam's profile from it",
1222
+ );
1223
+ const list = (k) =>
1224
+ opt(k) && opt(k) !== true
1225
+ ? String(opt(k))
1226
+ .split(k === 'line' ? ';' : ',')
1227
+ .filter(Boolean)
1228
+ : [];
1229
+ return measure(ref, {
1230
+ along: opt('along'),
1231
+ at: list('at'),
1232
+ line: list('line'),
1233
+ rules: opt('rules'),
1234
+ source: opt('source'),
1235
+ licence: opt('licence') || opt('license'),
1236
+ force: !!opt('force'),
1237
+ pictures: !opt('no-pictures'),
1238
+ });
539
1239
  }
540
1240
  if (!ref || (cmd === 'add' && !pos[2])) throw new Error(`usage: cad ${cmd} ${USAGE[cmd] || '<project>/<object>'}`);
541
- if (cmd === 'release') return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
1241
+ if (cmd === 'release')
1242
+ return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
542
1243
  if (cmd === 'variants') return variants(locate(ref));
543
1244
  if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
544
1245
  if (cmd === 'measured') return measuredCommand(ref);
@@ -551,32 +1252,50 @@ async function main() {
551
1252
  if (cmd === 'diff') return diff(locate(ref), pos[2], pos[3] || null);
552
1253
  if (cmd === 'printed') return printed(locate(ref));
553
1254
  if (cmd === 'why') return explainValue(ref);
554
- if (cmd === 'set') return isAssembly(ref) ? editFields(ref) : !ref.includes('/') ? editProject(ref) : editVariables(ref);
1255
+ if (cmd === 'set')
1256
+ return isAssembly(ref) ? editFields(ref) : !ref.includes('/') ? editProject(ref) : editVariables(ref);
555
1257
  if (cmd === 'add') return editAssembly(pos[1], pos[2]);
556
1258
  if (cmd === 'remove' || cmd === 'move') return removeOrMove(cmd, ref, pos[2]);
557
1259
  if (cmd === 'optimise' || cmd === 'optimize') return await optimiseProblem(ref);
558
1260
  // A problem file's preview: its result drawn, and its run to watch again (or live, with --watch)
559
1261
  const problemRef = /^(?:projects[\\/])?([^\\/]+)[\\/]problems[\\/]([^\\/:]+?)(?:\.json)?(:[^\\/]+)?$/.exec(ref || '');
560
- if (cmd === 'preview' && problemRef) return await optimiseProblem(`${problemRef[1]}/${problemRef[2]}${problemRef[3] || ''}`, { preview: true });
1262
+ if (cmd === 'preview' && problemRef)
1263
+ return await optimiseProblem(`${problemRef[1]}/${problemRef[2]}${problemRef[3] || ''}`, { preview: true });
561
1264
  if (isAssembly(ref)) return assembly(cmd, ref);
562
1265
  const [base, at] = ref.split('@');
563
- const d = at ? materialise(locate(base), at) : locate(ref), set = sets();
1266
+ const d = at ? materialise(locate(base), at) : locate(ref),
1267
+ set = sets();
564
1268
  // A check reads the files against their schemas first: a broken .json is said as that, before a build fails on it
565
1269
  if (cmd === 'check' && !at && fs.existsSync(d.json)) {
566
1270
  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)
567
- if (bad.length) { say(`${d.project}/${d.name}`); report(bad, { object: `${d.project}/${d.name}` }); process.exitCode = 1; return; }
1271
+ if (bad.length) {
1272
+ say(`${d.project}/${d.name}`);
1273
+ report(bad, { object: `${d.project}/${d.name}` });
1274
+ process.exitCode = 1;
1275
+ return;
1276
+ }
568
1277
  }
569
1278
  const b = opt('part') ? pick(await build(d, set), { part: opt('part') }) : await build(d, set);
570
1279
  const tag = `${d.variant ? `-${d.variant}` : ''}${suffix(set)}${opt('part') ? `-${opt('part')}` : ''}`; // in file names
571
- const title = `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`, version = b.object.version || '0.0.0';
1280
+ const title = `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`,
1281
+ version = b.object.version || '0.0.0';
572
1282
 
573
1283
  if (b.circuit && ['check', 'preview', 'export'].includes(cmd)) return board(cmd, d, b, { title, version, tag });
574
1284
 
575
1285
  if (cmd === 'match') {
576
1286
  const file = pos[2];
577
- if (!file || file.startsWith('--')) throw new Error(`usage: cad match ${ref} <model.stl|model.3mf> [--tol 0.2] [--place "rz90 t1,2,3"]`);
578
- const tol = opt('tol') ? Number(opt('tol')) : printer(b, d).fit ?? 0.2;
579
- const ok = await match(b, d, file, { place: opt('place'), tol, samples: Number(opt('samples')) || 20000, at: opt('at') ? String(opt('at')).split(',') : [], title: `${title} ${version}`, tag, pictures: !opt('no-pictures') });
1287
+ if (!file || file.startsWith('--'))
1288
+ throw new Error(`usage: cad match ${ref} <model.stl|model.3mf> [--tol 0.2] [--place "rz90 t1,2,3"]`);
1289
+ const tol = opt('tol') ? Number(opt('tol')) : (printer(b, d).fit ?? 0.2);
1290
+ const ok = await match(b, d, file, {
1291
+ place: opt('place'),
1292
+ tol,
1293
+ samples: Number(opt('samples')) || 20000,
1294
+ at: opt('at') ? String(opt('at')).split(',') : [],
1295
+ title: `${title} ${version}`,
1296
+ tag,
1297
+ pictures: !opt('no-pictures'),
1298
+ });
580
1299
  process.exitCode = ok ? 0 : 1;
581
1300
  return;
582
1301
  }
@@ -584,60 +1303,152 @@ async function main() {
584
1303
  if (cmd === 'values') {
585
1304
  const list = valuesOf(b, positional().slice(2));
586
1305
  if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, values: list }, null, 2));
587
- for (const v of list) console.log(`${v.name.padEnd(18)} ${`${fmt(v.value)} ${v.unit}`.padEnd(14)} ${v.expr ? `= ${v.expr}` : ''}`);
1306
+ for (const v of list)
1307
+ console.log(`${v.name.padEnd(18)} ${`${fmt(v.value)} ${v.unit}`.padEnd(14)} ${v.expr ? `= ${v.expr}` : ''}`);
588
1308
  return;
589
1309
  }
590
1310
 
591
1311
  if (cmd === 'rules') {
592
- 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));
593
- 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)' : ''}`);
1312
+ if (opt('json'))
1313
+ return console.log(
1314
+ JSON.stringify(
1315
+ {
1316
+ object: `${d.project}/${d.name}`,
1317
+ variables: b.entries.map((e) => ({
1318
+ name: e.name,
1319
+ value: e.value,
1320
+ unit: e.unit || null,
1321
+ expr: e.expr || null,
1322
+ rule: e.rule || null,
1323
+ ...(e.source ? { source: e.source, kind: e.kind || null } : {}),
1324
+ })),
1325
+ },
1326
+ null,
1327
+ 2,
1328
+ ),
1329
+ );
1330
+ for (const e of b.entries)
1331
+ console.log(
1332
+ `${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)' : ''}`,
1333
+ );
594
1334
  return;
595
1335
  }
596
1336
 
597
1337
  if (cmd === 'check') {
598
1338
  say(`${title} ${version}${Object.keys(set).length ? ` (${suffix(set).slice(1)})` : ''}`);
599
- const raw = lint(fs.readFileSync(d.js, 'utf8')), file = path.relative(WS, d.js);
1339
+ const raw = lint(readOwnText(d.js)),
1340
+ file = path.relative(WS, d.js);
600
1341
  // The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
601
- 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));
602
- const problemFiles = [...new Set([...Object.values(b.object.variables || {}).filter((v) => v.type === 'problem').flatMap((v) => v.choice || [v.value]), ...(b.object.analysis || []).map((a) => a.problem)].map((n) => problemFile(d.project, String(n).split(':')[0])))].filter((f) => fs.existsSync(f));
603
- const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f))),
604
- ...problemFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'problem', own(f)))];
605
- const failed = report([
606
- ...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
607
- ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
608
- ...unruled(b.object, own(d.json)),
609
- 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 } }
610
- : { level: 'pass', text: 'every measurement is a variable', code: 'lint.numbers', refs: { file } },
611
- ...(b.object.role === 'reference'
612
- ? [{ level: 'pass', text: `a reference (${(await import('@rulecad/printcheck')).bounds(b.triangles).size.map(fmt).join(' × ')} mm), not printed: no print checks`, code: 'print.reference' }]
613
- : await printChecks(b, d)),
614
- ...(b.mechanism?.findings || []), // a lamina mechanism's own: it prints free, stops, holds, clears in every state
615
- ...(b.fixings || []), // what v.fixings drew: each hole and seat, what it was drawn to and the rule it rests on
616
- ...(await analyses(b, d, tag)),
617
- ], { object: `${d.project}/${d.name}`, title, version, ...(Object.keys(set).length ? { set } : {}), orientation: b.object.orientation, parts: b.parts.map((p) => ({ name: p.name, role: p.role || 'part' })) });
1342
+ const own = (f) => path.relative(WS, f),
1343
+ ruleFiles = (b.object.uses || [])
1344
+ .filter((u) => !u.includes('/'))
1345
+ .map((u) => path.join(WS, 'rules', `${u}.json`))
1346
+ .filter((f) => fs.existsSync(f));
1347
+ const problemFiles = [
1348
+ ...new Set(
1349
+ [
1350
+ ...Object.values(b.object.variables || {})
1351
+ .filter((v) => v.type === 'problem')
1352
+ .flatMap((v) => v.choice || [v.value]),
1353
+ ...(b.object.analysis || []).map((a) => a.problem),
1354
+ ].map((n) => problemFile(d.project, String(n).split(':')[0])),
1355
+ ),
1356
+ ].filter((f) => fs.existsSync(f));
1357
+ const schemaProblems = [
1358
+ ...schemaFindings(readJson(d.json), 'object', own(d.json)),
1359
+ ...ruleFiles.flatMap((f) => schemaFindings(readJson(f), 'rules', own(f))),
1360
+ ...problemFiles.flatMap((f) => schemaFindings(readJson(f), 'problem', own(f))),
1361
+ ];
1362
+ const failed = report(
1363
+ [
1364
+ ...(schemaProblems.length
1365
+ ? schemaProblems
1366
+ : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
1367
+ ...(b.units || []).map((u) => ({
1368
+ level: 'warn',
1369
+ text: `units: ${u.message}`,
1370
+ code: 'units',
1371
+ refs: { file: own(d.json), path: u.path, variable: u.name },
1372
+ })),
1373
+ ...unruled(b.object, own(d.json)),
1374
+ raw.length
1375
+ ? {
1376
+ level: 'fail',
1377
+ text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}`,
1378
+ code: 'lint.numbers',
1379
+ refs: { file, numbers: raw },
1380
+ }
1381
+ : { level: 'pass', text: 'every measurement is a variable', code: 'lint.numbers', refs: { file } },
1382
+ ...(b.object.role === 'reference'
1383
+ ? [
1384
+ {
1385
+ level: 'pass',
1386
+ text: `a reference (${(await import('@rulecad/printcheck')).bounds(b.triangles).size.map(fmt).join(' × ')} mm), not printed: no print checks`,
1387
+ code: 'print.reference',
1388
+ },
1389
+ ]
1390
+ : await printChecks(b, d)),
1391
+ ...(b.mechanism?.findings || []), // a lamina mechanism's own: it prints free, stops, holds, clears in every state
1392
+ ...(b.fixings || []), // what v.fixings drew: each hole and seat, what it was drawn to and the rule it rests on
1393
+ ...(await analyses(b, d, tag)),
1394
+ ],
1395
+ {
1396
+ object: `${d.project}/${d.name}`,
1397
+ title,
1398
+ version,
1399
+ ...(Object.keys(set).length ? { set } : {}),
1400
+ orientation: b.object.orientation,
1401
+ parts: b.parts.map((p) => ({ name: p.name, role: p.role || 'part' })),
1402
+ },
1403
+ );
618
1404
  if (b.object.orientation) say(` orientation: ${b.object.orientation}`);
619
- if (b.parts.length > 1) say(` parts: ${b.parts.map((p) => `${p.name}${p.role === 'support' ? ' (support)' : ''}`).join(', ')}`);
1405
+ if (b.parts.length > 1)
1406
+ say(` parts: ${b.parts.map((p) => `${p.name}${p.role === 'support' ? ' (support)' : ''}`).join(', ')}`);
620
1407
  process.exitCode = failed ? 1 : 0;
621
1408
  return;
622
1409
  }
623
1410
 
624
1411
  if (cmd === 'animate') {
625
- if (!b.mechanism) throw new Error(`${d.project}/${d.name} isn't a lamina mechanism: cad animate plays the sequence of one made with flexures.lamina()`);
1412
+ if (!b.mechanism)
1413
+ throw new Error(
1414
+ `${d.project}/${d.name} isn't a lamina mechanism: cad animate plays the sequence of one made with flexures.lamina()`,
1415
+ );
626
1416
  const out = paths.preview(d.project, `${d.name}${tag}-sequence.svg`);
627
1417
  fs.mkdirSync(path.dirname(out), { recursive: true });
628
- fs.writeFileSync(out, (await import('../lib/animate.mjs')).sequenceSvg(b.mechanism, { title: `${title} ${version}: ${(b.mechanism.sequence || []).join(', ')}` }));
1418
+ fs.writeFileSync(
1419
+ out,
1420
+ (await import('../lib/animate.mjs')).sequenceSvg(b.mechanism, {
1421
+ title: `${title} ${version}: ${(b.mechanism.sequence || []).join(', ')}`,
1422
+ }),
1423
+ );
629
1424
  // and the sequence as data (shapes, forces, energies, strains each frame), with a page that plays it
630
- const { playerData, playerHtml } = await import('../lib/player.mjs'), data = playerData(b.mechanism, { title, version, object: `${d.project}/${d.name}` });
631
- const json = paths.preview(d.project, `${d.name}${tag}-sequence.json`), html = paths.preview(d.project, `${d.name}${tag}-player.html`);
632
- fs.writeFileSync(json, JSON.stringify(data)); fs.writeFileSync(html, playerHtml(data));
633
- console.log(out); console.log(json); return console.log(html);
1425
+ const { playerData, playerHtml } = await import('../lib/player.mjs'),
1426
+ data = playerData(b.mechanism, { title, version, object: `${d.project}/${d.name}` });
1427
+ const json = paths.preview(d.project, `${d.name}${tag}-sequence.json`),
1428
+ html = paths.preview(d.project, `${d.name}${tag}-player.html`);
1429
+ fs.writeFileSync(json, JSON.stringify(data));
1430
+ fs.writeFileSync(html, playerHtml(data));
1431
+ console.log(out);
1432
+ console.log(json);
1433
+ return console.log(html);
634
1434
  }
635
1435
 
636
1436
  if (cmd === 'preview') {
637
1437
  const out = paths.preview(d.project, `${d.name}${tag}${opt('explode') ? '-exploded' : ''}.png`);
638
- const size = (await import('@rulecad/printcheck')).bounds(b.triangles).size.map((n) => fmt(n)).join(' × ');
639
- const parts = b.parts.length > 1 ? ` · ${b.parts.map((p) => (p.role === 'support' ? `${p.label} (faint)` : p.label)).join(', ')}` : '';
640
- await preview(b.parts, { title: `${title} ${version}${opt('part') ? `: ${b.parts[0].label}` : ''}`, meta: [`${size} mm`, b.object.material].filter(Boolean).join(' · ') + parts, out, explode: !!opt('explode') });
1438
+ const size = (await import('@rulecad/printcheck'))
1439
+ .bounds(b.triangles)
1440
+ .size.map((n) => fmt(n))
1441
+ .join(' × ');
1442
+ const parts =
1443
+ b.parts.length > 1
1444
+ ? ` · ${b.parts.map((p) => (p.role === 'support' ? `${p.label} (faint)` : p.label)).join(', ')}`
1445
+ : '';
1446
+ await preview(b.parts, {
1447
+ title: `${title} ${version}${opt('part') ? `: ${b.parts[0].label}` : ''}`,
1448
+ meta: [`${size} mm`, b.object.material].filter(Boolean).join(' · ') + parts,
1449
+ out,
1450
+ explode: !!opt('explode'),
1451
+ });
641
1452
  return console.log(out);
642
1453
  }
643
1454
 
@@ -645,10 +1456,28 @@ async function main() {
645
1456
  const out = paths.exports(d.project, `${d.name}@${version}${tag}.3mf`);
646
1457
  fs.mkdirSync(path.dirname(out), { recursive: true });
647
1458
  const fil = filaments(d.project); // one object, a part per part, each in its filament
648
- 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) }));
1459
+ fs.writeFileSync(
1460
+ out,
1461
+ await threemf(
1462
+ [
1463
+ {
1464
+ name: `${d.name}${d.variant ? ` ${d.variant}` : ''}`,
1465
+ parts: b.parts.map((p) => ({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) })),
1466
+ },
1467
+ ],
1468
+ { filaments: slots(fil) },
1469
+ ),
1470
+ );
649
1471
  const notes = filamentNotes(b.parts, fil);
650
1472
  if (opt('open')) openInSlicer(out);
651
- 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)
1473
+ if (opt('json'))
1474
+ return console.log(
1475
+ JSON.stringify(
1476
+ { object: `${d.project}/${d.name}`, version, file: path.relative(WS, out), findings: notes },
1477
+ null,
1478
+ 2,
1479
+ ),
1480
+ ); // (one object: the file is in it, not a line after)
652
1481
  report(notes);
653
1482
  return console.log(out);
654
1483
  }
@@ -659,8 +1488,18 @@ async function main() {
659
1488
  const light = b.object.mirror && !opt('part') ? await build(d, set, { mirror: true }) : b; // the object's mirror settings
660
1489
  const shown = pick(light, { forMirror: true }); // the design itself, not what holds it up while printing, nor fine detail
661
1490
  // The rules card: the variables marked show, one line each
662
- const items = b.entries.filter((e) => e.show).slice(0, 6).map((e) => `${e.label || e.name} ${fmt(e.value)} ${e.unit || ''}${e.set ? ' (set)' : ''}`.trim());
663
- await (await target('show'))({ title: `${title} ${version}`, ttl: opt('ttl') || '10m', mesh: { polygons: shown.polygons }, card: { title: `${title} rules`, items } });
1491
+ const items = b.entries
1492
+ .filter((e) => e.show)
1493
+ .slice(0, 6)
1494
+ .map((e) => `${e.label || e.name} ${fmt(e.value)} ${e.unit || ''}${e.set ? ' (set)' : ''}`.trim());
1495
+ await (
1496
+ await target('show')
1497
+ )({
1498
+ title: `${title} ${version}`,
1499
+ ttl: opt('ttl') || '10m',
1500
+ mesh: { polygons: shown.polygons },
1501
+ card: { title: `${title} rules`, items },
1502
+ });
664
1503
  return await printLinks(await links(d, b, set));
665
1504
  }
666
1505
 
@@ -675,10 +1514,23 @@ async function main() {
675
1514
  // keeping the file's layout; refused if the variables wouldn't resolve
676
1515
  async function editVariables(ref) {
677
1516
  const pairs = positional().slice(2);
678
- if (!ref || !pairs.length || pairs.some((p) => !p.includes('='))) throw new Error('usage: cad set <project>/<object> name=value [name=value …] [--unit mm] [--rule "why"] [--label "Label"] [--new]');
679
- const extra = Object.fromEntries(['unit', 'rule', 'label'].filter((k) => typeof opt(k) === 'string').map((k) => [k, opt(k)]));
680
- if (pairs.length > 1 && (extra.rule || extra.label)) throw new Error(`--${extra.rule ? 'rule' : 'label'} describes one variable: set ${pairs.map((p) => p.split('=')[0]).join(' and ')} one at a time`);
681
- const changes = Object.fromEntries(pairs.map((p) => { const i = p.indexOf('='); return [p.slice(0, i).trim(), { value: parseValue(p.slice(i + 1).trim()), ...extra }]; }));
1517
+ if (!ref || !pairs.length || pairs.some((p) => !p.includes('=')))
1518
+ throw new Error(
1519
+ 'usage: cad set <project>/<object> name=value [name=value …] [--unit mm] [--rule "why"] [--label "Label"] [--new]',
1520
+ );
1521
+ const extra = Object.fromEntries(
1522
+ ['unit', 'rule', 'label'].filter((k) => typeof opt(k) === 'string').map((k) => [k, opt(k)]),
1523
+ );
1524
+ if (pairs.length > 1 && (extra.rule || extra.label))
1525
+ throw new Error(
1526
+ `--${extra.rule ? 'rule' : 'label'} describes one variable: set ${pairs.map((p) => p.split('=')[0]).join(' and ')} one at a time`,
1527
+ );
1528
+ const changes = Object.fromEntries(
1529
+ pairs.map((p) => {
1530
+ const i = p.indexOf('=');
1531
+ return [p.slice(0, i).trim(), { value: parseValue(p.slice(i + 1).trim()), ...extra }];
1532
+ }),
1533
+ );
682
1534
  const r = await setVariables(ref, changes, { create: !!opt('new'), dryRun: !!opt('dry-run') });
683
1535
  if (opt('json')) return console.log(JSON.stringify(r));
684
1536
  console.log(`${r.dryRun ? `dry run, nothing written: would set` : 'set'} ${r.changed.join(', ')} in ${rel(r.file)}`);
@@ -686,86 +1538,265 @@ async function editVariables(ref) {
686
1538
 
687
1539
  // cad add fit|joint|item|loop|pose|fasten|join <project>/<assembly> --key value …: add to an assembly, keeping its layout
688
1540
  async function editAssembly(what, ref) {
689
- const list = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => parseValue(x.trim())) : undefined);
690
- const pick = (keys) => Object.fromEntries(keys.map((k) => [k, typeof opt(k) === 'string' ? parseValue(opt(k)) : undefined]).filter(([, v]) => v !== undefined));
691
- const text = (keys) => Object.fromEntries(keys.filter((k) => typeof opt(k) === 'string').map((k) => [k, String(opt(k))]));
1541
+ const list = (k) =>
1542
+ typeof opt(k) === 'string'
1543
+ ? opt(k)
1544
+ .split(',')
1545
+ .map((x) => parseValue(x.trim()))
1546
+ : undefined;
1547
+ const pick = (keys) =>
1548
+ Object.fromEntries(
1549
+ keys
1550
+ .map((k) => [k, typeof opt(k) === 'string' ? parseValue(opt(k)) : undefined])
1551
+ .filter(([, v]) => v !== undefined),
1552
+ );
1553
+ const text = (keys) =>
1554
+ Object.fromEntries(keys.filter((k) => typeof opt(k) === 'string').map((k) => [k, String(opt(k))]));
692
1555
  // (an item's at is a point, 1,2,3, or an address on a beam: --at x1.top@50%)
693
- const at = () => (typeof opt('at') !== 'string' ? {} : /^[a-z][\w-]*\./i.test(opt('at')) ? { at: String(opt('at')) } : { at: list('at') });
1556
+ const at = () =>
1557
+ typeof opt('at') !== 'string'
1558
+ ? {}
1559
+ : /^[a-z][\w-]*\./i.test(opt('at'))
1560
+ ? { at: String(opt('at')) }
1561
+ : { at: list('at') };
694
1562
  let entry;
695
- if (what === 'fit') entry = { ...text(['a', 'b']), ...pick(['min', 'max']), ...(list('poses') ? { poses: list('poses').map(String) } : {}), ...text(['note', 'label']) };
696
- else if (what === 'joint') entry = { ...text(['id', 'type', 'parent', 'child', 'label', 'follow']), ...pick(['min', 'max', 'value', 'ratio']) };
1563
+ if (what === 'fit')
1564
+ entry = {
1565
+ ...text(['a', 'b']),
1566
+ ...pick(['min', 'max']),
1567
+ ...(list('poses') ? { poses: list('poses').map(String) } : {}),
1568
+ ...text(['note', 'label']),
1569
+ };
1570
+ else if (what === 'joint')
1571
+ entry = {
1572
+ ...text(['id', 'type', 'parent', 'child', 'label', 'follow']),
1573
+ ...pick(['min', 'max', 'value', 'ratio']),
1574
+ };
697
1575
  else if (what === 'beam') {
698
- if (typeof opt('profile') !== 'string') throw new Error('usage: cad add beam <project>/<assembly> --id x1 --profile 2020-misumi-hfs5 --from 0,0,0 --to 300,0,0 [--roll 90] [--length 300] [--material al6063-t5], or --length 300 --at 0,0,0 --rotate 0,90,0');
699
- entry = { ...text(['id']), beam: { profile: String(opt('profile')), ...pick(['length']), ...text(['material']) }, ...(list('from') ? { from: list('from') } : {}), ...(list('to') ? { to: list('to') } : {}), ...pick(['roll']), ...at(), ...(list('rotate') ? { rotate: list('rotate') } : {}) };
700
- } else if (what === 'item') entry = { ...text(['id', 'object', 'assembly', 'variant']), ...at(), ...(list('rotate') ? { rotate: list('rotate') } : {}),
701
- ...(typeof opt('set') === 'string' ? { set: Object.fromEntries(sets() && Object.entries(sets()).map(([k, v]) => [k, parseValue(v)])) } : {}) };
1576
+ if (typeof opt('profile') !== 'string')
1577
+ throw new Error(
1578
+ 'usage: cad add beam <project>/<assembly> --id x1 --profile 2020-misumi-hfs5 --from 0,0,0 --to 300,0,0 [--roll 90] [--length 300] [--material al6063-t5], or --length 300 --at 0,0,0 --rotate 0,90,0',
1579
+ );
1580
+ entry = {
1581
+ ...text(['id']),
1582
+ beam: { profile: String(opt('profile')), ...pick(['length']), ...text(['material']) },
1583
+ ...(list('from') ? { from: list('from') } : {}),
1584
+ ...(list('to') ? { to: list('to') } : {}),
1585
+ ...pick(['roll']),
1586
+ ...at(),
1587
+ ...(list('rotate') ? { rotate: list('rotate') } : {}),
1588
+ };
1589
+ } else if (what === 'item')
1590
+ entry = {
1591
+ ...text(['id', 'object', 'assembly', 'variant']),
1592
+ ...at(),
1593
+ ...(list('rotate') ? { rotate: list('rotate') } : {}),
1594
+ ...(typeof opt('set') === 'string'
1595
+ ? { set: Object.fromEntries(sets() && Object.entries(sets()).map(([k, v]) => [k, parseValue(v)])) }
1596
+ : {}),
1597
+ };
702
1598
  else if (what === 'loop') entry = text(['a', 'b', 'label']);
703
- else if (what === 'fasten' && opt('from-fits')) { // a holes fit and a fit that fastens, put as one fasten
704
- const s = await buildAssembly(ref), { fastenFromFits } = await import('../lib/fasten.mjs');
705
- const r = fastenFromFitsEdit(ref, fastenFromFits(s), { screw: typeof opt('screw') === 'string' ? opt('screw') : undefined, dryRun: !!opt('dry-run') });
1599
+ else if (what === 'fasten' && opt('from-fits')) {
1600
+ // a holes fit and a fit that fastens, put as one fasten
1601
+ const s = await buildAssembly(ref),
1602
+ { fastenFromFits } = await import('../lib/fasten.mjs');
1603
+ const r = fastenFromFitsEdit(ref, fastenFromFits(s), {
1604
+ screw: typeof opt('screw') === 'string' ? opt('screw') : undefined,
1605
+ dryRun: !!opt('dry-run'),
1606
+ });
706
1607
  if (opt('json')) return console.log(JSON.stringify(r));
707
1608
  if (r.dryRun) console.log('dry run, nothing written:');
708
- for (const x of r.added) console.log(`${r.dryRun ? 'would add' : 'added'} a fasten to ${rel(r.file)} in place of its holes fit and its fit that fastens: ${JSON.stringify(x)}`);
1609
+ for (const x of r.added)
1610
+ console.log(
1611
+ `${r.dryRun ? 'would add' : 'added'} a fasten to ${rel(r.file)} in place of its holes fit and its fit that fastens: ${JSON.stringify(x)}`,
1612
+ );
709
1613
  return console.log(`check its screws: cad check ${ref}`);
710
- }
711
- else if (what === 'fasten') { // --screw "M3 cap" --through bracket --into base --at bracket.h1,bracket.h2 | --holes bracket.body [--nut [hex] --washer --length 12 --torque 0.5 --note …]
712
- const names = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => x.trim()).filter(Boolean) : undefined);
713
- entry = { ...text(['screw']), through: names('through') ?? [], ...text(['into']), ...(names('at') ? { at: names('at') } : {}), ...text(['holes']), ...(opt('nut') ? { nut: opt('nut') === true ? true : String(opt('nut')) } : {}), ...(opt('washer') ? { washer: true } : {}), ...pick(['length', 'torque']), ...text(['note']) };
714
- }
715
- else if (what === 'join') entry = text(['kind', 'a', 'b', 'fitting', 'screw', 'note']);
1614
+ } else if (what === 'fasten') {
1615
+ // --screw "M3 cap" --through bracket --into base --at bracket.h1,bracket.h2 | --holes bracket.body [--nut [hex] --washer --length 12 --torque 0.5 --note …]
1616
+ const names = (k) =>
1617
+ typeof opt(k) === 'string'
1618
+ ? opt(k)
1619
+ .split(',')
1620
+ .map((x) => x.trim())
1621
+ .filter(Boolean)
1622
+ : undefined;
1623
+ entry = {
1624
+ ...text(['screw']),
1625
+ through: names('through') ?? [],
1626
+ ...text(['into']),
1627
+ ...(names('at') ? { at: names('at') } : {}),
1628
+ ...text(['holes']),
1629
+ ...(opt('nut') ? { nut: opt('nut') === true ? true : String(opt('nut')) } : {}),
1630
+ ...(opt('washer') ? { washer: true } : {}),
1631
+ ...pick(['length', 'torque']),
1632
+ ...text(['note']),
1633
+ };
1634
+ } else if (what === 'join') entry = text(['kind', 'a', 'b', 'fitting', 'screw', 'note']);
716
1635
  else if (what === 'pose') {
717
1636
  const pairs = positional().slice(3);
718
- if (typeof opt('name') !== 'string' || !pairs.length) throw new Error('usage: cad add pose <project>/<assembly> --name open hinge=90 [joint=value …]');
719
- entry = { name: opt('name'), values: Object.fromEntries(pairs.map((p) => { const [k, v] = p.split('='); return [k.trim(), v.includes(',') ? v.split(',').map(parseValue) : parseValue(v)]; })) };
1637
+ if (typeof opt('name') !== 'string' || !pairs.length)
1638
+ throw new Error('usage: cad add pose <project>/<assembly> --name open hinge=90 [joint=value …]');
1639
+ entry = {
1640
+ name: opt('name'),
1641
+ values: Object.fromEntries(
1642
+ pairs.map((p) => {
1643
+ const [k, v] = p.split('=');
1644
+ return [k.trim(), v.includes(',') ? v.split(',').map(parseValue) : parseValue(v)];
1645
+ }),
1646
+ ),
1647
+ };
720
1648
  } else if (what === 'load') entry = { ...text(['joint']), ...pick(['mass', 'torque']), ...at(), ...text(['note']) };
721
1649
  else if (what === 'guide' || what === 'wire') entry = { ...text(['id', 'kind', 'note']) };
722
- else throw new Error('usage: cad add fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]');
1650
+ else
1651
+ throw new Error(
1652
+ 'usage: cad add fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]',
1653
+ );
723
1654
  // field=value pairs, for any field (nested by dots: motor.model=nema17), over the options
724
- if (what !== 'pose') for (const [k, v] of pairsOf(positional().slice(3), 'cad add')) { const keys = k.split('.'); let o = entry; for (const x of keys.slice(0, -1)) o = (o[x] ??= {}); o[keys.at(-1)] = v; }
1655
+ if (what !== 'pose')
1656
+ for (const [k, v] of pairsOf(positional().slice(3), 'cad add')) {
1657
+ const keys = k.split('.');
1658
+ let o = entry;
1659
+ for (const x of keys.slice(0, -1)) o = o[x] ??= {};
1660
+ o[keys.at(-1)] = v;
1661
+ }
725
1662
  const r = addToAssembly(ref, what === 'beam' ? 'item' : what, entry, { dryRun: !!opt('dry-run') });
726
- edited(r, 'add', { added: entry }, `${opt('dry-run') ? 'would add' : 'added'} ${/^[aeiou]/.test(what) ? 'an' : 'a'} ${what} to ${rel(r.file)} (${r.changes[0].path})`);
1663
+ edited(
1664
+ r,
1665
+ 'add',
1666
+ { added: entry },
1667
+ `${opt('dry-run') ? 'would add' : 'added'} ${/^[aeiou]/.test(what) ? 'an' : 'a'} ${what} to ${rel(r.file)} (${r.changes[0].path})`,
1668
+ );
727
1669
  }
728
1670
 
729
1671
  // name=value pairs from the command line, each value as cad set takes it; refused by name where one has no =
730
1672
  function pairsOf(list, what) {
731
1673
  const bad = list.find((p) => !p.includes('='));
732
1674
  if (bad) throw new Error(`${what}: "${bad}" isn't field=value`);
733
- return list.map((p) => { const i = p.indexOf('='); return [p.slice(0, i).trim(), parseSetting(p.slice(i + 1))]; });
1675
+ return list.map((p) => {
1676
+ const i = p.indexOf('=');
1677
+ return [p.slice(0, i).trim(), parseSetting(p.slice(i + 1))];
1678
+ });
734
1679
  }
735
1680
  const rel = (f) => path.relative(WS, f).split(path.sep).join('/');
736
- const shownValue = (v) => (v === undefined ? 'nothing' : JSON.stringify(v).length > 70 ? `${JSON.stringify(v).slice(0, 67)}...` : JSON.stringify(v));
1681
+ const shownValue = (v) =>
1682
+ v === undefined
1683
+ ? 'nothing'
1684
+ : JSON.stringify(v).length > 70
1685
+ ? `${JSON.stringify(v).slice(0, 67)}...`
1686
+ : JSON.stringify(v);
737
1687
  // What an edit did, as words or as data (--json): its changes, then its checks
738
1688
  function edited(r, command, extra = {}, head = null) {
739
- if (opt('json')) return console.log(JSON.stringify({ command, file: rel(r.file), written: r.written, ...(r.dryRun ? { dryRun: true } : {}), ...(r.made ? { made: r.made.map(rel) } : {}), ...extra, changes: r.changes, findings: r.findings }, null, 2));
740
- const verb = { set: 'set', add: 'added', remove: 'removed', make: 'made' }, would = r.dryRun ? 'would be ' : '';
741
- console.log(`${r.dryRun ? 'dry run, nothing written: ' : ''}${head ?? `${rel(r.file)}${r.dryRun || r.written ? '' : ' (no change)'}`}`);
742
- if (!head) for (const c of r.changes) console.log(` ${would}${verb[c.op]} ${c.path}${c.op === 'set' ? `: ${shownValue(c.before)} → ${shownValue(c.after)}` : c.op === 'add' ? `: ${shownValue(c.after)}` : c.because ? ` (it ${c.because})` : ''}`);
1689
+ if (opt('json'))
1690
+ return console.log(
1691
+ JSON.stringify(
1692
+ {
1693
+ command,
1694
+ file: rel(r.file),
1695
+ written: r.written,
1696
+ ...(r.dryRun ? { dryRun: true } : {}),
1697
+ ...(r.made ? { made: r.made.map(rel) } : {}),
1698
+ ...extra,
1699
+ changes: r.changes,
1700
+ findings: r.findings,
1701
+ },
1702
+ null,
1703
+ 2,
1704
+ ),
1705
+ );
1706
+ const verb = { set: 'set', add: 'added', remove: 'removed', make: 'made' },
1707
+ would = r.dryRun ? 'would be ' : '';
1708
+ console.log(
1709
+ `${r.dryRun ? 'dry run, nothing written: ' : ''}${head ?? `${rel(r.file)}${r.dryRun || r.written ? '' : ' (no change)'}`}`,
1710
+ );
1711
+ if (!head)
1712
+ for (const c of r.changes)
1713
+ console.log(
1714
+ ` ${would}${verb[c.op]} ${c.path}${c.op === 'set' ? `: ${shownValue(c.before)} → ${shownValue(c.after)}` : c.op === 'add' ? `: ${shownValue(c.after)}` : c.because ? ` (it ${c.because})` : ''}`,
1715
+ );
743
1716
  report(r.findings);
744
1717
  }
745
1718
 
746
1719
  // cad new <project> [--title --description --material --printer], cad new <project>/<assembly> --assembly [--frame ...]
747
1720
  async function newCommand(ref) {
748
- const dryRun = !!opt('dry-run'), str = (k) => (typeof opt(k) === 'string' ? opt(k) : undefined);
749
- if (!ref) throw new Error('usage: cad new <project>/<object>, cad new <project>, or cad new <project>/<assembly> --assembly');
750
- if (!ref.includes('/')) return edited(newProject(ref, { title: str('title'), description: str('description'), material: str('material'), printer: str('printer'), dryRun }), 'new');
1721
+ const dryRun = !!opt('dry-run'),
1722
+ str = (k) => (typeof opt(k) === 'string' ? opt(k) : undefined);
1723
+ if (!ref)
1724
+ throw new Error('usage: cad new <project>/<object>, cad new <project>, or cad new <project>/<assembly> --assembly');
1725
+ if (!ref.includes('/'))
1726
+ return edited(
1727
+ newProject(ref, {
1728
+ title: str('title'),
1729
+ description: str('description'),
1730
+ material: str('material'),
1731
+ printer: str('printer'),
1732
+ dryRun,
1733
+ }),
1734
+ 'new',
1735
+ );
751
1736
  let frame;
752
1737
  // the frame's options go with --frame, and a join's fitting and screw with --join: none is dropped unsaid
753
- const FRAME_OPTS = ['inside', 'outside', 'profile', 'join', 'fitting', 'screw', 'feet', 'caps'], loose = FRAME_OPTS.filter((k) => opt(k) !== undefined);
754
- if (!opt('frame') && loose.length) throw new Error(`--${loose.join(', --')} ${loose.length === 1 ? 'is a frame option' : 'are frame options'}: give --frame box|portal|table|gantry|shelf with ${loose.length === 1 ? 'it' : 'them'}, or set the fields after with cad set ${ref} frame.<field>=…`);
755
- if (opt('frame') && !str('join') && (str('fitting') || str('screw'))) throw new Error(`--${['fitting', 'screw'].filter((k) => str(k)).join(' and --')} ${str('fitting') && str('screw') ? 'say' : 'says'} how the join is made: give the join's kind with ${str('fitting') && str('screw') ? 'them' : 'it'}, as --join blind`);
1738
+ const FRAME_OPTS = ['inside', 'outside', 'profile', 'join', 'fitting', 'screw', 'feet', 'caps'],
1739
+ loose = FRAME_OPTS.filter((k) => opt(k) !== undefined);
1740
+ if (!opt('frame') && loose.length)
1741
+ throw new Error(
1742
+ `--${loose.join(', --')} ${loose.length === 1 ? 'is a frame option' : 'are frame options'}: give --frame box|portal|table|gantry|shelf with ${loose.length === 1 ? 'it' : 'them'}, or set the fields after with cad set ${ref} frame.<field>=…`,
1743
+ );
1744
+ if (opt('frame') && !str('join') && (str('fitting') || str('screw')))
1745
+ throw new Error(
1746
+ `--${['fitting', 'screw'].filter((k) => str(k)).join(' and --')} ${str('fitting') && str('screw') ? 'say' : 'says'} how the join is made: give the join's kind with ${str('fitting') && str('screw') ? 'them' : 'it'}, as --join blind`,
1747
+ );
756
1748
  if (opt('frame')) {
757
- const nums = (k) => (str(k) ? str(k).split(',').map((x) => parseValue(x.trim())) : undefined);
758
- const join = str('join') && (str('fitting') || str('screw')) ? { kind: str('join'), ...(str('fitting') ? { fitting: str('fitting') } : {}), ...(str('screw') ? { screw: str('screw') } : {}) } : str('join');
759
- frame = Object.fromEntries(Object.entries({ kind: str('frame'), inside: nums('inside'), outside: nums('outside'), profile: str('profile'), join, feet: str('feet'), caps: str('caps') != null ? parseSetting(str('caps')) : undefined }).filter(([, v]) => v !== undefined));
760
- if (opt('frame') === true || !frame.profile || (!frame.inside && !frame.outside)) throw new Error('usage: cad new <project>/<assembly> --assembly --frame box|portal|table|gantry|shelf --inside 300,300,350 (or --outside) --profile <set> [--join blind] [--feet levelling]');
1749
+ const nums = (k) =>
1750
+ str(k)
1751
+ ? str(k)
1752
+ .split(',')
1753
+ .map((x) => parseValue(x.trim()))
1754
+ : undefined;
1755
+ const join =
1756
+ str('join') && (str('fitting') || str('screw'))
1757
+ ? {
1758
+ kind: str('join'),
1759
+ ...(str('fitting') ? { fitting: str('fitting') } : {}),
1760
+ ...(str('screw') ? { screw: str('screw') } : {}),
1761
+ }
1762
+ : str('join');
1763
+ frame = Object.fromEntries(
1764
+ Object.entries({
1765
+ kind: str('frame'),
1766
+ inside: nums('inside'),
1767
+ outside: nums('outside'),
1768
+ profile: str('profile'),
1769
+ join,
1770
+ feet: str('feet'),
1771
+ caps: str('caps') != null ? parseSetting(str('caps')) : undefined,
1772
+ }).filter(([, v]) => v !== undefined),
1773
+ );
1774
+ if (opt('frame') === true || !frame.profile || (!frame.inside && !frame.outside))
1775
+ throw new Error(
1776
+ 'usage: cad new <project>/<assembly> --assembly --frame box|portal|table|gantry|shelf --inside 300,300,350 (or --outside) --profile <set> [--join blind] [--feet levelling]',
1777
+ );
761
1778
  }
762
- edited(newAssembly(ref, { title: str('title'), kind: str('kind'), description: str('description'), frame, fields: Object.fromEntries(pairsOf(positional().slice(2), 'cad new')), project: { material: str('material'), printer: str('printer') }, dryRun }), 'new');
1779
+ edited(
1780
+ newAssembly(ref, {
1781
+ title: str('title'),
1782
+ kind: str('kind'),
1783
+ description: str('description'),
1784
+ frame,
1785
+ fields: Object.fromEntries(pairsOf(positional().slice(2), 'cad new')),
1786
+ project: { material: str('material'), printer: str('printer') },
1787
+ dryRun,
1788
+ }),
1789
+ 'new',
1790
+ );
763
1791
  }
764
1792
 
765
1793
  // cad set <project>/<assembly> <address>=<value> …
766
1794
  function editFields(ref) {
767
1795
  const pairs = pairsOf(positional().slice(2), 'cad set');
768
- if (!pairs.length) throw new Error(`usage: cad set ${ref} <address>=<value> … (x1.at=[0,0,20], joins.0.kind=bracket, frame.join.fitting=printed)`);
1796
+ if (!pairs.length)
1797
+ throw new Error(
1798
+ `usage: cad set ${ref} <address>=<value> … (x1.at=[0,0,20], joins.0.kind=bracket, frame.join.fitting=printed)`,
1799
+ );
769
1800
  edited(setInAssembly(ref, Object.fromEntries(pairs), { dryRun: !!opt('dry-run') }), 'set');
770
1801
  }
771
1802
  // cad set <project> field=value …
@@ -776,34 +1807,89 @@ function editProject(project) {
776
1807
  }
777
1808
  // cad remove <project>/<assembly> <address> [--with-refs], cad move <project>/<assembly> <id> --at | --to [--rotate]
778
1809
  function removeOrMove(cmd, ref, what) {
779
- if (!what || !isAssembly(ref)) throw new Error(`usage: cad ${cmd} ${USAGE[cmd]}${ref && !isAssembly(ref) ? ` (there is no assembly ${ref})` : ''}`);
780
- if (cmd === 'remove') return edited(removeFromAssembly(ref, what, { withRefs: !!opt('with-refs'), dryRun: !!opt('dry-run') }), 'remove');
781
- const list = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => parseValue(x.trim())) : undefined);
1810
+ if (!what || !isAssembly(ref))
1811
+ throw new Error(
1812
+ `usage: cad ${cmd} ${USAGE[cmd]}${ref && !isAssembly(ref) ? ` (there is no assembly ${ref})` : ''}`,
1813
+ );
1814
+ if (cmd === 'remove')
1815
+ return edited(removeFromAssembly(ref, what, { withRefs: !!opt('with-refs'), dryRun: !!opt('dry-run') }), 'remove');
1816
+ const list = (k) =>
1817
+ typeof opt(k) === 'string'
1818
+ ? opt(k)
1819
+ .split(',')
1820
+ .map((x) => parseValue(x.trim()))
1821
+ : undefined;
782
1822
  const at = typeof opt('at') !== 'string' ? undefined : opt('at').includes(',') ? list('at') : parseValue(opt('at'));
783
- edited(moveInAssembly(ref, what, { at, to: typeof opt('to') === 'string' ? opt('to') : undefined, rotate: list('rotate'), dryRun: !!opt('dry-run') }), 'move');
1823
+ edited(
1824
+ moveInAssembly(ref, what, {
1825
+ at,
1826
+ to: typeof opt('to') === 'string' ? opt('to') : undefined,
1827
+ rotate: list('rotate'),
1828
+ dryRun: !!opt('dry-run'),
1829
+ }),
1830
+ 'move',
1831
+ );
784
1832
  }
785
1833
 
786
1834
  // cad why <project>/<object>.<name>: the value, and what it reads, down to the rules (estimates marked)
787
1835
  async function explainValue(ref) {
788
1836
  const m = /^([^/]+\/[^.]+)\.(.+)$/.exec(ref || '');
789
- if (!m) throw new Error('usage: cad why <project>/<object>.<variable> (or .<set>.<rule>), e.g. cad why keyboard/case.depth');
1837
+ if (!m)
1838
+ throw new Error(
1839
+ 'usage: cad why <project>/<object>.<variable> (or .<set>.<rule>), e.g. cad why keyboard/case.depth',
1840
+ );
790
1841
  const tree = await why(m[1], m[2], { depth: Number(opt('depth')) || 12 });
791
1842
  if (opt('json')) return console.log(JSON.stringify(tree, null, 2));
792
1843
  const line = (n, pad) => {
793
1844
  const about = n.kind ? ` [${n.kind === 'estimate' ? 'ESTIMATE' : n.kind}${n.source ? `: ${n.source}` : ''}]` : '';
794
1845
  const where = n.via ? ` (${n.object})` : '';
795
- console.log(`${pad}${n.name} = ${fmt(n.value)}${n.unit ? ` ${n.unit}` : ''}${n.expr ? ` = ${n.expr}` : ''}${where}${n.seen ? ' (above)' : ''}${about}`);
1846
+ console.log(
1847
+ `${pad}${n.name} = ${fmt(n.value)}${n.unit ? ` ${n.unit}` : ''}${n.expr ? ` = ${n.expr}` : ''}${where}${n.seen ? ' (above)' : ''}${about}`,
1848
+ );
796
1849
  if (!n.seen && n.rule && !pad) console.log(` ${n.rule}`);
797
- if (n.problem) { // the result a problem variable picks, and what it is made from
798
- const q = n.problem, vals = Object.entries(q.variables);
799
- console.log(`${pad} optimised from ${q.file}: ${q.title}, ${q.material}${q.set ? `, with ${Object.entries(q.set).map(([k, v]) => `${k} = ${v}`).join(', ')}` : ''}`);
1850
+ if (n.problem) {
1851
+ // the result a problem variable picks, and what it is made from
1852
+ const q = n.problem,
1853
+ vals = Object.entries(q.variables);
1854
+ console.log(
1855
+ `${pad} optimised from ${q.file}: ${q.title}, ${q.material}${
1856
+ q.set
1857
+ ? `, with ${Object.entries(q.set)
1858
+ .map(([k, v]) => `${k} = ${v}`)
1859
+ .join(', ')}`
1860
+ : ''
1861
+ }`,
1862
+ );
800
1863
  console.log(`${pad} rule sets: ${q.uses.join(', ')}`);
801
- if (vals.length) console.log(`${pad} its values: ${vals.map(([k, v]) => `${k} = ${typeof v === 'number' ? fmt(v) : v}`).join(', ')}`);
1864
+ if (vals.length)
1865
+ console.log(
1866
+ `${pad} its values: ${vals.map(([k, v]) => `${k} = ${typeof v === 'number' ? fmt(v) : v}`).join(', ')}`,
1867
+ );
802
1868
  if (q.parts.length) console.log(`${pad} parts read: ${q.parts.join(', ')}`);
803
- if (q.assembly) { const A = q.assembly, bits = [...(A.joints.length ? [`joints read: ${A.joints.map((j) => `${j.joint} at (${j.at.map(fmt).join(', ')})`).join(', ')}`] : []), ...(A.sweeps.length ? [`swept: ${A.sweeps.map((w) => `${w.sweep} through ${w.through}, ${fmt(w.from)} to ${fmt(w.to)} in ${w.steps} steps`).join(', ')}`] : [])]; console.log(`${pad} in the assembly ${A.name}, item ${A.item}${A.pose ? `, pose ${A.pose}` : ''}${bits.length ? `: ${bits.join('; ')}` : ''}`); }
804
- if (q.anchors.length) console.log(`${pad} anchors read: ${q.anchors.map((a) => `${a.anchor} at (${a.at.map(fmt).join(', ')})`).join(', ')}`);
1869
+ if (q.assembly) {
1870
+ const A = q.assembly,
1871
+ bits = [
1872
+ ...(A.joints.length
1873
+ ? [`joints read: ${A.joints.map((j) => `${j.joint} at (${j.at.map(fmt).join(', ')})`).join(', ')}`]
1874
+ : []),
1875
+ ...(A.sweeps.length
1876
+ ? [
1877
+ `swept: ${A.sweeps.map((w) => `${w.sweep} through ${w.through}, ${fmt(w.from)} to ${fmt(w.to)} in ${w.steps} steps`).join(', ')}`,
1878
+ ]
1879
+ : []),
1880
+ ];
1881
+ console.log(
1882
+ `${pad} in the assembly ${A.name}, item ${A.item}${A.pose ? `, pose ${A.pose}` : ''}${bits.length ? `: ${bits.join('; ')}` : ''}`,
1883
+ );
1884
+ }
1885
+ if (q.anchors.length)
1886
+ console.log(
1887
+ `${pad} anchors read: ${q.anchors.map((a) => `${a.anchor} at (${a.at.map(fmt).join(', ')})`).join(', ')}`,
1888
+ );
805
1889
  console.log(`${pad} filter ${fmt(q.filter.value)} mm: ${q.filter.from}`);
806
- console.log(`${pad} ${q.made ? `kept in ${q.densities}` : `not made yet (cad optimise ${n.object.split('/')[0]}/${q.problem}); it will be kept in ${q.densities}`}: made again only when one of these, or the solver, changes`);
1890
+ console.log(
1891
+ `${pad} ${q.made ? `kept in ${q.densities}` : `not made yet (cad optimise ${n.object.split('/')[0]}/${q.problem}); it will be kept in ${q.densities}`}: made again only when one of these, or the solver, changes`,
1892
+ );
807
1893
  }
808
1894
  for (const c of n.reads || []) line(c, `${pad} `);
809
1895
  };
@@ -811,21 +1897,53 @@ async function explainValue(ref) {
811
1897
  }
812
1898
 
813
1899
  async function board(cmd, d, b, { title, version, tag }) {
814
- const pcb = await pcbEngine(), name = `${d.name}@${version}${tag}`;
1900
+ const pcb = await pcbEngine(),
1901
+ name = `${d.name}@${version}${tag}`;
815
1902
  if (cmd === 'check') {
816
1903
  say(`${title} ${version}`);
817
- const raw = lint(fs.readFileSync(d.js, 'utf8'));
1904
+ const raw = lint(readOwnText(d.js));
818
1905
  // The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
819
- 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));
820
- const problemFiles = [...new Set([...Object.values(b.object.variables || {}).filter((v) => v.type === 'problem').flatMap((v) => v.choice || [v.value]), ...(b.object.analysis || []).map((a) => a.problem)].map((n) => problemFile(d.project, String(n).split(':')[0])))].filter((f) => fs.existsSync(f));
821
- const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f))),
822
- ...problemFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'problem', own(f)))];
823
- const failed = report([
824
- ...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
825
- ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
826
- 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' },
827
- ...(await pcb.checks(b.circuit, b.values, b.matrix, b.source)),
828
- ], { object: `${d.project}/${d.name}`, title, version });
1906
+ const own = (f) => path.relative(WS, f),
1907
+ ruleFiles = (b.object.uses || [])
1908
+ .filter((u) => !u.includes('/'))
1909
+ .map((u) => path.join(WS, 'rules', `${u}.json`))
1910
+ .filter((f) => fs.existsSync(f));
1911
+ const problemFiles = [
1912
+ ...new Set(
1913
+ [
1914
+ ...Object.values(b.object.variables || {})
1915
+ .filter((v) => v.type === 'problem')
1916
+ .flatMap((v) => v.choice || [v.value]),
1917
+ ...(b.object.analysis || []).map((a) => a.problem),
1918
+ ].map((n) => problemFile(d.project, String(n).split(':')[0])),
1919
+ ),
1920
+ ].filter((f) => fs.existsSync(f));
1921
+ const schemaProblems = [
1922
+ ...schemaFindings(readJson(d.json), 'object', own(d.json)),
1923
+ ...ruleFiles.flatMap((f) => schemaFindings(readJson(f), 'rules', own(f))),
1924
+ ...problemFiles.flatMap((f) => schemaFindings(readJson(f), 'problem', own(f))),
1925
+ ];
1926
+ const failed = report(
1927
+ [
1928
+ ...(schemaProblems.length
1929
+ ? schemaProblems
1930
+ : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
1931
+ ...(b.units || []).map((u) => ({
1932
+ level: 'warn',
1933
+ text: `units: ${u.message}`,
1934
+ code: 'units',
1935
+ refs: { file: own(d.json), path: u.path, variable: u.name },
1936
+ })),
1937
+ raw.length
1938
+ ? {
1939
+ level: 'fail',
1940
+ text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}`,
1941
+ }
1942
+ : { level: 'pass', text: 'every measurement is a variable' },
1943
+ ...(await boardChecks(b, d)),
1944
+ ],
1945
+ { object: `${d.project}/${d.name}`, title, version },
1946
+ );
829
1947
  if (b.object.orientation) say(` ${b.object.orientation}`);
830
1948
  process.exitCode = failed ? 1 : 0;
831
1949
  return;
@@ -833,22 +1951,46 @@ async function board(cmd, d, b, { title, version, tag }) {
833
1951
  if (cmd === 'preview') {
834
1952
  const top = await pcb.png(b.circuit, paths.preview(d.project, `${d.name}${tag}-pcb.png`));
835
1953
  const sch = await pcb.schematicPng(b.circuit, paths.preview(d.project, `${d.name}${tag}-schematic.png`));
836
- const size = (await import('@rulecad/printcheck')).bounds(b.triangles).size.map((n) => fmt(n)).join(' × ');
1954
+ const size = (await import('@rulecad/printcheck'))
1955
+ .bounds(b.triangles)
1956
+ .size.map((n) => fmt(n))
1957
+ .join(' × ');
837
1958
  const out = paths.preview(d.project, `${d.name}${tag}.png`);
838
1959
  await preview(b.parts, { title: `${title} ${version}`, meta: `${size} mm · a circuit board`, out, explode: false });
839
1960
  return console.log(`${top}\n${sch}\n${out}`);
840
1961
  }
841
1962
  // export: exports/<project>/<name>-fab.zip (Gerbers, drills, BOM, placement: upload it to JLCPCB as it is), KiCad's
842
1963
  // board and schematic beside it, and the matrix for firmware
843
- const dir = paths.exports(d.project), { zip: zipOf } = await import('@rulecad/model-link');
1964
+ const dir = paths.exports(d.project),
1965
+ { zip: zipOf } = await import('@rulecad/model-link');
844
1966
  fs.mkdirSync(dir, { recursive: true });
845
- const fab = await pcb.fabFiles(b.circuit, d.name, { source: b.source }), zip = path.join(dir, `${name}-fab.zip`);
1967
+ const fab = await pcb.fabFiles(b.circuit, d.name, { source: b.source }),
1968
+ zip = path.join(dir, `${name}-fab.zip`);
846
1969
  fs.writeFileSync(zip, await zipOf(Object.entries(fab)));
847
1970
  const written = [zip];
848
- for (const [f, t] of Object.entries(await pcb.kicadFiles(b.circuit, name, { source: b.source }))) { fs.writeFileSync(path.join(dir, f), t); written.push(path.join(dir, f)); }
849
- if (b.matrix) { const f = path.join(dir, `${name}-matrix.json`); fs.writeFileSync(f, JSON.stringify(b.matrix, null, 2) + '\n'); written.push(f); }
850
- 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)` }];
851
- 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));
1971
+ for (const [f, t] of Object.entries(await pcb.kicadFiles(b.circuit, name, { source: b.source }))) {
1972
+ fs.writeFileSync(path.join(dir, f), t);
1973
+ written.push(path.join(dir, f));
1974
+ }
1975
+ if (b.matrix) {
1976
+ const f = path.join(dir, `${name}-matrix.json`);
1977
+ fs.writeFileSync(f, JSON.stringify(b.matrix, null, 2) + '\n');
1978
+ written.push(f);
1979
+ }
1980
+ const done = [
1981
+ {
1982
+ level: 'pass',
1983
+ 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)`,
1984
+ },
1985
+ ];
1986
+ if (opt('json'))
1987
+ return console.log(
1988
+ JSON.stringify(
1989
+ { object: `${d.project}/${d.name}`, version, files: written.map((f) => path.relative(WS, f)), findings: done },
1990
+ null,
1991
+ 2,
1992
+ ),
1993
+ );
852
1994
  report(done);
853
1995
  for (const f of written) console.log(f);
854
1996
  }
@@ -856,7 +1998,9 @@ async function board(cmd, d, b, { title, version, tag }) {
856
1998
  // ---------- assemblies ----------
857
1999
  async function assembly(cmd, ref) {
858
2000
  const pose = typeof opt('pose') === 'string' ? opt('pose') : undefined;
859
- const s = await buildAssembly(ref, [], {}, { pose, progress: showProgress }), a = s.a, title = `${a.title || s.name}${pose ? ` (${pose})` : ''}`;
2001
+ const s = await buildAssembly(ref, [], {}, { pose, progress: showProgress }),
2002
+ a = s.a,
2003
+ title = `${a.title || s.name}${pose ? ` (${pose})` : ''}`;
860
2004
  const versions = [...new Map(s.objects.map((o) => [o.objName, `${o.objName} ${o.version}`])).values()].join(', ');
861
2005
  const rules = (ns) => Object.fromEntries(Object.keys(loadRuleSet(ns).rules).map((k) => [k, s.num(`${ns}.${k}`)]));
862
2006
  const printed = s.parts.filter((p) => p.role !== 'reference');
@@ -865,67 +2009,148 @@ async function assembly(cmd, ref) {
865
2009
  say(`${title} (${a.kind || 'fit'}: ${versions})`);
866
2010
  // Each pose (or the one asked for): what's the same in every pose is said once, the rest under the pose's name
867
2011
  const findings = assemblyFindings(s, a, pose);
868
- if (opt('sweep')) findings.push(...sweep(s, { joint: typeof opt('sweep') === 'string' ? opt('sweep') : undefined, steps: Number(opt('steps')) || 24, progress: showProgress }));
869
- if (a.kind === 'plate') findings.push(...check(printed.flatMap((p) => p.triangles), rules(printerOf(s.project)), { parts: printed }));
870
- process.exitCode = report(findings, { assembly: ref, title, kind: a.kind || 'fit', ...(pose ? { pose } : {}) }) ? 1 : 0;
2012
+ if (opt('sweep'))
2013
+ findings.push(
2014
+ ...sweep(s, {
2015
+ joint: typeof opt('sweep') === 'string' ? opt('sweep') : undefined,
2016
+ steps: Number(opt('steps')) || 24,
2017
+ progress: showProgress,
2018
+ }),
2019
+ );
2020
+ if (a.kind === 'plate')
2021
+ findings.push(
2022
+ ...check(
2023
+ printed.flatMap((p) => p.triangles),
2024
+ rules(printerOf(s.project)),
2025
+ { parts: printed },
2026
+ ),
2027
+ );
2028
+ process.exitCode = report(findings, { assembly: ref, title, kind: a.kind || 'fit', ...(pose ? { pose } : {}) })
2029
+ ? 1
2030
+ : 0;
871
2031
  return;
872
2032
  }
873
2033
  if (cmd === 'animate') {
874
- if (!s.gait) { // a motor turning what it drives: the gears cut across their shafts, the load's part turning with them
875
- const { driveSvg } = await import('../lib/drive.mjs'), out = paths.preview(s.project, `${s.name}-drive.svg`);
2034
+ if (!s.gait) {
2035
+ // a motor turning what it drives: the gears cut across their shafts, the load's part turning with them
2036
+ const { driveSvg } = await import('../lib/drive.mjs'),
2037
+ out = paths.preview(s.project, `${s.name}-drive.svg`);
876
2038
  fs.mkdirSync(path.dirname(out), { recursive: true });
877
2039
  fs.writeFileSync(out, driveSvg(s, { title, ...(opt('turns') ? { turns: Number(opt('turns')) } : {}) }));
878
2040
  return console.log(out);
879
2041
  }
880
- const { gaitSvg, gaitData } = await import('../lib/animate.mjs'), { framesOf } = await import('../lib/gait.mjs'), r = framesOf(s);
881
- if (!r.frames.length) throw new Error(`${ref}'s gait has nothing to play: ${r.findings.map((x) => x.text).join('; ')}`);
882
- const svg = paths.preview(s.project, `${s.name}-gait.svg`), json = paths.preview(s.project, `${s.name}-gait.json`);
2042
+ const { gaitSvg, gaitData } = await import('../lib/animate.mjs'),
2043
+ { framesOf } = await import('../lib/gait.mjs'),
2044
+ r = framesOf(s);
2045
+ if (!r.frames.length)
2046
+ throw new Error(`${ref}'s gait has nothing to play: ${r.findings.map((x) => x.text).join('; ')}`);
2047
+ const svg = paths.preview(s.project, `${s.name}-gait.svg`),
2048
+ json = paths.preview(s.project, `${s.name}-gait.json`);
883
2049
  fs.mkdirSync(path.dirname(svg), { recursive: true });
884
- fs.writeFileSync(svg, gaitSvg(s, r, { title: `${title}: ${typeof a.gait.pattern === 'string' ? a.gait.pattern : 'a gait'}` })); fs.writeFileSync(json, JSON.stringify(gaitData(s, r)));
885
- console.log(svg); return console.log(json);
2050
+ fs.writeFileSync(
2051
+ svg,
2052
+ gaitSvg(s, r, { title: `${title}: ${typeof a.gait.pattern === 'string' ? a.gait.pattern : 'a gait'}` }),
2053
+ );
2054
+ fs.writeFileSync(json, JSON.stringify(gaitData(s, r)));
2055
+ console.log(svg);
2056
+ return console.log(json);
886
2057
  }
887
2058
  if (cmd === 'preview') {
888
2059
  const check = !!opt('check'); // the check view: each motor's torque labelled at its joints, never on the rest view
889
- const out = paths.preview(s.project, `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}${check ? '-check' : ''}.png`);
2060
+ const out = paths.preview(
2061
+ s.project,
2062
+ `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}${check ? '-check' : ''}.png`,
2063
+ );
890
2064
  let marks = null;
891
2065
  if (check) {
892
- if (!s.motion?.drives?.length) throw new Error(`${ref} has no motor: cad preview --check labels the torque a motor sends through its joints`);
2066
+ if (!s.motion?.drives?.length)
2067
+ throw new Error(`${ref} has no motor: cad preview --check labels the torque a motor sends through its joints`);
893
2068
  marks = (await import('../lib/motorsvg.mjs')).workMarks(s);
894
2069
  }
895
- const size = (await import('@rulecad/printcheck')).bounds(s.triangles).size.map((n) => fmt(n)).join(' × ');
896
- const built = s.a.show === 'built' // (show: built: references drawn solid, as the thing built)
897
- const faint = [...new Set(s.parts.filter((p) => p.role !== 'part' && !(built && p.role === 'reference')).map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`))]; // each kind once
898
- await preview([...s.parts, ...wireTubesOf(s)], { title: check ? `${title}: the motor at work` : title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode'), marks, built });
2070
+ const size = (await import('@rulecad/printcheck'))
2071
+ .bounds(s.triangles)
2072
+ .size.map((n) => fmt(n))
2073
+ .join(' × ');
2074
+ const built = s.a.show === 'built'; // (show: built: references drawn solid, as the thing built)
2075
+ const faint = [
2076
+ ...new Set(
2077
+ s.parts
2078
+ .filter((p) => p.role !== 'part' && !(built && p.role === 'reference'))
2079
+ .map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`),
2080
+ ),
2081
+ ]; // each kind once
2082
+ await preview([...s.parts, ...wireTubesOf(s)], {
2083
+ title: check ? `${title}: the motor at work` : title,
2084
+ meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`,
2085
+ out,
2086
+ explode: !!opt('explode'),
2087
+ marks,
2088
+ built,
2089
+ });
899
2090
  // each motor at work beside it: its curve with the working point, and the torque through its train (said before
900
2091
  // the picture, which stays the last line, for whatever reads it)
901
2092
  if (s.motion?.drives?.length && !pose && !opt('explode') && !check) {
902
2093
  const { motorWork, workCurve, trainSvg } = await import('../lib/motorsvg.mjs');
903
2094
  for (const w of motorWork(s)) {
904
- for (const [kind, svg] of [['curve', workCurve(w)], ['train', trainSvg(w)]]) {
2095
+ for (const [kind, svg] of [
2096
+ ['curve', workCurve(w)],
2097
+ ['train', trainSvg(w)],
2098
+ ]) {
905
2099
  const file = paths.preview(s.project, `${s.name}-${w.id}-${kind}.svg`);
906
- fs.writeFileSync(file, svg); console.log(file);
2100
+ fs.writeFileSync(file, svg);
2101
+ console.log(file);
907
2102
  }
908
2103
  }
909
2104
  }
910
2105
  return console.log(out);
911
2106
  }
912
2107
  if (cmd === 'export') {
913
- if (a.kind !== 'plate') throw new Error(`${ref} is a fit assembly, for checking: export its objects, or make a plate (kind: plate) to print them together`);
2108
+ if (a.kind !== 'plate')
2109
+ throw new Error(
2110
+ `${ref} is a fit assembly, for checking: export its objects, or make a plate (kind: plate) to print them together`,
2111
+ );
914
2112
  const out = paths.exports(s.project, `${s.name}.3mf`);
915
2113
  fs.mkdirSync(path.dirname(out), { recursive: true });
916
2114
  // One object per printed thing (a keycap with its legend and supports), a part per part, each in its filament
917
- const fil = filaments(s.project), things = new Map();
918
- for (const p of printed) { if (!things.has(p.leaf)) things.set(p.leaf, []); things.get(p.leaf).push({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) }); }
919
- fs.writeFileSync(out, await threemf([...things].map(([name, parts]) => ({ name, parts })), { filaments: slots(fil) }));
2115
+ const fil = filaments(s.project),
2116
+ things = new Map();
2117
+ for (const p of printed) {
2118
+ if (!things.has(p.leaf)) things.set(p.leaf, []);
2119
+ things.get(p.leaf).push({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) });
2120
+ }
2121
+ fs.writeFileSync(
2122
+ out,
2123
+ await threemf(
2124
+ [...things].map(([name, parts]) => ({ name, parts })),
2125
+ { filaments: slots(fil) },
2126
+ ),
2127
+ );
920
2128
  report(filamentNotes(printed, fil));
921
2129
  if (opt('open')) openInSlicer(out);
922
2130
  return console.log(out);
923
2131
  }
924
2132
  const link = async () => {
925
- const model = await assemblyModel(s, { title, versions, filaments: filaments(s.project), noRules: !!opt('no-rules'), steps: opt('no-steps') ? false : opt('steps') });
926
- if (model.steps) say(`carries the drawing ${model.steps.name ?? '(unnamed)'} (${model.steps.b.length} blocks; --no-steps to leave it out)`);
2133
+ const model = await assemblyModel(s, {
2134
+ title,
2135
+ versions,
2136
+ filaments: filaments(s.project),
2137
+ noRules: !!opt('no-rules'),
2138
+ steps: opt('no-steps') ? false : opt('steps'),
2139
+ });
2140
+ if (model.steps)
2141
+ say(
2142
+ `carries the drawing ${model.steps.name ?? '(unnamed)'} (${model.steps.b.length} blocks; --no-steps to leave it out)`,
2143
+ );
927
2144
  const url = await linkTo(model);
928
- return { view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, src: model.src, size: url.length, title, version: '' };
2145
+ return {
2146
+ view: url,
2147
+ stl: `${url}&get=stl`,
2148
+ '3mf': `${url}&get=3mf`,
2149
+ src: model.src,
2150
+ size: url.length,
2151
+ title,
2152
+ version: '',
2153
+ };
929
2154
  };
930
2155
  if (cmd === 'link') return await printLinks(await link());
931
2156
  if (cmd === 'show') {
@@ -934,9 +2159,18 @@ async function assembly(cmd, ref) {
934
2159
  const m = await buildAssembly(ref, [], {}, { mirror: true, pose });
935
2160
  const placed = shapes(m.parts.filter((p) => p.role !== 'support' && p.mirror !== false));
936
2161
  // The card: what the checks found, one short line each
937
- const items = checkAssembly(s).filter((x) => x.card).slice(0, 6).map((x) => x.card);
938
- await (await target('show'))({ title, ttl: opt('ttl') || '10m', mesh: { shapes: placed.shapes.map((x) => x.polygons), place: placed.place },
939
- card: { title: a.kind === 'plate' ? `${title}: ${versions}` : `${title}: checks`, items } });
2162
+ const items = checkAssembly(s)
2163
+ .filter((x) => x.card)
2164
+ .slice(0, 6)
2165
+ .map((x) => x.card);
2166
+ await (
2167
+ await target('show')
2168
+ )({
2169
+ title,
2170
+ ttl: opt('ttl') || '10m',
2171
+ mesh: { shapes: placed.shapes.map((x) => x.polygons), place: placed.place },
2172
+ card: { title: a.kind === 'plate' ? `${title}: ${versions}` : `${title}: checks`, items },
2173
+ });
940
2174
  return await printLinks(await link());
941
2175
  }
942
2176
  throw new Error(`cad ${cmd} doesn't work on an assembly (check, preview, export, show, link do)`);
@@ -944,20 +2178,42 @@ async function assembly(cmd, ref) {
944
2178
 
945
2179
  // The model as a link: full print precision (triangles), the rules card, and exactly which version it is.
946
2180
  async function links(d, b, set) {
947
- const s = d.tag ? { kind: null } : await since(d), fil = filaments(d.project);
2181
+ const s = d.tag ? { kind: null } : await since(d),
2182
+ fil = filaments(d.project);
948
2183
  const version = d.version || b.object.version || '0.0.0';
949
2184
  const src = `${d.project}/${d.name}${d.variant ? `:${d.variant}` : ''}@${version}${s.kind && s.kind !== 'first' ? '+changes' : s.kind === 'first' ? '+unreleased' : ''}`;
950
- const model = await objectModel(b, { title: `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`, version, src, set: Object.keys(set).length ? suffix(set).slice(1).replace(/-(?=\w+=)/g, ',') : null, filaments: fil, noRules: !!opt('no-rules') });
2185
+ const model = await objectModel(b, {
2186
+ title: `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`,
2187
+ version,
2188
+ src,
2189
+ set: Object.keys(set).length
2190
+ ? suffix(set)
2191
+ .slice(1)
2192
+ .replace(/-(?=\w+=)/g, ',')
2193
+ : null,
2194
+ filaments: fil,
2195
+ noRules: !!opt('no-rules'),
2196
+ });
951
2197
  const url = await linkTo(model);
952
- return { view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, src, size: url.length, title: model.title, version };
2198
+ return {
2199
+ view: url,
2200
+ stl: `${url}&get=stl`,
2201
+ '3mf': `${url}&get=3mf`,
2202
+ src,
2203
+ size: url.length,
2204
+ title: model.title,
2205
+ version,
2206
+ };
953
2207
  }
954
2208
 
955
2209
  // Short links: the model's data stored by the shorten target (a secret Gist), and a link that carries only its ID. The
956
2210
  // same model reuses its ID (.cache/links.json, by the data's hash). Without a shorten target, links stay long.
957
2211
  async function shorten(l) {
958
2212
  if (!hasTarget('shorten')) return l;
959
- const token = l.view.split('#m=')[1], hash = (await import('node:crypto')).createHash('sha256').update(token).digest('hex').slice(0, 16);
960
- const file = paths.cache('links.json'), cache = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
2213
+ const token = l.view.split('#m=')[1],
2214
+ hash = (await import('node:crypto')).createHash('sha256').update(token).digest('hex').slice(0, 16);
2215
+ const file = paths.cache('links.json'),
2216
+ cache = cached(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
961
2217
  if (!cache[hash]) {
962
2218
  cache[hash] = await (await target('shorten'))(token, { desc: `model: ${l.src}` });
963
2219
  fs.mkdirSync(path.dirname(file), { recursive: true });
@@ -972,18 +2228,33 @@ async function shorten(l) {
972
2228
  const TOO_LONG = 8000; // characters: past this, chat apps and email cut a link short or refuse it
973
2229
  async function printLinks(l) {
974
2230
  if ((opt('md') && !opt('long')) || opt('short')) l = await shorten(l);
975
- if (!l.short && l.view.length > TOO_LONG) console.error(`this link is ${(l.view.length / 1024).toFixed(0)} KB, too long for chat or email. ${hasTarget('shorten')
976
- ? 'Leave out --long for a short one.' : 'For short links, add "shorten": "gist" to "targets" in cad.config.json: each model you share is then stored in a secret GitHub Gist (needs the gh command, signed in).'}`);
2231
+ // (on stderr, so that --md still prints one line to paste)
2232
+ if (viewNote()) console.error(viewNote());
2233
+ if (!l.short && l.view.length > TOO_LONG)
2234
+ console.error(
2235
+ `this link is ${(l.view.length / 1024).toFixed(0)} KB, too long for chat or email. ${
2236
+ hasTarget('shorten')
2237
+ ? 'Leave out --long for a short one.'
2238
+ : 'For short links, add "shorten": "gist" to "targets" in cad.config.json: each model you share is then stored in a secret GitHub Gist (needs the gh command, signed in).'
2239
+ }`,
2240
+ );
977
2241
  // One link: the page picks which parts go in a download (all of them, one key, only the case)
978
- if (opt('md')) return console.log(`**${[l.title, l.version].filter(Boolean).join(' ')}**${l.src.includes('+') ? ' (not a release)' : ''}: [View and download](${l.view})`);
979
- console.log(`${l.src}, ${l.short ? 'short links (data in a secret Gist)' : `${(l.size / 1024).toFixed(1)} KB links`}${l.src.includes('+') ? ' (not a release: the link shows it)' : ''}`);
2242
+ if (opt('md'))
2243
+ return console.log(
2244
+ `**${[l.title, l.version].filter(Boolean).join(' ')}**${l.src.includes('+') ? ' (not a release)' : ''}: [View and download](${l.view})`,
2245
+ );
2246
+ console.log(
2247
+ `${l.src}, ${l.short ? 'short links (data in a secret Gist)' : `${(l.size / 1024).toFixed(1)} KB links`}${l.src.includes('+') ? ' (not a release: the link shows it)' : ''}`,
2248
+ );
980
2249
  // A long link is the whole model: printed only when asked for (--long), else written to a file (a link of a
981
2250
  // keyboard is megabytes: in a terminal or an agent's context it's only noise)
982
2251
  if (!l.short && !opt('long')) {
983
2252
  const f = paths.cache('links', `${l.src.replace(/[^\w@.+-]+/g, '-')}.txt`);
984
2253
  fs.mkdirSync(path.dirname(f), { recursive: true });
985
2254
  fs.writeFileSync(f, `view ${l.view}\nstl ${l.stl}\n3mf ${l['3mf']}\n`);
986
- return console.log(` links in ${path.relative(WS, f)} (--md: one ${hasTarget('shorten') ? 'short ' : ''}link for chat; --long: print them)`);
2255
+ return console.log(
2256
+ ` links in ${path.relative(WS, f)} (--md: one ${hasTarget('shorten') ? 'short ' : ''}link for chat; --long: print them)`,
2257
+ );
987
2258
  }
988
2259
  console.log(` view ${l.view}`);
989
2260
  console.log(` stl ${l.stl}`);
@@ -1008,21 +2279,28 @@ async function since(d) {
1008
2279
  // docs). What it can't release past is uncommitted shared code (lib/, bin/) or a rule or layout it uses: those would
1009
2280
  // be in the build but not in the release.
1010
2281
  function onlyChanged(allowed) {
1011
- const dirty = git('status', '--porcelain', '--untracked-files=all').split('\n').filter(Boolean).map((l) => l.slice(3).replace(/^"|"$/g, ''));
2282
+ const dirty = git('status', '--porcelain', '--untracked-files=all')
2283
+ .split('\n')
2284
+ .filter(Boolean)
2285
+ .map((l) => l.slice(3).replace(/^"|"$/g, ''));
1012
2286
  const shared = dirty.filter((f) => !allowed.includes(f) && /^(lib|bin)\//.test(f));
1013
- if (shared.length) throw new Error(`commit shared code first (the release would build with it): ${shared.join(', ')}`);
2287
+ if (shared.length)
2288
+ throw new Error(`commit shared code first (the release would build with it): ${shared.join(', ')}`);
1014
2289
  }
1015
2290
 
1016
2291
  function commitAndTag(paths, subject, tag, message) {
1017
2292
  git('add', '--', ...paths);
1018
2293
  git('commit', '-q', '-m', subject, ...(opt('trailer') ? ['--trailer', opt('trailer')] : []), '--', ...paths); // only these, whatever else is staged
1019
2294
  git('tag', '-a', tag, '-m', message);
1020
- if (opt('push')) { git('push', '-q', 'origin', 'HEAD'); git('push', '-q', 'origin', tag); }
2295
+ if (opt('push')) {
2296
+ git('push', '-q', 'origin', 'HEAD');
2297
+ git('push', '-q', 'origin', tag);
2298
+ }
1021
2299
  }
1022
2300
 
1023
2301
  function changelog(dir, heading, message, reasons) {
1024
2302
  const f = path.join(dir, 'CHANGELOG.md');
1025
- const old = fs.existsSync(f) ? fs.readFileSync(f, 'utf8').replace(/^# .*\n+/, '') : '';
2303
+ const old = fs.existsSync(insideWorkspace(f)) ? readOwnText(f).replace(/^# .*\n+/, '') : '';
1026
2304
  const entry = `## ${heading}\n\n${message}\n${reasons.length ? `\n${reasons.map((r) => `- ${r.text} (${r.kind})`).join('\n')}\n` : ''}`;
1027
2305
  fs.writeFileSync(f, `# ${path.basename(dir)} changelog\n\n${entry}\n${old}`);
1028
2306
  return path.relative(WS, f).split(path.sep).join('/'); // (git's terms: forward slashes)
@@ -1030,23 +2308,42 @@ function changelog(dir, heading, message, reasons) {
1030
2308
 
1031
2309
  // An object's print checks: printcheck's, and for parts printed in place, theirs (lib/inplace.mjs)
1032
2310
  async function printChecks(b, d) {
1033
- const pr = printer(b, d), printed = check(b.triangles, pr, { parts: b.parts });
1034
- return b.object.printInPlace ? [...printed, ...(await (await import('../lib/inplace.mjs')).inPlaceChecks(b, pr, printed))] : printed;
2311
+ const pr = printer(b, d),
2312
+ printed = check(b.triangles, pr, { parts: b.parts });
2313
+ return b.object.printInPlace
2314
+ ? [...printed, ...(await (await import('../lib/inplace.mjs')).inPlaceChecks(b, pr, printed))]
2315
+ : printed;
1035
2316
  }
1036
2317
 
1037
2318
  async function releaseObject(d, { batch = false } = {}) {
1038
2319
  const message = opt('m');
1039
2320
  if (!message || message === true) throw new Error('say what changed: -m "Wider slot for a looser fit"');
1040
- const object = readObject(d), b = await build(d);
1041
- const raw = lint(fs.readFileSync(d.js, 'utf8')), fails = (b.circuit ? await (await pcbEngine()).checks(b.circuit, b.values, b.matrix, b.source) // boards: the board's checks
1042
- : b.object.role === 'reference' ? [] : [...(await printChecks(b, d)), ...(b.mechanism?.findings || [])]).filter((r) => r.level === 'fail'); // references aren't printed; a mechanism's own checks count
1043
- if (raw.length || fails.length) throw new Error(`fix the check first: ${[...raw.map((r) => `raw number ${r.text} on line ${r.line}`), ...fails.map((f) => f.text)].join('; ')}`);
2321
+ const object = readObject(d),
2322
+ b = await build(d);
2323
+ const raw = lint(readOwnText(d.js)),
2324
+ fails = (
2325
+ b.circuit
2326
+ ? await boardChecks(b, d) // boards: the board's checks (under the design's limits, where it is sandboxed)
2327
+ : b.object.role === 'reference'
2328
+ ? []
2329
+ : [...(await printChecks(b, d)), ...(b.mechanism?.findings || [])]
2330
+ ).filter((r) => r.level === 'fail'); // references aren't printed; a mechanism's own checks count
2331
+ if (raw.length || fails.length)
2332
+ throw new Error(
2333
+ `fix the check first: ${[...raw.map((r) => `raw number ${r.text} on line ${r.line}`), ...fails.map((f) => f.text)].join('; ')}`,
2334
+ );
1044
2335
  let { last, kind, reasons } = await since(d);
1045
2336
  if (!kind) throw new Error(`nothing has changed since ${last.version}`);
1046
2337
  const asked = opt('bump');
1047
2338
  if (asked && last) {
1048
2339
  if (!KINDS.includes(asked)) throw new Error('--bump is major, minor or patch');
1049
- if (bigger(asked, kind) !== asked && !opt('force')) throw new Error(`the changes need at least a ${kind} release (${reasons.filter((r) => r.kind === kind).map((r) => r.text).join('; ')}); --force to override`);
2340
+ if (bigger(asked, kind) !== asked && !opt('force'))
2341
+ throw new Error(
2342
+ `the changes need at least a ${kind} release (${reasons
2343
+ .filter((r) => r.kind === kind)
2344
+ .map((r) => r.text)
2345
+ .join('; ')}); --force to override`,
2346
+ );
1050
2347
  kind = asked;
1051
2348
  }
1052
2349
  const version = last ? bump(last.version, kind) : object.version || '0.1.0';
@@ -1054,67 +2351,122 @@ async function releaseObject(d, { batch = false } = {}) {
1054
2351
  console.log(`${tag} (${kind}${last ? `, from ${last.version}` : ''})`);
1055
2352
  for (const r of reasons) console.log(` ${r.kind.padEnd(5)} ${r.text}`);
1056
2353
  if (opt('dry-run')) return;
1057
- const allowed = [...files(d, object), `projects/${d.project}/CHANGELOG.md`, path.relative(WS, printsFile(d)).split(path.sep).join('/')];
2354
+ const allowed = [
2355
+ ...files(d, object),
2356
+ `projects/${d.project}/CHANGELOG.md`,
2357
+ path.relative(WS, printsFile(d)).split(path.sep).join('/'),
2358
+ ];
1058
2359
  if (!batch) onlyChanged(allowed); // releaseAll checked the whole tree first
1059
- fs.writeFileSync(d.json, setAt(fs.readFileSync(d.json, 'utf8'), ['version'], version)); // the object's own version (added, if it had none), nothing else
2360
+ fs.writeFileSync(d.json, setAt(readOwnText(d.json), ['version'], version)); // the object's own version (added, if it had none), nothing else
1060
2361
  const log = changelog(d.dir, `${d.name} ${version} (${kind}), ${today()}`, message, reasons);
1061
- commitAndTag([...files(d, object), log].filter((f) => fs.existsSync(path.join(WS, f))), `${tag}: ${message}`, tag, `${kind}: ${message}${b.circuit ? `\n\nengine: ${engineId()}` : ''}`);
2362
+ commitAndTag(
2363
+ [...files(d, object), log].filter((f) => fs.existsSync(path.join(WS, f))),
2364
+ `${tag}: ${message}`,
2365
+ tag,
2366
+ `${kind}: ${message}${b.circuit ? `\n\nengine: ${engineId()}` : ''}`,
2367
+ );
1062
2368
  console.log(`tagged ${tag}${opt('push') ? ' and pushed' : ' (not pushed: --push, or git push --follow-tags)'}`);
1063
2369
  }
1064
2370
 
1065
2371
  // A project's project.json, or a plain word that there's no such project (and which there are)
1066
2372
  function projectFile(project) {
1067
2373
  const pj = path.join(paths.project(project), 'project.json');
1068
- if (!fs.existsSync(pj)) { const have = projects(); throw new Error(`no project "${project}"${have.length ? ` (projects: ${have.join(', ')})` : ': cad new <project>/<object> starts one'}`); }
2374
+ if (!fs.existsSync(pj)) {
2375
+ const have = projects();
2376
+ throw new Error(
2377
+ `no project "${project}"${have.length ? ` (projects: ${have.join(', ')})` : ': cad new <project>/<object> starts one'}`,
2378
+ );
2379
+ }
1069
2380
  return pj;
1070
2381
  }
1071
2382
  // The workspace's projects: the folders under projects/ that hold a project.json (not a stray file, such as .DS_Store)
1072
- const projects = () => (fs.existsSync(paths.projects) ? fs.readdirSync(paths.projects).filter((p) => fs.existsSync(path.join(paths.project(p), 'project.json'))).sort() : []);
2383
+ const projects = () =>
2384
+ fs.existsSync(paths.projects)
2385
+ ? fs
2386
+ .readdirSync(paths.projects)
2387
+ .filter((p) => isPlainName(p) && fs.existsSync(path.join(paths.project(p), 'project.json')))
2388
+ .sort()
2389
+ : []; // (a folder whose name isn't plain is not a project the tool can name)
1073
2390
 
1074
2391
  async function releaseProject(project) {
1075
2392
  const message = opt('m');
1076
2393
  if (!message || message === true) throw new Error('say what this release is: -m "First full set"');
1077
- const dir = paths.project(project), pj = projectFile(project);
1078
- const p = JSON.parse(fs.readFileSync(pj, 'utf8')), manifest = {};
2394
+ const dir = paths.project(project),
2395
+ pj = projectFile(project);
2396
+ const p = readJson(pj),
2397
+ manifest = {};
1079
2398
  for (const name of p.objects) {
1080
- const d = locate(`${project}/${name}`), s = await since(d);
2399
+ const d = locateIn(project, name, `projects/${project}/project.json, its "objects"`),
2400
+ s = await since(d);
1081
2401
  if (!s.last) throw new Error(`${name} has no release yet: cad release ${project}/${name} -m "…"`);
1082
2402
  if (s.kind) throw new Error(`${name} has changes since ${s.last.version}: release it first`);
1083
2403
  manifest[name] = s.last.version;
1084
2404
  }
1085
2405
  const last = tags(project).at(-1);
1086
- let kind = 'first', reasons = [];
2406
+ let kind = 'first',
2407
+ reasons = [];
1087
2408
  if (last) {
1088
- const before = JSON.parse(git('cat-file', '-p', `refs/tags/${last.tag}`).split('\n\n').slice(1).join('\n\n').split('\n').find((l) => l.startsWith('{')) || '{}');
2409
+ const before = JSON.parse(
2410
+ git('cat-file', '-p', `refs/tags/${last.tag}`)
2411
+ .split('\n\n')
2412
+ .slice(1)
2413
+ .join('\n\n')
2414
+ .split('\n')
2415
+ .find((l) => l.startsWith('{')) || '{}',
2416
+ );
1089
2417
  for (const [name, v] of Object.entries(manifest)) {
1090
2418
  if (!before[name]) reasons.push({ kind: 'minor', text: `${name} ${v} added` });
1091
2419
  else if (before[name] !== v) {
1092
- const k = tags(project, name).filter((t) => newer(t.version, before[name]) && !newer(t.version, v)).reduce((m, t) => bigger(m, t.kind === 'first' ? 'patch' : t.kind || 'patch'), 'patch');
2420
+ const k = tags(project, name)
2421
+ .filter((t) => newer(t.version, before[name]) && !newer(t.version, v))
2422
+ .reduce((m, t) => bigger(m, t.kind === 'first' ? 'patch' : t.kind || 'patch'), 'patch');
1093
2423
  reasons.push({ kind: k, text: `${name} ${before[name]} → ${v}` });
1094
2424
  }
1095
2425
  }
1096
- for (const name of Object.keys(before)) if (!manifest[name]) reasons.push({ kind: 'major', text: `${name} removed` });
2426
+ for (const name of Object.keys(before))
2427
+ if (!manifest[name]) reasons.push({ kind: 'major', text: `${name} removed` });
1097
2428
  if (!reasons.length) throw new Error(`nothing has changed since ${project}@${last.version}`);
1098
2429
  kind = reasons.reduce((k, r) => bigger(k, r.kind), 'patch');
1099
2430
  }
1100
2431
  const version = last ? bump(last.version, kind) : p.version || '0.1.0';
1101
- console.log(`${project}@${version} (${kind}): ${Object.entries(manifest).map(([n, v]) => `${n}@${v}`).join(', ')}`);
2432
+ console.log(
2433
+ `${project}@${version} (${kind}): ${Object.entries(manifest)
2434
+ .map(([n, v]) => `${n}@${v}`)
2435
+ .join(', ')}`,
2436
+ );
1102
2437
  if (opt('dry-run')) return;
1103
- onlyChanged([`projects/${project}/project.json`, `projects/${project}/CHANGELOG.md`, `projects/${project}/prints.jsonl`]);
1104
- p.version = version; p.release = manifest;
2438
+ onlyChanged([
2439
+ `projects/${project}/project.json`,
2440
+ `projects/${project}/CHANGELOG.md`,
2441
+ `projects/${project}/prints.jsonl`,
2442
+ ]);
2443
+ p.version = version;
2444
+ p.release = manifest;
1105
2445
  fs.writeFileSync(pj, JSON.stringify(p, null, 2) + '\n');
1106
2446
  const log = changelog(dir, `${project} ${version} (${kind}), ${today()}`, message, reasons);
1107
- commitAndTag([`projects/${project}/project.json`, log], `${project}@${version}: ${message}`, `${project}@${version}`, `${kind}: ${message}\n\n${JSON.stringify(manifest)}`);
2447
+ commitAndTag(
2448
+ [`projects/${project}/project.json`, log],
2449
+ `${project}@${version}: ${message}`,
2450
+ `${project}@${version}`,
2451
+ `${kind}: ${message}\n\n${JSON.stringify(manifest)}`,
2452
+ );
1108
2453
  console.log(`tagged ${project}@${version}`);
1109
2454
  }
1110
2455
 
1111
2456
  // Release every object in a project that changed, then the project: the tree may hold changes only to their files.
1112
2457
  async function releaseAll(project) {
1113
- const pj = JSON.parse(fs.readFileSync(projectFile(project), 'utf8'));
2458
+ const pj = readJson(projectFile(project));
1114
2459
  const changed = [];
1115
- for (const n of pj.objects) { const d = locate(`${project}/${n}`); if ((await since(d)).kind) changed.push(d); }
1116
- const allowed = new Set([`projects/${project}/project.json`, `projects/${project}/CHANGELOG.md`, `projects/${project}/prints.jsonl`,
1117
- ...changed.flatMap((d) => files(d, readObject(d)))]);
2460
+ for (const n of pj.objects) {
2461
+ const d = locateIn(project, n, `projects/${project}/project.json, its "objects"`);
2462
+ if ((await since(d)).kind) changed.push(d);
2463
+ }
2464
+ const allowed = new Set([
2465
+ `projects/${project}/project.json`,
2466
+ `projects/${project}/CHANGELOG.md`,
2467
+ `projects/${project}/prints.jsonl`,
2468
+ ...changed.flatMap((d) => files(d, readObject(d))),
2469
+ ]);
1118
2470
  onlyChanged([...allowed]);
1119
2471
  for (const d of changed) await releaseObject(d, { batch: true });
1120
2472
  if (!opt('dry-run')) await releaseProject(project);
@@ -1124,8 +2476,14 @@ async function releaseAll(project) {
1124
2476
  function variants(d) {
1125
2477
  const v = readObject(d).variants || {};
1126
2478
  if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, variants: v }, null, 2));
1127
- if (!Object.keys(v).length) return console.log(`${d.name} has no variants: add "variants": { "name": { …inputs } } to its .json`);
1128
- 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(', ')}`);
2479
+ if (!Object.keys(v).length)
2480
+ return console.log(`${d.name} has no variants: add "variants": { "name": { …inputs } } to its .json`);
2481
+ for (const [n, set] of Object.entries(v))
2482
+ console.log(
2483
+ `${`${d.project}/${d.name}:${n}`.padEnd(32)} ${Object.entries(set)
2484
+ .map(([k, x]) => `${k}=${x}`)
2485
+ .join(', ')}`,
2486
+ );
1129
2487
  }
1130
2488
 
1131
2489
  // Two variants or releases side by side in one preview, the second to the right of the first
@@ -1134,89 +2492,231 @@ async function compareVariants(d, a, b) {
1134
2492
  const one = async (x) => build(/^\d+\.\d+\.\d+$/.test(x) ? materialise(d, x) : { ...d, variant: x }, sets());
1135
2493
  const [A, B] = [await one(a), await one(b)];
1136
2494
  const { bounds } = await import('@rulecad/printcheck');
1137
- const gap = (bounds(A.triangles).size[0] + bounds(B.triangles).size[0]) / 4, dx = bounds(A.triangles).hi[0] - bounds(B.triangles).lo[0] + gap;
2495
+ const gap = (bounds(A.triangles).size[0] + bounds(B.triangles).size[0]) / 4,
2496
+ dx = bounds(A.triangles).hi[0] - bounds(B.triangles).lo[0] + gap;
1138
2497
  const moved = (p) => ({ ...p, triangles: p.triangles.map((t) => t.map(([x, y, z]) => [x + dx, y, z])) });
1139
- const parts = [...A.parts.map((p) => ({ ...p, item: a, label: `${a}: ${p.label}` })), ...B.parts.map((p) => moved({ ...p, item: b, label: `${b}: ${p.label}` }))];
2498
+ const parts = [
2499
+ ...A.parts.map((p) => ({ ...p, item: a, label: `${a}: ${p.label}` })),
2500
+ ...B.parts.map((p) => moved({ ...p, item: b, label: `${b}: ${p.label}` })),
2501
+ ];
1140
2502
  const out = paths.preview(d.project, `${d.name}-${a}-vs-${b}.png`);
1141
- await preview(parts, { title: `${A.object.title || d.name}: ${a} and ${b}`, meta: `${a} on the left, ${b} on the right`, out, explode: false });
2503
+ await preview(parts, {
2504
+ title: `${A.object.title || d.name}: ${a} and ${b}`,
2505
+ meta: `${a} on the left, ${b} on the right`,
2506
+ out,
2507
+ explode: false,
2508
+ });
1142
2509
  console.log(out);
1143
2510
  }
1144
2511
 
1145
2512
  async function status(project) {
1146
- if (!project && !projects().length) return console.log(`no projects in ${WS} yet: cad new <project>/<object> starts one`);
2513
+ if (!project && !projects().length)
2514
+ return console.log(`no projects in ${WS} yet: cad new <project>/<object> starts one`);
1147
2515
  for (const p of project ? [project] : projects()) {
1148
- const pj = JSON.parse(fs.readFileSync(projectFile(p), 'utf8'));
2516
+ const pj = readJson(projectFile(p));
1149
2517
  console.log(`${p}${pj.version ? `@${pj.version}` : ''}`);
1150
2518
  for (const name of pj.objects) {
1151
- const s = await since(locate(`${p}/${name}`));
1152
- console.log(` ${name.padEnd(16)} ${s.last ? s.last.version.padEnd(8) : 'unreleased'} ${s.kind === 'first' ? '' : s.kind ? `changed since: needs a ${s.kind} release` : 'up to date'}`);
2519
+ const s = await since(locateIn(p, name, `projects/${p}/project.json, its "objects"`));
2520
+ console.log(
2521
+ ` ${name.padEnd(16)} ${s.last ? s.last.version.padEnd(8) : 'unreleased'} ${s.kind === 'first' ? '' : s.kind ? `changed since: needs a ${s.kind} release` : 'up to date'}`,
2522
+ );
1153
2523
  }
1154
2524
  }
1155
2525
  }
1156
2526
 
1157
2527
  async function machineCommand(what, ref) {
1158
- if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
1159
- const m = await import('../lib/machine.mjs'), s = await buildAssembly(ref);
1160
- if (what === 'machine') { const out = m.machineOf(s), file = m.writeMachine(s, out); (await import('../lib/buildpage.mjs')).writeWiring(s); return console.log(opt('json') ? JSON.stringify(out, null, 2) : file); }
1161
- const source = positional()[2], tol = opt('tol') != null ? Number(opt('tol')) : undefined;
2528
+ if (!isAssembly(ref))
2529
+ throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
2530
+ const m = await import('../lib/machine.mjs'),
2531
+ s = await buildAssembly(ref);
2532
+ if (what === 'machine') {
2533
+ const out = m.machineOf(s),
2534
+ file = m.writeMachine(s, out);
2535
+ (await import('../lib/buildpage.mjs')).writeWiring(s);
2536
+ return console.log(opt('json') ? JSON.stringify(out, null, 2) : file);
2537
+ }
2538
+ const source = positional()[2],
2539
+ tol = opt('tol') != null ? Number(opt('tol')) : undefined;
1162
2540
  if (!source && !opt('calibrate') && s.gait && !s.task?.sheet) return gaitPlot(m, s, ref);
1163
- if (!source && !opt('calibrate')) throw new Error('usage: cad plot <project>/<assembly> <drawing.svg> [--calibrate], or cad plot <project>/<assembly> on an assembly with a gait');
1164
- const { sheetFrame } = await import('@rulecad/robots'), f = s.task?.sheet ? sheetFrame(s.task.sheet) : null;
1165
- const svg = opt('calibrate') ? m.CALIBRATION(f?.width ?? 148, f?.height ?? 210) : fs.readFileSync(source, 'utf8'), base = `${s.name}-${opt('calibrate') ? 'calibration' : path.basename(source, path.extname(source))}`;
2541
+ if (!source && !opt('calibrate'))
2542
+ throw new Error(
2543
+ 'usage: cad plot <project>/<assembly> <drawing.svg> [--calibrate], or cad plot <project>/<assembly> on an assembly with a gait',
2544
+ );
2545
+ const { sheetFrame } = await import('@rulecad/robots'),
2546
+ f = s.task?.sheet ? sheetFrame(s.task.sheet) : null;
2547
+ const svg = opt('calibrate') ? m.CALIBRATION(f?.width ?? 148, f?.height ?? 210) : fs.readFileSync(source, 'utf8'),
2548
+ base = `${s.name}-${opt('calibrate') ? 'calibration' : path.basename(source, path.extname(source))}`;
1166
2549
  const r = m.plot(s, svg, { tolerance: tol, name: base });
1167
2550
  const failed = !r.ok;
1168
- if (opt('json')) { console.log(JSON.stringify({ ok: r.ok, findings: r.findings, ...(r.time ? { time: r.time } : {}), ...(r.ok ? { file: m.writePlot(s, r, base).file } : {}) }, null, 2)); process.exitCode = failed ? 1 : 0; return; }
2551
+ if (opt('json')) {
2552
+ console.log(
2553
+ JSON.stringify(
2554
+ {
2555
+ ok: r.ok,
2556
+ findings: r.findings,
2557
+ ...(r.time ? { time: r.time } : {}),
2558
+ ...(r.ok ? { file: m.writePlot(s, r, base).file } : {}),
2559
+ },
2560
+ null,
2561
+ 2,
2562
+ ),
2563
+ );
2564
+ process.exitCode = failed ? 1 : 0;
2565
+ return;
2566
+ }
1169
2567
  report(r.findings, { assembly: ref, title: `${ref}: ${base}` });
1170
- if (r.ok) { const w = m.writePlot(s, r, base); console.log(path.relative(WS, w.file)); console.log(path.relative(WS, w.preview)); }
2568
+ if (r.ok) {
2569
+ const w = m.writePlot(s, r, base);
2570
+ console.log(path.relative(WS, w.file));
2571
+ console.log(path.relative(WS, w.preview));
2572
+ }
1171
2573
  process.exitCode = failed ? 1 : 0;
1172
2574
  }
1173
2575
 
1174
2576
  // A gait as a step file: --cycles (3), --period (s a cycle; default the gait's), --pose (where it starts and ends; default the one shown)
1175
2577
  async function gaitPlot(m, s, ref) {
1176
- const cycles = opt('cycles') != null ? Number(opt('cycles')) : 3, period = opt('period') != null ? Number(opt('period')) : undefined;
1177
- if (!Number.isInteger(cycles) || cycles < 1) throw new Error(`--cycles is a whole number, 1 or more (got ${opt('cycles')})`);
1178
- if (period != null && !(period > 0)) throw new Error(`--period is the seconds of one cycle, above 0 (got ${opt('period')})`);
2578
+ const cycles = opt('cycles') != null ? Number(opt('cycles')) : 3,
2579
+ period = opt('period') != null ? Number(opt('period')) : undefined;
2580
+ if (!Number.isInteger(cycles) || cycles < 1)
2581
+ throw new Error(`--cycles is a whole number, 1 or more (got ${opt('cycles')})`);
2582
+ if (period != null && !(period > 0))
2583
+ throw new Error(`--period is the seconds of one cycle, above 0 (got ${opt('period')})`);
1179
2584
  const r = m.plotGait(s, { cycles, period, from: opt('pose') });
1180
- if (opt('json')) { console.log(JSON.stringify({ ok: r.ok, findings: r.findings, time: r.time, ...(r.ok ? { file: m.writeGait(s, r).file } : {}) }, null, 2)); process.exitCode = r.ok ? 0 : 1; return; }
2585
+ if (opt('json')) {
2586
+ console.log(
2587
+ JSON.stringify(
2588
+ { ok: r.ok, findings: r.findings, time: r.time, ...(r.ok ? { file: m.writeGait(s, r).file } : {}) },
2589
+ null,
2590
+ 2,
2591
+ ),
2592
+ );
2593
+ process.exitCode = r.ok ? 0 : 1;
2594
+ return;
2595
+ }
1181
2596
  report(r.findings, { assembly: ref, title: `${ref}: its gait` });
1182
- if (r.ok) { const w = m.writeGait(s, r); console.log(path.relative(WS, w.file)); console.log(path.relative(WS, w.preview)); }
2597
+ if (r.ok) {
2598
+ const w = m.writeGait(s, r);
2599
+ console.log(path.relative(WS, w.file));
2600
+ console.log(path.relative(WS, w.preview));
2601
+ }
1183
2602
  process.exitCode = r.ok ? 0 : 1;
1184
2603
  }
1185
2604
 
1186
2605
  async function platesCommand(what, ref) {
1187
- if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
2606
+ if (!isAssembly(ref))
2607
+ throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
1188
2608
  const s = await buildAssembly(ref);
1189
2609
  if (what === 'order') {
1190
- const { orderOf, orderText, stepPictures } = await import('../lib/order.mjs'), { withPreload } = await import('../lib/slotnuts.mjs'), r = withPreload(s, orderOf(s));
2610
+ const { orderOf, orderText, stepPictures } = await import('../lib/order.mjs'),
2611
+ { withPreload } = await import('../lib/slotnuts.mjs'),
2612
+ r = withPreload(s, orderOf(s));
1191
2613
  // a frame (beams with joins): from bars to a square frame, its sides built flat, nuts loaded before the join that would shut them in
1192
- const frame = s.joins?.length ? (await import('../lib/framebuild.mjs')) : null, fb = frame ? frame.frameBuild(s) : null;
1193
- if (opt('json')) { console.log(JSON.stringify(fb ? { ...r, frame: fb } : r, null, 2)); if (r.stuck || fb?.stuck) process.exitCode = 1; return; }
2614
+ const frame = s.joins?.length ? await import('../lib/framebuild.mjs') : null,
2615
+ fb = frame ? frame.frameBuild(s) : null;
2616
+ if (opt('json')) {
2617
+ console.log(JSON.stringify(fb ? { ...r, frame: fb } : r, null, 2));
2618
+ if (r.stuck || fb?.stuck) process.exitCode = 1;
2619
+ return;
2620
+ }
1194
2621
  console.log(fb ? frame.frameBuildText(ref, fb) : orderText(ref, r));
1195
- if (r.stuck || fb?.stuck) { process.exitCode = 1; return; }
1196
- if (opt('preview') && fb) { for (const { n, parts } of frame.frameStepPictures(s, fb)) { const st = fb.steps[n - 1], out = paths.preview(s.project, `${s.name}-step-${String(n).padStart(2, '0')}.png`); await preview(parts, { title: `${s.a.title || s.name}: step ${n} of ${fb.steps.length}`, meta: st.text, out }); console.log(path.relative(WS, out)); } return; } // (numbered as the frame's build is)
1197
- if (opt('preview')) { const pics = stepPictures(s, r); for (const [i, parts] of pics.entries()) { const st = r.steps[i], out = paths.preview(s.project, `${s.name}-step-${String(st.n).padStart(2, '0')}.png`); await preview(parts, { title: `${s.a.title || s.name}: step ${st.n} of ${r.steps.length}`, meta: st.text, out }); console.log(path.relative(WS, out)); } }
2622
+ if (r.stuck || fb?.stuck) {
2623
+ process.exitCode = 1;
2624
+ return;
2625
+ }
2626
+ if (opt('preview') && fb) {
2627
+ for (const { n, parts } of frame.frameStepPictures(s, fb)) {
2628
+ const st = fb.steps[n - 1],
2629
+ out = paths.preview(s.project, `${s.name}-step-${String(n).padStart(2, '0')}.png`);
2630
+ await preview(parts, { title: `${s.a.title || s.name}: step ${n} of ${fb.steps.length}`, meta: st.text, out });
2631
+ console.log(path.relative(WS, out));
2632
+ }
2633
+ return;
2634
+ } // (numbered as the frame's build is)
2635
+ if (opt('preview')) {
2636
+ const pics = stepPictures(s, r);
2637
+ for (const [i, parts] of pics.entries()) {
2638
+ const st = r.steps[i],
2639
+ out = paths.preview(s.project, `${s.name}-step-${String(st.n).padStart(2, '0')}.png`);
2640
+ await preview(parts, {
2641
+ title: `${s.a.title || s.name}: step ${st.n} of ${r.steps.length}`,
2642
+ meta: st.text,
2643
+ out,
2644
+ });
2645
+ console.log(path.relative(WS, out));
2646
+ }
2647
+ }
1198
2648
  return;
1199
2649
  }
1200
- const { platesOf, checkPlate } = await import('../lib/plates.mjs'), gap = opt('gap') != null ? Number(opt('gap')) : undefined;
2650
+ const { platesOf, checkPlate } = await import('../lib/plates.mjs'),
2651
+ gap = opt('gap') != null ? Number(opt('gap')) : undefined;
1201
2652
  if (gap != null && !(gap > 0)) throw new Error(`--gap is a distance in mm, above 0 (got ${opt('gap')})`);
1202
2653
  // a frame's jigs (its beams' drill and tap guides, length stops and squaring corners) on beds of their own, in the
1203
2654
  // project's plastic: exports/<project>/<assembly>.jigs.3mf, as cad beams --jigs writes them (--no-jigs leaves them)
1204
- const { cutListOf } = await import('../lib/beams.mjs'), jigs = !opt('no-jigs') && cutListOf(s) ? await (await import('../lib/jigs.mjs')).writeJigs(s) : null;
2655
+ const { cutListOf } = await import('../lib/beams.mjs'),
2656
+ jigs = !opt('no-jigs') && cutListOf(s) ? await (await import('../lib/jigs.mjs')).writeJigs(s) : null;
1205
2657
  let r;
1206
- try { r = await platesOf(s, { write: true, gap }); } catch (e) { if (e.code !== 'plates.empty' || !jigs?.jigs.length) throw e; r = { bed: null, gap: null, plates: [], touched: [], removed: [], findings: [] }; } // (bought fittings only: the jigs are what it prints)
2658
+ try {
2659
+ r = await platesOf(s, { write: true, gap });
2660
+ } catch (e) {
2661
+ if (e.code !== 'plates.empty' || !jigs?.jigs.length) throw e;
2662
+ r = { bed: null, gap: null, plates: [], touched: [], removed: [], findings: [] };
2663
+ } // (bought fittings only: the jigs are what it prints)
1207
2664
  const results = [];
1208
- for (const p of r.plates.filter((x) => !x.stood)) results.push({ name: p.name, findings: await checkPlate(`${s.project}/${p.name}`) });
1209
- const jigRows = jigs ? { plates: jigs.plates.map((p) => ({ ...p, file: path.relative(WS, p.file) })), count: jigs.jigs.length, grams: +jigs.jigs.reduce((t, x) => t + x.grams, 0).toFixed(1), findings: jigs.findings } : null;
1210
- const fails = [...r.findings, ...results.flatMap((x) => x.findings), ...(jigs?.findings ?? [])].some((x) => x.level === 'fail');
1211
- if (opt('json')) { console.log(JSON.stringify({ assembly: ref, bed: r.bed, gap: r.gap, plates: r.plates, repacked: r.touched, removed: r.removed, findings: r.findings, checks: results, ...(jigRows ? { jigs: jigRows } : {}) }, null, 2)); process.exitCode = fails ? 1 : 0; return; }
2665
+ for (const p of r.plates.filter((x) => !x.stood))
2666
+ results.push({ name: p.name, findings: await checkPlate(`${s.project}/${p.name}`) });
2667
+ const jigRows = jigs
2668
+ ? {
2669
+ plates: jigs.plates.map((p) => ({ ...p, file: path.relative(WS, p.file) })),
2670
+ count: jigs.jigs.length,
2671
+ grams: +jigs.jigs.reduce((t, x) => t + x.grams, 0).toFixed(1),
2672
+ findings: jigs.findings,
2673
+ }
2674
+ : null;
2675
+ const fails = [...r.findings, ...results.flatMap((x) => x.findings), ...(jigs?.findings ?? [])].some(
2676
+ (x) => x.level === 'fail',
2677
+ );
2678
+ if (opt('json')) {
2679
+ console.log(
2680
+ JSON.stringify(
2681
+ {
2682
+ assembly: ref,
2683
+ bed: r.bed,
2684
+ gap: r.gap,
2685
+ plates: r.plates,
2686
+ repacked: r.touched,
2687
+ removed: r.removed,
2688
+ findings: r.findings,
2689
+ checks: results,
2690
+ ...(jigRows ? { jigs: jigRows } : {}),
2691
+ },
2692
+ null,
2693
+ 2,
2694
+ ),
2695
+ );
2696
+ process.exitCode = fails ? 1 : 0;
2697
+ return;
2698
+ }
1212
2699
  report(r.findings);
1213
- if (r.plates.length) say(`${ref}: ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}, parts ${r.gap} mm apart (the first layer's rule)`);
1214
- for (const p of r.plates) say(` ${p.name}${p.stood ? ' (unchanged)' : ''}: ${p.material}, ${p.filament}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min: ${p.parts.map((x) => x.id).join(', ')}`);
2700
+ if (r.plates.length)
2701
+ say(
2702
+ `${ref}: ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}, parts ${r.gap} mm apart (the first layer's rule)`,
2703
+ );
2704
+ for (const p of r.plates)
2705
+ say(
2706
+ ` ${p.name}${p.stood ? ' (unchanged)' : ''}: ${p.material}, ${p.filament}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min: ${p.parts.map((x) => x.id).join(', ')}`,
2707
+ );
1215
2708
  if (r.removed.length) say(` removed ${r.removed.join(', ')} (nothing is on them now)`);
1216
- for (const x of results) { const bad = x.findings.filter((y) => (y.level === 'fail' || y.level === 'warn') && y.code !== 'rules.estimate'); say(` ${x.name}: ${bad.length ? `${bad.length} to look at` : 'prints clean'}`); for (const y of bad) say(` [${y.level}] ${y.text}`); }
2709
+ for (const x of results) {
2710
+ const bad = x.findings.filter((y) => (y.level === 'fail' || y.level === 'warn') && y.code !== 'rules.estimate');
2711
+ say(` ${x.name}: ${bad.length ? `${bad.length} to look at` : 'prints clean'}`);
2712
+ for (const y of bad) say(` [${y.level}] ${y.text}`);
2713
+ }
1217
2714
  if (jigRows?.count) {
1218
- say(`${ref}: ${jigRows.count} jig${jigRows.count === 1 ? '' : 's'} for its beams, ${jigRows.grams} g, on ${jigRows.plates.length} plate${jigRows.plates.length === 1 ? '' : 's'} of their own (cad beams ${ref} --jigs says what each is for)`);
1219
- for (const p of jigRows.plates) say(` ${p.file}: ${p.material}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}`);
2715
+ say(
2716
+ `${ref}: ${jigRows.count} jig${jigRows.count === 1 ? '' : 's'} for its beams, ${jigRows.grams} g, on ${jigRows.plates.length} plate${jigRows.plates.length === 1 ? '' : 's'} of their own (cad beams ${ref} --jigs says what each is for)`,
2717
+ );
2718
+ for (const p of jigRows.plates)
2719
+ say(` ${p.file}: ${p.material}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}`);
1220
2720
  for (const f of jigRows.findings) say(` [${f.level}] ${f.text}`);
1221
2721
  }
1222
2722
  process.exitCode = fails ? 1 : 0;
@@ -1224,97 +2724,240 @@ async function platesCommand(what, ref) {
1224
2724
 
1225
2725
  // An assembly's findings as cad check gives them: each pose (or the one asked for), what is the same in every pose
1226
2726
  // said once and the rest under the pose's name, after its files' schema check. cad kit counts the same list
1227
- function assemblyFindings(s, a, pose) {
2727
+ // (raw: the assembly as it would be written, checked in place of its file's)
2728
+ function assemblyFindings(s, a, pose, raw) {
1228
2729
  const poses = pose ? [pose] : Object.keys(s.motion.poses);
1229
- const file = path.join(paths.project(s.project), 'assemblies', `${s.name}.json`), layouts = new Set((a.items || []).map((i) => i.repeat?.layout).filter((l) => l && !l.includes('/')));
1230
- const schemaProblems = [...(fs.existsSync(file) ? schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'assembly', path.relative(WS, file)) : []),
1231
- ...[...layouts].map((l) => path.join(paths.project(s.project), 'layouts', `${l}.json`)).filter((f) => fs.existsSync(f)).flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'layout', path.relative(WS, f)))];
2730
+ const file = path.join(paths.project(s.project), 'assemblies', `${s.name}.json`),
2731
+ layouts = new Set((a.items || []).map((i) => i.repeat?.layout).filter((l) => isPlainName(l))); // (object/name is a layout kept in an object; a name that is not plain is refused where the layout is read)
2732
+ const schemaProblems = [
2733
+ ...(raw || fs.existsSync(file) ? schemaFindings(raw ?? readJson(file), 'assembly', path.relative(WS, file)) : []),
2734
+ ...[...layouts]
2735
+ .map((l) => path.join(paths.project(s.project), 'layouts', `${l}.json`))
2736
+ .filter((f) => fs.existsSync(f))
2737
+ .flatMap((f) => schemaFindings(readJson(f), 'layout', path.relative(WS, f))),
2738
+ ];
1232
2739
  let findings = checkAssembly(s);
1233
2740
  if (poses.length > 1) {
1234
- const each = poses.map((p) => [p, checkAssembly(s.at(p))]), same = (x) => each.every(([, list]) => list.some((y) => y.text === x.text && y.level === x.level));
1235
- findings = [{ level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}`, code: 'poses', refs: { poses } }, ...each[0][1].filter(same),
1236
- ...each.flatMap(([p, list]) => list.filter((x) => !same(x)).map((x) => ({ ...x, text: `${p}: ${x.text}`, ...(x.card ? { card: `${p}: ${x.card}` } : {}), refs: { ...x.refs, pose: p } })))];
2741
+ const each = poses.map((p) => [p, checkAssembly(s.at(p))]),
2742
+ same = (x) => each.every(([, list]) => list.some((y) => y.text === x.text && y.level === x.level));
2743
+ findings = [
2744
+ { level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}`, code: 'poses', refs: { poses } },
2745
+ ...each[0][1].filter(same),
2746
+ ...each.flatMap(([p, list]) =>
2747
+ list
2748
+ .filter((x) => !same(x))
2749
+ .map((x) => ({
2750
+ ...x,
2751
+ text: `${p}: ${x.text}`,
2752
+ ...(x.card ? { card: `${p}: ${x.card}` } : {}),
2753
+ refs: { ...x.refs, pose: p },
2754
+ })),
2755
+ ),
2756
+ ];
1237
2757
  }
1238
- findings.unshift(...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]));
2758
+ findings.unshift(
2759
+ ...(schemaProblems.length
2760
+ ? schemaProblems
2761
+ : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
2762
+ );
1239
2763
  return findings;
1240
2764
  }
1241
2765
 
1242
2766
  // cad kit: the folder to build an assembly from, without the model (lib/kit.mjs)
1243
2767
  async function kitCommand(ref) {
1244
- if (!isAssembly(ref)) throw new Error(`cad kit works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
2768
+ if (!isAssembly(ref))
2769
+ throw new Error(`cad kit works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
1245
2770
  // (laying out its plates reads the printer's rule set: a fresh workspace gets its own copy in rules/, as cad plates
1246
2771
  // gives it, and the kit says which it copied)
1247
- const rulesDir = path.join(WS, 'rules'), had = new Set(fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : []);
1248
- const s = await buildAssembly(ref), { writeKit } = await import('../lib/kit.mjs');
2772
+ const rulesDir = path.join(WS, 'rules'),
2773
+ had = new Set(fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : []);
2774
+ const s = await buildAssembly(ref),
2775
+ { writeKit } = await import('../lib/kit.mjs');
1249
2776
  const r = await writeKit(s, assemblyFindings(s, s.a, undefined), { pictures: !!opt('pictures'), preview });
1250
- const copied = (fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : []).filter((f) => f.endsWith('.json') && !had.has(f)).map((f) => `rules/${f}`);
1251
- const shown = { assembly: ref, dir: path.relative(WS, r.dir), files: r.files, copied, plates: r.plates.map(({ name, material, filament, parts, grams, minutes, file, issues }) => ({ name, material, filament, parts: parts.length, grams, minutes, file, issues })), jigs: r.jigs, sheets: r.sheets, steps: r.steps, warnings: r.findings.map((f) => f.text) };
2777
+ const copied = (fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : [])
2778
+ .filter((f) => f.endsWith('.json') && !had.has(f))
2779
+ .map((f) => `rules/${f}`);
2780
+ const shown = {
2781
+ assembly: ref,
2782
+ dir: path.relative(WS, r.dir),
2783
+ files: r.files,
2784
+ copied,
2785
+ plates: r.plates.map(({ name, material, filament, parts, grams, minutes, file, issues }) => ({
2786
+ name,
2787
+ material,
2788
+ filament,
2789
+ parts: parts.length,
2790
+ grams,
2791
+ minutes,
2792
+ file,
2793
+ issues,
2794
+ })),
2795
+ jigs: r.jigs,
2796
+ sheets: r.sheets,
2797
+ steps: r.steps,
2798
+ warnings: r.findings.map((f) => f.text),
2799
+ };
1252
2800
  if (opt('json')) return console.log(JSON.stringify(shown, null, 2));
1253
2801
  say(`${ref}: the kit to build it from, in ${shown.dir}${path.sep}`);
1254
- say(` README.md: what the checks say, what to buy, what to print${r.sheets.length ? ', the cut list, the drilling and tapping' : ''}${r.steps ? `, and the build in ${r.steps} steps` : ''}`);
2802
+ say(
2803
+ ` README.md: what the checks say, what to buy, what to print${r.sheets.length ? ', the cut list, the drilling and tapping' : ''}${r.steps ? `, and the build in ${r.steps} steps` : ''}`,
2804
+ );
1255
2805
  say(' buy.csv: the shopping list');
1256
- for (const p of shown.plates) say(` ${p.file}: ${p.material}, ${p.parts} part${p.parts === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min${p.issues.length ? ` (${p.issues.length} to look at)` : ''}`);
2806
+ for (const p of shown.plates)
2807
+ say(
2808
+ ` ${p.file}: ${p.material}, ${p.parts} part${p.parts === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min${p.issues.length ? ` (${p.issues.length} to look at)` : ''}`,
2809
+ );
1257
2810
  for (const p of r.jigs?.plates ?? []) say(` ${p.file}: ${r.jigs.count} jigs for the beams, ${p.parts} parts`);
1258
2811
  for (const x of r.sheets) say(` ${x.file}: mark ${x.mark} (${x.items.join(', ')})`);
1259
2812
  const pics = r.files.filter((f) => f.startsWith('pictures/'));
1260
2813
  if (pics.length) say(` pictures/: ${pics.length} pictures (the whole, and the steps of the build)`);
1261
2814
  for (const w of shown.warnings) say(` warning: ${w}`);
1262
- for (const f of copied) say(`and copied ${f} into this workspace: the rule set its plates were laid out by, yours to keep and edit (the next kit reads your copy)`);
2815
+ for (const f of copied)
2816
+ say(
2817
+ `and copied ${f} into this workspace: the rule set its plates were laid out by, yours to keep and edit (the next kit reads your copy)`,
2818
+ );
2819
+ }
2820
+
2821
+ // cad frame --size --write: the design it would write, built and checked as cad check checks it; refused, naming the
2822
+ // failing checks (each code and how many, the first three in full), where any check would fail
2823
+ async function refuseFailing(ref, next) {
2824
+ const n = await buildAssembly(ref, [], {}, { assembly: next }),
2825
+ failing = assemblyFindings(n, n.a, undefined, next).filter((x) => x.level === 'fail');
2826
+ if (!failing.length) return;
2827
+ const count = new Map();
2828
+ for (const x of failing) count.set(x.code ?? 'check', (count.get(x.code ?? 'check') ?? 0) + 1);
2829
+ const codes = [...count].map(([c, k]) => (k > 1 ? `${c} x${k}` : c)).join(', '),
2830
+ first = failing
2831
+ .slice(0, 3)
2832
+ .map((x) => x.text)
2833
+ .join('; ');
2834
+ throw new Error(
2835
+ `${ref}: with the sized profiles written in, cad check would fail ${failing.length} check${failing.length > 1 ? 's' : ''} (${codes}), so nothing is written. The first: ${first}. Fix what they name in the design, or leave the profile that breaks them out of frame.size.profiles, then size again`,
2836
+ );
1263
2837
  }
1264
2838
 
1265
2839
  // cad frame: a generated frame as it expands, and --expand writes the expansion into the assembly, to edit by hand
1266
2840
  async function frameCommand(ref) {
1267
- if (!isAssembly(ref)) throw new Error(`cad frame works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
1268
- const { expandFrame, frameText } = await import('../lib/framegen.mjs'), { assemblyPath } = await import('../lib/assembly.mjs');
1269
- const file = assemblyPath(ref), raw = readJson(file);
2841
+ if (!isAssembly(ref))
2842
+ throw new Error(`cad frame works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
2843
+ const { expandFrame, frameText } = await import('../lib/framegen.mjs'),
2844
+ { assemblyPath } = await import('../lib/assembly.mjs');
2845
+ const file = assemblyPath(ref),
2846
+ raw = readJson(file);
1270
2847
  if (opt('size')) {
1271
- const { frameSizing, sizingText, writeSizing, sizeOption } = await import('../lib/framesize.mjs'), { placeItems, jointValues, mul } = await import('@rulecad/model-link');
1272
- const s = await buildAssembly(ref), r = frameSizing(s, { placeItems, jointValues, mul }, sizeOption(s) ?? undefined);
1273
- if (!r) throw new Error(`${ref} has no frame to size: its beams need joins between them, or "frame": { "supports" }`);
1274
- const rows = r.rows, out = { assembly: ref, ok: r.ok, total: r.total, drawn: r.drawn, tried: r.tried, search: r.search, groups: rows, limits: r.limits };
2848
+ const { frameSizing, sizingText, writeSizing, sizeOption } = await import('../lib/framesize.mjs'),
2849
+ { placeItems, jointValues, mul } = await import('@rulecad/model-link');
2850
+ const s = await buildAssembly(ref),
2851
+ r = frameSizing(s, { placeItems, jointValues, mul }, sizeOption(s) ?? undefined);
2852
+ if (!r)
2853
+ throw new Error(`${ref} has no frame to size: its beams need joins between them, or "frame": { "supports" }`);
2854
+ const rows = r.rows,
2855
+ out = {
2856
+ assembly: ref,
2857
+ ok: r.ok,
2858
+ total: r.total,
2859
+ drawn: r.drawn,
2860
+ tried: r.tried,
2861
+ search: r.search,
2862
+ groups: rows,
2863
+ limits: r.limits,
2864
+ unchecked: r.unchecked,
2865
+ };
1275
2866
  if (opt('write')) {
1276
- if (!r.ok) throw new Error(`${ref}: no profile in the list meets every limit, so nothing is written (cad frame ${ref} --size says how near it comes)`);
1277
- if (opt('dry-run')) { // the sizing and the check above, nothing written
1278
- if (opt('json')) return console.log(JSON.stringify({ ...out, file: rel(file), written: false, dryRun: true }, null, 2));
2867
+ if (!r.ok)
2868
+ throw new Error(
2869
+ `${ref}: no profile in the list meets every limit, so nothing is written (cad frame ${ref} --size says how near it comes)`,
2870
+ );
2871
+ // the profiles drawn are already the ones chosen: nothing to write, and a generated frame stays generated
2872
+ if (rows.every((x) => !x.roll && x.drawn.length === 1 && x.drawn[0] === x.profile.replace(/^profile-/, ''))) {
2873
+ if (opt('json'))
2874
+ return console.log(JSON.stringify({ ...out, file: rel(file), written: false, unchanged: true }, null, 2));
1279
2875
  console.log(sizingText(r).join('\n'));
1280
- return console.log(`dry run, nothing written: would write ${rel(file)}`);
2876
+ return console.log(
2877
+ `nothing written: every beam already has the profile chosen for it, so ${rel(file)} stays as it is`,
2878
+ );
1281
2879
  }
1282
- fs.writeFileSync(file, `${JSON.stringify(writeSizing(raw, raw.frame?.kind != null ? expandFrame(raw, s.num).a : raw, r), null, 2)}\n`);
2880
+ const next = writeSizing(raw, raw.frame?.kind != null ? expandFrame(raw, s.num).a : raw, r);
2881
+ await refuseFailing(ref, next);
2882
+ if (opt('dry-run')) {
2883
+ // the sizing and the checks above, nothing written
2884
+ if (opt('json'))
2885
+ return console.log(JSON.stringify({ ...out, file: rel(file), written: false, dryRun: true }, null, 2));
2886
+ console.log(sizingText(r).join('\n'));
2887
+ return console.log(`dry run, nothing written: would write ${rel(file)}, which cad check passes`);
2888
+ }
2889
+ fs.writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`);
1283
2890
  if (opt('json')) return console.log(JSON.stringify({ ...out, file: path.relative(WS, file) }, null, 2));
1284
2891
  console.log(sizingText(r).join('\n'));
1285
- return console.log(`wrote ${path.relative(WS, file)}: ${rows.reduce((t, x) => t + x.beams.length, 0)} beams given their profiles${raw.frame?.kind != null ? ' (the generated frame written out expanded, as --expand does, as a generator takes one profile)' : ''}; their lines are kept (a deeper beam that would stand past the end of the one it meets moves along it), so check the joins and ends of any beam that changed size`);
2892
+ return console.log(
2893
+ `wrote ${path.relative(WS, file)}: ${rows.reduce((t, x) => t + x.beams.length, 0)} beams given their profiles${raw.frame?.kind != null ? ' (the generated frame written out expanded, as --expand does, as a generator takes one profile)' : ''}; their lines are kept (a deeper beam that would stand past the end of the one it meets moves along it), so check the joins and ends of any beam that changed size`,
2894
+ );
1286
2895
  }
1287
2896
  if (opt('json')) return console.log(JSON.stringify(out, null, 2));
1288
- return console.log(`${ref}: ${sizingText(r).join('\n')}\n(cad frame ${ref} --size --write writes these profiles into the assembly)`);
2897
+ return console.log(
2898
+ `${ref}: ${sizingText(r).join('\n')}\n(cad frame ${ref} --size --write writes these profiles into the assembly)`,
2899
+ );
1289
2900
  }
1290
- if (raw.frame?.kind == null) throw new Error(`${ref} asks for no generated frame: give it "frame": { "kind": "box", "inside": [300, 300, 350], "profile": "2020-misumi-hfs5", "join": "blind" }`);
1291
- const s = await buildAssembly(ref), m = s.generated, out = expandFrame(raw, s.num).a;
2901
+ if (raw.frame?.kind == null)
2902
+ throw new Error(
2903
+ `${ref} asks for no generated frame: give it "frame": { "kind": "box", "inside": [300, 300, 350], "profile": "2020-misumi-hfs5", "join": "blind" }`,
2904
+ );
2905
+ const s = await buildAssembly(ref),
2906
+ m = s.generated,
2907
+ out = expandFrame(raw, s.num).a;
1292
2908
  if (opt('expand') && opt('dry-run')) {
1293
- if (opt('json')) return console.log(JSON.stringify({ assembly: ref, file: rel(file), written: false, dryRun: true, frame: m, expanded: out }, null, 2));
1294
- return console.log(`dry run, nothing written: would write ${rel(file)}: the ${m.kind} as ${m.beams.length + (m.moving ? 1 : 0)} beams, ${m.joins.length} joins and ${m.ends.length + m.panels.length} fittings`);
2909
+ if (opt('json'))
2910
+ return console.log(
2911
+ JSON.stringify(
2912
+ { assembly: ref, file: rel(file), written: false, dryRun: true, frame: m, expanded: out },
2913
+ null,
2914
+ 2,
2915
+ ),
2916
+ );
2917
+ return console.log(
2918
+ `dry run, nothing written: would write ${rel(file)}: the ${m.kind} as ${m.beams.length + (m.moving ? 1 : 0)} beams, ${m.joins.length} joins and ${m.ends.length + m.panels.length} fittings`,
2919
+ );
1295
2920
  }
1296
2921
  if (opt('expand')) {
1297
2922
  fs.writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`);
1298
- if (opt('json')) return console.log(JSON.stringify({ assembly: ref, file: path.relative(WS, file), frame: m }, null, 2));
1299
- return console.log(`wrote ${path.relative(WS, file)}: the ${m.kind} as ${m.beams.length + (m.moving ? 1 : 0)} beams, ${m.joins.length} joins and ${m.ends.length + m.panels.length} fittings, to edit by hand (its "frame" keeps only how it is solved)`);
2923
+ if (opt('json'))
2924
+ return console.log(JSON.stringify({ assembly: ref, file: path.relative(WS, file), frame: m }, null, 2));
2925
+ return console.log(
2926
+ `wrote ${path.relative(WS, file)}: the ${m.kind} as ${m.beams.length + (m.moving ? 1 : 0)} beams, ${m.joins.length} joins and ${m.ends.length + m.panels.length} fittings, to edit by hand (its "frame" keeps only how it is solved)`,
2927
+ );
1300
2928
  }
1301
2929
  if (opt('json')) return console.log(JSON.stringify({ assembly: ref, frame: m, expanded: out }, null, 2));
1302
- console.log(`${ref}: ${frameText(m).join('\n')}\n(cad frame ${ref} --expand writes these into the assembly, to edit by hand)`);
2930
+ console.log(
2931
+ `${ref}: ${frameText(m).join('\n')}\n(cad frame ${ref} --expand writes these into the assembly, to edit by hand)`,
2932
+ );
1303
2933
  }
1304
2934
 
1305
2935
  async function listCommand(what, ref) {
1306
- if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
2936
+ if (!isAssembly(ref))
2937
+ throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
1307
2938
  const s = await buildAssembly(ref);
1308
2939
  if (what === 'list') {
1309
- const { shoppingList, listText } = await import('../lib/list.mjs'), l = shoppingList(s);
2940
+ const { shoppingList, listText } = await import('../lib/list.mjs'),
2941
+ l = shoppingList(s);
1310
2942
  return console.log(opt('json') ? JSON.stringify(l, null, 2) : listText(ref, l));
1311
2943
  }
1312
2944
  if (what === 'beams' && opt('jigs')) {
1313
- const { writeJigs, jigsText } = await import('../lib/jigs.mjs'), r = await writeJigs(s), rel = (f) => path.relative(WS, f);
2945
+ const { writeJigs, jigsText } = await import('../lib/jigs.mjs'),
2946
+ r = await writeJigs(s),
2947
+ rel = (f) => path.relative(WS, f);
1314
2948
  const shown = { ...r, plates: r.plates.map((p) => ({ ...p, file: rel(p.file) })) };
1315
2949
  if (opt('preview') && r.parts.length) {
1316
2950
  const out = paths.preview(s.project, `${s.name}-jigs.png`);
1317
- await preview(r.parts.flatMap((o) => o.parts.map((p) => ({ name: p.name, label: p.name, role: 'part', triangles: p.triangles }))), { title: `${s.a.title || s.name}: jigs`, meta: `${r.jigs.length} jigs on ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}`, out });
2951
+ await preview(
2952
+ r.parts.flatMap((o) =>
2953
+ o.parts.map((p) => ({ name: p.name, label: p.name, role: 'part', triangles: p.triangles })),
2954
+ ),
2955
+ {
2956
+ title: `${s.a.title || s.name}: jigs`,
2957
+ meta: `${r.jigs.length} jigs on ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}`,
2958
+ out,
2959
+ },
2960
+ );
1318
2961
  shown.preview = rel(out);
1319
2962
  }
1320
2963
  delete shown.parts;
@@ -1325,35 +2968,81 @@ async function listCommand(what, ref) {
1325
2968
  return;
1326
2969
  }
1327
2970
  if (what === 'beams') {
1328
- const { writeBeamSheets } = await import('../lib/beams.mjs'), sheets = writeBeamSheets(s);
1329
- if (opt('json')) return console.log(JSON.stringify(sheets.map((x) => ({ ...x, file: path.relative(WS, x.file) })), null, 2));
2971
+ const { writeBeamSheets } = await import('../lib/beams.mjs'),
2972
+ sheets = writeBeamSheets(s);
2973
+ if (opt('json'))
2974
+ return console.log(
2975
+ JSON.stringify(
2976
+ sheets.map((x) => ({ ...x, file: path.relative(WS, x.file) })),
2977
+ null,
2978
+ 2,
2979
+ ),
2980
+ );
1330
2981
  if (!sheets.length) return console.log(`${ref} has no beams`);
1331
2982
  for (const x of sheets) say(` mark ${x.mark} (${x.items.join(', ')}), 1:${x.scale}: ${path.relative(WS, x.file)}`);
1332
- const { writeFrameShape, writeFrameMode } = await import('../lib/framecheck.mjs'), sag = writeFrameShape(s), mode = writeFrameMode(s);
1333
- if (sag) say(` the frame's sag, drawn ${+sag.scale.toPrecision(3)} times its size (a check view): ${path.relative(WS, sag.file)}`);
1334
- if (mode) say(` the frame's lowest mode, ${+mode.Hz.toPrecision(3)} Hz, animated (a check view): ${path.relative(WS, mode.file)}`);
2983
+ const { writeFrameShape, writeFrameMode } = await import('../lib/framecheck.mjs'),
2984
+ sag = writeFrameShape(s),
2985
+ mode = writeFrameMode(s);
2986
+ if (sag)
2987
+ say(
2988
+ ` the frame's sag, drawn ${+sag.scale.toPrecision(3)} times its size (a check view): ${path.relative(WS, sag.file)}`,
2989
+ );
2990
+ if (mode)
2991
+ say(
2992
+ ` the frame's lowest mode, ${+mode.Hz.toPrecision(3)} Hz, animated (a check view): ${path.relative(WS, mode.file)}`,
2993
+ );
1335
2994
  return;
1336
2995
  }
1337
- const { wiresFor } = await import('../lib/assembly.mjs'), { wiringSheet } = await import('../lib/wires.mjs'), rows = wiresFor(s);
1338
- if (opt('json')) return console.log(JSON.stringify(rows.map(({ route, ...r }) => r), null, 2));
2996
+ const { wiresFor } = await import('../lib/assembly.mjs'),
2997
+ { wiringSheet } = await import('../lib/wires.mjs'),
2998
+ rows = wiresFor(s);
2999
+ if (opt('json'))
3000
+ return console.log(
3001
+ JSON.stringify(
3002
+ rows.map(({ route, ...r }) => r),
3003
+ null,
3004
+ 2,
3005
+ ),
3006
+ );
1339
3007
  if (!rows.length) return console.log(`${ref} has no "wires"`);
1340
- if (opt('out')) { fs.writeFileSync(path.resolve(opt('out')), wiringSheet(rows) + '\n'); return console.log(`wrote ${opt('out')}`); }
1341
- const { writeWiring } = await import('../lib/buildpage.mjs'), file = writeWiring(s);
1342
- console.log(wiringSheet(rows)); say(path.relative(WS, file));
3008
+ if (opt('out')) {
3009
+ fs.writeFileSync(path.resolve(opt('out')), wiringSheet(rows) + '\n');
3010
+ return console.log(`wrote ${opt('out')}`);
3011
+ }
3012
+ const { writeWiring } = await import('../lib/buildpage.mjs'),
3013
+ file = writeWiring(s);
3014
+ console.log(wiringSheet(rows));
3015
+ say(path.relative(WS, file));
1343
3016
  }
1344
3017
 
1345
3018
  async function measuredCommand(ref) {
1346
3019
  const { recordMeasured, assumptionsTable, writeTable, ledgerLines } = await import('../lib/measured.mjs');
1347
3020
  if (opt('table')) {
1348
3021
  const table = await assumptionsTable(ref);
1349
- if (opt('out')) { writeTable(path.resolve(opt('out')), table); return console.log(`wrote the table to ${opt('out')}`); }
3022
+ if (opt('out')) {
3023
+ writeTable(path.resolve(opt('out')), table);
3024
+ return console.log(`wrote the table to ${opt('out')}`);
3025
+ }
1350
3026
  return console.log(table);
1351
3027
  }
1352
- const values = Object.fromEntries(positional().slice(2).map((x) => { const i = x.indexOf('='); if (i < 1) throw new Error(`usage: cad measured <project>/<assembly> <name>=<value> … (got "${x}")`); return [x.slice(0, i), Number(x.slice(i + 1))]; }));
3028
+ const values = Object.fromEntries(
3029
+ positional()
3030
+ .slice(2)
3031
+ .map((x) => {
3032
+ const i = x.indexOf('=');
3033
+ if (i < 1) throw new Error(`usage: cad measured <project>/<assembly> <name>=<value> … (got "${x}")`);
3034
+ return [x.slice(0, i), Number(x.slice(i + 1))];
3035
+ }),
3036
+ );
1353
3037
  const r = await recordMeasured(ref, values, { unit: opt('unit'), source: opt('source'), rule: opt('rule') });
1354
3038
  if (opt('json')) return console.log(JSON.stringify({ entries: r.entries, moved: r.moved }, null, 2));
1355
3039
  for (const l of ledgerLines(r.entries)) say(l);
1356
- for (const m of r.moved) say(m.figure ? ` ${m.figure}: ${Number(m.from.toFixed(4))} ${m.unit} to ${Number(m.to.toFixed(4))} ${m.unit}` : ` ${m.code}: ${m.text}`);
3040
+ for (const m of r.moved)
3041
+ say(
3042
+ m.figure
3043
+ ? ` ${m.figure}: ${Number(m.from.toFixed(4))} ${m.unit} to ${Number(m.to.toFixed(4))} ${m.unit}`
3044
+ : ` ${m.code}: ${m.text}`,
3045
+ );
1357
3046
  if (!r.moved.length) say(' nothing the checks say has moved');
1358
3047
  }
1359
3048
 
@@ -1369,29 +3058,55 @@ async function history(ref) {
1369
3058
  const { rows, lines } = await ledger(project, name);
1370
3059
  if (opt('json')) return console.log(JSON.stringify({ assembly: ref, ledger: rows }, null, 2));
1371
3060
  if (!lines.length) return say(`${ref}: nothing measured yet (cad measured ${ref} <name>=<value>)`);
1372
- say('predicted against measured:'); for (const l of lines) say(` ${l}`);
3061
+ say('predicted against measured:');
3062
+ for (const l of lines) say(` ${l}`);
1373
3063
  return;
1374
3064
  }
1375
3065
  if (!name) {
1376
3066
  const { rows, lines } = await ledger(project);
1377
- if (lines.length && !opt('json')) { console.log('predicted against measured:'); for (const l of lines) console.log(` ${l}`); }
1378
- if (opt('json')) return console.log(JSON.stringify({ project, releases: tags(project).reverse(), ledger: rows }, null, 2));
3067
+ if (lines.length && !opt('json')) {
3068
+ console.log('predicted against measured:');
3069
+ for (const l of lines) console.log(` ${l}`);
3070
+ }
3071
+ if (opt('json'))
3072
+ return console.log(JSON.stringify({ project, releases: tags(project).reverse(), ledger: rows }, null, 2));
1379
3073
  for (const t of tags(project).reverse()) console.log(`${t.tag} ${t.date} ${t.kind} ${t.message}`);
1380
3074
  return status(project);
1381
3075
  }
1382
- const d = locate(ref), done = prints(d);
3076
+ const d = locate(ref),
3077
+ done = prints(d);
1383
3078
  const s = await since(d);
1384
- 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));
1385
- if (s.kind && s.last) { console.log(`unreleased (needs ${s.kind}):`); for (const r of s.reasons) console.log(` ${r.text}`); }
3079
+ if (opt('json'))
3080
+ return console.log(
3081
+ JSON.stringify(
3082
+ {
3083
+ object: ref,
3084
+ unreleased: s.kind && s.last ? { kind: s.kind, reasons: s.reasons.map((r) => r.text) } : null,
3085
+ releases: tags(d.project, d.name)
3086
+ .reverse()
3087
+ .map((t) => ({ ...t, prints: done.filter((x) => x.version === t.version) })),
3088
+ },
3089
+ null,
3090
+ 2,
3091
+ ),
3092
+ );
3093
+ if (s.kind && s.last) {
3094
+ console.log(`unreleased (needs ${s.kind}):`);
3095
+ for (const r of s.reasons) console.log(` ${r.text}`);
3096
+ }
1386
3097
  for (const t of tags(d.project, d.name).reverse()) {
1387
3098
  console.log(`${t.version.padEnd(8)} ${t.date} ${t.kind.padEnd(5)} ${t.message}`);
1388
- for (const p of done.filter((x) => x.version === t.version)) console.log(` printed ${p.date} in ${p.material}: ${p.result}${p.note ? `, ${p.note}` : ''}${p.set ? ` (${p.set})` : ''}`);
3099
+ for (const p of done.filter((x) => x.version === t.version))
3100
+ console.log(
3101
+ ` printed ${p.date} in ${p.material}: ${p.result}${p.note ? `, ${p.note}` : ''}${p.set ? ` (${p.set})` : ''}`,
3102
+ );
1389
3103
  }
1390
3104
  }
1391
3105
 
1392
3106
  async function diff(d, from, to) {
1393
3107
  if (!from) throw new Error('usage: cad diff <project>/<object> <from> [<to>]');
1394
- const a = await snap(materialise(d, from)), b = await snap(to ? materialise(d, to) : d);
3108
+ const a = await snap(materialise(d, from)),
3109
+ b = await snap(to ? materialise(d, to) : d);
1395
3110
  const r = compare(a, b);
1396
3111
  console.log(`${d.project}/${d.name} ${from} → ${to || 'now'}: ${r.kind ? `a ${r.kind} change` : 'no changes'}`);
1397
3112
  for (const x of r.reasons) console.log(` ${x.kind.padEnd(5)} ${x.text}`);
@@ -1399,16 +3114,40 @@ async function diff(d, from, to) {
1399
3114
 
1400
3115
  function printed(d) {
1401
3116
  const result = opt('result');
1402
- if (!['ok', 'failed'].includes(result)) throw new Error('--result ok or --result failed (and --note "what happened")');
1403
- const object = readObject(d), released = tags(d.project, d.name).map((t) => t.version), version = opt('version') || released.at(-1) || object.version;
1404
- if (opt('version') && version !== object.version && !released.includes(version)) throw new Error(`${d.name} has no version ${version} (${released.length ? `releases: ${released.join(', ')}` : `unreleased, at ${object.version}`})`);
1405
- const entry = { date: today(), object: d.name, version, ...(opt('set') ? { set: opt('set') } : {}), material: opt('material') || object.material, result, ...(opt('note') ? { note: opt('note') } : {}) };
1406
- fs.appendFileSync(printsFile(d), JSON.stringify(entry) + '\n');
3117
+ if (!['ok', 'failed'].includes(result))
3118
+ throw new Error('--result ok or --result failed (and --note "what happened")');
3119
+ const object = readObject(d),
3120
+ released = tags(d.project, d.name).map((t) => t.version),
3121
+ version = opt('version') || released.at(-1) || object.version;
3122
+ if (opt('version') && version !== object.version && !released.includes(version))
3123
+ throw new Error(
3124
+ `${d.name} has no version ${version} (${released.length ? `releases: ${released.join(', ')}` : `unreleased, at ${object.version}`})`,
3125
+ );
3126
+ const entry = {
3127
+ date: today(),
3128
+ object: d.name,
3129
+ version,
3130
+ ...(opt('set') ? { set: opt('set') } : {}),
3131
+ material: opt('material') || object.material,
3132
+ result,
3133
+ ...(opt('note') ? { note: opt('note') } : {}),
3134
+ };
3135
+ fs.appendFileSync(insideWorkspace(printsFile(d)), JSON.stringify(entry) + '\n'); // (never through a link: rules.mjs)
1407
3136
  console.log(`logged in ${path.relative(WS, printsFile(d))}: ${d.name}@${version} ${result}`);
1408
3137
  }
1409
3138
 
1410
3139
  main().catch((e) => {
1411
- if (opt('json')) console.log(JSON.stringify({ error: errorData({ ...e, message: e.message, code: e.code, file: e.file && path.relative(WS, e.file) }) }, null, 2));
1412
- else console.error(`${e.message}${e.file ? ` (${path.relative(WS, e.file)}${e.line ? `:${e.line}` : ''}${e.path ? `: ${e.path}` : ''})` : ''}`);
3140
+ if (opt('json'))
3141
+ console.log(
3142
+ JSON.stringify(
3143
+ { error: errorData({ ...e, message: e.message, code: e.code, file: e.file && path.relative(WS, e.file) }) },
3144
+ null,
3145
+ 2,
3146
+ ),
3147
+ );
3148
+ else
3149
+ console.error(
3150
+ `${e.message}${e.file ? ` (${path.relative(WS, e.file)}${e.line ? `:${e.line}` : ''}${e.path ? `: ${e.path}` : ''})` : ''}`,
3151
+ );
1413
3152
  process.exit(1);
1414
3153
  });