@rulecad/cad 0.7.26 → 0.7.31

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/README.md CHANGED
@@ -272,6 +272,10 @@ other items' variables, so a keycap can sit exactly where its slot meets the swi
272
272
  reach it. Run only designs you trust. It gets its values as data and returns its parts; what it prints
273
273
  (`console.log`) comes out on stderr. A workspace that trusts its designs sets `"sandbox": false` in cad.config.json
274
274
  (or `CAD_TRUST=1`). Board designs (engine pcb) run in the tool's process, with the board engine.
275
+ - **Trust, asked once:** what a workspace's cad.config.json asks to run outside the sandbox (`"sandbox": false`, a
276
+ target that is a module of its own) isn't done until you run `cad trust` in it. That records the folder and what it
277
+ asked for in your own list (`~/.config/rulecad/trusted.json`, or `$CAD_TRUSTED`), so a workspace cloned from
278
+ elsewhere can't turn the sandbox off on its first command; one that later asks for more is asked again.
275
279
  - **Mistakes are named:** a design that reads a variable that isn't there (`v.widht`) stops with the name it
276
280
  probably meant, not a shape drawn from `undefined`; errors in a design carry its file and line.
277
281
  - **Units:** `cad check` warns where an expression mixes units (millimetres added to degrees, a sine of a length) or
package/bin/cad.mjs CHANGED
@@ -4,7 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { execFileSync } from 'node:child_process';
6
6
  import { fmt, loadRuleSet } from '../lib/rules.mjs';
7
- import { WS, TOOL, paths, config, configError, printerOf } from '../lib/workspace.mjs';
7
+ import { WS, TOOL, paths, config, configError, printerOf, asks, trust, trusted } from '../lib/workspace.mjs';
8
8
  import { fromKLE } from '@rulecad/keyboard-layout';
9
9
  import { target, hasTarget } from '../lib/targets.mjs';
10
10
  import { locate, build, pick, lint, readObject, printer, pcbEngine, objectSets } from '../lib/design.mjs';
@@ -17,6 +17,7 @@ import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, motionData } f
17
17
  import { valuesOf, why } from '../lib/explain.mjs';
18
18
  import { errorData, near } from '../lib/errors.mjs';
19
19
  import { schemaFindings } from '../lib/schema.mjs';
20
+ import { readJson } from '../lib/host.mjs';
20
21
  import { optimised, readProblem, analysePart, picture, problemFile } from '../lib/optimise.mjs';
21
22
  import { evaluate } from '../lib/rules.mjs';
22
23
  import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
@@ -43,6 +44,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
43
44
  cad import-kle <file> <project>/<name> a keyboard layout from keyboard-layout-editor.com, into layouts/
44
45
  cad clone <board.kicad_pcb | GitHub link> <name> a published circuit board into rules/<name>.json, to redraw by rules [--source, --licence]
45
46
  cad agents AGENTS.md: how an AI agent should design in this workspace
47
+ cad trust allow what this workspace's cad.config.json asks (no sandbox, its own targets)
46
48
  cad rules <project>/<object> every variable: value, the rule behind it, its source
47
49
  cad values <project>/<object> [names…] the object's variables, resolved [--json]
48
50
  cad set <project>/<object> name=value … change variables, keeping the file's layout [--unit, --rule, --label, --new to add one]
@@ -97,7 +99,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
97
99
  cad --version this tool's version`;
98
100
 
99
101
  // Every command and option there is: a misspelt one is refused by name, not passed over
100
- const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
102
+ const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
101
103
  'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'match', 'variants', 'compare', 'help'];
