@rulecad/cad 0.8.0 → 0.9.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 (83) hide show
  1. package/AGENTS.md +24 -10
  2. package/CHANGELOG.md +404 -0
  3. package/EXAMPLES.md +40 -38
  4. package/README.md +193 -67
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2250 -512
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1847 -434
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +649 -121
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +899 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2702 -507
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +790 -175
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +123 -21
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +2 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1021 -213
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +3 -1
  57. package/lib/optimise.mjs +978 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +223 -35
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +15 -5
  68. package/lib/sandbox-hooks.mjs +77 -19
  69. package/lib/sandbox-run.mjs +117 -18
  70. package/lib/sandbox.mjs +509 -60
  71. package/lib/schema.mjs +42 -11
  72. package/lib/seats.mjs +227 -49
  73. package/lib/services.mjs +261 -52
  74. package/lib/sheet.mjs +851 -178
  75. package/lib/slotnuts.mjs +213 -34
  76. package/lib/targets/gist.mjs +4 -1
  77. package/lib/targets.mjs +22 -4
  78. package/lib/task.mjs +376 -79
  79. package/lib/versions.mjs +111 -28
  80. package/lib/wires.mjs +228 -45
  81. package/lib/workspace.mjs +197 -12
  82. package/package.json +19 -19
  83. package/schemas/assembly.schema.json +2 -2
package/lib/kit.mjs CHANGED
@@ -24,24 +24,60 @@ import { companions } from './fittings.mjs';
24
24
 
25
25
  const mm = (x) => String(+Number(x).toFixed(2));
26
26
  const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
27
- const cell = (x) => String(x ?? '').replace(/\|/g, '\\|').replace(/\n/g, ' ');
27
+ const cell = (x) =>
28
+ String(x ?? '')
29
+ .replace(/\|/g, '\\|')
30
+ .replace(/\n/g, ' ');
28
31
  // The upright beams (placed by their ends, running up z) and the corner each stands at, seen from above: left and right
29
32
  // by x, front and back by y (the front the side of least y), where the uprights stand in two rows that way
30
33
  function uprightPlan(s, marks) {
31
- const isVec = (v) => Array.isArray(v) && v.length === 3 && v.every((x) => typeof x === 'number' && Number.isFinite(x));
32
- const ups = (s.items ?? []).filter((it) => it.beam && isVec(it.from) && isVec(it.to) && Math.abs(it.from[0] - it.to[0]) < 1e-6 && Math.abs(it.from[1] - it.to[1]) < 1e-6 && Math.abs(it.to[2] - it.from[2]) > 1e-6);
34
+ const isVec = (v) =>
35
+ Array.isArray(v) && v.length === 3 && v.every((x) => typeof x === 'number' && Number.isFinite(x));
36
+ const ups = (s.items ?? []).filter(
37
+ (it) =>
38
+ it.beam &&
39
+ isVec(it.from) &&
40
+ isVec(it.to) &&
41
+ Math.abs(it.from[0] - it.to[0]) < 1e-6 &&
42
+ Math.abs(it.from[1] - it.to[1]) < 1e-6 &&
43
+ Math.abs(it.to[2] - it.from[2]) > 1e-6,
44
+ );
33
45
  if (ups.length < 2) return null;
34
- const xs = [...new Set(ups.map((u) => +u.from[0].toFixed(3)))].sort((a, b) => a - b), ys = [...new Set(ups.map((u) => +u.from[1].toFixed(3)))].sort((a, b) => a - b);
46
+ const xs = [...new Set(ups.map((u) => +u.from[0].toFixed(3)))].sort((a, b) => a - b),
47
+ ys = [...new Set(ups.map((u) => +u.from[1].toFixed(3)))].sort((a, b) => a - b);
35
48
  const side = (v, list, lo, hi) => (list.length === 2 ? (Math.abs(v - list[0]) < 1e-3 ? lo : hi) : null);
36
49
  const rows = ups.map((u) => {
37
- const fb = side(u.from[1], ys, 'front', 'back'), lr = side(u.from[0], xs, 'left', 'right');
38
- return [u.id, [fb, lr].filter(Boolean).join(' ') || 'see x, y', `${mm(u.from[0])}, ${mm(u.from[1])}`, marks.find((m) => m.items.includes(u.id))?.mark ?? ''];
50
+ const fb = side(u.from[1], ys, 'front', 'back'),
51
+ lr = side(u.from[0], xs, 'left', 'right');
52
+ return [
53
+ u.id,
54
+ [fb, lr].filter(Boolean).join(' ') || 'see x, y',
55
+ `${mm(u.from[0])}, ${mm(u.from[1])}`,
56
+ marks.find((m) => m.items.includes(u.id))?.mark ?? '',
57
+ ];
39
58
  });
40
59
  const down = ups.every((u) => u.from[2] < u.to[2]) ? ' Each upright stands with its end a down.' : '';
41
- return { rows, said: `Seen from above, x to the right and y away from you: the front is the side nearest you (least y), the left the side of least x.${down}` };
60
+ return {
61
+ rows,
62
+ said: `Seen from above, x to the right and y away from you: the front is the side nearest you (least y), the left the side of least x.${down}`,
63
+ };
42
64
  }
