@rulecad/cad 0.4.1 → 0.5.1

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/lib/host.mjs ADDED
@@ -0,0 +1,58 @@
1
+ // The host: how the core reads and writes, so it runs on more than Node's file system. The core (resolve, build,
2
+ // check) does its file work through `host`; the CLI uses Node's (the default). A test, or later a browser, swaps in
3
+ // another with useHost: memoryHost(files) keeps a workspace in memory, reading anything outside it (the tool's
4
+ // packages, the published rule sets) from disk.
5
+ // host.exists(file) host.readText(file) host.writeText(file, text) host.list(dir) host.mtime(file)
6
+ // host.remove(file) host.touch(file) host.loadModule(file): a design's module (its main)
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { createRequire } from 'node:module';
10
+ import { pathToFileURL } from 'node:url';
11
+
12
+ /** Node's file system. */
13
+ export const nodeHost = {
14
+ name: 'node',
15
+ exists: (f) => fs.existsSync(f),
16
+ readText: (f) => fs.readFileSync(f, 'utf8'),
17
+ writeText: (f, text) => { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, text); },
18
+ list: (d) => (fs.existsSync(d) ? fs.readdirSync(d) : []),
19
+ mtime: (f) => fs.statSync(f).mtimeMs,
20
+ remove: (f) => fs.rmSync(f, { force: true }),
21
+ touch: (f) => { const now = new Date(); fs.utimesSync(f, now, now); },
22
+ loadModule: (f) => import(`${pathToFileURL(f).href}?t=${fs.statSync(f).mtimeMs}`), // a fresh copy after each edit
23
+ };
24
+
25
+ let current = nodeHost;
26
+ /** The host the core uses now. */
27
+ export const host = new Proxy({}, { get: (_, k) => current[k] });
28
+ /** Use another host (until the returned function is called). @param {Partial<typeof nodeHost>} h @returns {() => void} */
29
+ export function useHost(h) { const before = current; current = { ...nodeHost, ...h }; return () => { current = before; }; }
30
+
31
+ /**
32
+ * A workspace in memory: { [path]: text } under root. Reads outside root come from disk (the tool, its rule sets);
33
+ * writes stay in memory. A design module is loaded from its text, its imports of @jscad/modeling and @rulecad/shapes
34
+ * pointed at the installed packages.
35
+ * @param {Record<string, string>} files paths relative to root @param {{ root?: string }} [options]
36
+ */
37
+ export function memoryHost(files = {}, { root = path.resolve('/rulecad-memory') } = {}) {
38
+ const mem = new Map(Object.entries(files).map(([k, v]) => [path.resolve(root, k), v])), times = new Map();
39
+ const inside = (f) => path.resolve(f).startsWith(root);
40
+ const tick = () => Date.now() + times.size;
41
+ const req = createRequire(import.meta.url);
42
+ const bare = (spec) => pathToFileURL(req.resolve(spec)).href;
43
+ return {
44
+ name: 'memory', root, files: mem,
45
+ exists: (f) => (inside(f) ? mem.has(path.resolve(f)) || [...mem.keys()].some((k) => k.startsWith(path.resolve(f) + path.sep)) : fs.existsSync(f)),
46
+ readText: (f) => { if (!inside(f)) return fs.readFileSync(f, 'utf8'); const t = mem.get(path.resolve(f)); if (t == null) throw Object.assign(new Error(`ENOENT: no such file, '${f}'`), { code: 'ENOENT' }); return t; },
47
+ writeText: (f, text) => { mem.set(path.resolve(f), text); times.set(path.resolve(f), tick()); },
48
+ list: (d) => { if (!inside(d)) return fs.existsSync(d) ? fs.readdirSync(d) : []; const p = path.resolve(d) + path.sep; return [...new Set([...mem.keys()].filter((k) => k.startsWith(p)).map((k) => k.slice(p.length).split(path.sep)[0]))]; },
49
+ mtime: (f) => (inside(f) ? times.get(path.resolve(f)) || 0 : fs.statSync(f).mtimeMs),
50
+ remove: (f) => { mem.delete(path.resolve(f)); },
51
+ touch: (f) => { times.set(path.resolve(f), tick()); },
52
+ loadModule: (f) => {
53
+ const src = (inside(f) ? mem.get(path.resolve(f)) : fs.readFileSync(f, 'utf8'))
54
+ .replace(/from\s+'(@jscad\/modeling|@rulecad\/shapes)'/g, (_, s) => `from '${bare(s)}'`);
55
+ return import(`data:text/javascript;base64,${Buffer.from(src).toString('base64')}`);
56
+ },
57
+ };
58
+ }
@@ -0,0 +1,84 @@
1
+ // Edits to JSON text that keep everything else as it was: key order, indentation, line breaks and characters (a ×
2
+ // stays a ×). A small scanner finds where each value is in the text; an edit replaces that span, or adds a key to an
3
+ // object (or an entry to an array) in the indentation already there. Used by cad set and cad add.
4
+
5
+ // Where every value is: [{ path: ['variables', 'w', 'value'], start, end }], in the order they appear
6
+ function spans(text) {
7
+ const out = [];
8
+ let i = 0;
9
+ const ws = () => { while (i < text.length && /\s/.test(text[i])) i++; };
10
+ const str = () => { const s = i++; while (text[i] !== '"') i += text[i] === '\\' ? 2 : 1; i++; return JSON.parse(text.slice(s, i)); };
11
+ const value = (path) => {
12
+ ws();
13
+ const start = i, c = text[i];
14
+ if (c === '{') {
15
+ i++; ws();
16
+ if (text[i] === '}') i++;
17
+ else for (;;) { ws(); const k = str(); ws(); i++; value([...path, k]); ws(); if (text[i++] === '}') break; }
18
+ } else if (c === '[') {
19
+ i++; ws();
20
+ if (text[i] === ']') i++;
21
+ else for (let n = 0; ; n++) { value([...path, n]); ws(); if (text[i++] === ']') break; }
22
+ } else if (c === '"') str();
23
+ else { while (i < text.length && /[^\s,\]}]/.test(text[i])) i++; }
24
+ out.push({ path, start, end: i });
25
+ };
26
+ value([]);
27
+ return out;
28
+ }
29
+ const same = (a, b) => a.length === b.length && a.every((x, k) => x === b[k]);
30
+ const find = (text, path) => spans(text).find((s) => same(s.path, path));
31
+ // The indentation of the line a position is on
32
+ const indentAt = (text, at) => { const line = text.lastIndexOf('\n', at - 1) + 1; return /^[ \t]*/.exec(text.slice(line))[0]; };
33
+ // A value as JSON, laid out like the file (two spaces a level, from the given indentation); short arrays of numbers
34
+ // and expressions stay on one line, as people write them
35
+ function render(v, indent) {
36
+ if (Array.isArray(v) && v.every((x) => typeof x !== 'object' || x === null) && JSON.stringify(v).length <= 80) return `[${v.map((x) => JSON.stringify(x)).join(', ')}]`;
37
+ const inner = `${indent} `;
38
+ if (Array.isArray(v)) return v.length ? `[\n${v.map((x) => `${inner}${render(x, inner)}`).join(',\n')}\n${indent}]` : '[]';
39
+ if (v && typeof v === 'object') { const e = Object.entries(v); return e.length ? `{\n${e.map(([k, x]) => `${inner}${JSON.stringify(k)}: ${render(x, inner)}`).join(',\n')}\n${indent}}` : '{}'; }
40
+ return JSON.stringify(v);
41
+ }
42
+
43
+ /** The value at a path, or undefined. @param {string} text @param {(string | number)[]} path */
44
+ export function getAt(text, path) {
45
+ const s = find(text, path);
46
+ return s ? JSON.parse(text.slice(s.start, s.end)) : undefined;
47
+ }
48
+
49
+ /**
50
+ * Set the value at a path: replace it where it is, or add the key at the end of its object.
51
+ * @param {string} text @param {(string | number)[]} path @param {any} value @returns {string}
52
+ */
53
+ export function setAt(text, path, value) {
54
+ const s = find(text, path);
55
+ if (s) return text.slice(0, s.start) + render(value, indentAt(text, s.start)) + text.slice(s.end);
56
+ const parent = find(text, path.slice(0, -1));
57
+ if (!parent) throw Object.assign(new Error(`no ${path.slice(0, -1).join('.') || 'top level'} to add ${path.at(-1)} to`), { code: 'edit.path' });
58
+ const body = text.slice(parent.start, parent.end);
59
+ if (body[0] !== '{') throw Object.assign(new Error(`${path.slice(0, -1).join('.')} isn't an object`), { code: 'edit.path' });
60
+ return insert(text, parent, `${JSON.stringify(path.at(-1))}: `, value);
61
+ }
62
+
63
+ /** Add an entry at the end of the array at a path. @param {string} text @param {(string | number)[]} path @param {any} value @returns {string} */
64
+ export function appendAt(text, path, value) {
65
+ const s = find(text, path);
66
+ if (!s) throw Object.assign(new Error(`no ${path.join('.')} to add to`), { code: 'edit.path' });
67
+ if (text[s.start] !== '[') throw Object.assign(new Error(`${path.join('.')} isn't a list`), { code: 'edit.path' });
68
+ return insert(text, s, '', value);
69
+ }
70
+
71
+ // Add a member before an object's } or an array's ], after its last one, indented like it
72
+ function insert(text, s, key, value) {
73
+ const close = s.end - 1, inner = text.slice(s.start + 1, close);
74
+ const outer = indentAt(text, close), empty = !inner.trim();
75
+ // Its own members (not theirs): the last one is where the new one goes after; the first says how they're indented
76
+ const members = spans(text).filter((x) => x.path.length === s.path.length + 1 && same(x.path.slice(0, -1), s.path)).sort((a, b) => a.start - b.start);
77
+ const last = members.at(-1), multi = empty || inner.includes('\n');
78
+ const first = members.length ? text.lastIndexOf('\n', members[0].start) : -1;
79
+ const indent = empty ? `${outer} ` : multi ? /^[ \t]*/.exec(text.slice(first + 1))[0] : outer;
80
+ const piece = `${key}${render(value, indent)}`;
81
+ if (empty) return `${text.slice(0, s.start + 1)}\n${indent}${piece}\n${outer}${text.slice(close)}`;
82
+ const after = last.end;
83
+ return multi ? `${text.slice(0, after)},\n${indent}${piece}${text.slice(after)}` : `${text.slice(0, after)}, ${piece}${text.slice(after)}`;
84
+ }
package/lib/layout.mjs CHANGED
@@ -1,14 +1,14 @@
1
1
  // Layout files: projects/<project>/layouts/<name>.json, in the format @rulecad/keyboard-layout describes and reads.
