@rulecad/cad 0.8.0 → 0.10.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 (102) hide show
  1. package/AGENTS.md +45 -16
  2. package/CHANGELOG.md +724 -0
  3. package/EXAMPLES.md +61 -54
  4. package/README.md +376 -98
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2664 -541
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1883 -435
  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/cache-file.mjs +105 -0
  15. package/lib/carried.mjs +201 -0
  16. package/lib/clone.mjs +194 -42
  17. package/lib/code-text.mjs +28 -0
  18. package/lib/design-imports.mjs +127 -0
  19. package/lib/design.mjs +871 -147
  20. package/lib/designshapes.mjs +142 -0
  21. package/lib/drive.mjs +187 -63
  22. package/lib/edit.mjs +922 -192
  23. package/lib/errors.mjs +16 -3
  24. package/lib/estimates.mjs +51 -0
  25. package/lib/explain.mjs +62 -13
  26. package/lib/fasten.mjs +2708 -507
  27. package/lib/fe-key.mjs +29 -0
  28. package/lib/fittings.mjs +721 -122
  29. package/lib/fixings.mjs +38 -13
  30. package/lib/framebuild.mjs +790 -175
  31. package/lib/framecheck.mjs +1901 -368
  32. package/lib/framegen.mjs +108 -22
  33. package/lib/frameheat.mjs +225 -42
  34. package/lib/frameprint.mjs +513 -108
  35. package/lib/frames.mjs +86 -18
  36. package/lib/framesize.mjs +719 -120
  37. package/lib/frametip.mjs +235 -0
  38. package/lib/gait.mjs +135 -23
  39. package/lib/grip.mjs +62 -13
  40. package/lib/guides.mjs +1403 -230
  41. package/lib/host.mjs +129 -23
  42. package/lib/inplace.mjs +171 -36
  43. package/lib/jigs.mjs +360 -78
  44. package/lib/joins.mjs +697 -118
  45. package/lib/jsonedit.mjs +88 -26
  46. package/lib/kept.mjs +84 -0
  47. package/lib/kit.mjs +439 -69
  48. package/lib/layout.mjs +2 -1
  49. package/lib/links.mjs +149 -42
  50. package/lib/list.mjs +334 -64
  51. package/lib/live-guard.mjs +68 -0
  52. package/lib/live-shape.mjs +96 -24
  53. package/lib/live.mjs +189 -59
  54. package/lib/loads.mjs +597 -136
  55. package/lib/machine.mjs +372 -74
  56. package/lib/magnets.mjs +162 -44
  57. package/lib/measured.mjs +1080 -117
  58. package/lib/mesh.mjs +526 -119
  59. package/lib/meshcmd.mjs +215 -60
  60. package/lib/motors.mjs +1002 -214
  61. package/lib/motorsvg.mjs +114 -32
  62. package/lib/names.mjs +18 -1
  63. package/lib/optimise.mjs +991 -287
  64. package/lib/order.mjs +515 -114
  65. package/lib/panels.mjs +482 -94
  66. package/lib/parts.mjs +81 -23
  67. package/lib/pins.mjs +163 -44
  68. package/lib/plates.mjs +223 -35
  69. package/lib/player.mjs +37 -9
  70. package/lib/power.mjs +64 -13
  71. package/lib/preview.mjs +83 -16
  72. package/lib/profilemeasure.mjs +572 -129
  73. package/lib/rules.mjs +17 -6
  74. package/lib/sandbox-hooks.mjs +179 -27
  75. package/lib/sandbox-lock.mjs +225 -0
  76. package/lib/sandbox-preload.mjs +2 -2
  77. package/lib/sandbox-run.mjs +122 -25
  78. package/lib/sandbox.mjs +667 -75
  79. package/lib/schema.mjs +42 -11
  80. package/lib/seats.mjs +227 -49
  81. package/lib/services.mjs +261 -52
  82. package/lib/sheet.mjs +963 -179
  83. package/lib/slotnuts.mjs +213 -34
  84. package/lib/targets/gist.mjs +4 -1
  85. package/lib/targets.mjs +22 -4
  86. package/lib/task.mjs +376 -79
  87. package/lib/versions.mjs +285 -39
  88. package/lib/wires.mjs +228 -45
  89. package/lib/workspace.mjs +200 -14
  90. package/package.json +19 -19
  91. package/schemas/assembly.schema.json +2 -2
  92. package/schemas/project.schema.json +6 -0
  93. package/templates/coupons/MEASURE.md +109 -0
  94. package/templates/coupons/assemblies/fixings-test.json +20 -0
  95. package/templates/coupons/assemblies/slot-test.json +11 -0
  96. package/templates/coupons/objects/fixings-coupon.js +88 -0
  97. package/templates/coupons/objects/fixings-coupon.json +26 -0
  98. package/templates/coupons/objects/holds-coupon.js +130 -0
  99. package/templates/coupons/objects/holds-coupon.json +42 -0
  100. package/templates/coupons/objects/slot-coupon.js +89 -0
  101. package/templates/coupons/objects/slot-coupon.json +29 -0
  102. package/templates/coupons/project.json +10 -0
package/lib/edit.mjs CHANGED
@@ -7,22 +7,45 @@ import { setAt, appendAt, getAt, removeAt } from './jsonedit.mjs';
7
7
  import { validate, schema } from './schema.mjs';
8
8
  import { CadError } from './errors.mjs';
9
9
  import { paths } from './workspace.mjs';
10
+ import { readOwnText } from './host.mjs'; // (a file of the workspace only where it really is inside it, never through a link out)
10
11
  import { plainName, isPlainName } from './names.mjs';
11
12
  import { locate, readObject, objectSets } from './design.mjs';
12
- import { resolve, evaluate, peekRuleSet } from './rules.mjs';
13
+ import { resolve, evaluate, peekRuleSet, isName } from './rules.mjs';
13
14
  import { expandFrame, frameText } from './framegen.mjs';
14
15
  import { framesContext } from './beams.mjs';
15
16
  import { plasticNamed } from './fittings.mjs';
16
17
 
17
18
  // A value from the command line: a number if it is one, otherwise an expression (or a name) as text
18
- export const parseValue = (s) => (s === undefined ? undefined : /^-?(\d+\.?\d*|\.\d+)(e-?\d+)?$/i.test(String(s).trim()) ? Number(s) : String(s));
19
+ export const parseValue = (s) =>
20
+ s === undefined ? undefined : /^-?(\d+\.?\d*|\.\d+)(e-?\d+)?$/i.test(String(s).trim()) ? Number(s) : String(s);
21
+
22
+ /**
23
+ * A value from the command line for a variable, read by the variable's kind: a text, anchor, layout or problem variable
24
+ * keeps the text as typed (a legend 007 stays 007, never the number 7); a choice takes the option named, a number only
25
+ * where that option is one (a turn of 90); any other variable, and a new one, is read as parseValue reads it.
26
+ * @param {object | undefined} d the variable as the object's .json holds it @param {string | undefined} s @returns {any}
27
+ */
28
+ export function valueFor(d, s) {
29
+ if (s === undefined || !d || typeof d !== 'object' || !isName(d)) return parseValue(s);
30
+ const t = String(s),
31
+ named = Array.isArray(d.choice) ? d.choice.find((o) => String(o) === t) : undefined;
32
+ return named !== undefined ? named : t;
33
+ }
19
34
 
20
35
  // The edited text, parsed and held to its schema: refused by name, nothing written
21
36
  function checked(file, text, kind) {
22
37
  let json;
23
- try { json = JSON.parse(text); } catch (e) { throw new CadError('edit.broken', `the edit would break ${file}'s JSON: ${e.message}`, { file }); }
38
+ try {
39
+ json = JSON.parse(text);
40
+ } catch (e) {
41
+ throw new CadError('edit.broken', `the edit would break ${file}'s JSON: ${e.message}`, { file });
42
+ }
24
43
  const problems = validate(json, schema(kind));
25
- if (problems.length) throw new CadError('schema', `${path.basename(file)}: ${problems[0].path}: ${problems[0].message}`, { file, path: problems[0].path });
44
+ if (problems.length)
45
+ throw new CadError('schema', `${path.basename(file)}: ${problems[0].path}: ${problems[0].message}`, {
46
+ file,
47
+ path: problems[0].path,
48
+ });
26
49
  return json;
27
50
  }
28
51
 
