@rulecad/cad 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/AGENTS.md +29 -10
  2. package/CHANGELOG.md +604 -0
  3. package/EXAMPLES.md +122 -105
  4. package/README.md +292 -63
  5. package/bin/cad.mjs +500 -87
  6. package/lib/assembly.mjs +486 -134
  7. package/lib/bays.mjs +124 -0
  8. package/lib/cache-file.mjs +148 -0
  9. package/lib/clone.mjs +93 -11
  10. package/lib/code-text.mjs +28 -0
  11. package/lib/design-imports.mjs +127 -0
  12. package/lib/design.mjs +291 -59
  13. package/lib/designshapes.mjs +142 -0
  14. package/lib/edit.mjs +29 -5
  15. package/lib/estimates.mjs +51 -0
  16. package/lib/fasten.mjs +11 -5
  17. package/lib/fe-key.mjs +29 -0
  18. package/lib/fittings.mjs +20 -15
  19. package/lib/fixings.mjs +17 -4
  20. package/lib/framebuild.mjs +73 -92
  21. package/lib/framecheck.mjs +154 -77
  22. package/lib/framegen.mjs +9 -1
  23. package/lib/frames.mjs +6 -2
  24. package/lib/framesize.mjs +45 -82
  25. package/lib/gait.mjs +17 -7
  26. package/lib/guides.mjs +84 -50
  27. package/lib/host.mjs +7 -3
  28. package/lib/kit.mjs +5 -5
  29. package/lib/list.mjs +29 -21
  30. package/lib/live-guard.mjs +18 -8
  31. package/lib/loads.mjs +35 -23
  32. package/lib/measured.mjs +740 -99
  33. package/lib/mesh.mjs +156 -56
  34. package/lib/motors.mjs +26 -33
  35. package/lib/names.mjs +15 -0
  36. package/lib/node-version.mjs +52 -0
  37. package/lib/optimise.mjs +34 -25
  38. package/lib/order.mjs +5 -12
  39. package/lib/parts.mjs +3 -0
  40. package/lib/picture-servers.mjs +66 -0
  41. package/lib/power.mjs +14 -7
  42. package/lib/preview.mjs +12 -25
  43. package/lib/programs.mjs +113 -0
  44. package/lib/rules.mjs +2 -1
  45. package/lib/sandbox-guard.mjs +43 -0
  46. package/lib/sandbox-hooks.mjs +109 -15
  47. package/lib/sandbox-lock.mjs +225 -0
  48. package/lib/sandbox-preload.mjs +2 -2
  49. package/lib/sandbox-run.mjs +22 -24
  50. package/lib/sandbox.mjs +345 -42
  51. package/lib/sheet.mjs +114 -3
  52. package/lib/targets/gist.mjs +9 -6
  53. package/lib/versions.mjs +294 -35
  54. package/lib/workspace.mjs +6 -3
  55. package/package.json +14 -14
  56. package/schemas/assembly.schema.json +6 -5
  57. package/schemas/object.schema.json +1 -1
  58. package/schemas/project.schema.json +6 -0
  59. package/templates/coupons/MEASURE.md +109 -0
  60. package/templates/coupons/assemblies/fixings-test.json +20 -0
  61. package/templates/coupons/assemblies/slot-test.json +11 -0
  62. package/templates/coupons/objects/fixings-coupon.js +88 -0
  63. package/templates/coupons/objects/fixings-coupon.json +26 -0
  64. package/templates/coupons/objects/holds-coupon.js +130 -0
  65. package/templates/coupons/objects/holds-coupon.json +42 -0
  66. package/templates/coupons/objects/slot-coupon.js +89 -0
  67. package/templates/coupons/objects/slot-coupon.json +29 -0
  68. package/templates/coupons/project.json +10 -0
package/lib/design.mjs CHANGED
@@ -22,6 +22,7 @@ import { host, readJson, cached } from './host.mjs';
22
22
  import { named, faces, fromFaces, polygons, unpack, watch } from './parts.mjs';
23
23
  import { sandboxed, canSandbox, stageFile, ROUTE_KEY, designLimits } from './sandbox.mjs';
24
24
  import { roomFor, STAGES_HELD, ROUTES_HELD } from './kept.mjs';
25
+ import { ownCacheFile, writeCacheFile, readCacheJson } from './cache-file.mjs';
25
26
  import { Worker } from 'node:worker_threads';
26
27
  export { polygons };
27
28
  import fs from 'node:fs';
@@ -30,18 +31,19 @@ import { pathToFileURL, fileURLToPath } from 'node:url';
30
31
  import { createRequire } from 'node:module';
31
32
  import crypto from 'node:crypto';
32
33
  import { resolve, loadRuleSet } from './rules.mjs';
