@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
@@ -0,0 +1,142 @@
1
+ // v.shapes: @rulecad/shapes as a design gets it, with what its seats were drawn to kept, as v.fixings keeps its holes
2
+ // (lib/fixings.mjs). A seat for a bought part (a shaft's bore, a bearing's pocket, a plain bearing, a pulley's bore) is
3
+ // drawn to a fit, and the fit is only as good as the figure it rests on: a press fit on a shaft is an estimate until
4
+ // someone presses one in. So each call of shaftBore, bearingSeat, plainBearing and pulleyBore says, as a 'seat.drawn'
5
+ // finding, what it was drawn to, the figure it rests on and how far that figure is trusted (its kind), and cad check
6
+ // and the estimate warning (rules.estimate) say it. @rulecad/shapes itself is unchanged: its helpers already return
7
+ // the fit and its kind; this only listens. No files are read here: the sandbox's runner uses it as the build does.
8
+ import { SHAFT_FITS } from '@rulecad/shapes';
9
+
10
+ /** The helpers of @rulecad/shapes that draw a seat for a bought part, and are reported. */
11
+ export const SEAT_HELPERS = ['shaftBore', 'bearingSeat', 'plainBearing', 'pulleyBore'];
12
+
13
+ const n = (x) => String(Number(Number(x).toFixed(4)));
14
+ const TRUST = {
15
+ measured: 'a measured figure',
16
+ spec: "a standard's figure",
17
+ community: 'a community figure',
18
+ estimate: 'an estimate',
19
+ given: 'a figure given by hand',
20
+ default: 'a default',
21
+ derived: 'a figure derived from the printer',
22
+ };
23
+ const trust = (kind) => TRUST[kind] ?? `a ${kind} figure`;
24
+
25
+ // The printer figure a helper read (press, slip, fit, hole_comp), named as a rule where it is the project's printer's
26
+ // (the printer the design was given reads the same as the printer's rule set: x1c.press, with that rule's kind), and
27
+ // otherwise as a figure the design gave, by hand
28
+ function printerFigure(given, printer, key) {
29
+ let value;
30
+ try {
31
+ value = given?.[key];
32
+ } catch {
33
+ value = undefined;
34
+ }
35
+ const rule = printer?.rules?.[key];
36
+ if (typeof value === 'number' && rule && typeof rule.value === 'number' && Math.abs(rule.value - value) < 1e-9)
37
+ return { rule: `${printer.name}.${key}`, kind: typeof rule.kind === 'string' ? rule.kind : 'given', value };
38
+ return { rule: `printer.${key}`, kind: 'given', value };
39
+ }
40
+
41
+ const fitSaid = (fit) => (typeof fit === 'number' ? `a fit of ${n(fit)} mm` : `${fit} fit`);
42
+
43
+ // A bearing's pocket, as a finding: what bearingSeat drew, and the printer's press or slip it rests on
44
+ function pocketFinding(args, r, printer, o) {
45
+ const s = r?.seat;
46
+ if (!s) return null;
47
+ const outer = args[0]?.outer_diameter ?? args[0]?.outer,
48
+ on =
49
+ typeof s.fit === 'number'
50
+ ? { rule: 'fit', says: 'the fit the design gave', kind: 'given', value: s.fit }
51
+ : { ...printerFigure(o.printer, printer, s.fit), says: null },
52
+ comp = printerFigure(o.printer, printer, 'hole_comp');
53
+ return {
54
+ level: 'info',
55
+ code: 'seat.drawn',
56
+ text:
57
+ `a pocket for a bearing ${n(outer)} mm across drawn ${n(s.pocket)} mm (bearingSeat, ${fitSaid(s.fit)}): it ` +
58
+ `rests on ${on.says ?? on.rule} (${n(Math.abs(s.clearance))} mm ${s.clearance < 0 ? 'of press' : 'of slip'} across), ` +
59
+ `${trust(on.kind)}, plus ${comp.rule} ${n(s.comp)} mm across, since a printed hole comes out small`,
60
+ values: { diameter: s.pocket, outer, clearance: s.clearance, comp: s.comp },
61
+ refs: { helper: 'bearingSeat', fit: s.fit, rule: on.rule, kind: on.kind },
62
+ };
63
+ }
64
+
65
+ // What one call drew, as a finding: { level, text, code, values, refs }
66
+ function seatFinding(helper, args, r, printer) {
67
+ const o = (args[1] && typeof args[1] === 'object' ? args[1] : {}) || {};
68
+ if (helper === 'bearingSeat') return pocketFinding(args, r, printer, o);
69
+ // a bore for a shaft: shaftBore's numbers, or plainBearing's and pulleyBore's solid with them on it
70
+ const shaft = helper === 'pulleyBore' ? args[0]?.bore : args[0],
71
+ diameter = helper === 'shaftBore' ? r?.diameter : r?.bore,
72
+ each = helper === 'shaftBore' ? r?.each : r?.clearance,
73
+ fit = r?.fit,
74
+ kind = r?.kind;
75
+ if (typeof diameter !== 'number' || typeof shaft !== 'number' || typeof each !== 'number') return null;
76
+ const comp = +(diameter - shaft - 2 * each).toFixed(4),
77
+ hc = printerFigure(o.printer, printer, 'hole_comp');
78
+ let on;
79
+ if (typeof fit === 'string' && Object.hasOwn(SHAFT_FITS, fit))
80
+ on = { rule: `SHAFT_FITS.${fit}`, says: `@rulecad/shapes' SHAFT_FITS.${fit}` };
81
+ else if (fit === 'run') {
82
+ const f = printerFigure(o.printer, printer, 'fit');
83
+ on = { rule: f.rule, says: `${f.rule}, the printer's fit` };
84
+ } else on = { rule: 'fit', says: 'the fit the design gave' };
85
+ const what = helper === 'shaftBore' ? 'a bore' : helper === 'pulleyBore' ? "a pulley's bore" : 'a plain bearing';
86
+ return {
87
+ level: 'info',
88
+ code: 'seat.drawn',
89
+ text:
90
+ `${what} for a ${n(shaft)} mm shaft drawn ${n(diameter)} mm (${helper}, ${fitSaid(fit)}): it rests on ` +
91
+ `${on.says} (${n(Math.abs(each))} mm ${each < 0 ? 'of press ' : ''}each side), ${trust(kind)}, plus ${hc.rule} ` +
92
+ `${n(comp)} mm across, since a printed hole comes out small`,
93
+ // (said after the count, where it came up again)
94
+ advice:
95
+ kind === 'estimate'
96
+ ? '. Press a shaft into a test print to settle it, and give the fit that works in mm each side (fit: <mm>)'
97
+ : '',
98
+ values: { diameter, shaft, each, comp },
99
+ refs: { helper, fit, rule: on.rule, kind },
100
+ };
101
+ }
102
+
103
+ /**
104
+ * @rulecad/shapes as a design gets it, with what its seat helpers drew kept as findings.
105
+ * @param {Record<string, any>} shapes the module (@rulecad/shapes)
106
+ * @param {{ printer?: { name: string, rules: Record<string, any> } | null }} [context] printer: the project's printer's
107
+ * rule set, so a fit read from it is named as its rule (x1c.press) with that rule's kind
108
+ * @returns {{ shapes: Record<string, any>, found: () => object[], used: () => boolean }} shapes: v.shapes; found: a
109
+ * 'seat.drawn' finding for each seat drawn, each said once (values.count where it came up again); used: whether the
110
+ * design drew any seat
111
+ */
112
+ export function designShapes(shapes, { printer } = {}) {
113
+ const found = new Map();
114
+ let calls = 0;
115
+ const keep = (x) => {
116
+ if (!x) return;
117
+ const k = `${x.code}|${x.text}${x.advice ?? ''}`,
118
+ had = found.get(k);
119
+ if (had) had.values = { ...had.values, count: (had.values.count ?? 1) + 1 };
120
+ else found.set(k, x);
121
+ };
122
+ const out = { ...shapes };
123
+ for (const helper of SEAT_HELPERS) {
124
+ const f = shapes[helper];
125
+ if (typeof f !== 'function') continue;
126
+ out[helper] = (...args) => {
127
+ const r = f(...args);
128
+ calls++;
129
+ keep(seatFinding(helper, args, r, printer));
130
+ return r;
131
+ };
132
+ }
133
+ return {
134
+ shapes: out,
135
+ found: () =>
136
+ [...found.values()].map(({ advice = '', ...x }) => ({
137
+ ...x,
138
+ text: `${x.text}${x.values.count ? ` (${x.values.count} drawn)` : ''}${advice}`,
139
+ })),
140
+ used: () => calls > 0,
141
+ };
142
+ }
package/lib/edit.mjs CHANGED
@@ -10,7 +10,7 @@ import { paths } from './workspace.mjs';
10
10
  import { readOwnText } from './host.mjs'; // (a file of the workspace only where it really is inside it, never through a link out)