43
- const table = (heads, rows) => [`| ${heads.join(' | ')} |`, `|${heads.map(() => '---').join('|')}|`, ...rows.map((r) => `| ${r.map(cell).join(' | ')} |`)];
44
- const csv = (rows) => rows.map((r) => r.map((x) => { const t = String(x ?? ''); return /[",\n]/.test(t) ? `"${t.replace(/"/g, '""')}"` : t; }).join(',')).join('\n');
65
+ const table = (heads, rows) => [
66
+ `| ${heads.join(' | ')} |`,
67
+ `|${heads.map(() => '---').join('|')}|`,
68
+ ...rows.map((r) => `| ${r.map(cell).join(' | ')} |`),
69
+ ];
70
+ const csv = (rows) =>
71
+ rows
72
+ .map((r) =>
73
+ r
74
+ .map((x) => {
75
+ const t = String(x ?? '');
76
+ return /[",\n]/.test(t) ? `"${t.replace(/"/g, '""')}"` : t;
77
+ })
78
+ .join(','),
79
+ )
80
+ .join('\n');
45
81
 
46
82
  /** The kit's folder for an assembly: exports/<project>/<assembly>-kit. @param {object} s a built assembly */
47
83
  export const kitDir = (s) => paths.exports(s.project, `${s.name}-kit`);
@@ -50,9 +86,20 @@ export const kitDir = (s) => paths.exports(s.project, `${s.name}-kit`);
50
86
  // cad export writes a plate)
51
87
  async function plate3mf(ref, file) {
52
88
  const { filaments, slots } = await import('./links.mjs');
53
- const s = await buildAssembly(ref), fil = filaments(s.project), things = new Map();
54
- for (const p of s.parts.filter((q) => q.role !== 'reference')) { if (!things.has(p.leaf)) things.set(p.leaf, []); things.get(p.leaf).push({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) }); }
55
- fs.writeFileSync(file, await threemf([...things].map(([name, parts]) => ({ name, parts })), { filaments: slots(fil) }));
89
+ const s = await buildAssembly(ref),
90
+ fil = filaments(s.project),
91
+ things = new Map();
92
+ for (const p of s.parts.filter((q) => q.role !== 'reference')) {
93
+ if (!things.has(p.leaf)) things.set(p.leaf, []);
94
+ things.get(p.leaf).push({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) });
95
+ }
96
+ fs.writeFileSync(
97
+ file,
98
+ await threemf(
99
+ [...things].map(([name, parts]) => ({ name, parts })),
100
+ { filaments: slots(fil) },
101
+ ),
102
+ );
56
103
  }
57
104
 
58
105
  /**
@@ -63,64 +110,199 @@ async function plate3mf(ref, file) {
63
110
  * @returns {Promise<{ dir: string, files: string[], plates: object[], jigs: object | null, sheets: object[], steps: number, findings: object[] }>}
64
111
  */
65
112
  export async function writeKit(s, findings, { pictures = false, preview = null } = {}) {
66
- const ref = `${s.project}/${s.name}`, fails = findings.filter((f) => f.level === 'fail');
67
- if (fails.length) throw new CadError('kit.check', `${ref}: cad check fails ${plural(fails.length, 'check')} (${fails.slice(0, 3).map((f) => f.text).join('; ')}${fails.length > 3 ? '; ..' : ''}), and a kit is written only for a design that checks with nothing failing: cad check ${ref}`);
68
- const dir = kitDir(s), files = [], rel = (f) => path.relative(dir, f).split(path.sep).join('/'), put = (f, text) => { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, text); files.push(rel(f)); };
113
+ const ref = `${s.project}/${s.name}`,
114
+ fails = findings.filter((f) => f.level === 'fail');
115
+ if (fails.length)
116
+ throw new CadError(
117
+ 'kit.check',
118
+ `${ref}: cad check fails ${plural(fails.length, 'check')} (${fails
119
+ .slice(0, 3)
120
+ .map((f) => f.text)
121
+ .join(
122
+ '; ',
123
+ )}${fails.length > 3 ? '; ..' : ''}), and a kit is written only for a design that checks with nothing failing: cad check ${ref}`,
124
+ );
125
+ const dir = kitDir(s),
126
+ files = [],
127
+ rel = (f) => path.relative(dir, f).split(path.sep).join('/'),
128
+ put = (f, text) => {
129
+ fs.mkdirSync(path.dirname(f), { recursive: true });
130
+ fs.writeFileSync(f, text);
131
+ files.push(rel(f));
132
+ };
69
133
  fs.rmSync(dir, { recursive: true, force: true }); // (the kit is written whole each time: nothing stale is left in it)
70
134
  fs.mkdirSync(dir, { recursive: true });
71
135
 
72
136
  // What to print: the plates (cad plates' own, each written as its 3MF) and the beams' jigs
73
137
  let pl = null;
74
- try { pl = await platesOf(s, { write: true }); } catch (e) { if (e.code !== 'plates.empty') throw e; }
138
+ try {
139
+ pl = await platesOf(s, { write: true });
140
+ } catch (e) {
141
+ if (e.code !== 'plates.empty') throw e;
142
+ }
75
143
  const plates = [];