2
- import fs from 'node:fs';
3
2
  import path from 'node:path';
3
+ import { host } from './host.mjs';
4
4
  import { WS, paths } from './workspace.mjs';
5
5
 
6
6
  export const layoutPath = (project, name, dir) => path.join(dir || path.join(paths.project(project), 'layouts'), `${name}.json`);
7
- export const hasLayout = (project, name, dir) => fs.existsSync(layoutPath(project, name, dir));
7
+ export const hasLayout = (project, name, dir) => host.exists(layoutPath(project, name, dir));
8
8
  export function readLayout(project, name, dir) {
9
9
  const f = layoutPath(project, name, dir);
10
- if (!fs.existsSync(f)) throw new Error(`no layout "${name}" (${path.relative(WS, f)})`);
11
- return JSON.parse(fs.readFileSync(f, 'utf8'));
10
+ if (!host.exists(f)) throw new Error(`no layout "${name}" (${path.relative(WS, f)})`);
11
+ return JSON.parse(host.readText(f));
12
12
  }
13
13
 
14
14
  export { keys, width, depth, project } from '@rulecad/keyboard-layout';
package/lib/links.mjs ADDED
@@ -0,0 +1,75 @@
1
+ // Model links: a design or an assembly as the model page's data (@rulecad/model-link): its parts (each on its filament
2
+ // slot), the rules card and sheet, a board's 2D views, an assembly's joints. Used by cad link and cad show.
3
+ import path from 'node:path';
4
+ import { fromParts, fromShapes, encode, check as checkLink, expand } from '@rulecad/model-link';
5
+ import { fmt } from './rules.mjs';
6
+ import { paths, config } from './workspace.mjs';
7
+ import { host } from './host.mjs';
8
+ import { pcbEngine } from './design.mjs';
9
+ import { shapes, motionData } from './assembly.mjs';
10
+ import { slotOf } from './threemf.mjs';
11
+
12
+ /** The project's filaments: { base: { slot: 1, … }, legend: { slot: 2, … } } in project.json. @param {string} project */
13
+ export const filaments = (project) => JSON.parse(host.readText(path.join(paths.project(project), 'project.json'))).filaments || {};
14
+ /** The filaments in AMS slot order, for the print file: [{ colour }, …], slot 1 first. */
15
+ export const slots = (fil) => { const out = []; for (const f of Object.values(fil)) out[(f.slot || 1) - 1] = f; return Array.from(out, (f) => f || {}); };
16
+
17
+ export const VIEW = process.env.CAD_VIEW_URL || config.viewUrl;
18
+ /** A link to the model page; one the page would turn away is an error here, not when someone opens it. */
19
+ export async function linkTo(model) {
20
+ const errors = checkLink(model.shapes ? expand(model) : model);
21
+ if (errors.length) throw new Error(`no link: ${errors[0]}`);
22
+ return `${VIEW}#m=${await encode(model)}`;
23
+ }
24
+
25
+ // The rules sheet: each object's variables, then the rules they use (once each)
26
+ export function sheet(objects, { noRules = false } = {}) {
27
+ if (noRules) return {};
28
+ const rows = [], seen = new Set(), trim = (r) => { while (r.length && (r[r.length - 1] === '' || r[r.length - 1] == null)) r.pop(); return r; };
29
+ for (const [obj, entries] of objects) for (const e of entries) {
30
+ if (!e.name.includes('.')) rows.push(trim([obj, e.label || e.name, fmt(e.value), e.unit || '', e.rule || '', e.expr || '']));
31
+ }
32
+ for (const [, entries] of objects) for (const e of entries) {
33
+ if (!e.name.includes('.') || !e.used || e.private || seen.has(e.name)) continue;
34
+ seen.add(e.name);
35
+ const [set, name] = e.name.split('.');
36
+ rows.push(trim([set, name, fmt(e.value), e.unit || '', e.rule || '', e.expr || '', e.kind || '', e.source || '', e.checked || '']));
37
+ }
38
+ return rows.length ? { sheet: rows } : {};
39
+ }
40
+
41
+ const triangles = (polys) => polys.flatMap((t) => t.slice(1, -1).map((_, i) => [t[0], t[i + 1], t[i + 2]]));
42
+
43
+ /** A built design as a model: full print precision (triangles), the rules card and sheet, exactly which version it is. */
44
+ export async function objectModel(b, { title, version, src, set, filaments: fil = {}, noRules = false }) {
45
+ return {
46
+ title, version, src, ...(set ? { set } : {}),
47
+ material: b.object.material, orientation: b.object.orientation,
48
+ rules: b.entries.filter((e) => e.show).map((e) => [e.label || e.name, fmt(e.value), e.unit || '']),
49
+ ...sheet([[b.object.name, b.entries]], { noRules }),
50
+ ...(b.circuit ? { views: await (await pcbEngine()).views(b.circuit) } : {}), // boards: the 2D board and schematic
51
+ ...fromParts(b.parts.map((p) => ({ name: p.name, role: p.role, label: p.label, slot: slotOf(fil, p.filament), triangles: triangles(p.triangles) }))),
52
+ };
53
+ }
54
+
55
+ /** A built assembly as a model: each shape once and placed (nine keys cost one keycap), its boards' views, its joints. */
56
+ export async function assemblyModel(s, { title, versions, filaments: fil = {}, noRules = false }) {
57
+ const model = {
58
+ title, version: versions, src: `${s.project}/${s.name}`, // object versions are in version: the file name stays short
59
+ rules: [],
60
+ ...sheet([...new Map(s.objects.filter((o) => o.built?.entries).map((o) => [o.objName, o.built.entries])).entries()], { noRules }),
61
+ // Its boards' 2D views (copper, schematic), so one link holds the whole build: tabs over the 3D model
62
+ ...(await (async () => {
63
+ const boards = [...new Map(s.objects.filter((o) => o.built?.circuit).map((o) => [o.objName, o])).values()];
64
+ if (!boards.length) return {};
65
+ const pcb = await pcbEngine(), views = [];
66
+ for (const o of boards) for (const [n, svg] of await pcb.views(o.built.circuit)) views.push([boards.length > 1 ? `${o.objName} ${n}` : n, svg]);
67
+ return { views };
68
+ })()),
69
+ ...fromShapes(shapes(s.parts).shapes.length ? (() => {
70
+ const placed = shapes(s.parts);
71
+ return placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: p.object || p.label, slot: slotOf(fil, p.filament), triangles: triangles(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; });
72
+ })() : []),
73
+ };
74
+ return Object.assign(model, motionData(s));
75
+ }
package/lib/parts.mjs ADDED
@@ -0,0 +1,42 @@
1
+ // A design's result as parts, and its shapes as faces: no file or process access, so the sandboxed runner
2
+ // (sandbox-run.mjs) uses them as the build does.
3
+ import jscad from '@jscad/modeling';
4
+
5
+ // A design's result as parts: named ({ cap, pillar }) or one unnamed shape ("body").
6
+ export function named(result, meta) {
7
+ const isShape = (r) => Array.isArray(r) || jscad.geometries.geom3.isA(r) || jscad.geometries.geom2.isA(r);
8
+ const entries = isShape(result) ? [['body', result]] : Object.entries(result || {});
9
+ const empty = (g) => g == null || (Array.isArray(g) && !g.length);
10
+ for (const k of Object.keys(meta)) if (!meta[k].optional && !entries.some(([n, g]) => n === k && !empty(g))) throw new Error(`parts in the .json lists "${k}", but main() returns no such part`);
11
+ return entries.filter(([name, g]) => !(empty(g) && meta[name]?.optional)).map(([name, g]) => {
12
+ const m = meta[name] || {};
13
+ if (m.role && !['part', 'support'].includes(m.role)) throw new Error(`part ${name}: role is part or support`);
14
+ // The solid for booleans (fit checks) is JSCAD's own, exactly; a cached build restores the very same faces
15
+ const geometry = solid(g);
16
+ return { name, role: m.role || 'part', label: m.label || name, ...(m.filament ? { filament: m.filament } : {}), ...(m.mirror === false ? { mirror: false } : {}),
17
+ geometry, polygons: polygons(g), triangles: polygons(g, { triangulate: true }) };
18
+ });
19
+ }
20
+
21
+ // A part's result as one JSCAD solid with its transforms applied (several solids become one set of faces), and back from
22
+ // the exact faces a cache keeps: the same numbers, so booleans on a cached build agree with a fresh one.
23
+ const { geom3, poly3 } = jscad.geometries;
24
+ export const solid = (g) => geom3.create([g].flat(Infinity).filter((x) => geom3.isA(x)).flatMap((x) => geom3.toPolygons(x)));
25
+ export const faces = (g) => geom3.toPolygons(g).map((p) => p.vertices.map((v) => [v[0], v[1], v[2]]));
26
+ export const fromFaces = (list) => geom3.create(list.map((vs) => poly3.create(vs)));
27
+
28
+
29
+ // Any JSCAD result -> polygons (corner lists), transforms applied. triangulate: also split faces at T-junctions (a
30
+ // corner of one face in the middle of a neighbour's edge, left by booleans) so every edge pairs up, as slicers want.
31
+ export function polygons(result, { triangulate = false } = {}) {
32
+ const { geom3, geom2 } = jscad.geometries;
33
+ const out = [];
34
+ for (const g of [result].flat(Infinity)) {
35
+ if (geom2.isA(g)) throw new Error("2D shapes can't be printed or shown: extrude them first");
36
+ if (!geom3.isA(g)) continue;
37
+ const fixed = jscad.modifiers.generalize({ snap: true, triangulate }, g);
38
+ for (const p of geom3.toPolygons(fixed)) out.push(p.vertices.map((v) => [v[0], v[1], v[2]]));
39
+ }
40
+ if (!out.length) throw new Error('the design has no 3D shapes');
41
+ return out;
42
+ }
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
- import fs from 'node:fs';
4
3
  import path from 'node:path';
