@rulecad/cad 0.7.97 → 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 (86) hide show
  1. package/AGENTS.md +26 -10
  2. package/CHANGELOG.md +442 -2
  3. package/EXAMPLES.md +48 -42
  4. package/README.md +226 -73
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2253 -514
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1854 -437
  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 +734 -113
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +900 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2710 -502
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +792 -176
  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 +149 -18
  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 +3 -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 +1022 -212
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +41 -0
  57. package/lib/optimise.mjs +979 -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 +224 -36
  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 +38 -4
  68. package/lib/sandbox-hooks.mjs +154 -12
  69. package/lib/sandbox-preload.mjs +2 -2
  70. package/lib/sandbox-run.mjs +127 -12
  71. package/lib/sandbox.mjs +632 -35
  72. package/lib/schema.mjs +43 -11
  73. package/lib/seats.mjs +227 -49
  74. package/lib/services.mjs +261 -52
  75. package/lib/sheet.mjs +851 -178
  76. package/lib/slotnuts.mjs +213 -34
  77. package/lib/targets/gist.mjs +4 -1
  78. package/lib/targets.mjs +42 -6
  79. package/lib/task.mjs +376 -79
  80. package/lib/versions.mjs +113 -28
  81. package/lib/wires.mjs +228 -45
  82. package/lib/workspace.mjs +216 -17
  83. package/package.json +19 -19
  84. package/schemas/assembly.schema.json +2 -2
  85. package/schemas/object.schema.json +1 -1
  86. package/schemas/project.schema.json +1 -1
package/lib/list.mjs CHANGED
@@ -20,117 +20,379 @@ const n = (x, d = 1) => Number(x.toFixed(d));
20
20
 
21
21
  export function materialOf(project) {
22
22
  let name = 'pla';
23
- try { name = String(readJson(path.join(paths.project(project), 'project.json')).material || 'pla').toLowerCase().split(/\s/)[0]; } catch {}
24
- try { const set = loadRuleSet(name); return { name, density: set.rules.density.value, ...(set.rules.cost ? { cost: set.rules.cost } : {}) }; } catch { return { name, density: 1.25, assumed: true }; }
23
+ try {
24
+ name = String(readJson(path.join(paths.project(project), 'project.json')).material || 'pla')
25
+ .toLowerCase()
26
+ .split(/\s/)[0];
27
+ } catch {
28
+ // (no project.json to read: PLA)
29
+ }
30
+ try {
31
+ const set = loadRuleSet(name);
32
+ return { name, density: set.rules.density.value, ...(set.rules.cost ? { cost: set.rules.cost } : {}) };
33
+ } catch {
34
+ return { name, density: 1.25, assumed: true };
35
+ }
25
36
  }
26
37
 
27
38
  // Every printed thing in the assembly, once for each copy: its volume, grams and minutes
28
39
  export function printedParts(s) {
29
- const mat = materialOf(s.project); let flow = 12;
30
- try { flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow; } catch {}
40
+ const mat = materialOf(s.project);
41
+ let flow = 12;
42
+ try {
43
+ flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow;
44
+ } catch {
45
+ // (no x1c rule set: 12 mm³/s, a usual print flow)
46
+ }
31
47
  const by = new Map();
32
48
  for (const p of s.parts) {
33
49
  if (p.role !== 'part' && p.role != null) continue;
34
50
  // (a printed beam's part is drawn solid and printed with walls and infill: its fill is the share of plastic laid)
35
- const key = p.leaf ?? p.item, mm3 = volume(p.triangles) * (p.fill ?? 1), o = by.get(key) ?? { id: key, object: p.object ?? null, volume: 0 };
36
- o.volume += mm3; by.set(key, o);
51
+ const key = p.leaf ?? p.item,
52
+ mm3 = p.triangles.length ? volume(p.triangles) * (p.fill ?? 1) : 0, // (a part drawn empty weighs nothing)
53
+ o = by.get(key) ?? { id: key, object: p.object ?? null, volume: 0 };
54
+ o.volume += mm3;
55
+ by.set(key, o);
37
56
  }
38
57
  // and what comes with a placed part, printed beside it (a levelling foot's pad), by its model's grams
39
- for (const c of companions(s)) if (c.grams > 0) by.set(c.id, { id: c.id, object: null, volume: (c.grams / mat.density) * 1000, with: c.of });
40
- return [...by.values()].map((o) => ({ ...o, volume: n(o.volume, 0), grams: n((o.volume / 1000) * mat.density), minutes: n(o.volume / flow / 60, 0) }));
58
+ for (const c of companions(s))
59
+ if (c.grams > 0) by.set(c.id, { id: c.id, object: null, volume: (c.grams / mat.density) * 1000, with: c.of });
60
+ return [...by.values()].map((o) => ({
61
+ ...o,
62
+ volume: n(o.volume, 0),
63
+ grams: n((o.volume / 1000) * mat.density),
64
+ minutes: n(o.volume / flow / 60, 0),
65
+ }));
41
66
  }
