@rulecad/cad 0.9.0 → 0.11.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 (68) hide show
  1. package/AGENTS.md +29 -10
  2. package/CHANGELOG.md +604 -0
  3. package/EXAMPLES.md +122 -105
  4. package/README.md +292 -63
  5. package/bin/cad.mjs +500 -87
  6. package/lib/assembly.mjs +486 -134
  7. package/lib/bays.mjs +124 -0
  8. package/lib/cache-file.mjs +148 -0
  9. package/lib/clone.mjs +93 -11
  10. package/lib/code-text.mjs +28 -0
  11. package/lib/design-imports.mjs +127 -0
  12. package/lib/design.mjs +291 -59
  13. package/lib/designshapes.mjs +142 -0
  14. package/lib/edit.mjs +29 -5
  15. package/lib/estimates.mjs +51 -0
  16. package/lib/fasten.mjs +11 -5
  17. package/lib/fe-key.mjs +29 -0
  18. package/lib/fittings.mjs +20 -15
  19. package/lib/fixings.mjs +17 -4
  20. package/lib/framebuild.mjs +73 -92
  21. package/lib/framecheck.mjs +154 -77
  22. package/lib/framegen.mjs +9 -1
  23. package/lib/frames.mjs +6 -2
  24. package/lib/framesize.mjs +45 -82
  25. package/lib/gait.mjs +17 -7
  26. package/lib/guides.mjs +84 -50
  27. package/lib/host.mjs +7 -3
  28. package/lib/kit.mjs +5 -5
  29. package/lib/list.mjs +29 -21
  30. package/lib/live-guard.mjs +18 -8
  31. package/lib/loads.mjs +35 -23
  32. package/lib/measured.mjs +740 -99
  33. package/lib/mesh.mjs +156 -56
  34. package/lib/motors.mjs +26 -33
  35. package/lib/names.mjs +15 -0
  36. package/lib/node-version.mjs +52 -0
  37. package/lib/optimise.mjs +34 -25
  38. package/lib/order.mjs +5 -12
  39. package/lib/parts.mjs +3 -0
  40. package/lib/picture-servers.mjs +66 -0
  41. package/lib/power.mjs +14 -7
  42. package/lib/preview.mjs +12 -25
  43. package/lib/programs.mjs +113 -0
  44. package/lib/rules.mjs +2 -1
  45. package/lib/sandbox-guard.mjs +43 -0
  46. package/lib/sandbox-hooks.mjs +109 -15
  47. package/lib/sandbox-lock.mjs +225 -0
  48. package/lib/sandbox-preload.mjs +2 -2
  49. package/lib/sandbox-run.mjs +22 -24
  50. package/lib/sandbox.mjs +345 -42
  51. package/lib/sheet.mjs +114 -3
  52. package/lib/targets/gist.mjs +9 -6
  53. package/lib/versions.mjs +294 -35
  54. package/lib/workspace.mjs +6 -3
  55. package/package.json +14 -14
  56. package/schemas/assembly.schema.json +6 -5
  57. package/schemas/object.schema.json +1 -1
  58. package/schemas/project.schema.json +6 -0
  59. package/templates/coupons/MEASURE.md +109 -0
  60. package/templates/coupons/assemblies/fixings-test.json +20 -0
  61. package/templates/coupons/assemblies/slot-test.json +11 -0
  62. package/templates/coupons/objects/fixings-coupon.js +88 -0
  63. package/templates/coupons/objects/fixings-coupon.json +26 -0
  64. package/templates/coupons/objects/holds-coupon.js +130 -0
  65. package/templates/coupons/objects/holds-coupon.json +42 -0
  66. package/templates/coupons/objects/slot-coupon.js +89 -0
  67. package/templates/coupons/objects/slot-coupon.json +29 -0
  68. package/templates/coupons/project.json +10 -0
package/lib/sheet.mjs CHANGED
@@ -44,10 +44,103 @@ function fileOf(name) {
44
44
  return file;
45
45
  }
46
46
 
