@rulecad/cad 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/AGENTS.md +21 -6
  2. package/CHANGELOG.md +320 -0
  3. package/EXAMPLES.md +22 -17
  4. package/README.md +192 -40
  5. package/bin/cad.mjs +465 -80
  6. package/lib/assembly.mjs +68 -33
  7. package/lib/cache-file.mjs +105 -0
  8. package/lib/code-text.mjs +28 -0
  9. package/lib/design-imports.mjs +127 -0
  10. package/lib/design.mjs +251 -55
  11. package/lib/designshapes.mjs +142 -0
  12. package/lib/edit.mjs +24 -2
  13. package/lib/estimates.mjs +51 -0
  14. package/lib/fasten.mjs +11 -5
  15. package/lib/fe-key.mjs +29 -0
  16. package/lib/fittings.mjs +20 -15
  17. package/lib/fixings.mjs +17 -4
  18. package/lib/framebuild.mjs +1 -1
  19. package/lib/framegen.mjs +9 -1
  20. package/lib/frames.mjs +6 -2
  21. package/lib/framesize.mjs +8 -81
  22. package/lib/host.mjs +7 -3
  23. package/lib/kit.mjs +5 -5
  24. package/lib/list.mjs +29 -21
  25. package/lib/loads.mjs +35 -23
  26. package/lib/measured.mjs +738 -98
  27. package/lib/motors.mjs +9 -29
  28. package/lib/names.mjs +15 -0
  29. package/lib/optimise.mjs +34 -25
  30. package/lib/order.mjs +4 -10
  31. package/lib/parts.mjs +3 -0
  32. package/lib/rules.mjs +2 -1
  33. package/lib/sandbox-hooks.mjs +109 -15
  34. package/lib/sandbox-lock.mjs +225 -0
  35. package/lib/sandbox-preload.mjs +2 -2
  36. package/lib/sandbox-run.mjs +22 -24
  37. package/lib/sandbox.mjs +173 -30
  38. package/lib/sheet.mjs +114 -3
  39. package/lib/versions.mjs +195 -32
  40. package/lib/workspace.mjs +3 -2
  41. package/package.json +11 -11
  42. package/schemas/assembly.schema.json +1 -1
  43. package/schemas/project.schema.json +6 -0
  44. package/templates/coupons/MEASURE.md +109 -0
  45. package/templates/coupons/assemblies/fixings-test.json +20 -0
  46. package/templates/coupons/assemblies/slot-test.json +11 -0
  47. package/templates/coupons/objects/fixings-coupon.js +88 -0
  48. package/templates/coupons/objects/fixings-coupon.json +26 -0
  49. package/templates/coupons/objects/holds-coupon.js +130 -0
  50. package/templates/coupons/objects/holds-coupon.json +42 -0
  51. package/templates/coupons/objects/slot-coupon.js +89 -0
  52. package/templates/coupons/objects/slot-coupon.json +29 -0
  53. package/templates/coupons/project.json +10 -0
package/lib/assembly.mjs CHANGED
@@ -20,12 +20,14 @@
20
20
  // Its holes are read from the parts as drawn, its screws placed as reference parts, and it holds as a fit that fastens does.
21
21
  // Beams are held to each other by joins (lib/joins.mjs): { "kind": "blind", "a": "y1.a", "b": "x1.back@120" }. Each puts
22
22
  // its operations on both beams and its screws into fasten before anything is built, and is checked once it is.
23
- import { host, readJson, cached } from './host.mjs';
23
+ import { host, readJson } from './host.mjs';
24
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
24
25
  import fs from 'node:fs';
25
26
  import crypto from 'node:crypto';
26
27
  import path from 'node:path';
27
28
  import { fileURLToPath } from 'node:url';
28
29
  import { evaluate, loadRuleSet } from './rules.mjs';
30
+ import { estimatesFinding } from './estimates.mjs';
29
31
  import { paths, printerOf } from './workspace.mjs';
30
32
  import { plainName, isPlainName } from './names.mjs';
31
33
  import { locateIn, build, readObject, jscad } from './design.mjs';