11
11
  import { plainName, isPlainName } from './names.mjs';
12
12
  import { locate, readObject, objectSets } from './design.mjs';
13
- import { resolve, evaluate, peekRuleSet } from './rules.mjs';
13
+ import { resolve, evaluate, peekRuleSet, isName } from './rules.mjs';
14
14
  import { expandFrame, frameText } from './framegen.mjs';
15
15
  import { framesContext } from './beams.mjs';
16
16
  import { plasticNamed } from './fittings.mjs';
@@ -19,6 +19,19 @@ import { plasticNamed } from './fittings.mjs';
19
19
  export const parseValue = (s) =>
20
20
  s === undefined ? undefined : /^-?(\d+\.?\d*|\.\d+)(e-?\d+)?$/i.test(String(s).trim()) ? Number(s) : String(s);
21
21
 
22
+ /**
23
+ * A value from the command line for a variable, read by the variable's kind: a text, anchor, layout or problem variable
24
+ * keeps the text as typed (a legend 007 stays 007, never the number 7); a choice takes the option named, a number only
25
+ * where that option is one (a turn of 90); any other variable, and a new one, is read as parseValue reads it.
26
+ * @param {object | undefined} d the variable as the object's .json holds it @param {string | undefined} s @returns {any}
27
+ */
28
+ export function valueFor(d, s) {
29
+ if (s === undefined || !d || typeof d !== 'object' || !isName(d)) return parseValue(s);
30
+ const t = String(s),
31
+ named = Array.isArray(d.choice) ? d.choice.find((o) => String(o) === t) : undefined;
32
+ return named !== undefined ? named : t;
33
+ }
34
+
22
35
  // The edited text, parsed and held to its schema: refused by name, nothing written