102
104
  const OPTIONS = ['all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
103
105
  'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
@@ -134,6 +136,15 @@ const showProgress = (e) => {
134
136
  process.stderr.write(`\r\x1b[K${e.stage === 'sweep' ? `sweeping ${e.joint} ${e.step}/${e.steps}` : `building ${e.item} (${e.done})`}`);
135
137
  };
136
138
  // Findings: as text (a mark and the words), or with --json as data: { ...about, findings: [{ level, text, code, values, refs, at }] }
139
+ // Every measurement says why it is what it is, and every object its name: a variable with a value and no rule (or an
140
+ // object with no name) is a warning, not a failure, so an older design still builds
141
+ function unruled(object, file) {
142
+ const out = [], none = Object.entries(object.variables || {}).filter(([, v]) => v && v.value !== undefined && !v.type && !v.rule).map(([n]) => n);
143
+ if (none.length) out.push({ level: 'warn', text: `${none.length === 1 ? 'a variable has' : `${none.length} variables have`} no rule saying why ${none.length === 1 ? 'it is' : 'they are'} what ${none.length === 1 ? 'it is' : 'they are'}: ${none.slice(0, 6).join(', ')}${none.length > 6 ? ', …' : ''}`, code: 'var.no-rule', refs: { file, variables: none } });
144
+ if (!object.name) out.push({ level: 'warn', text: 'the object has no "name": give it the file\'s name, so links and releases say what it is', code: 'object.no-name', refs: { file } });
145
+ return out;
146
+ }
147
+
137
148
  function report(findings, about = {}) {
138
149
  if (opt('json')) console.log(JSON.stringify({ ...about, findings }, null, 2));
139
150
  else { const mark = { pass: '✓', warn: '!', fail: '✗', info: '·' }; for (const r of findings) console.log(` ${mark[r.level]} ${r.text}`); }
@@ -326,9 +337,21 @@ async function main() {
326
337
  return console.log(`made projects/${project}/objects/${name}.{js,json}`);
327
338
  }
328
339
 
340
+ if (cmd === 'trust') { // this workspace may do what its cad.config.json asks (designs outside the sandbox, its own targets)
341
+ const what = asks();
342
+ if (!what.length) return console.log('this workspace asks for nothing outside the sandbox: nothing to trust');
343
+ trust();
344
+ return console.log(`trusted ${WS} for ${what.join(' and ')} (kept in your own list; a workspace that asks for more is asked again)`);
345
+ }
346
+
329
347
  if (cmd === 'agents') { // the notes for AI agents, into this workspace (AGENTS.md, and CLAUDE.md pointing at it)
330
- const to = path.join(WS, 'AGENTS.md');
331
- fs.copyFileSync(path.join(TOOL, 'AGENTS.md'), to);
348
+ const to = path.join(WS, 'AGENTS.md'), ours = fs.readFileSync(path.join(TOOL, 'AGENTS.md'), 'utf8'), record = paths.cache('agents.md');
349
+ // An AGENTS.md as cad agents last wrote it (or, with no record of that, one that is an earlier copy of ours) is
350
+ // brought up to date; one edited here is kept, unless --force
351
+ const mine = fs.existsSync(to) ? fs.readFileSync(to, 'utf8') : null, last = fs.existsSync(record) ? fs.readFileSync(record, 'utf8') : null;
352
+ const ourCopy = mine === null || mine === ours || (last !== null ? mine === last : mine.startsWith(ours.split('\n')[0]));
353
+ if (!ourCopy && !opt('force')) throw new Error('AGENTS.md here has been edited (or isn\'t rulecad\'s): it is kept as it is (cad agents --force replaces it)');
354
+ fs.writeFileSync(to, ours); fs.mkdirSync(path.dirname(record), { recursive: true }); fs.writeFileSync(record, ours);
332
355
  const claude = path.join(WS, 'CLAUDE.md');
333
356
  if (!fs.existsSync(claude)) fs.writeFileSync(claude, '@AGENTS.md\n');
334
357
  else if (!fs.readFileSync(claude, 'utf8').includes('@AGENTS.md')) fs.appendFileSync(claude, '\n@AGENTS.md\n');
@@ -367,6 +390,11 @@ async function main() {
367
390
  if (isAssembly(ref)) return assembly(cmd, ref);
368
391
  const [base, at] = ref.split('@');
369
392
  const d = at ? materialise(locate(base), at) : locate(ref), set = sets();
393
+ // A check reads the files against their schemas first: a broken .json is said as that, before a build fails on it
394
+ if (cmd === 'check' && !at && fs.existsSync(d.json)) {
395
+ const bad = schemaFindings(readJson(d.json), 'object', path.relative(WS, d.json)).filter((f) => f.level === 'fail'); // (readJson: broken JSON is named with its file)
396
+ if (bad.length) { say(`${d.project}/${d.name}`); report(bad, { object: `${d.project}/${d.name}` }); process.exitCode = 1; return; }
397
+ }
370
398
  const b = opt('part') ? pick(await build(d, set), { part: opt('part') }) : await build(d, set);
371
399
  const tag = `${d.variant ? `-${d.variant}` : ''}${suffix(set)}${opt('part') ? `-${opt('part')}` : ''}`; // in file names
372
400
  const title = `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`, version = b.object.version || '0.0.0';
@@ -390,6 +418,7 @@ async function main() {
390
418
  }
391
419
 
392
420
  if (cmd === 'rules') {
421
+ if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, variables: b.entries.map((e) => ({ name: e.name, value: e.value, unit: e.unit || null, expr: e.expr || null, rule: e.rule || null, ...(e.source ? { source: e.source, kind: e.kind || null } : {}) })) }, null, 2));
393
422
  for (const e of b.entries) console.log(`${e.name.padEnd(18)} ${`${fmt(e.value)} ${e.unit || ''}`.padEnd(14)} ${e.expr ? `= ${e.expr} ` : ''}${e.rule || ''}${e.source ? ` [${e.kind ? `${e.kind}: ` : ''}${e.source}]` : ''}${e.set ? ' (set)' : ''}`);
394
423
  return;
395
424
  }
@@ -405,6 +434,7 @@ async function main() {
405
434
  const failed = report([
406
435
  ...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
407
436
  ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
437
+ ...unruled(b.object, own(d.json)),
408
438
  raw.length ? { level: 'fail', text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}`, code: 'lint.numbers', refs: { file, numbers: raw } }
409
439
  : { level: 'pass', text: 'every measurement is a variable', code: 'lint.numbers', refs: { file } },
410
440
  ...(b.object.role === 'reference'
@@ -444,8 +474,10 @@ async function main() {
444
474
  fs.mkdirSync(path.dirname(out), { recursive: true });
445
475
  const fil = filaments(d.project); // one object, a part per part, each in its filament
446
476
  fs.writeFileSync(out, await threemf([{ name: `${d.name}${d.variant ? ` ${d.variant}` : ''}`, parts: b.parts.map((p) => ({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) })) }], { filaments: slots(fil) }));
447
- report(filamentNotes(b.parts, fil));
477
+ const notes = filamentNotes(b.parts, fil);
448
478
  if (opt('open')) openInSlicer(out);
479
+ if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, version, file: path.relative(WS, out), findings: notes }, null, 2)); // (one object: the file is in it, not a line after)
480
+ report(notes);
449
481
  return console.log(out);
450
482
  }
451
483
 
@@ -520,7 +552,7 @@ async function explainValue(ref) {
520
552
  async function board(cmd, d, b, { title, version, tag }) {
521
553
  const pcb = await pcbEngine(), name = `${d.name}@${version}${tag}`;
522
554
  if (cmd === 'check') {
523
- console.log(`${title} ${version}`);
555
+ say(`${title} ${version}`);
524
556
  const raw = lint(fs.readFileSync(d.js, 'utf8'));
525
557
  // The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
526
558
  const own = (f) => path.relative(WS, f), ruleFiles = (b.object.uses || []).filter((u) => !u.includes('/')).map((u) => path.join(WS, 'rules', `${u}.json`)).filter((f) => fs.existsSync(f));
@@ -532,8 +564,8 @@ async function board(cmd, d, b, { title, version, tag }) {
532
564
  ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
533
565
  raw.length ? { level: 'fail', text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}` } : { level: 'pass', text: 'every measurement is a variable' },
534
566
  ...(await pcb.checks(b.circuit, b.values, b.matrix, b.source)),
535
- ]);
536
- if (b.object.orientation) console.log(` ${b.object.orientation}`);
567
+ ], { object: `${d.project}/${d.name}`, title, version });
568
+ if (b.object.orientation) say(` ${b.object.orientation}`);
537
569
  process.exitCode = failed ? 1 : 0;