4
+ import { host } from './host.mjs';
5
5
  import { RULE_DIRS, WS } from './workspace.mjs';
6
6
  import { resolve as resolveWith } from '@rulecad/variables';
7
7
 
@@ -11,15 +11,14 @@ export { ANCHORS, isName, options, checkName, evaluate, fmt } from '@rulecad/var
11
11
  // is copied into the workspace the first time it's used: the workspace keeps every rule its designs depend on (so a
12
12
  // release can record them in git), and your own measurements are edits to your copy.
13
13
  export function loadRuleSet(name, dir) {
14
- const file = (dir ? [dir] : RULE_DIRS).map((d) => path.join(d, `${name}.json`)).find((f) => fs.existsSync(f));
14
+ const file = (dir ? [dir] : RULE_DIRS).map((d) => path.join(d, `${name}.json`)).find((f) => host.exists(f));
15
15
  if (!file) throw new Error(`no rule set "${name}" (rules/${name}.json)`);
16
16
  const own = path.join(WS, 'rules', `${name}.json`);
17
17
  if (!dir && file !== own) {
18
- fs.mkdirSync(path.dirname(own), { recursive: true });
19
- fs.copyFileSync(file, own);
18
+ host.writeText(own, host.readText(file));
20
19
  console.error(`copied the ${name} rule set into rules/${name}.json: yours to keep and edit`);
21
20
  }
22
- return JSON.parse(fs.readFileSync(own, 'utf8'));
21
+ return JSON.parse(host.readText(own));
23
22
  }