42
67
 
43
68
  // The items printed together in place (the assembly's printInPlace) as the one print they are: one row, their grams and
44
69
  // the minutes of the whole, in the place of the first of them
45
70
  function inPlaceRow(s, printed) {
46
- const ids = Array.isArray(s.a?.printInPlace) ? s.a.printInPlace : [], members = printed.filter((p) => ids.includes(p.id));
71
+ const ids = Array.isArray(s.a?.printInPlace) ? s.a.printInPlace : [],
72
+ members = printed.filter((p) => ids.includes(p.id));
47
73
  if (members.length < 2) return printed;
48
- const mat = materialOf(s.project); let flow = 12;
49
- try { flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow; } catch {}
50
- const volume = members.reduce((t, p) => t + p.volume, 0), row = { id: members.map((p) => p.id).join(', '), object: null, volume: n(volume, 0), grams: n((volume / 1000) * mat.density), minutes: n(volume / flow / 60, 0), inPlace: members.map((p) => p.id) };
74
+ const mat = materialOf(s.project);
75
+ let flow = 12;
76
+ try {
77
+ flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow;
78
+ } catch {
79
+ // (no x1c rule set: 12 mm³/s, a usual print flow)
80
+ }
81
+ const volume = members.reduce((t, p) => t + p.volume, 0),
82
+ row = {
83
+ id: members.map((p) => p.id).join(', '),
84
+ object: null,
85
+ volume: n(volume, 0),
86
+ grams: n((volume / 1000) * mat.density),
87
+ minutes: n(volume / flow / 60, 0),
88
+ inPlace: members.map((p) => p.id),
89
+ };
51
90
  const at = printed.indexOf(members[0]);
52
91
  return [...printed.slice(0, at), row, ...printed.slice(at).filter((p) => !members.includes(p))];
53
92
  }
54
93
 
55
94
  /** The whole list. @returns {{ bought: object[], fasteners: object[], wires: object[], printed: object[], cut: object | null, totals: object }} */