47
+ // A workspace's copy of a kit set beside the kit's own, rule by rule. cad copies a kit set into rules/ the first time
48
+ // a design uses it and reads only the copy from then on, so a figure the kit corrects later would never reach it. A
49
+ // rule of the copy is the kit's to replace when the copy's is not "measured" (a figure taken from the maker's own part
50
+ // beats any published one) and was checked before the kit's was (a figure checked on the same day or later is the
51
+ // maker's own word, kept). The same figure with only more said of it in the kit's (a range added, say) is the kit's to
52
+ // take too. What the kit has and the copy lacks is new; what the copy has and the kit lacks is its own.
53
+ const day = (r) => {
54
+ const d = String(r?.checked ?? '');
55
+ return /^\d{4}-\d{2}-\d{2}$/.test(d) ? d : '';
56
+ };
57
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
58
+ /**
59
+ * How a copy of a kit rule set stands against the kit's set.
60
+ * @param {{ rules?: Record<string, any> }} copy the workspace's copy
61
+ * @param {{ rules?: Record<string, any> }} kit the kit's set of the same name
62
+ * @returns {{ changed: string[], refreshed: string[], added: string[], measured: string[], newer: string[], own: string[] }}
63
+ * changed: a figure the kit has newer than the copy's (the kit's to take); refreshed: the same figure, its words or
64
+ * date newer in the kit, or more said of it there; added: the kit's rules the copy lacks; measured: the copy's
65
+ * measured figures that differ from the kit's; newer: the copy's figures that differ from the kit's and were checked
66
+ * on or after its date (or where neither says when); own: the copy's rules the kit has none of
67
+ */
68
+ export function kitDifference(copy, kit) {
69
+ const mine = copy?.rules && typeof copy.rules === 'object' ? copy.rules : {},
70
+ theirs = kit?.rules && typeof kit.rules === 'object' ? kit.rules : {},
71
+ out = { changed: [], refreshed: [], added: [], measured: [], newer: [], own: [] };
72
+ for (const [k, r] of Object.entries(theirs)) {
73
+ if (!(k in mine)) {
74
+ out.added.push(k);
75
+ continue;
76
+ }
77
+ const c = mine[k];
78
+ if (same(c, r)) continue;
79
+ const differs = !same(c?.value, r?.value);
80
+ if (c?.kind === 'measured') {
81
+ if (differs) out.measured.push(k);
82
+ } else if (day(r) && day(c) < day(r)) out[differs ? 'changed' : 'refreshed'].push(k);
83
+ else if (differs) out.newer.push(k);
84
+ else if (c && typeof c === 'object' && Object.entries(c).every(([f, x]) => same(x, r?.[f]))) out.refreshed.push(k); // (the kit's adds to the same figure: its range, say)
85
+ }
86
+ for (const k of Object.keys(mine)) if (!(k in theirs)) out.own.push(k);
87
+ return out;
88
+ }
89
+ /**
90
+ * The copy brought up to date with the kit's set: every rule in the kit's order, the kit's where kitDifference says
91
+ * it is the kit's to take (changed, refreshed or added), the copy's otherwise, then the copy's own rules. The set's
92
+ * other fields are the kit's, with any the copy alone has kept, and its "interface" both together.
93
+ * @param {Record<string, any>} copy
94
+ * @param {Record<string, any>} kit
95
+ * @returns {{ set: Record<string, any>, difference: ReturnType<typeof kitDifference> }}
96
+ */
97
+ export function updateFromKit(copy, kit) {
98
+ const difference = kitDifference(copy, kit),
99
+ take = new Set([...difference.changed, ...difference.refreshed, ...difference.added]),
100
+ rules = {};
101
+ for (const [k, r] of Object.entries(kit.rules || {})) rules[k] = take.has(k) ? r : copy.rules[k];
102
+ for (const k of difference.own) rules[k] = copy.rules[k];
103
+ const set = { ...copy, ...kit, rules };
104
+ if (copy.interface || kit.interface) set.interface = { ...copy.interface, ...kit.interface };
105
+ return { set, difference };
106
+ }
107
+ /**
108
+ * cad rules update's reading: the workspace's copy of a kit set and what bringing it up to date would make of it.
109
+ * Writes nothing. A name the kit has no set of is refused (that set is the workspace's alone); a workspace with no copy
110
+ * gets { file, copy: undefined }.
111
+ * @param {string} name a rule set's name, already held to plainName
112
+ * @returns {{ file: string, copy?: Record<string, any>, kit?: Record<string, any>, set?: Record<string, any>, difference?: ReturnType<typeof kitDifference>, fields?: string[] }}
113
+ * fields: the set's own fields (its _doc, its interface) the update changes
114
+ */
115
+ export function updateSet(name) {
116
+ const kitFile = path.join(RULE_DIRS.at(-1), `${name}.json`),
117
+ file = path.join(RULE_DIRS[0], `${name}.json`);
118
+ if (!fs.existsSync(kitFile))
119
+ throw new Error(
120
+ `the kit has no rule set "${name}", so there is nothing to update rules/${name}.json from: it is this workspace's own`,
121
+ );
122
+ if (RULE_DIRS.length < 2 || !fs.existsSync(file)) return { file };
123
+ const copy = readSet(file),
124
+ kit = readSet(kitFile);
125
+ if (!copy?.rules || typeof copy.rules !== 'object')
126
+ throw new Error(`rules/${name}.json has no "rules" to update: cad rules check ${name} says what is wrong with it`);
127
+ const { set, difference } = updateFromKit(copy, kit),
128
+ fields = [...new Set([...Object.keys(copy), ...Object.keys(set)])].filter(
129
+ (k) => k !== 'rules' && !same(copy[k], set[k]),
130
+ );
131
+ return { file, copy, kit, set, difference, fields };
132
+ }
133
+
134
+ // A figure as a note says it: a number or a word as it is, anything else as JSON
135
+ const said = (v) => (typeof v === 'number' || typeof v === 'string' ? String(v) : JSON.stringify(v));
136
+ const listed = (list) =>
137
+ list.length > 8 ? `${list.slice(0, 8).join(', ')} and ${list.length - 8} more (--json lists them)` : list.join(', ');
138
+
47
139
  // What a check notes and never fails on. An alias: a name the vocabulary shares across parts (screw_clearance, which a