538
570
  return;
539
571
  }
@@ -554,7 +586,9 @@ async function board(cmd, d, b, { title, version, tag }) {
554
586
  const written = [zip];
555
587
  for (const [f, t] of Object.entries(await pcb.kicadFiles(b.circuit, name))) { fs.writeFileSync(path.join(dir, f), t); written.push(path.join(dir, f)); }
556
588
  if (b.matrix) { const f = path.join(dir, `${name}-matrix.json`); fs.writeFileSync(f, JSON.stringify(b.matrix, null, 2) + '\n'); written.push(f); }
557
- report([{ level: 'pass', text: `fab zip: ${Object.keys(fab).length} files (${Object.keys(fab).filter((f) => !/\.(csv|DRL)$/.test(f)).length} Gerber layers, 2 drill files, BOM, placement)` }]);
589
+ const done = [{ level: 'pass', text: `fab zip: ${Object.keys(fab).length} files (${Object.keys(fab).filter((f) => !/\.(csv|DRL)$/.test(f)).length} Gerber layers, 2 drill files, BOM, placement)` }];
590
+ if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, version, files: written.map((f) => path.relative(WS, f)), findings: done }, null, 2));
591
+ report(done);
558
592
  for (const f of written) console.log(f);
559
593
  }
560
594
 
