@rulecad/cad 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +45 -16
- package/CHANGELOG.md +724 -0
- package/EXAMPLES.md +61 -54
- package/README.md +376 -98
- package/TUTORIAL.md +2 -2
- package/bin/cad.mjs +2664 -541
- package/lib/animate.mjs +173 -49
- package/lib/assembly.mjs +1883 -435
- package/lib/beams.mjs +256 -52
- package/lib/belts.mjs +66 -15
- package/lib/board-work.mjs +12 -0
- package/lib/bought.mjs +309 -53
- package/lib/buildpage.mjs +179 -29
- package/lib/cache-file.mjs +105 -0
- package/lib/carried.mjs +201 -0
- package/lib/clone.mjs +194 -42
- package/lib/code-text.mjs +28 -0
- package/lib/design-imports.mjs +127 -0
- package/lib/design.mjs +871 -147
- package/lib/designshapes.mjs +142 -0
- package/lib/drive.mjs +187 -63
- package/lib/edit.mjs +922 -192
- package/lib/errors.mjs +16 -3
- package/lib/estimates.mjs +51 -0
- package/lib/explain.mjs +62 -13
- package/lib/fasten.mjs +2708 -507
- package/lib/fe-key.mjs +29 -0
- package/lib/fittings.mjs +721 -122
- package/lib/fixings.mjs +38 -13
- package/lib/framebuild.mjs +790 -175
- package/lib/framecheck.mjs +1901 -368
- package/lib/framegen.mjs +108 -22
- package/lib/frameheat.mjs +225 -42
- package/lib/frameprint.mjs +513 -108
- package/lib/frames.mjs +86 -18
- package/lib/framesize.mjs +719 -120
- package/lib/frametip.mjs +235 -0
- package/lib/gait.mjs +135 -23
- package/lib/grip.mjs +62 -13
- package/lib/guides.mjs +1403 -230
- package/lib/host.mjs +129 -23
- package/lib/inplace.mjs +171 -36
- package/lib/jigs.mjs +360 -78
- package/lib/joins.mjs +697 -118
- package/lib/jsonedit.mjs +88 -26
- package/lib/kept.mjs +84 -0
- package/lib/kit.mjs +439 -69
- package/lib/layout.mjs +2 -1
- package/lib/links.mjs +149 -42
- package/lib/list.mjs +334 -64
- package/lib/live-guard.mjs +68 -0
- package/lib/live-shape.mjs +96 -24
- package/lib/live.mjs +189 -59
- package/lib/loads.mjs +597 -136
- package/lib/machine.mjs +372 -74
- package/lib/magnets.mjs +162 -44
- package/lib/measured.mjs +1080 -117
- package/lib/mesh.mjs +526 -119
- package/lib/meshcmd.mjs +215 -60
- package/lib/motors.mjs +1002 -214
- package/lib/motorsvg.mjs +114 -32
- package/lib/names.mjs +18 -1
- package/lib/optimise.mjs +991 -287
- package/lib/order.mjs +515 -114
- package/lib/panels.mjs +482 -94
- package/lib/parts.mjs +81 -23
- package/lib/pins.mjs +163 -44
- package/lib/plates.mjs +223 -35
- package/lib/player.mjs +37 -9
- package/lib/power.mjs +64 -13
- package/lib/preview.mjs +83 -16
- package/lib/profilemeasure.mjs +572 -129
- package/lib/rules.mjs +17 -6
- package/lib/sandbox-hooks.mjs +179 -27
- package/lib/sandbox-lock.mjs +225 -0
- package/lib/sandbox-preload.mjs +2 -2
- package/lib/sandbox-run.mjs +122 -25
- package/lib/sandbox.mjs +667 -75
- package/lib/schema.mjs +42 -11
- package/lib/seats.mjs +227 -49
- package/lib/services.mjs +261 -52
- package/lib/sheet.mjs +963 -179
- package/lib/slotnuts.mjs +213 -34
- package/lib/targets/gist.mjs +4 -1
- package/lib/targets.mjs +22 -4
- package/lib/task.mjs +376 -79
- package/lib/versions.mjs +285 -39
- package/lib/wires.mjs +228 -45
- package/lib/workspace.mjs +200 -14
- package/package.json +19 -19
- package/schemas/assembly.schema.json +2 -2
- package/schemas/project.schema.json +6 -0
- package/templates/coupons/MEASURE.md +109 -0
- package/templates/coupons/assemblies/fixings-test.json +20 -0
- package/templates/coupons/assemblies/slot-test.json +11 -0
- package/templates/coupons/objects/fixings-coupon.js +88 -0
- package/templates/coupons/objects/fixings-coupon.json +26 -0
- package/templates/coupons/objects/holds-coupon.js +130 -0
- package/templates/coupons/objects/holds-coupon.json +42 -0
- package/templates/coupons/objects/slot-coupon.js +89 -0
- package/templates/coupons/objects/slot-coupon.json +29 -0
- package/templates/coupons/project.json +10 -0
package/lib/clone.mjs
CHANGED
|
@@ -10,7 +10,8 @@ import { pcbEngine } from './design.mjs';
|
|
|
10
10
|
|
|
11
11
|
const today = () => new Date().toISOString().slice(0, 10);
|
|
12
12
|
// Licences that ask boards made from the source to stay under them (or forbid that use): said when cloning
|
|
13
|
-
export const reciprocal = (s) =>
|
|
13
|
+
export const reciprocal = (s) =>
|
|
14
|
+
/CERN-OHL-S|CERN Open Hardware Licence Version 2 - Strongly|GPL|share-?alike|\bSA\b/i.test(String(s || ''));
|
|
14
15
|
export const limiting = (s) => /\b(NC|ND)\b|non-?commercial|no-?deriv/i.test(String(s || ''));
|
|
15
16
|
|
|
16
17
|
// A GitHub file link (github.com/<owner>/<repo>/blob/<ref>/<path>) -> { owner, repo, ref, file }, else null
|
|
@@ -30,37 +31,118 @@ async function getJSON(url) {
|
|
|
30
31
|
async function fetchBoard(ref, o) {
|
|
31
32
|
const gh = githubFile(ref);
|
|
32
33
|
if (!gh) {
|
|
33
|
-
if (!fs.existsSync(ref))
|
|
34
|
-
|
|
34
|
+
if (!fs.existsSync(ref))
|
|
35
|
+
throw new Error(
|
|
36
|
+
`no file ${ref}: give a .kicad_pcb file, or a GitHub link to one (https://github.com/<owner>/<repo>/blob/<branch>/<path>.kicad_pcb)`,
|
|
37
|
+
);
|
|
38
|
+
return {
|
|
39
|
+
text: fs.readFileSync(ref, 'utf8'),
|
|
40
|
+
source: o.source || path.basename(ref),
|
|
41
|
+
licence: o.licence || null,
|
|
42
|
+
dir: path.dirname(path.resolve(ref)),
|
|
43
|
+
};
|
|
35
44
|
}
|
|
36
45
|
const base = `https://api.github.com/repos/${gh.owner}/${gh.repo}`;
|
|
37
46
|
const commit = (await getJSON(`${base}/commits/${encodeURIComponent(gh.ref)}`)).sha;
|
|
38
|
-
const raw = await fetch(
|
|
47
|
+
const raw = await fetch(
|
|
48
|
+
`https://raw.githubusercontent.com/${gh.owner}/${gh.repo}/${commit}/${gh.file.split('/').map(encodeURIComponent).join('/')}`,
|
|
49
|
+
);
|
|
39
50
|
if (!raw.ok) throw new Error(`couldn't download ${gh.file} at ${commit.slice(0, 7)} (${raw.status})`);
|
|
40
51
|
let licence = o.licence || null;
|
|
41
52
|
if (!licence) {
|
|
42
53
|
const l = await getJSON(`${base}/license?ref=${commit}`).catch(() => null);
|
|
43
|
-
const first = l?.content
|
|
54
|
+
const first = l?.content
|
|
55
|
+
? Buffer.from(l.content, 'base64')
|
|
56
|
+
.toString('utf8')
|
|
57
|
+
.split('\n')
|
|
58
|
+
.map((s) => s.trim())
|
|
59
|
+
.find(Boolean)
|
|
60
|
+
: null;
|
|
44
61
|
licence = l?.license?.spdx_id && l.license.spdx_id !== 'NOASSERTION' ? l.license.spdx_id : first;
|
|
45
62
|
}
|
|
46
|
-
return {
|
|
63
|
+
return {
|
|
64
|
+
text: await raw.text(),
|
|
65
|
+
source: `https://github.com/${gh.owner}/${gh.repo}/blob/${commit}/${gh.file}`,
|
|
66
|
+
licence,
|
|
67
|
+
commit,
|
|
68
|
+
github: { ...gh, commit },
|
|
69
|
+
};
|
|
47
70
|
}
|
|
48
71
|
|
|
49
72
|
// ---- the parts' 3D models ----
|
|
50
73
|
// KiCad's own library, by the version its path variable names (6 and later name it; older boards say KISYS3DMOD)
|
|
51
74
|
const KICAD = { 6: '6.0.11', 7: '7.0.11', 8: '8.0.8' };
|
|
52
|
-
const KICAD_LICENCE =
|
|
53
|
-
const fetchText = async (url) => {
|
|
75
|
+
const KICAD_LICENCE = "CC-BY-SA-4.0 with the KiCad libraries exception (designs using the models aren't bound by it)";
|
|
76
|
+
const fetchText = async (url) => {
|
|
77
|
+
const r = await fetch(url);
|
|
78
|
+
if (!r.ok) throw new Error(`${r.status} for ${url}`);
|
|
79
|
+
return r.text();
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// Whether file is in the folder dir, or a folder in it (by its name, and by where a link in the way leads)
|
|
83
|
+
function inside(dir, file) {
|
|
84
|
+
const within = (d, f) => {
|
|
85
|
+
const rel = nodePath.relative(d, f);
|
|
86
|
+
return rel !== '' && rel !== '..' && !rel.startsWith(`..${nodePath.sep}`) && !nodePath.isAbsolute(rel);
|
|
87
|
+
};
|
|
88
|
+
if (!within(dir, file)) return false;
|
|
89
|
+
try {
|
|
90
|
+
return within(fs.realpathSync(dir), fs.realpathSync(file));
|
|
91
|
+
} catch {
|
|
92
|
+
return true; // (no such file yet: reading it finds nothing, and says so)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// base + rest, refused if the address it makes leads out of base. (A web address reads "%2e%2e" and a backslash as
|
|
97
|
+
// ".." and "/", so a path the checks on its words pass can still climb to another repository, or out of KiCad's
|
|
98
|
+
// library, and be copied in under a licence that isn't its own.)
|
|
99
|
+
function under(base, rest, what) {
|
|
100
|
+
const url = base + rest;
|
|
101
|
+
if (!new URL(url).pathname.startsWith(new URL(base).pathname))
|
|
102
|
+
throw new Error(`its path leaves ${what}, so cad clone doesn't follow it`);
|
|
103
|
+
return url;
|
|
104
|
+
}
|
|
54
105
|
|
|
55
|
-
|
|
56
|
-
|
|
106
|
+
/**
|
|
107
|
+
* Where a model's file comes from: { url, licence } (or { file } for a board read from a file), or null. A path that
|
|
108
|
+
* leads out of the board's folder, its repository or KiCad's library is refused.
|
|
109
|
+
* @param {string} path the model's path as the board gives it
|
|
110
|
+
* @param {{ dir?: string, github?: { owner: string, repo: string, commit: string, file: string }, licence?: string }} got where the board came from
|
|
111
|
+
* @returns {Promise<{ url?: string, file?: string, dir?: string, licence?: string | null, kicad?: boolean } | null>}
|
|
112
|
+
*/
|
|
113
|
+
export async function modelSource(path, got) {
|
|
57
114
|
const kicad = path.match(/^\$\{(?:KICAD(\d+)_3DMODEL_DIR|KISYS3DMOD)\}\/(.+)$/);
|
|
58
|
-
if (kicad)
|
|
115
|
+
if (kicad)
|
|
116
|
+
return {
|
|
117
|
+
url: under(
|
|
118
|
+
`https://gitlab.com/kicad/libraries/kicad-packages3D/-/raw/${KICAD[kicad[1]] ?? KICAD[6]}/`,
|
|
119
|
+
kicad[2],
|
|
120
|
+
"KiCad's model library",
|
|
121
|
+
),
|
|
122
|
+
licence: KICAD_LICENCE,
|
|
123
|
+
kicad: true,
|
|
124
|
+
};
|
|
59
125
|
const own = path.match(/^\$\{KIPRJMOD\}\/(.+)$/);
|
|
60
126
|
if (!own) return null;
|
|
61
|
-
|
|
127
|
+
// A board's own models are in its folder: a path that climbs out of it (../, or one from the top of the disc) is
|
|
128
|
+
// refused, so a board from elsewhere can't have cad clone copy a file of this computer into the workspace. (From
|
|
129
|
+
// GitHub, the path may lead anywhere in the board's repository, which is fetched from GitHub, never from this disc.)
|
|
130
|
+
if (!got.github) {
|
|
131
|
+
if (!got.dir) return null;
|
|
132
|
+
const file = nodePath.resolve(got.dir, own[1]);
|
|
133
|
+
if (!inside(got.dir, file)) throw new Error(`its path leaves the board's folder, so cad clone doesn't follow it`);
|
|
134
|
+
return { file, dir: got.dir };
|
|
135
|
+
}
|
|
62
136
|
// In the source's repository, next to its board; a path into a submodule goes on in the submodule's repository
|
|
63
|
-
const { owner, repo, commit, file } = got.github,
|
|
137
|
+
const { owner, repo, commit, file } = got.github,
|
|
138
|
+
parts = nodePath.posix.normalize(nodePath.posix.join(nodePath.posix.dirname(file), own[1])).split('/');
|
|
139
|
+
if (parts[0] === '..' || parts[0] === '')
|
|
140
|
+
throw new Error(`its path leaves the board's repository, so cad clone doesn't follow it`);
|
|
141
|
+
const inRepo = under(
|
|
142
|
+
`https://raw.githubusercontent.com/${owner}/${repo}/${commit}/`,
|
|
143
|
+
parts.join('/'),
|
|
144
|
+
"the board's repository",
|
|
145
|
+
);
|
|
64
146
|
const api = (o, r, x) => getJSON(`https://api.github.com/repos/${o}/${r}/${x}`);
|
|
65
147
|
const top = await api(owner, repo, `contents/${encodeURIComponent(parts[0])}?ref=${commit}`).catch(() => null);
|
|
66
148
|
const licenceOf = async (o, r) => (await api(o, r, 'license').catch(() => null))?.license?.spdx_id;
|
|
@@ -68,37 +150,76 @@ async function modelSource(path, got) {
|
|
|
68
150
|
const m = top.submodule_git_url.match(/github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/);
|
|
69
151
|
if (!m) return null;
|
|
70
152
|
const lic = await licenceOf(m[1], m[2]);
|
|
71
|
-
return {
|
|
153
|
+
return {
|
|
154
|
+
url: under(
|
|
155
|
+
`https://raw.githubusercontent.com/${m[1]}/${m[2]}/${top.sha}/`,
|
|
156
|
+
parts.slice(1).join('/'),
|
|
157
|
+
"the board's repository",
|
|
158
|
+
),
|
|
159
|
+
licence: lic && lic !== 'NOASSERTION' ? lic : null,
|
|
160
|
+
};
|
|
72
161
|
}
|
|
73
|
-
return {
|
|
162
|
+
return {
|
|
163
|
+
url: inRepo,
|
|
164
|
+
licence: got.licence,
|
|
165
|
+
};
|
|
74
166
|
}
|
|
75
167
|
|
|
76
168
|
// Each model the circuit's parts name, fetched once into the workspace's models/ (a mesh, where its licence lets it be
|
|
77
169
|
// shared and it comes as VRML) or kept as its size (a STEP file, or a shape with no licence): circuit.models[path]
|
|
78
170
|
async function fetchModels(circuit, got, { wrlMesh, stepBounds }, notes) {
|
|
79
|
-
const out = {},
|
|
171
|
+
const out = {},
|
|
172
|
+
paths = [...new Set(circuit.parts.filter((p) => p.model).map((p) => p.model.path))];
|
|
80
173
|
for (const path of paths) {
|
|
81
174
|
try {
|
|
82
175
|
const src = await modelSource(path, got);
|
|
83
|
-
if (!src) {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
176
|
+
if (!src) {
|
|
177
|
+
notes.push(`no 3D model for ${path}: its path isn't one cad clone can follow`);
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
const name = path
|
|
181
|
+
.split('/')
|
|
182
|
+
.pop()
|
|
183
|
+
.replace(/\.(step|stp|wrl)$/i, ''),
|
|
184
|
+
dir = src.kicad ? `kicad/${path.split('/').slice(-2, -1)[0]}` : 'source';
|
|
185
|
+
const read = async (ext) => {
|
|
186
|
+
if (!src.file) return fetchText(src.url.replace(/\.[^./]+$/, ext));
|
|
187
|
+
const f = src.file.replace(/\.[^.]+$/, ext);
|
|
188
|
+
// (and where a link in the board's folder leads: it must stay in the folder too)
|
|
189
|
+
if (!inside(src.dir, f)) throw new Error(`its path leaves the board's folder, so cad clone doesn't follow it`);
|
|
190
|
+
return fs.promises.readFile(f, 'utf8');
|
|
191
|
+
};
|
|
192
|
+
if (src.licence || src.file) {
|
|
193
|
+
// VRML where there is one (KiCad's library has both): a mesh
|
|
87
194
|
const wrl = /\.wrl$/i.test(path) || src.kicad ? await read('.wrl').catch(() => null) : null;
|
|
88
195
|
if (wrl) {
|
|
89
196
|
const triangles = wrlMesh(wrl).map((t) => t.map((v) => v.map((n) => Math.round(n * 1e3) / 1e3)));
|
|
90
197
|
const file = `models/${dir}/${name}.json`;
|
|
91
198
|
fs.mkdirSync(nodePath.join(WS, nodePath.dirname(file)), { recursive: true });
|
|
92
|
-
fs.writeFileSync(
|
|
199
|
+
fs.writeFileSync(
|
|
200
|
+
nodePath.join(WS, file),
|
|
201
|
+
JSON.stringify({ source: src.url || src.file, licence: src.licence, triangles }),
|
|
202
|
+
);
|
|
93
203
|
out[path] = { mesh: file, licence: src.licence };
|
|
94
204
|
continue;
|
|
95
205
|
}
|
|
96
206
|
}
|
|
97
207
|
const step = await read(nodePath.extname(path) || '.step').catch(() => read('.step'));
|
|
98
208
|
const box = stepBounds(step);
|
|
99
|
-
if (!box) {
|
|
100
|
-
|
|
101
|
-
|
|
209
|
+
if (!box) {
|
|
210
|
+
notes.push(`no 3D model for ${name}: its file has no points to measure`);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
out[path] = {
|
|
214
|
+
box,
|
|
215
|
+
...(src.licence ? { licence: src.licence } : {}),
|
|
216
|
+
size_only: src.licence
|
|
217
|
+
? 'a STEP model: drawn as the box round it'
|
|
218
|
+
: 'no licence: only its size is used, drawn as a box',
|
|
219
|
+
};
|
|
220
|
+
} catch (e) {
|
|
221
|
+
notes.push(`no 3D model for ${path.split('/').pop()}: ${e.message}`);
|
|
222
|
+
}
|
|
102
223
|
}
|
|
103
224
|
return out;
|
|
104
225
|
}
|
|
@@ -108,43 +229,74 @@ async function fetchModels(circuit, got, { wrlMesh, stepBounds }, notes) {
|
|
|
108
229
|
* can't carry yet, and what the licence asks. o: { source, licence, force }.
|
|
109
230
|
*/
|
|
110
231
|
export async function cloneBoard(ref, name, o = {}) {
|
|
111
|
-
if (!ref || !/^[a-z][a-z0-9_]*$/.test(name || ''))
|
|
232
|
+
if (!ref || !/^[a-z][a-z0-9_]*$/.test(name || ''))
|
|
233
|
+
throw new Error(
|
|
234
|
+
'usage: cad clone <board.kicad_pcb | GitHub link> <name> [--source <link>] [--licence <licence>] [--force] (name: lower case, digits and _)',
|
|
235
|
+
);
|
|
112
236
|
const to = path.join(WS, 'rules', `${name}.json`);
|
|
113
237
|
if (fs.existsSync(to) && !o.force) throw new Error(`rules/${name}.json already exists (--force to replace it)`);
|
|
114
238
|
const { fromKicadPcb, clone, learnPlacement, wrlMesh, stepBounds } = await pcbEngine();
|
|
115
239
|
if (!learnPlacement) throw new Error('cad clone needs @rulecad/pcb 0.3.8 or later: npm install @rulecad/pcb@latest');
|
|
116
240
|
const got = await fetchBoard(ref, o);
|
|
117
241
|
const circuit = fromKicadPcb(got.text);
|
|
118
|
-
circuit.source = {
|
|
242
|
+
circuit.source = {
|
|
243
|
+
...circuit.source,
|
|
244
|
+
from: got.source,
|
|
245
|
+
...(got.commit ? { commit: got.commit } : {}),
|
|
246
|
+
read: today(),
|
|
247
|
+
};
|
|
119
248
|
circuit.placement = learnPlacement(circuit); // which small parts stay by which pins: edit max to be stricter or freer
|
|
120
249
|
const modelNotes = [];
|
|
121
250
|
if (!o.noModels && wrlMesh) circuit.models = await fetchModels(circuit, got, { wrlMesh, stepBounds }, modelNotes);
|
|
122
|
-
const extra = {
|
|
251
|
+
const extra = {
|
|
252
|
+
kind: 'derived',
|
|
253
|
+
source: got.source,
|
|
254
|
+
...(got.licence ? { licence: got.licence } : {}),
|
|
255
|
+
checked: today(),
|
|
256
|
+
};
|
|
123
257
|
const rule = (value, unit, text) => ({ value, ...(unit ? { unit } : {}), rule: text, ...extra });
|
|
124
258
|
const rules = {
|
|
125
|
-
width: rule(circuit.width, 'mm',
|
|
126
|
-
height: rule(circuit.height, 'mm',
|
|
127
|
-
layers: rule(circuit.layers, null, `Copper layers on the source board (${circuit.copper.join(', ')})`)
|
|
259
|
+
width: rule(circuit.width, 'mm', "The source board's width, across its outline"),
|
|
260
|
+
height: rule(circuit.height, 'mm', "The source board's height, across its outline"),
|
|
261
|
+
layers: rule(circuit.layers, null, `Copper layers on the source board (${circuit.copper.join(', ')})`),
|
|
128
262
|
};
|
|
129
|
-
if (circuit.thickness) rules.thickness = rule(circuit.thickness, 'mm',
|
|
263
|
+
if (circuit.thickness) rules.thickness = rule(circuit.thickness, 'mm', "The source board's thickness");
|
|
130
264
|
const doc = `Cloned from ${got.source} by cad clone: the circuit of a published board (its parts, pads, nets, planes and outline), for @rulecad/pcb's clone() to redraw by rules.${got.licence ? ` Licence: ${got.licence}.` : ' Licence unknown: find it before sharing anything made from this.'}${reciprocal(got.licence) ? ' Boards made from it must be shared under the same licence, with their design files.' : ''}`;
|
|
131
265
|
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
132
|
-
fs.writeFileSync(
|
|
266
|
+
fs.writeFileSync(
|
|
267
|
+
to,
|
|
268
|
+
`${JSON.stringify({ _doc: doc, name, ...(got.licence ? { licence: got.licence } : {}), rules, circuit }, null, 1)}\n`,
|
|
269
|
+
);
|
|
133
270
|
|
|
134
|
-
const nets = Object.keys(circuit.nets).length,
|
|
135
|
-
|
|
271
|
+
const nets = Object.keys(circuit.nets).length,
|
|
272
|
+
planes = Object.keys(circuit.planes);
|
|
273
|
+
console.log(
|
|
274
|
+
`made ${path.relative(process.cwd(), to)}: ${circuit.parts.length} parts, ${nets} nets, ${circuit.width} × ${circuit.height} mm, ${circuit.layers} copper layers${planes.length ? `, planes ${planes.join(' ')}` : ''}`,
|
|
275
|
+
);
|
|
136
276
|
console.log(` from ${got.source}`);
|
|
137
|
-
console.log(
|
|
277
|
+
console.log(
|
|
278
|
+
` placement: ${circuit.placement.length} small parts kept near the pins they serve (circuit.placement: edit max to change how near)`,
|
|
279
|
+
);
|
|
138
280
|
if (circuit.models) {
|
|
139
|
-
const all = Object.values(circuit.models),
|
|
140
|
-
|
|
281
|
+
const all = Object.values(circuit.models),
|
|
282
|
+
boxes = all.filter((m) => m.box).length;
|
|
283
|
+
console.log(
|
|
284
|
+
` 3D models: ${all.length - boxes} as meshes (in models/), ${boxes} as boxes the size of the part${all.some((m) => /no licence/.test(m.size_only || '')) ? ' (some have no licence: only their size is used)' : ''}`,
|
|
285
|
+
);
|
|
141
286
|
}
|
|
142
287
|
for (const n of modelNotes) console.log(` note: ${n}`);
|
|
143
|
-
if (!circuit.outline) console.log(
|
|
288
|
+
if (!circuit.outline) console.log(" note: the outline isn't one closed shape: designs get its bounds");
|
|
144
289
|
for (const n of clone(circuit).notes) console.log(` note: ${n}`);
|
|
145
|
-
if (!got.licence)
|
|
146
|
-
|
|
147
|
-
else if (
|
|
148
|
-
|
|
290
|
+
if (!got.licence)
|
|
291
|
+
console.log(" ! no licence given (--licence): find the source's licence before sharing anything made from it");
|
|
292
|
+
else if (limiting(got.licence))
|
|
293
|
+
console.log(` ! licence "${got.licence}" limits what you may make from this: read it before using the circuit`);
|
|
294
|
+
else if (reciprocal(got.licence))
|
|
295
|
+
console.log(
|
|
296
|
+
` ! licence "${got.licence}" is reciprocal: boards made from this must be shared under it too, with their design files. Keep this rule set apart from rules under other licences`,
|
|
297
|
+
);
|
|
298
|
+
console.log(
|
|
299
|
+
` use it in a board: clone(v.${name}.circuit) from @rulecad/pcb gives the parts and nets, each where the source put it`,
|
|
300
|
+
);
|
|
149
301
|
return { to, circuit };
|
|
150
302
|
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Code as it runs, for the keys of cad's slow caches (an optimisation's densities, a fitting's finite-element results):
|
|
2
|
+
// a module's text without its lines that are only a comment (// ..., or a /* ... */ or /** ... */ block) and without
|
|
3
|
+
// blank lines. Rewording a comment, or spacing the code out, then keeps a key and the minutes of work kept under it;
|
|
4
|
+
// any change to the code itself moves it. A comment after code on the same line stays in: telling it apart from a
|
|
5
|
+
// string that holds // would take a parser, and a key that moves now and then is only slower, never wrong.
|
|
6
|
+
// (@rulecad/frames has its own copy for fittingCode, as it runs in a browser and does not depend on cad.)
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A module's code without the lines that are only a comment and without blank lines.
|
|
10
|
+
* @param {string} text the module's text, or a function's (fn.toString())
|
|
11
|
+
* @returns {string}
|
|
12
|
+
*/
|
|
13
|
+
export function codeOnly(text) {
|
|
14
|
+
let inComment = false;
|
|
15
|
+
return String(text)
|
|
16
|
+
.split('\n')
|
|
17
|
+
.filter((line) => {
|
|
18
|
+
const t = line.trim();
|
|
19
|
+
// (a block comment's lines, kept only where code follows its end on the same line)
|
|
20
|
+
if (inComment || t.startsWith('/*')) {
|
|
21
|
+
const end = t.indexOf('*/', inComment ? 0 : 2);
|
|
22
|
+
inComment = end < 0;
|
|
23
|
+
return !inComment && t.slice(end + 2).trim() !== '';
|
|
24
|
+
}
|
|
25
|
+
return t !== '' && !t.startsWith('//');
|
|
26
|
+
})
|
|
27
|
+
.join('\n');
|
|
28
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// A design run in the tool's own process (a trusted workspace's), loaded so that the files it imports are known and
|
|
2
|
+
// never stale. Node keeps every module it has loaded for as long as the process runs, by its URL: a design is loaded
|
|
3
|
+
// by a URL that changes with its text, but a helper it imports ('./box.js') would be found by its plain URL and so kept
|
|
4
|
+
// as first loaded, however it is edited after (a live view runs for hours). So an import hook marks each file a design
|
|
5
|
+
// reaches by a path (not a package) with the design's load: `?rulecad-design=<token>`, the token a hash of the design's
|
|
6
|
+
// text and of the files it imported the last time. Edit a helper and the token changes, so the design and its helpers
|
|
7
|
+
// are loaded afresh. The hook notes those files too, for the build's cache (design.mjs): the tool learns them by
|
|
8
|
+
// importing a module the hook makes up, which works the same whether the hook runs in this thread or, on older Node,
|
|
9
|
+
// in a worker of its own.
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import * as nodeModule from 'node:module';
|
|
13
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
14
|
+
|
|
15
|
+
const MARK = 'rulecad-design',
|
|
16
|
+
LIST = 'rulecad-imports:'; // `${LIST}${token}?n=<count>`: the files a load imported, as a module of the hook's making
|
|
17
|
+
|
|
18
|
+
// ---- the hook (in this thread, or in the hooks' worker on older Node) ----
|
|
19
|
+
const imported = new Map(); // token -> Set of file: URLs
|
|
20
|
+
const tokenOf = (url) => {
|
|
21
|
+
if (!url?.startsWith('file:')) return null;
|
|
22
|
+
return new URL(url).searchParams.get(MARK);
|
|
23
|
+
};
|
|
24
|
+
const byPath = (spec) =>
|
|
25
|
+
spec.startsWith('./') || spec.startsWith('../') || spec.startsWith('/') || spec.startsWith('file:');
|
|
26
|
+
function mark(spec, context, r) {
|
|
27
|
+
const token = tokenOf(context.parentURL);
|
|
28
|
+
if (!token || !byPath(spec) || !r.url.startsWith('file:')) return r;
|
|
29
|
+
const u = new URL(r.url);
|
|
30
|
+
if (u.pathname.split('/').some((s) => s.toLowerCase() === 'node_modules')) return r; // (a package's file: left as it is)
|
|
31
|
+
const plain = new URL(u.href);
|
|
32
|
+
plain.search = plain.hash = '';
|
|
33
|
+
if (!imported.has(token)) imported.set(token, new Set());
|
|
34
|
+
imported.get(token).add(plain.href);
|
|
35
|
+
u.searchParams.set(MARK, token);
|
|
36
|
+
return { ...r, url: u.href };
|
|
37
|
+
}
|
|
38
|
+
/** The import hook's resolve, in this thread (module.registerHooks). */
|
|
39
|
+
export function resolveHook(spec, context, next) {
|
|
40
|
+
if (spec.startsWith(LIST)) return { url: spec, shortCircuit: true };
|
|
41
|
+
return mark(spec, context, next(spec, context));
|
|
42
|
+
}
|
|
43
|
+
/** The import hook's resolve, in a worker (module.register). */
|
|
44
|
+
export async function resolve(spec, context, next) {
|
|
45
|
+
if (spec.startsWith(LIST)) return { url: spec, shortCircuit: true };
|
|
46
|
+
return mark(spec, context, await next(spec, context));
|
|
47
|
+
}
|
|
48
|
+
/** The import hook's load, in this thread: the made-up module that lists a load's files. */
|
|
49
|
+
export function loadHook(url, context, next) {
|
|
50
|
+
if (!url.startsWith(LIST)) return next(url, context);
|
|
51
|
+
const token = url.slice(LIST.length).split('?')[0];
|
|
52
|
+
return {
|
|
53
|
+
format: 'module',
|
|
54
|
+
source: `export default ${JSON.stringify([...(imported.get(token) || [])])};`,
|
|
55
|
+
shortCircuit: true,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/** The import hook's load, in a worker. */
|
|
59
|
+
export async function load(url, context, next) {
|
|
60
|
+
return loadHook(url, context, next);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---- the tool's side ----
|
|
64
|
+
let hooked = false;
|
|
65
|
+
function hook() {
|
|
66
|
+
if (hooked) return;
|
|
67
|
+
hooked = true;
|
|
68
|
+
if (nodeModule.registerHooks) nodeModule.registerHooks({ resolve: resolveHook, load: loadHook });
|
|
69
|
+
else nodeModule.register(import.meta.url);
|
|
70
|
+
}
|
|
71
|
+
// For each design file: the token it was last loaded by and the files that load imported (paths)
|
|
72
|
+
const loads = new Map();
|
|
73
|
+
let asked = 0;
|
|
74
|
+
const textOf = (f) => {
|
|
75
|
+
try {
|
|
76
|
+
return fs.readFileSync(f, 'utf8');
|
|
77
|
+
} catch {
|
|
78
|
+
return '\u0000missing';
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// The files a load has imported so far, as the hook noted them (absolute paths)
|
|
83
|
+
const listed = async (token) =>
|
|
84
|
+
(await import(`${LIST}${token}?n=${asked++}`)).default.map((u) => fileURLToPath(u)).sort();
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* A design's module, loaded afresh when it or a file it imports has changed since its last load here.
|
|
88
|
+
* @param {string} file the design's .js
|
|
89
|
+
* @returns {Promise<any>} the module
|
|
90
|
+
*/
|
|
91
|
+
export async function loadDesign(file) {
|
|
92
|
+
hook();
|
|
93
|
+
const last = loads.get(file);
|
|
94
|
+
// (after a load that failed, a fresh token whatever the files say: Node keeps a failed load's error by its URL too,
|
|
95
|
+
// and the fault may have been a file that wasn't there, which no text of the last load's files shows)
|
|
96
|
+
const token = crypto
|
|
97
|
+
.createHash('sha256')
|
|
98
|
+
.update(
|
|
99
|
+
JSON.stringify([textOf(file), ...(last?.imports || []).map((f) => [f, textOf(f)]), last?.failed ? asked : null]),
|
|
100
|
+
)
|
|
101
|
+
.digest('hex')
|
|
102
|
+
.slice(0, 32);
|
|
103
|
+
if (last?.token === token && !last.failed) return import(last.url);
|
|
104
|
+
const url = new URL(pathToFileURL(file).href);
|
|
105
|
+
url.searchParams.set(MARK, token);
|
|
106
|
+
try {
|
|
107
|
+
const module = await import(url.href);
|
|
108
|
+
loads.set(file, { token, url: url.href, imports: await listed(token) });
|
|
109
|
+
return module;
|
|
110
|
+
} catch (e) {
|
|
111
|
+
loads.set(file, { token, url: url.href, imports: await listed(token), failed: true });
|
|
112
|
+
throw e;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The files of its own (not a package's) a design has imported since it was loaded, its main's own imports included:
|
|
118
|
+
* absolute paths. Asked after main has run.
|
|
119
|
+
* @param {string} file the design's .js
|
|
120
|
+
* @returns {Promise<string[]>}
|
|
121
|
+
*/
|
|
122
|
+
export async function importsOf(file) {
|
|
123
|
+
const last = loads.get(file);
|
|
124
|
+
if (!last) return [];
|
|
125
|
+
last.imports = await listed(last.token);
|
|
126
|
+
return last.imports;
|
|
127
|
+
}
|