@@ -87,6 +89,49 @@ export const isAssembly = (ref) => {
87
89
  return isPlainName(project) && isPlainName(name) && host.exists(assemblyPath(`${project}/${name}`));
88
90
  }; // (a path or a name that climbs is not an assembly: locate() says what it is)
89
91
 
92
+ /**
93
+ * The command line's --set on an assembly, { "hook.reach": "60" }, as the overrides buildAssembly takes,
94
+ * { hook: { reach: "60" } }: each name is an item of the assembly's own and one of that item's object's variables.
95
+ * Anything else is refused by name, never passed over: a component, a bought part, a beam or a motor takes no --set
96
+ * (set the object inside it with its own "set" in the assembly file). The values stay as typed: the build reads each by
97
+ * its variable's kind, and holds it to the variable's tweak range, as it does for an object's --set.
98
+ * @param {string} ref project/assembly @param {Record<string, string | undefined>} set @returns {Record<string, Record<string, string>>}
99
+ */
100
+ export function assemblyOverrides(ref, set) {
101
+ const names = Object.keys(set);
102
+ if (!names.length) return {};
103
+ const [project] = ref.split('/'),
104
+ a = readJson(assemblyPath(ref)),
105
+ items = (a.items || []).filter((it) => it && typeof it.id === 'string'),
106
+ out = {};
107
+ for (const [k, v] of Object.entries(set)) {
108
+ const said = `--set ${k}${v === undefined ? '' : `=${v}`}`,
109
+ dot = k.indexOf('.');
110
+ if (dot < 0)
111
+ throw new Error(
112
+ `${said}: on an assembly, name an item's variable as <item>.<variable> (items: ${items.map((it) => it.id).join(', ') || 'none'})`,
113
+ );
114
+ if (v === undefined || v === '') throw new Error(`${said}: give the value after an =, as ${k}=…`);
115
+ const id = k.slice(0, dot),
116
+ name = k.slice(dot + 1),
117
+ it = items.find((x) => x.id === id);
118
+ if (!it)
119
+ throw new Error(`${said}: ${ref} has no item "${id}" (items: ${items.map((x) => x.id).join(', ') || 'none'})`);
120
+ if (!it.object)
121
+ throw new Error(
122
+ `${said}: item ${id} is ${it.assembly ? `the assembly ${it.assembly}` : 'not an object'}, and --set reaches an object item's own variables only: set it in ${ref}'s file, in the item's "set"`,
123
+ );
124
+ const objName = String(it.object).split(/[:@]/)[0],
125
+ vars = readObject(locateIn(project, objName, `${assemblyPath(ref)}, item ${id}'s "object"`)).variables || {};
126
+ if (!Object.hasOwn(vars, name))
127
+ throw new Error(
128
+ `${said}: item ${id} (${objName}) has no variable "${name}" (variables: ${Object.keys(vars).join(', ') || 'none'})`,
129
+ );
130
+ (out[id] ||= {})[name] = v;
131
+ }
132
+ return out;
133
+ }
134
+
90
135
  export { satisfies }; // from @rulecad/versions
91
136
 
92
137
  // buildAssembly('keyboard/keycap-on-switch') -> { a, project, name, items, parts, objects, fits, requires, values, num }
