@rulecad/cad 0.7.48 → 0.7.53
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 +20 -6
- package/EXAMPLES.md +347 -1
- package/README.md +61 -3
- package/bin/cad.mjs +19 -8
- package/lib/assembly.mjs +34 -10
- package/lib/design.mjs +44 -12
- package/lib/edit.mjs +12 -4
- package/lib/fasten.mjs +824 -0
- package/lib/fixings.mjs +42 -0
- package/lib/links.mjs +2 -1
- package/lib/list.mjs +27 -8
- package/lib/measured.mjs +49 -8
- package/lib/motors.mjs +48 -7
- package/lib/order.mjs +19 -5
- package/lib/preview/page.html +4 -2
- package/lib/preview.mjs +3 -2
- package/lib/sandbox-hooks.mjs +2 -2
- package/lib/sandbox-run.mjs +5 -3
- package/lib/sandbox.mjs +7 -5
- package/package.json +3 -2
- package/schemas/assembly.schema.json +18 -0
package/lib/fixings.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// v.fixings: @rulecad/fixings as a design gets it, bound to its project. Every function is fixingsFor's, so it reads
|
|
2
|
+
// the workspace's own thread sets before the kit's, the project's printer, and the design's booleans (v.ops); where a
|
|
3
|
+
// call names no material, the project's is taken for what a thread is in or a head sits on (a hole, engagement,
|
|
4
|
+
// stripping, seating: never a screw's own steel). What each call found is kept, so cad check says what every hole
|
|
5
|
+
// and seat was drawn to. No files are read here: the sandbox's runner uses it as the build does.
|
|
6
|
+
import { fixingsFor } from '@rulecad/fixings';
|
|
7
|
+
|
|
8
|
+
// The functions whose material is the part's (the plastic a pilot is formed in, what a thread or a head bears on)
|
|
9
|
+
const IN_PART = ['hole', 'holeModel', 'engagement', 'stripping', 'seating'];
|
|
10
|
+
const isOptions = (o) => o && typeof o === 'object' && !Array.isArray(o);
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @rulecad/fixings bound to a design's project, with what its calls found.
|
|
14
|
+
* @param {{ sets?: object, printer?: object, material?: string | null, ops?: object }} context sets: the workspace's rule
|
|
15
|
+
* sets by name (threads, materials); printer: the printer's rule set ({ name, rules }); material: the project's; ops: v.ops
|
|
16
|
+
* @returns {{ fixings: Record<string, Function>, found: () => object[], used: () => boolean }} fixings: v.fixings;
|
|
17
|
+
* found: the findings of every model made, each said once (values.count where it came up again); used: whether the design called any of it
|
|
18
|
+
*/
|
|
19
|
+
export function designFixings({ sets, printer, material, ops } = {}) {
|
|
20
|
+
const bound = fixingsFor({ ...(sets && Object.keys(sets).length ? { sets } : {}), ...(printer ? { printer } : {}), ...(ops ? { ops } : {}) });
|
|
21
|
+
const found = new Map(); let calls = 0;
|
|
22
|
+
const keep = (r) => {
|
|
23
|
+
const list = Array.isArray(r) ? r : (r?.model ?? r)?.findings;
|
|
24
|
+
if (Array.isArray(list)) for (const x of list) {
|
|
25
|
+
if (!x || typeof x.text !== 'string' || typeof x.level !== 'string') continue;
|
|
26
|
+
const k = `${x.level}|${x.code}|${x.text}`, had = found.get(k);
|
|
27
|
+
if (had) had.values = { ...had.values, count: (had.values?.count ?? 1) + 1 }; else found.set(k, { ...x });
|
|
28
|
+
}
|
|
29
|
+
return r;
|
|
30
|
+
};
|
|
31
|
+
const fixings = {};
|
|
32
|
+
for (const [k, f] of Object.entries(bound)) {
|
|
33
|
+
if (typeof f !== 'function') { fixings[k] = f; continue; }
|
|
34
|
+
const lead = k === 'lengthFor' ? 2 : 1; // (lengthFor takes the stack first: its options come third)
|
|
35
|
+
fixings[k] = (...a) => {
|
|
36
|
+
calls++;
|
|
37
|
+
if (material && IN_PART.includes(k) && (a[lead] === undefined || isOptions(a[lead])) && a[lead]?.material == null) a[lead] = { material, ...a[lead] };
|
|
38
|
+
return keep(f(...a));
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
return { fixings, found: () => [...found.values()], used: () => calls > 0 };
|
|
42
|
+
}
|
package/lib/links.mjs
CHANGED
|
@@ -103,8 +103,9 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
|
|
|
103
103
|
alts.forEach((x, i) => (model.motion.swap[x.pose] ||= []).push([x.of, list.length - alts.length + i]));
|
|
104
104
|
}
|
|
105
105
|
// A machine's link carries the rest of the project: its task, a drawing to play, its wires' routes, the build page
|
|
106
|
+
// (an assembly with screws has one too: its shopping list and its steps, each with its screws and key)
|
|
106
107
|
if (s.wires?.length) model.wires = wireRoutesOf(s);
|
|
107
|
-
if (s.task || s.wires?.length || s.objects.some((o) => o.bought || o.motor)) {
|
|
108
|
+
if (s.task || s.wires?.length || s.a.fasten?.length || s.objects.some((o) => o.bought || o.motor)) {
|
|
108
109
|
const findings = s.task ? checkAssembly(s) : [];
|
|
109
110
|
if (s.task && model.motion) { model.task = taskData(s, findings); const carried = stepsData(s, steps); if (carried) model.steps = carried; }
|
|
110
111
|
Object.assign(model, await buildData(s));
|
package/lib/list.mjs
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
-
// What a machine takes to build, in numbers: the bought items by rule set with quantities,
|
|
2
|
-
//
|
|
1
|
+
// What a machine takes to build, in numbers: the bought items by rule set with quantities, every screw, nut, washer and
|
|
2
|
+
// insert (fasten.count: from the fasten relations, a motor's mounting screws, and fits that name a fastener), each by
|
|
3
|
+
// thread, length and head with its mass and the packs it is bought in, wires by gauge, and the printed parts with
|
|
4
|
+
// their grams and an estimate of the minutes.
|
|
5
|
+
import { placeItems, jointValues } from '@rulecad/model-link';
|
|
6
|
+
import { screwModel } from '@rulecad/fixings';
|
|
3
7
|
import { peekRuleSet as loadRuleSet } from './rules.mjs';
|
|
8
|
+
import { motorScrews } from './motors.mjs';
|
|
4
9
|
import { paths } from './workspace.mjs';
|
|
5
10
|
import { readJson } from './host.mjs';
|
|
6
11
|
import path from 'node:path';
|
|
@@ -35,24 +40,38 @@ export function shoppingList(s) {
|
|
|
35
40
|
const key = `${o.bought.set}|${o.bought.variant ?? ''}`, line = bought.get(key) ?? { set: o.bought.set, variant: o.bought.variant, part: o.bought.part, qty: 0, grams: o.bought.mass != null ? o.bought.mass * 1000 : null, items: [] };
|
|
36
41
|
line.qty++; line.items.push(o.id); bought.set(key, line);
|
|
37
42
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
43
|
+
// fasten.count: the hardware a fasten placed (a component's too), one part a piece; a motor's mounting screws; and a fit
|
|
44
|
+
// that names its fastener by hand. Summed by name, which is the thread, length and head, or the nut's kind
|
|
45
|
+
const add = (name, n, from, more = {}) => { const line = fasteners.get(name) ?? { fastener: name, qty: 0, from: [], ...more }; line.qty += n; if (!line.from.includes(from)) line.from.push(from); fasteners.set(name, line); };
|
|
46
|
+
for (const p of s.parts) if (p.hardware) { const h = p.hardware; add(h.name, 1, h.from ?? h.name, { kind: h.kind, thread: h.thread ?? null, length: h.length ?? null, head: h.head ?? null, grams: h.grams ?? null }); }
|
|
47
|
+
for (const m of motorScrews(s, { placeItems, jointValues })) {
|
|
48
|
+
let grams = null; try { grams = screwModel(m.thread, { length: m.length, head: 'cap', anyLength: true }).mass; } catch {}
|
|
49
|
+
add(`${m.thread}x${m.length} cap`, m.count, `${m.item} on ${m.other} (its mount, a fit that fastens)`, { kind: 'screw', thread: m.thread, length: m.length, head: 'cap', grams });
|
|
41
50
|
}
|
|
51
|
+
for (const x of s.fits) if (x.fastener && x.fasten == null) add(x.fastener, x.count != null ? x.num(x.count) : 1, x.note || `${x.a} / ${x.b}`);
|
|
52
|
+
// Rounded up to whole packs (packs.pack), the spares said
|
|
53
|
+
let pack = null; try { const r = loadRuleSet('packs').rules.pack; pack = { size: r.value, rule: 'packs.pack', kind: r.kind }; } catch {}
|
|
54
|
+
const fixings = [...fasteners.values()].map((l) => ({ ...l, ...(l.grams != null ? { grams: n(l.grams, 3), mass: n(l.grams * l.qty, 2) } : {}), ...(l.kind && pack ? { packs: Math.ceil(l.qty / pack.size), buy: Math.ceil(l.qty / pack.size) * pack.size, spare: Math.ceil(l.qty / pack.size) * pack.size - l.qty } : {}) }))
|
|
55
|
+
.sort((a, b) => (a.kind ? 0 : 1) - (b.kind ? 0 : 1) || ['screw', 'nut', 'washer', 'insert'].indexOf(a.kind) - ['screw', 'nut', 'washer', 'insert'].indexOf(b.kind) || String(a.thread).localeCompare(String(b.thread)) || (a.length ?? 0) - (b.length ?? 0) || a.fastener.localeCompare(b.fastener));
|
|
42
56
|
const rows = s.wires?.length ? wiresFor(s) : [], wires = new Map();
|
|
43
57
|
for (const w of rows) { const key = w.gauge ?? 'gauge not given', l = wires.get(key) ?? { gauge: w.gauge, conductors: 0, length: 0, runs: [] }; l.length += w.length * w.conductors; l.conductors += w.conductors; l.runs.push(w.id); wires.set(key, l); }
|
|
44
58
|
const boughtList = [...bought.values()].map((b) => ({ ...b, grams: b.grams != null ? n(b.grams) : null })).sort((a, b) => a.part.localeCompare(b.part) || a.set.localeCompare(b.set));
|
|
45
59
|
const printedGrams = printed.reduce((t, p) => t + p.grams, 0), boughtGrams = boughtList.reduce((t, b) => t + (b.grams ?? 0) * b.qty, 0), unknown = boughtList.filter((b) => b.grams == null).map((b) => b.set);
|
|
46
|
-
|
|
60
|
+
const fixingsGrams = fixings.reduce((t, f) => t + (f.mass ?? 0), 0);
|
|
61
|
+
return { bought: boughtList, fasteners: fixings, wires: [...wires.values()], printed, totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), fixingsGrams: n(fixingsGrams), machineGrams: n(printedGrams + boughtGrams + fixingsGrams), ...(pack && fixings.some((f) => f.packs) ? { pack } : {}), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
|
|
47
62
|
}
|
|
48
63
|
|
|
49
64
|
export function listText(ref, l) {
|
|
50
65
|
const out = [`${ref}: what it takes to build`];
|
|
51
66
|
const row = (a) => out.push(a.join(' '));
|
|
52
67
|
if (l.bought.length) { out.push('', 'Bought'); for (const b of l.bought) row([` ${String(b.qty).padStart(3)} ×`, `${b.set}${b.variant ? ` (${b.variant})` : ''}`, `a ${b.part}`, b.grams != null ? `${b.grams} g each` : 'mass not given', b.items.join(', ')]); }
|
|
53
|
-
if (l.fasteners.length) {
|
|
68
|
+
if (l.fasteners.length) {
|
|
69
|
+
out.push('', 'Fasteners');
|
|
70
|
+
for (const f of l.fasteners) row([` ${String(f.qty).padStart(3)} ×`, f.fastener, ...(f.mass != null ? [`${f.grams} g each, ${f.mass} g`] : []), ...(f.packs ? [`${f.packs} pack${f.packs > 1 ? 's' : ''} of ${l.totals.pack.size}, ${f.spare} spare`] : []), f.from.join('; ')]);
|
|
71
|
+
if (l.totals.pack) out.push(` (packs of ${l.totals.pack.size}: ${l.totals.pack.rule}, ${/^[aeiou]/.test(l.totals.pack.kind) ? 'an' : 'a'} ${l.totals.pack.kind}; masses are estimates from each piece's outline)`);
|
|
72
|
+
}
|
|
54
73
|
if (l.wires.length) { out.push('', 'Wire'); for (const w of l.wires) row([` ${w.length} mm of`, w.gauge ?? 'gauge not given', `in ${w.runs.join(', ')}`]); }
|
|
55
74
|
if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}`]); }
|
|
56
|
-
out.push('', `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
|
|
75
|
+
out.push('', `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.fixingsGrams ? `${l.totals.fixingsGrams} g of fixings, ` : ''}${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
|
|
57
76
|
return out.join('\n');
|
|
58
77
|
}
|
package/lib/measured.mjs
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
// A bench exists so measurements replace estimates and the predictions move. cad measured writes a measured value where
|
|
2
2
|
// the estimate was (in the workspace's copy of the rule set), or a measurement of something a check predicts (a figure
|
|
3
3
|
// no rule holds, like the pen's error at the far corner), runs the assembly's checks either side, says what moved, and
|
|
4
|
-
// keeps a ledger of predicted against measured beside prints.jsonl.
|
|
4
|
+
// keeps a ledger of predicted against measured beside prints.jsonl. The rules the fixings coupon measures (a pilot or an
|
|
5
|
+
// insert hole per thread, the nut fits, the thread gap and flank form) need no --rule: what each is comes from here.
|
|
5
6
|
import fs from 'node:fs';
|
|
6
7
|
import path from 'node:path';
|
|
7
8
|
import { setAt } from './jsonedit.mjs';
|
|
8
9
|
import { CadError } from './errors.mjs';
|
|
9
|
-
import { paths, WS } from './workspace.mjs';
|
|
10
|
+
import { paths, WS, RULE_DIRS } from './workspace.mjs';
|
|
10
11
|
import { loadRuleSet } from './rules.mjs';
|
|
11
12
|
import { buildAssembly, checkAssembly, assemblyPath } from './assembly.mjs';
|
|
13
|
+
import { fixingsContext } from './design.mjs';
|
|
14
|
+
import { fixingsFor, threads } from '@rulecad/fixings';
|
|
12
15
|
|
|
13
16
|
const today = () => new Date().toISOString().slice(0, 10), n = (x) => String(Number(Number(x).toFixed(4)));
|
|
14
17
|
export const ledgerFile = (project) => path.join(paths.project(project), 'ledger.jsonl');
|
|
@@ -27,6 +30,40 @@ function ruleFile(name) {
|
|
|
27
30
|
return { set, rule, data, file: path.join(WS, 'rules', `${set}.json`) };
|
|
28
31
|
}
|
|
29
32
|
|
|
33
|
+
// The printer's rules the fixings read that a printer's set may not hold yet, each measured on the fixings coupon
|
|
34
|
+
// (examples/bench/projects/benchmarks/MEASURE.md): what it is, its unit, and what the kit drew before it was measured,
|
|
35
|
+
// so the ledger shows predicted against measured. A pilot or an insert hole is per thread, and may name a plastic
|
|
36
|
+
// (x1c.pilot_m4, x1c.pilot_m4_petg); the rest are one per printer.
|
|
37
|
+
const COUPON = 'the fixings coupon (examples/bench/projects/benchmarks/MEASURE.md)';
|
|
38
|
+
function fixingsRule(project, set, key) {
|
|
39
|
+
if (set !== printerName(project)) return null;
|
|
40
|
+
let fx; const f = () => (fx ||= (() => { const { context } = fixingsContext({ project, dir: paths.project(project) }); return { ...fixingsFor({ sets: context.sets, printer: context.printer }), material: context.material }; })());
|
|
41
|
+
const plastic = (p) => (p ?? f().material ?? 'the project\'s plastic').toUpperCase();
|
|
42
|
+
const hole = key.match(/^(pilot|insert)_(.+)$/);
|
|
43
|
+
if (hole) {
|
|
44
|
+
const bySet = new Map(threads().map((t) => [fixingsFor().fixingModel(t).set, t]));
|
|
45
|
+
const [setName, thread] = [...bySet].filter(([k]) => hole[2] === k || hole[2].startsWith(`${k}_`)).sort((a, b) => b[0].length - a[0].length)[0] ?? [];
|
|
46
|
+
if (!thread) return null;
|
|
47
|
+
const own = hole[2].slice(setName.length + 1) || null;
|
|
48
|
+
if (own && !/^[a-z][a-z0-9]*$/.test(own)) return null;
|
|
49
|
+
const h = f().holeModel(thread, { kind: hole[1], ...(own ? { material: own } : {}) });
|
|
50
|
+
return { unit: 'mm', predicted: h.nominal, was: `${h.basis.rule}, ${h.basis.kind}`,
|
|
51
|
+
rule: hole[1] === 'pilot' ? `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} screw to form its own thread in ${plastic(own)}, standing upright: the one on ${COUPON} the screw went into straight and held in, turned by hand. Drawn as it is: no hole compensation`
|
|
52
|
+
: `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} heat-set insert in ${plastic(own)}: the one on ${COUPON} the insert went into straight and flush, and held when a screw was tightened in it. Drawn as it is: no hole compensation`,
|
|
53
|
+
source: COUPON };
|
|
54
|
+
}
|
|
55
|
+
if (key === 'nut_fit') return { unit: 'mm', predicted: f().nutPocketModel('M3').clearance, was: 'snug, no clearance', source: COUPON,
|
|
56
|
+
rule: `Clearance across the flats of a nut pocket let in from a face, on top of hole_comp: the tightest on ${COUPON} a hex nut dropped into by hand and did not turn in as its screw was tightened. A nut pocket's snug fit` };
|
|
57
|
+
if (key === 'nut_slip') { const t = f().nutTrapModel('M3', { depth: 1 }); return { unit: 'mm', predicted: t.clearance, was: t.rests.find((r) => /slip$/.test(r.name))?.name ?? 'slip', source: COUPON,
|
|
58
|
+
rule: `Clearance across the flats of a nut slot a nut slides into from the side, on top of hole_comp: the tightest on ${COUPON} a hex nut slid into by hand, stayed in turned over, and did not turn as its screw was tightened. A nut slot's slip fit` }; }
|
|
59
|
+
if (key === 'thread_flank') { const t = f().threadModel('M8', { length: f().holeModel('M8', { kind: 'thread' }).depth, internal: true }); return { unit: '°', predicted: t.overhang.drawn, was: 'flanks: printed, the default', source: COUPON, allowed: [t.overhang.drawn, t.overhang.standard],
|
|
60
|
+
rule: `The down-facing flank of a printed thread standing upright, as an overhang from upright: ${t.overhang.drawn} is the form laid back to the printer's overhang (flanks: 'printed', the kit's default), ${t.overhang.standard} the standard's own form (flanks: 'standard'). The one on ${COUPON} that held, turned smoothly and printed clean. A record for choosing the default: designs still draw flanks: 'printed' unless they say otherwise` }; }
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
const printerName = (project) => { try { return fixingsContext({ project, dir: paths.project(project) }).context.printer?.name ?? 'x1c'; } catch { return 'x1c'; } };
|
|
64
|
+
// A rule the workspace's copy lacks and the kit's own set of that name holds (a set copied before the rule was added)
|
|
65
|
+
function kitRule(set, key) { try { return JSON.parse(fs.readFileSync(path.join(RULE_DIRS.at(-1), `${set}.json`), 'utf8')).rules?.[key] ?? null; } catch { return null; } }
|
|
66
|
+
|
|
30
67
|
/**
|
|
31
68
|
* Write measurements back.
|
|
32
69
|
* @param {string} ref project/assembly
|
|
@@ -39,6 +76,7 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
|
|
|
39
76
|
if (!project || !name || !fs.existsSync(assemblyPath(ref))) throw new CadError('measured.assembly', `no assembly "${ref}": give <project>/<assembly>, the one whose predictions it moves`);
|
|
40
77
|
if (!Object.keys(values).length) throw new CadError('measured.usage', 'usage: cad measured <project>/<assembly> <name>=<value> … [--unit mm] [--source "how it was measured"]');
|
|
41
78
|
const before = await findingsOf(ref), entries = [], predictions = predictionsOf(before);
|
|
79
|
+
const writes = []; // (every value is checked before any is written, so a refusal leaves the rule set as it was)
|
|
42
80
|
for (const [k, value] of Object.entries(values)) {
|
|
43
81
|
if (!Number.isFinite(value)) throw new CadError('measured.value', `${k}: a measurement is a number (got ${value})`);
|
|
44
82
|
const named = predictions.filter((x) => x.code === k || x.predict.name === k);
|
|
@@ -48,13 +86,16 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
|
|
|
48
86
|
continue;
|
|
49
87
|
}
|
|
50
88
|
const { set, rule: key, data, file } = ruleFile(k);
|
|
51
|
-
const old = data.rules?.[key];
|
|
52
|
-
if (
|
|
53
|
-
if (
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
89
|
+
const old = data.rules?.[key], known = fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
|
|
90
|
+
if (known?.allowed && !known.allowed.includes(value)) throw new CadError('measured.value', `${k} is ${known.allowed.join(' or ')}: the flank forms the coupon prints (got ${value})`);
|
|
91
|
+
if (!old && !rule && !known) throw new CadError('measured.rule', `${set} has no rule "${key}" (and no check here predicts "${k}"): --rule "what it is" to add it (checks: ${[...new Set(predictions.map((x) => x.code))].join(', ') || 'none'})`);
|
|
92
|
+
const had = old ?? known, prior = typeof had?.value === 'number' ? had.value : known?.predicted ?? null;
|
|
93
|
+
if (unit && had?.unit && unit !== had.unit) throw new CadError('measured.unit', `${k} is in ${had.unit}, and this is in ${unit}: give it in ${had.unit}`);
|
|
94
|
+
const entry = { value, unit: unit ?? had?.unit ?? '', rule: rule ?? had.rule, kind: 'measured', source: source || known?.source || 'measured on the bench', checked: date };
|
|
95
|
+
writes.push([file, key, entry]);
|
|
96
|
+
entries.push({ date, assembly: name, name: k, figure: entry.rule, unit: entry.unit, predicted: prior, was: old ? old.kind : known?.was ?? known?.kind ?? null, measured: value, ratio: prior ? value / prior : null, ...(source ? { source } : {}) });
|
|
57
97
|
}
|
|
98
|
+
for (const [file, key, entry] of writes) fs.writeFileSync(file, setAt(fs.readFileSync(file, 'utf8'), ['rules', key], entry));
|
|
58
99
|
const after = await findingsOf(ref), was = new Map(before.map((x) => [keyOf(x), x])), moved = [];
|
|
59
100
|
for (const x of after) {
|
|
60
101
|
const y = was.get(keyOf(x));
|
package/lib/motors.mjs
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { createRequire } from 'node:module';
|
|
6
6
|
import { motorModel, motorParts, mountModel, performance } from '@rulecad/motors';
|
|
7
7
|
import { stageEfficiency } from '@rulecad/gears';
|
|
8
|
+
import { screwGroup } from '@rulecad/fixings';
|
|
8
9
|
import { named } from './parts.mjs';
|
|
9
10
|
import { referenceBuilt } from './bought.mjs';
|
|
10
11
|
import crypto from 'node:crypto';
|
|
@@ -145,6 +146,13 @@ function worstLoad(motion, loads, j, drive, { placeItems, jointValues, mul }) {
|
|
|
145
146
|
// What a stepper gives at the current it's set to: torque goes with the current, up to its rating
|
|
146
147
|
export const atCurrent = (m, spec, torque) => (m.type === 'stepper' && spec.current != null && m.figures.rated_current?.value ? torque * Math.min(1, spec.current / m.figures.rated_current.value) : torque);
|
|
147
148
|
|
|
149
|
+
/**
|
|
150
|
+
* The torque a motor puts on its own screws, as a reaction about its shaft: what it gives at its working speed (the
|
|
151
|
+
* assembly's, else workingSpeed), at the current it's set to. motor.torque, motor.mount and fasten.load all read this one.
|
|
152
|
+
* @param {{ model: object, spec: object }} d a drive (an assembly's motor item) @returns {number} N m
|
|
153
|
+
*/
|
|
154
|
+
export const mountTorque = (d) => atCurrent(d.model, d.spec, performance(d.model, { speed: workingSpeed(d.model, d.spec) }).motor.torque);
|
|
155
|
+
|
|
148
156
|
// A motor's speed if the assembly doesn't say: its corner speed, its rated speed, or half its free speed
|
|
149
157
|
export function workingSpeed(model, spec) {
|
|
150
158
|
if (spec.speed != null) return spec.speed;
|
|
@@ -157,7 +165,7 @@ const material = (name) => { const n = String(name || 'pla').toLowerCase().split
|
|
|
157
165
|
// The findings: f(level, text, card, extra), as the assembly's check makes them
|
|
158
166
|
export function motorChecks(s, f, helpers, materialName) {
|
|
159
167
|
const motion = s.motion, drives = motion?.drives || [], loads = motion?.loads || [], { placeItems, jointValues, mul } = helpers;
|
|
160
|
-
if (!drives.length) { if (loads.length) f('warn', `there are loads, but no motor: nothing has been checked against them (add a "motor" item that "drives" a joint)`, null, { code: 'motor.loads' }); return; }
|
|
168
|
+
if (!drives.length) { if (loads.length && !s.a.fasten?.length) f('warn', `there are loads, but no motor: nothing has been checked against them (add a "motor" item that "drives" a joint)`, null, { code: 'motor.loads' }); return; }
|
|
161
169
|
const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined));
|
|
162
170
|
for (const d of drives) {
|
|
163
171
|
const m = d.model, grams = n3(m.mass * 1000, 1), K = d.spec.margin != null ? d.spec.margin : 2, W = worlds[d.item];
|
|
@@ -191,7 +199,7 @@ export function motorChecks(s, f, helpers, materialName) {
|
|
|
191
199
|
back += (atLead / reduction) * ηback; backOn += atLead / reduction;
|
|
192
200
|
lines.push({ x, t, load, unit, reduction, atLead, η });
|
|
193
201
|
}
|
|
194
|
-
const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed }), avail =
|
|
202
|
+
const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed }), avail = mountTorque(d), margin = need ? avail / need : Infinity;
|
|
195
203
|
const main = lines[0], what = main.unit === 'N m' ? `${n3(main.load.torque)} N m` : `${n3(main.load.torque, 2)} N`, gives = main.unit === 'N m' ? `${n3(avail * main.reduction * main.η)} N m` : `${n3((avail * main.reduction * main.η * Math.PI * 1000) / (main.t.slide * 180), 1)} N`;
|
|
196
204
|
const trust = rated.rests.filter((k) => k !== 'spec' && k !== 'measured'), caveat = trust.length ? ` (rests on ${trust.join(' and ')} figures: measure it)` : '';
|
|
197
205
|
const level = margin < 1 ? 'fail' : margin < K ? 'warn' : 'pass', fix = margin < 1 && main.t.slide == null ? ` A ratio of ${n3((main.reduction * K) / margin, 1)}:1 would give it ${K} times` : '';
|
|
@@ -224,17 +232,50 @@ export function motorChecks(s, f, helpers, materialName) {
|
|
|
224
232
|
|
|
225
233
|
// The part a motor is fastened to, under the motor's full torque as a reaction at its screws: how thick it is at the
|
|
226
234
|
// holes (read from the part as drawn), the screws' bearing on the plastic, and how far the whole part bends (mountBends).
|
|
227
|
-
|
|
235
|
+
// The part a motor is fastened to, read at its screw holes in the motor's frame: the thinnest wall at a hole (t) and the
|
|
236
|
+
// plate round them (plate), or null where no fit that fastens names the motor
|
|
237
|
+
function mountPlate(s, d, W) {
|
|
228
238
|
const m = d.model, top = (n) => String(n).split(/[.@]/)[0], fit = s.fits.find((x) => x.fastens && [top(x.a), top(x.b)].includes(d.id));
|
|
229
|
-
if (!fit || !m.mount.holes.length) return;
|
|
230
|
-
const other = top(fit.a) === d.id ? top(fit.b) : top(fit.a), parts = s.parts.filter((p) => p.item === other || p.leaf === other);
|
|
231
|
-
if (!parts.length) return;
|
|
239
|
+
if (!fit || !m.mount.holes.length) return null;
|
|
240
|
+
const other = top(fit.a) === d.id ? top(fit.b) : top(fit.a), parts = s.parts.filter((p) => !p.hardware && (p.item === other || p.leaf === other));
|
|
241
|
+
if (!parts.length) return null;
|
|
232
242
|
const inv = (p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
|
|
233
243
|
const pts = parts.flatMap((p) => p.triangles.flat().map(inv)), side = m.mount.side, nominal = mountModel(m, { plate: 10 }), hd = nominal.holes[0].diameter;
|
|
234
244
|
let t = Infinity, plate = 0; // the shortest wall a hole has, and the plate round it (more, if the screw's head is sunk)
|
|
235
245
|
for (const [hx, hy] of m.mount.holes) for (const p of pts) { const r = Math.hypot(p[0] - hx, p[1] - hy), z = p[2] * side; if (r < hd / 2 + 2 && z > 0.5) { t = Math.min(t, z); plate = Math.max(plate, z); } }
|
|
246
|
+
return { fit, other, parts, inv, t, plate, hd };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* The screws that hold each motor to the part it is fastened to by a fit with "fastens" (a motor named in a "fasten"
|
|
251
|
+
* has its screws counted there): as many as its mounting holes, the length mountModel works out for the plate as drawn,
|
|
252
|
+
* taken to a length sold (the longest that does not pass it into the motor's own thread; through plain holes, the shortest that reaches).
|
|
253
|
+
* @param {object} s a built assembly @param {{ placeItems: Function, jointValues: Function }} helpers
|
|
254
|
+
* @returns {{ item: string, other: string, thread: string, length: number, wanted: number, count: number }[]}
|
|
255
|
+
*/
|
|
256
|
+
export function motorScrews(s, { placeItems, jointValues }) {
|
|
257
|
+
const drives = s.motion?.drives || [], top = (n) => String(n).split(/[.@]/)[0];
|
|
258
|
+
if (!drives.length) return [];
|
|
259
|
+
const named = new Set((s.a.fasten || []).flatMap((x) => [...(x.through || []), x.into].map(top)));
|
|
260
|
+
const worlds = placeItems(s.motion, s.jointValues ?? jointValues(s.motion, s.motion.pose ?? undefined)), out = [];
|
|
261
|
+
for (const d of drives) {
|
|
262
|
+
if (named.has(d.id)) continue;
|
|
263
|
+
const p = mountPlate(s, d, worlds[d.item]); if (!p || p.t === Infinity) continue;
|
|
264
|
+
const here = mountModel(d.model, { plate: +p.plate.toFixed(2), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), thread = here.screw?.thread, L = here.screwLength;
|
|
265
|
+
if (!thread || !(L > 0)) continue;
|
|
266
|
+
let sold = null; try { sold = peekRuleSet(thread.toLowerCase().replace('.', '_')).rules.lengths?.value ?? null; } catch {}
|
|
267
|
+
const length = !sold ? L : d.model.mount.thread ? [...sold].reverse().find((l) => l <= L) ?? sold[0] : sold.find((l) => l >= L) ?? sold.at(-1);
|
|
268
|
+
out.push({ item: d.id, other: p.other, thread, length, wanted: L, count: d.model.mount.holes.length });
|
|
269
|
+
}
|
|
270
|
+
return out;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function mountCheck(s, d, f, W, avail, materialName, frame) {
|
|
274
|
+
const m = d.model, at = mountPlate(s, d, W);
|
|
275
|
+
if (!at) return;
|
|
276
|
+
const { other, parts, inv, t, plate, hd } = at;
|
|
236
277
|
if (t === Infinity) return f('warn', `${d.id}: couldn't find the plate at its screw holes in ${other}`, `${d.id}: mount not found`, { code: 'motor.mount' });
|
|
237
|
-
const here = mountModel(m, { plate: +plate.toFixed(2), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), mat = material(materialName) || material('pla'),
|
|
278
|
+
const here = mountModel(m, { plate: +plate.toFixed(2), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), mat = material(materialName) || material('pla'), each = Math.max(...screwGroup(m.mount.holes, { moment: [0, 0, avail] }).screws.map((x) => x.shear)), bearing = each / (hd * t), margin = mat.strength / bearing;
|
|
238
279
|
for (const x of here.findings) f(x.level, `${d.id} on ${other}: ${x.text}`, x.level === 'pass' ? null : `${d.id}: ${x.code.split('.')[1]}`, { code: 'motor.mount' });
|
|
239
280
|
f(margin < 2 ? 'fail' : 'pass', `${d.id} on ${other}: ${n3(plate, 2)} mm of plate at the screws, each taking ${n3(each, 1)} N against the torque (bearing ${n3(bearing, 1)} MPa, ${n3(margin, 0)} times under ${mat.name.toUpperCase()}'s ${mat.strength} MPa)`, margin < 2 ? `${d.id}: screws pull through` : null, { code: 'motor.mount', values: { plate, bearing, margin } });
|
|
240
281
|
mountBends(s, d, f, W, avail, mat, { other, parts, inv, plate, hd, ...frame });
|
package/lib/order.mjs
CHANGED
|
@@ -130,10 +130,21 @@ export function assemblyOrder(s) {
|
|
|
130
130
|
else if (later) add(later, q.id, `${q.id} covers the screw of ${x.note || later}`);
|
|
131
131
|
}
|
|
132
132
|
}
|
|
133
|
+
// A fasten's screws (lib/fasten.mjs): what stands over a head goes on after the parts the screw joins. A part that
|
|
134
|
+
// must be there first (it comes before them, it is one of them, or it is no step at all) closes the way, unless a
|
|
135
|
+
// ball-end key reaches the head tilted
|
|
136
|
+
for (const rel of s.fastened?.relations ?? []) for (const sc of rel.screws) {
|
|
137
|
+
const acc = sc.access; if (!acc?.blockers?.length) continue;
|
|
138
|
+
const screwed = [...rel.through, rel.into].map(top).filter((t) => by.has(t)), later = [...screwed].sort(earlier).at(-1), walls = [...new Set(acc.blockers.map((b) => b.item))];
|
|
139
|
+
const first = walls.filter((q) => !by.has(q) || screwed.includes(q) || (later && reaches(q, later)));
|
|
140
|
+
if (first.length) { if (acc.tilt == null) bad.push({ fit: { note: rel.label }, wall: first[0], at: acc.top, later, fasten: rel.index, screw: sc.index, member: screwed.includes(first[0]), fixed: !by.has(first[0]) }); continue; }
|
|
141
|
+
for (const q of walls) add(later, q, `${q} covers the screws of ${rel.label}`);
|
|
142
|
+
}
|
|
133
143
|
const box = (g) => { const p = g.tris.flat(); return [0, 1, 2].map((k) => { const v = p.map((x) => x[k]); return (Math.min(...v) + Math.max(...v)) / 2; }); };
|
|
134
144
|
if (bad.length) {
|
|
135
|
-
const b = bad[0], label = b.fit.note || `${b.fit.a} to ${b.fit.b}`;
|
|
136
|
-
return { steps: [], stuck: { item: b.later, screw: label, wall: b.wall, at: b.at,
|
|
145
|
+
const b = bad[0], label = b.fit.note || `${b.fit.a} to ${b.fit.b}`, why = b.member ? 'it is one of the parts the screw joins' : b.fixed ? 'it is in place before anything is fitted' : `goes on first (${[...before.get(b.wall)].slice(0, 1).map(([, w]) => w)})`;
|
|
146
|
+
return { steps: [], stuck: { item: b.later, screw: label, wall: b.wall, at: b.at, ...(b.fasten != null ? { fasten: b.fasten, screws: bad.filter((x) => x.fasten === b.fasten).map((x) => x.screw) } : {}),
|
|
147
|
+
text: `the screw of "${label}" can't be reached in any order: ${b.wall} stands over it${b.member || b.fixed ? `, and ${why}` : ` and ${why}`}` } };
|
|
137
148
|
}
|
|
138
149
|
let span = 1;
|
|
139
150
|
for (const g of all) for (const t of g.tris) for (const p of t) for (const c of p) span = Math.max(span, Math.abs(c) * 2);
|
|
@@ -190,7 +201,7 @@ export function assemblyOrder(s) {
|
|
|
190
201
|
for (const [i, x] of seq.entries()) {
|
|
191
202
|
if (x.group) { steps.push({ items: x.group.map((g) => g.id), object: null, dir: round(x.d), fasteners: [], together: true }); continue; }
|
|
192
203
|
const { p, d } = x, list = [...new Set(s.fits.filter((f) => [...names(f.a), ...names(f.b)].includes(p.id) && (f.fastens || f.seat != null || f.fastener) && [...names(f.a), ...names(f.b)].every((n) => (at.get(n) ?? 0) <= i)))];
|
|
193
|
-
steps.push({ items: [p.id], object: p.object, dir: round(d), fasteners: list.map((f) => ({ fit: f.note || f.label || `${f.a} to ${f.b}`, ...(f.fastener ? { fastener: f.fastener } : {}), ...(f.count != null ? { count: f.num(f.count) } : {}) })) });
|
|
204
|
+
steps.push({ items: [p.id], object: p.object, dir: round(d), fasteners: list.map((f) => ({ fit: f.note || f.label || `${f.a} to ${f.b}`, ...(f.fastener ? { fastener: f.fastener } : {}), ...(f.count != null ? { count: f.num(f.count) } : {}), ...(f.key ? { key: f.key } : {}), ...(f.tighten ? { tighten: f.tighten } : {}) })) });
|
|
194
205
|
}
|
|
195
206
|
// Copies of one thing fitted the same way, one after another, are one step
|
|
196
207
|
const merged = [];
|
|
@@ -199,13 +210,16 @@ export function assemblyOrder(s) {
|
|
|
199
210
|
if (last && st.object && !st.together && last.object === st.object && last.dir.join() === st.dir.join() && JSON.stringify(last.fasteners.map((f) => f.fit)) === JSON.stringify(st.fasteners.map((f) => f.fit))) last.items.push(...st.items);
|
|
200
211
|
else merged.push({ items: [...st.items], object: st.object, dir: st.dir, fasteners: st.fasteners, ...(st.together ? { together: true } : {}) });
|
|
201
212
|
}
|
|
202
|
-
merged.forEach((st, i) => { st.n = i + 1; st.text = `${st.items.join(', ')}${st.object && !st.items.includes(st.object) ? ` (${st.object})` : ''}${st.together ? ' go on as one' : i ? ` goes on${st.items.length > 1 ? ', one by one' : ''}` : ' first'}${st.fasteners.length ? `: ${st.fasteners.map(
|
|
213
|
+
merged.forEach((st, i) => { st.n = i + 1; st.text = `${st.items.join(', ')}${st.object && !st.items.includes(st.object) ? ` (${st.object})` : ''}${st.together ? ' go on as one' : i ? ` goes on${st.items.length > 1 ? ', one by one' : ''}` : ' first'}${st.fasteners.length ? `: ${st.fasteners.map(fastenerText).join('; ')}` : ''}`; });
|
|
203
214
|
return { steps: merged, stuck: null };
|
|
204
215
|
}
|
|
205
216
|
|
|
217
|
+
/** One fastening of a step as the order and the build page say it: the fit, its screws by count and name, the key and how tight. */
|
|
218
|
+
export const fastenerText = (f) => `${f.fit}${f.fastener ? ` (${f.count != null ? `${f.count} × ` : ''}${f.fastener})` : ''}${f.key ? ` with ${/^[aeiou8]/i.test(f.key) ? 'an' : 'a'} ${f.key}` : ''}${f.tighten ? `, ${f.tighten.given ? `to ${f.tighten.torque} N m` : f.tighten.load ? `to ${f.tighten.torque} N m (what the joint's load leaves the thread)` : `to ${f.tighten.torque} N m at most (what the seat takes)`}` : ''}`;
|
|
219
|
+
|
|
206
220
|
// Cached by what the parts are and where they are, with everything else that changes the answer
|
|
207
221
|
function orderFile(s) {
|
|
208
|
-
const key = crypto.createHash('sha256').update(JSON.stringify([
|
|
222
|
+
const key = crypto.createHash('sha256').update(JSON.stringify([5, s.parts.map((p) => [p.item, p.hash ?? p.shape, Array.from(p.m ?? []).map((x) => +x.toFixed(4))]), s.fits.map(({ num, ...x }) => x), s.motion.joints.map((j) => [j.id, j.child, j.parent])])).digest('hex');
|
|
209
223
|
return paths.cache('order', `${key}.json`);
|
|
210
224
|
}
|
|
211
225
|
export function orderOf(s) {
|
package/lib/preview/page.html
CHANGED
|
@@ -27,8 +27,10 @@ if (data.explode) {
|
|
|
27
27
|
const gap = (all.max.y - all.min.y) * 0.8;
|
|
28
28
|
let drop = 0;
|
|
29
29
|
data.parts.forEach((p, i) => { if (p.role === 'support') { drop += gap; geos[i].translate(0, -drop, 0); geos[i].computeBoundingBox(); } });
|
|
30
|
-
const items = [...new Set(data.parts.map((p) => p.item).filter(Boolean))]; // assemblies: each item above the last
|
|
31
|
-
data.parts.forEach((p, i) => { const k = items.indexOf(p.item); if (k > 0) { geos[i].translate(0, k * gap, 0); geos[i].computeBoundingBox(); } });
|
|
30
|
+
const items = [...new Set(data.parts.filter((p) => !p.lift).map((p) => p.item).filter(Boolean))]; // assemblies: each item above the last
|
|
31
|
+
data.parts.forEach((p, i) => { const k = items.indexOf(p.lift ? p.with : p.item); if (k > 0) { geos[i].translate(0, k * gap, 0); geos[i].computeBoundingBox(); } });
|
|
32
|
+
// hardware (a screw, a nut, a washer, an insert) goes with the part it sits in, then out along its own axis (z up here is y)
|
|
33
|
+
data.parts.forEach((p, i) => { if (p.lift) { const d = gap * 0.45; geos[i].translate(p.lift[0] * d, p.lift[2] * d, -p.lift[1] * d); geos[i].computeBoundingBox(); } });
|
|
32
34
|
}
|
|
33
35
|
const box = new THREE.Box3(); geos.forEach((g) => box.union(g.boundingBox));
|
|
34
36
|
const center = box.getCenter(new THREE.Vector3()), radius = box.getSize(new THREE.Vector3()).length() / 2;
|
package/lib/preview.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// preview(parts, { title, meta, out, explode }) -> out: a 1800 × 1200 PNG of six views (front, side, 3/4, top, bottom, 3/4 below),
|
|
2
2
|
// parts: [{ name, role, label, item, triangles }]; supports and references are drawn faint (lines only); explode drops
|
|
3
|
-
// supports below and, in an assembly, lifts each kind of object above the one before (plate, switches, keycaps)
|
|
3
|
+
// supports below and, in an assembly, lifts each kind of object above the one before (plate, switches, keycaps); a part
|
|
4
|
+
// with `lift` (a screw, a nut: lib/fasten.mjs) goes with the part it sits in (`with`) and then out along its own axis.
|
|
4
5
|
// rendered by headless Chrome from lib/preview/page.html, served on this Mac only for the few seconds it takes.
|
|
5
6
|
import fs from 'node:fs';
|
|
6
7
|
import os from 'node:os';
|
|
@@ -20,7 +21,7 @@ const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); //
|
|
|
20
21
|
|
|
21
22
|
export async function preview(parts, { title = '', meta = '', out, explode = false, marks = null }) {
|
|
22
23
|
const flat = (tris) => { const positions = []; for (const t of tris) for (let i = 1; i < t.length - 1; i++) positions.push(...t[0], ...t[i], ...t[i + 1]); return positions; };
|
|
23
|
-
const data = JSON.stringify({ title, meta, explode, marks, parts: parts.map((p) => ({ name: p.name, role: p.role, label: p.label, item: p.object || p.item, positions: flat(p.triangles) })) });
|
|
24
|
+
const data = JSON.stringify({ title, meta, explode, marks, parts: parts.map((p) => ({ name: p.name, role: p.role, label: p.label, item: p.object || p.item, ...(p.lift ? { lift: p.lift, with: p.with } : {}), positions: flat(p.triangles) })) });
|
|
24
25
|
const server = http.createServer((req, res) => {
|
|
25
26
|
const u = new URL(req.url, 'http://x').pathname;
|
|
26
27
|
const send = (type, body) => { res.writeHead(200, { 'Content-Type': type }); res.end(body); };
|
package/lib/sandbox-hooks.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
// The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears, @rulecad/motors and files of
|
|
1
|
+
// The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears, @rulecad/motors, @rulecad/fixings and files of
|
|
2
2
|
// its own project, nothing else (no node: modules: no files, network or processes). The tool's own modules are free.
|
|
3
3
|
import { builtinModules } from 'node:module';
|
|
4
4
|
|
|
5
5
|
let project = '';
|
|
6
6
|
export async function initialize(data) { project = data?.project || ''; }
|
|
7
7
|
|
|
8
|
-
const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors'];
|
|
8
|
+
const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors', '@rulecad/fixings'];
|
|
9
9
|
const deny = (spec, why) => Object.assign(new Error(`designs can't import "${spec}": ${why}`), { code: 'design.sandbox' });
|
|
10
10
|
|
|
11
11
|
// The same check, for in-thread hooks (synchronous) and worker hooks (async)
|
package/lib/sandbox-run.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import * as shapes from '@rulecad/shapes';
|
|
|
6
6
|
import * as flexures from '@rulecad/flexures';
|
|
7
7
|
import * as gears from '@rulecad/gears';
|
|
8
8
|
import * as motors from '@rulecad/motors';
|
|
9
|
+
import { designFixings } from './fixings.mjs';
|
|
9
10
|
import { named, faces, unpack, watch } from './parts.mjs';
|
|
10
11
|
import { lineOf } from './errors.mjs';
|
|
11
12
|
|
|
@@ -18,7 +19,7 @@ for (const k of ['getBuiltinModule', 'binding', '_linkedBinding', 'dlopen', 'kil
|
|
|
18
19
|
}
|
|
19
20
|
const chunks = [];
|
|
20
21
|
for await (const c of process.stdin) chunks.push(c);
|
|
21
|
-
const { js, values, meta, engine, optional, stages } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
22
|
+
const { js, values, meta, engine, optional, stages, fixings: context } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
22
23
|
// A lamina's slow stages: read from the tool's cache (the workspace is readable), and what this run makes handed back
|
|
23
24
|
// with the parts for the tool to write (this process can't)
|
|
24
25
|
const kept = {}; // (what this run made of them)
|
|
@@ -29,10 +30,11 @@ console.log = console.info = console.debug = (...a) => console.error(...a);
|
|
|
29
30
|
try {
|
|
30
31
|
const mod = await import(js);
|
|
31
32
|
if (typeof mod.main !== 'function') throw Object.assign(new Error('the design has no exported main(v)'), { code: 'design.main' });
|
|
32
|
-
const
|
|
33
|
+
const ops = await shapes.ops(engine || 'jscad'), df = designFixings({ ...(context || {}), ops }); // (v.fixings: bound to the project, as the build's own is)
|
|
34
|
+
const { v, read } = watch(values, { shapes, flexures, gears, motors, fixings: df.fixings, ops }, optional);
|
|
33
35
|
const { shapes: made, mechanism } = unpack(await mod.main(v));
|
|
34
36
|
const parts = named(made, meta).map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) }));
|
|
35
|
-
done({ parts, read: [...read], ...(mechanism ? { mechanism } : {}), ...(Object.keys(kept).length ? { stages: kept } : {}) });
|
|
37
|
+
done({ parts, read: [...read], ...(mechanism ? { mechanism } : {}), ...(df.used() ? { fixings: df.found() } : {}), ...(Object.keys(kept).length ? { stages: kept } : {}) });
|
|
36
38
|
} catch (e) {
|
|
37
39
|
const line = lineOf(e, js);
|
|
38
40
|
done({ error: { message: e?.message || String(e), ...(line ? { line } : {}), ...(e?.name === 'SyntaxError' ? { syntax: true } : {}), code: e?.code && typeof e.code === 'string' && !/^ERR_/.test(e.code) ? e.code : e?.code === 'ERR_ACCESS_DENIED' ? 'design.sandbox' : 'design.run', ...(e?.code === 'ERR_ACCESS_DENIED' && e.resource ? { resource: e.resource } : {}) } });
|
package/lib/sandbox.mjs
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// promises, whatever the design does: it can't write or delete files, start programs or workers, or load addons, and
|
|
3
3
|
// it reads only the workspace and the packages designs use. That much is Node's own boundary.
|
|
4
4
|
// On top of it, to keep a design to making shapes: an import hook (sandbox-hooks.mjs) lets it import only
|
|
5
|
-
// @jscad/modeling, @rulecad/shapes, @rulecad/flexures and files in its
|
|
5
|
+
// @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears, @rulecad/motors, @rulecad/fixings and files in its
|
|
6
|
+
// own project (no node: modules); the runner
|
|
6
7
|
// takes away fetch and its kin and process's own ways to Node's modules; and it is started with none of this
|
|
7
8
|
// process's environment (no tokens). Those close the ordinary roads to the network, not every one: before Node 25
|
|
8
9
|
// the permission model doesn't cover the network, so a design written to get round them might still reach it, and
|
|
@@ -40,7 +41,7 @@ function readable() {
|
|
|
40
41
|
// Every node_modules above the workspace and the tool (package lookups read their links), and where links lead
|
|
41
42
|
const up = (dir) => { const out = []; for (let d = dir; ; d = path.dirname(d)) { out.push(path.join(d, 'node_modules')); if (path.dirname(d) === d) return out; } };
|
|
42
43
|
const dirs = [WS, TOOL, ...[...up(WS), ...up(TOOL)].filter((d) => fs.existsSync(d)),
|
|
43
|
-
...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors', '@rulecad/rules/x1c.json', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
|
|
44
|
+
...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors', '@rulecad/fixings', '@rulecad/rules/x1c.json', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
|
|
44
45
|
return [...new Set(dirs.filter(Boolean).flatMap((d) => [d, real(d)]).filter(Boolean))];
|
|
45
46
|
}
|
|
46
47
|
|
|
@@ -61,8 +62,9 @@ function refused(e) {
|
|
|
61
62
|
* @param {{ js: string }} d the design @param {object} values @param {object} meta the .json's parts @param {'jscad' | 'manifold'} [engine] v.ops's booleans
|
|
62
63
|
* @param {string[]} [optional] names main may read that aren't among the values (the display's own inputs)
|
|
63
64
|
* @param {{ salt: string, get: (k: string) => string | undefined, put: (k: string, text: string) => void } | null} [stages] where a lamina's slow stages are kept: the child reads them from the cache (it may read the workspace) and hands back what it made, which is written here
|
|
65
|
+
* @param {{ sets?: object, printer?: object, material?: string | null } | null} [fixings] what v.fixings is bound to (design.mjs fixingsContext); what its calls found comes back as fixings
|
|
64
66
|
*/
|
|
65
|
-
export function runSandboxed(d, values, meta, engine = 'jscad', optional = [], stages = null) {
|
|
67
|
+
export function runSandboxed(d, values, meta, engine = 'jscad', optional = [], stages = null, fixings = null) {
|
|
66
68
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
67
69
|
const args = [flag, ...readable().map((p) => `--allow-fs-read=${p}`), ...(inThread ? [] : ['--allow-worker']), '--import', pathToFileURL(path.join(here, 'sandbox-preload.mjs')).href, path.join(here, 'sandbox-run.mjs')];
|
|
68
70
|
// (real paths: Node names an imported file by where it really is, so a workspace reached through a link still matches)
|
|
@@ -83,8 +85,8 @@ export function runSandboxed(d, values, meta, engine = 'jscad', optional = [], s
|
|
|
83
85
|
if (err.length) process.stderr.write(Buffer.concat(err)); // what the design printed
|
|
84
86
|
if (r.error) return reject(located(Object.assign(new Error(refused(r.error)), { code: r.error.code, ...(r.error.line ? { line: r.error.line } : {}), ...(r.error.syntax ? { name: 'SyntaxError' } : {}) }), d.js, r.error.code || 'design.run'));
|
|
85
87
|
if (stages) for (const [k, text] of Object.entries(r.stages || {})) stages.put(k, text);
|
|
86
|
-
resolve({ parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })), read: new Set(r.read), mechanism: r.mechanism || null });
|
|
88
|
+
resolve({ parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })), read: new Set(r.read), mechanism: r.mechanism || null, fixings: r.fixings || null });
|
|
87
89
|
});
|
|
88
|
-
child.stdin.end(JSON.stringify({ js: `${pathToFileURL(js).href}?t=${fs.statSync(js).mtimeMs}`, values, meta, engine, optional, ...(stages ? { stages: { dir: stagesDir, salt: stages.salt } } : {}) }));
|
|
90
|
+
child.stdin.end(JSON.stringify({ js: `${pathToFileURL(js).href}?t=${fs.statSync(js).mtimeMs}`, values, meta, engine, optional, ...(stages ? { stages: { dir: stagesDir, salt: stages.salt } } : {}), ...(fixings ? { fixings } : {}) }));
|
|
89
91
|
});
|
|
90
92
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/cad",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.53",
|
|
4
4
|
"description": "The cad command: JSCAD designs from traceable rules, checked for printing and fit, versioned by what fits, shared as links and exported as Bambu 3MF.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
"@rulecad/model-link": "^0.3.2",
|
|
65
65
|
"@rulecad/versions": "^0.1.6",
|
|
66
66
|
"@rulecad/shapes": "^0.4.4",
|
|
67
|
-
"@rulecad/rules": "^0.3.
|
|
67
|
+
"@rulecad/rules": "^0.3.12",
|
|
68
68
|
"@jscad/modeling": "^2.12.0",
|
|
69
69
|
"three": "^0.186.1",
|
|
70
70
|
"@rulecad/fea": "^0.2.1",
|
|
@@ -72,6 +72,7 @@
|
|
|
72
72
|
"@rulecad/flexures": "^0.5.0",
|
|
73
73
|
"@rulecad/gears": "^0.3.2",
|
|
74
74
|
"@rulecad/motors": "^0.1.4",
|
|
75
|
+
"@rulecad/fixings": "^0.1.3",
|
|
75
76
|
"@rulecad/robots": "^0.1.1"
|
|
76
77
|
},
|
|
77
78
|
"peerDependencies": {
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
"requires": { "type": "object", "additionalProperties": { "type": "string" }, "description": "object → semver range" },
|
|
18
18
|
"items": { "type": "array", "items": { "$ref": "#/$defs/item" } },
|
|
19
19
|
"fits": { "type": "array", "items": { "$ref": "#/$defs/fit" } },
|
|
20
|
+
"fasten": { "type": "array", "description": "Screwed joints: each names its screw, the parts it passes through in order, and the part it ends in. The holes are read from the parts as drawn and each screw followed along one axis; a fasten holds its parts as a fit that fastens does, and lines their holes up as a holes fit does", "items": { "$ref": "#/$defs/fasten" } },
|
|
20
21
|
"joints": { "type": "array", "items": { "$ref": "#/$defs/joint" } },
|
|
21
22
|
"loops": { "type": "array", "items": { "$ref": "#/$defs/loop" } },
|
|
22
23
|
"planetary": { "type": "array", "items": { "$ref": "#/$defs/planetary" } },
|
|
@@ -94,6 +95,23 @@
|
|
|
94
95
|
"within": { "$ref": "#/$defs/expr", "description": "With an anchor name (item@anchor): only faces this close to it (mm, default 10)" }
|
|
95
96
|
}
|
|
96
97
|
},
|
|
98
|
+
"fasten": {
|
|
99
|
+
"type": "object",
|
|
100
|
+
"required": ["screw", "through", "into"],
|
|
101
|
+
"additionalProperties": false,
|
|
102
|
+
"properties": {
|
|
103
|
+
"screw": { "type": "string", "description": "The screw, by its thread and head: M3 cap, M4 button, M3x12 countersunk, 6-32 UNC cap (the names @rulecad/fixings reads). With no length in the name, the shortest sold length that fits is chosen" },
|
|
104
|
+
"through": { "type": "array", "items": { "type": "string" }, "description": "The parts the screw passes through, in order from under its head: items (bracket) or item.part (bracket.body). Each needs a clearance hole for the thread" },
|
|
105
|
+
"into": { "type": "string", "description": "The part the screw ends in: a pilot, a tapped or printed thread, an insert's hole or a nut's seat there, or a clearance hole with nut" },
|
|
106
|
+
"at": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/anchorRef" }, "description": "One screw at each anchor: a point on its axis (bracket.h1), the anchor's axis along the screw" },
|
|
107
|
+
"holes": { "type": "string", "description": "In place of at: a part whose holes are the screws' places, found in the part as drawn (a circuit board: its mounting holes)" },
|
|
108
|
+
"nut": { "anyOf": [{ "type": "boolean" }, { "type": "string" }], "description": "What holds the screw where the part it ends in does not: true or hex, square, lock. It sits on that part's far face, or in a nut's seat drawn there" },
|
|
109
|
+
"washer": { "type": "boolean", "description": "A plain washer under the head" },
|
|
110
|
+
"length": { "$ref": "#/$defs/expr", "description": "The screw's length in mm, where the name gives none: checked for reaching, bottoming out and standing proud" },
|
|
111
|
+
"torque": { "$ref": "#/$defs/expr", "description": "The tightening torque, N m: the pressure under the head is then held against the material it sits on (fasten.seat)" },
|
|
112
|
+
"note": { "type": "string" }
|
|
113
|
+
}
|
|
114
|
+
},
|
|
97
115
|
"anchorRef": {
|
|
98
116
|
"anyOf": [
|
|
99
117
|
{ "type": "string", "description": "item.anchor" },
|