24
23
  // resolve() as @rulecad/variables describes it, loading the rule sets it isn't handed
25
24
  export const resolve = (object, opts = {}) => resolveWith(object, { load: loadRuleSet, ...opts });
@@ -0,0 +1,32 @@
1
+ // The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes and files of
2
+ // its own project, nothing else (no node: modules: no files, network or processes). The tool's own modules are free.
3
+ import { builtinModules } from 'node:module';
4
+
5
+ let project = '';
6
+ export async function initialize(data) { project = data?.project || ''; }
7
+
8
+ const ALLOWED = ['@jscad/modeling', '@rulecad/shapes'];
9
+ const deny = (spec, why) => Object.assign(new Error(`designs can't import "${spec}": ${why}`), { code: 'design.sandbox' });
10
+
11
+ // The same check, for in-thread hooks (synchronous) and worker hooks (async)
12
+ export function resolveHook(spec, context, next) {
13
+ const fromDesign = check(spec, context), r = next(spec, context);
14
+ return fromDesign ? after(spec, r) : r;
15
+ }
16
+ export async function resolve(spec, context, next) {
17
+ const fromDesign = check(spec, context), r = await next(spec, context);
18
+ return fromDesign ? after(spec, r) : r;
19
+ }
20
+ const after = (spec, r) => {
21
+ if (r.url.startsWith('file:') && !r.url.startsWith(project) && !r.url.includes('/node_modules/')) throw deny(spec, 'it is outside the project');
22
+ return r;
23
+ };
24
+ function check(spec, context) {
25
+ const fromDesign = project && context.parentURL?.startsWith(project) && !context.parentURL.includes('/node_modules/');
26
+ if (fromDesign) {
27
+ if (spec.startsWith('node:') || builtinModules.includes(spec)) throw deny(spec, 'a design only makes shapes (no files, network or programs)');
28
+ const relative = spec.startsWith('./') || spec.startsWith('../');
29
+ if (!relative && !ALLOWED.some((a) => spec === a || spec.startsWith(`${a}/`))) throw deny(spec, `only ${ALLOWED.join(', ')} and files in its project`);
30
+ }
31
+ return fromDesign;
32
+ }
@@ -0,0 +1,10 @@
1
+ // Loaded first in the sandbox (node --import): the import hook that keeps designs to their own imports. In-thread
2
+ // (module.registerHooks) where Node has it; older Node runs hooks in a worker, which the sandbox then allows.
3
+ import * as mod from 'node:module';
4
+ import { resolveHook, initialize } from './sandbox-hooks.mjs';
5
+
6
+ const project = process.env.CAD_SANDBOX_PROJECT;
7
+ if (mod.registerHooks) {
8
+ initialize({ project });
9
+ mod.registerHooks({ resolve: resolveHook });
10
+ } else mod.register('./sandbox-hooks.mjs', import.meta.url, { data: { project } });
@@ -0,0 +1,23 @@
1
+ // The sandbox's runner: reads { js, values, meta } on stdin, runs the design's main(values), and writes its parts'
2
+ // faces (and the rules it read) as JSON on stdout. Started by sandbox.mjs, under Node's permission model.
3
+ import * as shapes from '@rulecad/shapes';
4
+ import { named, faces } from './parts.mjs';
5
+
6
+ for (const k of ['fetch', 'WebSocket', 'EventSource', 'XMLHttpRequest', 'Request', 'Response']) delete globalThis[k];
7
+ const chunks = [];
8
+ for await (const c of process.stdin) chunks.push(c);
9
+ const { js, values, meta, engine } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
10
+ const done = (o) => process.stdout.write(JSON.stringify(o), () => process.exit(0));
11
+ try {
12
+ const mod = await import(js);
13
+ if (typeof mod.main !== 'function') throw Object.assign(new Error('the design has no exported main(v)'), { code: 'design.main' });
14
+ // Rules the code reads directly (v.mx.housing_top) count as used too
15
+ const read = new Set(), watched = Object.fromEntries(Object.entries(values).map(([k, v]) => [k, v && typeof v === 'object'
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);
19
+ const parts = named(made, meta).map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) }));
20
+ done({ parts, read: [...read] });
21
+ } catch (e) {
22
+ done({ error: { message: e?.message || String(e), code: e?.code && typeof e.code === 'string' && !/^ERR_/.test(e.code) ? e.code : e?.code === 'ERR_ACCESS_DENIED' ? 'design.sandbox' : 'design.run' } });
23
+ }
@@ -0,0 +1,65 @@
1
+ // Designs are code. A JSCAD design runs in a sandbox: another Node process with the permission model on, so it can
2
+ // read the workspace and the tool's packages but can't write files, start programs or workers, or load addons; an
3
+ // import hook (sandbox-hooks.mjs) lets a design import only @jscad/modeling, @rulecad/shapes and files in its own
4
+ // project (no node: modules, so no network), and the runner removes fetch and its kin. It gets its values as data
5
+ // and sends back its parts' faces. A workspace that trusts its designs sets "sandbox": false in cad.config.json (or
6
+ // CAD_TRUST=1); Node without the permission model (18) runs designs as before. Board designs (engine pcb) run in the
7
+ // tool's own process, with the board engine.
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { spawn } from 'node:child_process';
11
+ import * as nodeModule from 'node:module';
12
+ import { pathToFileURL, fileURLToPath } from 'node:url';
13
+ import { WS, TOOL, config } from './workspace.mjs';
14
+ import { fromFaces } from './parts.mjs';
15
+ import { located } from './errors.mjs';
16
+
17
+ const flag = (() => {
18
+ const f = process.allowedNodeEnvironmentFlags;
19
+ return f.has('--permission') ? '--permission' : f.has('--experimental-permission') ? '--experimental-permission' : null;
20
+ })();
21
+
22
+ const inThread = typeof nodeModule.registerHooks === 'function'; // import hooks in this thread; older Node needs a worker for them
23
+
24
+ /** Whether designs run sandboxed here. */
25
+ export const sandboxed = () => !!flag && process.env.CAD_TRUST !== '1' && config.sandbox !== false;
26
+
27
+ // What the sandbox may read: the workspace, and the packages designs and the runner load (wherever npm put them)
28
+ function readable() {
29
+ const real = (p) => { try { return fs.realpathSync(p); } catch { return null; } };
30
+ const pkgDir = (name, from) => { // the package's folder: from its entry up to its package.json (exports may hide that file)
31
+ try { let d = path.dirname(nodeModule.createRequire(from).resolve(name)); while (!fs.existsSync(path.join(d, 'package.json')) && path.dirname(d) !== d) d = path.dirname(d); return d; } catch { return null; }
32
+ };
33
+ const fromWs = path.join(WS, 'package.json'), fromTool = path.join(TOOL, 'package.json');
34
+ // Every node_modules above the workspace and the tool (package lookups read their links), and where links lead
35
+ 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
+ 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)])];
38
+ return [...new Set(dirs.filter(Boolean).flatMap((d) => [d, real(d)]).filter(Boolean))];
39
+ }
40
+
41
+ /**
42
+ * Run a design's main(values) in the sandbox: { parts, read } as the build makes them.
43
+ * @param {{ js: string }} d the design @param {object} values @param {object} meta the .json's parts @param {'jscad' | 'manifold'} [engine] v.ops's booleans
44
+ */
45
+ export function runSandboxed(d, values, meta, engine = 'jscad') {
46
+ const here = path.dirname(fileURLToPath(import.meta.url));
47
+ 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
+ const project = pathToFileURL(path.dirname(path.dirname(d.js)) + path.sep).href;
49
+ return new Promise((resolve, reject) => {
50
+ const child = spawn(process.execPath, args, { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, CAD_SANDBOX_PROJECT: project } });
51
+ const out = [], err = [];
52
+ child.stdout.on('data', (b) => out.push(b));
53
+ child.stderr.on('data', (b) => err.push(b));
54
+ child.on('error', reject);
55
+ child.on('close', () => {
56
+ let r;
57
+ try { r = JSON.parse(Buffer.concat(out).toString('utf8')); } catch {
58
+ 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
+ }
60
+ if (r.error) return reject(located(Object.assign(new Error(r.error.message), { code: r.error.code }), d.js, r.error.code || 'design.run'));
61
+ resolve({ parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })), read: new Set(r.read) });
62
+ });
63
+ child.stdin.end(JSON.stringify({ js: `${pathToFileURL(d.js).href}?t=${fs.statSync(d.js).mtimeMs}`, values, meta, engine }));
64
+ });
65
+ }
package/lib/schema.mjs ADDED
@@ -0,0 +1,69 @@
1
+ // The file formats' JSON Schemas (schemas/*.schema.json) and a small validator for the parts of JSON Schema they use:
2
+ // type, enum, pattern, properties, required, additionalProperties, items, prefixItems, minItems, maxItems, anyOf and
3
+ // $ref to $defs. Problems come back with the path to fix (variables.cap_h.unti: not allowed, did you mean unit?).
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'schemas');
9
+ const cache = new Map();
10
+ /** A schema by name: object, assembly, rules or layout. @param {'object' | 'assembly' | 'rules' | 'layout'} name */
11
+ export function schema(name) {
12
+ if (!cache.has(name)) cache.set(name, JSON.parse(fs.readFileSync(path.join(DIR, `${name}.schema.json`), 'utf8')));
13
+ return cache.get(name);
14
+ }
15
+
16
+ const typeOf = (v) => (v === null ? 'null' : Array.isArray(v) ? 'array' : Number.isInteger(v) ? 'integer' : typeof v);
17
+ 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
+
26
+ /**
27
+ * Problems with a value against a schema: [{ path, message }], empty when it's valid.
28
+ * @param {any} value @param {object} s a schema @param {object} [root] the schema holding $defs @param {string} [at] the path so far
29
+ * @returns {{ path: string, message: string }[]}
30
+ */
31
+ export function validate(value, s, root = s, at = '') {
32
+ const out = [], here = at || '(top)', p = (k) => (at ? `${at}.${k}` : String(k));
33
+ if (s.$ref) return validate(value, s.$ref.replace('#/$defs/', '').split('/').reduce((o, k) => o[k], root.$defs), root, at);
34
+ if (s.anyOf) {
35
+ const each = s.anyOf.map((x) => validate(value, x, root, at));
36
+ if (each.some((e) => !e.length)) return [];
37
+ // Report the alternative that got furthest (the fewest problems), so a near miss says what's wrong with it
38
+ return each.sort((a, b) => a.length - b.length)[0];
39
+ }
40
+ if (s.type) {
41
+ const types = [].concat(s.type);
42
+ if (!types.some((t) => fits(value, t))) return [{ path: here, message: `should be ${types.join(' or ')}, not ${typeOf(value)}` }];
43
+ }
44
+ if (s.enum && !s.enum.includes(value)) out.push({ path: here, message: `should be one of ${s.enum.map((x) => JSON.stringify(x)).join(', ')} (got ${JSON.stringify(value)})` });
45
+ if (s.pattern && typeof value === 'string' && !new RegExp(s.pattern).test(value)) out.push({ path: here, message: `"${value}" isn't in the expected form (${s.pattern})` });
46
+ if (typeOf(value) === 'object') {
47
+ for (const k of s.required || []) if (!(k in value)) out.push({ path: here, message: `needs "${k}"` });
48
+ const props = s.properties || {};
49
+ for (const [k, v] of Object.entries(value)) {
50
+ if (props[k]) out.push(...validate(v, props[k], root, p(k)));
51
+ else if (s.additionalProperties === false) { const guess = near(k, Object.keys(props)); out.push({ path: p(k), message: `not allowed here${guess ? ` (did you mean "${guess}"?)` : ` (allowed: ${Object.keys(props).join(', ')})`}` }); }
52
+ else if (s.additionalProperties && typeof s.additionalProperties === 'object') out.push(...validate(v, s.additionalProperties, root, p(k)));
53
+ }
54
+ }
55
+ if (Array.isArray(value)) {
56
+ if (s.minItems != null && value.length < s.minItems) out.push({ path: here, message: `needs at least ${s.minItems} entries` });
57
+ if (s.maxItems != null && value.length > s.maxItems) out.push({ path: here, message: `takes at most ${s.maxItems} entries` });
58
+ value.forEach((v, i) => {
59
+ const item = s.prefixItems?.[i] || s.items;
60
+ if (item) out.push(...validate(v, item, root, `${at}[${i}]`));
61
+ });
62
+ }
63
+ return out;
64
+ }
65
+
66
+ /** Problems with a file's JSON as findings (code schema), for cad check. @param {any} json @param {'object' | 'assembly' | 'rules' | 'layout'} kind @param {string} file */
67
+ export function schemaFindings(json, kind, file) {
68
+ return validate(json, schema(kind)).map((x) => ({ level: 'fail', text: `${file}: ${x.path}: ${x.message}`, code: 'schema', refs: { file, path: x.path } }));
69
+ }
package/lib/workspace.mjs CHANGED
@@ -6,8 +6,8 @@
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';
10
9
  import path from 'node:path';