@@ -942,14 +987,11 @@ function measured(a, b, centre) {
942
987
  .update(JSON.stringify([gearsCode, a, b, +centre.toFixed(6)]))
943
988
  .digest('hex')}.json`,
944
989
  );
945
- if (!process.env.CAD_NO_CACHE && cached(file)) return JSON.parse(host.readText(file));
990
+ const kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
991
+ if (kept) return kept;
946
992
  const r = contact(a, b, { centre, steps: 12 }),
947
993
  keep = { findings: r.findings, backlash: r.backlash, error: r.error };
948
- try {
949
- host.writeText(file, JSON.stringify(keep));
950
- } catch {
951
- // (a cache that can't be written is only slower)
952
- }
994
+ writeCacheFile(file, JSON.stringify(keep)); // (one that can't be written is only slower)
953
995
  return keep;
954
996
  }
955
997
 
@@ -1724,11 +1766,8 @@ function pairOverlap(pa, pb) {
1724
1766
  const solidOf = (p) => p.collide ?? p.geometry; // (a beam by its envelope: lib/beams.mjs)
1725
1767
  if (!pa.hash || !pb.hash) return overlap(solidOf(pa), solidOf(pb));
1726
1768
  remembered ||= (() => {
1727
- try {
1728
- return cached(OVERLAPS) ? JSON.parse(host.readText(OVERLAPS)) : {};
1729
- } catch {
1730
- return {};
1731
- }
1769
+ const kept = readCacheJson(OVERLAPS); // (one cut short or spoiled: nothing remembered)
1770
+ return kept && typeof kept === 'object' && !Array.isArray(kept) ? kept : {};
1732
1771
  })();
1733
1772
  const at = (p) =>
1734
1773
  `${p.hash}@${Array.from(p.m || [])
@@ -1749,12 +1788,7 @@ function pairOverlap(pa, pb) {
1749
1788
  }
1750
1789
  function saveOverlaps() {
1751
1790
  if (!fresh) return;
1752
- try {
1753
- host.writeText(OVERLAPS, JSON.stringify(remembered));
1754
- fresh = 0;
1755
- } catch {
1756
- // (a cache that can't be written is only slower)
1757
- }
1791
+ if (writeCacheFile(OVERLAPS, JSON.stringify(remembered))) fresh = 0; // (one that can't be written is only slower)
1758
1792
  }
1759
1793
 
1760
1794
  // A screw and what it is threaded into (its part, its nut, its insert) share space by design: fasten's hardware says which
@@ -2311,6 +2345,7 @@ export function checkAssembly(s) {
2311
2345
  values: {
2312
2346
  inside: m.inside,
2313
2347
  outside: m.outside,
2348
+ envelope: m.envelope?.size ?? null,
2314
2349
  lengths: m.lengths.map(({ length, count }) => ({ length, count })),
2315
2350
  },
2316
2351
  refs: { kind: m.kind, profile: m.profile, join: m.join.kind, arrangement: m.arrangement, by: m.by },
@@ -2345,21 +2380,21 @@ export function checkAssembly(s) {
2345
2380
  refs: { items: refs.map((o) => o.id) },
2346
2381
  });
2347
2382
  }
2348
- // Rules that are only estimates, anywhere in the assembly or its components
2349
- const est = new Set();
2350
- for (const o of s.objects)
2351
- for (const e of o.built.entries) if (e.kind === 'estimate' && (e.used || !e.name.includes('.'))) est.add(e.name);
2352
- for (const n of s.seen) {
2353
- const [u, k] = n.split('.');
2354
- if (loadRuleSet(u).rules[k]?.kind === 'estimate') est.add(n);
2355
- }
2356
- if (est.size)
2357
- f(
2358
- 'warn',
2359
- `uses estimates, not measurements: ${[...est].join(', ')}. Measure each and settle it with cad measured ${s.project}/${s.name} <name>=<value>`,
2360
- `Estimate: ${[...est].join(', ')}`,
2361
- { code: 'rules.estimate', refs: { rules: [...est] } },
2362
- );
2383
+ // Rules that are only estimates, anywhere in the assembly or its components, and seats drawn to an estimated fit
2384
+ // (said the same way by an object's own check: estimates.mjs estimatesFinding)
2385
+ const est = estimatesFinding(
2386
+ s.objects.map((o) => o.built),
2387
+ {
2388
+ ref: `${s.project}/${s.name}`,
2389
+ seen: s.seen,
2390
+ kindOf: (n) => {
2391
+ const [u, k] = n.split('.');
2392
+ return loadRuleSet(u).rules[k]?.kind;
2393
+ },
2394
+ assembly: true,
2395
+ },
2396
+ );
2397
+ if (est) f(est.level, est.text, est.short, { code: est.code, refs: est.refs });
2363
2398
  saveOverlaps();
2364
2399
  return out;
2365
2400
  }