56
95
  export function shoppingList(s) {
57
- const mat = materialOf(s.project), printed = inPlaceRow(s, printedParts(s)), bought = new Map(), fasteners = new Map();
58
- for (const o of s.objects) if (o.bought && !o.unplaced) {
59
- // (a beam by its profile and length: one line for each length cut, lib/beams.mjs)
60
- // (a panel by its sheet and size: lib/panels.mjs)
61
- const len = o.bought.length != null ? Number(o.bought.length.toFixed(2)) : null, size = o.bought.size ?? null, inHand = o.have === true, // ("have": in hand, not to buy; set on each copy and on a component's parts by lib/assembly.mjs)
62
- key = `${o.bought.set}|${o.bought.variant ?? ''}|${len ?? ''}|${size ?? ''}|${inHand}`;
63
- const line = bought.get(key) ?? { set: o.bought.set, variant: o.bought.variant, part: o.bought.part, ...(len != null ? { length: len } : {}), ...(size ? { size } : {}), ...(inHand ? { have: true } : {}), qty: 0, grams: o.bought.mass != null ? o.bought.mass * 1000 : null, ...(o.bought.cost ? { cost: o.bought.cost.value, currency: o.bought.cost.unit } : {}), items: [] };
64
- line.qty++; line.items.push(o.id); bought.set(key, line);
65
- }
96
+ const mat = materialOf(s.project),
97
+ printed = inPlaceRow(s, printedParts(s)),
98
+ bought = new Map(),
99
+ fasteners = new Map();
100
+ for (const o of s.objects)
101
+ if (o.bought && !o.unplaced) {
102
+ // (a beam by its profile and length: one line for each length cut, lib/beams.mjs)
103
+ // (a panel by its sheet and size: lib/panels.mjs)
104
+ const len = o.bought.length != null ? Number(o.bought.length.toFixed(2)) : null,
105
+ size = o.bought.size ?? null,
106
+ inHand = o.have === true, // ("have": in hand, not to buy; set on each copy and on a component's parts by lib/assembly.mjs)
107
+ key = `${o.bought.set}|${o.bought.variant ?? ''}|${len ?? ''}|${size ?? ''}|${inHand}`;
108
+ const line = bought.get(key) ?? {
109
+ set: o.bought.set,
110
+ variant: o.bought.variant,
111
+ part: o.bought.part,
112
+ ...(len != null ? { length: len } : {}),
113
+ ...(size ? { size } : {}),
114
+ ...(inHand ? { have: true } : {}),
115
+ qty: 0,
116
+ grams: o.bought.mass != null ? o.bought.mass * 1000 : null,
117
+ ...(o.bought.cost ? { cost: o.bought.cost.value, currency: o.bought.cost.unit } : {}),
118
+ items: [],
119
+ };
120
+ line.qty++;
121
+ line.items.push(o.id);
122
+ bought.set(key, line);
123
+ }
66
124
  // fasten.count: the hardware a fasten placed (a component's too), one part a piece; a motor's mounting screws; and a fit
67
125
  // that names its fastener by hand. Summed by name, which is the thread, length and head, or the nut's kind
68
- const add = (name, n, from, more = {}) => { const line = fasteners.get(name) ?? { fastener: name, qty: 0, from: [], ...more }; line.qty += n; if (!line.from.includes(from)) line.from.push(from); fasteners.set(name, line); };
126
+ const add = (name, n, from, more = {}) => {
127
+ const line = fasteners.get(name) ?? { fastener: name, qty: 0, from: [], ...more };
128
+ line.qty += n;
129
+ if (!line.from.includes(from)) line.from.push(from);
130
+ fasteners.set(name, line);
131
+ };
69
132
  // (a printed bolt is no bought screw: it goes with the printed parts, by its name, with its grams and minutes)
70
133
  const bolts = new Map();
71
- for (const p of s.parts) if (p.hardware?.printed) { const h = p.hardware, b = bolts.get(h.name) ?? { id: h.name, object: null, count: 0, grams: 0, bolt: true, from: [] }; b.count++; b.grams += h.grams ?? 0; if (!b.from.includes(h.from)) b.from.push(h.from); bolts.set(h.name, b); }
72
- let flow = 12; try { flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow; } catch {}
73
- for (const b of bolts.values()) { const mm3 = (b.grams / mat.density) * 1000; printed.push({ id: b.id, object: null, volume: n(mm3, 0), grams: n(b.grams), minutes: n(mm3 / flow / 60, 0), count: b.count, bolt: true, from: b.from }); }
74
- for (const p of s.parts) if (p.hardware && !p.hardware.printed) { const h = p.hardware; add(h.name, 1, h.from ?? h.name, { kind: h.kind, thread: h.thread ?? null, length: h.length ?? null, head: h.head ?? null, grams: h.grams ?? null }); }
134
+ for (const p of s.parts)
135
+ if (p.hardware?.printed) {
136
+ const h = p.hardware,
137
+ b = bolts.get(h.name) ?? { id: h.name, object: null, count: 0, grams: 0, bolt: true, from: [] };
138
+ b.count++;
139
+ b.grams += h.grams ?? 0;
140
+ if (!b.from.includes(h.from)) b.from.push(h.from);
141
+ bolts.set(h.name, b);
142
+ }
143
+ let flow = 12;
144
+ try {
145
+ flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow;
146
+ } catch {
147
+ // (no x1c rule set: 12 mm³/s, a usual print flow)
148
+ }
149
+ for (const b of bolts.values()) {
150
+ const mm3 = (b.grams / mat.density) * 1000;
151
+ printed.push({
152
+ id: b.id,
153
+ object: null,
154
+ volume: n(mm3, 0),
155
+ grams: n(b.grams),
156
+ minutes: n(mm3 / flow / 60, 0),
157
+ count: b.count,
158
+ bolt: true,
159
+ from: b.from,
160
+ });
161
+ }
162
+ for (const p of s.parts)
163
+ if (p.hardware && !p.hardware.printed) {
164
+ const h = p.hardware;
165
+ add(h.name, 1, h.from ?? h.name, {
166
+ kind: h.kind,
167
+ thread: h.thread ?? null,
168
+ length: h.length ?? null,
169
+ head: h.head ?? null,
170
+ grams: h.grams ?? null,
171
+ });
172
+ }
75
173
  for (const m of motorScrews(s, { placeItems, jointValues })) {
76
- let grams = null; try { grams = screwModel(m.thread, { length: m.length, head: m.head, anyLength: true }).mass; } catch {}
77
- add(m.name, m.count, `${m.item} on ${m.other} (its mount, a fit that fastens)`, { kind: 'screw', thread: m.thread, length: m.length, head: m.head, grams });
174
+ let grams = null;
175
+ try {
176
+ grams = screwModel(m.thread, { length: m.length, head: m.head, anyLength: true }).mass;
177
+ } catch {
178
+ // (not a screw the fixings can weigh: listed with no weight)
179
+ }
180
+ add(m.name, m.count, `${m.item} on ${m.other} (its mount, a fit that fastens)`, {
181
+ kind: 'screw',
182
+ thread: m.thread,
183
+ length: m.length,
184
+ head: m.head,
185
+ grams,
186
+ });
78
187
  }
79
188
  // what a printed fitting takes besides its screws: a hinge's pin and its nut, a catch's magnet and strike (lib/fittings.mjs)
80
189
  // (a nut carrier's nuts that a fasten placed in it are listed with that fasten, not again)
81
- const placedIn = (o, h) => (o.fitting.fitting === 'nut-carrier' ? s.parts.filter((p) => p.hardware?.kind === h.kind && p.hardware.thread === h.thread && p.moves === o.id).length : 0);
82
- for (const o of s.objects) if (o.fitting?.hardware && !o.unplaced) for (const h of o.fitting.hardware) { const n = (h.count ?? 1) - placedIn(o, h); if (n > 0) add(h.name, n, `${o.id} (${h.why ?? 'its fitting'})`, { kind: h.kind, thread: h.thread ?? null, length: h.length ?? null, head: h.head ?? null, grams: null }); }
190
+ const placedIn = (o, h) =>
191
+ o.fitting.fitting === 'nut-carrier'
192
+ ? s.parts.filter((p) => p.hardware?.kind === h.kind && p.hardware.thread === h.thread && p.moves === o.id).length
193
+ : 0;
194
+ for (const o of s.objects)
195
+ if (o.fitting?.hardware && !o.unplaced)
196
+ for (const h of o.fitting.hardware) {
197
+ const n = (h.count ?? 1) - placedIn(o, h);
198
+ if (n > 0)
199
+ add(h.name, n, `${o.id} (${h.why ?? 'its fitting'})`, {
200
+ kind: h.kind,
201
+ thread: h.thread ?? null,
202
+ length: h.length ?? null,
203
+ head: h.head ?? null,
204
+ grams: null,
205
+ });
206
+ }
83
207
  // (pins and magnets a fit names by the schema's form: by name, with their mass and whether they are bought, cut from filament or printed)
84
- for (const x of s.fits) if (x.fastener && x.fasten == null) {
85
- let more = {}; if (x.pin) try { const m = pinModel(x.fastener, { material: mat.name }); more = { kind: 'pin', made: m.made, thread: null, length: m.length, grams: m.grams }; } catch {}
86
- if (x.magnet) try { more = { kind: 'magnet', made: 'bought', thread: null, length: null, grams: magnetModel(x.fastener).grams }; } catch {}
87
- add(x.fastener, x.count != null ? x.num(x.count) : 1, x.note || `${x.a} / ${x.b}`, more);
88
- }
208
+ for (const x of s.fits)
209
+ if (x.fastener && x.fasten == null) {
210
+ let more = {};
211
+ if (x.pin)
212
+ try {
213
+ const m = pinModel(x.fastener, { material: mat.name });
214
+ more = { kind: 'pin', made: m.made, thread: null, length: m.length, grams: m.grams };
215
+ } catch {
216
+ // (not a pin the fixings know: listed as it is named)
217
+ }
218
+ if (x.magnet)
219
+ try {
220
+ more = { kind: 'magnet', made: 'bought', thread: null, length: null, grams: magnetModel(x.fastener).grams };
221
+ } catch {
222
+ // (not a magnet the fixings know: listed as it is named)
223
+ }
224
+ add(x.fastener, x.count != null ? x.num(x.count) : 1, x.note || `${x.a} / ${x.b}`, more);
225
+ }
89
226
  // Rounded up to whole packs (packs.pack), the spares said
90
- let pack = null; try { const r = loadRuleSet('packs').rules.pack; pack = { size: r.value, rule: 'packs.pack', kind: r.kind }; } catch {}
91
- const fixings = [...fasteners.values()].map((l) => ({ ...l, ...(l.grams != null ? { grams: n(l.grams, 3), mass: n(l.grams * l.qty, 2) } : {}), ...(l.kind && pack && (l.kind !== 'pin' || l.made === 'bought') ? { packs: Math.ceil(l.qty / pack.size), buy: Math.ceil(l.qty / pack.size) * pack.size, spare: Math.ceil(l.qty / pack.size) * pack.size - l.qty } : {}) }))
92
- .sort((a, b) => (a.kind ? 0 : 1) - (b.kind ? 0 : 1) || ['screw', 'nut', 'washer', 'insert', 'pin', 'magnet'].indexOf(a.kind) - ['screw', 'nut', 'washer', 'insert', 'pin', 'magnet'].indexOf(b.kind) || String(a.thread).localeCompare(String(b.thread)) || (a.length ?? 0) - (b.length ?? 0) || a.fastener.localeCompare(b.fastener));
93
- const rows = s.wires?.length ? wiresFor(s) : [], wires = new Map();
94
- for (const w of rows) { const key = w.gauge ?? 'gauge not given', l = wires.get(key) ?? { gauge: w.gauge, conductors: 0, length: 0, runs: [] }; l.length += w.length * w.conductors; l.conductors += w.conductors; l.runs.push(w.id); wires.set(key, l); }
95
- const boughtList = [...bought.values()].map((b) => ({ ...b, grams: b.grams != null ? n(b.grams) : null })).sort((a, b) => a.part.localeCompare(b.part) || a.set.localeCompare(b.set) || (b.length ?? 0) - (a.length ?? 0));
96
- const printedGrams = printed.reduce((t, p) => t + p.grams, 0), boughtGrams = boughtList.reduce((t, b) => t + (b.grams ?? 0) * b.qty, 0), unknown = boughtList.filter((b) => b.grams == null).map((b) => b.set);
227
+ let pack = null;
228
+ try {
229
+ const r = loadRuleSet('packs').rules.pack;
230
+ pack = { size: r.value, rule: 'packs.pack', kind: r.kind };
231
+ } catch {
232
+ // (no packs rule set: fixings are listed one by one)
233
+ }
234
+ const fixings = [...fasteners.values()]
235
+ .map((l) => ({
236
+ ...l,
237
+ ...(l.grams != null ? { grams: n(l.grams, 3), mass: n(l.grams * l.qty, 2) } : {}),
238
+ ...(l.kind && pack && (l.kind !== 'pin' || l.made === 'bought')
239
+ ? {
240
+ packs: Math.ceil(l.qty / pack.size),
241
+ buy: Math.ceil(l.qty / pack.size) * pack.size,
242
+ spare: Math.ceil(l.qty / pack.size) * pack.size - l.qty,
243
+ }
244
+ : {}),
245
+ }))
246
+ .sort(
247
+ (a, b) =>
248
+ (a.kind ? 0 : 1) - (b.kind ? 0 : 1) ||
249
+ ['screw', 'nut', 'washer', 'insert', 'pin', 'magnet'].indexOf(a.kind) -
250
+ ['screw', 'nut', 'washer', 'insert', 'pin', 'magnet'].indexOf(b.kind) ||
251
+ String(a.thread).localeCompare(String(b.thread)) ||
252
+ (a.length ?? 0) - (b.length ?? 0) ||
253
+ a.fastener.localeCompare(b.fastener),
254
+ );
255
+ const rows = s.wires?.length ? wiresFor(s) : [],
256
+ wires = new Map();
257
+ for (const w of rows) {
258
+ const key = w.gauge ?? 'gauge not given',
259
+ l = wires.get(key) ?? { gauge: w.gauge, conductors: 0, length: 0, runs: [] };
260
+ l.length += w.length * w.conductors;
261
+ l.conductors += w.conductors;
262
+ l.runs.push(w.id);
263
+ wires.set(key, l);
264
+ }
265
+ const boughtList = [...bought.values()]
266
+ .map((b) => ({ ...b, grams: b.grams != null ? n(b.grams) : null }))
267
+ .sort((a, b) => a.part.localeCompare(b.part) || a.set.localeCompare(b.set) || (b.length ?? 0) - (a.length ?? 0));
268
+ const printedGrams = printed.reduce((t, p) => t + p.grams, 0),
269
+ boughtGrams = boughtList.reduce((t, b) => t + (b.grams ?? 0) * b.qty, 0),
270
+ unknown = boughtList.filter((b) => b.grams == null).map((b) => b.set);
97
271
  const cut = cutListData(cutListOf(s));
98
272
  const fixingsGrams = fixings.reduce((t, f) => t + (f.mass ?? 0), 0);
99
273
  // what it costs, where prices are given: the bought items' by their sets, the printed parts' plastic by the material's
100
274
  // price a kilogram; fixings and bars are not priced, and the list says which lines have no price
101
- const priced = boughtList.filter((b) => b.cost != null && !b.have), currencies = [...new Set(priced.map((b) => b.currency))];
102
- const plastic = printedGrams > 0 ? printedCost(printedGrams, { name: mat.name, rules: mat.cost ? { cost: mat.cost } : {} }) : null;
103
- const cost = priced.length || plastic ? { bought: priced.length && currencies.length === 1 ? n(priced.reduce((t, b) => t + b.cost * b.qty, 0), 2) : null, currency: currencies.length === 1 ? currencies[0] : plastic?.unit ?? null, ...(currencies.length > 1 ? { currencies } : {}),
104
- unpriced: [...new Set(boughtList.filter((b) => b.cost == null && !b.have).map((b) => b.set))], printed: plastic ? n(plastic.value, 2) : null, ...(plastic ? { printedUnit: plastic.unit, printedRule: plastic.rule } : {}) } : null;
105
- return { bought: boughtList, fasteners: fixings, wires: [...wires.values()], printed, cut, ...(cost ? { cost } : {}), totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), fixingsGrams: n(fixingsGrams), machineGrams: n(printedGrams + boughtGrams + fixingsGrams), ...(pack && fixings.some((f) => f.packs) ? { pack } : {}), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
275
+ const priced = boughtList.filter((b) => b.cost != null && !b.have),
276
+ currencies = [...new Set(priced.map((b) => b.currency))];
277
+ const plastic =
278
+ printedGrams > 0 ? printedCost(printedGrams, { name: mat.name, rules: mat.cost ? { cost: mat.cost } : {} }) : null;
279
+ const cost =
280
+ priced.length || plastic
281
+ ? {
282
+ bought:
283
+ priced.length && currencies.length === 1
284
+ ? n(
285
+ priced.reduce((t, b) => t + b.cost * b.qty, 0),
286
+ 2,
287
+ )
288
+ : null,
289
+ currency: currencies.length === 1 ? currencies[0] : (plastic?.unit ?? null),
290
+ ...(currencies.length > 1 ? { currencies } : {}),
291
+ unpriced: [...new Set(boughtList.filter((b) => b.cost == null && !b.have).map((b) => b.set))],
292
+ printed: plastic ? n(plastic.value, 2) : null,
293
+ ...(plastic ? { printedUnit: plastic.unit, printedRule: plastic.rule } : {}),
294
+ }
295
+ : null;
296
+ return {
297
+ bought: boughtList,
298
+ fasteners: fixings,
299
+ wires: [...wires.values()],
300
+ printed,
301
+ cut,
302
+ ...(cost ? { cost } : {}),
303
+ totals: {
304
+ printedGrams: n(printedGrams),
305
+ boughtGrams: n(boughtGrams),
306
+ fixingsGrams: n(fixingsGrams),
307
+ machineGrams: n(printedGrams + boughtGrams + fixingsGrams),
308
+ ...(pack && fixings.some((f) => f.packs) ? { pack } : {}),
309
+ minutes: n(
310
+ printed.reduce((t, p) => t + p.minutes, 0),
311
+ 0,
312
+ ),
313
+ material: mat.name,
314
+ ...(mat.assumed ? { densityAssumed: true } : {}),
315
+ ...(unknown.length ? { noMassFor: unknown } : {}),
316
+ },
317
+ };
106
318
  }
