@rulecad/cad 0.8.0 → 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.
- package/AGENTS.md +24 -10
- package/CHANGELOG.md +404 -0
- package/EXAMPLES.md +40 -38
- package/README.md +193 -67
- package/TUTORIAL.md +2 -2
- package/bin/cad.mjs +2250 -512
- package/lib/animate.mjs +173 -49
- package/lib/assembly.mjs +1847 -434
- package/lib/beams.mjs +256 -52
- package/lib/belts.mjs +66 -15
- package/lib/board-work.mjs +12 -0
- package/lib/bought.mjs +309 -53
- package/lib/buildpage.mjs +179 -29
- package/lib/carried.mjs +201 -0
- package/lib/clone.mjs +194 -42
- package/lib/design.mjs +649 -121
- package/lib/drive.mjs +187 -63
- package/lib/edit.mjs +899 -191
- package/lib/errors.mjs +16 -3
- package/lib/explain.mjs +62 -13
- package/lib/fasten.mjs +2702 -507
- package/lib/fittings.mjs +715 -121
- package/lib/fixings.mjs +21 -9
- package/lib/framebuild.mjs +790 -175
- package/lib/framecheck.mjs +1901 -368
- package/lib/framegen.mjs +100 -22
- package/lib/frameheat.mjs +225 -42
- package/lib/frameprint.mjs +513 -108
- package/lib/frames.mjs +81 -17
- package/lib/framesize.mjs +792 -120
- package/lib/frametip.mjs +235 -0
- package/lib/gait.mjs +135 -23
- package/lib/grip.mjs +62 -13
- package/lib/guides.mjs +1403 -230
- package/lib/host.mjs +123 -21
- package/lib/inplace.mjs +171 -36
- package/lib/jigs.mjs +360 -78
- package/lib/joins.mjs +697 -118
- package/lib/jsonedit.mjs +88 -26
- package/lib/kept.mjs +84 -0
- package/lib/kit.mjs +438 -68
- package/lib/layout.mjs +2 -1
- package/lib/links.mjs +149 -42
- package/lib/list.mjs +326 -64
- package/lib/live-guard.mjs +68 -0
- package/lib/live-shape.mjs +96 -24
- package/lib/live.mjs +189 -59
- package/lib/loads.mjs +579 -130
- package/lib/machine.mjs +372 -74
- package/lib/magnets.mjs +162 -44
- package/lib/measured.mjs +417 -94
- package/lib/mesh.mjs +526 -119
- package/lib/meshcmd.mjs +215 -60
- package/lib/motors.mjs +1021 -213
- package/lib/motorsvg.mjs +114 -32
- package/lib/names.mjs +3 -1
- package/lib/optimise.mjs +978 -283
- package/lib/order.mjs +519 -112
- package/lib/panels.mjs +482 -94
- package/lib/parts.mjs +78 -23
- package/lib/pins.mjs +163 -44
- package/lib/plates.mjs +223 -35
- package/lib/player.mjs +37 -9
- package/lib/power.mjs +64 -13
- package/lib/preview.mjs +83 -16
- package/lib/profilemeasure.mjs +572 -129
- package/lib/rules.mjs +15 -5
- package/lib/sandbox-hooks.mjs +77 -19
- package/lib/sandbox-run.mjs +117 -18
- package/lib/sandbox.mjs +509 -60
- package/lib/schema.mjs +42 -11
- package/lib/seats.mjs +227 -49
- package/lib/services.mjs +261 -52
- package/lib/sheet.mjs +851 -178
- package/lib/slotnuts.mjs +213 -34
- package/lib/targets/gist.mjs +4 -1
- package/lib/targets.mjs +22 -4
- package/lib/task.mjs +376 -79
- package/lib/versions.mjs +111 -28
- package/lib/wires.mjs +228 -45
- package/lib/workspace.mjs +197 -12
- package/package.json +19 -19
- package/schemas/assembly.schema.json +2 -2
package/lib/edit.mjs
CHANGED
|
@@ -7,6 +7,7 @@ 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
13
|
import { resolve, evaluate, peekRuleSet } from './rules.mjs';
|
|
@@ -15,14 +16,23 @@ 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) =>
|
|
19
|
+
export const parseValue = (s) =>
|
|
20
|
+
s === undefined ? undefined : /^-?(\d+\.?\d*|\.\d+)(e-?\d+)?$/i.test(String(s).trim()) ? Number(s) : String(s);
|
|
19
21
|
|
|
20
22
|
// The edited text, parsed and held to its schema: refused by name, nothing written
|
|
21
23
|
function checked(file, text, kind) {
|
|
22
24
|
let json;
|
|
23
|
-
try {
|
|
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
|
+
}
|
|
24
30
|
const problems = validate(json, schema(kind));
|
|
25
|
-
if (problems.length)
|
|
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
|
+
});
|
|
26
36
|
return json;
|
|
27
37
|
}
|
|
28
38
|
|
|
@@ -33,34 +43,65 @@ function checked(file, text, kind) {
|
|
|
33
43
|
* @param {{ create?: boolean, dryRun?: boolean }} [options] @returns {Promise<{ file: string, changed: string[], written: boolean, dryRun?: true }>}
|
|
34
44
|
*/
|
|
35
45
|
export async function setVariables(ref, changes, { create = false, dryRun = false } = {}) {
|
|
36
|
-
const d = locate(ref),
|
|
46
|
+
const d = locate(ref),
|
|
47
|
+
before = readOwnText(d.json);
|
|
37
48
|
let text = before;
|
|
38
49
|
for (const [name, c] of Object.entries(changes)) {
|
|
39
50
|
const exists = getAt(text, ['variables', name]) !== undefined;
|
|
40
|
-
if (!exists && !create)
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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]);
|
|
44
73
|
}
|
|
45
74
|
const json = checked(d.json, text, 'object');
|
|
46
|
-
try {
|
|
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)
|
|
47
77
|
const { values } = resolve(json, { sets: (await objectSets(d, readObject(d))).sets });
|
|
48
78
|
// and each changed value must lie within the variable's own range, where it has one (a tweak's min and max)
|
|
49
79
|
for (const name of Object.keys(changes)) {
|
|
50
|
-
const t = json.variables?.[name]?.tweak,
|
|
80
|
+
const t = json.variables?.[name]?.tweak,
|
|
81
|
+
v = values[name];
|
|
51
82
|
if (!t || typeof v !== 'number') continue;
|
|
52
|
-
const lo = typeof t.min === 'number' ? t.min : -Infinity,
|
|
53
|
-
|
|
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
|
+
);
|
|
54
91
|
}
|
|
55
|
-
} catch (e) {
|
|
92
|
+
} catch (e) {
|
|
93
|
+
throw Object.assign(e, { file: d.json, message: `not changed: ${e.message}` });
|
|
94
|
+
}
|
|
56
95
|
const written = !dryRun && text !== before;
|
|
57
96
|
if (written) fs.writeFileSync(d.json, text);
|
|
58
97
|
return { file: d.json, changed: Object.keys(changes), written, ...(dryRun ? { dryRun: true } : {}) };
|
|
59
98
|
}
|
|
60
99
|
|
|
61
100
|
const assemblyFile = (ref) => {
|
|
62
|
-
const [project, name] = ref.split('/'),
|
|
63
|
-
|
|
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 });
|
|
64
105
|
return file;
|
|
65
106
|
};
|
|
66
107
|
|
|
@@ -71,8 +112,11 @@ const assemblyFile = (ref) => {
|
|
|
71
112
|
* @param {{ dryRun?: boolean }} [options] @returns {{ file: string, written: boolean, changes: object[], findings: object[] }}
|
|
72
113
|
*/
|
|
73
114
|
export function addToAssembly(ref, what, entry, { dryRun = false } = {}) {
|
|
74
|
-
const file = assemblyFile(ref),
|
|
75
|
-
|
|
115
|
+
const file = assemblyFile(ref),
|
|
116
|
+
before = readOwnText(file),
|
|
117
|
+
list = LIST_OF[what];
|
|
118
|
+
let text = before,
|
|
119
|
+
at;
|
|
76
120
|
if (what === 'pose') {
|
|
77
121
|
entryProblems('pose', entry, { ref, file, known: knownOf(JSON.parse(text)) });
|
|
78
122
|
if (getAt(text, ['poses']) === undefined) text = setAt(text, ['poses'], {});
|
|
@@ -81,15 +125,30 @@ export function addToAssembly(ref, what, entry, { dryRun = false } = {}) {
|
|
|
81
125
|
} else {
|
|
82
126
|
if (!list) throw new CadError('edit.what', `can't add a ${what} (${Object.keys(LIST_OF).join(', ')} or pose)`);
|
|
83
127
|
if (getAt(text, [list]) === undefined) text = setAt(text, [list], []);
|
|
84
|
-
const json = JSON.parse(text),
|
|
85
|
-
|
|
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 });
|
|
86
132
|
const known = knownOf(json);
|
|
87
|
-
if (entry.id && what === 'item' && known.generated.includes(entry.id))
|
|
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
|
+
);
|
|
88
139
|
entryProblems(what, entry, { ref, file, known, self: idOf(list, entry, (json[list] || []).length) });
|
|
89
140
|
text = appendAt(text, [list], entry);
|
|
90
141
|
at = `${list}.${(json[list] || []).length}`;
|
|
91
142
|
}
|
|
92
|
-
return finish({
|
|
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
|
+
});
|
|
93
152
|
}
|
|
94
153
|
|
|
95
154
|
/**
|
|
@@ -102,14 +161,28 @@ export function addToAssembly(ref, what, entry, { dryRun = false } = {}) {
|
|
|
102
161
|
*/
|
|
103
162
|
export function fastenFromFitsEdit(ref, found, { screw, dryRun = false } = {}) {
|
|
104
163
|
const file = assemblyFile(ref);
|
|
105
|
-
if (!found.length)
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
+
}
|
|
109
178
|
// last first, so the places of the others hold
|
|
110
179
|
for (const i of [...new Set([...drop, ...trim])].sort((a, b) => b - a)) {
|
|
111
|
-
if (drop.has(i)) {
|
|
112
|
-
|
|
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]);
|
|
113
186
|
}
|
|
114
187
|
if (getAt(text, ['fasten']) === undefined) text = setAt(text, ['fasten'], []);
|
|
115
188
|
const added = found.map((g) => ({ ...g.fasten, ...(screw ? { screw } : {}) }));
|
|
@@ -126,7 +199,17 @@ export function fastenFromFitsEdit(ref, found, { screw, dryRun = false } = {}) {
|
|
|
126
199
|
// Each returns { file, written, changes: [{ op, path, before, after }], findings }, the shape cad prints with --json.
|
|
127
200
|
|
|
128
201
|
/** The list each kind of entry goes in. */
|
|
129
|
-
export const LIST_OF = {
|
|
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
|
+
};
|
|
130
213
|
// The lists whose entries have ids (a guide without one is g1, g2 .. by its place)
|
|
131
214
|
const ID_LISTS = ['items', 'joints', 'guides', 'wires'];
|
|
132
215
|
const LISTS = [...new Set([...Object.values(LIST_OF), 'planetary'])];
|
|
@@ -136,13 +219,20 @@ const rootOf = (n) => String(n).split(/[.@]/)[0];
|
|
|
136
219
|
// Numbers in an assembly's expressions, from the rule sets it uses (read, never copied in): enough for a frame's size
|
|
137
220
|
function numFor(a) {
|
|
138
221
|
const values = {};
|
|
139
|
-
for (const u of a.uses || []) {
|
|
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
|
+
}
|
|
140
229
|
const lookup = (n) => {
|
|
141
230
|
const p = n.split('.');
|
|
142
231
|
let v = values;
|
|
143
232
|
for (const k of p) v = v?.[k];
|
|
144
233
|
if (typeof v === 'string') v = evaluate(v, (k) => lookup(k.includes('.') ? k : `${p.slice(0, -1).join('.')}.${k}`));
|
|
145
|
-
if (typeof v !== 'number')
|
|
234
|
+
if (typeof v !== 'number')
|
|
235
|
+
throw Object.assign(new Error(`"${n}" is not a rule this check can read`), { code: 'edit.unread' });
|
|
146
236
|
return v;
|
|
147
237
|
};
|
|
148
238
|
return (x) => evaluate(x, lookup);
|
|
@@ -155,12 +245,35 @@ function numFor(a) {
|
|
|
155
245
|
* @returns {{ items: object[], beams: string[], generated: string[], guides: string[], joints: string[], joins: object[], wires: string[], frame: object | null, refused: Error | null }}
|
|
156
246
|
*/
|
|
157
247
|
export function knownOf(a) {
|
|
158
|
-
let items = a.items || [],
|
|
248
|
+
let items = a.items || [],
|
|
249
|
+
joints = a.joints || [],
|
|
250
|
+
joins = a.joins || [],
|
|
251
|
+
frame = null,
|
|
252
|
+
refused = null,
|
|
253
|
+
generated = [];
|
|
159
254
|
if (a.frame && typeof a.frame === 'object' && a.frame.kind != null) {
|
|
160
|
-
try {
|
|
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
|
+
}
|
|
161
265
|
}
|
|
162
|
-
return {
|
|
163
|
-
|
|
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
|
+
};
|
|
164
277
|
}
|
|
165
278
|
|
|
166
279
|
// 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 +283,353 @@ export function knownOf(a) {
|
|
|
170
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
|
|
171
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.
|
|
172
285
|
const esc = (x) => String(x).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
173
|
-
const GUIDE_PART =
|
|
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)$/;
|
|
174
288
|
const PANEL_PART = /^(clip|hinge-\d+|leaf-\d+|handle|latch|catch)(-\d+)?$/;
|
|
175
289
|
/**
|
|
176
290
|
* The items and joints an assembly's build makes from its entries, by name. @param {ReturnType<typeof knownOf>} known
|
|
177
291
|
* @returns {{ item: (n: string) => boolean, joint: (n: string) => boolean }}
|
|
178
292
|
*/
|
|
179
293
|
export function madeBy(known) {
|
|
180
|
-
const one = (n, id, re) => {
|
|
181
|
-
|
|
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+)?$`));
|
|
182
302
|
const items = known.items.filter((it) => it?.id != null);
|
|
183
|
-
const item = (n) =>
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
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)$/));
|
|
187
317
|
return { item, joint };
|
|
188
318
|
}
|
|
189
319
|
|
|
190
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
|
|
191
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.
|
|
192
322
|
function entryProblems(what, entry, { ref, file, known, self }) {
|
|
193
|
-
const items = known.items,
|
|
323
|
+
const items = known.items,
|
|
324
|
+
ids = items.map((x) => x?.id),
|
|
325
|
+
list = (xs) => xs.join(', ') || 'none';
|
|
194
326
|
const { item: made, joint: madeJoint } = madeBy(known); // what the build makes: g1-carriage-1, psu-mount, key-0-3 (madeBy)
|
|
195
|
-
if (what === 'fit')
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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
|
+
}
|
|
204
349
|
}
|
|
205
|
-
}
|
|
206
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
|
|
207
351
|
if (what === 'fasten') {
|
|
208
352
|
const has = (n) => ids.includes(rootOf(n)) || made(rootOf(n));
|
|
209
|
-
if (!entry.screw)
|
|
210
|
-
|
|
211
|
-
if (
|
|
212
|
-
|
|
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 });
|
|
213
375
|
}
|
|
214
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
|
|
215
377
|
if (what === 'join') {
|
|
216
|
-
if (!entry.kind || !entry.a || !entry.b)
|
|
217
|
-
|
|
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
|
+
}
|
|
218
391
|
}
|
|
219
392
|
// an item placed at an address, and a load carried at one, name an item that is there
|
|
220
|
-
if (
|
|
221
|
-
|
|
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
|
+
});
|
|
222
402
|
// a guide runs on a beam's face, and a screw guide drives another guide
|
|
223
403
|
if (what === 'guide') {
|
|
224
|
-
if (entry.on != null && !known.beams.includes(rootOf(entry.on)))
|
|
225
|
-
|
|
226
|
-
|
|
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
|
+
);
|
|
227
422
|
}
|
|
228
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
|
|
229
424
|
// follow another joint
|
|
230
425
|
if (what === 'joint') {
|
|
231
426
|
for (const side of ['parent', 'child']) {
|
|
232
|
-
const r = entry[side],
|
|
233
|
-
|
|
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
|
+
);
|
|
234
435
|
}
|
|
235
|
-
if (entry.follow != null && !known.joints.includes(String(entry.follow)))
|
|
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
|
+
);
|
|
236
445
|
}
|
|
237
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
|
|
238
447
|
// 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')
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
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
|
+
}
|
|
243
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
|
|
244
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.
|
|
245
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,
|
|
246
458
|
// psu-mount, key-0-3)
|
|
247
|
-
const anchorItem = (r) =>
|
|
248
|
-
|
|
249
|
-
const
|
|
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
|
+
};
|
|
250
471
|
const name = entry.id != null ? ` ${entry.id}` : '';
|
|
251
472
|
if (what === 'wire') {
|
|
252
473
|
for (const side of ['from', 'to']) if (entry[side] != null) noItem(`wire${name} ${side}`, entry[side]);
|
|
253
474
|
for (const v of Array.isArray(entry.via) ? entry.via : []) {
|
|
254
475
|
if (typeof v === 'string' && v.includes('.')) noItem(`wire${name} via`, v);
|
|
255
|
-
else if (typeof v === 'string' && !known.joints.includes(v) && !madeJoint(v))
|
|
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
|
+
);
|
|
256
482
|
else if (v && typeof v === 'object' && v.along != null) noBeam(`wire${name} via along`, v.along);
|
|
257
483
|
}
|
|
258
484
|
}
|
|
259
485
|
if (what === 'loop') for (const side of ['a', 'b']) noItem(`loop ${side}`, entry[side]);
|
|
260
486
|
if (what === 'load') {
|
|
261
|
-
if (entry.joint != null && !known.joints.includes(String(entry.joint)) && !madeJoint(String(entry.joint)))
|
|
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
|
+
);
|
|
262
493
|
if (entry.at != null && typeof entry.at === 'object') noItem('load at', entry.at);
|
|
263
494
|
}
|
|
264
|
-
if (what === 'item' && entry.mount && typeof entry.mount === 'object' && entry.mount.on != null)
|
|
495
|
+
if (what === 'item' && entry.mount && typeof entry.mount === 'object' && entry.mount.on != null)
|
|
496
|
+
noBeam(`item${name} mount on`, entry.mount.on);
|
|
265
497
|
}
|
|
266
498
|
|
|
267
499
|
// Every entry's names, checked as entryProblems checks one: [{ at, key, message }], where key is the same for the same
|
|
268
500
|
// problem in the same entry before and after an edit (its place may move, and the lists in its message change)
|
|
269
501
|
function namesProblems(json, known, { ref, file }) {
|
|
270
|
-
const out = [],
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
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 });
|
|
275
520
|
return out;
|
|
276
521
|
}
|
|
277
522
|
|
|
278
523
|
// A changed assembly, checked: its schema, its generated frame still expanding, and the names in each entry it touched
|
|
279
524
|
function assemblyFindings(json, { ref, file, touched = [], before = '' }) {
|
|
280
525
|
const problems = validate(json, schema('assembly'));
|
|
281
|
-
if (problems.length)
|
|
282
|
-
|
|
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);
|
|
283
533
|
if (known.refused) {
|
|
284
534
|
// 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))
|
|
286
|
-
|
|
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
|
+
});
|
|
287
542
|
} else if (known.frame) {
|
|
288
543
|
const [what, size] = frameText(known.frame);
|
|
289
|
-
out.push({
|
|
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
|
+
});
|
|
290
555
|
}
|
|
291
556
|
const kinds = Object.fromEntries(Object.entries(LIST_OF).map(([k, v]) => [v, k]));
|
|
292
|
-
for (const [list, i] of touched)
|
|
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) });
|
|
293
560
|
// and every other entry: a name it gave that was there before the edit must still be there (a beam renamed or
|
|
294
561
|
// removed, a frame changed or taken out, a guide renumbered). What was already missing is left to cad check
|
|
295
562
|
if (!known.refused) {
|
|
296
563
|
let was = [];
|
|
297
|
-
if (before) {
|
|
298
|
-
|
|
299
|
-
|
|
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
|
+
);
|
|
300
584
|
}
|
|
301
|
-
if (touched.length)
|
|
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
|
+
});
|
|
302
591
|
return out;
|
|
303
592
|
}
|
|
304
593
|
|
|
305
594
|
// Write the edit, or not: the one end of every edit here
|
|
306
595
|
function finish({ ref, file, before, text, kind, changes, dryRun, touched, findings: extra = [] }) {
|
|
307
596
|
let json;
|
|
308
|
-
try {
|
|
309
|
-
|
|
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
|
+
: [];
|
|
310
611
|
if (kind !== 'assembly') {
|
|
311
612
|
const problems = validate(json, schema(kind));
|
|
312
|
-
if (problems.length)
|
|
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
|
+
});
|
|
313
618
|
findings.push({ level: 'pass', text: `matches the ${kind} schema`, code: 'schema' });
|
|
314
619
|
}
|
|
315
620
|
findings.push(...extra);
|
|
316
621
|
const written = !dryRun && text !== before;
|
|
317
|
-
if (written) {
|
|
622
|
+
if (written) {
|
|
623
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
624
|
+
fs.writeFileSync(file, text);
|
|
625
|
+
}
|
|
318
626
|
return { file, written, ...(dryRun ? { dryRun: true } : {}), changes, findings };
|
|
319
627
|
}
|
|
320
628
|
// The list entry a path is in: 'joins.3.kind' → ['joins', 3]
|
|
321
|
-
const entryAt = (p) => {
|
|
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
|
+
};
|
|
322
633
|
|
|
323
634
|
/**
|
|
324
635
|
* A value as cad set takes it: JSON where it is JSON (a number, true, null, [300, 300, 350], {"kind": "bracket"}), a
|
|
@@ -327,53 +638,109 @@ const entryAt = (p) => { const m = /^([a-z]+)\.(\d+)/.exec(String(p)); return m
|
|
|
327
638
|
*/
|
|
328
639
|
export function parseSetting(s) {
|
|
329
640
|
const t = String(s).trim();
|
|
330
|
-
if (/^[[{"]|^(true|false|null)$/.test(t)) {
|
|
331
|
-
|
|
332
|
-
|
|
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
|
+
);
|
|
333
660
|
return parseValue(t);
|
|
334
661
|
}
|
|
335
662
|
|
|
336
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
|
|
337
664
|
// frame.supports["z1.a"], and joins[3] is joins.3
|
|
338
|
-
export const segmentsOf = (a) =>
|
|
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
|
+
);
|
|
339
669
|
|
|
340
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
|
|
341
671
|
// place), frame.join (a top-level field). Refused by name: an id nothing has, one two lists share, a generated frame's.
|
|
342
672
|
function addressPath(json, address, { ref, file, entry = false }) {
|
|
343
673
|
const segs = segmentsOf(address);
|
|
344
|
-
if (!segs.length)
|
|
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
|
+
);
|
|
345
680
|
const rest = (from) => segs.slice(from);
|
|
346
681
|
const [first] = segs;
|
|
347
682
|
if (LISTS.includes(first) && typeof segs[1] === 'number') {
|
|
348
|
-
const n = segs[1],
|
|
349
|
-
|
|
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
|
+
);
|
|
350
691
|
return { path: [first, n, ...rest(2)], entry: [first, n] };
|
|
351
692
|
}
|
|
352
|
-
const hits = ID_LISTS.flatMap((l) =>
|
|
353
|
-
|
|
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
|
+
);
|
|
354
702
|
if (hits.length) return { path: [...hits[0], ...rest(1)], entry: hits[0] };
|
|
355
703
|
const known = knownOf(json);
|
|
356
|
-
if (known.generated.includes(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
|
+
);
|
|
357
710
|
const top = Object.keys(schema('assembly').properties);
|
|
358
711
|
if (!entry && top.includes(first)) return { path: rest(0), entry: null };
|
|
359
712
|
const ids = ID_LISTS.flatMap((l) => (json[l] || []).map((x, i) => idOf(l, x, i))).filter(Boolean);
|
|
360
|
-
throw new CadError(
|
|
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
|
+
);
|
|
361
718
|
}
|
|
362
719
|
|
|
363
720
|
// Set at a path, making the objects it passes through where they are missing; a string where an object is asked for
|
|
364
721
|
// stands for its kind ("join": "blind" is { "kind": "blind" }), so frame.join.fitting=printed keeps the blind
|
|
365
722
|
function setDeep(text, p, value) {
|
|
366
723
|
for (let k = 1; k < p.length; k++) {
|
|
367
|
-
const up = p.slice(0, k),
|
|
724
|
+
const up = p.slice(0, k),
|
|
725
|
+
v = getAt(text, up);
|
|
368
726
|
if (v === undefined) {
|
|
369
|
-
if (typeof p[k] === 'number')
|
|
727
|
+
if (typeof p[k] === 'number')
|
|
728
|
+
throw new CadError('edit.address', `there is no ${up.join('.')} list to set entry ${p[k]} of`);
|
|
370
729
|
text = setAt(text, up, {});
|
|
371
730
|
} 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)
|
|
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
|
+
);
|
|
373
736
|
}
|
|
374
737
|
return setAt(text, p, value);
|
|
375
738
|
}
|
|
376
|
-
const shownPath = (p) =>
|
|
739
|
+
const shownPath = (p) =>
|
|
740
|
+
p
|
|
741
|
+
.map((k) => (typeof k === 'string' && /[.[\]"]/.test(k) ? `[${JSON.stringify(k)}]` : `.${k}`))
|
|
742
|
+
.join('')
|
|
743
|
+
.replace(/^\./, '');
|
|
377
744
|
|
|
378
745
|
/**
|
|
379
746
|
* Change fields of an assembly: { address: value }, each address an entry's field by its id (x1.at, hinge.max) or its
|
|
@@ -381,14 +748,28 @@ const shownPath = (p) => p.map((k) => (typeof k === 'string' && /[.[\]"]/.test(k
|
|
|
381
748
|
* @param {string} ref project/assembly @param {Record<string, any>} changes @param {{ dryRun?: boolean }} [options]
|
|
382
749
|
*/
|
|
383
750
|
export function setInAssembly(ref, changes, { dryRun = false } = {}) {
|
|
384
|
-
const file = assemblyFile(ref),
|
|
751
|
+
const file = assemblyFile(ref),
|
|
752
|
+
before = readOwnText(file);
|
|
385
753
|
let text = before;
|
|
386
|
-
const done = [],
|
|
754
|
+
const done = [],
|
|
755
|
+
touched = [];
|
|
387
756
|
for (const [address, value] of Object.entries(changes)) {
|
|
388
757
|
const { path: p, entry } = addressPath(JSON.parse(text), address, { ref, file });
|
|
389
|
-
if (entry && p.length === 2)
|
|
390
|
-
|
|
391
|
-
|
|
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
|
+
}
|
|
392
773
|
done.push({ op: 'set', path: shownPath(p), ...(was !== undefined ? { before: was } : {}), after: value });
|
|
393
774
|
if (entry) touched.push(entry);
|
|
394
775
|
}
|
|
@@ -397,18 +778,71 @@ export function setInAssembly(ref, changes, { dryRun = false } = {}) {
|
|
|
397
778
|
|
|
398
779
|
// Every place in an assembly that names an id (as itself, or as id.anchor, id.face@mm, id@pose): [{ path, value }].
|
|
399
780
|
// Values that never name an entry (kinds, profiles, screws, notes ..) are passed over.
|
|
400
|
-
const NOT_NAMES = new Set([
|
|
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
|
+
]);
|
|
401
821
|
function namesOf(json, id, { prefix = false } = {}) {
|
|
402
|
-
const hit = (s) =>
|
|
822
|
+
const hit = (s) =>
|
|
823
|
+
typeof s === 'string' &&
|
|
824
|
+
(s === id || s.startsWith(`${id}.`) || s.startsWith(`${id}@`) || (prefix && s.startsWith(`${id}-`)));
|
|
403
825
|
const out = [];
|
|
404
826
|
const walk = (v, p) => {
|
|
405
|
-
if (typeof v === 'string') {
|
|
406
|
-
|
|
407
|
-
|
|
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]);
|
|
827
|
+
if (typeof v === 'string') {
|
|
828
|
+
if (hit(v)) out.push({ path: p, value: v });
|
|
829
|
+
return;
|
|
411
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
|
+
}
|
|
412
846
|
};
|
|
413
847
|
walk(json, []);
|
|
414
848
|
return out;
|
|
@@ -421,30 +855,75 @@ function namesOf(json, id, { prefix = false } = {}) {
|
|
|
421
855
|
* @param {string} ref project/assembly @param {string} address @param {{ withRefs?: boolean, dryRun?: boolean }} [options]
|
|
422
856
|
*/
|
|
423
857
|
export function removeFromAssembly(ref, address, { withRefs = false, dryRun = false } = {}) {
|
|
424
|
-
const file = assemblyFile(ref),
|
|
858
|
+
const file = assemblyFile(ref),
|
|
859
|
+
before = readOwnText(file),
|
|
860
|
+
json = JSON.parse(before);
|
|
425
861
|
const { path: p, entry } = addressPath(json, address, { ref, file });
|
|
426
862
|
const was = getAt(before, p);
|
|
427
|
-
if (was === undefined)
|
|
428
|
-
|
|
429
|
-
|
|
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];
|
|
430
871
|
if (entry && p.length === 2) {
|
|
431
|
-
const [list, i] = entry,
|
|
872
|
+
const [list, i] = entry,
|
|
873
|
+
id = idOf(list, json[list][i], i);
|
|
432
874
|
// a guide with no id is g1, g2 .. by its place, so taking out any guide before one renames it, whether the guide
|
|
433
875
|
// taken out has an id or not
|
|
434
|
-
const renamed =
|
|
876
|
+
const renamed =
|
|
877
|
+
list === 'guides' ? json[list].map((g, k) => (k > i && g?.id == null ? k : -1)).filter((k) => k >= 0) : [];
|
|
435
878
|
if (renamed.length)
|
|
436
|
-
throw new CadError(
|
|
437
|
-
|
|
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
|
+
: [];
|
|
438
887
|
if (refs.length) {
|
|
439
888
|
// each name as what holds it: a list entry, or a pose's or a support's key
|
|
440
|
-
const holders = [
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
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
|
+
}
|
|
444
915
|
}
|
|
445
916
|
}
|
|
446
917
|
// the last first, so the places of the others hold
|
|
447
|
-
const order = (a, b) => {
|
|
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
|
+
};
|
|
448
927
|
let text = before;
|
|
449
928
|
for (const d of [...new Map(drop.map((x) => [shownPath(x), x])).values()].sort(order)) text = removeAt(text, d);
|
|
450
929
|
return finish({ ref, file, before, text, kind: 'assembly', changes, dryRun, touched: [] });
|
|
@@ -456,31 +935,85 @@ export function removeFromAssembly(ref, address, { withRefs = false, dryRun = fa
|
|
|
456
935
|
* @param {string} ref project/assembly @param {string} id @param {{ at?: any, to?: string, rotate?: any[], dryRun?: boolean }} move
|
|
457
936
|
*/
|
|
458
937
|
export function moveInAssembly(ref, id, { at, to, rotate, dryRun = false } = {}) {
|
|
459
|
-
const file = assemblyFile(ref),
|
|
460
|
-
|
|
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
|
+
);
|
|
461
947
|
const { entry } = addressPath(json, id, { ref, file, entry: true });
|
|
462
|
-
if (!entry || !['items', 'guides'].includes(entry[0]))
|
|
463
|
-
|
|
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 = [];
|
|
464
958
|
if (list === 'guides') {
|
|
465
|
-
if (rotate != null)
|
|
466
|
-
|
|
467
|
-
|
|
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
|
+
}
|
|
468
981
|
} else {
|
|
469
982
|
const ends = Array.isArray(x.from) && Array.isArray(x.to);
|
|
470
|
-
if (ends && (to != null || rotate != null))
|
|
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
|
+
);
|
|
471
989
|
if (at != null && ends) {
|
|
472
|
-
if (!Array.isArray(at) || at.length !== 3 || [...at, ...x.from, ...x.to].some((v) => typeof v !== 'number'))
|
|
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
|
+
);
|
|
473
996
|
const d = at.map((v, k) => v - x.from[k]);
|
|
474
997
|
sets.push([['from'], at], [['to'], x.to.map((v, k) => +(v + d[k]).toFixed(6))]);
|
|
475
998
|
} else if (at != null) {
|
|
476
|
-
if (!(Array.isArray(at) && at.length === 3) && typeof at !== 'string')
|
|
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
|
+
);
|
|
477
1005
|
sets.push([['at'], at]);
|
|
478
1006
|
}
|
|
479
1007
|
if (to != null) sets.push([['at'], String(to)]);
|
|
480
1008
|
if (rotate != null) sets.push([['rotate'], rotate]);
|
|
481
1009
|
}
|
|
482
1010
|
let text = before;
|
|
483
|
-
const changes = sets.map(([k, 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
|
+
});
|
|
484
1017
|
return finish({ ref, file, before, text, kind: 'assembly', changes, dryRun, touched: [entry] });
|
|
485
1018
|
}
|
|
486
1019
|
|
|
@@ -494,13 +1027,31 @@ const projectFile = (project) => path.join(paths.project(project), 'project.json
|
|
|
494
1027
|
function projectFindings(json, project) {
|
|
495
1028
|
const out = [];
|
|
496
1029
|
if (json.printer != null) {
|
|
497
|
-
let set = null;
|
|
498
|
-
|
|
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
|
+
);
|
|
499
1042
|
out.push({ level: 'pass', text: `prints are checked against ${json.printer}`, code: 'project.printer' });
|
|
500
1043
|
}
|
|
501
1044
|
if (json.material != null) {
|
|
502
|
-
try {
|
|
503
|
-
|
|
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
|
+
}
|
|
504
1055
|
}
|
|
505
1056
|
return out;
|
|
506
1057
|
}
|
|
@@ -513,27 +1064,66 @@ function projectFindings(json, project) {
|
|
|
513
1064
|
* @param {string} name @param {{ title?: string, description?: string, material?: string, printer?: string, dryRun?: boolean }} [fields]
|
|
514
1065
|
*/
|
|
515
1066
|
export function newProject(name, { dryRun = false, ...fields } = {}) {
|
|
516
|
-
if (!NAME.test(String(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)})`);
|
|
517
1069
|
const file = projectFile(name);
|
|
518
1070
|
const given = Object.fromEntries(Object.entries(fields).filter(([, v]) => v != null));
|
|
519
1071
|
if (fs.existsSync(file)) {
|
|
520
|
-
if (!Object.keys(given).length)
|
|
521
|
-
|
|
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
|
+
};
|
|
522
1085
|
}
|
|
523
|
-
const json = {
|
|
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
|
+
};
|
|
524
1093
|
const text = laidOut(json);
|
|
525
|
-
return finish({
|
|
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
|
+
});
|
|
526
1103
|
}
|
|
527
1104
|
|
|
528
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
|
|
529
1106
|
// none): a pass finding where each is already its own, refused by name where one differs, naming the cad set that
|
|
530
1107
|
// changes it
|
|
531
1108
|
function sameProject(name, given) {
|
|
532
|
-
const file = projectFile(name),
|
|
533
|
-
|
|
534
|
-
const
|
|
535
|
-
|
|
536
|
-
|
|
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
|
+
};
|
|
537
1127
|
}
|
|
538
1128
|
|
|
539
1129
|
/**
|
|
@@ -542,20 +1132,48 @@ function sameProject(name, given) {
|
|
|
542
1132
|
*/
|
|
543
1133
|
export function setProject(project, changes, { dryRun = false } = {}) {
|
|
544
1134
|
const file = projectFile(project);
|
|
545
|
-
if (!fs.existsSync(file))
|
|
546
|
-
|
|
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);
|
|
547
1142
|
let text = before;
|
|
548
|
-
const done = [],
|
|
1143
|
+
const done = [],
|
|
1144
|
+
fields = Object.keys(schema('project').properties).filter((k) => !['$schema', 'objects', 'name'].includes(k));
|
|
549
1145
|
for (const [address, value] of Object.entries(changes)) {
|
|
550
1146
|
const p = segmentsOf(address);
|
|
551
|
-
if (p[0] === 'objects')
|
|
552
|
-
|
|
553
|
-
|
|
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
|
+
});
|
|
554
1164
|
const was = getAt(text, p);
|
|
555
1165
|
text = setDeep(text, p, value);
|
|
556
1166
|
done.push({ op: 'set', path: shownPath(p), ...(was !== undefined ? { before: was } : {}), after: value });
|
|
557
1167
|
}
|
|
558
|
-
return finish({
|
|
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
|
+
});
|
|
559
1177
|
}
|
|
560
1178
|
|
|
561
1179
|
/**
|
|
@@ -567,30 +1185,70 @@ export function setProject(project, changes, { dryRun = false } = {}) {
|
|
|
567
1185
|
*/
|
|
568
1186
|
export function newObject(ref, { dryRun = false } = {}) {
|
|
569
1187
|
const [project, name] = String(ref || '').split('/');
|
|
570
|
-
if (!NAME.test(project || '') || !NAME.test(name || ''))
|
|
571
|
-
|
|
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);
|
|
572
1195
|
const files = ['js', 'json'].map((ext) => path.join(objects, `${name}.${ext}`));
|
|
573
1196
|
const there = files.find((f) => fs.existsSync(f));
|
|
574
|
-
if (there)
|
|
575
|
-
|
|
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
|
+
);
|
|
576
1206
|
const object = JSON.parse(texts[1]);
|
|
577
1207
|
const problems = validate(object, schema('object'));
|
|
578
|
-
if (problems.length)
|
|
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
|
+
});
|
|
579
1213
|
// its project: made where there is none, else the object added to its list (keeping the file's layout)
|
|
580
1214
|
const made = fs.existsSync(pj) ? null : newProject(project, { dryRun: true });
|
|
581
|
-
const before = made ? '' :
|
|
582
|
-
let text = made ? laidOut(made.changes[0].after) : before,
|
|
1215
|
+
const before = made ? '' : readOwnText(pj);
|
|
1216
|
+
let text = made ? laidOut(made.changes[0].after) : before,
|
|
1217
|
+
listed = [];
|
|
583
1218
|
const own = JSON.parse(text);
|
|
584
|
-
if (!Array.isArray(own.objects)) {
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
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
|
+
];
|
|
588
1239
|
if (!dryRun) {
|
|
589
1240
|
fs.mkdirSync(objects, { recursive: true });
|
|
590
1241
|
files.forEach((f, i) => fs.writeFileSync(f, texts[i]));
|
|
591
1242
|
if (text !== before) fs.writeFileSync(pj, text);
|
|
592
1243
|
}
|
|
593
|
-
return {
|
|
1244
|
+
return {
|
|
1245
|
+
file: files[1],
|
|
1246
|
+
written: !dryRun,
|
|
1247
|
+
...(dryRun ? { dryRun: true } : {}),
|
|
1248
|
+
made: [...(made ? [pj] : []), ...files],
|
|
1249
|
+
changes,
|
|
1250
|
+
findings,
|
|
1251
|
+
};
|
|
594
1252
|
}
|
|
595
1253
|
|
|
596
1254
|
/**
|
|
@@ -601,28 +1259,78 @@ export function newObject(ref, { dryRun = false } = {}) {
|
|
|
601
1259
|
* @param {string} ref project/assembly
|
|
602
1260
|
* @param {{ title?: string, kind?: string, description?: string, frame?: object, fields?: Record<string, any>, project?: { material?: string, printer?: string }, dryRun?: boolean }} [fields]
|
|
603
1261
|
*/
|
|
604
|
-
export function newAssembly(
|
|
1262
|
+
export function newAssembly(
|
|
1263
|
+
ref,
|
|
1264
|
+
{ title, kind = 'fit', description, frame, fields = {}, project: forProject = {}, dryRun = false } = {},
|
|
1265
|
+
) {
|
|
605
1266
|
const [project, name] = String(ref || '').split('/');
|
|
606
|
-
if (!NAME.test(project || '') || !NAME.test(name || ''))
|
|
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
|
+
);
|
|
607
1272
|
const file = path.join(paths.project(project), 'assemblies', `${name}.json`);
|
|
608
|
-
if (fs.existsSync(file))
|
|
609
|
-
|
|
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));
|
|
610
1281
|
const same = hasProject && Object.keys(projectFields).length ? sameProject(project, projectFields) : null; // refused where one differs
|
|
611
1282
|
if (!hasProject) newProject(project, { ...projectFields, dryRun: true }); // its material and printer refused before anything is written
|
|
612
|
-
if (kind !== 'fit')
|
|
613
|
-
|
|
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
|
+
};
|
|
614
1296
|
// its other fields as cad set takes them, before it is checked: a portal's supports, its loads
|
|
615
1297
|
let text = laidOut(json);
|
|
616
1298
|
const top = Object.keys(schema('assembly').properties);
|
|
617
1299
|
for (const [address, value] of Object.entries(fields)) {
|
|
618
1300
|
const p = segmentsOf(address);
|
|
619
|
-
if (!top.includes(p[0]))
|
|
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
|
+
);
|
|
620
1307
|
text = setDeep(text, p, value);
|
|
621
1308
|
}
|
|
622
|
-
const args = {
|
|
623
|
-
|
|
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
|
|
624
1323
|
const made = [];
|
|
625
1324
|
if (!hasProject) made.push(newProject(project, { ...projectFields, dryRun }));
|
|
626
1325
|
const r = finish({ ...args, dryRun });
|
|
627
|
-
return {
|
|
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
|
+
};
|
|
628
1336
|
}
|