@@ -0,0 +1,105 @@
1
+ // The workspace's .cache/ folder, written and read one way (issue #633). Everything cad keeps there (builds, stages,
2
+ // routes, overlaps, the gears' contact, the finite elements' results, assembly orders, optimised shapes and their
3
+ // densities, recorded runs, links, the record of AGENTS.md) is written by writeCacheFile and, where it is JSON, read by
4
+ // readCacheJson. test/cache-writes.test.mjs holds every file of lib/ and bin/ to that.
5
+ //
6
+ // Two dangers. A workspace cloned from someone else may carry a .cache/ of its own, and a file there that is a link to a
7
+ // file elsewhere (the user's trust list, a file in their home) would be written through, overwritten with what the tool
8
+ // worked out: so a cache file is written only where it, and every folder between it and the workspace, is a plain file
9
+ // and plain folders, or not there yet (ownCacheFile); otherwise the result is simply not kept. And a run stopped part way
10
+ // through writing (Ctrl-C, a test's time running out, a full disc) would leave a file cut short that every later run
11
+ // failed to read: so a file is written whole beside its place and then renamed over it, which leaves either the old
12
+ // file or the new one, never part of one; and a kept file that does not read as JSON is a miss, removed and made again.
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import crypto from 'node:crypto';
16
+ import { host, nodeHost, cached } from './host.mjs';
17
+ import { WS } from './workspace.mjs';
18
+
19
+ /**
20
+ * Whether the tool may write a cache file at `file`: it lies inside the workspace (root), and it and every folder on its
21
+ * way down from there are a plain file (not a link, and not hard-linked to another name) and plain folders, or are not
22
+ * there yet. A workspace in memory has nothing on disk to follow, so any file of it is the tool's own.
23
+ * @param {string} file @param {string} [root] the workspace @returns {boolean}
24
+ */
25
+ export function ownCacheFile(file, root = WS) {
26
+ if (host.name === 'memory') return true;
27
+ const top = path.resolve(root);
28
+ let p = path.resolve(file);
29
+ if (!p.startsWith(top + path.sep)) return false;
30
+ for (let first = true; p !== top; p = path.dirname(p), first = false) {
31
+ let st;
32
+ try {
33
+ st = fs.lstatSync(p);
34
+ } catch (e) {
35
+ if (e.code === 'ENOENT') continue;
36
+ return false;
37
+ }
38
+ if (first ? !(st.isFile() && st.nlink === 1) : !st.isDirectory()) return false;
39
+ }
40
+ return true;
41
+ }
42
+
43
+ /**
44
+ * Keep `text` in the cache file `file`, whole or not at all: only where ownCacheFile allows (a link, or a folder that is
45
+ * a link, is left as it is and the text not kept), written to a new file beside it that is then renamed over it. A
46
+ * cache that can't be written is only slower, so nothing is thrown.
47
+ * @param {string} file @param {string} text @returns {boolean} whether it was kept
48
+ */
49
+ export function writeCacheFile(file, text) {
50
+ try {
51
+ if (!ownCacheFile(file)) return false;
52
+ if (host.writeText !== nodeHost.writeText) {
53
+ host.writeText(file, text); // (a host of another kind, a workspace in memory: what it writes is its own business)
54
+ return true;
55
+ }
56
+ const dir = path.dirname(file);
57
+ fs.mkdirSync(dir, { recursive: true });
58
+ if (!ownCacheFile(file)) return false; // (the folders just made, checked again)
59
+ const temp = path.join(dir, `.${path.basename(file)}.${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`);
60
+ try {
61
+ fs.writeFileSync(temp, text, { flag: 'wx' }); // (wx: a new file, never one that is there already, nor a link)
62
+ fs.renameSync(temp, file);
63
+ } catch (e) {
64
+ fs.rmSync(temp, { force: true });
65
+ throw e;
66
+ }
67
+ return true;
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Remove a cache file that is the tool's own (ownCacheFile): a link, or a file elsewhere, is left alone.
75
+ * @param {string} file
76
+ */
77
+ export function dropCacheFile(file) {
78
+ try {
79
+ if (ownCacheFile(file)) host.remove(file);
80
+ } catch {
81
+ // (left for another run: it is a miss each time until then)
82
+ }
83
+ }
84
+
85
+ /**
86
+ * A kept JSON file of the cache, or undefined when there is none to read: not there, a link out of the workspace
87
+ * (host.mjs cached), or a file that does not read as JSON (cut short by a run that was stopped while writing it under an
88
+ * older version of the tool, or spoiled since), which is removed so that it is made again.
89
+ * @param {string} file @returns {any}
90
+ */
91
+ export function readCacheJson(file) {
92
+ if (!cached(file)) return undefined;
93
+ let text;
94
+ try {
95
+ text = host.readText(file);
96
+ } catch {
97
+ return undefined;
98
+ }
99
+ try {
100
+ return JSON.parse(text);
101
+ } catch {
102
+ dropCacheFile(file);
103
+ return undefined;
104
+ }
105
+ }
@@ -0,0 +1,28 @@
1
+ // Code as it runs, for the keys of cad's slow caches (an optimisation's densities, a fitting's finite-element results):
2
+ // a module's text without its lines that are only a comment (// ..., or a /* ... */ or /** ... */ block) and without
3
+ // blank lines. Rewording a comment, or spacing the code out, then keeps a key and the minutes of work kept under it;
4
+ // any change to the code itself moves it. A comment after code on the same line stays in: telling it apart from a
5
+ // string that holds // would take a parser, and a key that moves now and then is only slower, never wrong.
6
+ // (@rulecad/frames has its own copy for fittingCode, as it runs in a browser and does not depend on cad.)
7
+
8
+ /**
9
+ * A module's code without the lines that are only a comment and without blank lines.
10
+ * @param {string} text the module's text, or a function's (fn.toString())
11
+ * @returns {string}
12
+ */
13
+ export function codeOnly(text) {
14
+ let inComment = false;
15
+ return String(text)
16
+ .split('\n')
17
+ .filter((line) => {
18
+ const t = line.trim();
19
+ // (a block comment's lines, kept only where code follows its end on the same line)
20
+ if (inComment || t.startsWith('/*')) {
21
+ const end = t.indexOf('*/', inComment ? 0 : 2);
22
+ inComment = end < 0;
23
+ return !inComment && t.slice(end + 2).trim() !== '';
24
+ }
25
+ return t !== '' && !t.startsWith('//');
26
+ })
27
+ .join('\n');
28
+ }
@@ -0,0 +1,127 @@
1
+ // A design run in the tool's own process (a trusted workspace's), loaded so that the files it imports are known and
2
+ // never stale. Node keeps every module it has loaded for as long as the process runs, by its URL: a design is loaded
3
+ // by a URL that changes with its text, but a helper it imports ('./box.js') would be found by its plain URL and so kept
4
+ // as first loaded, however it is edited after (a live view runs for hours). So an import hook marks each file a design
5
+ // reaches by a path (not a package) with the design's load: `?rulecad-design=<token>`, the token a hash of the design's
6
+ // text and of the files it imported the last time. Edit a helper and the token changes, so the design and its helpers
7
+ // are loaded afresh. The hook notes those files too, for the build's cache (design.mjs): the tool learns them by
8
+ // importing a module the hook makes up, which works the same whether the hook runs in this thread or, on older Node,
9
+ // in a worker of its own.
10
+ import fs from 'node:fs';
11
+ import crypto from 'node:crypto';
12
+ import * as nodeModule from 'node:module';
13
+ import { fileURLToPath, pathToFileURL } from 'node:url';
14
+
15
+ const MARK = 'rulecad-design',
16
+ LIST = 'rulecad-imports:'; // `${LIST}${token}?n=<count>`: the files a load imported, as a module of the hook's making
17
+
18
+ // ---- the hook (in this thread, or in the hooks' worker on older Node) ----
19
+ const imported = new Map(); // token -> Set of file: URLs
20
+ const tokenOf = (url) => {
21
+ if (!url?.startsWith('file:')) return null;
22
+ return new URL(url).searchParams.get(MARK);
23
+ };
24
+ const byPath = (spec) =>
25
+ spec.startsWith('./') || spec.startsWith('../') || spec.startsWith('/') || spec.startsWith('file:');
26
+ function mark(spec, context, r) {
27
+ const token = tokenOf(context.parentURL);
28
+ if (!token || !byPath(spec) || !r.url.startsWith('file:')) return r;
29
+ const u = new URL(r.url);
30
+ if (u.pathname.split('/').some((s) => s.toLowerCase() === 'node_modules')) return r; // (a package's file: left as it is)
31
+ const plain = new URL(u.href);
32
+ plain.search = plain.hash = '';
33
+ if (!imported.has(token)) imported.set(token, new Set());
34
+ imported.get(token).add(plain.href);
35
+ u.searchParams.set(MARK, token);
36
+ return { ...r, url: u.href };
37
+ }
38
+ /** The import hook's resolve, in this thread (module.registerHooks). */
39
+ export function resolveHook(spec, context, next) {
40
+ if (spec.startsWith(LIST)) return { url: spec, shortCircuit: true };
41
+ return mark(spec, context, next(spec, context));
42
+ }
43
+ /** The import hook's resolve, in a worker (module.register). */
44
+ export async function resolve(spec, context, next) {
45
+ if (spec.startsWith(LIST)) return { url: spec, shortCircuit: true };
46
+ return mark(spec, context, await next(spec, context));
47
+ }
48
+ /** The import hook's load, in this thread: the made-up module that lists a load's files. */
49
+ export function loadHook(url, context, next) {
50
+ if (!url.startsWith(LIST)) return next(url, context);
51
+ const token = url.slice(LIST.length).split('?')[0];
52
+ return {
53
+ format: 'module',
54
+ source: `export default ${JSON.stringify([...(imported.get(token) || [])])};`,
55
+ shortCircuit: true,
56
+ };
57
+ }
58
+ /** The import hook's load, in a worker. */
59
+ export async function load(url, context, next) {
60
+ return loadHook(url, context, next);
61
+ }
62
+
63
+ // ---- the tool's side ----
64
+ let hooked = false;
65
+ function hook() {
66
+ if (hooked) return;
67
+ hooked = true;
68
+ if (nodeModule.registerHooks) nodeModule.registerHooks({ resolve: resolveHook, load: loadHook });
69
+ else nodeModule.register(import.meta.url);
70
+ }
71
+ // For each design file: the token it was last loaded by and the files that load imported (paths)
72
+ const loads = new Map();
73
+ let asked = 0;
74
+ const textOf = (f) => {
75
+ try {
76
+ return fs.readFileSync(f, 'utf8');
77
+ } catch {
78
+ return '\u0000missing';
79
+ }
80
+ };
81
+
82
+ // The files a load has imported so far, as the hook noted them (absolute paths)
83
+ const listed = async (token) =>
84
+ (await import(`${LIST}${token}?n=${asked++}`)).default.map((u) => fileURLToPath(u)).sort();
85
+
86
+ /**
87
+ * A design's module, loaded afresh when it or a file it imports has changed since its last load here.
88
+ * @param {string} file the design's .js
89
+ * @returns {Promise<any>} the module
90
+ */
91
+ export async function loadDesign(file) {
92
+ hook();
93
+ const last = loads.get(file);
94
+ // (after a load that failed, a fresh token whatever the files say: Node keeps a failed load's error by its URL too,
95
+ // and the fault may have been a file that wasn't there, which no text of the last load's files shows)
96
+ const token = crypto
97
+ .createHash('sha256')
98
+ .update(
99
+ JSON.stringify([textOf(file), ...(last?.imports || []).map((f) => [f, textOf(f)]), last?.failed ? asked : null]),
100
+ )
101
+ .digest('hex')
102
+ .slice(0, 32);
103
+ if (last?.token === token && !last.failed) return import(last.url);
104
+ const url = new URL(pathToFileURL(file).href);
105
+ url.searchParams.set(MARK, token);
106
+ try {
107
+ const module = await import(url.href);
108
+ loads.set(file, { token, url: url.href, imports: await listed(token) });
109
+ return module;
110
+ } catch (e) {
111
+ loads.set(file, { token, url: url.href, imports: await listed(token), failed: true });
112
+ throw e;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * The files of its own (not a package's) a design has imported since it was loaded, its main's own imports included:
118
+ * absolute paths. Asked after main has run.
119
+ * @param {string} file the design's .js
120
+ * @returns {Promise<string[]>}
121
+ */
122
+ export async function importsOf(file) {
123
+ const last = loads.get(file);
124
+ if (!last) return [];
125
+ last.imports = await listed(last.token);
126
+ return last.imports;
127
+ }