76
144
  for (const p of pl?.plates ?? []) {
77
- const file = path.join(dir, 'print', `${p.name}.3mf`); fs.mkdirSync(path.dirname(file), { recursive: true });
78
- await plate3mf(`${s.project}/${p.name}`, file); files.push(rel(file));
79
- const bad = (await checkPlate(`${s.project}/${p.name}`)).filter((f) => (f.level === 'fail' || f.level === 'warn') && f.code !== 'rules.estimate');
145
+ const file = path.join(dir, 'print', `${p.name}.3mf`);
146
+ fs.mkdirSync(path.dirname(file), { recursive: true });
147
+ await plate3mf(`${s.project}/${p.name}`, file);
148
+ files.push(rel(file));
149
+ const bad = (await checkPlate(`${s.project}/${p.name}`)).filter(
150
+ (f) => (f.level === 'fail' || f.level === 'warn') && f.code !== 'rules.estimate',
151
+ );
80
152
  plates.push({ ...p, file: rel(file), issues: bad.map((f) => `${f.level}: ${f.text}`) });
81
153
  }
82
- const cut = cutListOf(s), jigs = cut ? await writeJigs(s) : null;
83
- if (jigs) for (const p of jigs.plates) { const file = path.join(dir, 'print', path.basename(p.file)); fs.copyFileSync(p.file, file); files.push(rel(file)); p.kit = rel(file); }
154
+ const cut = cutListOf(s),
155
+ jigs = cut ? await writeJigs(s) : null;
156
+ if (jigs)
157
+ for (const p of jigs.plates) {
158
+ const file = path.join(dir, 'print', path.basename(p.file));
159
+ fs.copyFileSync(p.file, file);
160
+ files.push(rel(file));
161
+ p.kit = rel(file);
162
+ }
84
163
  // The sheets: each mark's, as cad beams writes them
85
- const sheets = cut ? writeBeamSheets(s).map((x) => { const file = path.join(dir, 'sheets', `beam-${x.mark}.svg`); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.copyFileSync(x.file, file); files.push(rel(file)); return { ...x, kit: rel(file), was: x.file }; }) : [];
164
+ const sheets = cut
165
+ ? writeBeamSheets(s).map((x) => {
166
+ const file = path.join(dir, 'sheets', `beam-${x.mark}.svg`);
167
+ fs.mkdirSync(path.dirname(file), { recursive: true });
168
+ fs.copyFileSync(x.file, file);
169
+ files.push(rel(file));
170
+ return { ...x, kit: rel(file), was: x.file };
171
+ })
172
+ : [];
86
173
  // What to buy, and how it goes together
87
- const list = shoppingList(s), frame = s.joins?.length ? frameBuild(s) : null, order = !frame && isBuilt(s) ? withPreload(s, orderOf(s)) : null;
88
- if (!cut && !plates.length && !list.bought.length && !list.fasteners.length) throw new CadError('kit.empty', `${ref} has nothing to build a kit from: no beams, nothing printed and nothing bought`);
174
+ const list = shoppingList(s),
175
+ frame = s.joins?.length ? frameBuild(s) : null,
176
+ order = !frame && isBuilt(s) ? withPreload(s, orderOf(s)) : null;
177
+ if (!cut && !plates.length && !list.bought.length && !list.fasteners.length)
178
+ throw new CadError(
179
+ 'kit.empty',
180
+ `${ref} has nothing to build a kit from: no beams, nothing printed and nothing bought`,
181
+ );
89
182
  if (frame?.stuck || order?.stuck) throw new CadError('kit.order', `${ref}: ${(frame ?? order).stuck.text}`);
90
183
  // a sheet named in a step by its file in exports/ is named by its file in the kit
91
- const local = (t) => sheets.reduce((x, sh) => x.split(path.relative(WS, sh.was)).join(sh.kit).split(path.relative(WS, sh.was).split(path.sep).join('/')).join(sh.kit), t);
184
+ const local = (t) =>
185
+ sheets.reduce(
186
+ (x, sh) =>
187
+ x
188
+ .split(path.relative(WS, sh.was))
189
+ .join(sh.kit)
190
+ .split(path.relative(WS, sh.was).split(path.sep).join('/'))
191
+ .join(sh.kit),
192
+ t,
193
+ );
92
194
 
93
195
  // Pictures: the whole, and each step that shows something
94
196
  const pics = new Map();
95
197
  if (pictures) {
96
- if (!preview) throw new CadError('kit.pictures', 'cad kit --pictures draws with lib/preview.mjs, and was given none');
198
+ if (!preview)
199
+ throw new CadError('kit.pictures', 'cad kit --pictures draws with lib/preview.mjs, and was given none');
97
200
  const whole = path.join(dir, 'pictures', `${s.name}.png`);
98
- await preview(s.parts.map((p) => ({ name: p.name, label: p.label, role: p.role, item: p.item, triangles: p.triangles })), { title: s.a.title || s.name, meta: 'as built', out: whole }); files.push(rel(whole));
99
- if (frame) for (const { n, parts } of frameStepPictures(s, frame)) { const st = frame.steps[n - 1], out = path.join(dir, 'pictures', `step-${String(n).padStart(2, '0')}.png`); await preview(parts, { title: `${s.a.title || s.name}: step ${n} of ${frame.steps.length}`, meta: st.text, out }); files.push(rel(out)); pics.set(n, rel(out)); }
201
+ await preview(
202
+ s.parts.map((p) => ({ name: p.name, label: p.label, role: p.role, item: p.item, triangles: p.triangles })),
203
+ { title: s.a.title || s.name, meta: 'as built', out: whole },
204
+ );
205
+ files.push(rel(whole));
206
+ if (frame)
207
+ for (const { n, parts } of frameStepPictures(s, frame)) {
208
+ const st = frame.steps[n - 1],
209
+ out = path.join(dir, 'pictures', `step-${String(n).padStart(2, '0')}.png`);
210
+ await preview(parts, {
211
+ title: `${s.a.title || s.name}: step ${n} of ${frame.steps.length}`,
212
+ meta: st.text,
213
+ out,
214
+ });
215
+ files.push(rel(out));
216
+ pics.set(n, rel(out));
217
+ }
100
218
  }