@@ -707,7 +741,7 @@ function changelog(dir, heading, message, reasons) {
707
741
  const old = fs.existsSync(f) ? fs.readFileSync(f, 'utf8').replace(/^# .*\n+/, '') : '';
708
742
  const entry = `## ${heading}\n\n${message}\n${reasons.length ? `\n${reasons.map((r) => `- ${r.text} (${r.kind})`).join('\n')}\n` : ''}`;
709
743
  fs.writeFileSync(f, `# ${path.basename(dir)} changelog\n\n${entry}\n${old}`);
710
- return path.relative(WS, f);
744
+ return path.relative(WS, f).split(path.sep).join('/'); // (git's terms: forward slashes)
711
745
  }
712
746
 
713
747
  async function releaseObject(d, { batch = false } = {}) {
@@ -730,7 +764,7 @@ async function releaseObject(d, { batch = false } = {}) {
730
764
  console.log(`${tag} (${kind}${last ? `, from ${last.version}` : ''})`);
731
765
  for (const r of reasons) console.log(` ${r.kind.padEnd(5)} ${r.text}`);
732
766
  if (opt('dry-run')) return;
733
- const allowed = [...files(d, object), `projects/${d.project}/CHANGELOG.md`, path.relative(WS, printsFile(d))];
767
+ const allowed = [...files(d, object), `projects/${d.project}/CHANGELOG.md`, path.relative(WS, printsFile(d)).split(path.sep).join('/')];
734
768
  if (!batch) onlyChanged(allowed); // releaseAll checked the whole tree first
735
769
  fs.writeFileSync(d.json, setAt(fs.readFileSync(d.json, 'utf8'), ['version'], version)); // the object's own version (added, if it had none), nothing else
736
770
  const log = changelog(d.dir, `${d.name} ${version} (${kind}), ${today()}`, message, reasons);
@@ -799,6 +833,7 @@ async function releaseAll(project) {
799
833
  // The object's variants, one a line: name, then its inputs
800
834
  function variants(d) {
801
835
  const v = readObject(d).variants || {};
836
+ if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, variants: v }, null, 2));
802
837
  if (!Object.keys(v).length) return console.log(`${d.name} has no variants: add "variants": { "name": { …inputs } } to its .json`);
803
838
  for (const [n, set] of Object.entries(v)) console.log(`${`${d.project}/${d.name}:${n}`.padEnd(32)} ${Object.entries(set).map(([k, x]) => `${k}=${x}`).join(', ')}`);
804
839
  }
@@ -832,11 +867,13 @@ async function status(project) {
832
867
  async function history(ref) {
833
868
  const [project, name] = ref.split('/');
834
869
  if (!name) {
870
+ if (opt('json')) return console.log(JSON.stringify({ project, releases: tags(project).reverse() }, null, 2));
835
871
  for (const t of tags(project).reverse()) console.log(`${t.tag} ${t.date} ${t.kind} ${t.message}`);
836
872
  return status(project);
837
873
  }
838
874
  const d = locate(ref), done = prints(d);
839
875
  const s = await since(d);
876
+ if (opt('json')) return console.log(JSON.stringify({ object: ref, unreleased: s.kind && s.last ? { kind: s.kind, reasons: s.reasons.map((r) => r.text) } : null, releases: tags(d.project, d.name).reverse().map((t) => ({ ...t, prints: done.filter((x) => x.version === t.version) })) }, null, 2));
840
877
  if (s.kind && s.last) { console.log(`unreleased (needs ${s.kind}):`); for (const r of s.reasons) console.log(` ${r.text}`); }
841
878
  for (const t of tags(d.project, d.name).reverse()) {
842
879
  console.log(`${t.version.padEnd(8)} ${t.date} ${t.kind.padEnd(5)} ${t.message}`);
package/lib/edit.mjs CHANGED
@@ -39,7 +39,14 @@ export async function setVariables(ref, changes, { create = false } = {}) {
39
39
  }
40
40
  const json = write(d.json, text, 'object');
41
41
  try { // the variables must still resolve: an unknown name or a loop puts the file back as it was
42
- resolve(json, { sets: (await objectSets(d, readObject(d))).sets });
42
+ const { values } = resolve(json, { sets: (await objectSets(d, readObject(d))).sets });
43
+ // and each changed value must lie within the variable's own range, where it has one (a tweak's min and max)
44
+ for (const name of Object.keys(changes)) {
45
+ const t = json.variables?.[name]?.tweak, v = values[name];
46
+ if (!t || typeof v !== 'number') continue;
47
+ const lo = typeof t.min === 'number' ? t.min : -Infinity, hi = typeof t.max === 'number' ? t.max : Infinity;
48
+ if (v < lo || v > hi) throw new CadError('edit.range', `${name} = ${v} is outside its range, ${t.min ?? '…'} to ${t.max ?? '…'} (change the range first if it should go there)`, { file: d.json, path: `variables.${name}` });
49
+ }
43
50
  } catch (e) { fs.writeFileSync(d.json, before); throw Object.assign(e, { file: d.json, message: `not changed: ${e.message}` }); }
44
51
  return { file: d.json, changed: Object.keys(changes) };
45
52
  }
@@ -66,6 +73,17 @@ export function addToAssembly(ref, what, entry) {
66
73
  if (getAt(text, [list]) === undefined) text = setAt(text, [list], []);
67
74
  const ids = (getAt(text, [list]) || []).map((x) => x.id).filter(Boolean);
68
75
  if (entry.id && ids.includes(entry.id)) throw new CadError('edit.duplicate', `${ref} already has a ${what} "${entry.id}"`, { file });
76
+ // a fit names parts as item.part: the item must be in the assembly, and the part one its object declares (or body)
77
+ if (what === 'fit') for (const side of ['a', 'b']) {
78
+ const named = entry[side]; if (typeof named !== 'string') continue;
79
+ const [item, part = 'body'] = named.split('@')[0].split('.'), it = (getAt(text, ['items']) || []).find((x) => x.id === item);
80
+ if (!it) throw new CadError('edit.part', `fit ${side}: no item "${item}" in ${ref} (items: ${(getAt(text, ['items']) || []).map((x) => x.id).join(', ') || 'none'})`, { file });
81
+ if (it.object) {
82
+ const [project] = ref.split('/'), obj = path.join(paths.project(project), 'objects', `${String(it.object).split(/[@:]/)[0]}.json`);
83
+ const parts = fs.existsSync(obj) ? Object.keys(JSON.parse(fs.readFileSync(obj, 'utf8')).parts || { body: {} }) : null;
84
+ if (parts && !parts.includes(part)) throw new CadError('edit.part', `fit ${side}: ${it.object} has no part "${part}" (parts: ${parts.join(', ')})`, { file });
85
+ }
86
+ }
69
87
  text = appendAt(text, [list], entry);
70
88
  }
71
89
  write(file, text, 'assembly');
package/lib/live.mjs CHANGED
@@ -221,7 +221,13 @@ if (!isMainThread && workerData?.flag) {
221
221
  } else if (req.url.startsWith('/three/') && fs.existsSync(path.join(THREE, path.basename(req.url)))) {
222
222
  res.writeHead(200, { 'content-type': 'text/javascript' }); res.end(fs.readFileSync(path.join(THREE, path.basename(req.url))));
223
223
  } else if (req.url.startsWith('/frame/') && frames[Number(req.url.slice(7))]) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(frames[Number(req.url.slice(7))]));
224
- } else if (req.url === '/stop' && req.method === 'POST') { Atomics.store(flag, 0, 1); res.end('stopping'); }
224
+ } else if (req.url === '/stop' && req.method === 'POST') {
225
+ // Only this page may stop the run: a request from another page (any site open in the browser can post here) comes
226
+ // with that page's Origin, and is refused
227
+ const origin = req.headers.origin, host = req.headers.host;
228
+ if (origin && origin !== `http://${host}`) { res.writeHead(403); return res.end('not from the live view'); }
229
+ Atomics.store(flag, 0, 1); res.end('stopping');
230
+ }
225
231
  else if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page(title)); }