@@ -33,34 +56,65 @@ function checked(file, text, kind) {
33
56
  * @param {{ create?: boolean, dryRun?: boolean }} [options] @returns {Promise<{ file: string, changed: string[], written: boolean, dryRun?: true }>}
34
57
  */
35
58
  export async function setVariables(ref, changes, { create = false, dryRun = false } = {}) {
36
- const d = locate(ref), before = fs.readFileSync(d.json, 'utf8');
59
+ const d = locate(ref),
60
+ before = readOwnText(d.json);
37
61
  let text = before;
38
62
  for (const [name, c] of Object.entries(changes)) {
39
63
  const exists = getAt(text, ['variables', name]) !== undefined;
40
- if (!exists && !create) throw new CadError('var.unknown', `${ref} has no variable "${name}" (add it with --new, a unit and a rule)`, { file: d.json, path: `variables.${name}` });
41
- if (!exists && (c.value === undefined || !c.rule)) throw new CadError('edit.incomplete', `a new variable needs a value and a rule (why the value is what it is): ${name}`, { file: d.json });
42
- if (!exists) { text = setAt(text, ['variables', name], { value: c.value, ...(c.unit !== undefined ? { unit: c.unit } : {}), rule: c.rule, ...(c.label ? { label: c.label } : {}) }); continue; }
43
- for (const k of ['value', 'unit', 'rule', 'label']) if (c[k] !== undefined) text = setAt(text, ['variables', name, k], c[k]);
64
+ if (!exists && !create)
65
+ throw new CadError('var.unknown', `${ref} has no variable "${name}" (add it with --new, a unit and a rule)`, {
66
+ file: d.json,
67
+ path: `variables.${name}`,
68
+ });
69
+ if (!exists && (c.value === undefined || !c.rule))
70
+ throw new CadError(
71
+ 'edit.incomplete',
72
+ `a new variable needs a value and a rule (why the value is what it is): ${name}`,
73
+ { file: d.json },
74
+ );
75
+ if (!exists) {
76
+ text = setAt(text, ['variables', name], {
77
+ value: c.value,
78
+ ...(c.unit !== undefined ? { unit: c.unit } : {}),
79
+ rule: c.rule,
80
+ ...(c.label ? { label: c.label } : {}),
81
+ });
82
+ continue;
83
+ }
84
+ for (const k of ['value', 'unit', 'rule', 'label'])
85
+ if (c[k] !== undefined) text = setAt(text, ['variables', name, k], c[k]);
44
86
  }
45
87
  const json = checked(d.json, text, 'object');
46
- try { // the variables must still resolve: an unknown name or a loop is refused (the edit changes no uses, so the sets are the file's own)
88
+ try {
89
+ // the variables must still resolve: an unknown name or a loop is refused (the edit changes no uses, so the sets are the file's own)
47
90
  const { values } = resolve(json, { sets: (await objectSets(d, readObject(d))).sets });
48
91
  // and each changed value must lie within the variable's own range, where it has one (a tweak's min and max)
49
92
  for (const name of Object.keys(changes)) {
50
- const t = json.variables?.[name]?.tweak, v = values[name];
93
+ const t = json.variables?.[name]?.tweak,
94
+ v = values[name];
51
95
  if (!t || typeof v !== 'number') continue;
52
- const lo = typeof t.min === 'number' ? t.min : -Infinity, hi = typeof t.max === 'number' ? t.max : Infinity;
53
- if (v < lo || v > hi) throw new CadError('edit.range', `${name} = ${v} is outside its range, ${t.min ?? '…'} to ${t.max ?? '…'} (change the range first if it should go there)`, { file: d.json, path: `variables.${name}` });
96
+ const lo = typeof t.min === 'number' ? t.min : -Infinity,
97
+ hi = typeof t.max === 'number' ? t.max : Infinity;
98
+ if (v < lo || v > hi)
99
+ throw new CadError(
100
+ 'edit.range',
101
+ `${name} = ${v} is outside its range, ${t.min ?? '…'} to ${t.max ?? '…'} (change the range first if it should go there)`,
102
+ { file: d.json, path: `variables.${name}` },
103
+ );
54
104
  }
55
- } catch (e) { throw Object.assign(e, { file: d.json, message: `not changed: ${e.message}` }); }
105
+ } catch (e) {
106
+ throw Object.assign(e, { file: d.json, message: `not changed: ${e.message}` });
107
+ }
56
108
  const written = !dryRun && text !== before;
57
109
  if (written) fs.writeFileSync(d.json, text);
58
110
  return { file: d.json, changed: Object.keys(changes), written, ...(dryRun ? { dryRun: true } : {}) };
59
111
  }
60
112
 
61
113
  const assemblyFile = (ref) => {
62
- const [project, name] = ref.split('/'), file = path.join(paths.project(project), 'assemblies', `${plainName(name, 'assembly name')}.json`); // (from the command line: never ../, nor ..\ on Windows)
63
- if (!fs.existsSync(file)) throw new CadError('assembly.missing', `no assembly at ${path.relative(paths.project(project), file)}`, { file });
114
+ const [project, name] = ref.split('/'),
115
+ file = path.join(paths.project(project), 'assemblies', `${plainName(name, 'assembly name')}.json`); // (from the command line: never ../, nor ..\ on Windows)
116
+ if (!fs.existsSync(file))
117
+ throw new CadError('assembly.missing', `no assembly at ${path.relative(paths.project(project), file)}`, { file });
64
118
  return file;
65
119
  };
66
120
 
@@ -71,8 +125,11 @@ const assemblyFile = (ref) => {
71
125
  * @param {{ dryRun?: boolean }} [options] @returns {{ file: string, written: boolean, changes: object[], findings: object[] }}
72
126
  */
73
127
  export function addToAssembly(ref, what, entry, { dryRun = false } = {}) {
74
- const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), list = LIST_OF[what];
75
- let text = before, at;
128
+ const file = assemblyFile(ref),
129
+ before = readOwnText(file),
130
+ list = LIST_OF[what];
131
+ let text = before,
132
+ at;
76
133
  if (what === 'pose') {
77
134
  entryProblems('pose', entry, { ref, file, known: knownOf(JSON.parse(text)) });
78
135
  if (getAt(text, ['poses']) === undefined) text = setAt(text, ['poses'], {});
@@ -81,15 +138,30 @@ export function addToAssembly(ref, what, entry, { dryRun = false } = {}) {
81
138
  } else {
82
139
  if (!list) throw new CadError('edit.what', `can't add a ${what} (${Object.keys(LIST_OF).join(', ')} or pose)`);
83
140
  if (getAt(text, [list]) === undefined) text = setAt(text, [list], []);
84
- const json = JSON.parse(text), ids = (json[list] || []).map((x) => x.id).filter(Boolean);
85
- if (entry.id && ids.includes(entry.id)) throw new CadError('edit.duplicate', `${ref} already has a ${what} "${entry.id}"`, { file });
141
+ const json = JSON.parse(text),
142
+ ids = (json[list] || []).map((x) => x.id).filter(Boolean);
143
+ if (entry.id && ids.includes(entry.id))
144
+ throw new CadError('edit.duplicate', `${ref} already has a ${what} "${entry.id}"`, { file });
86
145
  const known = knownOf(json);
87
- if (entry.id && what === 'item' && known.generated.includes(entry.id)) throw new CadError('edit.duplicate', `${ref}'s generated frame already names a part "${entry.id}": give the item another id`, { file });
146
+ if (entry.id && what === 'item' && known.generated.includes(entry.id))
147
+ throw new CadError(
148
+ 'edit.duplicate',
149
+ `${ref}'s generated frame already names a part "${entry.id}": give the item another id`,
150
+ { file },
151
+ );
88
152
  entryProblems(what, entry, { ref, file, known, self: idOf(list, entry, (json[list] || []).length) });
89
153
  text = appendAt(text, [list], entry);
90
154
  at = `${list}.${(json[list] || []).length}`;
91
155
  }
92
- return finish({ ref, file, before, text, kind: 'assembly', changes: [{ op: 'add', path: at, after: entry }], dryRun });
156
+ return finish({
157
+ ref,
158
+ file,
159
+ before,
160
+ text,
161
+ kind: 'assembly',
162
+ changes: [{ op: 'add', path: at, after: entry }],
163
+ dryRun,
164
+ });
93
165
  }
94
166
 
95
167
  /**
@@ -102,14 +174,28 @@ export function addToAssembly(ref, what, entry, { dryRun = false } = {}) {
102
174
  */
103
175
  export function fastenFromFitsEdit(ref, found, { screw, dryRun = false } = {}) {
104
176
  const file = assemblyFile(ref);
105
- if (!found.length) throw new CadError('edit.nothing', `${ref} has no holes fit with a fit that fastens the same two items (and no fasten for them yet): nothing to put a fasten in place of`, { file });
106
- let text = fs.readFileSync(file, 'utf8');
107
- const fits = getAt(text, ['fits']), drop = new Set(), trim = new Set();
108
- for (const g of found) { drop.add(g.holes); (fits[g.fastens].min != null || fits[g.fastens].max != null ? trim : drop).add(g.fastens); }
177
+ if (!found.length)
178
+ throw new CadError(
179
+ 'edit.nothing',
180
+ `${ref} has no holes fit with a fit that fastens the same two items (and no fasten for them yet): nothing to put a fasten in place of`,
181
+ { file },
182
+ );
183
+ let text = readOwnText(file);
184
+ const fits = getAt(text, ['fits']),
185
+ drop = new Set(),
186
+ trim = new Set();
187
+ for (const g of found) {
188
+ drop.add(g.holes);
189
+ (fits[g.fastens].min != null || fits[g.fastens].max != null ? trim : drop).add(g.fastens);
190
+ }
109
191
  // last first, so the places of the others hold
110
192
  for (const i of [...new Set([...drop, ...trim])].sort((a, b) => b - a)) {
111
- if (drop.has(i)) { text = removeAt(text, ['fits', i]); continue; }
112
- for (const k of ['count', 'fastener', 'fastens']) if (getAt(text, ['fits', i, k]) !== undefined) text = removeAt(text, ['fits', i, k]);
193
+ if (drop.has(i)) {
194
+ text = removeAt(text, ['fits', i]);
195
+ continue;
196
+ }
197
+ for (const k of ['count', 'fastener', 'fastens'])
198
+ if (getAt(text, ['fits', i, k]) !== undefined) text = removeAt(text, ['fits', i, k]);
113
199
  }
114
200
  if (getAt(text, ['fasten']) === undefined) text = setAt(text, ['fasten'], []);
115
201
  const added = found.map((g) => ({ ...g.fasten, ...(screw ? { screw } : {}) }));
@@ -126,7 +212,17 @@ export function fastenFromFitsEdit(ref, found, { screw, dryRun = false } = {}) {
126
212
  // Each returns { file, written, changes: [{ op, path, before, after }], findings }, the shape cad prints with --json.
127
213
 
128
214
  /** The list each kind of entry goes in. */
129
- export const LIST_OF = { fit: 'fits', joint: 'joints', item: 'items', loop: 'loops', fasten: 'fasten', join: 'joins', guide: 'guides', load: 'loads', wire: 'wires' };
215
+ export const LIST_OF = {
216
+ fit: 'fits',
217
+ joint: 'joints',
218
+ item: 'items',
219
+ loop: 'loops',
220
+ fasten: 'fasten',
221
+ join: 'joins',
222
+ guide: 'guides',
223
+ load: 'loads',
224
+ wire: 'wires',
225
+ };
130
226
  // The lists whose entries have ids (a guide without one is g1, g2 .. by its place)
131
227
  const ID_LISTS = ['items', 'joints', 'guides', 'wires'];
132
228
  const LISTS = [...new Set([...Object.values(LIST_OF), 'planetary'])];
@@ -136,13 +232,20 @@ const rootOf = (n) => String(n).split(/[.@]/)[0];
136
232
  // Numbers in an assembly's expressions, from the rule sets it uses (read, never copied in): enough for a frame's size
137
233
  function numFor(a) {
138
234
  const values = {};
139
- for (const u of a.uses || []) { try { values[u] = Object.fromEntries(Object.entries(peekRuleSet(u).rules || {}).map(([k, r]) => [k, r.value])); } catch {} }
235
+ for (const u of a.uses || []) {
236
+ try {
237
+ values[u] = Object.fromEntries(Object.entries(peekRuleSet(u).rules || {}).map(([k, r]) => [k, r.value]));
238
+ } catch {
239
+ // (a rule set that can't be read gives no values here: cad check names it)
240
+ }
241
+ }
140
242
  const lookup = (n) => {
141
243
  const p = n.split('.');
142
244
  let v = values;
143
245
  for (const k of p) v = v?.[k];
144
246
  if (typeof v === 'string') v = evaluate(v, (k) => lookup(k.includes('.') ? k : `${p.slice(0, -1).join('.')}.${k}`));
145
- if (typeof v !== 'number') throw Object.assign(new Error(`"${n}" is not a rule this check can read`), { code: 'edit.unread' });
247
+ if (typeof v !== 'number')
248
+ throw Object.assign(new Error(`"${n}" is not a rule this check can read`), { code: 'edit.unread' });
146
249
  return v;
147
250
  };
148
251
  return (x) => evaluate(x, lookup);
@@ -155,12 +258,35 @@ function numFor(a) {
155
258
  * @returns {{ items: object[], beams: string[], generated: string[], guides: string[], joints: string[], joins: object[], wires: string[], frame: object | null, refused: Error | null }}
156
259
  */
157
260
  export function knownOf(a) {
158
- let items = a.items || [], joints = a.joints || [], joins = a.joins || [], frame = null, refused = null, generated = [];
261
+ let items = a.items || [],
262
+ joints = a.joints || [],
263
+ joins = a.joins || [],
264
+ frame = null,
265
+ refused = null,
266
+ generated = [];
159
267
  if (a.frame && typeof a.frame === 'object' && a.frame.kind != null) {
160
- try { const x = expandFrame(a, numFor(a), framesContext()); frame = x.frame; generated = x.a.items.slice(0, x.a.items.length - items.length).map((it) => it.id); items = x.a.items; joints = x.a.joints || joints; joins = x.a.joins || joins; } catch (e) { refused = e; }
268
+ try {
269
+ const x = expandFrame(a, numFor(a), framesContext());
270
+ frame = x.frame;
271
+ generated = x.a.items.slice(0, x.a.items.length - items.length).map((it) => it.id);
272
+ items = x.a.items;
273
+ joints = x.a.joints || joints;
274
+ joins = x.a.joins || joins;
275
+ } catch (e) {
276
+ refused = e;
277
+ }
161
278
  }
162
- return { items, beams: items.filter((x) => x?.beam).map((x) => x.id), generated, guides: (a.guides || []).map((g, i) => idOf('guides', g, i)), joints: joints.map((j) => j?.id).filter(Boolean),
163
- joins: Array.isArray(joins) ? joins : [], wires: (Array.isArray(a.wires) ? a.wires : []).map((w, i) => w?.id ?? `w${i + 1}`), frame, refused };
279
+ return {
280
+ items,
281
+ beams: items.filter((x) => x?.beam).map((x) => x.id),
282
+ generated,
283
+ guides: (a.guides || []).map((g, i) => idOf('guides', g, i)),
284
+ joints: joints.map((j) => j?.id).filter(Boolean),
285
+ joins: Array.isArray(joins) ? joins : [],
286
+ wires: (Array.isArray(a.wires) ? a.wires : []).map((w, i) => w?.id ?? `w${i + 1}`),
287
+ frame,
288
+ refused,
289
+ };
164
290
  }
165
291
 
166
292
  // The names an assembly's build makes that are not in its file, each by the exact pattern its maker uses (lib/assembly,
@@ -170,155 +296,354 @@ export function knownOf(a) {
170
296
  // (g1-carriage-1, g1-belt); and the joints the build makes, a guide's sliding joints (g1-1) and a panel's hinge or bay
171
297
  // (door-hinge). A name that only starts with an item's id and a dash (rail-3, where rail is one beam) is none of them.
172
298
  const esc = (x) => String(x).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
173
- const GUIDE_PART = /^(carriage-\d+|wheel-\d+|holder-[ab]|endstop|endstop-mount|rod-\d+|bearing-\d+|plate|motor|coupler|screw|nut|support-[ab]|pulley|clamp|idler|idler-block|belt)$/;
299
+ const GUIDE_PART =
300
+ /^(carriage-\d+|wheel-\d+|holder-[ab]|endstop|endstop-mount|rod-\d+|bearing-\d+|plate|motor|coupler|screw|nut|support-[ab]|pulley|clamp|idler|idler-block|belt)$/;
174
301
  const PANEL_PART = /^(clip|hinge-\d+|leaf-\d+|handle|latch|catch)(-\d+)?$/;
175
302
  /**
176
303
  * The items and joints an assembly's build makes from its entries, by name. @param {ReturnType<typeof knownOf>} known
177
304
  * @returns {{ item: (n: string) => boolean, joint: (n: string) => boolean }}
178
305
  */
179
306
  export function madeBy(known) {
180
- const one = (n, id, re) => { const s = String(n), head = `${id}-`; return s.startsWith(head) && re.test(s.slice(head.length)); };
181
- const joins = (known.joins || []).filter((j) => j && typeof j.a === 'string' && typeof j.b === 'string').map((j) => new RegExp(`^${esc(rootOf(j.a))}-${esc(rootOf(j.b))}-[a-z]+(-\\d+)?$`));
307
+ const one = (n, id, re) => {
308
+ const s = String(n),
309
+ head = `${id}-`;
310
+ return s.startsWith(head) && re.test(s.slice(head.length));
311
+ };
312
+ const joins = (known.joins || [])
313
+ .filter((j) => j && typeof j.a === 'string' && typeof j.b === 'string')
314
+ .map((j) => new RegExp(`^${esc(rootOf(j.a))}-${esc(rootOf(j.b))}-[a-z]+(-\\d+)?$`));
182
315
  const items = known.items.filter((it) => it?.id != null);
183
- const item = (n) => items.some((it) => (it.repeat != null && one(n, it.id, /^\d+(-\d+)?$/)) || (it.mount != null && one(n, it.id, /^mount(-\d+)?$/))
184
- || (it.panel != null && one(n, it.id, PANEL_PART)) || (it.fitting?.kind === 'levelling-foot' && one(n, it.id, /^pad$/)))
185
- || known.guides.some((g) => one(n, g, GUIDE_PART)) || (known.wires || []).some((w) => one(n, w, /^clip(-\d+)?$/)) || joins.some((re) => re.test(String(n)));
186
- const joint = (n) => known.guides.some((g) => one(n, g, /^\d+$/)) || items.some((it) => it.panel != null && one(n, it.id, /^(hinge|bay)$/));
316
+ const item = (n) =>
317
+ items.some(
318
+ (it) =>
319
+ (it.repeat != null && one(n, it.id, /^\d+(-\d+)?$/)) ||
320
+ (it.mount != null && one(n, it.id, /^mount(-\d+)?$/)) ||
321
+ (it.panel != null && one(n, it.id, PANEL_PART)) ||
322
+ (it.fitting?.kind === 'levelling-foot' && one(n, it.id, /^pad$/)),
323
+ ) ||
324
+ known.guides.some((g) => one(n, g, GUIDE_PART)) ||
325
+ (known.wires || []).some((w) => one(n, w, /^clip(-\d+)?$/)) ||
326
+ joins.some((re) => re.test(String(n)));
327
+ const joint = (n) =>
328
+ known.guides.some((g) => one(n, g, /^\d+$/)) ||
329
+ items.some((it) => it.panel != null && one(n, it.id, /^(hinge|bay)$/));
187
330
  return { item, joint };
188
331
  }
189
332
 
190
333
  // The names an entry gives must be there: a fit's parts, a fasten's, a join's beams, a guide's beam and the guide it
191
334
  // drives, a joint's parent and child items and the joint it follows, a pose's joints. self is the entry's own id.
192
335
  function entryProblems(what, entry, { ref, file, known, self }) {
193
- const items = known.items, ids = items.map((x) => x?.id), list = (xs) => xs.join(', ') || 'none';
336
+ const items = known.items,
337
+ ids = items.map((x) => x?.id),
338
+ list = (xs) => xs.join(', ') || 'none';
194
339
  const { item: made, joint: madeJoint } = madeBy(known); // what the build makes: g1-carriage-1, psu-mount, key-0-3 (madeBy)
195
- if (what === 'fit') for (const side of ['a', 'b']) {
196
- const named = entry[side]; if (typeof named !== 'string') continue;
197
- const [item, part = 'body'] = named.split('@')[0].split('.'), it = items.find((x) => x?.id === item);
198
- if (!it && made(item)) continue; // a guide's part or a repeated item's copy (key-0-3)
199
- if (!it) throw new CadError('edit.part', `fit ${side}: no item "${item}" in ${ref} (items: ${list(ids)})`, { file });
200
- if (it.object) {
201
- const [project] = ref.split('/'), own = String(it.object).split(/[@:]/)[0], obj = isPlainName(own) && path.join(paths.project(project), 'objects', `${own}.json`); // (a name from the assembly's file: read only where it is plain)
202
- const parts = obj && fs.existsSync(obj) ? Object.keys(JSON.parse(fs.readFileSync(obj, 'utf8')).parts || { body: {} }) : null;
203
- if (parts && !parts.includes(part)) throw new CadError('edit.part', `fit ${side}: ${it.object} has no part "${part}" (parts: ${parts.join(', ')})`, { file });
340
+ if (what === 'fit')
341
+ for (const side of ['a', 'b']) {
342
+ const named = entry[side];
343
+ if (typeof named !== 'string') continue;
344
+ const [item, part = 'body'] = named.split('@')[0].split('.'),
345
+ it = items.find((x) => x?.id === item);
346
+ if (!it && made(item)) continue; // a guide's part or a repeated item's copy (key-0-3)
347
+ if (!it)
348
+ throw new CadError('edit.part', `fit ${side}: no item "${item}" in ${ref} (items: ${list(ids)})`, { file });
349
+ if (it.object) {
350
+ const [project] = ref.split('/'),
351
+ own = String(it.object).split(/[@:]/)[0],
352
+ obj = isPlainName(own) && path.join(paths.project(project), 'objects', `${own}.json`); // (a name from the assembly's file: read only where it is plain)
353
+ const parts =
354
+ obj && fs.existsSync(obj) ? Object.keys(JSON.parse(readOwnText(obj)).parts || { body: {} }) : null;
355
+ if (parts && !parts.includes(part))
356
+ throw new CadError(
357
+ 'edit.part',
358
+ `fit ${side}: ${it.object} has no part "${part}" (parts: ${parts.join(', ')})`,
359
+ { file },
360
+ );
361
+ }
204
362
  }
205
- }
206
363
  // a fasten names the parts its screw passes and ends in, and where the screws go: each must be an item of the assembly
207
364
  if (what === 'fasten') {
208
365
  const has = (n) => ids.includes(rootOf(n)) || made(rootOf(n));
209
- if (!entry.screw) throw new CadError('edit.incomplete', 'a fasten needs its screw, by thread and head: --screw "M3 cap"', { file });
210
- if (!entry.into || !Array.isArray(entry.through)) throw new CadError('edit.incomplete', 'a fasten needs the parts the screw passes and the one it ends in: --through bracket --into base', { file });
211
- if ((entry.at == null) === (entry.holes == null)) throw new CadError('edit.incomplete', 'a fasten needs where its screws go: --at bracket.h1,bracket.h2 (an anchor each) or --holes bracket.body (a part whose holes they use), one of the two', { file });
212
- for (const n of [...entry.through, entry.into, ...(entry.holes ? [entry.holes] : []), ...(entry.at || []).filter((x) => typeof x === 'string')]) if (!has(n)) throw new CadError('edit.part', `fasten: no item "${rootOf(n)}" in ${ref} (items: ${list(ids)})`, { file });
366
+ if (!entry.screw)
367
+ throw new CadError('edit.incomplete', 'a fasten needs its screw, by thread and head: --screw "M3 cap"', { file });
368
+ if (!entry.into || !Array.isArray(entry.through))
369
+ throw new CadError(
370
+ 'edit.incomplete',
371
+ 'a fasten needs the parts the screw passes and the one it ends in: --through bracket --into base',
372
+ { file },
373
+ );
374
+ if ((entry.at == null) === (entry.holes == null))
375
+ throw new CadError(
376
+ 'edit.incomplete',
377
+ 'a fasten needs where its screws go: --at bracket.h1,bracket.h2 (an anchor each) or --holes bracket.body (a part whose holes they use), one of the two',
378
+ { file },
379
+ );
380
+ for (const n of [
381
+ ...entry.through,
382
+ entry.into,
383
+ ...(entry.holes ? [entry.holes] : []),
384
+ ...(entry.at || []).filter((x) => typeof x === 'string'),
385
+ ])
386
+ if (!has(n))
387
+ throw new CadError('edit.part', `fasten: no item "${rootOf(n)}" in ${ref} (items: ${list(ids)})`, { file });
213
388
  }
214
389
  // a join names a beam's end and a place on another beam: each must be a beam of the assembly, its frame's included
215
390
  if (what === 'join') {
216
- if (!entry.kind || !entry.a || !entry.b) throw new CadError('edit.incomplete', 'a join needs its kind and the two beams: --kind blind --a y1.a --b x1.back@120', { file });
217
- for (const side of ['a', 'b']) { const id = rootOf(entry[side]); if (!known.beams.includes(id)) throw new CadError('edit.part', `join ${side}: no beam "${id}" in ${ref} (beams: ${list(known.beams)})`, { file }); }
391
+ if (!entry.kind || !entry.a || !entry.b)
392
+ throw new CadError(
393
+ 'edit.incomplete',
394
+ 'a join needs its kind and the two beams: --kind blind --a y1.a --b x1.back@120',
395
+ { file },
396
+ );
397
+ for (const side of ['a', 'b']) {
398
+ const id = rootOf(entry[side]);
399
+ if (!known.beams.includes(id))
400
+ throw new CadError('edit.part', `join ${side}: no beam "${id}" in ${ref} (beams: ${list(known.beams)})`, {
401
+ file,
402
+ });
403
+ }
218
404
  }
219
405
  // an item placed at an address, and a load carried at one, name an item that is there
220
- if ((what === 'item' || what === 'load') && typeof entry.at === 'string' && !ids.includes(rootOf(entry.at)) && !made(rootOf(entry.at)))
221
- throw new CadError('edit.part', `${what} at: no item "${rootOf(entry.at)}" in ${ref} (items: ${list(ids)})`, { file });
406
+ if (
407
+ (what === 'item' || what === 'load') &&
408
+ typeof entry.at === 'string' &&
409
+ !ids.includes(rootOf(entry.at)) &&
410
+ !made(rootOf(entry.at))
411
+ )
412
+ throw new CadError('edit.part', `${what} at: no item "${rootOf(entry.at)}" in ${ref} (items: ${list(ids)})`, {
413
+ file,
414
+ });
222
415
  // a guide runs on a beam's face, and a screw guide drives another guide
223
416
  if (what === 'guide') {
224
- if (entry.on != null && !known.beams.includes(rootOf(entry.on))) throw new CadError('edit.part', `guide on: no beam "${rootOf(entry.on)}" in ${ref} (beams: ${list(known.beams)})`, { file });
225
- if (entry.guide != null && !known.guides.includes(String(entry.guide))) throw new CadError('edit.part', `guide: no guide "${entry.guide}" in ${ref} for it to drive (guides: ${list(known.guides)})`, { file });
226
- if (entry.guide != null && self != null && String(entry.guide) === self) throw new CadError('edit.part', `guide ${self}: it names itself as the guide it drives (guides: ${list(known.guides)})`, { file });
417
+ if (entry.on != null && !known.beams.includes(rootOf(entry.on)))
418
+ throw new CadError(
419
+ 'edit.part',
420
+ `guide on: no beam "${rootOf(entry.on)}" in ${ref} (beams: ${list(known.beams)})`,
421
+ { file },
422
+ );
423
+ if (entry.guide != null && !known.guides.includes(String(entry.guide)))
424
+ throw new CadError(
425
+ 'edit.part',
426
+ `guide: no guide "${entry.guide}" in ${ref} for it to drive (guides: ${list(known.guides)})`,
427
+ { file },
428
+ );
429
+ if (entry.guide != null && self != null && String(entry.guide) === self)
430
+ throw new CadError(
431
+ 'edit.part',
432
+ `guide ${self}: it names itself as the guide it drives (guides: ${list(known.guides)})`,
433
+ { file },
434
+ );
227
435
  }
228
436
  // a joint ties an anchor on its child item to one on its parent (an anchor by item.anchor, or { item, at }), and may
229
437
  // follow another joint
230
438
  if (what === 'joint') {
231
439
  for (const side of ['parent', 'child']) {
232
- const r = entry[side], item = typeof r === 'string' ? rootOf(r) : r && typeof r === 'object' && r.item != null ? String(r.item) : null;
233
- if (item != null && !ids.includes(item) && !made(item)) throw new CadError('edit.part', `joint ${entry.id ?? ''} ${side}: no item "${item}" in ${ref} (items: ${list(ids)})`.replace(' ', ' '), { file });
440
+ const r = entry[side],
441
+ item = typeof r === 'string' ? rootOf(r) : r && typeof r === 'object' && r.item != null ? String(r.item) : null;
442
+ if (item != null && !ids.includes(item) && !made(item))
443
+ throw new CadError(
444
+ 'edit.part',
445
+ `joint ${entry.id ?? ''} ${side}: no item "${item}" in ${ref} (items: ${list(ids)})`.replace(' ', ' '),
446
+ { file },
447
+ );
234
448
  }
235
- if (entry.follow != null && !known.joints.includes(String(entry.follow))) throw new CadError('edit.part', `joint ${entry.id ?? ''} follow: no joint "${entry.follow}" in ${ref} (joints: ${list(known.joints)})`.replace(' ', ' '), { file });
449
+ if (entry.follow != null && !known.joints.includes(String(entry.follow)))
450
+ throw new CadError(
451
+ 'edit.part',
452
+ `joint ${entry.id ?? ''} follow: no joint "${entry.follow}" in ${ref} (joints: ${list(known.joints)})`.replace(
453
+ ' ',
454
+ ' ',
455
+ ),
456
+ { file },
457
+ );
236
458
  }
237
459
  // a pose gives values to joints by id (its keys with a dot in them are not joints); a guide's and an item's own
238
460
  // joints (g1-1, door-hinge) are made as it is built, so a name under one of theirs is taken as theirs
239
- if (what === 'pose') for (const k of Object.keys(entry.values || {})) {
240
- if (k.includes('.') || known.joints.includes(k) || madeJoint(k)) continue;
241
- throw new CadError('edit.part', `pose ${entry.name}: no joint "${k}" in ${ref} (joints: ${list(known.joints)})`, { file });
242
- }
461
+ if (what === 'pose')
462
+ for (const k of Object.keys(entry.values || {})) {
463
+ if (k.includes('.') || known.joints.includes(k) || madeJoint(k)) continue;
464
+ throw new CadError('edit.part', `pose ${entry.name}: no joint "${k}" in ${ref} (joints: ${list(known.joints)})`, {
465
+ file,
466
+ });
467
+ }
243
468
  // a wire runs from an anchor to an anchor, by anchors, path joints and runs along a beam's slot (via); a loop closes
244
469
  // between two anchors; a load is on a joint or carried at an anchor; a mounted item sits at an address on a beam.
245
470
  // An anchor is <item>.<anchor> (or { item, at }): its item must be there, or be one a guide or an item makes (g1-carriage-1,
246
471
  // psu-mount, key-0-3)
247
- const anchorItem = (r) => (typeof r === 'string' ? rootOf(r) : r && typeof r === 'object' && r.item != null ? String(r.item) : null);
248
- const noItem = (label, r) => { const item = anchorItem(r); if (item != null && !ids.includes(item) && !made(item)) throw new CadError('edit.part', `${label}: no item "${item}" in ${ref} (items: ${list(ids)})`, { file }); };
249
- const noBeam = (label, r) => { const id = rootOf(r); if (!known.beams.includes(id)) throw new CadError('edit.part', `${label}: no beam "${id}" in ${ref} (beams: ${list(known.beams)})`, { file }); };
472
+ const anchorItem = (r) =>
473
+ typeof r === 'string' ? rootOf(r) : r && typeof r === 'object' && r.item != null ? String(r.item) : null;
474
+ const noItem = (label, r) => {
475
+ const item = anchorItem(r);
476
+ if (item != null && !ids.includes(item) && !made(item))
477
+ throw new CadError('edit.part', `${label}: no item "${item}" in ${ref} (items: ${list(ids)})`, { file });
478
+ };
479
+ const noBeam = (label, r) => {
480
+ const id = rootOf(r);
481
+ if (!known.beams.includes(id))
482
+ throw new CadError('edit.part', `${label}: no beam "${id}" in ${ref} (beams: ${list(known.beams)})`, { file });
483
+ };
250
484
  const name = entry.id != null ? ` ${entry.id}` : '';
251
485
  if (what === 'wire') {
252
486
  for (const side of ['from', 'to']) if (entry[side] != null) noItem(`wire${name} ${side}`, entry[side]);
253
487
  for (const v of Array.isArray(entry.via) ? entry.via : []) {
254
488
  if (typeof v === 'string' && v.includes('.')) noItem(`wire${name} via`, v);
255
- else if (typeof v === 'string' && !known.joints.includes(v) && !madeJoint(v)) throw new CadError('edit.part', `wire${name} via: no joint "${v}" in ${ref}, and an anchor is <item>.<anchor> (joints: ${list(known.joints)})`, { file });
489
+ else if (typeof v === 'string' && !known.joints.includes(v) && !madeJoint(v))
490
+ throw new CadError(
491
+ 'edit.part',
492
+ `wire${name} via: no joint "${v}" in ${ref}, and an anchor is <item>.<anchor> (joints: ${list(known.joints)})`,
493
+ { file },
494
+ );
256
495
  else if (v && typeof v === 'object' && v.along != null) noBeam(`wire${name} via along`, v.along);
257
496
  }
258
497
  }
259
498
  if (what === 'loop') for (const side of ['a', 'b']) noItem(`loop ${side}`, entry[side]);
260
499
  if (what === 'load') {
261
- if (entry.joint != null && !known.joints.includes(String(entry.joint)) && !madeJoint(String(entry.joint))) throw new CadError('edit.part', `load joint: no joint "${entry.joint}" in ${ref} (joints: ${list(known.joints)})`, { file });
500
+ if (entry.joint != null && !known.joints.includes(String(entry.joint)) && !madeJoint(String(entry.joint)))
501
+ throw new CadError(
502
+ 'edit.part',
503
+ `load joint: no joint "${entry.joint}" in ${ref} (joints: ${list(known.joints)})`,
504
+ { file },
505
+ );
262
506
  if (entry.at != null && typeof entry.at === 'object') noItem('load at', entry.at);
263
507
  }
264
- if (what === 'item' && entry.mount && typeof entry.mount === 'object' && entry.mount.on != null) noBeam(`item${name} mount on`, entry.mount.on);
508
+ if (what === 'item' && entry.mount && typeof entry.mount === 'object' && entry.mount.on != null)
509
+ noBeam(`item${name} mount on`, entry.mount.on);
265
510
  }
266
511
 
267
512
  // Every entry's names, checked as entryProblems checks one: [{ at, key, message }], where key is the same for the same
268
513
  // problem in the same entry before and after an edit (its place may move, and the lists in its message change)
269
514
  function namesProblems(json, known, { ref, file }) {
270
- const out = [], one = (at, what, entry, self) => {
271
- try { entryProblems(what, entry, { ref, file, known, self }); } catch (e) { out.push({ at, key: `${what}|${JSON.stringify(entry)}|${String(e.message).replace(/ \(.*$/s, '')}`, message: e.message }); }
272
- };
273
- for (const [what, list] of Object.entries(LIST_OF)) (Array.isArray(json[list]) ? json[list] : []).forEach((e, i) => { if (e && typeof e === 'object') one(`${list}.${i}`, what, e, idOf(list, e, i)); });
274
- for (const [name, values] of Object.entries(json.poses && typeof json.poses === 'object' ? json.poses : {})) if (values && typeof values === 'object') one(`poses.${name}`, 'pose', { name, values });
515
+ const out = [],
516
+ one = (at, what, entry, self) => {
517
+ try {
518
+ entryProblems(what, entry, { ref, file, known, self });
519
+ } catch (e) {
520
+ out.push({
521
+ at,
522
+ key: `${what}|${JSON.stringify(entry)}|${String(e.message).replace(/ \(.*$/s, '')}`,
523
+ message: e.message,
524
+ });
525
+ }
526
+ };
527
+ for (const [what, list] of Object.entries(LIST_OF))
528
+ (Array.isArray(json[list]) ? json[list] : []).forEach((e, i) => {
529
+ if (e && typeof e === 'object') one(`${list}.${i}`, what, e, idOf(list, e, i));
530
+ });
531
+ for (const [name, values] of Object.entries(json.poses && typeof json.poses === 'object' ? json.poses : {}))
532
+ if (values && typeof values === 'object') one(`poses.${name}`, 'pose', { name, values });
275
533
  return out;
276
534
  }
277
535
 
278
536
  // A changed assembly, checked: its schema, its generated frame still expanding, and the names in each entry it touched
279
537
  function assemblyFindings(json, { ref, file, touched = [], before = '' }) {
280
538
  const problems = validate(json, schema('assembly'));
281
- if (problems.length) throw new CadError('schema', `not changed: ${path.basename(file)}: ${problems[0].path}: ${problems[0].message}`, { file, path: problems[0].path });
282
- const out = [{ level: 'pass', text: 'matches the assembly schema', code: 'schema' }], known = knownOf(json);
539
+ if (problems.length)
540
+ throw new CadError('schema', `not changed: ${path.basename(file)}: ${problems[0].path}: ${problems[0].message}`, {
541
+ file,
542
+ path: problems[0].path,
543
+ });
544
+ const out = [{ level: 'pass', text: 'matches the assembly schema', code: 'schema' }],
545
+ known = knownOf(json);
283
546
  if (known.refused) {
284
547
  // a frame the generator refuses is a broken edit; one whose size reads an item's values is left to cad check
285
- if (/^frame: /.test(known.refused.message)) throw new CadError('frame.refused', `not changed: ${known.refused.message}`, { file, path: 'frame' });
286
- out.push({ level: 'info', text: `the frame is not expanded here (${known.refused.message}): cad check ${ref} expands it`, code: 'edit.unread' });
548
+ if (/^frame: /.test(known.refused.message))
549
+ throw new CadError('frame.refused', `not changed: ${known.refused.message}`, { file, path: 'frame' });
550
+ out.push({
551
+ level: 'info',
552
+ text: `the frame is not expanded here (${known.refused.message}): cad check ${ref} expands it`,
553
+ code: 'edit.unread',
554
+ });
287
555
  } else if (known.frame) {
288
556
  const [what, size] = frameText(known.frame);
289
- out.push({ level: 'pass', text: `the frame expands: ${what}; ${size}`, code: 'frame.generated', values: { inside: known.frame.inside, outside: known.frame.outside, beams: known.frame.beams.length, joins: known.frame.joins.length } });
557
+ out.push({
558
+ level: 'pass',
559
+ text: `the frame expands: ${what}; ${size}`,
560
+ code: 'frame.generated',
561
+ values: {
562
+ inside: known.frame.inside,
563
+ outside: known.frame.outside,
564
+ envelope: known.frame.envelope?.size ?? null,
565
+ beams: known.frame.beams.length,
566
+ joins: known.frame.joins.length,
567
+ },
568
+ });
290
569
  }
291
570
  const kinds = Object.fromEntries(Object.entries(LIST_OF).map(([k, v]) => [v, k]));
292
- for (const [list, i] of touched) if (kinds[list] && json[list]?.[i]) entryProblems(kinds[list], json[list][i], { ref, file, known, self: idOf(list, json[list][i], i) });
571
+ for (const [list, i] of touched)
572
+ if (kinds[list] && json[list]?.[i])
573
+ entryProblems(kinds[list], json[list][i], { ref, file, known, self: idOf(list, json[list][i], i) });
293
574
  // and every other entry: a name it gave that was there before the edit must still be there (a beam renamed or
294
575
  // removed, a frame changed or taken out, a guide renumbered). What was already missing is left to cad check
295
576
  if (!known.refused) {
296
577
  let was = [];
297
- if (before) { try { const b = JSON.parse(before), bk = knownOf(b); if (!bk.refused) was = namesProblems(b, bk, { ref, file }); } catch {} }
298
- const old = new Set(was.map((p) => p.key)), fresh = namesProblems(json, known, { ref, file }).filter((p) => !old.has(p.key));
299
- if (fresh.length) throw Object.assign(new CadError('edit.dangling', `not changed: the edit leaves ${fresh.map((p) => `${p.at} (${p.message.replace(/ \(.*$/s, '')})`).join(', ')} naming what is no longer there: change or remove ${fresh.length === 1 ? 'it' : 'them'} first`, { file, path: fresh[0].at }), { refs: fresh.map((p) => p.at) });
578
+ if (before) {
579
+ try {
580
+ const b = JSON.parse(before),
581
+ bk = knownOf(b);
582
+ if (!bk.refused) was = namesProblems(b, bk, { ref, file });
583
+ } catch {
584
+ // (what was there before doesn't read: every problem found now counts as new)
585
+ }
586
+ }
587
+ const old = new Set(was.map((p) => p.key)),
588
+ fresh = namesProblems(json, known, { ref, file }).filter((p) => !old.has(p.key));
589
+ if (fresh.length)
590
+ throw Object.assign(
591
+ new CadError(
592
+ 'edit.dangling',
593
+ `not changed: the edit leaves ${fresh.map((p) => `${p.at} (${p.message.replace(/ \(.*$/s, '')})`).join(', ')} naming what is no longer there: change or remove ${fresh.length === 1 ? 'it' : 'them'} first`,
594
+ { file, path: fresh[0].at },
595
+ ),
596
+ { refs: fresh.map((p) => p.at) },
597
+ );
300
598
  }
301
- if (touched.length) out.push({ level: 'pass', text: `the names in ${touched.map(([l, i]) => `${l}.${i}`).join(', ')} are all in ${ref}`, code: 'edit.refs' });
599
+ if (touched.length)
600
+ out.push({
601
+ level: 'pass',
602
+ text: `the names in ${touched.map(([l, i]) => `${l}.${i}`).join(', ')} are all in ${ref}`,
603
+ code: 'edit.refs',
604
+ });
302
605
  return out;
303
606
  }
304
607
 
305
608
  // Write the edit, or not: the one end of every edit here
306
609
  function finish({ ref, file, before, text, kind, changes, dryRun, touched, findings: extra = [] }) {
307
610
  let json;
308
- try { json = JSON.parse(text); } catch (e) { throw new CadError('edit.broken', `the edit would break ${file}'s JSON: ${e.message}`, { file }); }
309
- const findings = kind === 'assembly' ? assemblyFindings(json, { ref, file, before, touched: touched ?? changes.map((c) => entryAt(c.path)).filter(Boolean) }) : [];
611
+ try {
612
+ json = JSON.parse(text);
613
+ } catch (e) {
614
+ throw new CadError('edit.broken', `the edit would break ${file}'s JSON: ${e.message}`, { file });
615
+ }
616
+ const findings =
617
+ kind === 'assembly'
618
+ ? assemblyFindings(json, {
619
+ ref,
620
+ file,
621
+ before,
622
+ touched: touched ?? changes.map((c) => entryAt(c.path)).filter(Boolean),
623
+ })
624
+ : [];
310
625
  if (kind !== 'assembly') {
311
626
  const problems = validate(json, schema(kind));
312
- if (problems.length) throw new CadError('schema', `not changed: ${path.basename(file)}: ${problems[0].path}: ${problems[0].message}`, { file, path: problems[0].path });
627
+ if (problems.length)
628
+ throw new CadError('schema', `not changed: ${path.basename(file)}: ${problems[0].path}: ${problems[0].message}`, {
629
+ file,
630
+ path: problems[0].path,
631
+ });
313
632
  findings.push({ level: 'pass', text: `matches the ${kind} schema`, code: 'schema' });
314
633
  }
315
634
  findings.push(...extra);
316
635
  const written = !dryRun && text !== before;
317
- if (written) { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, text); }
636
+ if (written) {
637
+ fs.mkdirSync(path.dirname(file), { recursive: true });
638
+ fs.writeFileSync(file, text);
639
+ }
318
640
  return { file, written, ...(dryRun ? { dryRun: true } : {}), changes, findings };
319
641
  }
320
642
  // The list entry a path is in: 'joins.3.kind' → ['joins', 3]
321
- const entryAt = (p) => { const m = /^([a-z]+)\.(\d+)/.exec(String(p)); return m && LISTS.includes(m[1]) ? [m[1], Number(m[2])] : null; };
643
+ const entryAt = (p) => {
644
+ const m = /^([a-z]+)\.(\d+)/.exec(String(p));
645
+ return m && LISTS.includes(m[1]) ? [m[1], Number(m[2])] : null;
646
+ };
322
647
 
323
648
  /**
324
649
  * A value as cad set takes it: JSON where it is JSON (a number, true, null, [300, 300, 350], {"kind": "bracket"}), a
@@ -327,53 +652,109 @@ const entryAt = (p) => { const m = /^([a-z]+)\.(\d+)/.exec(String(p)); return m
327
652
  */
328
653
  export function parseSetting(s) {
329
654
  const t = String(s).trim();
330
- if (/^[[{"]|^(true|false|null)$/.test(t)) { try { return JSON.parse(t); } catch {} }
331
- if (/^\[.*\]$/s.test(t)) return t.slice(1, -1).split(',').map((x) => x.trim()).filter((x) => x !== '').map(parseSetting);
332
- if (/^[{"]/.test(t)) throw new CadError('edit.value', `${t} starts like JSON and isn't: write it as JSON (in single quotes in the shell), or as plain text`);
655
+ if (/^[[{"]|^(true|false|null)$/.test(t)) {
656
+ try {
657
+ return JSON.parse(t);
658
+ } catch {
659
+ // (not JSON after all: kept as the text it is)
660
+ }
661
+ }
662
+ if (/^\[.*\]$/s.test(t))
663
+ return t
664
+ .slice(1, -1)
665
+ .split(',')
666
+ .map((x) => x.trim())
667
+ .filter((x) => x !== '')
668
+ .map(parseSetting);
669
+ if (/^[{"]/.test(t))
670
+ throw new CadError(
671
+ 'edit.value',
672
+ `${t} starts like JSON and isn't: write it as JSON (in single quotes in the shell), or as plain text`,
673
+ );
333
674
  return parseValue(t);
334
675
  }
335
676
 
336
677
  // An address's parts: x1.at.0 is ["x1", "at", 0]; a key with a dot in it goes in brackets and quotes, as
337
678
  // frame.supports["z1.a"], and joins[3] is joins.3
338
- export const segmentsOf = (a) => [...String(a).matchAll(/\["((?:[^"\\]|\\.)*)"\]|\[(\d+)\]|([^.[\]]+)/g)].map((m) => (m[1] != null ? m[1] : m[2] != null ? Number(m[2]) : /^\d+$/.test(m[3]) ? Number(m[3]) : m[3]));
679
+ export const segmentsOf = (a) =>
680
+ [...String(a).matchAll(/\["((?:[^"\\]|\\.)*)"\]|\[(\d+)\]|([^.[\]]+)/g)].map((m) =>
681
+ m[1] != null ? m[1] : m[2] != null ? Number(m[2]) : /^\d+$/.test(m[3]) ? Number(m[3]) : m[3],
682
+ );
339
683
 
340
684
  // An address in an assembly, as a path into its JSON: x1.at (an entry by its id), joins.3.kind or joins[3].kind (by its
341
685
  // place), frame.join (a top-level field). Refused by name: an id nothing has, one two lists share, a generated frame's.
342
686
  function addressPath(json, address, { ref, file, entry = false }) {
343
687
  const segs = segmentsOf(address);
344
- if (!segs.length) throw new CadError('edit.address', 'give what to change, as <id>.<field>, <list>.<n>.<field> or a top-level field', { file });
688
+ if (!segs.length)
689
+ throw new CadError(
690
+ 'edit.address',
691
+ 'give what to change, as <id>.<field>, <list>.<n>.<field> or a top-level field',
692
+ { file },
693
+ );
345
694
  const rest = (from) => segs.slice(from);
346
695
  const [first] = segs;
347
696
  if (LISTS.includes(first) && typeof segs[1] === 'number') {
348
- const n = segs[1], len = (json[first] || []).length;
349
- if (n >= len) throw new CadError('edit.address', `${ref} has ${len ? `${len} ${first} (${first}.0 to ${first}.${len - 1})` : `no ${first}`}: there is no ${first}.${n}`, { file });
697
+ const n = segs[1],
698
+ len = (json[first] || []).length;
699
+ if (n >= len)
700
+ throw new CadError(
701
+ 'edit.address',
702
+ `${ref} has ${len ? `${len} ${first} (${first}.0 to ${first}.${len - 1})` : `no ${first}`}: there is no ${first}.${n}`,
703
+ { file },
704
+ );
350
705
  return { path: [first, n, ...rest(2)], entry: [first, n] };
351
706
  }
352
- const hits = ID_LISTS.flatMap((l) => (json[l] || []).map((x, i) => (idOf(l, x, i) === first ? [l, i] : null)).filter(Boolean));
353
- if (hits.length > 1) throw new CadError('edit.ambiguous', `"${first}" names ${hits.map(([l, i]) => `${l}.${i}`).join(' and ')}: say which, as ${hits.map(([l, i]) => `${l}.${i}`).join(' or ')}`, { file });
707
+ const hits = ID_LISTS.flatMap((l) =>
708
+ (json[l] || []).map((x, i) => (idOf(l, x, i) === first ? [l, i] : null)).filter(Boolean),
709
+ );
710
+ if (hits.length > 1)
711
+ throw new CadError(
712
+ 'edit.ambiguous',
713
+ `"${first}" names ${hits.map(([l, i]) => `${l}.${i}`).join(' and ')}: say which, as ${hits.map(([l, i]) => `${l}.${i}`).join(' or ')}`,
714
+ { file },
715
+ );
354
716
  if (hits.length) return { path: [...hits[0], ...rest(1)], entry: hits[0] };
355
717
  const known = knownOf(json);
356
- if (known.generated.includes(first)) throw new CadError('edit.generated', `${first} is made by ${ref}'s generated frame (a ${json.frame.kind}), so it is not in the file to change: change the frame's own fields (frame.profile, frame.inside, frame.join ..), or write the frame out with cad frame ${ref} --expand and change ${first} there`, { file, path: first });
718
+ if (known.generated.includes(first))
719
+ throw new CadError(
720
+ 'edit.generated',
721
+ `${first} is made by ${ref}'s generated frame (a ${json.frame.kind}), so it is not in the file to change: change the frame's own fields (frame.profile, frame.inside, frame.join ..), or write the frame out with cad frame ${ref} --expand and change ${first} there`,
722
+ { file, path: first },
723
+ );
357
724
  const top = Object.keys(schema('assembly').properties);
358
725
  if (!entry && top.includes(first)) return { path: rest(0), entry: null };
359
726
  const ids = ID_LISTS.flatMap((l) => (json[l] || []).map((x, i) => idOf(l, x, i))).filter(Boolean);
360
- throw new CadError('edit.address', `${ref} has nothing called "${first}" (ids: ${ids.join(', ') || 'none'}; or a list entry by its place, as joins.0${entry ? '' : `; or a top-level field: ${top.filter((k) => k !== '$schema').join(', ')}`})`, { file, path: first });
727
+ throw new CadError(
728
+ 'edit.address',
729
+ `${ref} has nothing called "${first}" (ids: ${ids.join(', ') || 'none'}; or a list entry by its place, as joins.0${entry ? '' : `; or a top-level field: ${top.filter((k) => k !== '$schema').join(', ')}`})`,
730
+ { file, path: first },
731
+ );
361
732
  }
362
733
 
363
734
  // Set at a path, making the objects it passes through where they are missing; a string where an object is asked for
364
735
  // stands for its kind ("join": "blind" is { "kind": "blind" }), so frame.join.fitting=printed keeps the blind
365
736
  function setDeep(text, p, value) {
366
737
  for (let k = 1; k < p.length; k++) {
367
- const up = p.slice(0, k), v = getAt(text, up);
738
+ const up = p.slice(0, k),
739
+ v = getAt(text, up);
368
740
  if (v === undefined) {
369
- if (typeof p[k] === 'number') throw new CadError('edit.address', `there is no ${up.join('.')} list to set entry ${p[k]} of`);
741
+ if (typeof p[k] === 'number')
742
+ throw new CadError('edit.address', `there is no ${up.join('.')} list to set entry ${p[k]} of`);
370
743
  text = setAt(text, up, {});
371
744
  } else if (typeof v === 'string' && typeof p[k] === 'string') text = setAt(text, up, { kind: v });
372
- else if (Array.isArray(v) && typeof p[k] === 'number' && p[k] > v.length - 1) throw new CadError('edit.address', `${up.join('.')} has ${v.length} entries (0 to ${v.length - 1}): there is no ${up.join('.')}.${p[k]}`);
745
+ else if (Array.isArray(v) && typeof p[k] === 'number' && p[k] > v.length - 1)
746
+ throw new CadError(
747
+ 'edit.address',
748
+ `${up.join('.')} has ${v.length} entries (0 to ${v.length - 1}): there is no ${up.join('.')}.${p[k]}`,
749
+ );
373
750
  }
374
751
  return setAt(text, p, value);
375
752
  }
376
- const shownPath = (p) => p.map((k) => (typeof k === 'string' && /[.[\]"]/.test(k) ? `[${JSON.stringify(k)}]` : `.${k}`)).join('').replace(/^\./, '');
753
+ const shownPath = (p) =>
754
+ p
755
+ .map((k) => (typeof k === 'string' && /[.[\]"]/.test(k) ? `[${JSON.stringify(k)}]` : `.${k}`))
756
+ .join('')
757
+ .replace(/^\./, '');
377
758
 
378
759
  /**
379
760
  * Change fields of an assembly: { address: value }, each address an entry's field by its id (x1.at, hinge.max) or its
@@ -381,14 +762,28 @@ const shownPath = (p) => p.map((k) => (typeof k === 'string' && /[.[\]"]/.test(k
381
762
  * @param {string} ref project/assembly @param {Record<string, any>} changes @param {{ dryRun?: boolean }} [options]
382
763
  */
383
764
  export function setInAssembly(ref, changes, { dryRun = false } = {}) {
384
- const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8');
765
+ const file = assemblyFile(ref),
766
+ before = readOwnText(file);
385
767
  let text = before;
386
- const done = [], touched = [];
768
+ const done = [],
769
+ touched = [];
387
770
  for (const [address, value] of Object.entries(changes)) {
388
771
  const { path: p, entry } = addressPath(JSON.parse(text), address, { ref, file });
389
- if (entry && p.length === 2) throw new CadError('edit.address', `${address} is a whole ${entry[0].replace(/s$/, '')}: set one of its fields (${address}.<field>), or cad remove it and cad add another`, { file });
390
- const up = p.length > 1 ? getAt(text, p.slice(0, -1)) : undefined, was = typeof up === 'string' && p.at(-1) === 'kind' ? up : getAt(text, p); // ("join": "blind" is a kind of blind)
391
- try { text = setDeep(text, p, value); } catch (e) { throw e instanceof CadError ? Object.assign(e, { file }) : new CadError('edit.address', `${address}: ${e.message}`, { file }); }
772
+ if (entry && p.length === 2)
773
+ throw new CadError(
774
+ 'edit.address',
775
+ `${address} is a whole ${entry[0].replace(/s$/, '')}: set one of its fields (${address}.<field>), or cad remove it and cad add another`,
776
+ { file },
777
+ );
778
+ const up = p.length > 1 ? getAt(text, p.slice(0, -1)) : undefined,
779
+ was = typeof up === 'string' && p.at(-1) === 'kind' ? up : getAt(text, p); // ("join": "blind" is a kind of blind)
780
+ try {
781
+ text = setDeep(text, p, value);
782
+ } catch (e) {
783
+ throw e instanceof CadError
784
+ ? Object.assign(e, { file })
785
+ : new CadError('edit.address', `${address}: ${e.message}`, { file });
786
+ }
392
787
  done.push({ op: 'set', path: shownPath(p), ...(was !== undefined ? { before: was } : {}), after: value });
393
788
  if (entry) touched.push(entry);
394
789
  }
@@ -397,18 +792,71 @@ export function setInAssembly(ref, changes, { dryRun = false } = {}) {
397
792
 
398
793
  // Every place in an assembly that names an id (as itself, or as id.anchor, id.face@mm, id@pose): [{ path, value }].
399
794
  // Values that never name an entry (kinds, profiles, screws, notes ..) are passed over.
400
- const NOT_NAMES = new Set(['id', 'object', 'assembly', 'profile', 'kind', 'note', 'label', 'title', 'description', 'screw', 'nut', 'material', 'rail', 'carriage', 'model', 'variant', 'type', 'fitting', 'bought', 'sheet', 'thread', 'op', 'colour', 'gauge', 'mode', 'shape', 'rod', 'bearing', 'coupler', 'wheel', 'size', 'pose', 'show', '$schema', 'uses', 'requires', 'packed', 'tool']);
795
+ const NOT_NAMES = new Set([
796
+ 'id',
797
+ 'object',
798
+ 'assembly',
799
+ 'profile',
800
+ 'kind',
801
+ 'note',
802
+ 'label',
803
+ 'title',
804
+ 'description',
805
+ 'screw',
806
+ 'nut',
807
+ 'material',
808
+ 'rail',
809
+ 'carriage',
810
+ 'model',
811
+ 'variant',
812
+ 'type',
813
+ 'fitting',
814
+ 'bought',
815
+ 'sheet',
816
+ 'thread',
817
+ 'op',
818
+ 'colour',
819
+ 'gauge',
820
+ 'mode',
821
+ 'shape',
822
+ 'rod',
823
+ 'bearing',
824
+ 'coupler',
825
+ 'wheel',
826
+ 'size',
827
+ 'pose',
828
+ 'show',
829
+ '$schema',
830
+ 'uses',
831
+ 'requires',
832
+ 'packed',
833
+ 'tool',
834
+ ]);
401
835
  function namesOf(json, id, { prefix = false } = {}) {
402
- const hit = (s) => typeof s === 'string' && (s === id || s.startsWith(`${id}.`) || s.startsWith(`${id}@`) || (prefix && s.startsWith(`${id}-`)));
836
+ const hit = (s) =>
837
+ typeof s === 'string' &&
838
+ (s === id || s.startsWith(`${id}.`) || s.startsWith(`${id}@`) || (prefix && s.startsWith(`${id}-`)));
403
839
  const out = [];
404
840
  const walk = (v, p) => {
405
- if (typeof v === 'string') { if (hit(v)) out.push({ path: p, value: v }); return; }
406
- if (Array.isArray(v)) { v.forEach((x, i) => walk(x, [...p, i])); return; }
407
- if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) {
408
- if (NOT_NAMES.has(k)) continue;
409
- if ((p[0] === 'poses' && p.length === 2) || (p[0] === 'frame' && p[1] === 'supports' && p.length === 2)) { if (hit(k)) { out.push({ path: [...p, k], value: k }); continue; } }
410
- walk(x, [...p, k]);
841
+ if (typeof v === 'string') {
842
+ if (hit(v)) out.push({ path: p, value: v });
843
+ return;
844
+ }
845
+ if (Array.isArray(v)) {
846
+ v.forEach((x, i) => walk(x, [...p, i]));
847
+ return;
411
848
  }
849
+ if (v && typeof v === 'object')
850
+ for (const [k, x] of Object.entries(v)) {
851
+ if (NOT_NAMES.has(k)) continue;
852
+ if ((p[0] === 'poses' && p.length === 2) || (p[0] === 'frame' && p[1] === 'supports' && p.length === 2)) {
853
+ if (hit(k)) {
854
+ out.push({ path: [...p, k], value: k });
855
+ continue;
856
+ }
857
+ }
858
+ walk(x, [...p, k]);
859
+ }
412
860
  };
413
861
  walk(json, []);
414
862
  return out;
@@ -421,30 +869,75 @@ function namesOf(json, id, { prefix = false } = {}) {
421
869
  * @param {string} ref project/assembly @param {string} address @param {{ withRefs?: boolean, dryRun?: boolean }} [options]
422
870
  */
423
871
  export function removeFromAssembly(ref, address, { withRefs = false, dryRun = false } = {}) {
424
- const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), json = JSON.parse(before);
872
+ const file = assemblyFile(ref),
873
+ before = readOwnText(file),
874
+ json = JSON.parse(before);
425
875
  const { path: p, entry } = addressPath(json, address, { ref, file });
426
876
  const was = getAt(before, p);
427
- if (was === undefined) throw new CadError('edit.address', `${ref} has no ${address} to remove`, { file, path: address });
428
- if (p.length === 1 && LISTS.includes(p[0])) throw new CadError('edit.address', `${address} is a whole list: remove its entries by id or place (${p[0]}.0 ..)`, { file });
429
- const changes = [{ op: 'remove', path: shownPath(p), before: was }], drop = [p];
877
+ if (was === undefined)
878
+ throw new CadError('edit.address', `${ref} has no ${address} to remove`, { file, path: address });
879
+ if (p.length === 1 && LISTS.includes(p[0]))
880
+ throw new CadError('edit.address', `${address} is a whole list: remove its entries by id or place (${p[0]}.0 ..)`, {
881
+ file,
882
+ });
883
+ const changes = [{ op: 'remove', path: shownPath(p), before: was }],
884
+ drop = [p];
430
885
  if (entry && p.length === 2) {
431
- const [list, i] = entry, id = idOf(list, json[list][i], i);
886
+ const [list, i] = entry,
887
+ id = idOf(list, json[list][i], i);
432
888
  // a guide with no id is g1, g2 .. by its place, so taking out any guide before one renames it, whether the guide
433
889
  // taken out has an id or not
434
- const renamed = list === 'guides' ? json[list].map((g, k) => (k > i && g?.id == null ? k : -1)).filter((k) => k >= 0) : [];
890
+ const renamed =
891
+ list === 'guides' ? json[list].map((g, k) => (k > i && g?.id == null ? k : -1)).filter((k) => k >= 0) : [];
435
892
  if (renamed.length)
436
- throw new CadError('edit.renumber', `${address} goes before ${renamed.map((k) => `guides.${k}`).join(', ')}, which ${renamed.length === 1 ? 'has' : 'have'} no id of ${renamed.length === 1 ? 'its' : 'their'} own and so ${renamed.length === 1 ? 'is' : 'are'} named by place: ${renamed.map((k) => `g${k + 1} would become g${k}`).join(', ')}. Give ${renamed.length === 1 ? 'it an id' : 'them ids'} first (cad set ${ref} guides.${renamed[0]}.id=g${renamed[0] + 1})`, { file });
437
- const refs = id ? namesOf({ ...json, [list]: json[list].map((x, k) => (k === i ? null : x)) }, id, { prefix: list === 'guides' }) : [];
893
+ throw new CadError(
894
+ 'edit.renumber',
895
+ `${address} goes before ${renamed.map((k) => `guides.${k}`).join(', ')}, which ${renamed.length === 1 ? 'has' : 'have'} no id of ${renamed.length === 1 ? 'its' : 'their'} own and so ${renamed.length === 1 ? 'is' : 'are'} named by place: ${renamed.map((k) => `g${k + 1} would become g${k}`).join(', ')}. Give ${renamed.length === 1 ? 'it an id' : 'them ids'} first (cad set ${ref} guides.${renamed[0]}.id=g${renamed[0] + 1})`,
896
+ { file },
897
+ );
898
+ const refs = id
899
+ ? namesOf({ ...json, [list]: json[list].map((x, k) => (k === i ? null : x)) }, id, { prefix: list === 'guides' })
900
+ : [];
438
901
  if (refs.length) {
439
902
  // each name as what holds it: a list entry, or a pose's or a support's key
440
- const holders = [...new Map(refs.map((r) => { const e = entryAt(shownPath(r.path)); const h = e ? e : r.path[0] === 'poses' || r.path[0] === 'frame' ? r.path.slice(0, 3) : r.path; return [shownPath(h), h]; })).values()];
441
- const said = holders.map((h) => { const x = getAt(before, h); return `${shownPath(h)}${x && typeof x === 'object' && !Array.isArray(x) && (x.kind || x.a) ? ` (${[x.kind, x.a && `${x.a} to ${x.b}`].filter(Boolean).join(' ')})` : ''}`; });
442
- if (!withRefs) throw Object.assign(new CadError('edit.referenced', `${id} is named by ${said.join(', ')}: remove ${holders.length === 1 ? 'it' : 'them'} first, or add --with-refs to remove ${holders.length === 1 ? 'it' : 'them'} with ${id}`, { file, path: shownPath(p) }), { refs: said });
443
- for (const h of holders) { drop.push(h); changes.push({ op: 'remove', path: shownPath(h), before: getAt(before, h), because: `names ${id}` }); }
903
+ const holders = [
904
+ ...new Map(
905
+ refs.map((r) => {
906
+ const e = entryAt(shownPath(r.path));
907
+ const h = e ? e : r.path[0] === 'poses' || r.path[0] === 'frame' ? r.path.slice(0, 3) : r.path;
908
+ return [shownPath(h), h];
909
+ }),
910
+ ).values(),
911
+ ];
912
+ const said = holders.map((h) => {
913
+ const x = getAt(before, h);
914
+ return `${shownPath(h)}${x && typeof x === 'object' && !Array.isArray(x) && (x.kind || x.a) ? ` (${[x.kind, x.a && `${x.a} to ${x.b}`].filter(Boolean).join(' ')})` : ''}`;
915
+ });
916
+ if (!withRefs)
917
+ throw Object.assign(
918
+ new CadError(
919
+ 'edit.referenced',
920
+ `${id} is named by ${said.join(', ')}: remove ${holders.length === 1 ? 'it' : 'them'} first, or add --with-refs to remove ${holders.length === 1 ? 'it' : 'them'} with ${id}`,
921
+ { file, path: shownPath(p) },
922
+ ),
923
+ { refs: said },
924
+ );
925
+ for (const h of holders) {
926
+ drop.push(h);
927
+ changes.push({ op: 'remove', path: shownPath(h), before: getAt(before, h), because: `names ${id}` });
928
+ }
444
929
  }
445
930
  }
446
931
  // the last first, so the places of the others hold
447
- const order = (a, b) => { for (let k = 0; k < Math.min(a.length, b.length); k++) { if (a[k] === b[k]) continue; return typeof a[k] === 'number' && typeof b[k] === 'number' ? b[k] - a[k] : String(a[k]).localeCompare(String(b[k])); } return b.length - a.length; };
932
+ const order = (a, b) => {
933
+ for (let k = 0; k < Math.min(a.length, b.length); k++) {
934
+ if (a[k] === b[k]) continue;
935
+ return typeof a[k] === 'number' && typeof b[k] === 'number'
936
+ ? b[k] - a[k]
937
+ : String(a[k]).localeCompare(String(b[k]));
938
+ }
939
+ return b.length - a.length;
940
+ };
448
941
  let text = before;
449
942
  for (const d of [...new Map(drop.map((x) => [shownPath(x), x])).values()].sort(order)) text = removeAt(text, d);
450
943
  return finish({ ref, file, before, text, kind: 'assembly', changes, dryRun, touched: [] });
@@ -456,31 +949,85 @@ export function removeFromAssembly(ref, address, { withRefs = false, dryRun = fa
456
949
  * @param {string} ref project/assembly @param {string} id @param {{ at?: any, to?: string, rotate?: any[], dryRun?: boolean }} move
457
950
  */
458
951
  export function moveInAssembly(ref, id, { at, to, rotate, dryRun = false } = {}) {
459
- const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), json = JSON.parse(before);
460
- if (at == null && to == null && rotate == null) throw new CadError('edit.incomplete', 'say where it goes: --at x,y,z (a point), --to x1.top@50% (an address on a beam), and or --rotate 0,0,90', { file });
952
+ const file = assemblyFile(ref),
953
+ before = readOwnText(file),
954
+ json = JSON.parse(before);
955
+ if (at == null && to == null && rotate == null)
956
+ throw new CadError(
957
+ 'edit.incomplete',
958
+ 'say where it goes: --at x,y,z (a point), --to x1.top@50% (an address on a beam), and or --rotate 0,0,90',
959
+ { file },
960
+ );
461
961
  const { entry } = addressPath(json, id, { ref, file, entry: true });
462
- if (!entry || !['items', 'guides'].includes(entry[0])) throw new CadError('edit.move', `${id} is ${entry ? `a ${entry[0].replace(/s$/, '')}` : 'not an entry'}: cad move moves items and guides (change others with cad set)`, { file });
463
- const [list, i] = entry, x = json[list][i], base = [list, i], sets = [];
962
+ if (!entry || !['items', 'guides'].includes(entry[0]))
963
+ throw new CadError(
964
+ 'edit.move',
965
+ `${id} is ${entry ? `a ${entry[0].replace(/s$/, '')}` : 'not an entry'}: cad move moves items and guides (change others with cad set)`,
966
+ { file },
967
+ );
968
+ const [list, i] = entry,
969
+ x = json[list][i],
970
+ base = [list, i],
971
+ sets = [];
464
972
  if (list === 'guides') {
465
- if (rotate != null) throw new CadError('edit.move', `${id} is a guide: it lies along its beam's face, so it turns only with the beam`, { file });
466
- if (to != null) { if (!/^[a-z][\w-]*\.[\w.-]+$/i.test(String(to)) || String(to).includes('@')) throw new CadError('edit.move', `a guide goes on a beam's face, as x3.top; how far along it is --at <mm> (got ${to})`, { file }); sets.push([['on'], String(to)]); }
467
- if (at != null) { if (Array.isArray(at) || typeof at === 'string' && Number.isNaN(Number(at))) throw new CadError('edit.move', `a guide moves along its face by --at <mm> from the beam's end a (got ${at})`, { file }); sets.push([['from'], Number(at)]); }
973
+ if (rotate != null)
974
+ throw new CadError(
975
+ 'edit.move',
976
+ `${id} is a guide: it lies along its beam's face, so it turns only with the beam`,
977
+ { file },
978
+ );
979
+ if (to != null) {
980
+ if (!/^[a-z][\w-]*\.[\w.-]+$/i.test(String(to)) || String(to).includes('@'))
981
+ throw new CadError(
982
+ 'edit.move',
983
+ `a guide goes on a beam's face, as x3.top; how far along it is --at <mm> (got ${to})`,
984
+ { file },
985
+ );
986
+ sets.push([['on'], String(to)]);
987
+ }
988
+ if (at != null) {
989
+ if (Array.isArray(at) || (typeof at === 'string' && Number.isNaN(Number(at))))
990
+ throw new CadError('edit.move', `a guide moves along its face by --at <mm> from the beam's end a (got ${at})`, {
991
+ file,
992
+ });
993
+ sets.push([['from'], Number(at)]);
994
+ }
468
995
  } else {
469
996
  const ends = Array.isArray(x.from) && Array.isArray(x.to);
470
- if (ends && (to != null || rotate != null)) throw new CadError('edit.move', `${id} is a beam placed by its two ends: move it with --at x,y,z (where its end a goes; end b keeps its offset), and turn it with cad set ${ref} ${id}.from=… ${id}.to=… or ${id}.roll=90`, { file });
997
+ if (ends && (to != null || rotate != null))
998
+ throw new CadError(
999
+ 'edit.move',
1000
+ `${id} is a beam placed by its two ends: move it with --at x,y,z (where its end a goes; end b keeps its offset), and turn it with cad set ${ref} ${id}.from=… ${id}.to=… or ${id}.roll=90`,
1001
+ { file },
1002
+ );
471
1003
  if (at != null && ends) {
472
- if (!Array.isArray(at) || at.length !== 3 || [...at, ...x.from, ...x.to].some((v) => typeof v !== 'number')) throw new CadError('edit.move', `${id} is placed by its ends${[...x.from, ...x.to].some((v) => typeof v !== 'number') ? ' as expressions' : ''}: give --at as x,y,z in mm${[...x.from, ...x.to].some((v) => typeof v !== 'number') ? `, or set ${id}.from and ${id}.to` : ''}`, { file });
1004
+ if (!Array.isArray(at) || at.length !== 3 || [...at, ...x.from, ...x.to].some((v) => typeof v !== 'number'))
1005
+ throw new CadError(
1006
+ 'edit.move',
1007
+ `${id} is placed by its ends${[...x.from, ...x.to].some((v) => typeof v !== 'number') ? ' as expressions' : ''}: give --at as x,y,z in mm${[...x.from, ...x.to].some((v) => typeof v !== 'number') ? `, or set ${id}.from and ${id}.to` : ''}`,
1008
+ { file },
1009
+ );
473
1010
  const d = at.map((v, k) => v - x.from[k]);
474
1011
  sets.push([['from'], at], [['to'], x.to.map((v, k) => +(v + d[k]).toFixed(6))]);
475
1012
  } else if (at != null) {
476
- if (!(Array.isArray(at) && at.length === 3) && typeof at !== 'string') throw new CadError('edit.move', `--at is a point, x,y,z in mm (got ${JSON.stringify(at)}); an address on a beam is --to`, { file });
1013
+ if (!(Array.isArray(at) && at.length === 3) && typeof at !== 'string')
1014
+ throw new CadError(
1015
+ 'edit.move',
1016
+ `--at is a point, x,y,z in mm (got ${JSON.stringify(at)}); an address on a beam is --to`,
1017
+ { file },
1018
+ );
477
1019
  sets.push([['at'], at]);
478
1020
  }
479
1021
  if (to != null) sets.push([['at'], String(to)]);
480
1022
  if (rotate != null) sets.push([['rotate'], rotate]);
481
1023
  }
482
1024
  let text = before;
483
- const changes = sets.map(([k, v]) => { const p = [...base, ...k], was = getAt(text, p); text = setAt(text, p, v); return { op: 'set', path: shownPath(p), ...(was !== undefined ? { before: was } : {}), after: v }; });
1025
+ const changes = sets.map(([k, v]) => {
1026
+ const p = [...base, ...k],
1027
+ was = getAt(text, p);
1028
+ text = setAt(text, p, v);
1029
+ return { op: 'set', path: shownPath(p), ...(was !== undefined ? { before: was } : {}), after: v };
1030
+ });
484
1031
  return finish({ ref, file, before, text, kind: 'assembly', changes, dryRun, touched: [entry] });
485
1032
  }
486
1033
 
@@ -494,13 +1041,31 @@ const projectFile = (project) => path.join(paths.project(project), 'project.json
494
1041
  function projectFindings(json, project) {
495
1042
  const out = [];
496
1043
  if (json.printer != null) {
497
- let set = null; try { set = peekRuleSet(json.printer); } catch {}
498
- if (!set) throw new CadError('project.printer', `project ${project}: there is no printer rule set "${json.printer}" (rules/${json.printer}.json, or the kit's, as x1c)`, { path: 'printer' });
1044
+ let set = null;
1045
+ try {
1046
+ set = peekRuleSet(json.printer);
1047
+ } catch {
1048
+ // (no such printer rule set: refused just below)
1049
+ }
1050
+ if (!set)
1051
+ throw new CadError(
1052
+ 'project.printer',
1053
+ `project ${project}: there is no printer rule set "${json.printer}" (rules/${json.printer}.json, or the kit's, as x1c)`,
1054
+ { path: 'printer' },
1055
+ );
499
1056
  out.push({ level: 'pass', text: `prints are checked against ${json.printer}`, code: 'project.printer' });
500
1057
  }
501
1058
  if (json.material != null) {
502
- try { const m = plasticNamed(json.material, `project ${project}`); out.push({ level: 'pass', text: `printed fittings are sized from ${typeof m === 'string' ? m.toUpperCase() : json.material}`, code: 'project.material' }); }
503
- catch (e) { throw new CadError('project.material', e.message, { path: 'material' }); }
1059
+ try {
1060
+ const m = plasticNamed(json.material, `project ${project}`);
1061
+ out.push({
1062
+ level: 'pass',
1063
+ text: `printed fittings are sized from ${typeof m === 'string' ? m.toUpperCase() : json.material}`,
1064
+ code: 'project.material',
1065
+ });
1066
+ } catch (e) {
1067
+ throw new CadError('project.material', e.message, { path: 'material' });
1068
+ }
504
1069
  }
505
1070
  return out;
506
1071
  }
@@ -513,27 +1078,66 @@ function projectFindings(json, project) {
513
1078
  * @param {string} name @param {{ title?: string, description?: string, material?: string, printer?: string, dryRun?: boolean }} [fields]
514
1079
  */
515
1080
  export function newProject(name, { dryRun = false, ...fields } = {}) {
516
- if (!NAME.test(String(name || ''))) throw new CadError('edit.name', `a project's name is lower case, with dashes (got ${JSON.stringify(name)})`);
1081
+ if (!NAME.test(String(name || '')))
1082
+ throw new CadError('edit.name', `a project's name is lower case, with dashes (got ${JSON.stringify(name)})`);
517
1083
  const file = projectFile(name);
518
1084
  const given = Object.fromEntries(Object.entries(fields).filter(([, v]) => v != null));
519
1085
  if (fs.existsSync(file)) {
520
- if (!Object.keys(given).length) throw new CadError('project.exists', `projects/${name}/project.json is already there: change its fields with cad set ${name} material=PETG ..`, { file });
521
- return { file, written: false, ...(dryRun ? { dryRun: true } : {}), changes: [], findings: [sameProject(name, given)] };
1086
+ if (!Object.keys(given).length)
1087
+ throw new CadError(
1088
+ 'project.exists',
1089
+ `projects/${name}/project.json is already there: change its fields with cad set ${name} material=PETG ..`,
1090
+ { file },
1091
+ );
1092
+ return {
1093
+ file,
1094
+ written: false,
1095
+ ...(dryRun ? { dryRun: true } : {}),
1096
+ changes: [],
1097
+ findings: [sameProject(name, given)],
1098
+ };
522
1099
  }
523
- const json = { $schema: 'https://jonibach.github.io/rulecad/schemas/project.schema.json', name, ...given, material: given.material ?? 'PLA', objects: [] };
1100
+ const json = {
1101
+ $schema: 'https://jonibach.github.io/rulecad/schemas/project.schema.json',
1102
+ name,
1103
+ ...given,
1104
+ material: given.material ?? 'PLA',
1105
+ objects: [],
1106
+ };
524
1107
  const text = laidOut(json);
525
- return finish({ file, before: '', text, kind: 'project', changes: [{ op: 'make', path: `projects/${name}/project.json`, after: json }], dryRun, findings: projectFindings(json, name) });
1108
+ return finish({
1109
+ file,
1110
+ before: '',
1111
+ text,
1112
+ kind: 'project',
1113
+ changes: [{ op: 'make', path: `projects/${name}/project.json`, after: json }],
1114
+ dryRun,
1115
+ findings: projectFindings(json, name),
1116
+ });
526
1117
  }
527
1118
 
528
1119
  // A project that is there, held to the fields given for it (a material by its name in any case, PLA where it gives
529
1120
  // none): a pass finding where each is already its own, refused by name where one differs, naming the cad set that
530
1121
  // changes it
531
1122
  function sameProject(name, given) {
532
- const file = projectFile(name), own = JSON.parse(fs.readFileSync(file, 'utf8'));
533
- const ownOf = (k) => (k === 'material' ? own.material ?? 'PLA' : own[k]), same = (k, v) => (k === 'material' ? String(ownOf(k)).toLowerCase() === String(v).toLowerCase() : ownOf(k) === v);
534
- const differ = Object.entries(given).filter(([k, v]) => !same(k, v)), was = (k) => (ownOf(k) === undefined ? `no ${k}` : `${k} ${ownOf(k)}`);
535
- if (differ.length) throw new CadError('project.exists', `projects/${name}/project.json is already there with ${differ.map(([k]) => was(k)).join(' and ')}, so ${differ.map(([k, v]) => `--${k} ${v}`).join(' and ')} would change it: change ${differ.length === 1 ? 'it' : 'them'} with cad set ${name} ${differ.map(([k, v]) => `${k}=${/\s/.test(v) ? JSON.stringify(v) : v}`).join(' ')}`, { file });
536
- return { level: 'pass', text: `projects/${name}/project.json is already there with ${Object.keys(given).map(was).join(' and ')}: nothing to change`, code: 'project.exists', values: Object.fromEntries(Object.keys(given).map((k) => [k, ownOf(k)])) };
1123
+ const file = projectFile(name),
1124
+ own = JSON.parse(readOwnText(file));
1125
+ const ownOf = (k) => (k === 'material' ? (own.material ?? 'PLA') : own[k]),
1126
+ same = (k, v) => (k === 'material' ? String(ownOf(k)).toLowerCase() === String(v).toLowerCase() : ownOf(k) === v);
1127
+ const differ = Object.entries(given).filter(([k, v]) => !same(k, v)),
1128
+ was = (k) => (ownOf(k) === undefined ? `no ${k}` : `${k} ${ownOf(k)}`);
1129
+ if (differ.length)
1130
+ throw new CadError(
1131
+ 'project.exists',
1132
+ `projects/${name}/project.json is already there with ${differ.map(([k]) => was(k)).join(' and ')}, so ${differ.map(([k, v]) => `--${k} ${v}`).join(' and ')} would change it: change ${differ.length === 1 ? 'it' : 'them'} with cad set ${name} ${differ.map(([k, v]) => `${k}=${/\s/.test(v) ? JSON.stringify(v) : v}`).join(' ')}`,
1133
+ { file },
1134
+ );
1135
+ return {
1136
+ level: 'pass',
1137
+ text: `projects/${name}/project.json is already there with ${Object.keys(given).map(was).join(' and ')}: nothing to change`,
1138
+ code: 'project.exists',
1139
+ values: Object.fromEntries(Object.keys(given).map((k) => [k, ownOf(k)])),
1140
+ };
537
1141
  }
538
1142
 
539
1143
  /**
@@ -542,20 +1146,56 @@ function sameProject(name, given) {
542
1146
  */
543
1147
  export function setProject(project, changes, { dryRun = false } = {}) {
544
1148
  const file = projectFile(project);
545
- if (!fs.existsSync(file)) throw new CadError('project.missing', `there is no project ${project} (projects/${project}/project.json): make it with cad new ${project}`, { file });
546
- const before = fs.readFileSync(file, 'utf8');
1149
+ if (!fs.existsSync(file))
1150
+ throw new CadError(
1151
+ 'project.missing',
1152
+ `there is no project ${project} (projects/${project}/project.json): make it with cad new ${project}`,
1153
+ { file },
1154
+ );
1155
+ const before = readOwnText(file);
547
1156
  let text = before;
548
- const done = [], fields = Object.keys(schema('project').properties).filter((k) => !['$schema', 'objects', 'name'].includes(k));
1157
+ const done = [],
1158
+ fields = Object.keys(schema('project').properties).filter(
1159
+ (k) => !['$schema', 'objects', 'name', 'version', 'release'].includes(k),
1160
+ );
549
1161
  for (const [address, value] of Object.entries(changes)) {
550
1162
  const p = segmentsOf(address);
551
- if (p[0] === 'objects') throw new CadError('edit.address', 'a project\'s objects are listed by cad new <project>/<object>, as each is made', { file });
552
- if (p[0] === 'name') throw new CadError('edit.address', `a project's name is its folder's: to rename ${project}, rename projects/${project} and its name together`, { file });
553
- if (!fields.includes(p[0])) throw new CadError('edit.address', `a project has no field "${p[0]}" (fields: ${fields.join(', ')})`, { file, path: p[0] });
1163
+ if (p[0] === 'objects')
1164
+ throw new CadError(
1165
+ 'edit.address',
1166
+ "a project's objects are listed by cad new <project>/<object>, as each is made",
1167
+ { file },
1168
+ );
1169
+ if (p[0] === 'version' || p[0] === 'release')
1170
+ throw new CadError(
1171
+ 'edit.address',
1172
+ `a project's ${p[0]} is written by cad release ${project}, as each release is made`,
1173
+ { file },
1174
+ );
1175
+ if (p[0] === 'name')
1176
+ throw new CadError(
1177
+ 'edit.address',
1178
+ `a project's name is its folder's: to rename ${project}, rename projects/${project} and its name together`,
1179
+ { file },
1180
+ );
1181
+ if (!fields.includes(p[0]))
1182
+ throw new CadError('edit.address', `a project has no field "${p[0]}" (fields: ${fields.join(', ')})`, {
1183
+ file,
1184
+ path: p[0],
1185
+ });
554
1186
  const was = getAt(text, p);
555
1187
  text = setDeep(text, p, value);
556
1188
  done.push({ op: 'set', path: shownPath(p), ...(was !== undefined ? { before: was } : {}), after: value });
557
1189
  }
558
- return finish({ file, before, text, kind: 'project', changes: done, dryRun, findings: projectFindings(JSON.parse(text), project) });
1190
+ return finish({
1191
+ file,
1192
+ before,
1193
+ text,
1194
+ kind: 'project',
1195
+ changes: done,
1196
+ dryRun,
1197
+ findings: projectFindings(JSON.parse(text), project),
1198
+ });
559
1199
  }
560
1200
 
561
1201
  /**
@@ -567,30 +1207,70 @@ export function setProject(project, changes, { dryRun = false } = {}) {
567
1207
  */
568
1208
  export function newObject(ref, { dryRun = false } = {}) {
569
1209
  const [project, name] = String(ref || '').split('/');
570
- if (!NAME.test(project || '') || !NAME.test(name || '')) throw new CadError('edit.name', `an object is <project>/<name>, each lower case with dashes (got ${JSON.stringify(ref)})`);
571
- const objects = path.join(paths.project(project), 'objects'), pj = projectFile(project);
1210
+ if (!NAME.test(project || '') || !NAME.test(name || ''))
1211
+ throw new CadError(
1212
+ 'edit.name',
1213
+ `an object is <project>/<name>, each lower case with dashes (got ${JSON.stringify(ref)})`,
1214
+ );
1215
+ const objects = path.join(paths.project(project), 'objects'),
1216
+ pj = projectFile(project);
572
1217
  const files = ['js', 'json'].map((ext) => path.join(objects, `${name}.${ext}`));
573
1218
  const there = files.find((f) => fs.existsSync(f));
574
- if (there) throw new CadError('object.exists', `projects/${project}/objects/${path.basename(there)} is already there: change its variables with cad set ${ref} name=value`, { file: there });
575
- const texts = ['js', 'json'].map((ext) => fs.readFileSync(new URL(`../templates/object.${ext}`, import.meta.url), 'utf8').replaceAll('NAME', name));
1219
+ if (there)
1220
+ throw new CadError(
1221
+ 'object.exists',
1222
+ `projects/${project}/objects/${path.basename(there)} is already there: change its variables with cad set ${ref} name=value`,
1223
+ { file: there },
1224
+ );
1225
+ const texts = ['js', 'json'].map((ext) =>
1226
+ fs.readFileSync(new URL(`../templates/object.${ext}`, import.meta.url), 'utf8').replaceAll('NAME', name),
1227
+ );
576
1228
  const object = JSON.parse(texts[1]);
577
1229
  const problems = validate(object, schema('object'));
578
- if (problems.length) throw new CadError('schema', `not made: ${name}.json: ${problems[0].path}: ${problems[0].message}`, { file: files[1], path: problems[0].path });
1230
+ if (problems.length)
1231
+ throw new CadError('schema', `not made: ${name}.json: ${problems[0].path}: ${problems[0].message}`, {
1232
+ file: files[1],
1233
+ path: problems[0].path,
1234
+ });
579
1235
  // its project: made where there is none, else the object added to its list (keeping the file's layout)
580
1236
  const made = fs.existsSync(pj) ? null : newProject(project, { dryRun: true });
581
- const before = made ? '' : fs.readFileSync(pj, 'utf8');
582
- let text = made ? laidOut(made.changes[0].after) : before, listed = [];
1237
+ const before = made ? '' : readOwnText(pj);
1238
+ let text = made ? laidOut(made.changes[0].after) : before,
1239
+ listed = [];
583
1240
  const own = JSON.parse(text);
584
- if (!Array.isArray(own.objects)) { text = setAt(text, ['objects'], [name]); listed = [{ op: 'add', path: 'objects.0', after: name }]; }
585
- else if (!own.objects.includes(name)) { text = appendAt(text, ['objects'], name); listed = [{ op: 'add', path: `objects.${own.objects.length}`, after: name }]; }
586
- const changes = [...(made ? made.changes : []), ...files.map((f, i) => ({ op: 'make', path: `projects/${project}/objects/${path.basename(f)}`, ...(i === 1 ? { after: object } : {}) })), ...listed];
587
- const findings = [...(made ? made.findings.filter((f) => f.code !== 'schema') : []), { level: 'pass', text: 'matches the object schema', code: 'schema' }];
1241
+ if (!Array.isArray(own.objects)) {
1242
+ text = setAt(text, ['objects'], [name]);
1243
+ listed = [{ op: 'add', path: 'objects.0', after: name }];
1244
+ } else if (!own.objects.includes(name)) {
1245
+ text = appendAt(text, ['objects'], name);
1246
+ listed = [{ op: 'add', path: `objects.${own.objects.length}`, after: name }];
1247
+ }
1248
+ const changes = [
1249
+ ...(made ? made.changes : []),
1250
+ ...files.map((f, i) => ({
1251
+ op: 'make',
1252
+ path: `projects/${project}/objects/${path.basename(f)}`,
1253
+ ...(i === 1 ? { after: object } : {}),
1254
+ })),
1255
+ ...listed,
1256
+ ];
1257
+ const findings = [
1258
+ ...(made ? made.findings.filter((f) => f.code !== 'schema') : []),
1259
+ { level: 'pass', text: 'matches the object schema', code: 'schema' },
1260
+ ];
588
1261
  if (!dryRun) {
589
1262
  fs.mkdirSync(objects, { recursive: true });
590
1263
  files.forEach((f, i) => fs.writeFileSync(f, texts[i]));
591
1264
  if (text !== before) fs.writeFileSync(pj, text);
592
1265
  }
593
- return { file: files[1], written: !dryRun, ...(dryRun ? { dryRun: true } : {}), made: [...(made ? [pj] : []), ...files], changes, findings };
1266
+ return {
1267
+ file: files[1],
1268
+ written: !dryRun,
1269
+ ...(dryRun ? { dryRun: true } : {}),
1270
+ made: [...(made ? [pj] : []), ...files],
1271
+ changes,
1272
+ findings,
1273
+ };
594
1274
  }
595
1275
 
596
1276
  /**
@@ -601,28 +1281,78 @@ export function newObject(ref, { dryRun = false } = {}) {
601
1281
  * @param {string} ref project/assembly
602
1282
  * @param {{ title?: string, kind?: string, description?: string, frame?: object, fields?: Record<string, any>, project?: { material?: string, printer?: string }, dryRun?: boolean }} [fields]
603
1283
  */
604
- export function newAssembly(ref, { title, kind = 'fit', description, frame, fields = {}, project: forProject = {}, dryRun = false } = {}) {
1284
+ export function newAssembly(
1285
+ ref,
1286
+ { title, kind = 'fit', description, frame, fields = {}, project: forProject = {}, dryRun = false } = {},
1287
+ ) {
605
1288
  const [project, name] = String(ref || '').split('/');
606
- if (!NAME.test(project || '') || !NAME.test(name || '')) throw new CadError('edit.name', `an assembly is <project>/<name>, each lower case with dashes (got ${JSON.stringify(ref)})`);
1289
+ if (!NAME.test(project || '') || !NAME.test(name || ''))
1290
+ throw new CadError(
1291
+ 'edit.name',
1292
+ `an assembly is <project>/<name>, each lower case with dashes (got ${JSON.stringify(ref)})`,
1293
+ );
607
1294
  const file = path.join(paths.project(project), 'assemblies', `${name}.json`);
608
- if (fs.existsSync(file)) throw new CadError('assembly.exists', `projects/${project}/assemblies/${name}.json is already there: change it with cad set, cad add, cad move and cad remove`, { file });
609
- const projectFields = Object.fromEntries(Object.entries(forProject || {}).filter(([, v]) => v != null)), hasProject = fs.existsSync(projectFile(project));
1295
+ if (fs.existsSync(file))
1296
+ throw new CadError(
1297
+ 'assembly.exists',
1298
+ `projects/${project}/assemblies/${name}.json is already there: change it with cad set, cad add, cad move and cad remove`,
1299
+ { file },
1300
+ );
1301
+ const projectFields = Object.fromEntries(Object.entries(forProject || {}).filter(([, v]) => v != null)),
1302
+ hasProject = fs.existsSync(projectFile(project));
610
1303
  const same = hasProject && Object.keys(projectFields).length ? sameProject(project, projectFields) : null; // refused where one differs
611
1304
  if (!hasProject) newProject(project, { ...projectFields, dryRun: true }); // its material and printer refused before anything is written
612
- if (kind !== 'fit') throw new CadError('edit.kind', `an assembly's kind is fit (got ${JSON.stringify(kind)}): a mechanism is a fit with joints (cad add joint), a machine a fit with a task, and a plate is written by cad plates`, { file });
613
- const json = { $schema: 'https://jonibach.github.io/rulecad/schemas/assembly.schema.json', title: title ?? name, kind, ...(description ? { description } : {}), ...(frame ? { frame } : { items: [] }) };
1305
+ if (kind !== 'fit')
1306
+ throw new CadError(
1307
+ 'edit.kind',
1308
+ `an assembly's kind is fit (got ${JSON.stringify(kind)}): a mechanism is a fit with joints (cad add joint), a machine a fit with a task, and a plate is written by cad plates`,
1309
+ { file },
1310
+ );
1311
+ const json = {
1312
+ $schema: 'https://jonibach.github.io/rulecad/schemas/assembly.schema.json',
1313
+ title: title ?? name,
1314
+ kind,
1315
+ ...(description ? { description } : {}),
1316
+ ...(frame ? { frame } : { items: [] }),
1317
+ };
614
1318
  // its other fields as cad set takes them, before it is checked: a portal's supports, its loads
615
1319
  let text = laidOut(json);
616
1320
  const top = Object.keys(schema('assembly').properties);
617
1321
  for (const [address, value] of Object.entries(fields)) {
618
1322
  const p = segmentsOf(address);
619
- if (!top.includes(p[0])) throw new CadError('edit.address', `an assembly has no field "${p[0]}" (fields: ${top.filter((k) => k !== '$schema').join(', ')})`, { file });
1323
+ if (!top.includes(p[0]))
1324
+ throw new CadError(
1325
+ 'edit.address',
1326
+ `an assembly has no field "${p[0]}" (fields: ${top.filter((k) => k !== '$schema').join(', ')})`,
1327
+ { file },
1328
+ );
620
1329
  text = setDeep(text, p, value);
621
1330
  }
622
- const args = { ref, file, before: '', text, kind: 'assembly', changes: [{ op: 'make', path: `projects/${project}/assemblies/${name}.json`, after: JSON.parse(text) }], touched: [] };
623
- try { finish({ ...args, dryRun: true }); } catch (e) { throw Object.assign(e, { message: e.message.replace(/^not changed: /, 'not made: ') }); } // checked before anything is written, the project too
1331
+ const args = {
1332
+ ref,
1333
+ file,
1334
+ before: '',
1335
+ text,
1336
+ kind: 'assembly',
1337
+ changes: [{ op: 'make', path: `projects/${project}/assemblies/${name}.json`, after: JSON.parse(text) }],
1338
+ touched: [],
1339
+ };
1340
+ try {
1341
+ finish({ ...args, dryRun: true });
1342
+ } catch (e) {
1343
+ throw Object.assign(e, { message: e.message.replace(/^not changed: /, 'not made: ') });
1344
+ } // checked before anything is written, the project too
624
1345
  const made = [];
625
1346
  if (!hasProject) made.push(newProject(project, { ...projectFields, dryRun }));
626
1347
  const r = finish({ ...args, dryRun });
627
- return { ...r, changes: [...made.flatMap((m) => m.changes), ...r.changes], findings: [...made.flatMap((m) => m.findings.filter((f) => f.code !== 'schema')), ...(same ? [same] : []), ...r.findings], made: [...made.map((m) => m.file), r.file] };
1348
+ return {
1349
+ ...r,
1350
+ changes: [...made.flatMap((m) => m.changes), ...r.changes],
1351
+ findings: [
1352
+ ...made.flatMap((m) => m.findings.filter((f) => f.code !== 'schema')),
1353
+ ...(same ? [same] : []),
1354
+ ...r.findings,
1355
+ ],
1356
+ made: [...made.map((m) => m.file), r.file],
1357
+ };
628
1358
  }