101
219
 
102
220
  // buy.csv: one row a line to buy
103
221
  const rows = [['kind', 'quantity', 'what', 'buy', 'for']];
104
- for (const st of list.cut?.stock ?? []) for (const b of st.buy) rows.push(['bar', b.count, `${st.profile} x ${mm(b.length)} mm`, `${b.count} x ${mm(b.length)} mm`, `the cut list's marks ${[...new Set(st.bars.flatMap((x) => x.cuts.map((c) => c.mark)))].join(', ')}`]);
105
- for (const b of list.bought.filter((x) => x.part !== 'beam')) rows.push([b.have ? 'in hand' : 'bought', b.qty, `${b.set}${b.variant ? ` (${b.variant})` : ''}${b.size ? ` cut ${b.size[0]} x ${b.size[1]} mm` : ''}`, b.have ? 'none: in hand' : b.cost != null ? `${b.cost} ${b.currency} each` : '', b.items.join(' ')]);
106
- for (const f of list.fasteners) rows.push([f.kind ?? 'fixing', f.qty, f.fastener, f.packs ? `${f.packs} pack${f.packs > 1 ? 's' : ''} of ${list.totals.pack.size}` : '', f.from.join('; ')]);
222
+ for (const st of list.cut?.stock ?? [])
223
+ for (const b of st.buy)
224
+ rows.push([
225
+ 'bar',
226
+ b.count,
227
+ `${st.profile} x ${mm(b.length)} mm`,
228
+ `${b.count} x ${mm(b.length)} mm`,
229
+ `the cut list's marks ${[...new Set(st.bars.flatMap((x) => x.cuts.map((c) => c.mark)))].join(', ')}`,
230
+ ]);
231
+ for (const b of list.bought.filter((x) => x.part !== 'beam'))
232
+ rows.push([
233
+ b.have ? 'in hand' : 'bought',
234
+ b.qty,
235
+ `${b.set}${b.variant ? ` (${b.variant})` : ''}${b.size ? ` cut ${b.size[0]} x ${b.size[1]} mm` : ''}`,
236
+ b.have ? 'none: in hand' : b.cost != null ? `${b.cost} ${b.currency} each` : '',
237
+ b.items.join(' '),
238
+ ]);
239
+ for (const f of list.fasteners)
240
+ rows.push([
241
+ f.kind ?? 'fixing',
242
+ f.qty,
243
+ f.fastener,
244
+ f.packs ? `${f.packs} pack${f.packs > 1 ? 's' : ''} of ${list.totals.pack.size}` : '',
245
+ f.from.join('; '),
246
+ ]);
107
247
  put(path.join(dir, 'buy.csv'), `${csv(rows)}\n`);
108
248
 
109
249
  // README.md: the build page
110
- const title = s.a.title || s.name, out = [`# ${title}: the kit`, '', `Everything needed to build ${title}, made from the assembly \`${ref}\` by \`cad kit\`. The design checks with nothing failing; this folder is enough to buy, print, cut, drill and put it together without opening the model.`, ''];
111
- out.push('## In this folder', '', ...table(['File', 'What it is'], [
112
- ['README.md', 'This page: what the checks say, what to buy, what to print, the cut list, the drilling and tapping, and the build step by step'],
113
- ['buy.csv', 'The shopping list as a table: bars, bought parts, screws, nuts and inserts, each with how many to buy'],
114
- ...plates.map((p) => [p.file, `A plate to print in ${p.material.toUpperCase()}: ${plural(p.parts.length, 'part')}, ${mm(p.grams)} g, about ${p.minutes} min. Open it in the slicer as it is`]),
115
- ...(jigs?.plates ?? []).map((p) => [p.kit, `Jigs for cutting, drilling, tapping and squaring the beams, in ${String(p.material).toUpperCase()}: ${plural(p.parts.length, 'part')}`]),
116
- ...sheets.map((x) => [x.kit, `Mark ${x.mark}'s cut-and-drill sheet (${x.items.join(', ')}), to scale: print it at 100%`]),
117
- ...(pictures ? [[`pictures/${s.name}.png`, 'The whole, as built, from six sides'], ...[...pics].map(([n, f]) => [f, `Step ${n}, what is on the bench then`])] : []),
118
- ]), '');
250
+ const title = s.a.title || s.name,
251
+ out = [
252
+ `# ${title}: the kit`,
253
+ '',
254
+ `Everything needed to build ${title}, made from the assembly \`${ref}\` by \`cad kit\`. The design checks with nothing failing; this folder is enough to buy, print, cut, drill and put it together without opening the model.`,
255
+ '',
256
+ ];
257
+ out.push(
258
+ '## In this folder',
259
+ '',
260
+ ...table(
261
+ ['File', 'What it is'],
262
+ [
263
+ [
264
+ 'README.md',
265
+ 'This page: what the checks say, what to buy, what to print, the cut list, the drilling and tapping, and the build step by step',
266
+ ],
267
+ [
268
+ 'buy.csv',
269
+ 'The shopping list as a table: bars, bought parts, screws, nuts and inserts, each with how many to buy',
270
+ ],
271
+ ...plates.map((p) => [
272
+ p.file,
273
+ `A plate to print in ${p.material.toUpperCase()}: ${plural(p.parts.length, 'part')}, ${mm(p.grams)} g, about ${p.minutes} min. Open it in the slicer as it is`,
274
+ ]),
275
+ ...(jigs?.plates ?? []).map((p) => [
276
+ p.kit,
277
+ `Jigs for cutting, drilling, tapping and squaring the beams, in ${String(p.material).toUpperCase()}: ${plural(p.parts.length, 'part')}`,
278
+ ]),
279
+ ...sheets.map((x) => [
280
+ x.kit,
281
+ `Mark ${x.mark}'s cut-and-drill sheet (${x.items.join(', ')}), to scale: print it at 100%`,
282
+ ]),
283
+ ...(pictures
284
+ ? [
285
+ [`pictures/${s.name}.png`, 'The whole, as built, from six sides'],
286
+ ...[...pics].map(([n, f]) => [f, `Step ${n}, what is on the bench then`]),
287
+ ]
288
+ : []),
289
+ ],
290
+ ),
291
+ '',
292
+ );
119
293
 
