@rulecad/cad 0.7.97 → 0.9.0

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