@rulecad/cad 0.7.12 → 0.7.25
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 +6 -1
- package/README.md +72 -15
- package/TUTORIAL.md +225 -0
- package/bin/cad.mjs +97 -31
- package/lib/animate.mjs +71 -0
- package/lib/assembly.mjs +31 -5
- package/lib/clone.mjs +150 -0
- package/lib/design.mjs +75 -33
- package/lib/errors.mjs +20 -2
- package/lib/host.mjs +7 -0
- package/lib/jsonedit.mjs +17 -11
- package/lib/layout.mjs +2 -2
- package/lib/links.mjs +23 -7
- package/lib/live-shape.mjs +131 -0
- package/lib/live.mjs +2 -2
- package/lib/optimise.mjs +85 -23
- package/lib/parts.mjs +26 -0
- package/lib/player.mjs +225 -0
- package/lib/preview.mjs +3 -1
- package/lib/rules.mjs +2 -2
- package/lib/sandbox-hooks.mjs +9 -6
- package/lib/sandbox-run.mjs +24 -10
- package/lib/sandbox.mjs +27 -15
- package/lib/schema.mjs +1 -7
- package/lib/workspace.mjs +8 -3
- package/package.json +16 -7
- package/schemas/assembly.schema.json +1 -1
- package/schemas/object.schema.json +1 -1
- package/schemas/problem.schema.json +98 -4
- package/schemas/rules.schema.json +3 -1
package/lib/player.mjs
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// A lamina mechanism's sequence as data and as a page that plays it: every frame's shapes (the frame drawn once, the
|
|
2
|
+
// bodies and the bent flexures frame by frame), the forces acting (contacts and their friction, the hand, the flexures'
|
|
3
|
+
// pull on the frame), each flexure's energy and strain, the force curves, the shot and the findings. The data is plain
|
|
4
|
+
// JSON for any viewer; the page is self-contained (the data inside it), plays in any browser, phone included, and needs
|
|
5
|
+
// nothing installed: scrub, step from state to state, slow the shot down, zoom in on a part, tap a force for its x and y.
|
|
6
|
+
const r2 = (n) => Math.round(n * 100) / 100;
|
|
7
|
+
const loopsOf = (outlines) => outlines.map((o) => o.flatMap(([x, y]) => [r2(x), r2(y)])); // flat [x, y, x, y, …] a loop
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The mechanism's sequence as data.
|
|
11
|
+
* @param {object} mechanism what a lamina returns as its mechanism (cad keeps it with the build), frames and all
|
|
12
|
+
* @param {{ title?: string, version?: string, object?: string }} [meta]
|
|
13
|
+
* @returns {object} { title, version, object, kinds, ground, frames: [{ label, from, to, t, parts, forces, energy, strain }],
|
|
14
|
+
* curves, sequence, limit, friction, trip, shot, findings }: lengths in mm, forces in N, energies in mJ
|
|
15
|
+
*/
|
|
16
|
+
export function playerData(mechanism, { title = '', version = '', object = '' } = {}) {
|
|
17
|
+
const frames = mechanism.frames || [];
|
|
18
|
+
if (!frames.length) throw new Error('the mechanism has no sequence to play: give its lamina a sequence of states');
|
|
19
|
+
const flexures = new Set(Object.keys(mechanism.joints || {}));
|
|
20
|
+
const kinds = Object.fromEntries([...new Set(frames.flatMap((fr) => Object.keys(fr.parts)))].map((n) => [n, n === 'ground' ? 'ground' : flexures.has(n) ? 'flexure' : 'body']));
|
|
21
|
+
return {
|
|
22
|
+
title, version, object, kinds,
|
|
23
|
+
ground: frames[0].parts.ground ? loopsOf(frames[0].parts.ground) : [],
|
|
24
|
+
frames: frames.map((fr) => ({
|
|
25
|
+
label: fr.label || (fr.from === fr.to ? fr.from : `${fr.from} to ${fr.to}`), from: fr.from, to: fr.to, t: fr.t,
|
|
26
|
+
parts: Object.fromEntries(Object.entries(fr.parts).filter(([n]) => n !== 'ground').map(([n, o]) => [n, loopsOf(o)])),
|
|
27
|
+
...(fr.forces ? { forces: fr.forces } : {}), ...(fr.energy ? { energy: fr.energy } : {}), ...(fr.strain ? { strain: fr.strain } : {}),
|
|
28
|
+
})),
|
|
29
|
+
curves: (mechanism.curves || []).map((c) => ({ from: c.from, to: c.to, curve: c.curve, events: c.events || [], ...(c.holding ? { holding: c.holding } : {}) })),
|
|
30
|
+
sequence: mechanism.sequence || [], limit: mechanism.limit ?? null, friction: mechanism.friction ?? 0,
|
|
31
|
+
joints: mechanism.joints || {}, trip: mechanism.trip || null, shot: mechanism.shot || null,
|
|
32
|
+
findings: (mechanism.findings || []).map((f) => ({ level: f.level, code: f.code, text: f.text })),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The page that plays it.
|
|
38
|
+
* @param {object} data playerData's
|
|
39
|
+
* @returns {string} HTML
|
|
40
|
+
*/
|
|
41
|
+
export function playerHtml(data) {
|
|
42
|
+
const json = JSON.stringify(data).replace(/</g, '\\u003c');
|
|
43
|
+
const esc = (s) => String(s).replace(/[<>&"]/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' })[c]);
|
|
44
|
+
return `<!doctype html>
|
|
45
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
46
|
+
<title>${esc(`${data.title} ${data.version}`.trim())}</title>
|
|
47
|
+
<style>${CSS}</style></head>
|
|
48
|
+
<body>
|
|
49
|
+
<header><h1>${esc(data.title)} <span class="v">${esc(data.version)}</span></h1><p id="label"></p></header>
|
|
50
|
+
<main>
|
|
51
|
+
<div id="stage"><canvas id="view"></canvas><div id="pick" hidden></div><div id="coord"></div></div>
|
|
52
|
+
<section id="side">
|
|
53
|
+
<div class="controls">
|
|
54
|
+
<button id="play" title="Play or pause (space)">▶</button><button id="prev" title="Back a frame (←)">‹</button><button id="next" title="On a frame (→)">›</button>
|
|
55
|
+
<select id="speed" title="Speed"><option value="0.25">¼×</option><option value="0.5">½×</option><option value="1" selected>1×</option><option value="2">2×</option></select>
|
|
56
|
+
<button id="fit" title="See it all (0)">⤢</button>
|
|
57
|
+
</div>
|
|
58
|
+
<input id="scrub" type="range" min="0" value="0" step="1" aria-label="frame">
|
|
59
|
+
<div id="steps"></div>
|
|
60
|
+
<details open><summary>Show</summary><div id="layers"></div>
|
|
61
|
+
<label class="row">Arrows <input id="scale" type="range" min="-1.5" max="1.5" step="0.05" value="0"></label></details>
|
|
62
|
+
<details open><summary>This frame</summary><div id="now"></div></details>
|
|
63
|
+
<details open><summary>Force along the step</summary><canvas id="chart" height="150"></canvas><p id="chartNote" class="note"></p></details>
|
|
64
|
+
<details><summary>Findings</summary><ul id="findings"></ul></details>
|
|
65
|
+
</section>
|
|
66
|
+
</main>
|
|
67
|
+
<script id="data" type="application/json">${json}</script>
|
|
68
|
+
<script>${SCRIPT}</script>
|
|
69
|
+
</body></html>
|
|
70
|
+
`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const CSS = `
|
|
74
|
+
*{box-sizing:border-box}body{margin:0;font:14px/1.4 system-ui,sans-serif;color:#222;background:#f6f6f4}
|
|
75
|
+
header{padding:8px 14px;border-bottom:1px solid #ddd;background:#fff}h1{font-size:16px;margin:0}.v{color:#888;font-weight:400}
|
|
76
|
+
#label{margin:2px 0 0;color:#555;min-height:1.4em}
|
|
77
|
+
main{display:flex;height:calc(100vh - 62px)}#stage{position:relative;flex:1;min-width:0;background:#fff;touch-action:none}
|
|
78
|
+
canvas#view{width:100%;height:100%;display:block;cursor:grab}#side{width:330px;overflow:auto;padding:10px;border-left:1px solid #ddd;background:#fbfbfa}
|
|
79
|
+
.controls{display:flex;gap:6px;margin-bottom:6px}button,select{font:inherit;padding:5px 10px;border:1px solid #ccc;border-radius:6px;background:#fff;cursor:pointer}
|
|
80
|
+
#scrub{width:100%}#steps{display:flex;flex-wrap:wrap;gap:4px;margin:6px 0}#steps button{padding:3px 8px;font-size:12px}#steps button.on{background:#2f6fb3;color:#fff;border-color:#2f6fb3}
|
|
81
|
+
details{margin:8px 0}summary{font-weight:600;cursor:pointer}.row{display:flex;align-items:center;gap:6px;margin:3px 0}.row input[type=range]{flex:1}
|
|
82
|
+
.sw{display:inline-block;width:12px;height:12px;border-radius:2px}#now table{width:100%;border-collapse:collapse;font-size:13px}#now td{padding:2px 4px;border-bottom:1px solid #eee}
|
|
83
|
+
#now td.n{text-align:right;font-variant-numeric:tabular-nums}.bar{height:6px;background:#e8e8e8;border-radius:3px;overflow:hidden}.bar i{display:block;height:100%}
|
|
84
|
+
canvas#chart{width:100%;height:150px;background:#fff;border:1px solid #eee}.note{color:#666;font-size:12px;margin:4px 0}
|
|
85
|
+
#findings{padding-left:18px;font-size:12px}#findings li.fail{color:#b00020}#findings li.warn{color:#9a6700}
|
|
86
|
+
#pick{position:absolute;left:10px;bottom:10px;background:rgba(255,255,255,.95);border:1px solid #ccc;border-radius:6px;padding:6px 9px;font-size:13px;font-variant-numeric:tabular-nums;max-width:80%}
|
|
87
|
+
#coord{position:absolute;right:10px;bottom:10px;color:#888;font-size:12px;font-variant-numeric:tabular-nums}
|
|
88
|
+
@media (max-width:760px){main{flex-direction:column;height:auto}#stage{height:62vh}#side{width:auto;border-left:0;border-top:1px solid #ddd}}
|
|
89
|
+
`;
|
|
90
|
+
|
|
91
|
+
// The page's own script (plain browser JavaScript; the data is in #data)
|
|
92
|
+
const SCRIPT = String.raw`
|
|
93
|
+
const D = JSON.parse(document.getElementById('data').textContent), F = D.frames;
|
|
94
|
+
const $ = (id) => document.getElementById(id), view = $('view'), ctx = view.getContext('2d');
|
|
95
|
+
const COL = { ground: '#c9ccd1', body: '#2f6fb3', flexure: '#e07a1f', contact: '#7b3fe4', friction: '#0a9396', hand: '#d62828', spring: '#9c4a00' };
|
|
96
|
+
const LAYERS = [['frame', 'The frame', COL.ground, true], ['parts', 'Moving parts', COL.body, true], ['strain', 'Springs coloured by strain', '#3a9d3a', true],
|
|
97
|
+
['contact', 'Contact forces', COL.contact, true], ['friction', 'Friction, apart', COL.friction, false], ['hand', 'The hand', COL.hand, true], ['spring', 'Springs on the frame', COL.spring, false], ['labels', 'Newtons on the arrows', '#444', true]];
|
|
98
|
+
const on = Object.fromEntries(LAYERS.map(([k, , , v]) => [k, v]));
|
|
99
|
+
$('layers').innerHTML = LAYERS.map(([k, t, c]) => '<label class="row"><input type="checkbox" data-k="' + k + '"' + (on[k] ? ' checked' : '') + '><span class="sw" style="background:' + c + '"></span>' + t + '</label>').join('');
|
|
100
|
+
$('layers').addEventListener('change', (e) => { on[e.target.dataset.k] = e.target.checked; draw(); });
|
|
101
|
+
// The view: all of every frame, then wherever it's panned and zoomed
|
|
102
|
+
let lo = [Infinity, Infinity], hi = [-Infinity, -Infinity];
|
|
103
|
+
const grow = (l) => { for (let i = 0; i < l.length; i += 2) { lo = [Math.min(lo[0], l[i]), Math.min(lo[1], l[i + 1])]; hi = [Math.max(hi[0], l[i]), Math.max(hi[1], l[i + 1])]; } };
|
|
104
|
+
D.ground.forEach(grow); F.forEach((fr) => Object.values(fr.parts).forEach((ls) => ls.forEach(grow)));
|
|
105
|
+
let cam = { x: (lo[0] + hi[0]) / 2, y: (lo[1] + hi[1]) / 2, s: 1 }, W = 0, H = 0, dpr = 1;
|
|
106
|
+
const fit = () => { cam = { x: (lo[0] + hi[0]) / 2, y: (lo[1] + hi[1]) / 2, s: Math.min(W / (hi[0] - lo[0]), H / (hi[1] - lo[1])) * 0.92 }; };
|
|
107
|
+
const sx = (x) => (x - cam.x) * cam.s + W / 2, sy = (y) => H / 2 - (y - cam.y) * cam.s, wx = (px) => (px - W / 2) / cam.s + cam.x, wy = (py) => cam.y - (py - H / 2) / cam.s;
|
|
108
|
+
const resize = () => { dpr = devicePixelRatio || 1; const r = view.getBoundingClientRect(), first = !W; W = r.width; H = r.height; view.width = W * dpr; view.height = H * dpr; if (first) fit(); draw(); };
|
|
109
|
+
// Arrows: their length goes as the force, a big one of the steps a hand works (the shot's knocks aside) a fifth of the
|
|
110
|
+
// view (the slider scales it)
|
|
111
|
+
const mags = F.filter((fr) => !/fired/.test(fr.label)).flatMap((fr) => (fr.forces || []).map((f) => Math.hypot(...f.force))).filter((x) => x > 0.01).sort((a, b) => a - b);
|
|
112
|
+
const big = mags.length ? mags[Math.floor(mags.length * 0.9)] : 1;
|
|
113
|
+
const mmPerN = () => ((hi[0] - lo[0]) * 0.12 / big) * Math.pow(10, +$('scale').value);
|
|
114
|
+
// Strain colours: green at rest, amber at half the limit, red at it
|
|
115
|
+
const strainCol = (e) => { const u = D.limit ? Math.min(1, e / D.limit) : 0; const a = u < 0.5 ? [58, 157, 58] : [224, 160, 0], b = u < 0.5 ? [224, 160, 0] : [200, 30, 30], k = u < 0.5 ? u * 2 : (u - 0.5) * 2; return 'rgb(' + a.map((x, i) => Math.round(x + (b[i] - x) * k)).join(',') + ')'; };
|
|
116
|
+
let i = 0, playing = false, picked = null;
|
|
117
|
+
const pathOf = (loops) => { const p = new Path2D(); for (const l of loops) { p.moveTo(sx(l[0]), sy(l[1])); for (let k = 2; k < l.length; k += 2) p.lineTo(sx(l[k]), sy(l[k + 1])); p.closePath(); } return p; };
|
|
118
|
+
const arrows = () => { // the forces to draw this frame, as [x, y, fx, fy, colour, what]
|
|
119
|
+
const out = [], fr = F[i];
|
|
120
|
+
for (const f of fr.forces || []) {
|
|
121
|
+
if (f.kind === 'contact') {
|
|
122
|
+
const fr0 = f.friction || [0, 0], n = [f.force[0] - fr0[0], f.force[1] - fr0[1]];
|
|
123
|
+
if (on.friction) { if (on.contact) out.push([...f.at, ...n, COL.contact, f.on + ' pushed by ' + f.by]); out.push([...f.at, ...fr0, COL.friction, 'friction on ' + f.on + ' from ' + f.by]); }
|
|
124
|
+
else if (on.contact) out.push([...f.at, ...f.force, COL.contact, f.on + ' pushed by ' + f.by + (Math.hypot(...fr0) > 0.01 ? ' (friction in it)' : '')]);
|
|
125
|
+
} else if (f.kind === 'hand' && on.hand) out.push([...f.at, ...f.force, COL.hand, 'the hand on ' + f.on]);
|
|
126
|
+
else if (f.kind === 'spring' && on.spring) out.push([...f.at, ...f.force, COL.spring, f.by + ' pulling on the frame']);
|
|
127
|
+
}
|
|
128
|
+
return out.filter((a) => Math.hypot(a[2], a[3]) > 0.005);
|
|
129
|
+
};
|
|
130
|
+
function arrow(x, y, fx, fy, col, label) {
|
|
131
|
+
const k = mmPerN(), x1 = sx(x), y1 = sy(y), x2 = sx(x + fx * k), y2 = sy(y + fy * k), L = Math.hypot(x2 - x1, y2 - y1), h = Math.min(10, L * 0.35) * dpr / dpr;
|
|
132
|
+
ctx.strokeStyle = col; ctx.fillStyle = col; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke();
|
|
133
|
+
if (L > 1) { const a = Math.atan2(y2 - y1, x2 - x1); ctx.beginPath(); ctx.moveTo(x2, y2); ctx.lineTo(x2 - h * Math.cos(a - 0.4), y2 - h * Math.sin(a - 0.4)); ctx.lineTo(x2 - h * Math.cos(a + 0.4), y2 - h * Math.sin(a + 0.4)); ctx.closePath(); ctx.fill(); }
|
|
134
|
+
ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(x1 - 4, y1); ctx.lineTo(x1 + 4, y1); ctx.moveTo(x1, y1 - 4); ctx.lineTo(x1, y1 + 4); ctx.stroke(); // where it acts
|
|
135
|
+
if (on.labels) { ctx.font = '11px system-ui'; ctx.fillText(Math.hypot(fx, fy).toFixed(1) + ' N', x2 + 4, y2 - 4); }
|
|
136
|
+
}
|
|
137
|
+
function draw() {
|
|
138
|
+
if (!W) return;
|
|
139
|
+
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, W, H);
|
|
140
|
+
const fr = F[i];
|
|
141
|
+
if (on.frame && D.ground.length) { ctx.fillStyle = COL.ground; ctx.fill(pathOf(D.ground), 'evenodd'); }
|
|
142
|
+
if (on.parts) for (const [n, ls] of Object.entries(fr.parts)) {
|
|
143
|
+
const flex = D.kinds[n] === 'flexure';
|
|
144
|
+
ctx.fillStyle = flex ? (on.strain && fr.strain && fr.strain[n] != null ? strainCol(fr.strain[n]) : COL.flexure) : D.kinds[n] === 'body' ? COL.body : '#8aa';
|
|
145
|
+
ctx.globalAlpha = flex ? 1 : 0.85; ctx.fill(pathOf(ls), 'evenodd'); ctx.globalAlpha = 1;
|
|
146
|
+
}
|
|
147
|
+
for (const a of arrows()) arrow(...a);
|
|
148
|
+
if (picked) { // the picked force: its x and y, drawn as a crosshair and components
|
|
149
|
+
const [x, y, fx, fy, col, what] = picked, k = mmPerN(), x1 = sx(x), y1 = sy(y);
|
|
150
|
+
ctx.setLineDash([4, 3]); ctx.strokeStyle = '#333'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(0, y1); ctx.lineTo(W, y1); ctx.moveTo(x1, 0); ctx.lineTo(x1, H); ctx.stroke(); ctx.setLineDash([]);
|
|
151
|
+
arrow(x, y, fx, 0, '#555', ''); arrow(x, y, 0, fy, '#555', '');
|
|
152
|
+
}
|
|
153
|
+
$('label').textContent = fr.label + (fr.t && fr.from !== fr.to && !/fired/.test(fr.label) ? ' · ' + Math.round(fr.t * 100) + '%' : '');
|
|
154
|
+
$('scrub').value = i; side(); chart();
|
|
155
|
+
}
|
|
156
|
+
function side() {
|
|
157
|
+
const fr = F[i], rows = [];
|
|
158
|
+
for (const [n, e] of Object.entries(fr.energy || {})) { const most = Math.max(1e-6, ...F.map((g) => (g.energy || {})[n] || 0)); rows.push('<tr><td>' + n + ' stores</td><td class="n">' + e.toFixed(1) + ' mJ</td><td style="width:35%"><div class="bar"><i style="width:' + (100 * e / most).toFixed(0) + '%;background:' + COL.flexure + '"></i></div></td></tr>'); }
|
|
159
|
+
for (const [n, s] of Object.entries(fr.strain || {})) rows.push('<tr><td>' + n + ' strain</td><td class="n">' + (s * 100).toFixed(2) + '%</td><td><div class="bar"><i style="width:' + Math.min(100, 100 * s / (D.limit || 1)).toFixed(0) + '%;background:' + strainCol(s) + '"></i></div></td></tr>');
|
|
160
|
+
for (const f of (fr.forces || []).filter((f) => f.kind === 'hand')) rows.push('<tr><td>hand on ' + f.on + '</td><td class="n">' + Math.hypot(...f.force).toFixed(2) + ' N</td><td></td></tr>');
|
|
161
|
+
for (const f of (fr.forces || []).filter((f) => f.kind === 'contact').sort((a, b) => Math.hypot(...b.force) - Math.hypot(...a.force)).slice(0, 6)) rows.push('<tr><td>' + f.on + ' on ' + f.by + '</td><td class="n">' + Math.hypot(...f.force).toFixed(2) + ' N</td><td></td></tr>');
|
|
162
|
+
const s = D.shot && D.shot.exit && /fired/.test(fr.label) ? '<p class="note">The disc leaves at ' + D.shot.exit.speed.toFixed(1) + ' m/s after ' + (D.shot.exit.t * 1000).toFixed(1) + ' ms, with ' + (D.shot.exit.energy * 1000).toFixed(1) + ' mJ of the ' + (D.shot.stored * 1000).toFixed(1) + ' stored.</p>' : '';
|
|
163
|
+
$('now').innerHTML = (rows.length ? '<table>' + rows.join('') + '</table>' : '<p class="note">No forces recorded for this frame (a kinematic frame).</p>') + s;
|
|
164
|
+
}
|
|
165
|
+
function chart() { // the hand's force along the step this frame is in, a dot where it is
|
|
166
|
+
const c = $('chart'), g = c.getContext('2d'), w = c.width = c.clientWidth * dpr, h = c.height = 150 * dpr, fr = F[i];
|
|
167
|
+
g.clearRect(0, 0, w, h);
|
|
168
|
+
const tr = D.curves.find((x) => x.from === fr.from && x.to === fr.to), cv = tr && tr.curve[0];
|
|
169
|
+
if (!cv || cv.points.length < 2) { $('chartNote').textContent = 'No hand drives this step.'; return; }
|
|
170
|
+
const xs = cv.points.map((p) => Math.abs(p[0])), fs = cv.points.map((p) => p[1]), xm = Math.max(1e-9, ...xs), fmin = Math.min(0, ...fs), fmax = Math.max(1e-9, ...fs), m = 28 * dpr;
|
|
171
|
+
const px = (x) => m + (Math.abs(x) / xm) * (w - m * 1.5), py = (f) => h - m * 0.8 - ((f - fmin) / (fmax - fmin)) * (h - m * 1.4);
|
|
172
|
+
g.strokeStyle = '#ccc'; g.beginPath(); g.moveTo(m, py(0)); g.lineTo(w, py(0)); g.moveTo(m, 0); g.lineTo(m, h); g.stroke();
|
|
173
|
+
g.strokeStyle = COL.body; g.lineWidth = 2 * dpr; g.beginPath(); cv.points.forEach((p, k) => (k ? g.lineTo(px(p[0]), py(p[1])) : g.moveTo(px(p[0]), py(p[1])))); g.stroke();
|
|
174
|
+
const p = cv.points[Math.min(cv.points.length - 1, Math.round(fr.t * (cv.points.length - 1)))]; g.fillStyle = COL.hand; g.beginPath(); g.arc(px(p[0]), py(p[1]), 4 * dpr, 0, 7); g.fill();
|
|
175
|
+
g.fillStyle = '#555'; g.font = 11 * dpr + 'px system-ui'; g.fillText(fmax.toFixed(1) + ' N', 2, py(fmax) + 4 * dpr); g.fillText(xm.toFixed(1) + (cv.joint ? '' : ''), w - 40 * dpr, h - 4 * dpr);
|
|
176
|
+
const ev = (tr.events || [])[0];
|
|
177
|
+
$('chartNote').textContent = 'Driving ' + cv.joint + ' from ' + tr.from + ' to ' + tr.to + ': now ' + Math.abs(p[0]).toFixed(2) + ' (mm, or degrees turning) under ' + p[1].toFixed(2) + ' N' + (ev ? '; ' + ev.body + ' is let go ' + Math.round(ev.t * 100) + '% of the way' : '') + (tr.holding ? '; held by the catch: ' + Object.values(tr.holding).map((x) => x.toFixed(1) + ' N').join(', ') : '');
|
|
178
|
+
}
|
|
179
|
+
// Steps: a button for each state, and the shot
|
|
180
|
+
const starts = []; F.forEach((fr, k) => { const name = /fired/.test(fr.label) ? 'shot' : fr.t === 0 ? fr.from : null; if (name && (name !== 'shot' || !starts.some((s) => s.name === 'shot'))) starts.push({ name, k }); });
|
|
181
|
+
$('steps').innerHTML = starts.map((s) => '<button data-k="' + s.k + '">' + s.name + '</button>').join('');
|
|
182
|
+
$('steps').addEventListener('click', (e) => { if (e.target.dataset.k) { go(+e.target.dataset.k); stop(); } });
|
|
183
|
+
$('scrub').max = F.length - 1; $('scrub').addEventListener('input', (e) => { go(+e.target.value); stop(); });
|
|
184
|
+
const go = (k) => { i = Math.max(0, Math.min(F.length - 1, k)); picked = null; $('pick').hidden = true; for (const b of $('steps').children) b.classList.toggle('on', +b.dataset.k <= i && !(starts.find((s) => s.k > +b.dataset.k && s.k <= i))); draw(); };
|
|
185
|
+
// Playing: a frame each 70 ms (scaled), states held a moment, the shot slowed to be seen
|
|
186
|
+
let timer = null;
|
|
187
|
+
const hold = (fr) => (fr.t === 0 ? 500 : /fired/.test(fr.label) ? 140 : 70);
|
|
188
|
+
const tick = () => { if (!playing) return; const next = i + 1 >= F.length ? 0 : i + 1; go(next); timer = setTimeout(tick, hold(F[i]) / +$('speed').value); };
|
|
189
|
+
const stop = () => { playing = false; clearTimeout(timer); $('play').textContent = '▶'; };
|
|
190
|
+
$('play').onclick = () => { if (playing) return stop(); playing = true; $('play').textContent = '❚❚'; tick(); };
|
|
191
|
+
$('prev').onclick = () => { stop(); go(i - 1); }; $('next').onclick = () => { stop(); go(i + 1); }; $('fit').onclick = () => { fit(); draw(); };
|
|
192
|
+
$('scale').addEventListener('input', draw);
|
|
193
|
+
addEventListener('keydown', (e) => { if (e.key === ' ') { e.preventDefault(); $('play').click(); } else if (e.key === 'ArrowRight') $('next').click(); else if (e.key === 'ArrowLeft') $('prev').click(); else if (e.key === '0') $('fit').click(); });
|
|
194
|
+
// Pan, zoom (wheel, pinch), and a tap on a force picks it
|
|
195
|
+
const pts = new Map(); let moved = 0;
|
|
196
|
+
view.addEventListener('pointerdown', (e) => { view.setPointerCapture(e.pointerId); pts.set(e.pointerId, [e.offsetX, e.offsetY]); moved = 0; });
|
|
197
|
+
view.addEventListener('pointermove', (e) => {
|
|
198
|
+
$('coord').textContent = 'x ' + wx(e.offsetX).toFixed(1) + ' y ' + wy(e.offsetY).toFixed(1) + ' mm';
|
|
199
|
+
if (!pts.has(e.pointerId)) return;
|
|
200
|
+
const was = pts.get(e.pointerId); pts.set(e.pointerId, [e.offsetX, e.offsetY]);
|
|
201
|
+
if (pts.size === 1) { cam.x -= (e.offsetX - was[0]) / cam.s; cam.y += (e.offsetY - was[1]) / cam.s; moved += Math.hypot(e.offsetX - was[0], e.offsetY - was[1]); draw(); }
|
|
202
|
+
else if (pts.size === 2) { const [a, b] = [...pts.values()], other = a === pts.get(e.pointerId) ? b : a, d0 = Math.hypot(was[0] - other[0], was[1] - other[1]), d1 = Math.hypot(e.offsetX - other[0], e.offsetY - other[1]); if (d0 > 0) zoomAt((e.offsetX + other[0]) / 2, (e.offsetY + other[1]) / 2, d1 / d0); moved += 10; }
|
|
203
|
+
});
|
|
204
|
+
const up = (e) => { if (pts.size === 1 && moved < 5) pick(e.offsetX, e.offsetY); pts.delete(e.pointerId); };
|
|
205
|
+
view.addEventListener('pointerup', up); view.addEventListener('pointercancel', (e) => pts.delete(e.pointerId));
|
|
206
|
+
const zoomAt = (px, py, f) => { const x = wx(px), y = wy(py); cam.s *= f; cam.x = x - (px - W / 2) / cam.s; cam.y = y + (py - H / 2) / cam.s; draw(); };
|
|
207
|
+
view.addEventListener('wheel', (e) => { e.preventDefault(); zoomAt(e.offsetX, e.offsetY, Math.exp(-e.deltaY * 0.0015)); }, { passive: false });
|
|
208
|
+
view.addEventListener('dblclick', () => { fit(); draw(); });
|
|
209
|
+
function pick(px, py) { // the nearest arrow to the tap, along its length
|
|
210
|
+
const k = mmPerN(); let best = null;
|
|
211
|
+
for (const a of arrows()) { const x1 = sx(a[0]), y1 = sy(a[1]), x2 = sx(a[0] + a[2] * k), y2 = sy(a[1] + a[3] * k), ex = x2 - x1, ey = y2 - y1, l2 = ex * ex + ey * ey, u = l2 ? Math.max(0, Math.min(1, ((px - x1) * ex + (py - y1) * ey) / l2)) : 0, d = Math.hypot(px - x1 - u * ex, py - y1 - u * ey); if (d < 14 && (!best || d < best.d)) best = { d, a }; }
|
|
212
|
+
picked = best ? best.a : null;
|
|
213
|
+
if (picked) { const [x, y, fx, fy, , what] = picked; $('pick').hidden = false; $('pick').innerHTML = '<b>' + what + '</b><br>' + Math.hypot(fx, fy).toFixed(2) + ' N at ' + (Math.atan2(fy, fx) * 180 / Math.PI).toFixed(0) + '°: x ' + fx.toFixed(2) + ' N, y ' + fy.toFixed(2) + ' N<br>acting at (' + x.toFixed(1) + ', ' + y.toFixed(1) + ') mm'; }
|
|
214
|
+
else $('pick').hidden = true;
|
|
215
|
+
draw();
|
|
216
|
+
}
|
|
217
|
+
$('findings').innerHTML = D.findings.filter((f) => f.level !== 'pass').map((f) => '<li class="' + f.level + '">' + f.text.replace(/[<>&]/g, (c) => ({ '<': '<', '>': '>', '&': '&' })[c]) + '</li>').join('') || '<li>Every check passes.</li>';
|
|
218
|
+
// A link can open it at a frame (#f=12), zoomed on a point (&at=x,y&zoom=4); the address follows the frame
|
|
219
|
+
const q = new URLSearchParams(location.hash.slice(1));
|
|
220
|
+
addEventListener('resize', resize); resize();
|
|
221
|
+
if (q.has('at')) { const [x, y] = q.get('at').split(',').map(Number); cam.x = x; cam.y = y; cam.s *= +(q.get('zoom') || 1); }
|
|
222
|
+
go(+(q.get('f') || 0));
|
|
223
|
+
const follow = () => { try { history.replaceState(null, '', '#f=' + i); } catch (e) {} };
|
|
224
|
+
$('scrub').addEventListener('change', follow); $('steps').addEventListener('click', follow); $('prev').addEventListener('click', follow); $('next').addEventListener('click', follow);
|
|
225
|
+
`;
|
package/lib/preview.mjs
CHANGED
|
@@ -43,13 +43,15 @@ async function shoot(server, out, { width = 1800, height = 1200 } = {}) {
|
|
|
43
43
|
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
|
44
44
|
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cad-preview-'));
|
|
45
45
|
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
46
|
+
fs.rmSync(out, { force: true }); // an earlier picture mustn't pass for this one if Chrome fails
|
|
46
47
|
try {
|
|
47
48
|
await new Promise((resolve, reject) => {
|
|
48
49
|
if (!CHROME) return reject(new Error('no Chrome or Chromium found for previews: set CAD_CHROME to one'));
|
|
49
50
|
const p = spawn(CHROME, ['--headless=new', `--user-data-dir=${profile}`, '--no-first-run', '--hide-scrollbars', '--force-device-scale-factor=1',
|
|
50
51
|
`--window-size=${width},${height}`, '--virtual-time-budget=8000', `--screenshot=${out}`, `http://127.0.0.1:${server.address().port}/`], { stdio: 'ignore' });
|
|
51
52
|
const t = setTimeout(() => { p.kill(); reject(new Error('Chrome took too long to render the preview')); }, 60000);
|
|
52
|
-
p.on('
|
|
53
|
+
p.on('error', (e) => { clearTimeout(t); reject(new Error(`couldn't start Chrome for the preview (${CHROME}): ${e.message}. Set CAD_CHROME to a Chrome or Chromium`)); });
|
|
54
|
+
p.on('exit', () => { clearTimeout(t); fs.existsSync(out) ? resolve() : reject(new Error(`Chrome made no screenshot (${CHROME}): set CAD_CHROME to a Chrome or Chromium that runs headless`)); });
|
|
53
55
|
});
|
|
54
56
|
} finally {
|
|
55
57
|
server.close();
|
package/lib/rules.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Rules from files: the variables and expressions of @rulecad/variables, with rule sets read from the workspace's rules/
|
|
2
2
|
// (then the tool's) by name. Everything but loading is in @rulecad/variables, which needs no files and runs anywhere.
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import { host } from './host.mjs';
|
|
4
|
+
import { host, readJson } from './host.mjs';
|
|
5
5
|
import { RULE_DIRS, WS } from './workspace.mjs';
|
|
6
6
|
import { resolve as resolveWith } from '@rulecad/variables';
|
|
7
7
|
|
|
@@ -18,7 +18,7 @@ export function loadRuleSet(name, dir) {
|
|
|
18
18
|
host.writeText(own, host.readText(file));
|
|
19
19
|
console.error(`copied the ${name} rule set into rules/${name}.json: yours to keep and edit`);
|
|
20
20
|
}
|
|
21
|
-
return
|
|
21
|
+
return readJson(own);
|
|
22
22
|
}
|
|
23
23
|
// resolve() as @rulecad/variables describes it, loading the rule sets it isn't handed
|
|
24
24
|
export const resolve = (object, opts = {}) => resolveWith(object, { load: loadRuleSet, ...opts });
|
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 and files of
|
|
1
|
+
// The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures 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'];
|
|
8
|
+
const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures'];
|
|
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)
|
|
@@ -17,16 +17,19 @@ export async function resolve(spec, context, next) {
|
|
|
17
17
|
const fromDesign = check(spec, context), r = await next(spec, context);
|
|
18
18
|
return fromDesign ? after(spec, r) : r;
|
|
19
19
|
}
|
|
20
|
+
const isRelative = (spec) => spec.startsWith('./') || spec.startsWith('../');
|
|
21
|
+
// A design's own files are its project's. A path that leaves it is refused wherever it leads: into the workspace's
|
|
22
|
+
// node_modules, say, where any package may be. (The allowed packages are named bare, and may live anywhere.)
|
|
20
23
|
const after = (spec, r) => {
|
|
21
|
-
if (
|
|
24
|
+
if (isRelative(spec) && !r.url.startsWith(project)) throw deny(spec, 'it is outside the project');
|
|
22
25
|
return r;
|
|
23
26
|
};
|
|
27
|
+
// Everything under the project is the design's code, a node_modules folder there included
|
|
24
28
|
function check(spec, context) {
|
|
25
|
-
const fromDesign = project && context.parentURL?.startsWith(project)
|
|
29
|
+
const fromDesign = project && context.parentURL?.startsWith(project);
|
|
26
30
|
if (fromDesign) {
|
|
27
31
|
if (spec.startsWith('node:') || builtinModules.includes(spec)) throw deny(spec, 'a design only makes shapes (no files, network or programs)');
|
|
28
|
-
|
|
29
|
-
if (!relative && !ALLOWED.some((a) => spec === a || spec.startsWith(`${a}/`))) throw deny(spec, `only ${ALLOWED.join(', ')} and files in its project`);
|
|
32
|
+
if (!isRelative(spec) && !ALLOWED.some((a) => spec === a || spec.startsWith(`${a}/`))) throw deny(spec, `only ${ALLOWED.join(', ')} and files in its project`);
|
|
30
33
|
}
|
|
31
34
|
return fromDesign;
|
|
32
35
|
}
|
package/lib/sandbox-run.mjs
CHANGED
|
@@ -1,23 +1,37 @@
|
|
|
1
1
|
// The sandbox's runner: reads { js, values, meta } on stdin, runs the design's main(values), and writes its parts'
|
|
2
2
|
// faces (and the rules it read) as JSON on stdout. Started by sandbox.mjs, under Node's permission model.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
3
5
|
import * as shapes from '@rulecad/shapes';
|
|
4
|
-
import
|
|
6
|
+
import * as flexures from '@rulecad/flexures';
|
|
7
|
+
import { named, faces, unpack, watch } from './parts.mjs';
|
|
8
|
+
import { lineOf } from './errors.mjs';
|
|
5
9
|
|
|
6
10
|
for (const k of ['fetch', 'WebSocket', 'EventSource', 'XMLHttpRequest', 'Request', 'Response']) delete globalThis[k];
|
|
11
|
+
// and the ways round the import hook that process itself offers: Node's own modules by name, its internals, other
|
|
12
|
+
// processes. (sandbox.mjs's header says what this does and doesn't promise.)
|
|
13
|
+
const exit = process.exit.bind(process);
|
|
14
|
+
for (const k of ['getBuiltinModule', 'binding', '_linkedBinding', 'dlopen', 'kill', '_kill', '_getActiveHandles', '_getActiveRequests', '_debugProcess', '_startProfilerIdleNotifier']) {
|
|
15
|
+
if (k in process) Object.defineProperty(process, k, { value: undefined, configurable: false, writable: false });
|
|
16
|
+
}
|
|
7
17
|
const chunks = [];
|
|
8
18
|
for await (const c of process.stdin) chunks.push(c);
|
|
9
|
-
const { js, values, meta, engine } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
10
|
-
|
|
19
|
+
const { js, values, meta, engine, optional, stages } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
20
|
+
// A lamina's slow stages: read from the tool's cache (the workspace is readable), and what this run makes handed back
|
|
21
|
+
// with the parts for the tool to write (this process can't)
|
|
22
|
+
const kept = {}; // (what this run made of them)
|
|
23
|
+
if (stages) flexures.laminaCache({ salt: stages.salt, get: (k) => { try { return fs.readFileSync(path.join(stages.dir, `${k}.json`), 'utf8'); } catch { return undefined; } }, put: (k, text) => { kept[k] = text; } });
|
|
24
|
+
const stdout = process.stdout, done = (o) => stdout.write(JSON.stringify(o), () => exit(0));
|
|
25
|
+
// stdout carries the result, so what a design prints (console.log, to see a value) goes to stderr, which the tool passes on
|
|
26
|
+
console.log = console.info = console.debug = (...a) => console.error(...a);
|
|
11
27
|
try {
|
|
12
28
|
const mod = await import(js);
|
|
13
29
|
if (typeof mod.main !== 'function') throw Object.assign(new Error('the design has no exported main(v)'), { code: 'design.main' });
|
|
14
|
-
|
|
15
|
-
const
|
|
16
|
-
? new Proxy(v, { get: (t, r) => { if (typeof r === 'string' && r in t) read.add(`${k}.${r}`); return t[r]; } }) : v]));
|
|
17
|
-
watched.shapes = shapes; watched.ops = await shapes.ops(engine || 'jscad');
|
|
18
|
-
const made = await mod.main(watched);
|
|
30
|
+
const { v, read } = watch(values, { shapes, flexures, ops: await shapes.ops(engine || 'jscad') }, optional);
|
|
31
|
+
const { shapes: made, mechanism } = unpack(await mod.main(v));
|
|
19
32
|
const parts = named(made, meta).map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) }));
|
|
20
|
-
done({ parts, read: [...read] });
|
|
33
|
+
done({ parts, read: [...read], ...(mechanism ? { mechanism } : {}), ...(Object.keys(kept).length ? { stages: kept } : {}) });
|
|
21
34
|
} catch (e) {
|
|
22
|
-
|
|
35
|
+
const line = lineOf(e, js);
|
|
36
|
+
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' } });
|
|
23
37
|
}
|
package/lib/sandbox.mjs
CHANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
|
-
// Designs are code. A JSCAD design runs in a sandbox: another Node process with the permission model on
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
1
|
+
// Designs are code. A JSCAD design runs in a sandbox: another Node process with the permission model on. What that
|
|
2
|
+
// promises, whatever the design does: it can't write or delete files, start programs or workers, or load addons, and
|
|
3
|
+
// it reads only the workspace and the packages designs use. That much is Node's own boundary.
|
|
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 own project (no node: modules); the runner
|
|
6
|
+
// takes away fetch and its kin and process's own ways to Node's modules; and it is started with none of this
|
|
7
|
+
// process's environment (no tokens). Those close the ordinary roads to the network, not every one: before Node 25
|
|
8
|
+
// the permission model doesn't cover the network, so a design written to get round them might still reach it, and
|
|
9
|
+
// read the workspace as it does. So: run only designs you trust, as with any code.
|
|
10
|
+
// It gets its values as data and sends back its parts' faces. A workspace that trusts its designs sets
|
|
11
|
+
// "sandbox": false in cad.config.json (or CAD_TRUST=1). Board designs (engine pcb) run in the tool's own process,
|
|
12
|
+
// with the board engine.
|
|
8
13
|
import fs from 'node:fs';
|
|
9
14
|
import path from 'node:path';
|
|
10
15
|
import { spawn } from 'node:child_process';
|
|
11
16
|
import * as nodeModule from 'node:module';
|
|
12
17
|
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
13
|
-
import { WS, TOOL, config } from './workspace.mjs';
|
|
18
|
+
import { WS, TOOL, config, paths } from './workspace.mjs';
|
|
14
19
|
import { fromFaces } from './parts.mjs';
|
|
15
20
|
import { located } from './errors.mjs';
|
|
16
21
|
|
|
@@ -34,20 +39,25 @@ function readable() {
|
|
|
34
39
|
// Every node_modules above the workspace and the tool (package lookups read their links), and where links lead
|
|
35
40
|
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; } };
|
|
36
41
|
const dirs = [WS, TOOL, ...[...up(WS), ...up(TOOL)].filter((d) => fs.existsSync(d)),
|
|
37
|
-
...['@jscad/modeling', '@rulecad/shapes', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
|
|
42
|
+
...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
|
|
38
43
|
return [...new Set(dirs.filter(Boolean).flatMap((d) => [d, real(d)]).filter(Boolean))];
|
|
39
44
|
}
|
|
40
45
|
|
|
41
46
|
/**
|
|
42
47
|
* Run a design's main(values) in the sandbox: { parts, read } as the build makes them.
|
|
43
48
|
* @param {{ js: string }} d the design @param {object} values @param {object} meta the .json's parts @param {'jscad' | 'manifold'} [engine] v.ops's booleans
|
|
49
|
+
* @param {string[]} [optional] names main may read that aren't among the values (the display's own inputs)
|
|
50
|
+
* @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
|
|
44
51
|
*/
|
|
45
|
-
export function runSandboxed(d, values, meta, engine = 'jscad') {
|
|
52
|
+
export function runSandboxed(d, values, meta, engine = 'jscad', optional = [], stages = null) {
|
|
46
53
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
47
54
|
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')];
|
|
48
|
-
|
|
55
|
+
// (real paths: Node names an imported file by where it really is, so a workspace reached through a link still matches)
|
|
56
|
+
const js = fs.realpathSync(d.js), project = pathToFileURL(path.dirname(path.dirname(js)) + path.sep).href, stagesDir = paths.cache('stages');
|
|
57
|
+
// The child gets none of this process's environment but what Node needs to start: tokens and keys stay out of it
|
|
58
|
+
const env = Object.fromEntries(['PATH', 'SystemRoot', 'windir', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL', 'PHYS_DEBUG', 'LAMINA_TIMES'].filter((k) => process.env[k] != null).map((k) => [k, process.env[k]]));
|
|
49
59
|
return new Promise((resolve, reject) => {
|
|
50
|
-
const child = spawn(process.execPath, args, { stdio: ['pipe', 'pipe', 'pipe'], env: { ...
|
|
60
|
+
const child = spawn(process.execPath, args, { stdio: ['pipe', 'pipe', 'pipe'], env: { ...env, CAD_SANDBOX_PROJECT: project, NODE_NO_WARNINGS: '1' } }); // (its stderr is passed on: what the design prints, not Node's notes on its own flags)
|
|
51
61
|
const out = [], err = [];
|
|
52
62
|
child.stdout.on('data', (b) => out.push(b));
|
|
53
63
|
child.stderr.on('data', (b) => err.push(b));
|
|
@@ -57,9 +67,11 @@ export function runSandboxed(d, values, meta, engine = 'jscad') {
|
|
|
57
67
|
try { r = JSON.parse(Buffer.concat(out).toString('utf8')); } catch {
|
|
58
68
|
return reject(located(new Error(`the design's sandbox stopped: ${Buffer.concat(err).toString('utf8').trim().split('\n').slice(-3).join(' ') || 'no output'}`), d.js, 'design.sandbox'));
|
|
59
69
|
}
|
|
60
|
-
if (
|
|
61
|
-
|
|
70
|
+
if (err.length) process.stderr.write(Buffer.concat(err)); // what the design printed
|
|
71
|
+
if (r.error) return reject(located(Object.assign(new Error(r.error.message), { code: r.error.code, ...(r.error.line ? { line: r.error.line } : {}), ...(r.error.syntax ? { name: 'SyntaxError' } : {}) }), d.js, r.error.code || 'design.run'));
|
|
72
|
+
if (stages) for (const [k, text] of Object.entries(r.stages || {})) stages.put(k, text);
|
|
73
|
+
resolve({ parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })), read: new Set(r.read), mechanism: r.mechanism || null });
|
|
62
74
|
});
|
|
63
|
-
child.stdin.end(JSON.stringify({ js: `${pathToFileURL(
|
|
75
|
+
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 } } : {}) }));
|
|
64
76
|
});
|
|
65
77
|
}
|
package/lib/schema.mjs
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { near } from './errors.mjs';
|
|
7
8
|
|
|
8
9
|
const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'schemas');
|
|
9
10
|
const cache = new Map();
|
|
@@ -15,13 +16,6 @@ export function schema(name) {
|
|
|
15
16
|
|
|
16
17
|
const typeOf = (v) => (v === null ? 'null' : Array.isArray(v) ? 'array' : Number.isInteger(v) ? 'integer' : typeof v);
|
|
17
18
|
const fits = (v, t) => t === typeOf(v) || (t === 'number' && typeof v === 'number') || (t === 'integer' && Number.isInteger(v));
|
|
18
|
-
// The closest allowed name to a typo: one or two letters out
|
|
19
|
-
function near(word, names) {
|
|
20
|
-
const d = (a, b) => { const m = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]); for (let j = 1; j <= b.length; j++) m[0][j] = j;
|
|
21
|
-
for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) m[i][j] = Math.min(m[i - 1][j] + 1, m[i][j - 1] + 1, m[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); return m[a.length][b.length]; };
|
|
22
|
-
const best = names.map((n) => [n, d(word, n)]).sort((x, y) => x[1] - y[1])[0];
|
|
23
|
-
return best && best[1] <= 2 ? best[0] : null;
|
|
24
|
-
}
|
|
25
19
|
|
|
26
20
|
/**
|
|
27
21
|
* Problems with a value against a schema: [{ path, message }], empty when it's valid.
|
package/lib/workspace.mjs
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// viewUrl the model page that links open (the public one by default: it reads links as data, nothing is uploaded)
|
|
8
8
|
// targets optional extras: show (put a model on display: a module of your own) and shorten (short links: "gist")
|
|
9
9
|
import path from 'node:path';
|
|
10
|
-
import { host } from './host.mjs';
|
|
10
|
+
import { host, readJson } from './host.mjs';
|
|
11
11
|
import { fileURLToPath } from 'node:url';
|
|
12
12
|
|
|
13
13
|
export const TOOL = fileURLToPath(new URL('..', import.meta.url)).replace(/[\\/]$/, '');
|
|
@@ -21,9 +21,14 @@ function find() {
|
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
export const WS = find();
|
|
24
|
+
// A cad.config.json that doesn't parse is kept as configError for the command to report in its own words: this runs
|
|
25
|
+
// as the tool is loaded, where an error would reach a person as a stack trace
|
|
26
|
+
export let configError = null;
|
|
24
27
|
export const config = (() => {
|
|
25
28
|
const f = path.join(WS, 'cad.config.json');
|
|
26
|
-
|
|
29
|
+
let own = {};
|
|
30
|
+
try { if (host.exists(f)) own = readJson(f); } catch (e) { configError = e; }
|
|
31
|
+
return { printer: 'x1c', viewUrl: 'https://jonibach.github.io/rulecad/', targets: {}, ...own };
|
|
27
32
|
})();
|
|
28
33
|
|
|
29
34
|
// Rule sets: the workspace's own first (your copies, with your measurements), then the published ones (@rulecad/rules).
|
|
@@ -41,5 +46,5 @@ export const paths = {
|
|
|
41
46
|
// The printer a project's prints are checked against
|
|
42
47
|
export const printerOf = (project) => {
|
|
43
48
|
const f = project && path.join(paths.project(project), 'project.json');
|
|
44
|
-
return (f && host.exists(f) &&
|
|
49
|
+
return (f && host.exists(f) && readJson(f).printer) || config.printer;
|
|
45
50
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/cad",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.25",
|
|
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": {
|
|
@@ -15,7 +15,14 @@
|
|
|
15
15
|
"./versions": "./lib/versions.mjs",
|
|
16
16
|
"./preview": "./lib/preview.mjs",
|
|
17
17
|
"./targets": "./lib/targets.mjs",
|
|
18
|
-
"./threemf": "./lib/threemf.mjs"
|
|
18
|
+
"./threemf": "./lib/threemf.mjs",
|
|
19
|
+
"./host": "./lib/host.mjs",
|
|
20
|
+
"./links": "./lib/links.mjs",
|
|
21
|
+
"./edit": "./lib/edit.mjs",
|
|
22
|
+
"./explain": "./lib/explain.mjs",
|
|
23
|
+
"./schema": "./lib/schema.mjs",
|
|
24
|
+
"./errors": "./lib/errors.mjs",
|
|
25
|
+
"./optimise": "./lib/optimise.mjs"
|
|
19
26
|
},
|
|
20
27
|
"files": [
|
|
21
28
|
"bin",
|
|
@@ -23,6 +30,7 @@
|
|
|
23
30
|
"schemas",
|
|
24
31
|
"templates",
|
|
25
32
|
"README.md",
|
|
33
|
+
"TUTORIAL.md",
|
|
26
34
|
"LICENSE",
|
|
27
35
|
"AGENTS.md"
|
|
28
36
|
],
|
|
@@ -44,10 +52,10 @@
|
|
|
44
52
|
"directory": "packages/cad"
|
|
45
53
|
},
|
|
46
54
|
"dependencies": {
|
|
47
|
-
"@rulecad/variables": "^0.2.
|
|
55
|
+
"@rulecad/variables": "^0.2.2",
|
|
48
56
|
"@rulecad/keyboard-layout": "^0.1.2",
|
|
49
|
-
"@rulecad/printcheck": "^0.
|
|
50
|
-
"@rulecad/fit": "^0.
|
|
57
|
+
"@rulecad/printcheck": "^0.2.0",
|
|
58
|
+
"@rulecad/fit": "^0.3.0",
|
|
51
59
|
"@rulecad/model-link": "^0.2.0",
|
|
52
60
|
"@rulecad/versions": "^0.1.0",
|
|
53
61
|
"@rulecad/shapes": "^0.4.1",
|
|
@@ -55,10 +63,11 @@
|
|
|
55
63
|
"@jscad/modeling": "^2.12.0",
|
|
56
64
|
"three": "^0.186.1",
|
|
57
65
|
"@rulecad/fea": "^0.2.1",
|
|
58
|
-
"@rulecad/topopt": "^0.2.2"
|
|
66
|
+
"@rulecad/topopt": "^0.2.2",
|
|
67
|
+
"@rulecad/flexures": "^0.3.0"
|
|
59
68
|
},
|
|
60
69
|
"peerDependencies": {
|
|
61
|
-
"@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0"
|
|
70
|
+
"@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0 || ^0.4.0"
|
|
62
71
|
},
|
|
63
72
|
"peerDependenciesMeta": {
|
|
64
73
|
"@rulecad/pcb": {
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"fits": { "type": "array", "items": { "$ref": "#/$defs/fit" } },
|
|
19
19
|
"joints": { "type": "array", "items": { "$ref": "#/$defs/joint" } },
|
|
20
20
|
"loops": { "type": "array", "items": { "$ref": "#/$defs/loop" } },
|
|
21
|
-
"poses": { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { "$ref": "#/$defs/values" } } },
|
|
21
|
+
"poses": { "type": "object", "description": "Named sets of joint values ({ \"hinge\": 90 }), and of items' variables (\"action.travel\": 25: a flexure drawn bent in that pose, printed as drawn)", "additionalProperties": { "type": "object", "additionalProperties": { "$ref": "#/$defs/values" } } },
|
|
22
22
|
"pose": { "type": "string" }
|
|
23
23
|
},
|
|
24
24
|
"$defs": {
|
|
@@ -85,7 +85,7 @@
|
|
|
85
85
|
"additionalProperties": false,
|
|
86
86
|
"properties": {
|
|
87
87
|
"label": { "type": "string" },
|
|
88
|
-
"role": { "enum": ["part", "support", "reference"
|
|
88
|
+
"role": { "enum": ["part", "support"], "description": "support: printed, then removed (a breakaway pillar). A thing that isn't printed at all is an object with \"role\": \"reference\"" },
|
|
89
89
|
"filament": { "type": "string" },
|
|
90
90
|
"display": { "type": "boolean" },
|
|
91
91
|
"mirror": { "type": "boolean" },
|