226
232
  else { res.writeHead(404); res.end(); }
227
233
  });
package/lib/sandbox.mjs CHANGED
@@ -15,7 +15,7 @@ import path from 'node:path';
15
15
  import { spawn } from 'node:child_process';
16
16
  import * as nodeModule from 'node:module';
17
17
  import { pathToFileURL, fileURLToPath } from 'node:url';
18
- import { WS, TOOL, config, paths } from './workspace.mjs';
18
+ import { WS, TOOL, config, paths, trusted } from './workspace.mjs';
19
19
  import { fromFaces } from './parts.mjs';
20
20
  import { located } from './errors.mjs';
21
21
 
@@ -27,7 +27,8 @@ const flag = (() => {
27
27
  const inThread = typeof nodeModule.registerHooks === 'function'; // import hooks in this thread; older Node needs a worker for them
28
28
 
29
29
  /** Whether designs run sandboxed here. */
30
- export const sandboxed = () => !!flag && process.env.CAD_TRUST !== '1' && config.sandbox !== false;
30
+ // (a workspace's "sandbox": false counts only once the user has trusted it: cad trust)
31
+ export const sandboxed = () => !!flag && process.env.CAD_TRUST !== '1' && !(config.sandbox === false && trusted());
31
32
 
32
33
  // What the sandbox may read: the workspace, and the packages designs and the runner load (wherever npm put them)
33
34
  function readable() {
package/lib/targets.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { pathToFileURL } from 'node:url';
10
- import { WS, config } from './workspace.mjs';
10
+ import { WS, config, needTrust } from './workspace.mjs';
11
11
 
12
12
  export const hasTarget = (kind) => !!config.targets?.[kind];
13
13
 
@@ -15,6 +15,7 @@ export async function target(kind) {
15
15
  const name = config.targets?.[kind];
16
16
  if (!name) throw new Error(`no "${kind}" target: name one in cad.config.json ("targets": { "${kind}": … })`);
17
17
  const own = new URL(`./targets/${name}.mjs`, import.meta.url);
18
+ if (!fs.existsSync(own)) needTrust(); // (the workspace's own code, run in the tool's process: only once it is trusted)
18
19
  const mod = await import(fs.existsSync(own) ? own : pathToFileURL(path.resolve(WS, name)).href);
19
20
  if (typeof mod[kind] !== 'function') throw new Error(`target ${name} has no ${kind}()`);
20
21
  return mod[kind];
package/lib/versions.mjs CHANGED
@@ -36,10 +36,13 @@ export function tags(project, name) {
36
36
  const layoutNames = (d, object) => Object.values(object.variables || {}).filter((v) => v.type === 'layout')
37
37
  .flatMap((v) => v.choice || [v.value]).filter((n) => hasLayout(d.project, n, d.layoutsDir));
38
38
 
39
+ // A file's path in git's terms: relative to the workspace, forward slashes on every system (git show tag:path needs them)
40
+ const rel = (f) => path.relative(WS, f).split(path.sep).join('/');
41
+
39
42
  // The files a design depends on, relative to the workspace (its git repo): its .js and .json, the rule sets and the layouts it uses.
40
43
  // (A board's engine is the tool's code, not the workspace's: its release records engineId() instead.)
41
44
  export function files(d, object) {
42
- return [path.relative(WS, d.js), path.relative(WS, d.json), ...(object.uses || []).filter((u) => !u.includes('/')).map((u) => `rules/${u}.json`),
45
+ return [rel(d.js), rel(d.json), ...(object.uses || []).filter((u) => !u.includes('/')).map((u) => `rules/${u}.json`),
43
46
  ...layoutNames(d, object).map((n) => `projects/${d.project}/layouts/${n}.json`)];
44
47
  }
45
48
 
@@ -49,10 +52,10 @@ export function materialise(d, version) {
49
52
  try { git('rev-parse', '--verify', `refs/tags/${tag}`); } catch { throw new Error(`no release ${tag} (releases: ${tags(d.project, d.name).map((t) => t.version).join(', ') || 'none'})`); }
50
53
  const base = paths.versions(d.project, `${d.name}@${version}`);
51
54
  const show = (rel) => git('show', `${tag}:${rel}`);
52
- const object = JSON.parse(show(path.relative(WS, d.json)));
55
+ const object = JSON.parse(show(rel(d.json)));
53
56
  fs.mkdirSync(path.join(base, 'rules'), { recursive: true });
54
57
  const js = path.join(base, `${d.name}.js`), json = path.join(base, `${d.name}.json`);
55
- fs.writeFileSync(js, show(path.relative(WS, d.js)));
58
+ fs.writeFileSync(js, show(rel(d.js)));
56
59
  fs.writeFileSync(json, JSON.stringify(object, null, 2));
57
60
  for (const u of (object.uses || []).filter((x) => !x.includes('/'))) fs.writeFileSync(path.join(base, 'rules', `${u}.json`), show(`rules/${u}.json`)); // objects it reads are released on their own
58
61
  // The layouts it could pick, as they were then (only files that existed in that release)
package/lib/workspace.mjs CHANGED
@@ -6,6 +6,7 @@
6
6
  // printer the rule set a print is checked against (bed, overhang, bridges); a project.json's "printer" wins
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
+ import fs from 'node:fs';
9
10
  import path from 'node:path';
10
11
  import { host, readJson } from './host.mjs';
11
12
  import { fileURLToPath } from 'node:url';
@@ -48,3 +49,25 @@ export const printerOf = (project) => {
48
49
  const f = project && path.join(paths.project(project), 'project.json');
49
50
  return (f && host.exists(f) && readJson(f).printer) || config.printer;
50
51
  };
52
+
53
+ // Trust: a workspace that turns the design sandbox off ("sandbox": false), or runs code of its own as a target (a
54
+ // module path rather than one of rulecad's), runs that code in the tool's process. A workspace cloned from elsewhere
55
+ // could do that on its first command, so it is asked once: cad trust records this folder, with what it asked for, in
56
+ // the user's own list (~/.config/rulecad/trusted.json, or $CAD_TRUSTED); asking for more later is asked again.
57
+ import os from 'node:os';
58
+ const TRUSTED = () => process.env.CAD_TRUSTED || path.join(os.homedir(), '.config', 'rulecad', 'trusted.json');
59
+ /** What this workspace asks to run outside the sandbox: [] when nothing. */
60
+ export function asks(cfg = config) {
61
+ const own = Object.entries(cfg.targets || {}).filter(([, v]) => typeof v === 'string' && (v.includes('/') || v.endsWith('.mjs') || v.endsWith('.js'))).map(([k, v]) => `the ${k} target ${v}`);
62
+ return [...(cfg.sandbox === false ? ['designs run outside the sandbox'] : []), ...own].sort();
63
+ }
64
+ const trustList = () => { try { return JSON.parse(fs.readFileSync(TRUSTED(), 'utf8')); } catch { return {}; } };
65
+ /** Whether the user has trusted this workspace for all it asks. */
66
+ export const trusted = (cfg = config) => { const a = asks(cfg); if (!a.length || process.env.CAD_TRUST === '1') return true; const t = trustList()[WS]; return !!t && a.every((x) => t.includes(x)); };
67
+ /** Trust this workspace for what it asks now. */
68
+ export function trust(cfg = config) { const list = trustList(); list[WS] = asks(cfg); fs.mkdirSync(path.dirname(TRUSTED()), { recursive: true }); fs.writeFileSync(TRUSTED(), JSON.stringify(list, null, 2) + '\n'); return list[WS]; }
69
+ /** Throws, saying what it asks and how to allow it, when this workspace isn't trusted for what it asks. */
70
+ export function needTrust(cfg = config) {
71
+ if (trusted(cfg)) return;
72
+ throw Object.assign(new Error(`this workspace asks for ${asks(cfg).join(' and ')} (cad.config.json). If you trust it, run cad trust once; until then, it isn't done`), { code: 'workspace.untrusted' });
73
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.26",
3
+ "version": "0.7.31",
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": {
@@ -52,8 +52,12 @@
52
52
  "url": "git+https://github.com/JoniBach/rulecad.git",
53
53
  "directory": "packages/cad"
54
54
  },
55
+ "homepage": "https://github.com/JoniBach/rulecad/tree/main/packages/cad#readme",
56
+ "bugs": {
57
+ "url": "https://github.com/JoniBach/rulecad/issues"
58
+ },
55
59
  "dependencies": {
56
- "@rulecad/variables": "^0.2.2",
60
+ "@rulecad/variables": "^0.3.0",
57
61
  "@rulecad/keyboard-layout": "^0.1.2",
58
62
  "@rulecad/printcheck": "^0.2.0",
59
63
  "@rulecad/fit": "^0.3.0",
@@ -64,8 +68,8 @@
64
68
  "@jscad/modeling": "^2.12.0",
65
69
  "three": "^0.186.1",
66
70
  "@rulecad/fea": "^0.2.1",
67
- "@rulecad/topopt": "^0.2.2",
68
- "@rulecad/flexures": "^0.3.0"
71
+ "@rulecad/topopt": "^0.3.0",
72
+ "@rulecad/flexures": "^0.4.0"
69
73
  },
70
74
  "peerDependencies": {
71
75
  "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0 || ^0.4.0 || ^0.5.0"
@@ -48,7 +48,7 @@
48
48
  "required": ["value"],
49
49
  "additionalProperties": false,
50
50
  "properties": {
51
- "value": { "description": "A number, an expression (x1c.line * 3), or for typed variables a name or text" },
51
+ "value": { "description": "A number, an expression (x1c.line * 3), or for typed variables a name or text", "type": ["number", "string", "boolean", "array", "object"] },
52
52
  "unit": { "type": "string" },
53
53
  "rule": { "type": "string", "description": "Why the value is what it is" },
54
54
  "label": { "type": "string" },