120
294
  // what the checks say: the warnings, and what the frame's own checks found, each with what it rests on
121
- const warns = findings.filter((f) => f.level === 'warn'), passes = findings.filter((f) => f.level === 'pass').length;
122
- const said = findings.filter((f) => /^frame\.(deflection|stress|buckling|rack|frequency|square)$/.test(f.code ?? '') || f.code === 'mass.parts');
123
- out.push('## What the checks say', '', `\`cad check ${ref}\`: ${plural(passes, 'check')} pass, none fail${warns.length ? `, ${plural(warns.length, 'warning')}` : ', none warn'}.`, '');
295
+ const warns = findings.filter((f) => f.level === 'warn'),
296
+ passes = findings.filter((f) => f.level === 'pass').length;
297
+ const said = findings.filter(
298
+ (f) => /^frame\.(deflection|stress|buckling|rack|frequency|square)$/.test(f.code ?? '') || f.code === 'mass.parts',
299
+ );
300
+ out.push(
301
+ '## What the checks say',
302
+ '',
303
+ `\`cad check ${ref}\`: ${plural(passes, 'check')} pass, none fail${warns.length ? `, ${plural(warns.length, 'warning')}` : ', none warn'}.`,
304
+ '',
305
+ );
124
306
  for (const f of warns) out.push(`- Warning: ${f.text}`);
125
307
  for (const f of said) out.push(`- ${f.text}`);
126
308
  out.push('');