10
+ import { host } from './host.mjs';
11
11
  import { fileURLToPath } from 'node:url';
12
12
 
13
13
  export const TOOL = fileURLToPath(new URL('..', import.meta.url)).replace(/[\\/]$/, '');
@@ -15,7 +15,7 @@ export const TOOL = fileURLToPath(new URL('..', import.meta.url)).replace(/[\\/]
15
15
  function find() {
16
16
  if (process.env.CAD_WORKSPACE) return path.resolve(process.env.CAD_WORKSPACE);
17
17
  for (let dir = process.cwd(); ; dir = path.dirname(dir)) {
18
- if (fs.existsSync(path.join(dir, 'cad.config.json'))) return dir;
18
+ if (host.exists(path.join(dir, 'cad.config.json'))) return dir;
19
19
  if (dir === path.dirname(dir)) return process.cwd(); // none: where you are
20
20
  }
21
21
  }
@@ -23,7 +23,7 @@ function find() {
23
23
  export const WS = find();
24
24
  export const config = (() => {
25
25
  const f = path.join(WS, 'cad.config.json');
26
- return { printer: 'x1c', viewUrl: 'https://jonibach.github.io/rulecad/', targets: {}, ...(fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : {}) };
26
+ return { printer: 'x1c', viewUrl: 'https://jonibach.github.io/rulecad/', targets: {}, ...(host.exists(f) ? JSON.parse(host.readText(f)) : {}) };
27
27
  })();
28
28
 
29
29
  // Rule sets: the workspace's own first (your copies, with your measurements), then the published ones (@rulecad/rules).
@@ -41,5 +41,5 @@ export const paths = {
41
41
  // The printer a project's prints are checked against
42
42
  export const printerOf = (project) => {
43
43
  const f = project && path.join(paths.project(project), 'project.json');
44
- return (f && fs.existsSync(f) && JSON.parse(fs.readFileSync(f, 'utf8')).printer) || config.printer;
44
+ return (f && host.exists(f) && JSON.parse(host.readText(f)).printer) || config.printer;
45
45
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
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": {
@@ -20,6 +20,7 @@
20
20
  "files": [
21
21
  "bin",
22
22
  "lib",
23
+ "schemas",
23
24
  "templates",
24
25
  "README.md",
25
26
  "LICENSE",
@@ -43,13 +44,13 @@
43
44
  "directory": "packages/cad"
44
45
  },
45
46
  "dependencies": {
46
- "@rulecad/variables": "^0.1.6",
47
+ "@rulecad/variables": "^0.1.7",
47
48
  "@rulecad/keyboard-layout": "^0.1.2",
48
- "@rulecad/printcheck": "^0.1.0",
49
- "@rulecad/fit": "^0.2.0",
49
+ "@rulecad/printcheck": "^0.1.3",
50
+ "@rulecad/fit": "^0.2.1",
50
51
  "@rulecad/model-link": "^0.2.0",
51
52
  "@rulecad/versions": "^0.1.0",
52
- "@rulecad/shapes": "^0.2.0",
53
+ "@rulecad/shapes": "^0.2.1",
53
54
  "@rulecad/rules": "^0.2.0",
54
55
  "@jscad/modeling": "^2.12.0",
55
56
  "three": "^0.186.1"