33
- import { WS, paths, printerOf, RULE_DIRS, readOwnText, noLinksOut } from './workspace.mjs';
34
+ import { WS, config, paths, printerOf, RULE_DIRS, readOwnText, noLinksOut } from './workspace.mjs';
34
35
  import { readLayout, hasLayout, keys, width, depth } from './layout.mjs';
35
36
  import { optimised, forDesign, ownResults } from './optimise.mjs';
36
37
  import * as shapes from '@rulecad/shapes';
38
+ import { designShapes } from './designshapes.mjs';
37
39
  import * as flexures from '@rulecad/flexures';
38
40
  import * as gears from '@rulecad/gears';
39
41
  import * as motors from '@rulecad/motors';
40
42
  import { designFrames, framesContext } from './frames.mjs';
41
43
  import { resolve as resolveWith } from '@rulecad/variables';
42
- import { engineId, packageVersion, materialise } from './versions.mjs';
44
+ import { engineId, packageVersion, materialise, files as filesOf, inRelease } from './versions.mjs';
43
45
  import { satisfies } from '@rulecad/versions';
44
- import { plainName, isObjectRefName } from './names.mjs';
46
+ import { plainName, isObjectRefName, isWorkspacePath } from './names.mjs';
45
47
 
46
48
  const require = createRequire(import.meta.url);
47
49
  const jscad = require('@jscad/modeling');