@@ -128,27 +310,128 @@ export async function writeKit(s, findings, { pictures = false, preview = null }
128
310
  // what to buy
129
311
  out.push('## What to buy', '');
130
312
  if (list.cut) {
131
- out.push('### Bars', '', `Cut to the cut list below. Each cut takes the saw's ${mm(list.cut.rules.kerf.value)} mm kerf, and ${mm(list.cut.rules.trim.value)} mm is trimmed off each bar's first end.`, '');
132
- out.push(...table(['Profile', 'Buy', 'Left over, mm'], list.cut.stock.map((st) => [st.profile, st.buy.map((b) => `${b.count} x ${mm(b.length)} mm`).join(', '), mm(st.offcut ?? 0)])), '');
313
+ out.push(
314
+ '### Bars',
315
+ '',
316
+ `Cut to the cut list below. Each cut takes the saw's ${mm(list.cut.rules.kerf.value)} mm kerf, and ${mm(list.cut.rules.trim.value)} mm is trimmed off each bar's first end.`,
317
+ '',
318
+ );
319
+ out.push(
320
+ ...table(
321
+ ['Profile', 'Buy', 'Left over, mm'],
322
+ list.cut.stock.map((st) => [
323
+ st.profile,
324
+ st.buy.map((b) => `${b.count} x ${mm(b.length)} mm`).join(', '),
325
+ mm(st.offcut ?? 0),
326
+ ]),
327
+ ),
328
+ '',
329
+ );
133
330
  }
134
- const bought = list.bought.filter((b) => b.part !== 'beam' && !b.have), inHand = list.bought.filter((b) => b.part !== 'beam' && b.have);
135
- if (bought.length) out.push('### Bought parts', '', ...table(['Qty', 'Part', 'What', 'Price each', 'Where it goes'], bought.map((b) => [b.qty, `${b.set}${b.variant ? ` (${b.variant})` : ''}${b.size ? `, cut ${b.size[0]} x ${b.size[1]} mm` : ''}`, b.part, b.cost != null ? `${b.cost} ${b.currency}` : 'not given', b.items.join(', ')])), '');
136
- if (inHand.length) out.push('### In hand', '', 'Marked `"have"` in the assembly: nothing to buy for these.', '', ...table(['Qty', 'Part', 'What', 'Where it goes'], inHand.map((b) => [b.qty, `${b.set}${b.variant ? ` (${b.variant})` : ''}`, b.part, b.items.join(', ')])), '');
137
- if (list.fasteners.length) out.push('### Screws, nuts and inserts', '', ...table(['Qty', 'Fixing', 'Buy', 'Where it goes'], list.fasteners.map((f) => [f.qty, f.fastener, f.packs ? `${plural(f.packs, 'pack')} of ${list.totals.pack.size}, ${f.spare} spare` : '', f.from.join('; ')])), '');
138
- if (list.totals.pack) out.push(`Packs of ${list.totals.pack.size} are ${list.totals.pack.kind === 'estimate' ? 'an estimate' : `${list.totals.pack.kind}`} (${list.totals.pack.rule}).`, '');
331
+ const bought = list.bought.filter((b) => b.part !== 'beam' && !b.have),
332
+ inHand = list.bought.filter((b) => b.part !== 'beam' && b.have);
333
+ if (bought.length)
334
+ out.push(
335
+ '### Bought parts',
336
+ '',
337
+ ...table(
338
+ ['Qty', 'Part', 'What', 'Price each', 'Where it goes'],
339
+ bought.map((b) => [
340
+ b.qty,
341
+ `${b.set}${b.variant ? ` (${b.variant})` : ''}${b.size ? `, cut ${b.size[0]} x ${b.size[1]} mm` : ''}`,
342
+ b.part,
343
+ b.cost != null ? `${b.cost} ${b.currency}` : 'not given',
344
+ b.items.join(', '),
345
+ ]),
346
+ ),
347
+ '',
348
+ );
349
+ if (inHand.length)
350
+ out.push(
351
+ '### In hand',
352
+ '',
353
+ 'Marked `"have"` in the assembly: nothing to buy for these.',
354
+ '',
355
+ ...table(
356
+ ['Qty', 'Part', 'What', 'Where it goes'],
357
+ inHand.map((b) => [b.qty, `${b.set}${b.variant ? ` (${b.variant})` : ''}`, b.part, b.items.join(', ')]),
358
+ ),
359
+ '',
360
+ );
361
+ if (list.fasteners.length)
362
+ out.push(
363
+ '### Screws, nuts and inserts',
364
+ '',
365
+ ...table(
366
+ ['Qty', 'Fixing', 'Buy', 'Where it goes'],
367
+ list.fasteners.map((f) => [
368
+ f.qty,
369
+ f.fastener,
370
+ f.packs ? `${plural(f.packs, 'pack')} of ${list.totals.pack.size}, ${f.spare} spare` : '',
371
+ f.from.join('; '),
372
+ ]),
373
+ ),
374
+ '',
375
+ );
376
+ if (list.totals.pack)
377
+ out.push(
378
+ `Packs of ${list.totals.pack.size} are ${list.totals.pack.kind === 'estimate' ? 'an estimate' : `${list.totals.pack.kind}`} (${list.totals.pack.rule}).`,
379
+ '',
380
+ );
139
381
 
140
382
  // what to print
141
383
  if (plates.length || jigs?.jigs.length) {
142
384
  out.push('## What to print', '');
143
385
  if (plates.length) {
144
- out.push(...table(['Plate', 'Material', 'Parts', 'Grams', 'Minutes', 'Prints'], plates.map((p) => [p.file, p.material.toUpperCase(), p.parts.map((x) => x.id).join(', '), mm(p.grams), p.minutes, p.issues.length ? p.issues.join('; ') : 'clean'])), '');
386
+ out.push(
387
+ ...table(
388
+ ['Plate', 'Material', 'Parts', 'Grams', 'Minutes', 'Prints'],
389
+ plates.map((p) => [
390
+ p.file,
391
+ p.material.toUpperCase(),
392
+ p.parts.map((x) => x.id).join(', '),
393
+ mm(p.grams),
394
+ p.minutes,
395
+ p.issues.length ? p.issues.join('; ') : 'clean',
396
+ ]),
397
+ ),
398
+ '',
399
+ );
145
400
  const companions = list.printed.filter((x) => x.with);
146
- if (companions.length) out.push(`${companions.map((x) => x.id).join(', ')} ${companions.length === 1 ? 'is' : 'are'} printed beside the part ${companions.length === 1 ? 'it goes' : 'they go'} with (${[...new Set(companions.map((x) => x.with))].join(', ')}) and screwed in by hand once that is on.`, '');
147
- out.push(`About ${mm(list.totals.printedGrams)} g of ${list.totals.material.toUpperCase()} and ${list.totals.minutes} min of printing (an estimate from each part's volume and the printer's flow).`, '');
401
+ if (companions.length)
402
+ out.push(
403
+ `${companions.map((x) => x.id).join(', ')} ${companions.length === 1 ? 'is' : 'are'} printed beside the part ${companions.length === 1 ? 'it goes' : 'they go'} with (${[...new Set(companions.map((x) => x.with))].join(', ')}) and screwed in by hand once that is on.`,
404
+ '',
405
+ );
406
+ out.push(
407
+ `About ${mm(list.totals.printedGrams)} g of ${list.totals.material.toUpperCase()} and ${list.totals.minutes} min of printing (an estimate from each part's volume and the printer's flow).`,
408
+ '',
409
+ );
148
410
  }
149
411
  if (jigs?.jigs.length) {
150
- out.push('### Jigs', '', 'Printed tools for making the beams, each marked with the marks it is for. Print them first.', '');
151
- out.push(...table(['Jig', 'Mark', 'For', 'Grams', 'Margin at its load'], jigs.jigs.map((x) => [x.name, x.mark, x.kind === 'length-stop' ? `cutting ${x.for.map((w) => `mark ${w.mark}`).join(', ')} to length against one stop` : x.kind === 'square-corner' ? x.for.map((w) => w.text).join('; ') : x.for.map((w) => `${w.label ?? w.mark} (${w.items.join(', ')}): ${w.line}`).join('; '), mm(x.grams), `${mm(x.margin)} x`])), '');
412
+ out.push(
413
+ '### Jigs',
414
+ '',
415
+ 'Printed tools for making the beams, each marked with the marks it is for. Print them first.',
416
+ '',
417
+ );
418
+ out.push(
419
+ ...table(
420
+ ['Jig', 'Mark', 'For', 'Grams', 'Margin at its load'],
421
+ jigs.jigs.map((x) => [
422
+ x.name,
423
+ x.mark,
424
+ x.kind === 'length-stop'
425
+ ? `cutting ${x.for.map((w) => `mark ${w.mark}`).join(', ')} to length against one stop`
426
+ : x.kind === 'square-corner'
427
+ ? x.for.map((w) => w.text).join('; ')
428
+ : x.for.map((w) => `${w.label ?? w.mark} (${w.items.join(', ')}): ${w.line}`).join('; '),
429
+ mm(x.grams),
430
+ `${mm(x.margin)} x`,
431
+ ]),
432
+ ),
433
+ '',
434
+ );
152
435
  for (const f of jigs.findings) out.push(`- ${f.level === 'warn' ? 'Warning: ' : ''}${f.text}`);
153
436
  if (jigs.findings.length) out.push('');
154
437
  }
@@ -157,35 +440,122 @@ export async function writeKit(s, findings, { pictures = false, preview = null }
157
440
  // the cut list and the drilling
158
441
  if (list.cut) {
159
442
  out.push('## Cut', '', 'Beams that are the same share a mark. Write the item on each beam as it is cut.', '');
160
- out.push(...table(['Mark', 'Qty', 'Profile', 'Length, mm', 'Items'], list.cut.marks.map((m) => [m.mark, m.count, m.profile, mm(m.length), m.items.join(', ')])), '');
161
- for (const st of list.cut.stock) { out.push(`${st.profile}, the cuts on each bar in order:`, ''); st.bars.forEach((b, i) => out.push(`${i + 1}. A ${mm(b.length)} mm bar: ${b.cuts.map((c) => `${c.mark} ${mm(c.length)} (${c.item})`).join(', ')}; ${mm(b.offcut)} mm left`)); out.push(''); }
162
- out.push('## Drill and tap', '', 'Each mark\'s work, every hole dimensioned from end a on its sheet.', '');
163
- out.push(...table(['Mark', 'Work', 'Sheet'], list.cut.marks.map((m) => [m.mark, m.ops.length ? m.ops.join('; ') : 'cut square, nothing else', sheets.find((x) => x.mark === m.mark)?.kit ?? ''])), '');
443
+ out.push(
444
+ ...table(
445
+ ['Mark', 'Qty', 'Profile', 'Length, mm', 'Items'],
446
+ list.cut.marks.map((m) => [m.mark, m.count, m.profile, mm(m.length), m.items.join(', ')]),
447
+ ),
448
+ '',
449
+ );
450
+ for (const st of list.cut.stock) {
451
+ out.push(`${st.profile}, the cuts on each bar in order:`, '');
452
+ st.bars.forEach((b, i) =>
453
+ out.push(
454
+ `${i + 1}. A ${mm(b.length)} mm bar: ${b.cuts.map((c) => `${c.mark} ${mm(c.length)} (${c.item})`).join(', ')}; ${mm(b.offcut)} mm left`,
455
+ ),
456
+ );
457
+ out.push('');
458
+ }
459
+ out.push('## Drill and tap', '', "Each mark's work, every hole dimensioned from end a on its sheet.", '');
460
+ out.push(
461
+ ...table(
462
+ ['Mark', 'Work', 'Sheet'],
463
+ list.cut.marks.map((m) => [
464
+ m.mark,
465
+ m.ops.length ? m.ops.join('; ') : 'cut square, nothing else',
466
+ sheets.find((x) => x.mark === m.mark)?.kit ?? '',
467
+ ]),
468
+ ),
469
+ '',
470
+ );
164
471
  }
165
472
 
166
473
  // where each upright stands: a plan of the frame's corners, so the build is followed without the pictures
167
474
  const plan = uprightPlan(s, list.cut?.marks ?? []);
168
- if (frame && plan) out.push('## Where the uprights stand', '', plan.said, '', ...table(['Upright', 'Corner', 'x, y (mm, its centre line)', 'Mark'], plan.rows), '');
475
+ if (frame && plan)
476
+ out.push(
477
+ '## Where the uprights stand',
478
+ '',
479
+ plan.said,
480
+ '',
481
+ ...table(['Upright', 'Corner', 'x, y (mm, its centre line)', 'Mark'], plan.rows),
482
+ '',
483
+ );
169
484
 
170
485
  // the build
171
486
  const pads = companions(s);
172
487
  if (frame) {
173
- out.push('## Build', '', 'From bars to a square frame, then the rest mounted on it. Snug joins are tightened to their torque once their bay is square.', '');
488
+ out.push(
489
+ '## Build',
490
+ '',
491
+ 'From bars to a square frame, then the rest mounted on it. Snug joins are tightened to their torque once their bay is square.',
492
+ '',
493
+ );
174
494
  for (const st of frame.steps) {
175
495
  out.push(`${st.n}. ${local(st.text)}`);
176
496
  for (const l of st.lines ?? []) out.push(` - ${local(l)}`);
177
- for (const c of pads.filter((x) => st.items?.includes(x.of))) out.push(` - Then screw ${c.id} (printed beside it) into ${c.of} by hand, as far as levels the frame`);
497
+ for (const c of pads.filter((x) => st.items?.includes(x.of)))
498
+ out.push(` - Then screw ${c.id} (printed beside it) into ${c.of} by hand, as far as levels the frame`);
178
499
  if (pics.has(st.n)) out.push('', ` ![Step ${st.n}](${pics.get(st.n)})`, '');
179
500
  }
180
501
  out.push('');
181
- for (const x of frame.notFlat ?? []) out.push(`The bay of ${x.name} is built on the frame, not flat: ${x.why}.`, '');
182
- if (frame.torques.length) out.push('### Tightening, by kind of join', '', ...table(['Join', 'Joins', 'Screws', 'Key', 'N m', 'Why'], frame.torques.map((t) => [t.kind, t.joins, t.fasteners.join(', '), t.key, mm(t.torque), t.why])), '');
183
- if (frame.bays.length) out.push('### Diagonals', '', 'Measure both diagonals of each bay, inside corner to inside corner. Where they differ by more than the last column, push the corners of the long diagonal together, tighten and measure again.', '', ...table(['Bay', 'Opening, mm', 'Each diagonal, mm', 'Accept a difference up to, mm'], frame.bays.map((b) => [b.name, `${mm(b.width)} x ${mm(b.height)}`, mm(b.square.diagonal), mm(b.square.accept)])), '');
502
+ for (const x of frame.notFlat ?? [])
503
+ out.push(`The bay of ${x.name} is built on the frame, not flat: ${x.why}.`, '');
504
+ if (frame.torques.length)
505
+ out.push(
506
+ '### Tightening, by kind of join',
507
+ '',
508
+ ...table(
509
+ ['Join', 'Joins', 'Screws', 'Key', 'N m', 'Why'],
510
+ frame.torques.map((t) => [t.kind, t.joins, t.fasteners.join(', '), t.key, mm(t.torque), t.why]),
511
+ ),
512
+ '',
513
+ );
514
+ if (frame.bays.length)
515
+ out.push(
516
+ '### Diagonals',
517
+ '',
518
+ 'Measure both diagonals of each bay, inside corner to inside corner. Where they differ by more than the last column, push the corners of the long diagonal together, tighten and measure again.',
519
+ '',
520
+ ...table(
521
+ ['Bay', 'Opening, mm', 'Each diagonal, mm', 'Accept a difference up to, mm'],
522
+ frame.bays.map((b) => [
523
+ b.name,
524
+ `${mm(b.width)} x ${mm(b.height)}`,
525
+ mm(b.square.diagonal),
526
+ mm(b.square.accept),
527
+ ]),
528
+ ),
529
+ '',
530
+ );
184
531
  } else if (order) {
185
532
  out.push('## Build', '');
186
- for (const st of order.steps) { out.push(`${st.n}. ${st.text}`); for (const l of st.load ?? []) out.push(` - First, ${l}`); }
533
+ for (const st of order.steps) {
534
+ out.push(`${st.n}. ${st.text}`);
535
+ for (const l of st.load ?? []) out.push(` - First, ${l}`);
536
+ }
187
537
  out.push('');
188
538
  }
189
- put(path.join(dir, 'README.md'), `${out.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd()}\n`);
190
- return { dir, files: files.sort(), plates, jigs: jigs ? { count: jigs.jigs.length, plates: jigs.plates.map((p) => ({ file: p.kit, material: p.material, parts: p.parts.length })), findings: jigs.findings } : null, sheets: sheets.map((x) => ({ mark: x.mark, file: x.kit, items: x.items })), steps: frame?.steps.length ?? order?.steps.length ?? 0, findings: warns };
539
+ put(
540
+ path.join(dir, 'README.md'),
541
+ `${out
542
+ .join('\n')
543
+ .replace(/\n{3,}/g, '\n\n')
544
+ .trimEnd()}\n`,
545
+ );
546
+ return {
547
+ dir,
548
+ files: files.sort(),
549
+ plates,
550
+ jigs: jigs
551
+ ? {
552
+ count: jigs.jigs.length,
553
+ plates: jigs.plates.map((p) => ({ file: p.kit, material: p.material, parts: p.parts.length })),
554
+ findings: jigs.findings,
555
+ }
556
+ : null,
557
+ sheets: sheets.map((x) => ({ mark: x.mark, file: x.kit, items: x.items })),
558
+ steps: frame?.steps.length ?? order?.steps.length ?? 0,
559
+ findings: warns,
560
+ };
191
561
  }
package/lib/layout.mjs CHANGED
@@ -4,7 +4,8 @@ import { host, readJson } from './host.mjs';
4
4
  import { WS, paths } from './workspace.mjs';
5
5
  import { plainName } from './names.mjs';
6
6
 
7
- export const layoutPath = (project, name, dir) => path.join(dir || path.join(paths.project(project), 'layouts'), `${plainName(name, 'layout name')}.json`); // (a name from a design's file: never ../)
7
+ export const layoutPath = (project, name, dir) =>
8
+ path.join(dir || path.join(paths.project(project), 'layouts'), `${plainName(name, 'layout name')}.json`); // (a name from a design's file: never ../)
8
9
  export const hasLayout = (project, name, dir) => host.exists(layoutPath(project, name, dir));
9
10
  export function readLayout(project, name, dir) {
10
11
  const f = layoutPath(project, name, dir);