48
140
  // motor's mount reads) that a set gives to one of its own rules in "interface". A copy: a workspace's own copy of a
49
141
  // set the kit has (cad copies a set into rules/ the first time a design uses it), which is used as it is, even after
50
- // the kit's set gains figures: it is told which, so a design that wants one knows where it went.
142
+ // the kit's set gains figures or corrects one: it is told which (rules.new, rules.changed), and cad rules update takes
143
+ // them. A copy that is the kit's set word for word holds nothing of the workspace's own (rules.same).
51
144
  function notesOf(set, file) {
52
145
  const notes = [],
53
146
  kitDir = RULE_DIRS.at(-1),
@@ -69,12 +162,30 @@ function notesOf(set, file) {
69
162
  typeof set.rules === 'object'
70
163
  ) {
71
164
  const kit = readSet(kitFile),
72
- added = Object.keys(kit.rules || {}).filter((k) => !(k in set.rules));
165
+ { added, changed } = kitDifference(set, kit);
166
+ if (same(set, kit))
167
+ notes.push({
168
+ level: 'info',
169
+ code: 'rules.same',
170
+ text: `rules/${name}.json is the kit's ${name} as it is: nothing in it is yours yet. Unless you mean to put your own figures in it, you can delete it: the next design to use ${name} copies in the kit's as it is then`,
171
+ });
172
+ if (changed.length) {
173
+ const one = changed[0],
174
+ c = set.rules[one],
175
+ k = kit.rules[one];
176
+ notes.push({
177
+ level: 'info',
178
+ code: 'rules.changed',
179
+ text: `the kit's ${name} has a newer figure than your copy for ${one} (${said(c?.value)} here, ${said(k?.value)} in the kit's, checked ${k.checked})${changed.length > 1 ? ` and for ${listed(changed.slice(1))}` : ''}: cad rules update ${name} takes the kit's newer figures and keeps your measured ones`,
180
+ values: { count: changed.length },
181
+ refs: { rules: changed },
182
+ });
183
+ }
73
184
  if (added.length)
74
185
  notes.push({
75
186
  level: 'info',
76
187
  code: 'rules.new',
77
- text: `your copy is used as it is; the kit's ${name} now also has ${added.length > 8 ? `${added.slice(0, 8).join(', ')} and ${added.length - 8} more (--json lists them)` : added.join(', ')}: copy any you want into rules/${name}.json, or delete it to read the kit's own`,
188
+ text: `your copy is used as it is; the kit's ${name} now also has ${listed(added)}: copy any you want into rules/${name}.json, or cad rules update ${name} adds them all and keeps what is yours`,
78
189
  values: { count: added.length },
79
190
  refs: { rules: added },
80
191
  });
@@ -1,10 +1,13 @@
1
- // Short links through a secret GitHub Gist (unlisted: only people with the link find it), made with the gh command.
2
- import { execFileSync } from 'node:child_process';
1
+ // Short links through a secret GitHub Gist (unlisted: only people with the link find it), made with the gh command
2
+ // (found on PATH, never in the workspace: ../programs.mjs).
3
+ import { runProgram } from '../programs.mjs';
3
4
 
4
5
  export async function shorten(data, { desc }) {
5
- const out = execFileSync('gh', ['gist', 'create', '--filename', 'model.txt', '--desc', desc, '-'], {
6
- input: data,
7
- encoding: 'utf8',
8
- }).trim();
6
+ const out = runProgram(
7
+ 'gh',
8
+ ['gist', 'create', '--filename', 'model.txt', '--desc', desc, '-'],
9
+ { input: data, encoding: 'utf8' },
10
+ "gh, GitHub's command that makes the short link's Gist,",
11
+ ).trim();
9
12
  return out.split('/').pop();
10
13
  }
package/lib/versions.mjs CHANGED
@@ -5,19 +5,96 @@
5
5
  // A project release (keyboard@1.0.0) records which version of each object it contains.
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
- import { execFileSync } from 'node:child_process';
9
8
  import { createRequire } from 'node:module';
10
9
  import { fileURLToPath } from 'node:url';
11
10
  import crypto from 'node:crypto';
12
11
  import { resolve, loadRuleSet } from './rules.mjs';
13
12
  import { WS, paths } from './workspace.mjs';
14
13
  import { readJson, readOwnText } from './host.mjs';
15
- import { plainName, isPlainName } from './names.mjs';
14
+ import { plainName, isPlainName, isWorkspacePath } from './names.mjs';
16
15
  import { readLayout, hasLayout } from './layout.mjs';
17
16
  import { newer } from '@rulecad/versions';
17
+ import { runProgram } from './programs.mjs';
18
+ import { notOwn, writeOwnFile, removeOwnFolder } from './cache-file.mjs';
18
19
 
19
- export const git = (...args) =>
20
- execFileSync('git', args, { cwd: WS, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trimEnd();
20
+ // git, found by cad itself on PATH and never in the workspace (programs.mjs), run in the workspace
21
+ const GIT = 'git, which keeps releases,';
22
+ const runGit = (args) =>
23
+ runProgram('git', args, { cwd: WS, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }, GIT).trimEnd();
24
+
25
+ // git's own settings can name programs for it to run, and a workspace that comes with its .git folder (an archive, a
26
+ // copy) brings its .git/config and .git/hooks with it. Of the commands cad runs to read a workspace's releases and
27
+ // changes, git status (and write-tree) start such programs: the file system monitor (core.fsmonitor), a filter driver
28
+ // that cleans each file it compares (filter.<name>.clean, .process, chosen by the workspace's .gitattributes) and the
29
+ // post-index-change hook. So every git command cad runs to read has them closed on its command line: the monitor
30
+ // off, hooks looked for in a file (so none is found), no index written back (--no-optional-locks), no pager, and every
31
+ // filter and diff program git's settings name blanked. (for-each-ref, tag -l, show <tag>:<file>, ls-tree, rev-parse,
32
+ // cat-file and var start none of them; they are closed all the same.) What a release commits, tags and pushes runs as
33
+ // those commands would by hand: gitAsByHand.
34
+ let closing = null;
35
+ // A list of git's settings (git config --list -z, as bytes) cut into its entries
36
+ function split(list) {
37
+ const out = [];
38
+ for (let at = 0; at < list.length;) {
39
+ const end = list.indexOf(0, at);
40
+ out.push(list.subarray(at, end < 0 ? list.length : end));
41
+ at = end < 0 ? list.length : end + 1;
42
+ }
43
+ return out;
44
+ }
45
+ function closed() {
46
+ if (closing) return closing;
47
+ const args = [
48
+ '--no-pager',
49
+ '--no-optional-locks',
50
+ '-c',
51
+ 'core.fsmonitor=', // (empty, not false: git before 2.36 would run a program named "false" as the monitor)
52
+ '-c',
53
+ `core.hooksPath=${process.execPath}`,
54
+ ];
55
+ // (as bytes, not text: a name in the settings that is not UTF-8 could not be given back to git as written; and with
56
+ // room for a long list: cut short, it would leave the programs named past the cut running)
57
+ let list;
58
+ try {
59
+ list = runProgram(
60
+ 'git',
61
+ ['--no-pager', 'config', '--list', '-z'],
62
+ {
63
+ cwd: WS,
64
+ stdio: ['ignore', 'pipe', 'pipe'],
65
+ maxBuffer: 64 * 1024 * 1024,
66
+ },
67
+ GIT,
68
+ );
69
+ } catch (e) {
70
+ if (e.code === 'ENOENT') throw e; // (git missing: said in plain words)
71
+ // (settings git can't read, or too many to read: git is not run on them, as cad could not tell what they start)
72
+ throw new Error(
73
+ `git could not list its settings for this workspace, so cad does not run git here (they may name programs for git to start). ${String(e.stderr || e.message).trim()} Look at the settings (git config --list --show-origin) and put right what is wrong`,
74
+ );
75
+ }
76
+ for (const bytes of split(list)) {
77
+ const raw = bytes.subarray(0, bytes.indexOf(10) < 0 ? bytes.length : bytes.indexOf(10)),
78
+ key = raw.toString('utf8'),
79
+ m = /^filter\.(.*)\.(?:clean|smudge|process)$/s.exec(key) || /^diff\.(.*)\.(?:textconv|command)$/s.exec(key);
80
+ if (!m && key !== 'diff.external') continue;
81
+ if (key.includes('=') || /[\r\n]/.test(key) || !Buffer.from(key, 'utf8').equals(raw))
82
+ throw new Error(
83
+ `git's settings for this workspace name a program under a name cad cannot switch off (${JSON.stringify(key)}), so git is not run. Look at the settings (git config --list --show-origin) and remove that one`,
84
+ );
85
+ args.push('-c', `${key}=`);
86
+ if (key.startsWith('filter.')) args.push('-c', `filter.${m[1]}.required=false`);
87
+ }
88
+ return (closing = args);
89
+ }
90
+
91
+ /** A git command, run in the workspace with every program git's settings name closed (above). */
92
+ export const git = (...args) => runGit([...closed(), ...args]);
93
+ /**
94
+ * A git command run as it would be by hand, the repository's hooks and settings in force: only for what a release
95
+ * commits, tags and pushes (the cad README, "Programs cad starts"), where the user's own hooks and signing are wanted.
96
+ */
97
+ export const gitAsByHand = (...args) => runGit(args);
21
98
 
22
99
  // ---------- semver: @rulecad/versions ----------
23
100
  export { parse, bump, newer, bigger, compare } from '@rulecad/versions';
@@ -59,22 +136,164 @@ const layoutNames = (d, object) =>
59
136
  // A file's path in git's terms: relative to the workspace, forward slashes on every system (git show tag:path needs them)
60
137
  const rel = (f) => path.relative(WS, f).split(path.sep).join('/');
61
138
 
62
- // 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.
139
+ // The files a design depends on, relative to the workspace (its git repo): its .js and .json, the rule sets and the
140
+ // layouts it uses, and, given its build (b), everything else the build read (design.mjs readsOf): the files its design
141
+ // imported, the rule sets v.fixings and v.frames read, and the files of the objects it reads through "uses". A release
142
+ // commits them all, so its tag holds every file it was built from.
63
143
  // (A board's engine is the tool's code, not the workspace's: its release records engineId() instead.)
64
- export function files(d, object) {
65
- return [
144
+ export function files(d, object, b) {
145
+ const own = [
66
146
  rel(d.js),
67
147
  rel(d.json),
68
148
  ...(object.uses || []).filter((u) => !u.includes('/')).map((u) => `rules/${u}.json`),
69
149
  ...layoutNames(d, object).map((n) => `projects/${d.project}/layouts/${n}.json`),
70
150
  ];
151
+ const r = b?.reads;
152
+ if (!r) return own;
153
+ // (only the workspace's own files: never a release's copy in .versions/, nor the cache)
154
+ const more = [...r.files, ...r.sets, ...r.also].filter((f) => isWorkspacePath(f) && !f.startsWith('.'));
155
+ return [...new Set([...own, ...more])];
156
+ }
157
+
158
+ // What a release records of its build's reads, in its tag's message (a line "reads: {…}"): the files its design
159
+ // imported, whether it called v.fixings and v.frames, and the files of the objects it reads. Its rule sets aren't
160
+ // listed: a release is rebuilt with every rule set its tag holds.
161
+ export const READS = 'reads: ';
162
+ export const readsLine = (b) =>
163
+ b?.reads
164
+ ? `${READS}${JSON.stringify({
165
+ files: b.reads.files.filter((f) => !f.startsWith('.')),
166
+ fixings: b.reads.fixings,
167
+ frames: b.reads.frames,
168
+ also: b.reads.also.filter((f) => !f.startsWith('.')),
169
+ })}`
170
+ : '';
171
+ // A tag's record of what its release read, or null for a release made before releases recorded it (or a line that is
172
+ // not one the tool writes: a tag comes with a cloned workspace, so its paths are taken only where they are plain paths
173
+ // inside the workspace)
174
+ function recorded(tag) {
175
+ let text;
176
+ try {
177
+ text = git('tag', '-l', '--format=%(contents)', tag);
178
+ } catch {
179
+ return null;
180
+ }
181
+ const line = text.split('\n').findLast((l) => l.startsWith(READS)); // (the tool's line comes after the message)
182
+ if (!line) return null;
183
+ let r;
184
+ try {
185
+ r = JSON.parse(line.slice(READS.length));
186
+ } catch {
187
+ return null;
188
+ }
189
+ const list = (x) => (Array.isArray(x) ? x.filter((f) => isWorkspacePath(f) && !f.startsWith('.')) : []);
190
+ return r && typeof r === 'object'
191
+ ? { files: list(r.files), fixings: r.fixings === true, frames: r.frames === true, also: list(r.also) }
192
+ : null;
193
+ }
194
+
195
+ // The files a .js imports by a path ('./box.js', '../shared/x.mjs'), as written in it: a release made before releases
196
+ // recorded what they read is rebuilt with these (and what they import in turn). Paths inside the workspace, from the
197
+ // file's own (`from`, a path inside the workspace).
198
+ const IMPORTED = /(?:\bfrom\s*|\bimport\s*\(?\s*)(['"])(\.\.?\/[^'"\n]+)\1/g;
199
+ const importedBy = (from, text) =>
200
+ [...String(text).matchAll(IMPORTED)]
201
+ .map((m) => path.posix.join(path.posix.dirname(from), m[2]))
202
+ .filter((f) => isWorkspacePath(f) && /\.(m?js|json)$/.test(f));
203
+
204
+ // A release's folder holds its files at the paths they have in the workspace (.versions/<project>/<object>@<version>/
205
+ // projects/<project>/objects/<object>.js, …/rules/x1c.json), so that what the design imports by a path is found there
206
+ // as it was, and what it imports from a package is found in the workspace's node_modules, above.
207
+ // put: a file of the release written there from its tag (false when the tag has no such file)
208
+ // A workspace cloned from someone else may bring a .versions/ of its own, and a link there (.versions itself, a
209
+ // version's folder, a folder in its tree, one of its files) would have the tool write a file of the stranger's choosing
210
+ // outside the workspace, remove a folder there, or read a file from elsewhere as the release's design (and send it out
211
+ // in a model link). So nothing under .versions/ is written, read or removed through a link (cache-file.mjs notOwn,
212
+ // the guard .cache/ has too): one found is refused, named, and nothing is written or removed (issue #696).
213
+ function linkRefused(bad) {
214
+ const name = path.relative(WS, bad) || bad;
215
+ throw Object.assign(
216
+ new Error(
217
+ `${name} is a link (or not the plain folder or file cad makes there: a file with a second name elsewhere, say), so cad does not unpack or read a released version through it: it could lead outside this workspace (${WS}). cad keeps its copies of released versions in .versions/ and makes them again when they are needed: look at where the link leads, then remove the .versions folder and run the command again`,
218
+ ),
219
+ { code: 'versions.link', file: bad },
220
+ );
221
+ }
222
+ // A path under .versions/ that may be read or written: it, and every folder on its way, plain or not there yet
223
+ const ownVersionPath = (p, folder = false) => {
224
+ const bad = notOwn(p, WS, { folder });
225
+ if (bad) linkRefused(bad);
226
+ return p;
227
+ };
228
+ function treeOf(tag, base) {
229
+ const show = (f) => git('show', `${tag}:./${f}`); // (./: from the workspace, which may be below the repository's root)
230
+ const put = (f) => {
231
+ if (!isWorkspacePath(f)) return false;
232
+ const to = ownVersionPath(path.join(base, ...f.split('/'))); // (a file there already is read: not through a link)
233
+ if (fs.existsSync(to)) return true;
234
+ let text;
235
+ try {
236
+ text = show(f);
237
+ } catch {
238
+ return false;
239
+ }
240
+ writeOwnFile(to, text, linkRefused);
241
+ return true;
242
+ };
243
+ // A design's file, and those it imports by a path, in turn (as written: what it imports as it runs is in the record)
244
+ const withImports = (f) => {
245
+ const seen = new Set();
246
+ for (let todo = [f]; todo.length && seen.size < 1000;) {
247
+ const x = todo.pop();
248
+ if (seen.has(x) || !put(x)) continue;
249
+ seen.add(x);
250
+ if (/\.m?js$/.test(x)) todo.push(...importedBy(x, fs.readFileSync(path.join(base, ...x.split('/')), 'utf8')));
251
+ }
252
+ seen.delete(f);
253
+ return [...seen].sort();
254
+ };
255
+ return { show, put, withImports };
256
+ }
257
+
258
+ // An object's files from a release's tag, into the release's folder: its .js and what that imports, its .json and the
259
+ // layouts it can pick. -> its .json, parsed, and the files its .js imports
260
+ function objectFrom(t, project, name, where) {
261
+ const json = `projects/${project}/objects/${name}.json`,
262
+ js = `projects/${project}/objects/${name}.js`;
263
+ let object;
264
+ try {
265
+ object = JSON.parse(t.show(json));
266
+ } catch {
267
+ throw new Error(`${where} has no ${project}/${name} that can be read (${json})`);
268
+ }
269
+ t.put(json);
270
+ if (!t.put(js)) throw new Error(`${where} has no ${js}`);
271
+ const imports = t.withImports(js);
272
+ for (const v of Object.values(object.variables || {}))
273
+ if (v.type === 'layout')
274
+ for (const n of (v.choice || [v.value]).filter(isPlainName)) t.put(`projects/${project}/layouts/${n}.json`); // (another name is refused where the layout is read; a built-in (grid) has no file)
275
+ return { object, imports };
276
+ }
277
+
278
+ // The rule sets a release holds, all of them, into its folder: what its "uses" names, and what v.fixings and v.frames
279
+ // read (thread, material, profile sets and the printer's, with rules/outlines/), as its tag has them
280
+ function rulesFrom(tag, t) {
281
+ let names = [];
282
+ try {
283
+ // (--full-tree: below the repository's root, ls-tree would list only what is under the same folder of the tree)
284
+ names = git('ls-tree', '-r', '--name-only', '--full-tree', `${tag}:./rules`).split('\n');
285
+ } catch {
286
+ // (no rules/ in the release)
287
+ }
288
+ for (const n of names) if (/^(outlines\/)?[^/]+\.json$/.test(n)) t.put(`rules/${n}`);
71
289
  }
72
290
 
73
291
  // A released version's files, written under .versions/ so its imports still find node_modules. -> a design to build
74
292
  export function materialise(d, version) {
75
293
  const tag = `${d.project}/${d.name}@${version}`;
294
+ let id;
76
295
  try {
77
- git('rev-parse', '--verify', `refs/tags/${tag}`);
296
+ id = git('rev-parse', '--verify', `refs/tags/${tag}`);
78
297
  } catch {
79
298
  throw new Error(
80
299
  `no release ${tag} (releases: ${
@@ -85,32 +304,70 @@ export function materialise(d, version) {
85
304
  );
86
305
  }
87
306
  const base = paths.versions(d.project, `${d.name}@${version}`);
88
- const show = (rel) => git('show', `${tag}:${rel}`);
89
- const object = JSON.parse(show(rel(d.json)));
90
- fs.mkdirSync(path.join(base, 'rules'), { recursive: true });
91
- const js = path.join(base, `${d.name}.js`),
92
- json = path.join(base, `${d.name}.json`);
93
- fs.writeFileSync(js, show(rel(d.js)));
94
- fs.writeFileSync(json, JSON.stringify(object, null, 2));
307
+ // A file already in the folder is used as it is (treeOf), so the folder is made afresh when it was written from
308
+ // another tag of the same name (one deleted and made again) or by an earlier version of the tool (another layout)
309
+ // (.versions, the project's folder there and the version's: plain folders, or not there yet; the same for its stamp)
310
+ const stamp = ownVersionPath(path.join(ownVersionPath(base, true), '.tag'));
311
+ if (fs.existsSync(base) && (!fs.existsSync(stamp) || fs.readFileSync(stamp, 'utf8') !== id))
312
+ removeOwnFolder(base, linkRefused);
313
+ writeOwnFile(stamp, id, linkRefused);
314
+ const t = treeOf(tag, base);
95
315
  // (names from the release's own file, each written as a file here: plain names only, never ../)
316
+ const object = JSON.parse(t.show(rel(d.json)));
96
317
  for (const u of (object.uses || []).filter((x) => !x.includes('/')))
97
- fs.writeFileSync(
98
- path.join(base, 'rules', `${plainName(u, 'rule set name', `${tag}'s ${d.name}.json, in its "uses"`)}.json`),
99
- show(`rules/${u}.json`),
100
- ); // objects it reads are released on their own
101
- // The layouts it could pick, as they were then (only files that existed in that release)
102
- fs.mkdirSync(path.join(base, 'layouts'), { recursive: true });
103
- for (const v of Object.values(object.variables || {}))
104
- if (v.type === 'layout')
105
- for (const n of (v.choice || [v.value]).filter(isPlainName)) {
106
- // (another name is refused where the layout is read)
107
- try {
108
- fs.writeFileSync(path.join(base, 'layouts', `${n}.json`), show(`projects/${d.project}/layouts/${n}.json`));
109
- } catch {
110
- // (a built-in layout (grid): nothing to write)
111
- }
112
- }
113
- return { ...d, js, json, rulesDir: path.join(base, 'rules'), layoutsDir: path.join(base, 'layouts'), version, tag };
318
+ plainName(u, 'rule set name', `${tag}'s ${d.name}.json, in its "uses"`);
319
+ const { imports } = objectFrom(t, d.project, d.name, tag);
320
+ rulesFrom(tag, t);
321
+ t.put(`projects/${d.project}/project.json`); // (the material v.fixings draws for, as it was)
322
+ // What the release read, as its tag records it; for one made before tags recorded it, the files its .js imports by
323
+ // a path, and v.fixings and v.frames where its code names them
324
+ let reads = recorded(tag);
325
+ if (reads) for (const f of [...reads.files, ...reads.also]) t.put(f);
326
+ else {
327
+ const code = [rel(d.js), ...imports]
328
+ .map((f) => fs.readFileSync(path.join(base, ...f.split('/')), 'utf8'))
329
+ .join('\n');
330
+ reads = { files: imports, fixings: /\bfixings\b/.test(code), frames: /\bframes\b/.test(code), also: [] };
331
+ }
332
+ const at = (f) => path.join(base, ...rel(f).split('/'));
333
+ return {
334
+ ...d,
335
+ js: at(d.js),
336
+ json: at(d.json),
337
+ rulesDir: path.join(base, 'rules'),
338
+ layoutsDir: path.join(base, 'projects', d.project, 'layouts'),
339
+ version,
340
+ tag,
341
+ tree: base,
342
+ reads,
343
+ };
344
+ }
345
+
346
+ /**
347
+ * Another object as a release has it (its files at the release's tag), for a release that reads it through "uses"
348
+ * without naming a version: rebuilt from the same tag as the release, so with the numbers it had then.
349
+ * @param {{ tag: string, tree: string, rulesDir: string, project: string }} d the release (materialise's)
350
+ * @param {string} project @param {string} name the object, plain names (design.mjs objectSets has checked them)
351
+ */
352
+ export function inRelease(d, project, name) {
353
+ const [plain, variant] = String(name).split(':');
354
+ plainName(project, 'project name');
355
+ plainName(plain, 'object name');
356
+ const t = treeOf(d.tag, d.tree);
357
+ objectFrom(t, project, plain, d.tag);
358
+ const at = (f) => path.join(d.tree, 'projects', project, f);
359
+ return {
360
+ project,
361
+ name: plain,
362
+ js: at(`objects/${plain}.js`),
363
+ json: at(`objects/${plain}.json`),
364
+ dir: paths.project(project),
365
+ rulesDir: d.rulesDir,
366
+ layoutsDir: at('layouts'),
367
+ tag: d.tag,
368
+ tree: d.tree,
369
+ ...(variant ? { variant } : {}),
370
+ };
114
371
  }
115
372
 
116
373
  // ---------- what changed: compare() is @rulecad/versions' (exported above) ----------
@@ -159,7 +416,7 @@ function taggedEngine(tag) {
159
416
  const m = git('tag', '-l', '--format=%(contents)', tag).match(/^engine: (\w+)$/m);
160
417
  if (m) return m[1];
161
418
  try {
162
- return engineHash(git('show', `${tag}:lib/pcb.mjs`));
419
+ return engineHash(git('show', `${tag}:./lib/pcb.mjs`));
163
420
  } catch {
164
421
  return '';
165
422
  } // (the engine once lived in the workspace)
@@ -167,7 +424,8 @@ function taggedEngine(tag) {
167
424
 
168
425
  // Resolve a design as it is on disk, or as materialised from a release.
169
426
  // refs: the numbers of objects it reads (design.mjs objectSets), which a snapshot can't build itself.
170
- export function snapshot(d, refs = {}) {
427
+ // reads: the text of each file it read besides its own (design.mjs readTexts), compared file by file by compare()
428
+ export function snapshot(d, refs = {}, reads = null) {
171
429
  const object = readJson(d.json); // (the workspace's own files only where they really are inside it: host.mjs)
172
430
  const sets = {
173
431
  ...(d.rulesDir
@@ -183,9 +441,10 @@ export function snapshot(d, refs = {}) {
183
441
  return {
184
442
  object,
185
443
  entries: resolve(object, { sets }).entries,
186
- js: readOwnText(d.js),
444
+ js: readOwnText(d.js).replace(/\r\n/g, '\n'), // (git keeps \n; a Windows checkout may write \r\n)
187
445
  layouts,
188
446
  ...(engine != null ? { engine } : {}),
447
+ ...(reads ? { reads } : {}),
189
448
  };
190
449
  }
191
450
 
package/lib/workspace.mjs CHANGED
@@ -2,8 +2,10 @@
2
2
  // and what's generated) are separate folders.
3
3
  // The workspace is $CAD_WORKSPACE, else the nearest folder at or above the current one with a cad.config.json, else
4
4
  // the current folder.
5
- // cad.config.json: { "printer": "x1c", "viewUrl": "https://…/", "targets": { "show": "targets/show.mjs", "shorten": "gist" } }
5
+ // cad.config.json: { "printer": "x1c", "engine": "manifold", "viewUrl": "https://…/", "targets": { "show": "targets/show.mjs", "shorten": "gist" } }
6
6
  // printer the rule set a print is checked against (bed, overhang, bridges); a project.json's "printer" wins
7
+ // engine the boolean engine of designs whose object names none: "manifold" (with manifold-3d installed; a new
8
+ // workspace's) or "jscad", the default (design.mjs booleans)
7
9
  // viewUrl the model page that links open (the public one by default: it reads links as data, nothing is uploaded)
8
10
  // targets optional extras: show (put a model on display: a module of your own) and shorten (short links: "gist")
9
11
  // designTimeout, designMemory how long a design may run in the sandbox (seconds) and the memory it may hold
@@ -189,8 +191,9 @@ export const paths = {
189
191
 
190
192
  // The printer a project's prints are checked against: project.json's "printer", else cad.config.json's. Either is a
191
193
  // rule set's name, which becomes part of a path (rules/<printer>.json, and the kit's), so it must be a plain name.
192
- export const printerOf = (project) => {
193
- const f = project && path.join(paths.project(project), 'project.json');
194
+ // dir: the project's folder as a release has it (lib/versions.mjs materialise), so it draws for the printer it named then.
195
+ export const printerOf = (project, dir = project && paths.project(project)) => {
196
+ const f = dir && path.join(dir, 'project.json');
194
197
  const own = f && host.exists(f) && readJson(f).printer;
195
198
  if (own) return plainName(own, '"printer" field', path.relative(WS, f));
196
199
  return plainName(config.printer, '"printer" field', 'cad.config.json');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
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": {
@@ -60,25 +60,25 @@
60
60
  "dependencies": {
61
61
  "@rulecad/variables": "^0.4.0",
62
62
  "@rulecad/keyboard-layout": "^0.2.0",
63
- "@rulecad/printcheck": "^0.4.0",
64
- "@rulecad/fit": "^0.5.0",
63
+ "@rulecad/printcheck": "^0.5.0",
64
+ "@rulecad/fit": "^0.5.1",
65
65
  "@rulecad/model-link": "^0.4.0",
66
- "@rulecad/versions": "^0.2.0",
67
- "@rulecad/shapes": "^0.5.0",
68
- "@rulecad/rules": "^0.4.0",
66
+ "@rulecad/versions": "^0.3.0",
67
+ "@rulecad/shapes": "^0.7.0",
68
+ "@rulecad/rules": "^0.6.0",
69
69
  "@jscad/modeling": "^2.12.0",
70
70
  "three": "^0.186.1",
71
- "@rulecad/fea": "^0.4.0",
72
- "@rulecad/topopt": "^0.4.0",
73
- "@rulecad/flexures": "^0.6.0",
74
- "@rulecad/gears": "^0.4.0",
75
- "@rulecad/motors": "^0.2.0",
76
- "@rulecad/fixings": "^0.2.0",
71
+ "@rulecad/fea": "^0.5.0",
72
+ "@rulecad/topopt": "^0.4.2",
73
+ "@rulecad/flexures": "^0.8.0",
74
+ "@rulecad/gears": "^0.5.0",
75
+ "@rulecad/motors": "^0.3.0",
76
+ "@rulecad/fixings": "^0.3.1",
77
77
  "@rulecad/robots": "^0.2.0",
78
- "@rulecad/frames": "^0.2.0"
78
+ "@rulecad/frames": "^0.4.0"
79
79
  },
80
80
  "peerDependencies": {
81
- "@rulecad/pcb": "^0.7.0"
81
+ "@rulecad/pcb": "^0.8.0"
82
82
  },
83
83
  "peerDependenciesMeta": {
84
84
  "@rulecad/pcb": {