107
319
 
108
320
  export function listText(ref, l) {
109
321
  const out = [`${ref}: what it takes to build`];
110
322
  const row = (a) => out.push(a.join(' '));
111
323
  // (with parts in hand, those to buy come first, then what is in hand: neither is left off the list)
112
- const boughtRow = (b) => row([` ${String(b.qty).padStart(3)} ×`, `${b.set}${b.variant ? ` (${b.variant})` : ''}${b.length != null ? ` x ${b.length} mm` : ''}${b.size ? ` cut ${b.size[0]} x ${b.size[1]} mm` : ''}`, `a ${b.part}`, b.grams != null ? `${b.grams} g each` : 'mass not given', ...(b.cost != null ? [`${b.cost} ${b.currency} each`] : []), b.items.join(', ')]);
113
- const toBuy = l.bought.filter((b) => !b.have), inHand = l.bought.filter((b) => b.have);
114
- if (l.bought.length && !inHand.length) { out.push('', 'Bought'); toBuy.forEach(boughtRow); }
115
- else if (l.bought.length) {
116
- out.push('', toBuy.length ? 'Bought, to buy' : 'Bought: nothing to buy, all in hand'); toBuy.forEach(boughtRow);
117
- out.push('', 'Bought, in hand (marked "have" in the assembly)'); inHand.forEach(boughtRow);
118
- }
119
- if (l.cut) { out.push('', `Cut list (kerf ${l.cut.rules.kerf.value} mm, trim ${l.cut.rules.trim.value} mm; a sheet for each mark: cad beams ${ref})`, ...cutListText(l.cut)); }
324
+ const boughtRow = (b) =>
325
+ row([
326
+ ` ${String(b.qty).padStart(3)} ×`,
327
+ `${b.set}${b.variant ? ` (${b.variant})` : ''}${b.length != null ? ` x ${b.length} mm` : ''}${b.size ? ` cut ${b.size[0]} x ${b.size[1]} mm` : ''}`,
328
+ `a ${b.part}`,
329
+ b.grams != null ? `${b.grams} g each` : 'mass not given',
330
+ ...(b.cost != null ? [`${b.cost} ${b.currency} each`] : []),
331
+ b.items.join(', '),
332
+ ]);
333
+ const toBuy = l.bought.filter((b) => !b.have),
334
+ inHand = l.bought.filter((b) => b.have);
335
+ if (l.bought.length && !inHand.length) {
336
+ out.push('', 'Bought');
337
+ toBuy.forEach(boughtRow);
338
+ } else if (l.bought.length) {
339
+ out.push('', toBuy.length ? 'Bought, to buy' : 'Bought: nothing to buy, all in hand');
340
+ toBuy.forEach(boughtRow);
341
+ out.push('', 'Bought, in hand (marked "have" in the assembly)');
342
+ inHand.forEach(boughtRow);
343
+ }
344
+ if (l.cut) {
345
+ out.push(
346
+ '',
347
+ `Cut list (kerf ${l.cut.rules.kerf.value} mm, trim ${l.cut.rules.trim.value} mm; a sheet for each mark: cad beams ${ref})`,
348
+ ...cutListText(l.cut),
349
+ );
350
+ }
120
351
  if (l.fasteners.length) {
121
352
  out.push('', 'Fasteners');
122
- for (const f of l.fasteners) row([` ${String(f.qty).padStart(3)} ×`, f.fastener, ...(f.mass != null ? [`${f.grams} g each, ${f.mass} g`] : []), ...(f.packs ? [`${f.packs} pack${f.packs > 1 ? 's' : ''} of ${l.totals.pack.size}, ${f.spare} spare`] : []), f.from.join('; ')]);
123
- if (l.totals.pack) out.push(` (packs of ${l.totals.pack.size}: ${l.totals.pack.rule}, ${/^[aeiou]/.test(l.totals.pack.kind) ? 'an' : 'a'} ${l.totals.pack.kind}; masses are estimates from each piece's outline)`);
353
+ for (const f of l.fasteners)
354
+ row([
355
+ ` ${String(f.qty).padStart(3)} ×`,
356
+ f.fastener,
357
+ ...(f.mass != null ? [`${f.grams} g each, ${f.mass} g`] : []),
358
+ ...(f.packs ? [`${f.packs} pack${f.packs > 1 ? 's' : ''} of ${l.totals.pack.size}, ${f.spare} spare`] : []),
359
+ f.from.join('; '),
360
+ ]);
361
+ if (l.totals.pack)
362
+ out.push(
363
+ ` (packs of ${l.totals.pack.size}: ${l.totals.pack.rule}, ${/^[aeiou]/.test(l.totals.pack.kind) ? 'an' : 'a'} ${l.totals.pack.kind}; masses are estimates from each piece's outline)`,
364
+ );
365
+ }
366
+ if (l.wires.length) {
367
+ out.push('', 'Wire');
368
+ for (const w of l.wires) row([` ${w.length} mm of`, w.gauge ?? 'gauge not given', `in ${w.runs.join(', ')}`]);
369
+ }
370
+ if (l.printed.length) {
371
+ out.push('', `Printed (${l.totals.material})`);
372
+ for (const p of l.printed)
373
+ row([
374
+ ` ${String(p.grams).padStart(7)} g`,
375
+ `about ${p.minutes} min`,
376
+ `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}${p.inPlace ? ' (printed together in place: one print)' : ''}${p.with ? ` (comes with ${p.with}: printed beside it, screwed into it by hand)` : ''}${p.bolt ? ` (${p.count} printed bolt${p.count > 1 ? 's' : ''}, standing on ${p.count > 1 ? 'their heads' : 'its head'}: ${p.from.join('; ')})` : ''}`,
377
+ ]);
124
378
  }
125
- if (l.wires.length) { out.push('', 'Wire'); for (const w of l.wires) row([` ${w.length} mm of`, w.gauge ?? 'gauge not given', `in ${w.runs.join(', ')}`]); }
126
- if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}${p.inPlace ? ' (printed together in place: one print)' : ''}${p.with ? ` (comes with ${p.with}: printed beside it, screwed into it by hand)` : ''}${p.bolt ? ` (${p.count} printed bolt${p.count > 1 ? 's' : ''}, standing on ${p.count > 1 ? 'their heads' : 'its head'}: ${p.from.join('; ')})` : ''}`]); }
127
- out.push('', `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.fixingsGrams ? `${l.totals.fixingsGrams} g of fixings, ` : ''}${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
379
+ out.push(
380
+ '',
381
+ `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.fixingsGrams ? `${l.totals.fixingsGrams} g of fixings, ` : ''}${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`,
382
+ );
128
383
  if (l.cost) {
129
- const c = l.cost, parts = [];
130
- if (c.bought != null) parts.push(`${c.bought} ${c.currency} bought${c.unpriced.length ? ` (no price given for ${c.unpriced.join(', ')})` : ''}`);
384
+ const c = l.cost,
385
+ parts = [];
386
+ if (c.bought != null)
387
+ parts.push(
388
+ `${c.bought} ${c.currency} bought${c.unpriced.length ? ` (no price given for ${c.unpriced.join(', ')})` : ''}`,
389
+ );
131
390
  else if (c.currencies) parts.push(`bought items priced in ${c.currencies.join(' and ')}, not added together`);
132
- if (c.printed != null) parts.push(`${c.printed} ${c.printedUnit} of ${l.totals.material} printed (the plastic alone)`);
133
- out.push(`Cost: ${parts.join(', ')}; fixings and bars are not priced. Prices are each set's, on the date it was checked`);
391
+ if (c.printed != null)
392
+ parts.push(`${c.printed} ${c.printedUnit} of ${l.totals.material} printed (the plastic alone)`);
393
+ out.push(
394
+ `Cost: ${parts.join(', ')}; fixings and bars are not priced. Prices are each set's, on the date it was checked`,
395
+ );
134
396
  }
135
397
  return out.join('\n');
136
398
  }