@@ -93,11 +95,12 @@ const building = new Set();
93
95
  export async function objectSets(d, object, { trusted = false } = {}) {
94
96
  const refs = (object.uses || []).filter(isObjectRef),
95
97
  sets = {},
96
- extra = {};
98
+ extra = {},
99
+ files = []; // the files of the objects it reads as they are now (not a release of theirs): their own and what they read
97
100
  // Its rule sets (the entries without a slash) become paths, rules/<name>.json: plain names only, said with the file they're in
98
101
  for (const u of object.uses || [])
99
102
  if (!isObjectRef(u)) plainName(u, 'rule set name', `${path.relative(WS, d.json)}, in its "uses"`);
100
- if (!refs.length) return { sets, extra };
103
+ if (!refs.length) return { sets, extra, files };
101
104
  const self = `${d.project}/${d.name}`;
102
105
  building.add(self);
103
106
  try {
@@ -113,9 +116,11 @@ export async function objectSets(d, object, { trusted = false } = {}) {
113
116
  throw new Error(
114
117
  `${self} and ${ref} read each other's numbers: one of them has to give its numbers to the other, not both`,
115
118
  );
116
- const base = locateIn(...ref.split('/')),
119
+ // (read by a release: as that release has it, from its tag, where it isn't pinned to a release of its own)
120
+ const base = d.tree && !exact ? inRelease(d, ...ref.split('/')) : locateIn(...ref.split('/')),
117
121
  b = await build(exact ? materialise(base, want) : base, {}, { trusted }),
118
122
  version = b.object.version;
123
+ if (!exact) files.push(...filesOf(base, b.object, b));
119
124
  if (want && !exact && !satisfies(version, want))
120
125
  throw new Error(
121
126
  `${self} uses ${ref} ${want}, but ${ref} is ${version}: change the range, or the design to suit ${version}`,
@@ -146,7 +151,7 @@ export async function objectSets(d, object, { trusted = false } = {}) {
146
151
  } finally {
147
152
  building.delete(self);
148
153
  }
149
- return { sets, extra };
154
+ return { sets, extra, files: [...new Set(files)].sort() };
150
155
  }
151
156
 
152
157
  // The layouts an object can pick, by name, from its layout variables' choices (built-ins like grid have no file)
@@ -201,7 +206,8 @@ export function variantSet(d, object, set = {}) {
201
206
  }
202
207
 
203
208
  const CACHE = paths.cache('builds'),
204
- CACHE_VERSION = 3;
209
+ CACHE_VERSION = 6; // (4: a kept build lists the files its design imported, and holds only while they read the same;
210
+ // 5: and says whether the design used v.frames, which a release records; 6: and holds what v.shapes' seats were drawn to)
205
211
  // The autorouter's results too, by its exact input (@rulecad/pcb reads RULECAD_ROUTE_CACHE): a board rebuilt for anything
206
212
  // but its routing (a change to the library, its finish, its checks) reuses its route instead of searching again
207
213
  if (!process.env.CAD_NO_CACHE) process.env.RULECAD_ROUTE_CACHE ||= paths.cache('routes');
@@ -250,32 +256,89 @@ const own = crypto
250
256
  // name, its inputs and the library's code, which anyone can work out, so a design that came with a cloned workspace
251
257
  // could otherwise hand back a false result under the key another design (the user's own) reads, and pass a mechanism
252
258
  // that would fail.
259
+ // A stage's salt is everything a lamina's stages run besides their inputs: flexures' code and the code it calls
260
+ // (@rulecad/fea, @rulecad/fixings and @rulecad/gears, and @rulecad/shapes, which fixings calls), each as flexures
261
+ // finds it, and the versions of the geometry libraries it measures with (manifold-3d: every clash, offset and area;
262
+ // @jscad/modeling: the shapes). A change to any of them works the stages out again.
263
+ const nextTo = (name, dir) =>
264
+ path.dirname(createRequire(pathToFileURL(path.join(dir, 'package.json')).href).resolve(name));
265
+ // (a package's version as installed where `dir` finds it, by its package.json, which manifold-3d does not export;
266
+ // 'none' where it is not installed)
267
+ function installedVersion(name, dir) {
268
+ for (const at of createRequire(pathToFileURL(path.join(dir, 'package.json')).href).resolve.paths(name) ?? []) {
269
+ const f = path.join(at, name, 'package.json');
270
+ if (fs.existsSync(f)) return JSON.parse(fs.readFileSync(f, 'utf8')).version;
271
+ }
272
+ return 'none';
273
+ }
274
+ /**
275
+ * What a lamina's slow stages are worked out with, besides their own inputs: the code of flexures and of the packages
276
+ * it calls (fea, fixings, gears, and shapes through fixings), and the versions of manifold-3d and @jscad/modeling.
277
+ * @returns {{ sources: string[], versions: Record<string, string> }}
278
+ */
279
+ export function stageInputs() {
280
+ const fixings = nextTo('@rulecad/fixings', flexuresDir);
281
+ return {
282
+ sources: [
283
+ flexuresDir,
284
+ feaDir,
285
+ fixings,
286
+ nextTo('@rulecad/gears', flexuresDir),
287
+ nextTo('@rulecad/shapes', fixings),
288
+ ].map(helperSources),
289
+ versions: Object.fromEntries(['manifold-3d', '@jscad/modeling'].map((n) => [n, installedVersion(n, flexuresDir)])),
290
+ };
291
+ }
292
+ /**
293
+ * The salt a lamina's stages are kept under (.cache/stages): a hash of stageInputs.
294
+ * @param {ReturnType<typeof stageInputs>} inputs @returns {string}
295
+ */
296
+ export const stageSaltOf = (inputs) => crypto.createHash('sha256').update(JSON.stringify(inputs)).digest('hex');
253
297
  const STAGES = paths.cache('stages'),
254
- stageSalt = crypto
255
- .createHash('sha256')
256
- .update(helperSources(flexuresDir) + helperSources(feaDir))
257
- .digest('hex');
258
- // A workspace cloned from elsewhere may hold links of its own in .cache/: a cache file that is a link to a file outside
259
- // (the trust list, say) would have the tool write what a sandboxed design handed back through it, and a cache folder
260
- // that is a link would have cache files written, and pruned, somewhere else. So a cache file is written only when it
261
- // and every folder between it and the workspace are a plain file and plain folders, or not there yet.
262
- function ownCacheFile(file, root = WS) {
263
- if (host.name === 'memory') return true; // (held in memory: nothing on disk to follow)
264
- const top = path.resolve(root);
265
- let p = path.resolve(file);
266
- if (!p.startsWith(top + path.sep)) return false;
267
- for (let first = true; p !== top; p = path.dirname(p), first = false) {
268
- let st;
298
+ stageSalt = stageSaltOf(stageInputs());
299
+ // (a cache file is written only where it and every folder between it and the workspace are a plain file and plain
300
+ // folders, or not there yet, and whole: cache-file.mjs ownCacheFile and writeCacheFile)
301
+ // The files of the workspace a design imported (its project's helpers: lid.js's ./box.js), as each reads now: { path in
302
+ // the workspace, with forward slashes: its SHA-256 }. A kept build was made from them as much as from the design's own
303
+ // text, so it holds only while each reads as it did when the build was made. Null when one of them can't be read
304
+ // as a file of the workspace (gone, outside it, in its node_modules, or reached through a link out of it): such a build
305
+ // is never kept, nor a kept one used. (A kept build's list comes from .cache/, which a cloned workspace may bring: a
306
+ // path that climbs out, or names a file elsewhere, is never read, whatever it hashed to.)
307
+ const ownPath = (f) => isWorkspacePath(f) && !path.isAbsolute(f);
308
+ function importHashes(files) {
309
+ const out = {};
310
+ for (const f of files) {
311
+ if (!ownPath(f)) return null;
269
312
  try {
270
- st = fs.lstatSync(p);
271
- } catch (e) {
272
- if (e.code === 'ENOENT') continue;
273
- return false;
313
+ out[f] = crypto
314
+ .createHash('sha256')
315
+ .update(readOwnText(path.resolve(WS, f)))
316
+ .digest('hex');
317
+ } catch {
318
+ return null;
274
319
  }
275
- if (first ? !(st.isFile() && st.nlink === 1) : !st.isDirectory()) return false;
276
320
  }
277
- return true;
321
+ return out;
278
322
  }
323
+ const sameHashes = (a, b) =>
324
+ !!a && !!b && Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((f) => a[f] === b[f]);
325
+ // (a path inside the workspace, with forward slashes, as importHashes takes them: Node names an imported file by its
326
+ // real path, so a workspace reached through a link, /var for /private/var, is matched by its real path too)
327
+ let realWS = null;
328
+ function inWorkspace(f) {
329
+ const leaves = (rel) => rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel);
330
+ let rel = path.relative(WS, f);
331
+ if (leaves(rel)) {
332
+ try {
333
+ realWS ||= fs.realpathSync(WS);
334
+ } catch {
335
+ realWS = WS;
336
+ }
337
+ if (!leaves(path.relative(realWS, f))) rel = path.relative(realWS, f);
338
+ }
339
+ return rel.split(path.sep).join('/');
340
+ }
341
+
279
342
  // A design's own folder of a cache: named by a hash of its file's path in the workspace, so it stays the same when the
280
343
  // workspace moves, and one design's results are never read by another
281
344
  const designFolder = (dir, d) =>
@@ -357,7 +420,7 @@ function stageStore(d) {
357
420
  try {
358
421
  clearOldStages();
359
422
  prune(dir, STAGES_KEEP);
360
- if (makeRoom(STAGES, dir, Buffer.byteLength(text, 'utf8'), STAGES_HELD)) host.writeText(f, text);
423
+ if (makeRoom(STAGES, dir, Buffer.byteLength(text, 'utf8'), STAGES_HELD)) writeCacheFile(f, text);
361
424
  } catch {
362
425
  // (a cache that can't be written is only slower)
363
426
  }
@@ -384,7 +447,7 @@ const routeStore = (d) => {
384
447
  if (!f || !ownCacheFile(f)) return;
385
448
  try {
386
449
  prune(dir, ROUTES_KEEP);
387
- if (makeRoom(paths.cache('routes'), dir, Buffer.byteLength(text, 'utf8'), ROUTES_HELD)) host.writeText(f, text);
450
+ if (makeRoom(paths.cache('routes'), dir, Buffer.byteLength(text, 'utf8'), ROUTES_HELD)) writeCacheFile(f, text);
388
451
  } catch {
389
452
  // (a cache that can't be written is only slower)
390
453
  }
@@ -398,15 +461,21 @@ export const pcbEngine = () =>
398
461
  throw e;
399
462
  });
400
463
 
401
- // What v.fixings is bound to (lib/fixings.mjs): the workspace's own rule sets by name (a release's own, where it is one:
402
- // its threads and materials are used before the kit's), the project's printer as a rule set with its values worked
403
- // out, and the project's material. With a hash of all of it and of the kit's sets: a build that called v.fixings is
404
- // made from these too, so its cache holds only while they stand.
405
464
  let kitRules = null;
465
+ /**
466
+ * What v.fixings is bound to (lib/fixings.mjs): the workspace's own rule sets by name (a release's own, where it is
467
+ * one: its threads and materials are used before the kit's), the project's printer as a rule set with its values
468
+ * worked out, and the project's material (a release's, as it was then). With a hash of all of it and of the kit's
469
+ * sets: a build that called v.fixings is made from these too, so its cache holds only while they stand. And the files
470
+ * it read them from: a release records those of the workspace, so a changed thread set counts as a change.
471
+ * @param {{ project: string, dir: string, rulesDir?: string, tree?: string }} d the design (a release's, materialised)
472
+ * @returns {{ context: { sets: object, printer: object | null, material: string | null }, hash: string, files: string[] }}
473
+ */
406
474
  export function fixingsContext(d) {
407
475
  const dir = d.rulesDir || RULE_DIRS[0],
408
476
  sets = {},
409
- text = [];
477
+ text = [],
478
+ files = [];
410
479
  for (const f of host
411
480
  .list(dir)
412
481
  .filter((x) => x.endsWith('.json'))
@@ -417,16 +486,19 @@ export function fixingsContext(d) {
417
486
  if (s && s.rules && typeof s.rules === 'object') {
418
487
  sets[s.name ?? f.slice(0, -5)] = s;
419
488
  text.push(raw);
489
+ files.push(path.join(dir, f));
420
490
  }
421
491
  } catch {
422
492
  // (a broken set is cad check's to name, where a design uses it)
423
493
  }
424
494
  }
425
- const name = printerOf(d.project),
495
+ const projectDir = d.tree ? path.join(d.tree, 'projects', d.project) : d.dir; // (a release's: its project.json as it was)
496
+ const name = printerOf(d.project, projectDir),
426
497
  peek = (n) => {
427
498
  plainName(n, 'rule set name');
428
499
  const f = [dir, ...RULE_DIRS].map((x) => path.join(x, `${n}.json`)).find((x) => host.exists(x));
429
500
  if (!f) throw new Error(`no rule set "${n}" (rules/${n}.json)`);
501
+ files.push(f);
430
502
  return readJson(f);
431
503
  };
432
504
  let printer = null;
@@ -445,7 +517,7 @@ export function fixingsContext(d) {
445
517
  }
446
518
  let material = null;
447
519
  try {
448
- const f = path.join(d.dir, 'project.json');
520
+ const f = path.join(projectDir, 'project.json');
449
521
  if (host.exists(f))
450
522
  material =
451
523
  String(readJson(f).material || '')
@@ -472,6 +544,7 @@ export function fixingsContext(d) {
472
544
  const context = { sets, printer, material };
473
545
  return {
474
546
  context,
547
+ files: [...new Set(files)].sort(),
475
548
  hash: crypto
476
549
  .createHash('sha256')
477
550
  .update(JSON.stringify([text, printer, material, kitRules]))
@@ -482,9 +555,45 @@ export function fixingsContext(d) {
482
555
 
483
556
  // An object's on-screen settings are "display" ({ "smooth": 24 }), and a part left off screen is "display": false.
484
557
  // Their first name, "mirror", still works: read here, the rest of the tool sees it as mirror either way.
485
- // Which engine a design's v.ops booleans use: the object's "engine": "manifold", or CAD_ENGINE=manifold for every design
486
- export const booleans = (object) =>
487
- object.engine === 'manifold' ? 'manifold' : object.engine === 'pcb' ? 'jscad' : process.env.CAD_ENGINE || 'jscad';
558
+ // Which engine a design's v.ops booleans use: the object's "engine": "manifold"; else CAD_ENGINE=manifold (or jscad)
559
+ // for every design; else the object's "engine": "jscad"; else the workspace's, "engine" in cad.config.json (a new
560
+ // workspace's is "manifold"); else JSCAD's. A workspace that asks for Manifold where manifold-3d isn't installed gets
561
+ // JSCAD's, and is told once how to install it (an object that asks for it by name is refused, as before: shapes.ops).
562
+ export const booleans = (object) => {
563
+ // (a misspelt workspace engine is refused whichever design reads it, so it isn't found only by the first that names none)
564
+ if (config.engine != null && config.engine !== 'jscad' && config.engine !== 'manifold')
565
+ throw Object.assign(
566
+ new Error(
567
+ `"engine" in cad.config.json is ${JSON.stringify(config.engine)}: it should be "manifold" (with manifold-3d installed) or "jscad", or left out for JSCAD`,
568
+ ),
569
+ { code: 'engine.unknown', file: 'cad.config.json', path: 'engine' },
570
+ );
571
+ if (object.engine === 'manifold') return 'manifold';
572
+ if (object.engine === 'pcb') return 'jscad';
573
+ if (process.env.CAD_ENGINE) return process.env.CAD_ENGINE;
574
+ if (object.engine === 'jscad' || config.engine !== 'manifold') return 'jscad';
575
+ if (manifoldInstalled()) return 'manifold';
576
+ if (!toldNoManifold) {
577
+ toldNoManifold = true;
578
+ process.stderr.write(
579
+ `Note: cad.config.json asks for the Manifold engine, but manifold-3d isn't installed here, so designs are built with JSCAD (slower, and its seams can read as overlaps). To use Manifold: npm install manifold-3d (in ${WS}). To keep JSCAD and not be told again: "engine": "jscad" in cad.config.json\n`,
580
+ );
581
+ }
582
+ return 'jscad';
583
+ };
584
+ let toldNoManifold = false,
585
+ manifoldThere = null;
586
+ // (found where the boolean engine looks for it, without loading it: a workspace's packages sit side by side)
587
+ function manifoldInstalled() {
588
+ if (manifoldThere == null)
589
+ try {
590
+ import.meta.resolve('manifold-3d');
591
+ manifoldThere = true;
592
+ } catch {
593
+ manifoldThere = false;
594
+ }
595
+ return manifoldThere;
596
+ }
488
597
 
489
598
  export const readObject = (d) => {
490
599
  const o = readJson(d.json);
@@ -660,10 +769,82 @@ export async function boardChecks(b, d) {
660
769
  return boardWork('checks', args, d, until);
661
770
  }
662
771
 
772
+ // What a build read besides its own .js and .json, its "uses" rule sets and its layouts, as a release records it (lib/
773
+ // versions.mjs): files, the workspace's files its design imported (lid.js's ./box.js); fixings and frames, whether it
774
+ // called v.fixings or v.frames, which read the rule sets of rules/ (thread, material, profile sets, the printer's);
775
+ // sets, those rule sets' files as they are now (the workspace's own only: the kit's come with the kit), and the
776
+ // project's project.json where v.fixings drew (its material); also, the files
777
+ // of the objects it reads through "uses", so that the release holds them as they were. Paths inside the workspace (or
778
+ // the release), with forward slashes.
779
+ // (a file's path inside the workspace, or inside the release a design was materialised from, else null: the kit's own)
780
+ const inside = (d, f) => {
781
+ const r = path
782
+ .relative(d.tree || WS, f)
783
+ .split(path.sep)
784
+ .join('/');
785
+ return isWorkspacePath(r) ? r : null;
786
+ };
787
+ function readsOf(d, { imports, fixings, frames, also, framed, fixed }) {
788
+ const js = inside(d, d.js);
789
+ // (with the project's project.json where v.fixings drew: the material it drew for is the project's)
790
+ const pj = path.join(d.tree ? path.join(d.tree, 'projects', d.project) : d.dir, 'project.json');
791
+ const sets = [
792
+ ...(fixings ? fixed().files : []),
793
+ ...(fixings && host.exists(pj) ? [pj] : []),
794
+ ...(frames ? framed.files || [] : []),
795
+ ]
796
+ .map((f) => inside(d, f))
797
+ .filter(Boolean);
798
+ return {
799
+ files: imports.filter((f) => f !== js),
800
+ fixings,
801
+ frames,
802
+ sets: [...new Set(sets)].sort(),
803
+ also,
804
+ };
805
+ }
806
+
807
+ /**
808
+ * The text of each file a design read besides its own, as a release's record names them (lib/versions.mjs: the files
809
+ * its design imported, and, where it called v.fixings or v.frames, the rule sets those read and the project's material),
810
+ * read from the release's folder for a release, else from the workspace: compared file by file between a release and
811
+ * the design now, so an edited helper or thread set counts as a change. A file that isn't there is null.
812
+ * @param {{ project: string, dir: string, js: string, rulesDir?: string, tree?: string }} d the design, or a release (materialise's)
813
+ * @param {{ files: string[], fixings: boolean, frames: boolean }} reads a release's record
814
+ * @returns {Record<string, string | null>} by path inside the workspace
815
+ */
816
+ export function readTexts(d, reads) {
817
+ const top = d.tree || WS,
818
+ out = {};
819
+ const text = (f) => {
820
+ try {
821
+ return readOwnText(path.join(top, ...f.split('/'))).replace(/\r\n/g, '\n'); // (a Windows checkout may write \r\n)
822
+ } catch {
823
+ return null;
824
+ }
825
+ };
826
+ for (const f of reads.files) out[f] = text(f);
827
+ const fx = reads.fixings ? fixingsContext(d) : null;
828
+ const sets = [...(fx ? fx.files : []), ...(reads.frames ? framesContext(d.rulesDir || RULE_DIRS[0]).files : [])]
829
+ .map((f) => inside(d, f))
830
+ .filter(Boolean);
831
+ for (const f of sets.sort()) out[f] = text(f);
832
+ if (fx) {
833
+ // (the project's material and printer, which v.fixings draws for: a project.json with another printer is a change)
834
+ out[`projects/${d.project}/project.json: material`] = fx.context.material;
835
+ out[`projects/${d.project}/project.json: printer`] = fx.context.printer?.name ?? null;
836
+ }
837
+ return out;
838
+ }
839
+
663
840
  // build(design, set, { mirror, trusted }) -> { object, values, entries, parts, polygons (for the mirror), triangles (for checks and export), fixings? }
664
841
  // trusted: the caller trusts the design, for a host other than Node's file system (memoryHost): run it in this process, not the sandbox (runsHere)
665
842
  // fixings: what the design's calls to v.fixings found (each hole and seat, what it was drawn to and rests on), as findings
843
+ // seats: what v.shapes' seat helpers drew (shaftBore, bearingSeat, plainBearing, pulleyBore), as 'seat.drawn' findings
666
844
  // parts: [{ name, role, label, geometry, polygons, triangles }]; polygons and triangles: every part together
845
+ // imports: the files of the workspace the design imported (its project's helpers), paths inside the workspace with
846
+ // forward slashes: the build is made from them too, and its kept copy holds only while they read the same
847
+ // reads: what it read besides its own files, as a release records it (readsOf)
667
848
  export async function build(d, set = {}, { mirror = false, trusted = false } = {}) {
668
849
  const object = readObject(d);
669
850
  set = variantSet(d, object, set);
@@ -703,9 +884,18 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
703
884
  ...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))),
704
885
  JSON.stringify(refs.extra),
705
886
  ];
706
- const reads = { values, parts: object.parts, engine: object.engine, mirror: object.mirror };
707
- // (v.frames reads the workspace's own profile sets: a build is made from them too, lib/frames.mjs)
708
- const framed = framesContext(RULE_DIRS[0]);
887
+ // (and whether it is printed: a reference's holes, or a board's, made by its fab, are drawn with no hole
888
+ // compensation, lib/fixings.mjs)
889
+ const reference = ['reference', 'board'].includes(object.role),
890
+ reads = {
891
+ values,
892
+ parts: object.parts,
893
+ engine: object.engine,
894
+ mirror: object.mirror,
895
+ ...(reference ? { reference } : {}),
896
+ };
897
+ // (v.frames reads the workspace's own profile sets, or a release's own: a build is made from them too, lib/frames.mjs)
898
+ const framed = framesContext(d.rulesDir || RULE_DIRS[0]);
709
899
  const key = crypto
710
900
  .createHash('sha256')
711
901
  .update(
@@ -726,18 +916,27 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
726
916
  .digest('hex');
727
917
  const hit = path.join(CACHE, `${key}.json`);
728
918
  // (a build that called v.fixings is also made from the workspace's thread sets, its printer and material: it holds
729
- // while those stand, and is known by them too, so what is kept by a build's hash, an overlap, follows a changed pilot)
919
+ // while those stand, and is known by them too, so what is kept by a build's hash, an overlap, follows a changed pilot.
920
+ // Likewise the files the design imported: a kept build holds while they read the same, and is known by them)
730
921
  let fx = null;
731
922
  const fixed = () => (fx ||= fixingsContext(d)),
732
- known = (f) =>
733
- f
923
+ // (v.fixings as this object has it: a reference is not printed)
924
+ bound = () => ({ ...fixed().context, ...(reference ? { printed: false } : {}) }),
925
+ known = (f, imported) => {
926
+ const more = (f || '') + (imported && Object.keys(imported).length ? JSON.stringify(imported) : '');
927
+ return more
734
928
  ? crypto
735
929
  .createHash('sha256')
736
- .update(key + f)
930
+ .update(key + more)
737
931
  .digest('hex')
738
932
  : key;
739
- const kept = !process.env.CAD_NO_CACHE && cached(hit) ? JSON.parse(host.readText(hit)) : null;
740
- if (kept && (!kept.fixed || kept.fixed === fixed().hash)) {
933
+ };
934
+ const kept = (!process.env.CAD_NO_CACHE && readCacheJson(hit)) || null; // (one cut short or spoiled: a miss, made again)
935
+ const keptImports =
936
+ kept && kept.imports && typeof kept.imports === 'object' && !Array.isArray(kept.imports)
937
+ ? importHashes(Object.keys(kept.imports))
938
+ : null;
939
+ if (kept && sameHashes(keptImports, kept.imports) && (!kept.fixed || kept.fixed === fixed().hash)) {
741
940
  const c = kept;
742
941
  try {
743
942
  host.touch(hit);
@@ -757,8 +956,18 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
757
956
  polygons: parts.flatMap((p) => p.polygons),
758
957
  triangles: parts.flatMap((p) => p.triangles),
759
958
  cached: true,
760
- hash: known(c.fixed),
959
+ hash: known(c.fixed, keptImports),
960
+ imports: Object.keys(keptImports),
961
+ reads: readsOf(d, {
962
+ imports: Object.keys(keptImports),
963
+ fixings: !!c.fixed,
964
+ frames: !!c.frames,
965
+ also: refs.files,
966
+ framed,
967
+ fixed,
968
+ }),
761
969
  ...(c.fixings ? { fixings: c.fixings } : {}),
970
+ ...(Array.isArray(c.seats) ? { seats: c.seats } : {}),
762
971
  ...(c.mechanism ? { mechanism: c.mechanism } : {}),
763
972
  ...(c.circuit ? { circuit: c.circuit, matrix: c.matrix, ...(c.source ? { source: c.source } : {}) } : {}),
764
973
  };
@@ -770,8 +979,10 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
770
979
  let parts,
771
980
  board = null,
772
981
  read,
982
+ imported = [], // the files of the workspace the design imported (paths inside it, forward slashes)
773
983
  mechanism = null,
774
984
  fixings = null,
985
+ seats = null, // what v.shapes' seat helpers drew (lib/designshapes.mjs), as findings
775
986
  mounted = false;
776
987
  const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
777
988
  const stages = stageStore(d);
@@ -793,13 +1004,15 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
793
1004
  engine: booleans(object),
794
1005
  optional,
795
1006
  stages,
796
- bound: { frames: framed, fixings: fixed().context },
1007
+ bound: { frames: framed, fixings: bound() },
797
1008
  board: pcb ? { routes: routeStore(d) } : null,
798
1009
  })
799
1010
  .catch((e) => {
800
1011
  throw syntaxAt(e, d);
801
1012
  });
802
- ({ parts, read, mechanism, fixings } = r);
1013
+ ({ parts, read, mechanism, fixings, seats } = r);
1014
+ const project = path.dirname(path.dirname(path.resolve(d.js)));
1015
+ imported = (r.imports || []).map((f) => inWorkspace(path.resolve(project, f)));
803
1016
  if (pcb) {
804
1017
  board = r.board;
805
1018
  mounted = r.mounted;
@@ -819,7 +1032,8 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
819
1032
  });
820
1033
  if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
821
1034
  const ops = await shapes.ops(booleans(object)),
822
- df = (await import('./fixings.mjs')).designFixings({ ...fixed().context, ops }); // (loaded when a design is run here: the sandbox's runner has its own)
1035
+ df = (await import('./fixings.mjs')).designFixings({ ...bound(), ops }), // (loaded when a design is run here: the sandbox's runner has its own)
1036
+ ds = designShapes(shapes, { printer: fixed().context.printer });
823
1037
  // v.pcb.mount('M2', ...) reads the workspace's thread sets, as v.fixings does: such a build is known by them too
824
1038
  const engine = pcb
825
1039
  ? {
@@ -833,7 +1047,7 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
833
1047
  const w = watch(
834
1048
  values,
835
1049
  {
836
- shapes,
1050
+ shapes: ds.shapes,
837
1051
  flexures,
838
1052
  gears,
839
1053
  motors,
@@ -863,20 +1077,28 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
863
1077
  throw located(e, d.js, 'design.run');
864
1078
  }
865
1079
  if (df.used()) fixings = df.found();
1080
+ if (ds.used()) seats = ds.found();
1081
+ imported = ((await host.importsOf?.(d.js)) || []).map(inWorkspace); // (after main: it may import as it runs)
866
1082
  }
867
1083
  for (const e of entries) if (read.has(e.name)) e.used = true;
868
- if (ownCacheFile(hit))
1084
+ // (read after the run: a helper saved while the design ran is then read as it is now, and the build kept under it,
1085
+ // until the next edit; a window of the run's length, against a cache that otherwise never sees the helper at all)
1086
+ const importsNow = importHashes([...new Set(imported)].sort());
1087
+ if (importsNow && ownCacheFile(hit))
869
1088
  try {
870
1089
  prune();
871
- host.writeText(
1090
+ writeCacheFile(
872
1091
  hit,
873
1092
  JSON.stringify({
874
1093
  used: entries.filter((e) => e.used).map((e) => e.name),
1094
+ imports: importsNow,
875
1095
  parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })),
876
1096
  ...(board || {}),
877
1097
  ...(mechanism ? { mechanism } : {}),
878
- ...(fixings || mounted ? { fixed: fixed().hash } : {}),
1098
+ ...(fixings || seats || mounted ? { fixed: fixed().hash } : {}),
879
1099
  ...(fixings ? { fixings } : {}),
1100
+ ...(seats ? { seats } : {}),
1101
+ ...(read.has(':frames') ? { frames: true } : {}),
880
1102
  }),
881
1103
  );
882
1104
  } catch {
@@ -891,8 +1113,18 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
891
1113
  parts,
892
1114
  polygons: parts.flatMap((p) => p.polygons),
893
1115
  triangles: parts.flatMap((p) => p.triangles),
894
- hash: known(fixings || mounted ? fixed().hash : null),
1116
+ hash: known(fixings || seats || mounted ? fixed().hash : null, importsNow || { [crypto.randomUUID()]: 'unread' }), // (one not read: known by no other build)
1117
+ imports: [...new Set(imported)].sort(),
1118
+ reads: readsOf(d, {
1119
+ imports: [...new Set(imported)].sort(),
1120
+ fixings: !!(fixings || seats || mounted),
1121
+ frames: read.has(':frames'),
1122
+ also: refs.files,
1123
+ framed,
1124
+ fixed,
1125
+ }),
895
1126
  ...(fixings ? { fixings } : {}),
1127
+ ...(seats ? { seats } : {}),
896
1128
  ...(board || {}),
897
1129
  ...(mechanism ? { mechanism } : {}),
898
1130
  };