@rulecad/cad 0.7.60 → 0.7.62
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 +22 -5
- package/CHANGELOG.md +61 -0
- package/EXAMPLES.md +29 -49
- package/README.md +104 -2
- package/bin/cad.mjs +97 -15
- package/lib/assembly.mjs +2 -0
- package/lib/belts.mjs +62 -0
- package/lib/edit.mjs +493 -36
- package/lib/errors.mjs +1 -1
- package/lib/fasten.mjs +1 -1
- package/lib/fittings.mjs +11 -1
- package/lib/guides.mjs +100 -9
- package/lib/motors.mjs +16 -8
- package/lib/schema.mjs +2 -2
- package/lib/versions.mjs +6 -2
- package/package.json +2 -2
- package/schemas/assembly.schema.json +2 -2
- package/schemas/project.schema.json +31 -0
package/lib/edit.mjs
CHANGED
|
@@ -8,7 +8,10 @@ import { validate, schema } from './schema.mjs';
|
|
|
8
8
|
import { CadError } from './errors.mjs';
|
|
9
9
|
import { paths } from './workspace.mjs';
|
|
10
10
|
import { locate, readObject, objectSets } from './design.mjs';
|
|
11
|
-
import { resolve } from './rules.mjs';
|
|
11
|
+
import { resolve, evaluate, peekRuleSet } from './rules.mjs';
|
|
12
|
+
import { expandFrame, frameText } from './framegen.mjs';
|
|
13
|
+
import { framesContext } from './beams.mjs';
|
|
14
|
+
import { plasticNamed } from './fittings.mjs';
|
|
12
15
|
|
|
13
16
|
// A value from the command line: a number if it is one, otherwise an expression (or a name) as text
|
|
14
17
|
export const parseValue = (s) => (s === undefined ? undefined : /^-?(\d+\.?\d*|\.\d+)(e-?\d+)?$/i.test(String(s).trim()) ? Number(s) : String(s));
|
|
@@ -58,50 +61,31 @@ const assemblyFile = (ref) => {
|
|
|
58
61
|
};
|
|
59
62
|
|
|
60
63
|
/**
|
|
61
|
-
* Add to an assembly: a fit, a joint, an item, a loop, a fasten or a
|
|
62
|
-
*
|
|
63
|
-
* @
|
|
64
|
+
* Add to an assembly: a fit, a joint, an item, a loop, a fasten, a join, a guide or a load (appended to its list), or a
|
|
65
|
+
* pose (by name). The names it gives are checked against the assembly's items, a generated frame's beams among them.
|
|
66
|
+
* @param {string} ref project/assembly @param {'fit' | 'joint' | 'item' | 'loop' | 'fasten' | 'join' | 'guide' | 'load' | 'pose'} what @param {any} entry (a pose: { name, values })
|
|
67
|
+
* @param {{ dryRun?: boolean }} [options] @returns {{ file: string, written: boolean, changes: object[], findings: object[] }}
|
|
64
68
|
*/
|
|
65
|
-
export function addToAssembly(ref, what, entry) {
|
|
66
|
-
const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), list =
|
|
67
|
-
let text = before;
|
|
69
|
+
export function addToAssembly(ref, what, entry, { dryRun = false } = {}) {
|
|
70
|
+
const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), list = LIST_OF[what];
|
|
71
|
+
let text = before, at;
|
|
68
72
|
if (what === 'pose') {
|
|
73
|
+
entryProblems('pose', entry, { ref, file, known: knownOf(JSON.parse(text)) });
|
|
69
74
|
if (getAt(text, ['poses']) === undefined) text = setAt(text, ['poses'], {});
|
|
70
75
|
text = setAt(text, ['poses', entry.name], entry.values);
|
|
76
|
+
at = `poses.${entry.name}`;
|
|
71
77
|
} else {
|
|
72
|
-
if (!list) throw new CadError('edit.what', `can't add a ${what} (
|
|
78
|
+
if (!list) throw new CadError('edit.what', `can't add a ${what} (${Object.keys(LIST_OF).join(', ')} or pose)`);
|
|
73
79
|
if (getAt(text, [list]) === undefined) text = setAt(text, [list], []);
|
|
74
|
-
const
|
|
80
|
+
const json = JSON.parse(text), ids = (json[list] || []).map((x) => x.id).filter(Boolean);
|
|
75
81
|
if (entry.id && ids.includes(entry.id)) throw new CadError('edit.duplicate', `${ref} already has a ${what} "${entry.id}"`, { file });
|
|
76
|
-
|
|
77
|
-
if (what === '
|
|
78
|
-
|
|
79
|
-
const [item, part = 'body'] = named.split('@')[0].split('.'), it = (getAt(text, ['items']) || []).find((x) => x.id === item);
|
|
80
|
-
if (!it) throw new CadError('edit.part', `fit ${side}: no item "${item}" in ${ref} (items: ${(getAt(text, ['items']) || []).map((x) => x.id).join(', ') || 'none'})`, { file });
|
|
81
|
-
if (it.object) {
|
|
82
|
-
const [project] = ref.split('/'), obj = path.join(paths.project(project), 'objects', `${String(it.object).split(/[@:]/)[0]}.json`);
|
|
83
|
-
const parts = fs.existsSync(obj) ? Object.keys(JSON.parse(fs.readFileSync(obj, 'utf8')).parts || { body: {} }) : null;
|
|
84
|
-
if (parts && !parts.includes(part)) throw new CadError('edit.part', `fit ${side}: ${it.object} has no part "${part}" (parts: ${parts.join(', ')})`, { file });
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
// a fasten names the parts its screw passes and ends in, and where the screws go: each must be an item of the assembly
|
|
88
|
-
if (what === 'fasten') {
|
|
89
|
-
const items = (getAt(text, ['items']) || []).map((x) => x.id), has = (n) => items.includes(String(n).split(/[.@]/)[0]);
|
|
90
|
-
if (!entry.screw) throw new CadError('edit.incomplete', 'a fasten needs its screw, by thread and head: --screw "M3 cap"', { file });
|
|
91
|
-
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 });
|
|
92
|
-
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 });
|
|
93
|
-
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 "${String(n).split(/[.@]/)[0]}" in ${ref} (items: ${items.join(', ') || 'none'})`, { file });
|
|
94
|
-
}
|
|
95
|
-
// a join names a beam's end and a place on another beam: each must be a beam item of the assembly
|
|
96
|
-
if (what === 'join') {
|
|
97
|
-
const beams = (getAt(text, ['items']) || []).filter((x) => x.beam).map((x) => x.id);
|
|
98
|
-
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 });
|
|
99
|
-
for (const side of ['a', 'b']) { const id = String(entry[side]).split('.')[0]; if (!beams.includes(id)) throw new CadError('edit.part', `join ${side}: no beam "${id}" in ${ref} (beams: ${beams.join(', ') || 'none'})`, { file }); }
|
|
100
|
-
}
|
|
82
|
+
const known = knownOf(json);
|
|
83
|
+
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 });
|
|
84
|
+
entryProblems(what, entry, { ref, file, known, self: idOf(list, entry, (json[list] || []).length) });
|
|
101
85
|
text = appendAt(text, [list], entry);
|
|
86
|
+
at = `${list}.${(json[list] || []).length}`;
|
|
102
87
|
}
|
|
103
|
-
|
|
104
|
-
return { file };
|
|
88
|
+
return finish({ ref, file, before, text, kind: 'assembly', changes: [{ op: 'add', path: at, after: entry }], dryRun });
|
|
105
89
|
}
|
|
106
90
|
|
|
107
91
|
/**
|
|
@@ -128,3 +112,476 @@ export function fastenFromFitsEdit(ref, found, { screw } = {}) {
|
|
|
128
112
|
write(file, text, 'assembly');
|
|
129
113
|
return { file, added };
|
|
130
114
|
}
|
|
115
|
+
|
|
116
|
+
// ---------- the workspace's own files: projects and assemblies, made, changed, moved and removed ----------
|
|
117
|
+
// Every edit below works the same way: it reads the file, makes the change in its text (lib/jsonedit.mjs keeps the
|
|
118
|
+
// layout), holds the result to the file's schema and a quick check of what the change could break, and only then
|
|
119
|
+
// writes it. A refusal names what is wrong and writes nothing; --dry-run does all of it and writes nothing either.
|
|
120
|
+
// Each returns { file, written, changes: [{ op, path, before, after }], findings }, the shape cad prints with --json.
|
|
121
|
+
|
|
122
|
+
/** The list each kind of entry goes in. */
|
|
123
|
+
export const LIST_OF = { fit: 'fits', joint: 'joints', item: 'items', loop: 'loops', fasten: 'fasten', join: 'joins', guide: 'guides', load: 'loads', wire: 'wires' };
|
|
124
|
+
// The lists whose entries have ids (a guide without one is g1, g2 .. by its place)
|
|
125
|
+
const ID_LISTS = ['items', 'joints', 'guides', 'wires'];
|
|
126
|
+
const LISTS = [...new Set([...Object.values(LIST_OF), 'planetary'])];
|
|
127
|
+
const idOf = (list, x, i) => x?.id ?? (list === 'guides' ? `g${i + 1}` : undefined);
|
|
128
|
+
const rootOf = (n) => String(n).split(/[.@]/)[0];
|
|
129
|
+
|
|
130
|
+
// Numbers in an assembly's expressions, from the rule sets it uses (read, never copied in): enough for a frame's size
|
|
131
|
+
function numFor(a) {
|
|
132
|
+
const values = {};
|
|
133
|
+
for (const u of a.uses || []) { try { values[u] = Object.fromEntries(Object.entries(peekRuleSet(u).rules || {}).map(([k, r]) => [k, r.value])); } catch {} }
|
|
134
|
+
const lookup = (n) => {
|
|
135
|
+
const p = n.split('.');
|
|
136
|
+
let v = values;
|
|
137
|
+
for (const k of p) v = v?.[k];
|
|
138
|
+
if (typeof v === 'string') v = evaluate(v, (k) => lookup(k.includes('.') ? k : `${p.slice(0, -1).join('.')}.${k}`));
|
|
139
|
+
if (typeof v !== 'number') throw Object.assign(new Error(`"${n}" is not a rule this check can read`), { code: 'edit.unread' });
|
|
140
|
+
return v;
|
|
141
|
+
};
|
|
142
|
+
return (x) => evaluate(x, lookup);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* What an assembly names, its generated frame expanded: its items (with the frame's beams, ends and panels), the beams
|
|
147
|
+
* among them, the ids the generator gives, its guides' ids, and the frame's model (or why it did not expand).
|
|
148
|
+
* @param {object} a the assembly as read
|
|
149
|
+
* @returns {{ items: object[], beams: string[], generated: string[], guides: string[], joints: string[], joins: object[], wires: string[], frame: object | null, refused: Error | null }}
|
|
150
|
+
*/
|
|
151
|
+
export function knownOf(a) {
|
|
152
|
+
let items = a.items || [], joints = a.joints || [], joins = a.joins || [], frame = null, refused = null, generated = [];
|
|
153
|
+
if (a.frame && typeof a.frame === 'object' && a.frame.kind != null) {
|
|
154
|
+
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; }
|
|
155
|
+
}
|
|
156
|
+
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),
|
|
157
|
+
joins: Array.isArray(joins) ? joins : [], wires: (Array.isArray(a.wires) ? a.wires : []).map((w, i) => w?.id ?? `w${i + 1}`), frame, refused };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// The names an assembly's build makes that are not in its file, each by the exact pattern its maker uses (lib/assembly,
|
|
161
|
+
// fittings, panels, services, guides): a repeated item's copies (key-0-3: <id>-<i>, <id>-<i>-<j>), a mounted item's
|
|
162
|
+
// mount (psu-mount), a panel's clips, hinges, leaves, handle and catch, a levelling foot's pad, a join's fitting
|
|
163
|
+
// (y1-x1-bracket), a wire's clips (w1-clip), a guide's carriages, wheels, holders, rods, bearings and drive parts
|
|
164
|
+
// (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
|
|
165
|
+
// (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.
|
|
166
|
+
const esc = (x) => String(x).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
167
|
+
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)$/;
|
|
168
|
+
const PANEL_PART = /^(clip|hinge-\d+|leaf-\d+|handle|latch|catch)(-\d+)?$/;
|
|
169
|
+
/**
|
|
170
|
+
* The items and joints an assembly's build makes from its entries, by name. @param {ReturnType<typeof knownOf>} known
|
|
171
|
+
* @returns {{ item: (n: string) => boolean, joint: (n: string) => boolean }}
|
|
172
|
+
*/
|
|
173
|
+
export function madeBy(known) {
|
|
174
|
+
const one = (n, id, re) => { const s = String(n), head = `${id}-`; return s.startsWith(head) && re.test(s.slice(head.length)); };
|
|
175
|
+
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+)?$`));
|
|
176
|
+
const items = known.items.filter((it) => it?.id != null);
|
|
177
|
+
const item = (n) => items.some((it) => (it.repeat != null && one(n, it.id, /^\d+(-\d+)?$/)) || (it.mount != null && one(n, it.id, /^mount(-\d+)?$/))
|
|
178
|
+
|| (it.panel != null && one(n, it.id, PANEL_PART)) || (it.fitting?.kind === 'levelling-foot' && one(n, it.id, /^pad$/)))
|
|
179
|
+
|| 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)));
|
|
180
|
+
const joint = (n) => known.guides.some((g) => one(n, g, /^\d+$/)) || items.some((it) => it.panel != null && one(n, it.id, /^(hinge|bay)$/));
|
|
181
|
+
return { item, joint };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// 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
|
|
185
|
+
// drives, a joint's parent and child items and the joint it follows, a pose's joints. self is the entry's own id.
|
|
186
|
+
function entryProblems(what, entry, { ref, file, known, self }) {
|
|
187
|
+
const items = known.items, ids = items.map((x) => x?.id), list = (xs) => xs.join(', ') || 'none';
|
|
188
|
+
const { item: made, joint: madeJoint } = madeBy(known); // what the build makes: g1-carriage-1, psu-mount, key-0-3 (madeBy)
|
|
189
|
+
if (what === 'fit') for (const side of ['a', 'b']) {
|
|
190
|
+
const named = entry[side]; if (typeof named !== 'string') continue;
|
|
191
|
+
const [item, part = 'body'] = named.split('@')[0].split('.'), it = items.find((x) => x?.id === item);
|
|
192
|
+
if (!it && made(item)) continue; // a guide's part or a repeated item's copy (key-0-3)
|
|
193
|
+
if (!it) throw new CadError('edit.part', `fit ${side}: no item "${item}" in ${ref} (items: ${list(ids)})`, { file });
|
|
194
|
+
if (it.object) {
|
|
195
|
+
const [project] = ref.split('/'), obj = path.join(paths.project(project), 'objects', `${String(it.object).split(/[@:]/)[0]}.json`);
|
|
196
|
+
const parts = fs.existsSync(obj) ? Object.keys(JSON.parse(fs.readFileSync(obj, 'utf8')).parts || { body: {} }) : null;
|
|
197
|
+
if (parts && !parts.includes(part)) throw new CadError('edit.part', `fit ${side}: ${it.object} has no part "${part}" (parts: ${parts.join(', ')})`, { file });
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
// a fasten names the parts its screw passes and ends in, and where the screws go: each must be an item of the assembly
|
|
201
|
+
if (what === 'fasten') {
|
|
202
|
+
const has = (n) => ids.includes(rootOf(n)) || made(rootOf(n));
|
|
203
|
+
if (!entry.screw) throw new CadError('edit.incomplete', 'a fasten needs its screw, by thread and head: --screw "M3 cap"', { file });
|
|
204
|
+
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 });
|
|
205
|
+
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 });
|
|
206
|
+
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 });
|
|
207
|
+
}
|
|
208
|
+
// 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
|
|
209
|
+
if (what === 'join') {
|
|
210
|
+
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 });
|
|
211
|
+
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 }); }
|
|
212
|
+
}
|
|
213
|
+
// an item placed at an address, and a load carried at one, name an item that is there
|
|
214
|
+
if ((what === 'item' || what === 'load') && typeof entry.at === 'string' && !ids.includes(rootOf(entry.at)) && !made(rootOf(entry.at)))
|
|
215
|
+
throw new CadError('edit.part', `${what} at: no item "${rootOf(entry.at)}" in ${ref} (items: ${list(ids)})`, { file });
|
|
216
|
+
// a guide runs on a beam's face, and a screw guide drives another guide
|
|
217
|
+
if (what === 'guide') {
|
|
218
|
+
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 });
|
|
219
|
+
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 });
|
|
220
|
+
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 });
|
|
221
|
+
}
|
|
222
|
+
// a joint ties an anchor on its child item to one on its parent (an anchor by item.anchor, or { item, at }), and may
|
|
223
|
+
// follow another joint
|
|
224
|
+
if (what === 'joint') {
|
|
225
|
+
for (const side of ['parent', 'child']) {
|
|
226
|
+
const r = entry[side], item = typeof r === 'string' ? rootOf(r) : r && typeof r === 'object' && r.item != null ? String(r.item) : null;
|
|
227
|
+
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 });
|
|
228
|
+
}
|
|
229
|
+
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 });
|
|
230
|
+
}
|
|
231
|
+
// 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
|
|
232
|
+
// joints (g1-1, door-hinge) are made as it is built, so a name under one of theirs is taken as theirs
|
|
233
|
+
if (what === 'pose') for (const k of Object.keys(entry.values || {})) {
|
|
234
|
+
if (k.includes('.') || known.joints.includes(k) || madeJoint(k)) continue;
|
|
235
|
+
throw new CadError('edit.part', `pose ${entry.name}: no joint "${k}" in ${ref} (joints: ${list(known.joints)})`, { file });
|
|
236
|
+
}
|
|
237
|
+
// a wire runs from an anchor to an anchor, by anchors, path joints and runs along a beam's slot (via); a loop closes
|
|
238
|
+
// between two anchors; a load is on a joint or carried at an anchor; a mounted item sits at an address on a beam.
|
|
239
|
+
// 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,
|
|
240
|
+
// psu-mount, key-0-3)
|
|
241
|
+
const anchorItem = (r) => (typeof r === 'string' ? rootOf(r) : r && typeof r === 'object' && r.item != null ? String(r.item) : null);
|
|
242
|
+
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 }); };
|
|
243
|
+
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 }); };
|
|
244
|
+
const name = entry.id != null ? ` ${entry.id}` : '';
|
|
245
|
+
if (what === 'wire') {
|
|
246
|
+
for (const side of ['from', 'to']) if (entry[side] != null) noItem(`wire${name} ${side}`, entry[side]);
|
|
247
|
+
for (const v of Array.isArray(entry.via) ? entry.via : []) {
|
|
248
|
+
if (typeof v === 'string' && v.includes('.')) noItem(`wire${name} via`, v);
|
|
249
|
+
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 });
|
|
250
|
+
else if (v && typeof v === 'object' && v.along != null) noBeam(`wire${name} via along`, v.along);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
if (what === 'loop') for (const side of ['a', 'b']) noItem(`loop ${side}`, entry[side]);
|
|
254
|
+
if (what === 'load') {
|
|
255
|
+
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 });
|
|
256
|
+
if (entry.at != null && typeof entry.at === 'object') noItem('load at', entry.at);
|
|
257
|
+
}
|
|
258
|
+
if (what === 'item' && entry.mount && typeof entry.mount === 'object' && entry.mount.on != null) noBeam(`item${name} mount on`, entry.mount.on);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Every entry's names, checked as entryProblems checks one: [{ at, key, message }], where key is the same for the same
|
|
262
|
+
// problem in the same entry before and after an edit (its place may move, and the lists in its message change)
|
|
263
|
+
function namesProblems(json, known, { ref, file }) {
|
|
264
|
+
const out = [], one = (at, what, entry, self) => {
|
|
265
|
+
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 }); }
|
|
266
|
+
};
|
|
267
|
+
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)); });
|
|
268
|
+
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 });
|
|
269
|
+
return out;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// A changed assembly, checked: its schema, its generated frame still expanding, and the names in each entry it touched
|
|
273
|
+
function assemblyFindings(json, { ref, file, touched = [], before = '' }) {
|
|
274
|
+
const problems = validate(json, schema('assembly'));
|
|
275
|
+
if (problems.length) throw new CadError('schema', `not changed: ${path.basename(file)}: ${problems[0].path}: ${problems[0].message}`, { file, path: problems[0].path });
|
|
276
|
+
const out = [{ level: 'pass', text: 'matches the assembly schema', code: 'schema' }], known = knownOf(json);
|
|
277
|
+
if (known.refused) {
|
|
278
|
+
// a frame the generator refuses is a broken edit; one whose size reads an item's values is left to cad check
|
|
279
|
+
if (/^frame: /.test(known.refused.message)) throw new CadError('frame.refused', `not changed: ${known.refused.message}`, { file, path: 'frame' });
|
|
280
|
+
out.push({ level: 'info', text: `the frame is not expanded here (${known.refused.message}): cad check ${ref} expands it`, code: 'edit.unread' });
|
|
281
|
+
} else if (known.frame) {
|
|
282
|
+
const [what, size] = frameText(known.frame);
|
|
283
|
+
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 } });
|
|
284
|
+
}
|
|
285
|
+
const kinds = Object.fromEntries(Object.entries(LIST_OF).map(([k, v]) => [v, k]));
|
|
286
|
+
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) });
|
|
287
|
+
// and every other entry: a name it gave that was there before the edit must still be there (a beam renamed or
|
|
288
|
+
// removed, a frame changed or taken out, a guide renumbered). What was already missing is left to cad check
|
|
289
|
+
if (!known.refused) {
|
|
290
|
+
let was = [];
|
|
291
|
+
if (before) { try { const b = JSON.parse(before), bk = knownOf(b); if (!bk.refused) was = namesProblems(b, bk, { ref, file }); } catch {} }
|
|
292
|
+
const old = new Set(was.map((p) => p.key)), fresh = namesProblems(json, known, { ref, file }).filter((p) => !old.has(p.key));
|
|
293
|
+
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) });
|
|
294
|
+
}
|
|
295
|
+
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' });
|
|
296
|
+
return out;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Write the edit, or not: the one end of every edit here
|
|
300
|
+
function finish({ ref, file, before, text, kind, changes, dryRun, touched, findings: extra = [] }) {
|
|
301
|
+
let json;
|
|
302
|
+
try { json = JSON.parse(text); } catch (e) { throw new CadError('edit.broken', `the edit would break ${file}'s JSON: ${e.message}`, { file }); }
|
|
303
|
+
const findings = kind === 'assembly' ? assemblyFindings(json, { ref, file, before, touched: touched ?? changes.map((c) => entryAt(c.path)).filter(Boolean) }) : [];
|
|
304
|
+
if (kind !== 'assembly') {
|
|
305
|
+
const problems = validate(json, schema(kind));
|
|
306
|
+
if (problems.length) throw new CadError('schema', `not changed: ${path.basename(file)}: ${problems[0].path}: ${problems[0].message}`, { file, path: problems[0].path });
|
|
307
|
+
findings.push({ level: 'pass', text: `matches the ${kind} schema`, code: 'schema' });
|
|
308
|
+
}
|
|
309
|
+
findings.push(...extra);
|
|
310
|
+
const written = !dryRun && text !== before;
|
|
311
|
+
if (written) { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, text); }
|
|
312
|
+
return { file, written, ...(dryRun ? { dryRun: true } : {}), changes, findings };
|
|
313
|
+
}
|
|
314
|
+
// The list entry a path is in: 'joins.3.kind' → ['joins', 3]
|
|
315
|
+
const entryAt = (p) => { const m = /^([a-z]+)\.(\d+)/.exec(String(p)); return m && LISTS.includes(m[1]) ? [m[1], Number(m[2])] : null; };
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* A value as cad set takes it: JSON where it is JSON (a number, true, null, [300, 300, 350], {"kind": "bracket"}), a
|
|
319
|
+
* list in brackets without quotes ([1515-openbeam, 2020-misumi-hfs5]), and otherwise a number or a piece of text.
|
|
320
|
+
* @param {string} s @returns {any}
|
|
321
|
+
*/
|
|
322
|
+
export function parseSetting(s) {
|
|
323
|
+
const t = String(s).trim();
|
|
324
|
+
if (/^[[{"]|^(true|false|null)$/.test(t)) { try { return JSON.parse(t); } catch {} }
|
|
325
|
+
if (/^\[.*\]$/s.test(t)) return t.slice(1, -1).split(',').map((x) => x.trim()).filter((x) => x !== '').map(parseSetting);
|
|
326
|
+
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`);
|
|
327
|
+
return parseValue(t);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// An address's parts: x1.at.0 is ["x1", "at", 0]; a key with a dot in it goes in brackets and quotes, as
|
|
331
|
+
// frame.supports["z1.a"], and joins[3] is joins.3
|
|
332
|
+
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]));
|
|
333
|
+
|
|
334
|
+
// 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
|
|
335
|
+
// place), frame.join (a top-level field). Refused by name: an id nothing has, one two lists share, a generated frame's.
|
|
336
|
+
function addressPath(json, address, { ref, file, entry = false }) {
|
|
337
|
+
const segs = segmentsOf(address);
|
|
338
|
+
if (!segs.length) throw new CadError('edit.address', 'give what to change, as <id>.<field>, <list>.<n>.<field> or a top-level field', { file });
|
|
339
|
+
const rest = (from) => segs.slice(from);
|
|
340
|
+
const [first] = segs;
|
|
341
|
+
if (LISTS.includes(first) && typeof segs[1] === 'number') {
|
|
342
|
+
const n = segs[1], len = (json[first] || []).length;
|
|
343
|
+
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 });
|
|
344
|
+
return { path: [first, n, ...rest(2)], entry: [first, n] };
|
|
345
|
+
}
|
|
346
|
+
const hits = ID_LISTS.flatMap((l) => (json[l] || []).map((x, i) => (idOf(l, x, i) === first ? [l, i] : null)).filter(Boolean));
|
|
347
|
+
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 });
|
|
348
|
+
if (hits.length) return { path: [...hits[0], ...rest(1)], entry: hits[0] };
|
|
349
|
+
const known = knownOf(json);
|
|
350
|
+
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 });
|
|
351
|
+
const top = Object.keys(schema('assembly').properties);
|
|
352
|
+
if (!entry && top.includes(first)) return { path: rest(0), entry: null };
|
|
353
|
+
const ids = ID_LISTS.flatMap((l) => (json[l] || []).map((x, i) => idOf(l, x, i))).filter(Boolean);
|
|
354
|
+
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 });
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Set at a path, making the objects it passes through where they are missing; a string where an object is asked for
|
|
358
|
+
// stands for its kind ("join": "blind" is { "kind": "blind" }), so frame.join.fitting=printed keeps the blind
|
|
359
|
+
function setDeep(text, p, value) {
|
|
360
|
+
for (let k = 1; k < p.length; k++) {
|
|
361
|
+
const up = p.slice(0, k), v = getAt(text, up);
|
|
362
|
+
if (v === undefined) {
|
|
363
|
+
if (typeof p[k] === 'number') throw new CadError('edit.address', `there is no ${up.join('.')} list to set entry ${p[k]} of`);
|
|
364
|
+
text = setAt(text, up, {});
|
|
365
|
+
} else if (typeof v === 'string' && typeof p[k] === 'string') text = setAt(text, up, { kind: v });
|
|
366
|
+
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]}`);
|
|
367
|
+
}
|
|
368
|
+
return setAt(text, p, value);
|
|
369
|
+
}
|
|
370
|
+
const shownPath = (p) => p.map((k) => (typeof k === 'string' && /[.[\]"]/.test(k) ? `[${JSON.stringify(k)}]` : `.${k}`)).join('').replace(/^\./, '');
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Change fields of an assembly: { address: value }, each address an entry's field by its id (x1.at, hinge.max) or its
|
|
374
|
+
* place (joins.3.kind, fits.0.min), or a top-level field (title, frame.join, frame.inside).
|
|
375
|
+
* @param {string} ref project/assembly @param {Record<string, any>} changes @param {{ dryRun?: boolean }} [options]
|
|
376
|
+
*/
|
|
377
|
+
export function setInAssembly(ref, changes, { dryRun = false } = {}) {
|
|
378
|
+
const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8');
|
|
379
|
+
let text = before;
|
|
380
|
+
const done = [], touched = [];
|
|
381
|
+
for (const [address, value] of Object.entries(changes)) {
|
|
382
|
+
const { path: p, entry } = addressPath(JSON.parse(text), address, { ref, file });
|
|
383
|
+
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 });
|
|
384
|
+
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)
|
|
385
|
+
try { text = setDeep(text, p, value); } catch (e) { throw e instanceof CadError ? Object.assign(e, { file }) : new CadError('edit.address', `${address}: ${e.message}`, { file }); }
|
|
386
|
+
done.push({ op: 'set', path: shownPath(p), ...(was !== undefined ? { before: was } : {}), after: value });
|
|
387
|
+
if (entry) touched.push(entry);
|
|
388
|
+
}
|
|
389
|
+
return finish({ ref, file, before, text, kind: 'assembly', changes: done, dryRun, touched });
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Every place in an assembly that names an id (as itself, or as id.anchor, id.face@mm, id@pose): [{ path, value }].
|
|
393
|
+
// Values that never name an entry (kinds, profiles, screws, notes ..) are passed over.
|
|
394
|
+
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']);
|
|
395
|
+
function namesOf(json, id, { prefix = false } = {}) {
|
|
396
|
+
const hit = (s) => typeof s === 'string' && (s === id || s.startsWith(`${id}.`) || s.startsWith(`${id}@`) || (prefix && s.startsWith(`${id}-`)));
|
|
397
|
+
const out = [];
|
|
398
|
+
const walk = (v, p) => {
|
|
399
|
+
if (typeof v === 'string') { if (hit(v)) out.push({ path: p, value: v }); return; }
|
|
400
|
+
if (Array.isArray(v)) { v.forEach((x, i) => walk(x, [...p, i])); return; }
|
|
401
|
+
if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) {
|
|
402
|
+
if (NOT_NAMES.has(k)) continue;
|
|
403
|
+
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; } }
|
|
404
|
+
walk(x, [...p, k]);
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
walk(json, []);
|
|
408
|
+
return out;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Remove from an assembly: an entry by its id or place (x1, joins.3), or a field (x1.rotate, frame.feet). Refused by
|
|
413
|
+
* name where other entries name what goes (a join's beam, a fit's part, a load's anchor), unless withRefs, which removes
|
|
414
|
+
* those entries too and lists them; and where taking out a guide without an id would rename the guides after it.
|
|
415
|
+
* @param {string} ref project/assembly @param {string} address @param {{ withRefs?: boolean, dryRun?: boolean }} [options]
|
|
416
|
+
*/
|
|
417
|
+
export function removeFromAssembly(ref, address, { withRefs = false, dryRun = false } = {}) {
|
|
418
|
+
const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), json = JSON.parse(before);
|
|
419
|
+
const { path: p, entry } = addressPath(json, address, { ref, file });
|
|
420
|
+
const was = getAt(before, p);
|
|
421
|
+
if (was === undefined) throw new CadError('edit.address', `${ref} has no ${address} to remove`, { file, path: address });
|
|
422
|
+
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 });
|
|
423
|
+
const changes = [{ op: 'remove', path: shownPath(p), before: was }], drop = [p];
|
|
424
|
+
if (entry && p.length === 2) {
|
|
425
|
+
const [list, i] = entry, id = idOf(list, json[list][i], i);
|
|
426
|
+
// a guide with no id is g1, g2 .. by its place, so taking out any guide before one renames it, whether the guide
|
|
427
|
+
// taken out has an id or not
|
|
428
|
+
const renamed = list === 'guides' ? json[list].map((g, k) => (k > i && g?.id == null ? k : -1)).filter((k) => k >= 0) : [];
|
|
429
|
+
if (renamed.length)
|
|
430
|
+
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 });
|
|
431
|
+
const refs = id ? namesOf({ ...json, [list]: json[list].map((x, k) => (k === i ? null : x)) }, id, { prefix: list === 'guides' }) : [];
|
|
432
|
+
if (refs.length) {
|
|
433
|
+
// each name as what holds it: a list entry, or a pose's or a support's key
|
|
434
|
+
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()];
|
|
435
|
+
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(' ')})` : ''}`; });
|
|
436
|
+
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 });
|
|
437
|
+
for (const h of holders) { drop.push(h); changes.push({ op: 'remove', path: shownPath(h), before: getAt(before, h), because: `names ${id}` }); }
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
// the last first, so the places of the others hold
|
|
441
|
+
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; };
|
|
442
|
+
let text = before;
|
|
443
|
+
for (const d of [...new Map(drop.map((x) => [shownPath(x), x])).values()].sort(order)) text = removeAt(text, d);
|
|
444
|
+
return finish({ ref, file, before, text, kind: 'assembly', changes, dryRun, touched: [] });
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Move an item or a guide: an item to a point (--at x,y,z: a beam placed by its ends moves both, as one) or to an
|
|
449
|
+
* address on a beam (--to x1.top@50%), turned by rotate; a guide to another face (--to x3.top) or along it (--at 100).
|
|
450
|
+
* @param {string} ref project/assembly @param {string} id @param {{ at?: any, to?: string, rotate?: any[], dryRun?: boolean }} move
|
|
451
|
+
*/
|
|
452
|
+
export function moveInAssembly(ref, id, { at, to, rotate, dryRun = false } = {}) {
|
|
453
|
+
const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), json = JSON.parse(before);
|
|
454
|
+
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 });
|
|
455
|
+
const { entry } = addressPath(json, id, { ref, file, entry: true });
|
|
456
|
+
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 });
|
|
457
|
+
const [list, i] = entry, x = json[list][i], base = [list, i], sets = [];
|
|
458
|
+
if (list === 'guides') {
|
|
459
|
+
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 });
|
|
460
|
+
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)]); }
|
|
461
|
+
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)]); }
|
|
462
|
+
} else {
|
|
463
|
+
const ends = Array.isArray(x.from) && Array.isArray(x.to);
|
|
464
|
+
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 });
|
|
465
|
+
if (at != null && ends) {
|
|
466
|
+
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 });
|
|
467
|
+
const d = at.map((v, k) => v - x.from[k]);
|
|
468
|
+
sets.push([['from'], at], [['to'], x.to.map((v, k) => +(v + d[k]).toFixed(6))]);
|
|
469
|
+
} else if (at != null) {
|
|
470
|
+
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 });
|
|
471
|
+
sets.push([['at'], at]);
|
|
472
|
+
}
|
|
473
|
+
if (to != null) sets.push([['at'], String(to)]);
|
|
474
|
+
if (rotate != null) sets.push([['rotate'], rotate]);
|
|
475
|
+
}
|
|
476
|
+
let text = before;
|
|
477
|
+
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 }; });
|
|
478
|
+
return finish({ ref, file, before, text, kind: 'assembly', changes, dryRun, touched: [entry] });
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
const NAME = /^[a-z][a-z0-9-]*$/;
|
|
482
|
+
// A new file laid out as cad's edits lay one out: two spaces, short lists of numbers on one line
|
|
483
|
+
const laidOut = (json) => Object.entries(json).reduce((t, [k, v]) => setAt(t, [k], v), '{}\n');
|
|
484
|
+
const projectFile = (project) => path.join(paths.project(project), 'project.json');
|
|
485
|
+
// A project's own fields checked beyond the schema: its printer must be a rule set, and its material a plastic printed
|
|
486
|
+
// fittings can be sized from (pla, petg, or a rule set with strength, modulus and density), as its schema says: every
|
|
487
|
+
// frame command reads it (lib/fittings.mjs's plasticOf) as it builds the assembly's joins, guides and panels
|
|
488
|
+
function projectFindings(json, project) {
|
|
489
|
+
const out = [];
|
|
490
|
+
if (json.printer != null) {
|
|
491
|
+
let set = null; try { set = peekRuleSet(json.printer); } catch {}
|
|
492
|
+
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' });
|
|
493
|
+
out.push({ level: 'pass', text: `prints are checked against ${json.printer}`, code: 'project.printer' });
|
|
494
|
+
}
|
|
495
|
+
if (json.material != null) {
|
|
496
|
+
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' }); }
|
|
497
|
+
catch (e) { throw new CadError('project.material', e.message, { path: 'material' }); }
|
|
498
|
+
}
|
|
499
|
+
return out;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Make a project: projects/<name>/project.json with its name, and title, description, material (PLA unless given) and
|
|
504
|
+
* printer where given. Run again on a project that is there with the same fields, it changes nothing and says so (a
|
|
505
|
+
* guide's step can be run twice). Refused by name: a name not in lower case with dashes, a project already there given
|
|
506
|
+
* no fields or fields that differ from its own (cad set changes those), a printer with no rule set.
|
|
507
|
+
* @param {string} name @param {{ title?: string, description?: string, material?: string, printer?: string, dryRun?: boolean }} [fields]
|
|
508
|
+
*/
|
|
509
|
+
export function newProject(name, { dryRun = false, ...fields } = {}) {
|
|
510
|
+
if (!NAME.test(String(name || ''))) throw new CadError('edit.name', `a project's name is lower case, with dashes (got ${JSON.stringify(name)})`);
|
|
511
|
+
const file = projectFile(name);
|
|
512
|
+
const given = Object.fromEntries(Object.entries(fields).filter(([, v]) => v != null));
|
|
513
|
+
if (fs.existsSync(file)) {
|
|
514
|
+
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 });
|
|
515
|
+
return { file, written: false, ...(dryRun ? { dryRun: true } : {}), changes: [], findings: [sameProject(name, given)] };
|
|
516
|
+
}
|
|
517
|
+
const json = { $schema: 'https://jonibach.github.io/rulecad/schemas/project.schema.json', name, ...given, material: given.material ?? 'PLA', objects: [] };
|
|
518
|
+
const text = laidOut(json);
|
|
519
|
+
return finish({ file, before: '', text, kind: 'project', changes: [{ op: 'make', path: `projects/${name}/project.json`, after: json }], dryRun, findings: projectFindings(json, name) });
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// A project that is there, held to the fields given for it (a material by its name in any case, PLA where it gives
|
|
523
|
+
// none): a pass finding where each is already its own, refused by name where one differs, naming the cad set that
|
|
524
|
+
// changes it
|
|
525
|
+
function sameProject(name, given) {
|
|
526
|
+
const file = projectFile(name), own = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
527
|
+
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);
|
|
528
|
+
const differ = Object.entries(given).filter(([k, v]) => !same(k, v)), was = (k) => (ownOf(k) === undefined ? `no ${k}` : `${k} ${ownOf(k)}`);
|
|
529
|
+
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 });
|
|
530
|
+
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)])) };
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Change a project's own fields: title, description, material, printer, filaments.<name>.slot. Its objects are kept by
|
|
535
|
+
* cad new <project>/<object>, and refused here. @param {string} project @param {Record<string, any>} changes @param {{ dryRun?: boolean }} [options]
|
|
536
|
+
*/
|
|
537
|
+
export function setProject(project, changes, { dryRun = false } = {}) {
|
|
538
|
+
const file = projectFile(project);
|
|
539
|
+
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 });
|
|
540
|
+
const before = fs.readFileSync(file, 'utf8');
|
|
541
|
+
let text = before;
|
|
542
|
+
const done = [], fields = Object.keys(schema('project').properties).filter((k) => !['$schema', 'objects', 'name'].includes(k));
|
|
543
|
+
for (const [address, value] of Object.entries(changes)) {
|
|
544
|
+
const p = segmentsOf(address);
|
|
545
|
+
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 });
|
|
546
|
+
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 });
|
|
547
|
+
if (!fields.includes(p[0])) throw new CadError('edit.address', `a project has no field "${p[0]}" (fields: ${fields.join(', ')})`, { file, path: p[0] });
|
|
548
|
+
const was = getAt(text, p);
|
|
549
|
+
text = setDeep(text, p, value);
|
|
550
|
+
done.push({ op: 'set', path: shownPath(p), ...(was !== undefined ? { before: was } : {}), after: value });
|
|
551
|
+
}
|
|
552
|
+
return finish({ file, before, text, kind: 'project', changes: done, dryRun, findings: projectFindings(JSON.parse(text), project) });
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Make an assembly: projects/<project>/assemblies/<name>.json, empty (items: []) or a generated frame, checked as it
|
|
557
|
+
* is made; its project is made first where there is none, with the material and printer given for it (checked as cad new
|
|
558
|
+
* <project> checks them). Refused by name: an assembly already there, a kind that is not fit, a frame the generator
|
|
559
|
+
* refuses, a material or printer for a project that is already there with another (cad set <project> changes those).
|
|
560
|
+
* @param {string} ref project/assembly
|
|
561
|
+
* @param {{ title?: string, kind?: string, description?: string, frame?: object, fields?: Record<string, any>, project?: { material?: string, printer?: string }, dryRun?: boolean }} [fields]
|
|
562
|
+
*/
|
|
563
|
+
export function newAssembly(ref, { title, kind = 'fit', description, frame, fields = {}, project: forProject = {}, dryRun = false } = {}) {
|
|
564
|
+
const [project, name] = String(ref || '').split('/');
|
|
565
|
+
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)})`);
|
|
566
|
+
const file = path.join(paths.project(project), 'assemblies', `${name}.json`);
|
|
567
|
+
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 });
|
|
568
|
+
const projectFields = Object.fromEntries(Object.entries(forProject || {}).filter(([, v]) => v != null)), hasProject = fs.existsSync(projectFile(project));
|
|
569
|
+
const same = hasProject && Object.keys(projectFields).length ? sameProject(project, projectFields) : null; // refused where one differs
|
|
570
|
+
if (!hasProject) newProject(project, { ...projectFields, dryRun: true }); // its material and printer refused before anything is written
|
|
571
|
+
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 });
|
|
572
|
+
const json = { $schema: 'https://jonibach.github.io/rulecad/schemas/assembly.schema.json', title: title ?? name, kind, ...(description ? { description } : {}), ...(frame ? { frame } : { items: [] }) };
|
|
573
|
+
// its other fields as cad set takes them, before it is checked: a portal's supports, its loads
|
|
574
|
+
let text = laidOut(json);
|
|
575
|
+
const top = Object.keys(schema('assembly').properties);
|
|
576
|
+
for (const [address, value] of Object.entries(fields)) {
|
|
577
|
+
const p = segmentsOf(address);
|
|
578
|
+
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 });
|
|
579
|
+
text = setDeep(text, p, value);
|
|
580
|
+
}
|
|
581
|
+
const args = { ref, file, before: '', text, kind: 'assembly', changes: [{ op: 'make', path: `projects/${project}/assemblies/${name}.json`, after: JSON.parse(text) }], touched: [] };
|
|
582
|
+
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
|
|
583
|
+
const made = [];
|
|
584
|
+
if (!hasProject) made.push(newProject(project, { ...projectFields, dryRun }));
|
|
585
|
+
const r = finish({ ...args, dryRun });
|
|
586
|
+
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] };
|
|
587
|
+
}
|
package/lib/errors.mjs
CHANGED
|
@@ -22,7 +22,7 @@ export function located(e, file, code) {
|
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
/** An error as plain data: { code, message, file?, line?, path? }. @param {any} e */
|
|
25
|
-
export const errorData = (e) => ({ code: e?.code || 'error', message: e?.message || String(e), ...(e?.file ? { file: e.file } : {}), ...(e?.line ? { line: e.line } : {}), ...(e?.path ? { path: e.path } : {}) });
|
|
25
|
+
export const errorData = (e) => ({ code: e?.code || 'error', message: e?.message || String(e), ...(e?.file ? { file: e.file } : {}), ...(e?.line ? { line: e.line } : {}), ...(e?.path ? { path: e.path } : {}), ...(e?.refs ? { refs: e.refs } : {}) });
|
|
26
26
|
|
|
27
27
|
/** The closest name to a typo, one or two letters out, or null. @param {string} word @param {string[]} names */
|
|
28
28
|
export function near(word, names) {
|
package/lib/fasten.mjs
CHANGED
|
@@ -668,7 +668,7 @@ export function fastenOf(s, worlds, opts = {}) {
|
|
|
668
668
|
// The far end: the hole in the last part, from its mouth; or, into a slot, the slot nut under its lips
|
|
669
669
|
const first = B.segs.find((seg) => seg.solid || seg.hole);
|
|
670
670
|
let end = null;
|
|
671
|
-
const mh = !slotAt && first?.solid ? onMount(O, D) : null;
|
|
671
|
+
const mh = !slotAt && (first?.solid || (first?.hole && drive && drive === boughtMount)) ? onMount(O, D) : null; // (a bought part may draw its tapped holes: a rail's carriage)
|
|
672
672
|
if (slotAt) end = slotEnd(s, slotAt, slotNutM, { B, O, D, x, fx, cl, clr, say, sc });
|
|
673
673
|
else if (mh) {
|
|
674
674
|
if (mh.thread !== fx.thread) { say('fasten.end', 'fail', `${x.into}'s mounting holes are ${mh.thread} threads, and the screw is ${fx.thread}: use ${an(mh.thread)} ${mh.thread} screw`); bad = true; }
|