@@ -0,0 +1,68 @@
1
+ // Who may use a live view (live.mjs, the optimiser's; live-shape.mjs, a flexure being shaped). Both are small web
2
+ // servers on this computer, and any web page open in the browser can send requests to them. Two checks keep those pages
3
+ // out:
4
+ // - The Host the request names must be this computer: 127.0.0.1, localhost or [::1], the address the server was told
5
+ // to listen on, any other written-out address (192.168.1.5, 100.101.102.103, [fd7a::1]), or a name the person asked
6
+ // for (allowHosts). A page on someone's site can point its own name at 127.0.0.1 (DNS rebinding) and then read the
7
+ // view as if it were its own; its requests still carry its own name as the Host, and are refused. A written-out
8
+ // address can't be pointed anywhere, so accepting every one is as safe as accepting this computer's own, and it lets
9
+ // in a phone on Tailscale: in Tailscale's userspace mode the machine has no 100.x address of its own, and tailscaled
10
+ // passes the phone's requests to 127.0.0.1 with the Host the phone used.
11
+ // - A POST (the stop button) that says which page sent it (Origin) must come from the view's own page: the Origin must
12
+ // be http:// and the Host. A page on any other site that posts here names its own site, and is refused.
13
+ // - No other page may show the view inside itself (a frame): a page that frames it, nearly invisible, under a button of
14
+ // its own gets the person's click on the view's stop button, which then comes from the view's own page. Every answer
15
+ // says it may not be framed.
16
+ // The port is not checked: the name is what a page can't fake, and a view reached through a forwarded port (ssh -L
17
+ // 9000:localhost:8090) arrives with another port in its Host.
18
+ import net from 'node:net';
19
+
20
+ const LOCAL = ['127.0.0.1', 'localhost', '::1'];
21
+
22
+ /**
23
+ * The name in a Host header, without its port or an IPv6 address's brackets, in lower case ('' if there is none).
24
+ * @param {string | undefined} host
25
+ * @returns {string}
26
+ */
27
+ export function hostName(host) {
28
+ const h = String(host ?? '')
29
+ .trim()
30
+ .toLowerCase();
31
+ if (h.startsWith('[')) return h.slice(1, h.indexOf(']') < 0 ? undefined : h.indexOf(']'));
32
+ const name = h.split(':').length === 2 ? h.slice(0, h.lastIndexOf(':')) : h;
33
+ return name.endsWith('.') ? name.slice(0, -1) : name;
34
+ }
35
+
36
+ /**
37
+ * Makes the check a live view's server runs on each request. It answers a refused request itself (421 for a Host
38
+ * that isn't this computer's, 403 for another page's POST) and says whether to go on. Every answer refuses to be shown
39
+ * in another page's frame.
40
+ * @param {{ host?: string, allowHosts?: string[] }} [o] host: the address the server listens on; allowHosts: more
41
+ * names to accept, such as a Tailscale MagicDNS name (my-laptop)
42
+ * @returns {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => boolean} true when
43
+ * the request may go on
44
+ */
45
+ export function liveGuard({ host, allowHosts = [] } = {}) {
46
+ const names = new Set([...LOCAL, ...[host, ...allowHosts].filter(Boolean).map(hostName)]);
47
+ const accepted = (name) => names.has(name) || net.isIP(name) !== 0;
48
+ return (req, res) => {
49
+ res.setHeader('content-security-policy', "frame-ancestors 'none'");
50
+ res.setHeader('x-frame-options', 'DENY');
51
+ const given = req.headers.host;
52
+ if (!given || !accepted(hostName(given))) {
53
+ res.writeHead(421, { 'content-type': 'text/plain; charset=utf-8' });
54
+ res.end(
55
+ `This live view answers only to this computer's own names and addresses, not "${given ?? ''}". ` +
56
+ 'To open it by another name (a Tailscale name, say), give that name with --allow-host.\n',
57
+ );
58
+ return false;
59
+ }
60
+ const origin = req.headers.origin;
61
+ if (req.method === 'POST' && origin !== undefined && origin.toLowerCase() !== `http://${given.toLowerCase()}`) {
62
+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' });
63
+ res.end('Only the live view itself can stop the run: this request came from another page.\n');
64
+ return false;
65
+ }
66
+ return true;
67
+ };
68
+ }