@rulecad/cad 0.7.97 → 0.8.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.
package/AGENTS.md CHANGED
@@ -231,6 +231,8 @@ variable says which rule it comes from. Follow these steps; they're what makes a
231
231
 
232
232
  ## Circuit boards
233
233
  - `"engine": "pcb"` in the .json; `main(v)` returns a board built with `v.pcb` (see @rulecad/pcb's README).
234
+ - A board design runs in the sandbox as any design does, with `v.pcb` as its only way to the board engine: it can't
235
+ import Node's modules, read files outside the workspace or write any. A workspace with boards asks for no trust.
234
236
  - Parts come from rule sets where one exists (`v.pcb.xiao`, `qwiic`, `jstph`, `header`), or any standard footprint by
235
237
  name (`v.pcb.part('U2', 'soic8', x, y)`). Turn parts in quarter turns with `rotation`, held in a variable.
236
238
  - A board's mounting holes are named by their screws' thread, never typed: `v.pcb.mount('M2', x, y)` in its `holes`
package/CHANGELOG.md CHANGED
@@ -5,6 +5,44 @@ print (a hole's diameter, a seat's depth, a part's outline). Each release lists
5
5
  its reason. A **fasten** is an entry in an assembly's `"fasten"` list: one screwed joint, naming the screw by thread
6
6
  and head, the parts it passes through and the part it ends in.
7
7
 
8
+ ## 0.8.0: board designs run in the design sandbox, and a workspace with boards asks for no trust; a design in a workspace held in memory runs in the tool's own process only when the caller trusts it; dot-files are not a package's sources; 'no parts overlap' catches parts that overlap on a shared plane, without manifold-3d; the torque to tighten a screw in a printed thread to is half what strips it, at most; names read from a workspace's files can no longer reach outside it; a sandboxed design can no longer import its way out of an allowed package; a sandboxed design can no longer write files through its reply; every target but the kit's own is asked about
9
+
10
+ ### Changed
11
+
12
+ - A board design (an object whose JSON says `"engine": "pcb"`) now runs in the design sandbox, as every other design does: another process that can't write files, start programs or import Node's modules, and that reads only the workspace and the packages designs use, with the board engine (`@rulecad/pcb` and the tscircuit packages it loads) allowed there. The design still reaches the engine as `v.pcb`; `v.pcb.mount` still reads the workspace's own thread sets. It hands back its board's Circuit JSON, which is checked like the rest of a sandbox's reply before the tool makes the board's solid and files from it, and the routes the autorouter found, which the tool keeps in `.cache/routes/` (or the folder `RULECAD_ROUTE_CACHE` names, which the sandbox may then read) under the route cache's own names only. A part's 3D model named in a board is read only from a plain path inside the workspace (`models/…`), and only when the file really is there: a link in `models/` to a file elsewhere is not followed. The board engine's packages the sandbox may read are found from the tool's own copy of `@rulecad/pcb`, never from one in the workspace's `node_modules`, so a workspace can't widen what a design reads by the package files it ships.
13
+ - So the one-time board question is gone: `cad trust` no longer lists "board designs run outside the sandbox", and a cloned board workspace builds with nothing trusted. A board design that read files or used Node itself (`import fs from 'node:fs'`) now stops with a `design.sandbox` message, as a JSCAD design does; a workspace that trusts its designs (`"sandbox": false`, then `cad trust`) still runs them in the tool's own process.
14
+ - A workspace held in memory (`memoryHost`) now runs its designs in the same sandbox, through a new host hook, `runDesign`: the design's project is copied into a temporary folder for the sandbox to read, and removed after. `build(d, set, { trusted: true })` still runs one in the tool's own process. A design in memory that imports Node's modules is now refused with `design.sandbox` rather than `workspace.untrusted`.
15
+ - A workspace that trusts its designs runs only its own in the tool's process: a design from another folder (a path to it, or a link out of the workspace), JSCAD or board, is refused there, as board designs already were.
16
+ - Upgrading: nothing to do. An entry "board designs run outside the sandbox" left in your trust list does no harm. Board builds take a second or so longer (a second process starts and loads the board engine); the thin-picro macropad builds to the same circuit either way. No printed size changes.
17
+
18
+ - A workspace held in memory (`memoryHost`) runs a design in the tool's own process only when `build` is called with `{ trusted: true }`, and `true` there means `true` itself, not any value that looks true. Otherwise the design runs in the sandbox (board-sandbox.md). No shipped command uses `memoryHost`.
19
+ - Upgrading: code that builds through `memoryHost` and needs a design run in its own process passes `{ trusted: true }` to `build`. No printed size changes.
20
+
21
+ ### Fixed
22
+
23
+ - cad's build keys read every module of its helper packages, and so also a scratch module another package's tests write beside them for a moment (the fixings README test's `.readme-example-<n>.mjs`). Run in parallel, as CI runs the packages' tests, cad could list it and then fail to read it once deleted (ENOENT, seen on Windows twice). Dot-files are now left out, in the build key, the gears' key and the board engine's. Builds miss the cache once (this code is part of its key). No printed size changes.
24
+
25
+ - In a workspace without `manifold-3d` (a new workspace's default), the overlap check threw away the volume JSCAD measured whenever `@rulecad/fit` said the parts' surfaces did not cross. Parts of the same height standing on one plane and run into each other, or a part placed twice, share face planes, and fit read them as touching: 'no parts overlap' passed two 10 mm cubes sharing 250 mm³. fit now finds these overlaps, so the check fails them with the volume measured. If you upgrade, an assembly with parts like these that passed now fails 'no parts overlap', naming the two parts and how much they share. Remembered overlaps (`.cache/overlaps.json`) are measured again once. No printed size changes.
26
+
27
+ - `fasten.load` said to tighten a screw in a printed pilot to the preload that left the thread twice the pull, within what the seat under the head takes; with a washer, a metal part under the head or no seat material known, that was nearly what strips the thread. It now leaves the thread twice the preload and the pull together, within half what the seat takes (`screwLoad` of `@rulecad/fixings`), and the thread's margin counts the preload. A joint with no load named tightens to the least of what the seat takes and half what the thread is estimated to strip at, and `cad order` and the build page say "half what the thread strips at" where the thread sets it (`tighten.thread` in `--json`; a frame's tightening by kind of join says so too). `fasten.seat` names that torque beside what the seat takes, and where a torque given is more than the seat takes it says to tighten to the thread's torque, not the seat's; past half what the thread strips at it no longer names a washer that would let the seat take the torque given. Where two screws hold the same margin, the one pulled harder is named. If you upgrade, the torques `cad check` and `cad order` give for screws in printed threads fall, by about half under a load; under a load, a screw into a nut or an insert whose seat set its torque is tightened to half what the seat takes (an M5 button screw on PLA: 0.9 N m where it was 1.8); on a joint with a load, a torque given that clamps with more than half the thread's stripping load now warns, and some joints that passed now warn that their clamp holds the shear by friction fewer than twice over. No printed size changes.
28
+
29
+ - A rule set named in a workspace's own files can no longer make the tool read or write outside the workspace. The first time a design uses one of the kit's rule sets, the tool copies it into the workspace's `rules/` folder, and it joined the name into both paths unchecked: `"printer": "../../../A/B"` in a cloned workspace's `project.json` made `cad check` copy a file from the workspace to a new place two folders above it, often your home folder. Rule-set, project, object, layout, problem and assembly names are now plain names (letters, digits, `-` and `_`, starting with a letter or digit), and one that is not is refused with the file and field it came from, as `projects/p/project.json: the "printer" field "../x" is not a plain name`. The same holds for `printer` in `cad.config.json`, for the rule sets in an object's `"uses"`, and for the names given on the command line.
30
+ - In an object's `"uses"`, another object must be named `<project>/<object>`, optionally with `:<variant>` and `@<version>`; a path to a file there is refused. The project and object schemas say the same, so an editor marks such a name as you type it, and `cad check` says in words what such an entry may be, where it used to print the schema's pattern. The name `cad rules draft` writes a rule set under is held to the same rule.
31
+ - An object named in an assembly's item, a project's `"objects"` or a problem is always an object of that project, never a path: `"object": "../../elsewhere/x/objects/evil"` read from where you stand used to reach a design outside the workspace. The tool no longer copies a rule set into `rules/` when `rules/`, or the file it would write, is a link (as a cloned workspace can hold) to somewhere else: it says which link to replace with a folder or file of the workspace's own.
32
+ - Upgrading: nothing to do for the kit's own rule sets and for names made with `cad new`. A workspace whose rule set, project, object, layout or problem name holds a space, a dot or a slash now stops with a message asking for a plain name: rename the file and the names that point at it. A folder under `projects/` whose name is not plain is no longer listed as a project. No printed size changes.
33
+
34
+ - A design in the sandbox can no longer climb out of a package it may import. The import filter checked only that an import began with an allowed package's name, not where it led, so `@jscad/modeling/../../graceful-fs/graceful-fs.js` handed a design a module that reads files, and a longer climb loaded any file of the workspace outside the design's project, which was free to import the network. An import of an allowed package must now name a file by its plain path in the package (no `..` or `.` folders, no `node_modules` folder, backslashes, `%` or `~`, and no folder whose name ends in a dot or a space, which Windows would drop), and the file it finds must lie in that package's own folder, as rulecad finds it, or in the design's project. Anything else stops the build with a `design.sandbox` message naming the import.
35
+ - A file of an allowed package that a design reaches may import only the allowed packages and what that package's `package.json` depends on. `@jscad/modeling` ships its own tests, which `require('ava')`: a design that imported one of them, in a workspace that installs a package of its own under that name, ran that package outside the filter, free to reach the network. It is now refused before Node looks for it.
36
+ - Upgrading: nothing to do for designs that import `@jscad/modeling` or a file in it by its path (`@jscad/modeling/src/primitives/index.js`), or the other allowed packages by name: none of the kit's own designs changes. A design whose import of a package goes through `..` is refused: name the file by its path inside the package. A design whose project holds its own copy of an allowed package keeps working; one that reaches a package through a link out of the project to some other folder, or a copy outside the project that is not the one rulecad itself uses, is refused: the message says where the import led and which copy rulecad uses (`npm ls <package>` lists the copies a workspace has). No printed size changes.
37
+ - The README's Sandbox paragraph now lists `@rulecad/frames`, which designs could always import.
38
+
39
+ - A design in the sandbox can no longer write files through the reply it hands back. The tool used to write the slow stages a reply carried (a lamina's physics) as `.cache/stages/<name>.json` with no check on the name, so a design could climb out of the cache with `../` and overwrite any JSON file you own, your trust list among them, and its next build then ran outside the sandbox. Every field of the reply is now checked: a stage is written only under a name of the form the cache makes, directly in `.cache/stages/`, and a reply that is not one rulecad makes stops the build with a `design.sandbox` message, with nothing from it used or written.
40
+ - A workspace cloned from elsewhere can no longer use links in its `.cache/` folder to the same end: a cache file (a stage, or a build) is written only when it and the folders above it in the workspace are plain files and folders, never through a link, so a stage file shipped as a link to your trust list is left as it is.
41
+ - Upgrading: nothing to do. Designs build as before and cached stages are reused. A design that writes a reply of its own to the process's output (`process.stdout.write`, then `process.exit`) is now refused unless that reply is exactly of the form rulecad's runner makes. No printed size changes. If you made your workspace's `.cache/` (or a folder in it) a link to another disk, builds and stages are no longer kept there: they are made afresh each time until the link is replaced by a real folder.
42
+
43
+ - A target in cad.config.json is now the kit's own only when its name is exactly one of the kit's (today only `gist`). Every other name is the workspace's own code, run in the tool's process, and is asked about with `cad trust` first, whatever it looks like: a bare name (`"show": "show"`), a backslash path, or a `../` name that reaches one of the kit's modules. Before, those ran in a cloned workspace on its first `cad show` or `cad link --md` with nothing asked. A target outside the workspace's folder is refused even once trusted: put the module in the workspace and name it from there.
44
+ - Upgrading: a workspace whose own target is named without a slash or extension is asked for `cad trust` once; after that it runs as before. Workspaces using `gist` change nothing. No printed size changes.
45
+
8
46
  ## 0.7.97: robust: true
9
47
  ### Added
10
48
 
@@ -44,7 +82,6 @@ and head, the parts it passes through and the part it ends in.
44
82
  - A refusal of a feature past three cells asks for cells of at least a third of it, rounded up (it asked for cells of
45
83
  1.33 mm or less for 4 mm, which it refused again), or a smaller feature.
46
84
 
47
-
48
85
  ## 0.7.92: eight axes on a Mega 2560 (#199)
49
86
  - The wiring sheet names a Mega slot's pins as step, dir and enable (D38, every slot's): the wire to a driver breakout carries EN, STEP, DIR and GND, and the axis's home switch is a wire of its own. A CNC shield's axis still names its limit pin.
50
87
  - The quadruped carries a 12 V supply (a Mean Well LRS-100-12 to buy: about 6 A for eight motors, an estimate) and a power wire to each breakout.
@@ -710,7 +747,6 @@ None.
710
747
  - Two joins at one beam end's two bores (a 2040's `a.1` and `a.2`) now tap both: the second tap was taken for the
711
748
  first, and its screw met an untapped 4.2 mm bore (`fasten`: no hole for M5).
712
749
 
713
-
714
750
  ## 0.7.57: frames in assemblies (Frames 2)
715
751
 
716
752
  ### Added
package/EXAMPLES.md CHANGED
@@ -327,6 +327,9 @@ export function main (v) {
327
327
 
328
328
  `"role": "board"` says the fab makes it: it is not printed, and a list leaves it out of the plastic.
329
329
 
330
+ A board design runs in the design sandbox, with the board engine, as every design does: it can't write files or start
331
+ programs, and the workspace asks for no trust.
332
+
330
333
  ```sh
331
334
  npx cad check home/pad
332
335
  npx cad export home/pad
@@ -6385,9 +6388,10 @@ What the check says, screw by screw:
6385
6388
  of 0.33 N m; the countersunk heads sit in an 89.8° countersink, flush with the back.
6386
6389
  - `fasten.access`: a 2.5 mm hex key reaches each cap head along its axis, and a 2 mm key each countersunk head, with
6387
6390
  nothing within the key's corners for its long arm's 58.5 mm or 52 mm (`hexkey`, ISO 2936).
6388
- - `fasten.load`: with the shelf's 2 kg, the front screws hold 41.4 times the load, the pilot's thread in PLA first;
6389
- the back screws 32.6 times, the screw first (the nut's thread is steel and not checked). Each holds its shear by
6390
- friction 9.5 and 3.6 times over. The torque on the back screws is given (0.3 N m), because the check holds the
6391
+ - `fasten.load`: with the shelf's 2 kg, the front screws are tightened to 0.16 N m, half what the seat under the head
6392
+ takes, and the pilot's thread in PLA holds that preload and the pull 4.3 times over; the back screws hold 32.6 times
6393
+ the load, the screw first (the nut's thread is steel and not checked). Each holds its shear by friction 4.6 and 3.6
6394
+ times over. The torque on the back screws is given (0.3 N m), because the check holds the
6391
6395
  pressure under a flat seat and not yet on a countersink's cone.
6392
6396
 
6393
6397
  Each relation is reckoned as if it held the bracket alone, so the two figures are each the worst case. They rest on
@@ -6407,7 +6411,7 @@ The design rule is the smallest part that carries its load about twice over. By
6407
6411
  |---|---|---|---|---|
6408
6412
  | Bracket's web | At the foot, 23.6 mm in from the shelf's weight, a section 44 mm deep and 3 mm thick | 463 N mm | 0.48 MPa | 81 times |
6409
6413
  | Plate | At the lowest post, 19 mm above its bottom edge, which bears on the wall; the top wall screw pulls 780 / 64 = 12.2 N | 232 N mm | 7.7 MPa | 5 times |
6410
- | Front screws | `fasten.load` | 16.3 N of pull | | 41.4 times |
6414
+ | Front screws | `fasten.load` | 16.3 N of pull and a 266.7 N preload | | 4.3 times |
6411
6415
  | Back screws | `fasten.load` | 65.2 N of pull | | 32.6 times |
6412
6416
 
6413
6417
  The web's section modulus is 3 × 44² / 6 = 968 mm³ and the plate's 20 × 3² / 6 = 30 mm³; each stress is the moment
package/README.md CHANGED
@@ -137,11 +137,12 @@ else the current folder:
137
137
  ```
138
138
 
139
139
  - `printer`: the rule set prints are checked against (bed, overhang, layer, bridge, support_gap); a project.json's
140
- `printer` wins.
140
+ `printer` wins. Either is a rule set's plain name (letters, digits, `-` and `_`; see Variables).
141
141
  - `targets`: optional. `show` puts a model on display: a module of yours, exporting `show({ title, ttl, mesh, card })`
142
142
  (lib/targets.mjs describes it): a smart mirror, a second screen, a slicer. `shorten` stores a link's data for
143
143
  short links (`gist`: a secret Gist, through the `gh` command). Leave one out and `cad show` says so, and links stay
144
- long.
144
+ long. `gist`, spelt exactly so, is the kit's own target; any other name is a module of yours, a path inside the
145
+ workspace, and is asked about once (see Trust).
145
146
  - Designs are ES modules that import JSCAD themselves, so the workspace needs `"type": "module"` and
146
147
  `@jscad/modeling`. Circuit boards need `@rulecad/pcb` as well.
147
148
  - Previews need Chrome or Chromium: `$CAD_CHROME`, else the usual install paths.
@@ -242,6 +243,12 @@ own copy anywhere and name it in `viewUrl`.
242
243
  share-alike) carries over to boards made from it: keep such a rule set apart from your others.
243
244
  - An object or rule set named with a hyphen (`mx-switch`) is read with an underscore in expressions (`mx_switch.housing_top`),
244
245
  since a hyphen there is a minus.
246
+ - Rule-set, project, object, layout, problem and assembly names are plain: letters, digits, `-` and `_`, starting
247
+ with a letter or digit (`x1c`, `m1_6`, `profile-2020-bosch`). Each becomes part of a file's name (`rules/x1c.json`,
248
+ `projects/keyboard/`), so a name with a space, a dot, a slash or a backslash is refused, with the file and field it
249
+ was read from (`projects/p/project.json: the "printer" field "../x" is not a plain name`): a workspace's own files
250
+ cannot make the tool read or write anywhere but where it means to. In `"uses"`, another object is
251
+ `<project>/<object>`, optionally with `:<variant>` and `@<version>`, never a path to a file.
245
252
  - Rules carry `kind`: spec (manufacturer), default (slicer), community (rule of thumb) or measured (your own test
246
253
  print, which beats the rest), plus `source` and `checked`.
247
254
 
@@ -381,16 +388,36 @@ other items' variables, so a keycap can sit exactly where its slot meets the swi
381
388
  can't write or delete files, start programs or workers, or load addons, and it reads only the workspace and the
382
389
  packages designs use, by their real paths (a `node_modules` link spelled through another link, as macOS spells its
383
390
  temporary folders through `/tmp` and `/var`, is refused by name: make the link with the real path). To keep it to making shapes it may import only `@jscad/modeling`, `@rulecad/shapes`,
384
- `@rulecad/flexures`, `@rulecad/gears`, `@rulecad/motors`, `@rulecad/fixings` and files in its own project (no `node:` modules), `fetch` and its kin are gone, and it is
391
+ `@rulecad/flexures`, `@rulecad/gears`, `@rulecad/motors`, `@rulecad/frames`, `@rulecad/fixings` and files in its own project (no `node:` modules).
392
+ An import of a package must lead inside that package: a file of it is named by its path there
393
+ (`@jscad/modeling/src/primitives/index.js`), never with `..`, `.`, `node_modules`, a backslash, `%` or `~`, and the file it finds must be
394
+ the package's own, as rulecad finds it, or one in the project, so no path or link climbs out of it to another file.
395
+ A file of such a package may in turn import only what that package depends on (its own tests' tools are refused).
396
+ `fetch` and its kin are gone, and it is
385
397
  started with none of your environment (no tokens). Those shut the ordinary roads to the network, not every one:
386
398
  before Node 25 the permission model doesn't cover the network, so a design written to get round them might still
387
399
  reach it. Run only designs you trust. It gets its values as data and returns its parts; what it prints
388
- (`console.log`) comes out on stderr. A workspace that trusts its designs sets `"sandbox": false` in cad.config.json
389
- (or `CAD_TRUST=1`). Board designs (engine pcb) run in the tool's process, with the board engine.
390
- - **Trust, asked once:** what a workspace's cad.config.json asks to run outside the sandbox (`"sandbox": false`, a
391
- target that is a module of its own) isn't done until you run `cad trust` in it. That records the folder and what it
392
- asked for in your own list (`~/.config/rulecad/trusted.json`, or `$CAD_TRUSTED`), so a workspace cloned from
393
- elsewhere can't turn the sandbox off on its first command; one that later asks for more is asked again.
400
+ (`console.log`) comes out on stderr. What comes back is checked before it is used, since the design could have
401
+ written it itself: a reply that is not one rulecad makes stops the build with a `design.sandbox` message, and the
402
+ only files written from a reply are the cache's slow stages, each directly in `.cache/stages/` under a name of the
403
+ form the cache makes. A workspace that trusts its designs sets `"sandbox": false` in cad.config.json
404
+ (or `CAD_TRUST=1`). Board designs (`"engine": "pcb"` in the object's JSON) run in the sandbox too, with the board
405
+ engine: the sandbox may then also read `@rulecad/pcb` and the packages it loads, the design reaches the engine only
406
+ as `v.pcb`, and it hands back its board's Circuit JSON, which is checked like the rest of a reply before the tool
407
+ makes the board's solid and files from it. The routes the autorouter finds come back the same way and are written
408
+ to `.cache/routes/`, each under a name of the form the route cache makes. A board build takes a little longer for
409
+ it (a second process starts and loads the engine).
410
+ - **Trust, asked once:** what a workspace asks to run outside the sandbox isn't done until you run `cad trust` in it:
411
+ `"sandbox": false` or a target that is a module of its own (in cad.config.json). Only the kit's own targets, by their
412
+ exact names (today only `gist`), run without asking: every other target name, with or without a slash or an
413
+ extension, is the workspace's own code, and one outside the workspace's folder is never run. `cad trust` records the
414
+ folder and what it asked for, in words such as "designs run outside the sandbox", in your own list
415
+ (`~/.config/rulecad/trusted.json`, or `$CAD_TRUSTED`), so a workspace cloned from elsewhere can't turn the sandbox
416
+ off or run its own code on its first command; one that later asks for more is asked again. A trusted workspace runs
417
+ only its own designs in the tool's process: one from another folder (a path to it, or a link out) is refused. A
418
+ workspace held in memory (`memoryHost`, for tests and later a browser or an editor's server) runs its designs in the
419
+ same sandbox, through the host's `runDesign` (a copy of the design's project in a temporary folder, removed after),
420
+ and in the tool's own process only when `build` is called with `{ trusted: true }`.
394
421
  - **Mistakes are named:** a design that reads a variable that isn't there (`v.widht`) stops with the name it
395
422
  probably meant, not a shape drawn from `undefined`; errors in a design carry its file and line.
396
423
  - **Units:** `cad check` warns where an expression mixes units (millimetres added to degrees, a sine of a length) or
@@ -471,10 +498,10 @@ starts and stops. From that the check says:
471
498
  | `fasten.end` | The far end is a pilot, a hole to tap, a thread drawn to print, an insert's hole or a nut's seat of this thread (a pocket on the far face, or a slot across the screw partway along it, as `v.fixings.nutTrap` cuts), or a clearance hole with `nut`; into a motor, one of its own threaded mounting holes |
472
499
  | `fasten.length` | The length chosen where none is given: the shortest sold length that fits the stack as measured (into a motor, the longest that stops short of the end of its thread). A given length is checked for reaching the far end, bottoming out in a blind hole (1 mm is kept at the tip) and standing more than a diameter proud |
473
500
  | `fasten.engagement` | The thread engaged at the far end against the rule for what it is in: the thread's `pilot_depth` or the engagement rule for the project's material, an insert's length, a nut's height; into a motor, its own thread's depth, and at least one diameter (`engagement.steel`, as `motor.mount` holds it). A short one names the length or the depth that would do |
474
- | `fasten.seat` | The head (or its washer) has a flat seat as wide as itself and square to the screw, read under the head from the part; a countersunk head has a countersink of its angle. It says the force and torque the seat takes on the project's material, and with `torque` holds the pressure against the material's strength and names the washer that would bring it within |
501
+ | `fasten.seat` | The head (or its washer) has a flat seat as wide as itself and square to the screw, read under the head from the part; a countersunk head has a countersink of its angle. It says the force and torque the seat takes on the project's material (and, for a screw in a thread in plastic, the less torque that clamps with half what the thread is estimated to strip at), and with `torque` holds the pressure against the material's strength and names the washer that would bring it within |
475
502
  | `fasten.torque` | A printed bolt given a `torque`: the clamp it is turned to (T = K d F with steel's nut factor, an estimate for a printed thread) held against what the bolt breaks at, about twice over (`fixings.load_margin`); a turn that would break it fails, naming the most to turn it to |
476
503
  | `fasten.access` | A key or driver reaches the head along its axis, in the build pose: a cylinder as wide as the key across its corners, as long as its long arm (both from the `hexkey` set, ISO 2936; a hexagon head's socket adds `hexkey.socket_wall`, an estimate), clear of every other part. A part over the head that goes on after the screw passes, with the step it goes on at: `cad order` puts it after. One that must be there first (it comes earlier in the order, it is one of the joined parts, or it is no step at all) fails by name with how far over the head it is; where a ball-end key tilted up to `hexkey.ball_end_tilt` (25°) clears it, it warns instead |
477
- | `fasten.load` | With `loads` or a motor's torque on the joint: what it holds up (the parts left with no other way to the first item, their masses, the loads hung on them, under the assembly's `gravity`, and the torque of a motor among them), shared between the screws as a group (`screwGroup` of `@rulecad/fixings`: shear by distance from the centroid, pull by a plane through it). The screw that takes the most is held against its proof load, the thread it is in against stripping, and the clamp against slipping, at its preload (`screwLoad`); the margin is how many times the load it holds, and under 2 it warns. With no `torque`, it says the torque that leaves the thread twice the load, within the seat, and `cad order` tightens to that. It names the estimates it rests on (the nut factor, a plastic's shear strength, the friction) |
504
+ | `fasten.load` | With `loads` or a motor's torque on the joint: what it holds up (the parts left with no other way to the first item, their masses, the loads hung on them, under the assembly's `gravity`, and the torque of a motor among them), shared between the screws as a group (`screwGroup` of `@rulecad/fixings`: shear by distance from the centroid, pull by a plane through it). The screw that takes the most is held against its proof load, the thread it is in against stripping, and the clamp against slipping, at its preload (`screwLoad`); the margin is how many times the load it holds (for the thread, how many times the preload and the pull together), and under 2 it warns. With no `torque`, it says the torque that leaves the thread twice the preload and the pull, within half what the seat takes, so never more than half what the thread is estimated to strip at, and `cad order` tightens to that. It names the estimates it rests on (the nut factor, a plastic's shear strength, the friction) |
478
505
 
479
506
  Every finding has `at` (under the head) and `between` (head to tip), so the viewer points at the screw. The screws,
480
507
  nuts, washers and inserts are placed as reference parts from `@rulecad/fixings`: faint in previews, lifted along
@@ -582,7 +609,7 @@ then y, then z, as `rotate` does.
582
609
  true` makes it a ring gear round its pinion. `shift` ([the driver's, this one's]), `pressureAngle` and `backlash` are
583
610
  as `@rulecad/gears` takes them. Each gear is drawn as `v.gears` draws it (axis up its z, first tooth on +x; a rack
584
611
  along its x, teeth up +y) and its joint is anchored at its centre, along its axis. The check gives the ratio, the
585
- contact ratio and the centre distance (`mesh.centre`: closer than the gears need eats their backlash, and past it they jam; further adds backlash),
612
+ contact ratio where the axes are and the centre distance (`mesh.centre`: closer than the gears need eats their backlash, and past it they jam; further adds backlash), the room under the tips (`mesh.tipClearance`, which shifted pairs lose),
586
613
  each placed between the two axes, and measures the pair from its drawn teeth (`mesh.backlash`, `mesh.interference`,
587
614
  kept in `.cache/gears/`); `--sweep` turns the train and looks for teeth that touch. Both gears' axes sit on
588
615
  one part, or on parts held still; planets on a carrier are a `planetary`.
@@ -986,7 +1013,7 @@ address stands for the faces near it, as `item@anchor` does (`"within"`, 10 mm b
986
1013
  A worked check: a 2020 shelf frame, legs 400 mm, a 600 mm front beam joined blind to the legs 390 mm up, 5 kg at its
987
1014
  middle, sags 0.215 mm by hand with the joins rigid (a beam whose ends turn with the corners the legs and the side
988
1015
  beams' twist hold) and 0.310 mm with the blind joins' estimated 1.5 N·m/mrad springs; the solve gives the same to three
989
- figures (`packages/cad/test.mjs`, "frame checks: a shelf frame").
1016
+ figures (`packages/cad/test/frame-checks.test.mjs`, "frame checks: a shelf frame").
990
1017
 
991
1018
  Two more: a 2020 gantry beam, 600 mm, fixed at both ends, with 2.01 kg carried at its middle, rings first at 74.2 Hz;
992
1019
  the formula above gives 74.2 Hz (192 E I / L³ = 461.5 N/mm, M + 0.375 m = 2.1225 kg). An open 2020 cube, 420 mm
@@ -1222,7 +1249,7 @@ limit: it is a bay's to brace, not a beam's to thicken.
1222
1249
 
1223
1250
  Once an assembly is checked, these say how to make it. They all read the assembly itself, so they can't disagree with it.
1224
1251
 
1225
- - `cad order <project>/<assembly>`: the order it goes together in, each step with the part and what fastens it. A `fasten` names its screws on the step where its parts are both there, with the key that turns them and how tight: its `torque`, or the most the seat under the head takes (`2. bracket goes on: bracket fastened to base (2 × M3x10 cap) with a 2.5 mm hex key, to 0.33 N m at most (what the seat takes)`); `--json` gives each as `{ fit, fastener, count, key, tighten: { torque, given } }`, and the build page shows the same. What is not a screw (pins, a clip) is named on a fit that fastens: `"fastener": "push pin", "count": 2` puts it on the shopping list and the step. `--preview` writes a picture of each step to `.preview/`: what's there, and the new part held off along the way it goes on. The order is found by taking the assembly apart, so a part goes in after what it's fastened into, a bearing before its shaft, and a nut trapped by a wall before the neighbour that traps it. A part goes on along a straight line that clears everything already there; which line comes from the part as drawn.
1252
+ - `cad order <project>/<assembly>`: the order it goes together in, each step with the part and what fastens it. A `fasten` names its screws on the step where its parts are both there, with the key that turns them and how tight: its `torque`, or the most the seat under the head takes, held for a screw in a thread in plastic to half what the thread is estimated to strip at (`2. bracket goes on: bracket fastened to base (2 × M3x10 cap) with a 2.5 mm hex key, to 0.27 N m at most (half what the thread strips at)`); `--json` gives each as `{ fit, fastener, count, key, tighten: { torque, given } }` (with `thread: true` where the thread sets the torque, `load: true` where the joint's load does), and the build page shows the same. What is not a screw (pins, a clip) is named on a fit that fastens: `"fastener": "push pin", "count": 2` puts it on the shopping list and the step. `--preview` writes a picture of each step to `.preview/`: what's there, and the new part held off along the way it goes on. The order is found by taking the assembly apart, so a part goes in after what it's fastened into, a bearing before its shaft, and a nut trapped by a wall before the neighbour that traps it. A part goes on along a straight line that clears everything already there; which line comes from the part as drawn.
1226
1253
  - `cad order` on a **frame** (an assembly with `joins`) gives its build from bars to a square frame, in numbered steps:
1227
1254
  1. **Cut** the beams: each mark's count and length, the bars to buy and the cuts on each (the cut list).
1228
1255
  2. **Drill and tap** each mark as its cut-and-drill sheet shows (each mark's work and its sheet's file).
package/bin/cad.mjs CHANGED
@@ -3,11 +3,12 @@
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { execFileSync } from 'node:child_process';
6
- import { fmt, loadRuleSet } from '../lib/rules.mjs';
6
+ import { fmt, loadRuleSet, insideWorkspace } from '../lib/rules.mjs';
7
7
  import { WS, TOOL, paths, config, configError, printerOf, asks, trust, trusted } from '../lib/workspace.mjs';
8
+ import { isPlainName, plainName } from '../lib/names.mjs';
8
9
  import { fromKLE } from '@rulecad/keyboard-layout';
9
10
  import { target, hasTarget } from '../lib/targets.mjs';
10
- import { locate, build, pick, lint, readObject, printer, pcbEngine, objectSets } from '../lib/design.mjs';
11
+ import { locate, locateIn, build, pick, lint, readObject, printer, pcbEngine, objectSets } from '../lib/design.mjs';
11
12
  import { git, tags, bump, bigger, newer, compare, snapshot, materialise, files, prints, printsFile, engineId } from '../lib/versions.mjs';
12
13
  import { check } from '@rulecad/printcheck';
13
14
  import { preview } from '../lib/preview.mjs';
@@ -456,7 +457,7 @@ function ruleSheets(what, names) {
456
457
  if (!name) throw new Error(`usage: cad rules ${what} <set>${what === 'draft' ? ` --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>` : ''}`);
457
458
  if (what === 'draw') { const to = opt('out') || `${name}.svg`; fs.writeFileSync(to, drawSet(name)); return console.log(`drew ${to}: compare it with the datasheet`); }
458
459
  const save = (as, set) => {
459
- const to = path.join(paths.rules ? paths.rules() : path.join(WS, 'rules'), `${as}.json`);
460
+ const to = insideWorkspace(path.join(paths.rules ? paths.rules() : path.join(WS, 'rules'), `${plainName(as, 'rule set name')}.json`)); // (from the command line: never ../, nor through a link out of rules/)
460
461
  if (fs.existsSync(to) && !opt('force')) throw new Error(`${path.relative(WS, to)} already exists (--force replaces it)`);
461
462
  fs.mkdirSync(path.dirname(to), { recursive: true }); fs.writeFileSync(to, JSON.stringify(set, null, 2) + '\n');
462
463
  return to;
@@ -1069,7 +1070,7 @@ function projectFile(project) {
1069
1070
  return pj;
1070
1071
  }
1071
1072
  // The workspace's projects: the folders under projects/ that hold a project.json (not a stray file, such as .DS_Store)
1072
- const projects = () => (fs.existsSync(paths.projects) ? fs.readdirSync(paths.projects).filter((p) => fs.existsSync(path.join(paths.project(p), 'project.json'))).sort() : []);
1073
+ const projects = () => (fs.existsSync(paths.projects) ? fs.readdirSync(paths.projects).filter((p) => isPlainName(p) && fs.existsSync(path.join(paths.project(p), 'project.json'))).sort() : []); // (a folder whose name isn't plain is not a project the tool can name)
1073
1074
 
1074
1075
  async function releaseProject(project) {
1075
1076
  const message = opt('m');
@@ -1077,7 +1078,7 @@ async function releaseProject(project) {
1077
1078
  const dir = paths.project(project), pj = projectFile(project);
1078
1079
  const p = JSON.parse(fs.readFileSync(pj, 'utf8')), manifest = {};
1079
1080
  for (const name of p.objects) {
1080
- const d = locate(`${project}/${name}`), s = await since(d);
1081
+ const d = locateIn(project, name, `projects/${project}/project.json, its "objects"`), s = await since(d);
1081
1082
  if (!s.last) throw new Error(`${name} has no release yet: cad release ${project}/${name} -m "…"`);
1082
1083
  if (s.kind) throw new Error(`${name} has changes since ${s.last.version}: release it first`);
1083
1084
  manifest[name] = s.last.version;
@@ -1112,7 +1113,7 @@ async function releaseProject(project) {
1112
1113
  async function releaseAll(project) {
1113
1114
  const pj = JSON.parse(fs.readFileSync(projectFile(project), 'utf8'));
1114
1115
  const changed = [];
1115
- for (const n of pj.objects) { const d = locate(`${project}/${n}`); if ((await since(d)).kind) changed.push(d); }
1116
+ for (const n of pj.objects) { const d = locateIn(project, n, `projects/${project}/project.json, its "objects"`); if ((await since(d)).kind) changed.push(d); }
1116
1117
  const allowed = new Set([`projects/${project}/project.json`, `projects/${project}/CHANGELOG.md`, `projects/${project}/prints.jsonl`,
1117
1118
  ...changed.flatMap((d) => files(d, readObject(d)))]);
1118
1119
  onlyChanged([...allowed]);
@@ -1148,7 +1149,7 @@ async function status(project) {
1148
1149
  const pj = JSON.parse(fs.readFileSync(projectFile(p), 'utf8'));
1149
1150
  console.log(`${p}${pj.version ? `@${pj.version}` : ''}`);
1150
1151
  for (const name of pj.objects) {
1151
- const s = await since(locate(`${p}/${name}`));
1152
+ const s = await since(locateIn(p, name, `projects/${p}/project.json, its "objects"`));
1152
1153
  console.log(` ${name.padEnd(16)} ${s.last ? s.last.version.padEnd(8) : 'unreleased'} ${s.kind === 'first' ? '' : s.kind ? `changed since: needs a ${s.kind} release` : 'up to date'}`);
1153
1154
  }
1154
1155
  }
@@ -1226,7 +1227,7 @@ async function platesCommand(what, ref) {
1226
1227
  // said once and the rest under the pose's name, after its files' schema check. cad kit counts the same list
1227
1228
  function assemblyFindings(s, a, pose) {
1228
1229
  const poses = pose ? [pose] : Object.keys(s.motion.poses);
1229
- const file = path.join(paths.project(s.project), 'assemblies', `${s.name}.json`), layouts = new Set((a.items || []).map((i) => i.repeat?.layout).filter((l) => l && !l.includes('/')));
1230
+ const file = path.join(paths.project(s.project), 'assemblies', `${s.name}.json`), layouts = new Set((a.items || []).map((i) => i.repeat?.layout).filter((l) => isPlainName(l))); // (object/name is a layout kept in an object; a name that is not plain is refused where the layout is read)
1230
1231
  const schemaProblems = [...(fs.existsSync(file) ? schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'assembly', path.relative(WS, file)) : []),
1231
1232
  ...[...layouts].map((l) => path.join(paths.project(s.project), 'layouts', `${l}.json`)).filter((f) => fs.existsSync(f)).flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'layout', path.relative(WS, f)))];
1232
1233
  let findings = checkAssembly(s);
package/lib/assembly.mjs CHANGED
@@ -27,7 +27,8 @@ import path from 'node:path';
27
27
  import { fileURLToPath } from 'node:url';
28
28
  import { evaluate, loadRuleSet } from './rules.mjs';
29
29
  import { paths, printerOf } from './workspace.mjs';
30
- import { locate, build, readObject, jscad } from './design.mjs';
30
+ import { plainName, isPlainName } from './names.mjs';
31
+ import { locateIn, build, readObject, jscad } from './design.mjs';
31
32
  import { materialise } from './versions.mjs';
32
33
  import { satisfies } from '@rulecad/versions';
33
34
  import { bounds } from '@rulecad/printcheck';
@@ -64,8 +65,8 @@ import { frameSquareChecks, frameBuild } from './framebuild.mjs';
64
65
  let pinning = null; // lib/pins.mjs, loaded with the first assembly whose fits name pins
65
66
  let fastening = null; // lib/fasten.mjs, loaded with the first assembly that has a fasten: the rest start as fast as before
66
67
 
67
- export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
68
- export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
68
+ export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project), 'assemblies', `${plainName(name, 'assembly name')}.json`); };
69
+ export const isAssembly = (ref) => { const [project, name] = String(ref).split('@')[0].split('/'); return isPlainName(project) && isPlainName(name) && host.exists(assemblyPath(`${project}/${name}`)); }; // (a path or a name that climbs is not an assembly: locate() says what it is)
69
70
 
70
71
  export { satisfies }; // from @rulecad/versions
71
72
 
@@ -161,21 +162,21 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
161
162
  if (typeof x !== 'string') return x;
162
163
  try { return num(x); } catch {}
163
164
  if (!it.object || !new RegExp(`\\b${it.id}\\.`).test(x)) return x;
164
- if (!own) { const [r, named] = String(it.object).split(':'), [objName, pin] = r.split('@'), d = locate(`${project}/${objName}`); own = (await build({ ...(pin ? materialise(d, pin) : d), ...((named || it.variant) ? { variant: named || it.variant } : {}) }, base, opts)).values; }
165
+ if (!own) { const [r, named] = String(it.object).split(':'), [objName, pin] = r.split('@'), d = locateIn(project, objName, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`); own = (await build({ ...(pin ? materialise(d, pin) : d), ...((named || it.variant) ? { variant: named || it.variant } : {}) }, base, opts)).values; }
165
166
  return evaluate(x, (n) => { if (n.startsWith(`${it.id}.`)) { const v = own[n.slice(it.id.length + 1)]; if (typeof v === 'number') return v; } return lookup(n); });
166
167
  };
167
168
  const posed = {};
168
169
  for (const [k, x] of Object.entries(ownSets[it.id] || {})) posed[k] = await ownValue(x);
169
170
  const set = { ...(it.set || {}), ...from, ...posed, ...(overrides[it.id] || {}), ...(it.assembly ? {} : extra) };
170
171
  // Built for the mirror, an object's mirror settings win (no legends), so copies that differ only there are one shape
171
- if (opts.mirror && it.object) for (const k of Object.keys(readObject(locate(`${project}/${String(it.object).split(/[:@]/)[0]}`)).mirror || {})) delete set[k];
172
+ if (opts.mirror && it.object) for (const k of Object.keys(readObject(locateIn(project, String(it.object).split(/[:@]/)[0], `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`)).mirror || {})) delete set[k];
172
173
  const sub = it.assembly ? extra : {}; // a component's values go to its items: { cap: { units: 1.5 } }
173
174
  const key = JSON.stringify([it.object, it.variant, it.assembly, set, sub]);
174
175
  if (!built.has(key)) {
175
176
  if (it.assembly) built.set(key, { key, sub: await buildAssembly(`${project}/${it.assembly}`, [...stack, ref], sub, { ...opts, pose: undefined }) }); // a pose names the outer assembly's joints
176
177
  else {
177
178
  const [ref, named] = String(it.object).split(':'), [objName, pin] = ref.split('@'), variant = named || it.variant;
178
- const d = locate(`${project}/${objName}`), at = { ...(pin ? materialise(d, pin) : d), ...(variant ? { variant } : {}) };
179
+ const d = locateIn(project, objName, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`), at = { ...(pin ? materialise(d, pin) : d), ...(variant ? { variant } : {}) };
179
180
  const b = await build(at, set, opts);
180
181
  built.set(key, { key, objName, b, version: pin || b.object.version, variant, role: ['reference', 'board'].includes(b.object.role) ? 'reference' : 'part', set: base }); // a board is made by a fab: checked, never printed. set: what it's made with, as printed (not bent by a pose)
181
182
  }
@@ -193,7 +194,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
193
194
  if (rl) {
194
195
  // A layout file in the project's layouts/, or (older assemblies) object/name: a layout kept in an object's .json
195
196
  const [lp, ln] = String(rl).includes('/') ? String(rl).split('/') : [null, rl];
196
- const data = lp ? readObject(locate(`${project}/${lp}`)).layouts?.[ln] : readLayout(project, ln);
197
+ const data = lp ? readObject(locateIn(project, lp, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "repeat" layout`)).layouts?.[ln] : readLayout(project, ln);
197
198
  if (!data) throw new Error(`item ${it.id}: no layout "${ln}" in ${lp}.json`);
198
199
  const step = num(it.repeat.step);
199
200
  // Values each copy sets: its width, a value for its row (rows: { "cap.row": ["R1", …] }) and constants (each)
@@ -481,7 +482,7 @@ function motionOf(a, placed, num, ref) {
481
482
  // .cache/gears/ by the pair, the centre distance and the gears package's code, as it takes half a second
482
483
  let gearsCode = null;
483
484
  function measured(a, b, centre) {
484
- gearsCode ||= (() => { const dir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))); return fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs').sort().map((f) => fs.readFileSync(path.join(dir, f), 'utf8')).join(''); })();
485
+ gearsCode ||= (() => { const dir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))); return fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs' && !f.startsWith('.')).sort().map((f) => fs.readFileSync(path.join(dir, f), 'utf8')).join(''); })();
485
486
  const file = paths.cache('gears', `${crypto.createHash('sha256').update(JSON.stringify([gearsCode, a, b, +centre.toFixed(6)])).digest('hex')}.json`);
486
487
  if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
487
488
  const r = contact(a, b, { centre, steps: 12 }), keep = { findings: r.findings, backlash: r.backlash, error: r.error };
@@ -766,8 +767,9 @@ export function overlap(ga, gb) {
766
767
  const fell = solid?.stats.fallbacks ?? 0;
767
768
  const v = Math.abs(jscad.measurements.measureVolume((solid ? solid.intersect : jscad.booleans.intersect)(ga, gb)));
768
769
  if (v < 1e-6) return 0;
769
- // JSCAD's answer (no Manifold, or a shape Manifold couldn't read): only if their surfaces really cross, which fit
770
- // says exactly (slower, so only here)
770
+ // JSCAD's answer (no Manifold, or a shape Manifold couldn't read): only if fit says they really run into each other
771
+ // (their surfaces cross, one is inside the other, or they share volume beside a face plane they share: slower, so
772
+ // only here)
771
773
  if (!solid || solid.stats.fallbacks > fell) { const faces = (g) => jscad.geometries.geom3.toPolygons(g).map((q) => q.vertices); if (!overlapAt(faces(ga), faces(gb))) return 0; }
772
774
  return v;
773
775
  }
@@ -790,7 +792,9 @@ function pairOverlap(pa, pb) {
790
792
  if (!pa.hash || !pb.hash) return overlap(solidOf(pa), solidOf(pb));
791
793
  remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
792
794
  const at = (p) => `${p.hash}@${Array.from(p.m || []).map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
793
- const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`crossing+tracks+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
795
+ // (the words in front change whenever the measure does, so an answer remembered from before is measured again: flush
796
+ // overlaps, which fit once read as touching and were remembered as 0, came with #371)
797
+ const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`flush+crossing+tracks+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
794
798
  if (!(k in remembered)) { remembered[k] = overlap(solidOf(pa), solidOf(pb)); fresh++; }
795
799
  return remembered[k];
796
800
  }