23
36
  function checked(file, text, kind) {
24
37
  let json;
@@ -548,6 +561,7 @@ function assemblyFindings(json, { ref, file, touched = [], before = '' }) {
548
561
  values: {
549
562
  inside: known.frame.inside,
550
563
  outside: known.frame.outside,
564
+ envelope: known.frame.envelope?.size ?? null,
551
565
  beams: known.frame.beams.length,
552
566
  joins: known.frame.joins.length,
553
567
  },
@@ -1141,7 +1155,9 @@ export function setProject(project, changes, { dryRun = false } = {}) {
1141
1155
  const before = readOwnText(file);
1142
1156
  let text = before;
1143
1157
  const done = [],
1144
- fields = Object.keys(schema('project').properties).filter((k) => !['$schema', 'objects', 'name'].includes(k));
1158
+ fields = Object.keys(schema('project').properties).filter(
1159
+ (k) => !['$schema', 'objects', 'name', 'version', 'release'].includes(k),
1160
+ );
1145
1161
  for (const [address, value] of Object.entries(changes)) {
1146
1162
  const p = segmentsOf(address);
1147
1163
  if (p[0] === 'objects')
@@ -1150,6 +1166,12 @@ export function setProject(project, changes, { dryRun = false } = {}) {
1150
1166
  "a project's objects are listed by cad new <project>/<object>, as each is made",
1151
1167
  { file },
1152
1168
  );
1169
+ if (p[0] === 'version' || p[0] === 'release')
1170
+ throw new CadError(
1171
+ 'edit.address',
1172
+ `a project's ${p[0]} is written by cad release ${project}, as each release is made`,
1173
+ { file },
1174
+ );
1153
1175
  if (p[0] === 'name')
1154
1176
  throw new CadError(
1155
1177
  'edit.address',
@@ -0,0 +1,51 @@
1
+ // What a design rests on that is only an estimate, said as one warning (rules.estimate) by an object's check and an
2
+ // assembly's alike: AGENTS.md promises that a figure nobody has measured is flagged where it is used. No files are read
3
+ // here (an assembly hands in what its own rule names are, kindOf), so a seeded defect can run it as it is.
4
+
5
+ /**
6
+ * The warning that a design rests on estimates (rules.estimate), for an object's check and an assembly's alike: the
7
+ * rule-set entries that are only estimates (those the design read, and the object's own variables marked so), the
8
+ * assembly's own rule names that are (seen), and the seats v.shapes drew to an estimated fit (lib/designshapes.mjs).
9
+ * Null where nothing rests on an estimate.
10
+ * @param {{ entries?: object[], seats?: object[] | null }[]} builds each object's build (an assembly's every item's)
11
+ * @param {{ ref: string, seen?: Iterable<string>, kindOf?: (name: string) => string | undefined, assembly?: boolean }} o
12
+ * ref: the object or assembly, project/name; seen: rule names (set.rule) the assembly itself read, with kindOf to
13
+ * give each one's kind; assembly: whether ref is an assembly, which cad measured takes
14
+ * @returns {{ level: 'warn', text: string, short: string, code: 'rules.estimate', refs: { rules: string[],
15
+ * seats?: { helper: string, rule: string, fit: any }[] } } | null}
16
+ */
17
+ export function estimatesFinding(builds, { ref, seen = [], kindOf = () => undefined, assembly = false }) {
18
+ const est = new Set();
19
+ for (const b of builds)
20
+ for (const e of b?.entries ?? []) if (e.kind === 'estimate' && (e.used || !e.name.includes('.'))) est.add(e.name);
21
+ for (const n of seen) if (kindOf(n) === 'estimate') est.add(n);
22
+ const seats = new Map();
23
+ for (const b of builds)
24
+ for (const s of Array.isArray(b?.seats) ? b.seats : [])
25
+ if (s?.refs?.kind === 'estimate' && typeof s.refs.rule === 'string')
26
+ seats.set(`${s.refs.helper} ${s.refs.rule}`, { helper: s.refs.helper, rule: s.refs.rule, fit: s.refs.fit });
27
+ if (!est.size && !seats.size) return null; // (a seat drawn to an estimated fit always names that fit's rule)
28
+ // (a seat drawn to a rule-set entry, x1c.press, is named once, as that rule, even where the design passed the
29
+ // printer's figures as a copy and never read the rule itself: cad measured settles it; one drawn to a fit of
30
+ // @rulecad/shapes' own, SHAFT_FITS.press, is settled by giving the fit that works, in mm each side)
31
+ const seated = [...seats.values()],
32
+ own = seated.filter((s) => s.rule.startsWith('SHAFT_FITS.'));
33
+ for (const s of seated) if (!s.rule.startsWith('SHAFT_FITS.')) est.add(s.rule);
34
+ const rules = [...est],
35
+ named = [...rules, ...own.map((s) => `${s.helper}'s ${s.rule}`)];
36
+ const settle = assembly
37
+ ? `cad measured ${ref} <name>=<value>`
38
+ : `cad measured <project>/<assembly> <name>=<value>, from an assembly that holds ${ref}`;
39
+ return {
40
+ level: 'warn',
41
+ text:
42
+ `uses estimates, not measurements: ${named.join(', ')}` +
43
+ (rules.length ? `. Measure each and settle it with ${settle}` : '') +
44
+ (own.length
45
+ ? `. A seat drawn to an estimated fit is settled by pressing its part into a test print and giving the fit that works, in mm each side (fit: <mm>)`
46
+ : ''),
47
+ short: `Estimate: ${named.join(', ')}`,
48
+ code: 'rules.estimate',
49
+ refs: { rules, ...(seated.length ? { seats: seated } : {}) },
50
+ };
51
+ }
package/lib/fasten.mjs CHANGED
@@ -1483,8 +1483,9 @@ export function fastenOf(s, worlds, opts = {}) {
1483
1483
  const isBoard = (m) =>
1484
1484
  m.parts.some((p) => {
1485
1485
  const o = s.objects.find((q) => q.id === p.leaf);
1486
- return o?.built?.circuit || o?.bought?.part === 'board';
1487
- }); // (a circuit's holes, or a bought board's, are drilled, not printed)
1486
+ return o?.built?.circuit || o?.bought?.part === 'board' || o?.role === 'reference';
1487
+ }); // (a circuit's holes, a bought board's, or any reference's, are drilled, not printed: v.fixings draws a
1488
+ // reference's holes with no hole compensation, lib/fixings.mjs)
1488
1489
 
1489
1490
  axes.forEach((ax, i) => {
1490
1491
  const sc = { index: i, name: ax.name, found: {}, hardware: [] },
@@ -2483,7 +2484,12 @@ export function fastenOf(s, worlds, opts = {}) {
2483
2484
  values,
2484
2485
  );
2485
2486
  else {
2486
- const D2 = st.head === 'hex' ? head.across * Math.cos(Math.PI / 6) : head.across,
2487
+ // (the head bears on the flat face under it, its bearing diameter dw, where its rule set gives it:
2488
+ // seating says which it took)
2489
+ const outline = st.head === 'hex' ? head.across * Math.cos(Math.PI / 6) : head.across,
2490
+ D2 = st.bearing ?? outline,
2491
+ faceSays =
2492
+ !washer && Math.abs(D2 - outline) > 0.01 ? `, out to the head's ${mm(r3(D2))} mm bearing face,` : '',
2487
2493
  area = (d) => (Math.PI / 4) * (d * d - (2 * boreR) ** 2),
2488
2494
  bare = area(D2),
2489
2495
  onWasher = st.washer ? area(st.washer.diameter) : null,
@@ -2526,14 +2532,14 @@ export function fastenOf(s, worlds, opts = {}) {
2526
2532
  say(
2527
2533
  'fasten.seat',
2528
2534
  'pass',
2529
- `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm² takes ${mm(+takes.toFixed(0))} N. A printed bolt is done up by hand, with no torque to tighten to`,
2535
+ `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm²${faceSays} takes ${mm(+takes.toFixed(0))} N. A printed bolt is done up by hand, with no torque to tighten to`,
2530
2536
  v2,
2531
2537
  );
2532
2538
  else if (torque == null)
2533
2539
  say(
2534
2540
  'fasten.seat',
2535
2541
  'pass',
2536
- `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm² ${takesSays}${safeSays}${washerMost != null ? `; the ${fx.thread} washer would raise what it takes to ${mm(+(st.limit * onWasher).toFixed(0))} N, so it could be tightened to ${mm(washerMost)} N m` : ''}${threadSays(seatSafe)}`,
2542
+ `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm²${faceSays} ${takesSays}${safeSays}${washerMost != null ? `; the ${fx.thread} washer would raise what it takes to ${mm(+(st.limit * onWasher).toFixed(0))} N, so it could be tightened to ${mm(washerMost)} N m` : ''}${threadSays(seatSafe)}`,
2537
2543
  v2,
2538
2544
  );
2539
2545
  else {
package/lib/fe-key.mjs ADDED
@@ -0,0 +1,29 @@
1
+ // The names under which cad keeps its finite-element (FE) results in .cache: a printed clip's stress (loads.mjs
2
+ // clipStress), a bent link's (loads.mjs linkFE) and a motor mount's (motors.mjs mountFE). Each is slow to work out, so
3
+ // it is kept and used again while everything it was worked out from reads the same. The name is a hash of all of it:
4
+ // every triangle of the part (not a count and the first few, which an edit to a neck or a tip leaves as they were),
5
+ // the material (stiffness and Poisson's ratio), the loads, the cell size, and the version below.
6
+ //
7
+ // Raise a kind's version when the way its result is worked out changes (another stress read, another way of holding
8
+ // the part): results kept by the older code are then worked out again rather than read.
9
+ import crypto from 'node:crypto';
10
+
11
+ /** Each FE cache's version: raise one when its sum changes, so that results kept by the older code are not read. */
12
+ export const FE_CACHE_VERSIONS = Object.freeze({ clip: 2, link: 2, mount: 5 });
13
+
14
+ /**
15
+ * The name of a kept FE result: a hash of the kind, its version and every input given (the whole mesh among them).
16
+ * @param {keyof typeof FE_CACHE_VERSIONS} kind which result: 'clip', 'link' or 'mount'
17
+ * @param {unknown[]} inputs everything the result is worked out from, as JSON
18
+ * @param {number} [length] how many hexadecimal characters of the hash to keep
19
+ * @returns {string}
20
+ */
21
+ export function feKey(kind, inputs, length = 24) {
22
+ const version = FE_CACHE_VERSIONS[kind];
23
+ if (version == null) throw new Error(`feKey: no FE cache called "${kind}"`);
24
+ return crypto
25
+ .createHash('sha256')
26
+ .update(JSON.stringify([kind, version, ...inputs]))
27
+ .digest('hex')
28
+ .slice(0, length);
29
+ }
package/lib/fittings.mjs CHANGED
@@ -6,11 +6,15 @@
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import crypto from 'node:crypto';
9
+ import { createRequire } from 'node:module';
10
+ import { fileURLToPath, pathToFileURL } from 'node:url';
9
11
  import * as frames from '@rulecad/frames';
10
12
  const { bracketModel, bracket, plateModel, plate } = frames;
11
- import { host, readJson, cached } from './host.mjs';
13
+ import { readJson } from './host.mjs';
14
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
12
15
  import { paths, RULE_DIRS } from './workspace.mjs';
13
16
  import { named } from './parts.mjs';
17
+ import { codeOnly } from './code-text.mjs';
14
18
  import { givenFor } from './frames.mjs';
15
19
  import { peekRuleSet } from './rules.mjs';
16
20
  import { ops as booleans } from '@rulecad/shapes';
@@ -86,27 +90,28 @@ export const FITTING_KINDS = ['bracket', 'gusset', 'splice', ...Object.keys(MORE
86
90
  const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
87
91
  const strip = (e) => String(e?.message ?? e).replace(/^(bracketModel|plateModel|bracket|plate): /, '');
88
92
 
93
+ // The code of @rulecad/fea that frames' fittings are worked out with, as frames finds it, without comments or blank
94
+ // lines: frames keys its results by its own code and fea's exported functions (fittingCode), which it can read in a
95
+ // browser; on disk they are kept by all of fea's code as well, the functions it does not export among them
96
+ const feaCode = (() => {
97
+ const framesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/frames'))),
98
+ entry = createRequire(pathToFileURL(path.join(framesDir, 'package.json')).href).resolve('@rulecad/fea');
99
+ return crypto
100
+ .createHash('sha256')
101
+ .update(codeOnly(fs.readFileSync(entry, 'utf8')))
102
+ .digest('hex');
103
+ })();
104
+ const fittingFile = (key) =>
105
+ paths.cache('fitting', `${crypto.createHash('sha256').update(`${feaCode}\n${key}`).digest('hex').slice(0, 24)}.json`);
89
106
  /** The finite elements' results kept on disk, as the motor mount's are: .cache/fitting/<hash>.json (CAD_NO_CACHE skips it). */
90
107
  export const fittingCache = {
91
108
  get(key) {
92
109
  if (process.env.CAD_NO_CACHE) return undefined;
93
- const file = paths.cache('fitting', `${crypto.createHash('sha256').update(key).digest('hex').slice(0, 24)}.json`);
94
- try {
95
- return cached(file) ? JSON.parse(host.readText(file)) : undefined;
96
- } catch {
97
- return undefined;
98
- }
110
+ return readCacheJson(fittingFile(key));
99
111
  },
100
112
  set(key, v) {
101
113
  if (process.env.CAD_NO_CACHE) return;
102
- try {
103
- host.writeText(
104
- paths.cache('fitting', `${crypto.createHash('sha256').update(key).digest('hex').slice(0, 24)}.json`),
105
- JSON.stringify(v),
106
- );
107
- } catch {
108
- // (a cache that cannot be written is solved again next time)
109
- }
114
+ writeCacheFile(fittingFile(key), JSON.stringify(v)); // (one that cannot be written is solved again next time)
110
115
  },
111
116
  };
112
117
 
package/lib/fixings.mjs CHANGED
@@ -2,21 +2,27 @@
2
2
  // the workspace's own thread sets before the kit's, the project's printer, and the design's booleans (v.ops); where a
3
3
  // call names no material, the project's is taken for what a thread is in or a head sits on (a hole, engagement,
4
4
  // stripping, seating: never a screw's own steel). What each call found is kept, so cad check says what every hole
5
- // and seat was drawn to. No files are read here: the sandbox's runner uses it as the build does.
5
+ // and seat was drawn to. In an object that is not printed (a reference: a bought circuit board, drilled by its maker),
6
+ // a hole is drawn to its rule's figure as it stands, with no hole compensation. No files are read here: the sandbox's
7
+ // runner uses it as the build does.
6
8
  import { fixingsFor } from '@rulecad/fixings';
7
9
 
8
10
  // The functions whose material is the part's (the plastic a pilot is formed in, what a thread or a head bears on)
9
11
  const IN_PART = ['hole', 'holeModel', 'engagement', 'stripping', 'seating'];
12
+ // The functions that draw a hole to a figure and add the printer's hole compensation to it, which take printed: false
13
+ const HOLES = ['hole', 'holeModel'];
10
14
  const isOptions = (o) => o && typeof o === 'object' && !Array.isArray(o);
11
15
 
12
16
  /**
13
17
  * @rulecad/fixings bound to a design's project, with what its calls found.
14
- * @param {{ sets?: object, printer?: object, material?: string | null, ops?: object }} context sets: the workspace's rule
15
- * sets by name (threads, materials); printer: the printer's rule set ({ name, rules }); material: the project's; ops: v.ops
18
+ * @param {{ sets?: object, printer?: object, material?: string | null, ops?: object, printed?: boolean }} context sets:
19
+ * the workspace's rule sets by name (threads, materials); printer: the printer's rule set ({ name, rules }); material:
20
+ * the project's; ops: v.ops; printed: false for an object that is not printed (a reference), whose holes then get no
21
+ * hole compensation unless a call says printed itself
16
22
  * @returns {{ fixings: Record<string, Function>, found: () => object[], used: () => boolean }} fixings: v.fixings;
17
23
  * found: the findings of every model made, each said once (values.count where it came up again); used: whether the design called any of it
18
24
  */
19
- export function designFixings({ sets, printer, material, ops } = {}) {
25
+ export function designFixings({ sets, printer, material, ops, printed = true } = {}) {
20
26
  const bound = fixingsFor({
21
27
  ...(sets && Object.keys(sets).length ? { sets } : {}),
22
28
  ...(printer ? { printer } : {}),
@@ -47,6 +53,13 @@ export function designFixings({ sets, printer, material, ops } = {}) {
47
53
  calls++;
48
54
  if (material && IN_PART.includes(k) && (a[lead] === undefined || isOptions(a[lead])) && a[lead]?.material == null)
49
55
  a[lead] = { material, ...a[lead] };
56
+ if (
57
+ printed === false &&
58
+ HOLES.includes(k) &&
59
+ (a[lead] === undefined || isOptions(a[lead])) &&
60
+ a[lead]?.printed == null
61
+ )
62
+ a[lead] = { printed: false, ...a[lead] };
50
63
  return keep(f(...a));
51
64
  };
52
65
  }
@@ -353,7 +353,7 @@ function buildFrame(s) {
353
353
  kind: 'cut',
354
354
  text: `Cut the beams: ${c.marks.map((m) => `${m.count} × ${m.mark} at ${mm(m.length)} mm`).join(', ')} (kerf ${c.rules.kerf.value} mm, ${c.rules.trim.value} mm off each bar's first end; cut each mark against one stop)`,
355
355
  lines: c.stock.flatMap((st) => [
356
- `${st.profile}: buy ${st.buy.map((x) => `${x.count} × ${mm(x.length)} mm`).join(', ')}`,
356
+ `${st.label ?? st.profile}: buy ${st.buy.map((x) => `${x.count} × ${mm(x.length)} mm`).join(', ')}`,
357
357
  ...st.bars.map(
358
358
  (b, i) =>
359
359
  `bar ${i + 1}, ${mm(b.length)} mm: ${b.cuts.map((q) => `${q.mark} ${mm(q.length)} (${q.item})`).join(', ')}; offcut ${mm(b.offcut)}`,
package/lib/framegen.mjs CHANGED
@@ -177,13 +177,21 @@ export function frameText(m) {
177
177
  `inside ${size(m.inside)} mm, outside ${size(m.outside)} mm${m.shelves ? `; ${m.shelves} shelves, each bay ${+m.bay.toFixed(2)} mm clear` : ''}${m.lift ? `; the bottom ring stands ${+m.lift.toFixed(2)} mm up the uprights, so its joins' holes clear the feet's tapped ends` : ''}`,
178
178
  ];
179
179
  for (const l of m.lengths) lines.push(` ${l.count} x ${+l.length.toFixed(2)} mm: ${l.ids.join(', ')}`);
180
+ // the whole frame with its feet and end caps (an outside asked for is this envelope's), where it is more than the beams
181
+ const env = m.envelope;
182
+ const overall = !env
183
+ ? "overall: not known, as a castor plate's castor is bought and not drawn: add its height from its maker's drawing"
184
+ : env.size.some((v, k) => Math.abs(v - m.outside[k]) > 1e-6)
185
+ ? `overall, its feet and end caps fitted: ${size(env.size)} mm${env.from[2] < 0 ? `, standing ${+(-env.from[2]).toFixed(2)} mm below the beams on its ${m.ends.some((e) => e.role === 'foot') ? 'feet' : 'end caps'}` : ''}`
186
+ : null;
180
187
  // (a brace is a printed bracket added beside the join asked for at each corner of a braced side, or, where the join is
181
188
  // a printed bracket already, its web)
182
189
  const braced = m.braced ?? 0,
183
190
  webbed = m.join.kind === 'bracket' && m.join.fitting === 'printed',
184
191
  asked = m.joins.length - (webbed ? 0 : braced);
185
192
  lines.push(
186
- `${asked} joins (${m.join.kind})${braced ? (webbed ? `, ${braced} of them braced: their brackets drawn with a web across the inside corner` : `, ${braced} braced with printed brackets`) : ''}; ${m.ends.length} end fittings${m.ends.length ? ` (${[...new Set(m.ends.map((e) => e.fitting ?? e.bought))].join(', ')})` : ''}${m.panels.length ? `; ${m.panels.length} panels` : ''}${m.moving ? `; g rides ${m.moving.track} through ${m.moving.travel} mm on the joint gantry` : ''}`,
193
+ `${asked} joins (${m.join.kind}${m.join.estimate ? ', taken by their estimate' : ''})${braced ? (webbed ? `, ${braced} of them braced: their brackets drawn with a web across the inside corner` : `, ${braced} braced with printed brackets`) : ''}; ${m.ends.length} end fittings${m.ends.length ? ` (${[...new Set(m.ends.map((e) => e.fitting ?? e.bought))].join(', ')})` : ''}${m.panels.length ? `; ${m.panels.length} panels` : ''}${m.moving ? `; g rides ${m.moving.track} through ${m.moving.travel} mm on the joint gantry` : ''}`,
187
194
  );
195
+ if (overall) lines.push(overall);
188
196
  return lines;
189
197
  }
package/lib/frames.mjs CHANGED
@@ -14,7 +14,8 @@ let seen = null;
14
14
  /**
15
15
  * What @rulecad/frames is handed from a workspace: its own rule sets by name, and the measured outlines beside them.
16
16
  * @param {string} dir the workspace's rules/ folder
17
- * @returns {{ sets: Record<string, object>, outlines: Record<string, object>, hash: string }}
17
+ * @returns {{ sets: Record<string, object>, outlines: Record<string, object>, hash: string, files: string[] }} files: the
18
+ * paths of the files those sets and outlines were read from
18
19
  */
19
20
  export function framesContext(dir) {
20
21
  const out = path.join(dir, 'outlines');
@@ -34,7 +35,8 @@ export function framesContext(dir) {
34
35
  if (seen?.key === key) return seen.context;
35
36
  const sets = {},
36
37
  outlines = {},
37
- text = [];
38
+ text = [],
39
+ from = [];
38
40
  for (const [d, into] of [
39
41
  [dir, sets],
40
42
  [out, outlines],
@@ -63,6 +65,7 @@ export function framesContext(dir) {
63
65
  ) {
64
66
  into[s.name ?? f.slice(0, -5)] = s;
65
67
  text.push(raw);
68
+ from.push(path.join(d, f));
66
69
  }
67
70
  } catch {
68
71
  // (a broken set is cad rules check's to name)
@@ -73,6 +76,7 @@ export function framesContext(dir) {
73
76
  sets,
74
77
  outlines,
75
78
  hash: crypto.createHash('sha256').update(text.join('\n')).digest('hex').slice(0, 24),
79
+ files: from, // (the files of those sets and outlines: a release records them, lib/versions.mjs)
76
80
  };
77
81
  seen = { key, context };
78
82
  return context;
package/lib/framesize.mjs CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  joinStiffness,
21
21
  boughtStiffness,
22
22
  JOINS,
23
- outline,
23
+ blindKeyBlocked,
24
24
  footModel,
25
25
  levellingFootModel,
26
26
  stackingFootModel,
@@ -205,92 +205,19 @@ export function joinFit(x, pa, pb, given, beamOf = beamAt) {
205
205
  const a = () => 'an'; // (a metric thread's name is said em: an M5, an M3)
206
206
  const beamAt = (profile, length) => beamModel(profile, { length });
207
207
 
208
- // Where a line across a section (from p, along d) is in metal: the spans [t0, t1] along it, from the outline's loops
209
- // (as @rulecad/frames' operations find a hole's walls)
210
- function metalAlong(loops, p, d) {
211
- const ts = [];
212
- for (const loop of loops)
213
- for (let i = 0; i < loop.length; i++) {
214
- const q0 = loop[i],
215
- q1 = loop[(i + 1) % loop.length];
216
- const s0 = d[0] * (q0[1] - p[1]) - d[1] * (q0[0] - p[0]),
217
- s1 = d[0] * (q1[1] - p[1]) - d[1] * (q1[0] - p[0]);
218
- if (s0 > 0 === s1 > 0) continue;
219
- const k = s0 / (s0 - s1);
220
- ts.push((q0[0] + k * (q1[0] - q0[0]) - p[0]) * d[0] + (q0[1] + k * (q1[1] - q0[1]) - p[1]) * d[1]);
221
- }
222
- ts.sort((x, y) => x - y);
223
- const out = [];
224
- for (let i = 0; i + 1 < ts.length; i += 2) out.push([ts[i], ts[i + 1]]);
225
- return out;
226
- }
227
- const KEY_STRIPS = 16; // (lines across the key's width the section is looked along: its corners and between)
228
-
229
- /**
230
- * Whether a blind join's hex key reaches its head straight, as fasten.access looks for it: the key comes in through
231
- * the access hole drilled across b from its far face (the hole @rulecad/frames drills for the join, to its own depth)
232
- * and on through b's section to the head under the near slot's lips. The section is the same all along the beam, so
233
- * any metal across the key's width (its corners', from the hexkey set) between the head's top and the hole's end, or
234
- * in the hole wider than the hole, stands in its way: a slot floor that slants down to a narrow groove (OpenBeam's)
235
- * keeps the key off the head. Null where it reaches, else why not.
236
- * @param {object} B b's beam model @param {object} place the place on b the head sits under @param {object} sl its slot
237
- * @param {string} thread the screw's thread @param {object} fx its button-head screw's model @param {string} bName b's profile, as said
238
- * @returns {string | null}
239
- */
208
+ // Whether a blind join's hex key reaches its head straight (@rulecad/frames' blindKeyBlocked), the key's width across
209
+ // its corners from the workspace's hexkey set where it has one
240
210
  function keyBlocked(B, place, sl, thread, fx, bName) {
241
- const key = fx.head.key;
242
- if (!(key > 0)) return null;
243
- // the place across from it on the same line, as @rulecad/frames' blind join drills its access hole (on a face with
244
- // two slots, a 2040's, the one in line with the head's)
245
- const far = B.places.find(
246
- (q) =>
247
- Math.abs(q.normal[0] + place.normal[0]) < 1e-9 &&
248
- Math.abs(q.normal[1] + place.normal[1]) < 1e-9 &&
249
- Math.abs(place.normal[0] * (q.at[1] - place.at[1]) - place.normal[1] * (q.at[0] - place.at[0])) < 1e-6,
250
- );
251
- if (!far) return null; // (the join itself refuses a face with none across it)
252
- let op;
253
- try {
254
- op = beamModel(B.profile, {
255
- length: B.length,
256
- ops: [{ op: 'access', at: `${far.name}@${B.length / 2}`, thread, head: 'button', through: 'beam' }],
257
- }).ops.find((o) => o.op === 'access');
258
- } catch {
259
- return null; // (an access hole that cannot be drilled is the join's own refusal, said when it is built)
260
- }
261
- let radius = key / Math.cos(Math.PI / 6) / 2;
211
+ let corners = null;
262
212
  try {
263
213
  const set = peekRuleSet('hexkey').rules,
264
- i = set.sizes.value.findIndex((s) => Math.abs(s - key) < 1e-6);
265
- if (i >= 0) radius = set.corners.value[i] / 2;
214
+ i = set.sizes.value.findIndex((s) => Math.abs(s - fx.head.key) < 1e-6);
215
+ if (i >= 0) corners = set.corners.value[i];
266
216
  } catch {
267
- // (no hexkey set: the key's corners by its size)
217
+ // (no hexkey set: the kit's)
268
218
  }
269
- const loops = outline(B.profile).loops,
270
- d = [-place.normal[0], -place.normal[1]],
271
- side = [place.normal[1], -place.normal[0]];
272
- // depths from b's near face, inward: the head's top, and where the access hole from the far face ends
273
- const T = Math.max(...loops.flat().map((q) => (q[0] - place.at[0]) * d[0] + (q[1] - place.at[1]) * d[1])),
274
- top = sl.lip + fx.head.height,
275
- holeEnd = T - op.depth,
276
- hole = op.diameter / 2;
277
- for (let k = 0; k <= KEY_STRIPS; k++) {
278
- const s = radius * ((2 * k) / KEY_STRIPS - 1),
279
- p = [place.at[0] + side[0] * s, place.at[1] + side[1] * s];
280
- for (const [t0, t1] of metalAlong(loops, p, d)) {
281
- const undrilled = t1 > top + 1e-3 && t0 < holeEnd - 1e-3,
282
- outsideHole = Math.abs(s) > hole + 1e-9 && t1 > Math.max(top, holeEnd) + 1e-3 && t0 < T - 1e-3;
283
- if (undrilled || outsideHole)
284
- return `a ${mm1(key)} mm hex key cannot reach ${a(thread)} ${thread} button head in ${bName}'s slot: ${
285
- undrilled
286
- ? `${bName}'s section stands in its way ${mm1(Math.max(t0, top) - top)} mm over the head, past the end of the Ø${mm1(op.diameter)} mm access hole`
287
- : `the key is ${mm1(2 * radius)} mm across its corners and the access hole Ø${mm1(op.diameter)} mm`
288
- }`;
289
- }
290
- }
291
- return null;
219
+ return blindKeyBlocked(B, place, sl, thread, fx, bName, corners);
292
220
  }
293
- const mm1 = (x) => String(+Number(x).toFixed(2));
294
221
 
295
222
  // a place's face as a fitting names it: the face, or the place where the face has several (a 2040's top.1)
296
223
  const faceName = (B, q) => (B.places.filter((p) => p.face === q.face).length > 1 ? q.name : q.face);