@rulecad/cad 0.4.1 → 0.5.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 +9 -1
- package/README.md +19 -0
- package/bin/cad.mjs +117 -96
- package/lib/assembly.mjs +95 -30
- package/lib/design.mjs +50 -69
- package/lib/edit.mjs +73 -0
- package/lib/errors.mjs +25 -0
- package/lib/explain.mjs +40 -0
- package/lib/host.mjs +58 -0
- package/lib/jsonedit.mjs +84 -0
- package/lib/layout.mjs +4 -4
- package/lib/links.mjs +75 -0
- package/lib/parts.mjs +42 -0
- package/lib/rules.mjs +4 -5
- package/lib/sandbox-hooks.mjs +32 -0
- package/lib/sandbox-preload.mjs +10 -0
- package/lib/sandbox-run.mjs +23 -0
- package/lib/sandbox.mjs +65 -0
- package/lib/schema.mjs +69 -0
- package/lib/workspace.mjs +4 -4
- package/package.json +6 -5
- package/schemas/assembly.schema.json +113 -0
- package/schemas/layout.schema.json +33 -0
- package/schemas/object.schema.json +76 -0
- package/schemas/rules.schema.json +35 -0
- package/templates/object.json +1 -0
package/AGENTS.md
CHANGED
|
@@ -29,7 +29,11 @@ variable says which rule it comes from. Follow these steps; they're what makes a
|
|
|
29
29
|
## Changing a design
|
|
30
30
|
1. `npx cad history <project>/<object>` first: read the print log. A failed print is the reason for most changes:
|
|
31
31
|
fix the rule or variable it points at (a measured fit beats a community rule).
|
|
32
|
-
2. Change, then check, preview and look, as for a new part.
|
|
32
|
+
2. Change, then check, preview and look, as for a new part. Change values with `npx cad set <project>/<object>
|
|
33
|
+
name=value` and assemblies with `npx cad add fit|joint|item|pose …`: they keep the file's layout and refuse an edit
|
|
34
|
+
that breaks it. `npx cad values` lists an object's numbers; `npx cad why <project>/<object>.<name>` shows what a
|
|
35
|
+
value depends on, down to the rules (estimates marked). `--json` on check, values and why gives data to act on:
|
|
36
|
+
each finding has a code, its numbers and where it is.
|
|
33
37
|
3. `npx cad release <project>/<object> -m "what changed, for the person" --dry-run` shows the bump and why. If it's
|
|
34
38
|
major, tell the person which interface values changed: earlier prints may no longer fit.
|
|
35
39
|
4. Release only when the person agrees. Don't use `--force` without asking.
|
|
@@ -40,6 +44,10 @@ variable says which rule it comes from. Follow these steps; they're what makes a
|
|
|
40
44
|
- Holes and slots get the printer's hole compensation; parts that slide together get its fit clearance. Chamfer
|
|
41
45
|
bottom edges.
|
|
42
46
|
- An overhang warning means supports: say so in `orientation`, or change the shape or orientation.
|
|
47
|
+
- Use the print-aware features in `v.shapes` before drawing your own: `countersink`, `teardropHole`, `nutPocket`,
|
|
48
|
+
`crushRibs`, `wallOpening` print without supports as drawn. Use `v.ops.union/subtract/intersect` for booleans: the
|
|
49
|
+
workspace can switch them to Manifold (faster, watertight) without touching the design.
|
|
50
|
+
- Designs run sandboxed: they may import only `@jscad/modeling`, `@rulecad/shapes` and files in their project.
|
|
43
51
|
- Something printed under the part and removed afterwards is a named `support` part (`return { cap, pillar }`, both
|
|
44
52
|
described in the .json's `parts`), not part of the shape. Look at `cad preview --explode` too.
|
|
45
53
|
|
package/README.md
CHANGED
|
@@ -224,6 +224,25 @@ other items' variables, so a keycap can sit exactly where its slot meets the swi
|
|
|
224
224
|
- **fit** assemblies check how parts go together: no overlaps (unless a fit allows a press fit with a negative
|
|
225
225
|
`min`), and the closest gap for each `fit` within its range. Supports are left out: they're snipped off first.
|
|
226
226
|
Objects with `"role": "reference"` (the MX switch) model things you don't print: drawn faint, never exported.
|
|
227
|
+
- **Hosts:** the core (resolve, build, check) reads and writes through a host (`lib/host.mjs`): Node's file system
|
|
228
|
+
for the CLI, or `memoryHost(files)`, a workspace in memory (reading the tool's own packages from disk), for tests
|
|
229
|
+
and, later, a browser. `useHost(h)` switches. The model-link building (`lib/links.mjs`) and the joints' data for the
|
|
230
|
+
page (`motionData`) are in the library too, so other programs make the same links without the CLI.
|
|
231
|
+
- **Engines:** designs get `v.ops` (union, subtract, intersect): JSCAD's booleans by default, Manifold's (faster,
|
|
232
|
+
watertight; `npm install manifold-3d`) with `"engine": "manifold"` in the object's JSON or `CAD_ENGINE=manifold`.
|
|
233
|
+
- **Sandbox:** a JSCAD design runs in a separate Node process under Node's permission model: it can read the
|
|
234
|
+
workspace and the tool's packages, but can't write files, start programs or workers, or load addons, and it may
|
|
235
|
+
import only `@jscad/modeling`, `@rulecad/shapes` and files in its own project (no `node:` modules, so no network;
|
|
236
|
+
`fetch` is gone too). It gets its values as data and returns its parts. A workspace that trusts its designs sets
|
|
237
|
+
`"sandbox": false` in cad.config.json (or `CAD_TRUST=1`); on Node 18, without the permission model, designs run in
|
|
238
|
+
the tool's process. Board designs (engine pcb) run in the tool's process, with the board engine.
|
|
239
|
+
- **Units:** `cad check` warns where an expression mixes units (millimetres added to degrees, a sine of a length) or
|
|
240
|
+
comes to another unit than its variable says (mm × mm with unit mm). Counts (keys, u, rows) are plain numbers.
|
|
241
|
+
- **Progress:** `--progress` shows what a long check or sweep is building; a program passes `progress` to
|
|
242
|
+
`buildAssembly` and `sweep` and gets `{ stage, item | joint, … }` events.
|
|
243
|
+
- **Near an anchor:** a fit can name an item's faces near one of its anchors, `"a": "case@pivot"` (with `"within": 6`,
|
|
244
|
+
mm; 10 by default): the pocket round a pivot rather than the whole case. A fit's finding says where its closest gap
|
|
245
|
+
is (`at` in `--json`) and which anchor that's nearest (`… 0.4 mm from link@mount`).
|
|
227
246
|
- **plate** assemblies lay objects out on the bed: they're checked as one print and `export` writes one 3MF with an
|
|
228
247
|
object per part. Supports are kept.
|
|
229
248
|
- **Turning:** `"rotate": [0, 180, 0]` turns an item (degrees about x, y, z, in that order) about its own origin
|
package/bin/cad.mjs
CHANGED
|
@@ -12,14 +12,14 @@ import { git, tags, bump, bigger, newer, compare, snapshot, materialise, files,
|
|
|
12
12
|
import { check } from '@rulecad/printcheck';
|
|
13
13
|
import { preview } from '../lib/preview.mjs';
|
|
14
14
|
import { measure, match } from '../lib/meshcmd.mjs';
|
|
15
|
-
import { isAssembly, buildAssembly, checkAssembly, shapes, sweep } from '../lib/assembly.mjs';
|
|
16
|
-
import {
|
|
15
|
+
import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, motionData } from '../lib/assembly.mjs';
|
|
16
|
+
import { valuesOf, why } from '../lib/explain.mjs';
|
|
17
|
+
import { errorData } from '../lib/errors.mjs';
|
|
18
|
+
import { schemaFindings } from '../lib/schema.mjs';
|
|
19
|
+
import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
|
|
17
20
|
import { threemf, slotOf } from '../lib/threemf.mjs';
|
|
21
|
+
import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
|
|
18
22
|
|
|
19
|
-
// The project's filaments: { base: { slot: 1, … }, legend: { slot: 2, … } } in project.json
|
|
20
|
-
const filaments = (project) => JSON.parse(fs.readFileSync(path.join(paths.project(project), 'project.json'), 'utf8')).filaments || {};
|
|
21
|
-
// The filaments in AMS slot order, for the print file: [{ colour }, …], slot 1 first
|
|
22
|
-
const slots = (fil) => { const out = []; for (const f of Object.values(fil)) out[(f.slot || 1) - 1] = f; return Array.from(out, (f) => f || {}); };
|
|
23
23
|
// What the print file asks of the AMS: which filament each kind of part prints in
|
|
24
24
|
function filamentNotes(parts, fil) {
|
|
25
25
|
const used = [...new Set(parts.map((p) => p.filament || 'base'))];
|
|
@@ -31,13 +31,6 @@ function filamentNotes(parts, fil) {
|
|
|
31
31
|
// --open: the 3MF in Bambu Studio (macOS), else whatever opens .3mf files
|
|
32
32
|
const openInSlicer = (f) => (process.platform === 'darwin' ? execFileSync('open', ['-a', 'Bambu Studio', f])
|
|
33
33
|
: execFileSync(process.platform === 'win32' ? 'explorer' : 'xdg-open', [f]));
|
|
34
|
-
const VIEW = process.env.CAD_VIEW_URL || config.viewUrl;
|
|
35
|
-
// A link to the model page; one the page would turn away is an error here, not when someone opens it
|
|
36
|
-
async function linkTo(model) {
|
|
37
|
-
const errors = checkLink(model.shapes ? expand(model) : model);
|
|
38
|
-
if (errors.length) throw new Error(`no link: ${errors[0]}`);
|
|
39
|
-
return `${VIEW}#m=${await encode(model)}`;
|
|
40
|
-
}
|
|
41
34
|
|
|
42
35
|
const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
43
36
|
|
|
@@ -45,7 +38,11 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
45
38
|
cad import-kle <file> <project>/<name> a keyboard layout from keyboard-layout-editor.com, into layouts/
|
|
46
39
|
cad agents AGENTS.md: how an AI agent should design in this workspace
|
|
47
40
|
cad rules <project>/<object> every variable: value, the rule behind it, its source
|
|
48
|
-
cad
|
|
41
|
+
cad values <project>/<object> [names…] the object's variables, resolved [--json]
|
|
42
|
+
cad set <project>/<object> name=value … change variables, keeping the file's layout [--unit, --rule, --label, --new to add one]
|
|
43
|
+
cad add fit|joint|item|loop|pose <project>/<assembly> --a … --b … --min … add to an assembly, keeping its layout
|
|
44
|
+
cad why <project>/<object>.<name> what a value reads, down to the rules and their sources [--json] [--depth N]
|
|
45
|
+
cad check <project>/<object> raw numbers in the design, then printability (exit 1 on a failure) [--json: findings as data]
|
|
49
46
|
cad preview <project>/<object> four views as a PNG in .preview/ (prints the path)
|
|
50
47
|
cad export <project>/<object> a 3MF for Bambu Studio in exports/ [--open: open it in Bambu Studio]
|
|
51
48
|
cad show <project>/<object> the model on display through your show target, with its rules [--ttl 10m]
|
|
@@ -90,14 +87,23 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
90
87
|
const args = process.argv.slice(2);
|
|
91
88
|
// --name value, or -m for one-letter names
|
|
92
89
|
const opt = (k) => { const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`)); return i >= 0 ? (args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : true) : undefined; };
|
|
90
|
+
// The arguments that aren't options or an option's value: cad values keyboard/case depth width --json
|
|
91
|
+
const positional = () => args.filter((a, i) => !a.startsWith('--') && !(i > 0 && args[i - 1].startsWith('--') && !['--json', '--long', '--short', '--md', '--all', '--explode'].includes(args[i - 1])));
|
|
93
92
|
const sets = () => Object.fromEntries(String(opt('set') || '').split(',').filter(Boolean).map((p) => p.split('=').map((s) => s.trim())));
|
|
94
93
|
const suffix = (set) => Object.entries(set).map(([k, v]) => `-${k}=${v}`).join('');
|
|
95
94
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
95
|
+
// --progress: what a long build or sweep is doing, on one line of stderr
|
|
96
|
+
const showProgress = (e) => {
|
|
97
|
+
if (!opt('progress')) return;
|
|
98
|
+
process.stderr.write(`\r\x1b[K${e.stage === 'sweep' ? `sweeping ${e.joint} ${e.step}/${e.steps}` : `building ${e.item} (${e.done})`}`);
|
|
99
|
+
};
|
|
100
|
+
// Findings: as text (a mark and the words), or with --json as data: { ...about, findings: [{ level, text, code, values, refs, at }] }
|
|
101
|
+
function report(findings, about = {}) {
|
|
102
|
+
if (opt('json')) console.log(JSON.stringify({ ...about, findings }, null, 2));
|
|
103
|
+
else { const mark = { pass: '✓', warn: '!', fail: '✗', info: '·' }; for (const r of findings) console.log(` ${mark[r.level]} ${r.text}`); }
|
|
99
104
|
return findings.some((r) => r.level === 'fail');
|
|
100
105
|
}
|
|
106
|
+
const say = (...a) => { if (!opt('json')) console.log(...a); }; // text output that --json leaves out
|
|
101
107
|
|
|
102
108
|
async function main() {
|
|
103
109
|
const [cmd, ref] = args;
|
|
@@ -153,6 +159,9 @@ async function main() {
|
|
|
153
159
|
if (cmd === 'history') return history(ref);
|
|
154
160
|
if (cmd === 'diff') return diff(locate(ref), args[2], args[3] && !args[3].startsWith('--') ? args[3] : null);
|
|
155
161
|
if (cmd === 'printed') return printed(locate(ref));
|
|
162
|
+
if (cmd === 'why') return explainValue(ref);
|
|
163
|
+
if (cmd === 'set') return editVariables(ref);
|
|
164
|
+
if (cmd === 'add') return editAssembly(args[1], args[2]);
|
|
156
165
|
if (isAssembly(ref)) return assembly(cmd, ref);
|
|
157
166
|
const [base, at] = ref.split('@');
|
|
158
167
|
const d = at ? materialise(locate(base), at) : locate(ref), set = sets();
|
|
@@ -171,22 +180,35 @@ async function main() {
|
|
|
171
180
|
return;
|
|
172
181
|
}
|
|
173
182
|
|
|
183
|
+
if (cmd === 'values') {
|
|
184
|
+
const list = valuesOf(b, positional().slice(2));
|
|
185
|
+
if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, values: list }, null, 2));
|
|
186
|
+
for (const v of list) console.log(`${v.name.padEnd(18)} ${`${fmt(v.value)} ${v.unit}`.padEnd(14)} ${v.expr ? `= ${v.expr}` : ''}`);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
|
|
174
190
|
if (cmd === 'rules') {
|
|
175
191
|
for (const e of b.entries) console.log(`${e.name.padEnd(18)} ${`${fmt(e.value)} ${e.unit || ''}`.padEnd(14)} ${e.expr ? `= ${e.expr} ` : ''}${e.rule || ''}${e.source ? ` [${e.kind ? `${e.kind}: ` : ''}${e.source}]` : ''}${e.set ? ' (set)' : ''}`);
|
|
176
192
|
return;
|
|
177
193
|
}
|
|
178
194
|
|
|
179
195
|
if (cmd === 'check') {
|
|
180
|
-
|
|
181
|
-
const raw = lint(fs.readFileSync(d.js, 'utf8'));
|
|
196
|
+
say(`${title} ${version}${Object.keys(set).length ? ` (${suffix(set).slice(1)})` : ''}`);
|
|
197
|
+
const raw = lint(fs.readFileSync(d.js, 'utf8')), file = path.relative(WS, d.js);
|
|
198
|
+
// The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
|
|
199
|
+
const own = (f) => path.relative(WS, f), ruleFiles = (b.object.uses || []).filter((u) => !u.includes('/')).map((u) => path.join(WS, 'rules', `${u}.json`)).filter((f) => fs.existsSync(f));
|
|
200
|
+
const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f)))];
|
|
182
201
|
const failed = report([
|
|
183
|
-
|
|
202
|
+
...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
|
|
203
|
+
...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
|
|
204
|
+
raw.length ? { level: 'fail', text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}`, code: 'lint.numbers', refs: { file, numbers: raw } }
|
|
205
|
+
: { level: 'pass', text: 'every measurement is a variable', code: 'lint.numbers', refs: { file } },
|
|
184
206
|
...(b.object.role === 'reference'
|
|
185
|
-
? [{ level: 'pass', text: `a reference (${(await import('@rulecad/printcheck')).bounds(b.triangles).size.map(fmt).join(' × ')} mm), not printed: no print checks
|
|
207
|
+
? [{ level: 'pass', text: `a reference (${(await import('@rulecad/printcheck')).bounds(b.triangles).size.map(fmt).join(' × ')} mm), not printed: no print checks`, code: 'print.reference' }]
|
|
186
208
|
: check(b.triangles, printer(b, d), { parts: b.parts })),
|
|
187
|
-
]);
|
|
188
|
-
if (b.object.orientation)
|
|
189
|
-
if (b.parts.length > 1)
|
|
209
|
+
], { object: `${d.project}/${d.name}`, title, version, ...(Object.keys(set).length ? { set } : {}), orientation: b.object.orientation, parts: b.parts.map((p) => ({ name: p.name, role: p.role || 'part' })) });
|
|
210
|
+
if (b.object.orientation) say(` orientation: ${b.object.orientation}`);
|
|
211
|
+
if (b.parts.length > 1) say(` parts: ${b.parts.map((p) => `${p.name}${p.role === 'support' ? ' (support)' : ''}`).join(', ')}`);
|
|
190
212
|
process.exitCode = failed ? 1 : 0;
|
|
191
213
|
return;
|
|
192
214
|
}
|
|
@@ -227,12 +249,66 @@ async function main() {
|
|
|
227
249
|
// ---------- boards ----------
|
|
228
250
|
// A circuit board (engine pcb): its checks are the board's (design rules, the fab's limits, the matrix), its preview is
|
|
229
251
|
// drawn from above as well as in 3D, and its export is the fab's zip plus KiCad's files, not a print file.
|
|
252
|
+
// cad set <project>/<object> name=value … [--unit mm] [--rule "…"] [--label "…"] [--new]: change (or add) variables,
|
|
253
|
+
// keeping the file's layout; refused if the variables wouldn't resolve
|
|
254
|
+
async function editVariables(ref) {
|
|
255
|
+
const pairs = positional().slice(2);
|
|
256
|
+
if (!ref || !pairs.length || pairs.some((p) => !p.includes('='))) throw new Error('usage: cad set <project>/<object> name=value [name=value …] [--unit mm] [--rule "why"] [--label "Label"] [--new]');
|
|
257
|
+
const extra = Object.fromEntries(['unit', 'rule', 'label'].filter((k) => typeof opt(k) === 'string').map((k) => [k, opt(k)]));
|
|
258
|
+
const changes = Object.fromEntries(pairs.map((p) => { const i = p.indexOf('='); return [p.slice(0, i).trim(), { value: parseValue(p.slice(i + 1).trim()), ...extra }]; }));
|
|
259
|
+
const r = await setVariables(ref, changes, { create: !!opt('new') });
|
|
260
|
+
if (opt('json')) return console.log(JSON.stringify(r));
|
|
261
|
+
console.log(`set ${r.changed.join(', ')} in ${path.relative(WS, r.file)}`);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// cad add fit|joint|item|loop|pose <project>/<assembly> --key value …: add to an assembly, keeping its layout
|
|
265
|
+
async function editAssembly(what, ref) {
|
|
266
|
+
const list = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => parseValue(x.trim())) : undefined);
|
|
267
|
+
const pick = (keys) => Object.fromEntries(keys.map((k) => [k, typeof opt(k) === 'string' ? parseValue(opt(k)) : undefined]).filter(([, v]) => v !== undefined));
|
|
268
|
+
const text = (keys) => Object.fromEntries(keys.filter((k) => typeof opt(k) === 'string').map((k) => [k, String(opt(k))]));
|
|
269
|
+
let entry;
|
|
270
|
+
if (what === 'fit') entry = { ...text(['a', 'b']), ...pick(['min', 'max']), ...(list('poses') ? { poses: list('poses').map(String) } : {}), ...text(['note', 'label']) };
|
|
271
|
+
else if (what === 'joint') entry = { ...text(['id', 'type', 'parent', 'child', 'label', 'follow']), ...pick(['min', 'max', 'value', 'ratio']) };
|
|
272
|
+
else if (what === 'item') entry = { ...text(['id', 'object', 'assembly', 'variant']), ...(list('at') ? { at: list('at') } : {}), ...(list('rotate') ? { rotate: list('rotate') } : {}),
|
|
273
|
+
...(typeof opt('set') === 'string' ? { set: Object.fromEntries(sets() && Object.entries(sets()).map(([k, v]) => [k, parseValue(v)])) } : {}) };
|
|
274
|
+
else if (what === 'loop') entry = text(['a', 'b', 'label']);
|
|
275
|
+
else if (what === 'pose') {
|
|
276
|
+
const pairs = positional().slice(3);
|
|
277
|
+
if (typeof opt('name') !== 'string' || !pairs.length) throw new Error('usage: cad add pose <project>/<assembly> --name open hinge=90 [joint=value …]');
|
|
278
|
+
entry = { name: opt('name'), values: Object.fromEntries(pairs.map((p) => { const [k, v] = p.split('='); return [k.trim(), v.includes(',') ? v.split(',').map(parseValue) : parseValue(v)]; })) };
|
|
279
|
+
} else throw new Error('usage: cad add fit|joint|item|loop|pose <project>/<assembly> --key value …');
|
|
280
|
+
const r = addToAssembly(ref, what, entry);
|
|
281
|
+
if (opt('json')) return console.log(JSON.stringify({ ...r, added: entry }));
|
|
282
|
+
console.log(`added ${/^[aeiou]/.test(what) ? "an" : "a"} ${what} to ${path.relative(WS, r.file)}`);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// cad why <project>/<object>.<name>: the value, and what it reads, down to the rules (estimates marked)
|
|
286
|
+
async function explainValue(ref) {
|
|
287
|
+
const m = /^([^/]+\/[^.]+)\.(.+)$/.exec(ref || '');
|
|
288
|
+
if (!m) throw new Error('usage: cad why <project>/<object>.<variable> (or .<set>.<rule>), e.g. cad why keyboard/case.depth');
|
|
289
|
+
const tree = await why(m[1], m[2], { depth: Number(opt('depth')) || 12 });
|
|
290
|
+
if (opt('json')) return console.log(JSON.stringify(tree, null, 2));
|
|
291
|
+
const line = (n, pad) => {
|
|
292
|
+
const about = n.kind ? ` [${n.kind === 'estimate' ? 'ESTIMATE' : n.kind}${n.source ? `: ${n.source}` : ''}]` : '';
|
|
293
|
+
const where = n.via ? ` (${n.object})` : '';
|
|
294
|
+
console.log(`${pad}${n.name} = ${fmt(n.value)}${n.unit ? ` ${n.unit}` : ''}${n.expr ? ` = ${n.expr}` : ''}${where}${n.seen ? ' (above)' : ''}${about}`);
|
|
295
|
+
if (!n.seen && n.rule && !pad) console.log(` ${n.rule}`);
|
|
296
|
+
for (const c of n.reads || []) line(c, `${pad} `);
|
|
297
|
+
};
|
|
298
|
+
line(tree, '');
|
|
299
|
+
}
|
|
300
|
+
|
|
230
301
|
async function board(cmd, d, b, { title, version, tag }) {
|
|
231
302
|
const pcb = await pcbEngine(), name = `${d.name}@${version}${tag}`;
|
|
232
303
|
if (cmd === 'check') {
|
|
233
304
|
console.log(`${title} ${version}`);
|
|
234
305
|
const raw = lint(fs.readFileSync(d.js, 'utf8'));
|
|
306
|
+
// The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
|
|
307
|
+
const own = (f) => path.relative(WS, f), ruleFiles = (b.object.uses || []).filter((u) => !u.includes('/')).map((u) => path.join(WS, 'rules', `${u}.json`)).filter((f) => fs.existsSync(f));
|
|
308
|
+
const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f)))];
|
|
235
309
|
const failed = report([
|
|
310
|
+
...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
|
|
311
|
+
...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
|
|
236
312
|
raw.length ? { level: 'fail', text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}` } : { level: 'pass', text: 'every measurement is a variable' },
|
|
237
313
|
...(await pcb.checks(b.circuit, b.values, b.matrix)),
|
|
238
314
|
]);
|
|
@@ -264,23 +340,28 @@ async function board(cmd, d, b, { title, version, tag }) {
|
|
|
264
340
|
// ---------- assemblies ----------
|
|
265
341
|
async function assembly(cmd, ref) {
|
|
266
342
|
const pose = typeof opt('pose') === 'string' ? opt('pose') : undefined;
|
|
267
|
-
const s = await buildAssembly(ref, [], {}, { pose }), a = s.a, title = `${a.title || s.name}${pose ? ` (${pose})` : ''}`;
|
|
343
|
+
const s = await buildAssembly(ref, [], {}, { pose, progress: showProgress }), a = s.a, title = `${a.title || s.name}${pose ? ` (${pose})` : ''}`;
|
|
268
344
|
const versions = [...new Map(s.objects.map((o) => [o.objName, `${o.objName} ${o.version}`])).values()].join(', ');
|
|
269
345
|
const rules = (ns) => Object.fromEntries(Object.keys(loadRuleSet(ns).rules).map((k) => [k, s.num(`${ns}.${k}`)]));
|
|
270
346
|
const printed = s.parts.filter((p) => p.role !== 'reference');
|
|
271
347
|
|
|
272
348
|
if (cmd === 'check') {
|
|
273
|
-
|
|
349
|
+
say(`${title} (${a.kind || 'fit'}: ${versions})`);
|
|
274
350
|
// Each pose (or the one asked for): what's the same in every pose is said once, the rest under the pose's name
|
|
275
351
|
const poses = pose ? [pose] : Object.keys(s.motion.poses);
|
|
352
|
+
const file = path.join(paths.project(s.project), 'assemblies', `${s.name}.json`), layouts = new Set((a.items || []).map((i) => i.repeat?.layout).filter((l) => l && !l.includes('/')));
|
|
353
|
+
const schemaProblems = [...(fs.existsSync(file) ? schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'assembly', path.relative(WS, file)) : []),
|
|
354
|
+
...[...layouts].map((l) => path.join(paths.project(s.project), 'layouts', `${l}.json`)).filter((f) => fs.existsSync(f)).flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'layout', path.relative(WS, f)))];
|
|
276
355
|
let findings = checkAssembly(s);
|
|
277
356
|
if (poses.length > 1) {
|
|
278
357
|
const each = poses.map((p) => [p, checkAssembly(s.at(p))]), same = (x) => each.every(([, list]) => list.some((y) => y.text === x.text && y.level === x.level));
|
|
279
|
-
findings = [{ level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}
|
|
358
|
+
findings = [{ level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}`, code: 'poses', refs: { poses } }, ...each[0][1].filter(same),
|
|
359
|
+
...each.flatMap(([p, list]) => list.filter((x) => !same(x)).map((x) => ({ ...x, text: `${p}: ${x.text}`, ...(x.card ? { card: `${p}: ${x.card}` } : {}), refs: { ...x.refs, pose: p } })))];
|
|
280
360
|
}
|
|
281
|
-
|
|
361
|
+
findings.unshift(...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]));
|
|
362
|
+
if (opt('sweep')) findings.push(...sweep(s, { joint: typeof opt('sweep') === 'string' ? opt('sweep') : undefined, steps: Number(opt('steps')) || 24, progress: showProgress }));
|
|
282
363
|
if (a.kind === 'plate') findings.push(...check(printed.flatMap((p) => p.triangles), rules(printerOf(s.project)), { parts: printed }));
|
|
283
|
-
process.exitCode = report(findings) ? 1 : 0;
|
|
364
|
+
process.exitCode = report(findings, { assembly: ref, title, kind: a.kind || 'fit', ...(pose ? { pose } : {}) }) ? 1 : 0;
|
|
284
365
|
return;
|
|
285
366
|
}
|
|
286
367
|
if (cmd === 'preview') {
|
|
@@ -303,26 +384,7 @@ async function assembly(cmd, ref) {
|
|
|
303
384
|
return console.log(out);
|
|
304
385
|
}
|
|
305
386
|
const link = async () => {
|
|
306
|
-
const
|
|
307
|
-
const model = {
|
|
308
|
-
title, version: versions, src: `${s.project}/${s.name}`, // object versions are in version: the file name stays short orientation: a.note || (a.kind === 'plate' ? 'A print plate: print everything together.' : 'A fit check: references are faint.'),
|
|
309
|
-
rules: [],
|
|
310
|
-
...sheet([...new Map(s.objects.filter((o) => o.built?.entries).map((o) => [o.objName, o.built.entries])).entries()]),
|
|
311
|
-
// Its boards' 2D views (copper, schematic), so one link holds the whole build: tabs over the 3D model
|
|
312
|
-
...(await (async () => {
|
|
313
|
-
const boards = [...new Map(s.objects.filter((o) => o.built?.circuit).map((o) => [o.objName, o])).values()];
|
|
314
|
-
if (!boards.length) return {};
|
|
315
|
-
const pcb = await pcbEngine(), views = [];
|
|
316
|
-
for (const o of boards) for (const [n, svg] of await pcb.views(o.built.circuit)) views.push([boards.length > 1 ? `${o.objName} ${n}` : n, svg]);
|
|
317
|
-
return { views };
|
|
318
|
-
})()),
|
|
319
|
-
// Each shape once and placed: the macropad's nine keys cost one keycap
|
|
320
|
-
...fromShapes(shapes(s.parts).shapes.length ? (() => {
|
|
321
|
-
const placed = shapes(s.parts), tri = (polys) => polys.flatMap((t) => t.slice(1, -1).map((_, i) => [t[0], t[i + 1], t[i + 2]]));
|
|
322
|
-
return placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: p.object || p.label, slot: slotOf(fil, p.filament), triangles: tri(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; });
|
|
323
|
-
})() : []),
|
|
324
|
-
};
|
|
325
|
-
Object.assign(model, motionLink(s));
|
|
387
|
+
const model = await assemblyModel(s, { title, versions, filaments: filaments(s.project), noRules: !!opt('no-rules') });
|
|
326
388
|
const url = await linkTo(model);
|
|
327
389
|
return { view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, src: model.src, size: url.length, title, version: '' };
|
|
328
390
|
};
|
|
@@ -341,57 +403,12 @@ async function assembly(cmd, ref) {
|
|
|
341
403
|
throw new Error(`cad ${cmd} doesn't work on an assembly (check, preview, export, show, link do)`);
|
|
342
404
|
}
|
|
343
405
|
|
|
344
|
-
// An assembly's joints, for the page's sliders: each part moves with its item (motion in @rulecad/model-link)
|
|
345
|
-
function motionLink(s) {
|
|
346
|
-
const mo = s.motion;
|
|
347
|
-
if (!mo.joints.length) return {};
|
|
348
|
-
const r = (x) => Number(x.toFixed(6)), names = mo.items.map((x) => x[0]);
|
|
349
|
-
const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`), allow = [];
|
|
350
|
-
const loose = s.fits.filter((x) => x.min != null && x.num(x.min) < 0);
|
|
351
|
-
s.parts.forEach((pa, i) => s.parts.forEach((pb, j) => {
|
|
352
|
-
if (j > i && pa.item !== pb.item && loose.some((x) => (named(pa, x.a) && named(pb, x.b)) || (named(pa, x.b) && named(pb, x.a)))) allow.push([i, j]);
|
|
353
|
-
}));
|
|
354
|
-
return { motion: {
|
|
355
|
-
items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
|
|
356
|
-
joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone }) => ({ id, type, parent, child, a: a.map(r), b: b.map(r), dofs: dofs.map((d) => d.map(r)),
|
|
357
|
-
...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}) })),
|
|
358
|
-
poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
|
|
359
|
-
part: s.parts.map((p) => names.indexOf(p.item)),
|
|
360
|
-
...(allow.length ? { allow } : {}),
|
|
361
|
-
} };
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
// ---------- links ----------
|
|
365
|
-
// The rules sheet a link carries, for the page's Rules panel: a row for each of an object's own values, then each rule
|
|
366
|
-
// they use, as [group, name, value, unit, rule, expr, kind, source, checked] (group: the object, or the rule's set).
|
|
367
|
-
// A rule set marked "private" stays out, and --no-rules leaves the sheet out altogether.
|
|
368
|
-
function sheet(objects) {
|
|
369
|
-
if (opt('no-rules')) return {};
|
|
370
|
-
const rows = [], seen = new Set(), trim = (r) => { while (r.length && (r[r.length - 1] === '' || r[r.length - 1] == null)) r.pop(); return r; };
|
|
371
|
-
for (const [obj, entries] of objects) for (const e of entries) {
|
|
372
|
-
if (!e.name.includes('.')) rows.push(trim([obj, e.label || e.name, fmt(e.value), e.unit || '', e.rule || '', e.expr || '']));
|
|
373
|
-
}
|
|
374
|
-
for (const [, entries] of objects) for (const e of entries) {
|
|
375
|
-
if (!e.name.includes('.') || !e.used || e.private || seen.has(e.name)) continue;
|
|
376
|
-
seen.add(e.name);
|
|
377
|
-
const [set, name] = e.name.split('.');
|
|
378
|
-
rows.push(trim([set, name, fmt(e.value), e.unit || '', e.rule || '', e.expr || '', e.kind || '', e.source || '', e.checked || '']));
|
|
379
|
-
}
|
|
380
|
-
return rows.length ? { sheet: rows } : {};
|
|
381
|
-
}
|
|
382
406
|
// The model as a link: full print precision (triangles), the rules card, and exactly which version it is.
|
|
383
407
|
async function links(d, b, set) {
|
|
384
408
|
const s = d.tag ? { kind: null } : await since(d), fil = filaments(d.project);
|
|
385
409
|
const version = d.version || b.object.version || '0.0.0';
|
|
386
410
|
const src = `${d.project}/${d.name}${d.variant ? `:${d.variant}` : ''}@${version}${s.kind && s.kind !== 'first' ? '+changes' : s.kind === 'first' ? '+unreleased' : ''}`;
|
|
387
|
-
const model = {
|
|
388
|
-
title: `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`, version, src, ...(Object.keys(set).length ? { set: suffix(set).slice(1).replace(/-(?=\w+=)/g, ',') } : {}),
|
|
389
|
-
material: b.object.material, orientation: b.object.orientation,
|
|
390
|
-
rules: b.entries.filter((e) => e.show).map((e) => [e.label || e.name, fmt(e.value), e.unit || '']),
|
|
391
|
-
...sheet([[b.object.name, b.entries]]),
|
|
392
|
-
...(b.circuit ? { views: await (await pcbEngine()).views(b.circuit) } : {}), // boards: the 2D board and schematic
|
|
393
|
-
...fromParts(b.parts.map((p) => ({ name: p.name, role: p.role, label: p.label, slot: slotOf(fil, p.filament), triangles: p.triangles.flatMap((t) => t.slice(1, -1).map((_, i) => [t[0], t[i + 1], t[i + 2]])) }))),
|
|
394
|
-
};
|
|
411
|
+
const model = await objectModel(b, { title: `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`, version, src, set: Object.keys(set).length ? suffix(set).slice(1).replace(/-(?=\w+=)/g, ',') : null, filaments: fil, noRules: !!opt('no-rules') });
|
|
395
412
|
const url = await linkTo(model);
|
|
396
413
|
return { view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, src, size: url.length, title: model.title, version };
|
|
397
414
|
}
|
|
@@ -614,4 +631,8 @@ function printed(d) {
|
|
|
614
631
|
console.log(`logged in ${path.relative(WS, printsFile(d))}: ${d.name}@${version} ${result}`);
|
|
615
632
|
}
|
|
616
633
|
|
|
617
|
-
main().catch((e) => {
|
|
634
|
+
main().catch((e) => {
|
|
635
|
+
if (opt('json')) console.log(JSON.stringify({ error: errorData({ ...e, message: e.message, code: e.code, file: e.file && path.relative(WS, e.file) }) }, null, 2));
|
|
636
|
+
else console.error(`${e.message}${e.file ? ` (${path.relative(WS, e.file)}${e.path ? `: ${e.path}` : ''})` : ''}`);
|
|
637
|
+
process.exit(1);
|
|
638
|
+
});
|