@rulecad/pcb 0.4.0 → 0.5.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 (3) hide show
  1. package/circuit.mjs +11 -4
  2. package/package.json +1 -1
  3. package/pcb.mjs +69 -25
package/circuit.mjs CHANGED
@@ -40,14 +40,16 @@ import { fp } from '@tscircuit/footprinter';
40
40
  import { symbols } from 'schematic-symbols';
41
41
 
42
42
  const SUB = 'subcircuit_source_group_0';
43
- const PASTE = 0.7;
43
+ // Solder paste: each side of an SMD pad's opening this share of the pad's (an aperture about 10% smaller than its pad, as
44
+ // stencil guides give for ordinary pads: 81% of the area; 0.7, tscircuit's, left 49%)
45
+ const PASTE = 0.9;
44
46
  // Quarter turns, counter-clockwise, as exact cosines and sines (no rounding error in pad positions)
45
47
  const QUARTER = { 0: [1, 0], 90: [0, 1], 180: [-1, 0], 270: [0, -1] };
46
48
  function quarter(r = 0) {
47
49
  const t = QUARTER[((r % 360) + 360) % 360];
48
50
  if (!t) throw new Error(`a part's rotation is ${r}°: boards take 0, 90, 180 or 270`);
49
51
  return t;
50
- } // solder paste, as a share of an SMD pad (what tscircuit uses)
52
+ }
51
53
  // The board's manufacturing minimums (mm): tscircuit's defaults, within what common fabs make. The router keeps to them.
52
54
  const FAB_MINIMUMS = { min_trace_width: 0.1, min_via_hole_diameter: 0.2, min_via_pad_diameter: 0.3, min_via_hole_edge_to_via_hole_edge_clearance: 0.1,
53
55
  min_trace_to_hole_edge_clearance: 0.2, min_trace_to_pad_edge_clearance: 0.1, min_pad_edge_to_pad_edge_clearance: 0.1,
@@ -112,7 +114,8 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
112
114
  for (const part of board.parts) {
113
115
  const comp = add('source_component', { ftype: part.ftype, name: part.name, manufacturer_part_number: part.mpn,
114
116
  ...(part.lcsc ? { supplier_part_numbers: { jlcpcb: [part.lcsc] } } : {}), ...(part.value ? { display_value: part.value } : {}), ...(part.bom === false ? { exclude_from_bom: true } : {}),
115
- are_pins_interchangeable: part.ftype === 'simple_switch', source_group_id: 'source_group_0', subcircuit_id: SUB });
117
+ are_pins_interchangeable: part.ftype === 'simple_switch', source_group_id: 'source_group_0', subcircuit_id: SUB,
118
+ ...(part.package || typeof part.footprint === 'string' ? { rulecad_package: part.package ?? part.footprint } : {}) }); // (for the BOM's footprint column)
116
119
  const fpEls = part.footprint ? fp.string(part.footprint).circuitJson() : [];
117
120
  const mirror = part.layer === 'bottom' ? -1 : 1;
118
121
  const [cos, sin] = quarter(part.rotation), swap = sin !== 0;
@@ -146,6 +149,7 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
146
149
  // (the vias the router may make: the board's sizes, else ones with the ring a fab recommends, 0.3 in 0.8)
147
150
  add('pcb_board', { source_board_id: sourceBoard.source_board_id, subcircuit_id: SUB, center: board.center, thickness: board.thickness, num_layers: copper.length,
148
151
  width: board.width, height: board.height, ...(board.outline ? { outline: board.outline.map(({ x, y }) => ({ x, y })) } : {}), material: 'fr4', ...FAB_MINIMUMS,
152
+ ...(board.fab ? { min_trace_width: board.fab.track_min, min_trace_to_pad_edge_clearance: board.fab.gap_min, min_pad_edge_to_pad_edge_clearance: board.fab.gap_min, min_via_hole_edge_to_via_hole_edge_clearance: board.fab.gap_min } : {}), // (the fab's own, when the board names its rules)
149
153
  min_via_hole_diameter: board.via_hole ?? 0.3, min_via_pad_diameter: board.via_pad ?? 0.8 });
150
154
 
151
155
  for (const { part, comp, pads, sourcePorts, fpEls, at, mirror, size } of placed) {
@@ -195,7 +199,10 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
195
199
  // ---- planes: each plane net's pads reach its inner layer, through their own holes or a via each ----
196
200
  if (board.planes && copper.length < 4) throw new Error('planes need a board of 4 layers or more (board.layers): the outer two carry the tracks');
197
201
  const netOf = new Map(); // `${part}.${pin}` -> net, for the pours
198
- for (const [net, spec] of Object.entries(board.nets || {})) for (const pin of Array.isArray(spec) ? spec : spec.pins) netOf.set(pin, net);
202
+ for (const [net, spec] of Object.entries(board.nets || {})) for (const pin of Array.isArray(spec) ? spec : spec.pins) {
203
+ if (netOf.has(pin) && netOf.get(pin) !== net) throw new Error(`${pin} is in two nets, ${netOf.get(pin)} and ${net}: a pin is on one net (join the nets, or take it out of one)`);
204
+ netOf.set(pin, net);
205
+ }
199
206
  for (const [net, spec] of Object.entries(board.planes || {})) for (const pin of spec.pins) netOf.set(pin, net);
200
207
  const { nets: planeNets = null, links = [] } = board.planes ? planeVias(out, add, board, copper) : {};
201
208
  if (board.copper) keptCopper(out, add, board, copper, planeNets || {});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/pcb",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Circuit boards from rules: parts from rule sets or any standard footprint, quarter-turn rotation, nets and autorouting; keyboards with every matrix track drawn by rule. Gerbers, KiCad files and a JLCPCB BOM. Circuit JSON written directly: no React.",
5
5
  "type": "module",
6
6
  "exports": "./pcb.mjs",
package/pcb.mjs CHANGED
@@ -32,7 +32,7 @@ const hole = (x, y, d) => ({ x, y, d });
32
32
 
33
33
  // An MX switch, PCB mount: two pins, the centre post and the two fixing pegs
34
34
  export function mx(name, x, y, m, sch = {}) {
35
- return { name, ftype: 'simple_switch', mpn: 'Cherry MX (PCB mount)', x, y, layer: 'top', sch,
35
+ return { name, ftype: 'simple_switch', mpn: 'Cherry MX (PCB mount)', package: 'Cherry MX, PCB mount', x, y, layer: 'top', sch,
36
36
  pads: [pad('pin1', m.pcb_pin1_x, m.pcb_pin1_y, m.pcb_pin_drill, m.pcb_pin_pad), pad('pin2', m.pcb_pin2_x, m.pcb_pin2_y, m.pcb_pin_drill, m.pcb_pin_pad)],
37
37
  holes: [hole(0, 0, m.pcb_centre_hole), hole(-m.pcb_peg_x, 0, m.pcb_peg_hole), hole(m.pcb_peg_x, 0, m.pcb_peg_hole)],
38
38
  courtyard: { w: m.pcb_body, h: m.pcb_body } }; // the housing's footprint on the board
@@ -45,7 +45,7 @@ export function pico(name, x, y, p, sch = {}) {
45
45
  const left = n <= 20, i = left ? n - 1 : 40 - n;
46
46
  pins.push(pad(`pin${n}`, (left ? -1 : 1) * p.pin_rows / 2, (19 / 2 - i) * p.pin_pitch, p.pin_hole, p.pin_pad));
47
47
  }
48
- return { name, ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', x, y, layer: 'top', sch, pads: pins, courtyard: { w: p.width, h: p.length } };
48
+ return { name, ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', package: 'Raspberry Pi Pico, 0.1 in header pins', x, y, layer: 'top', sch, pads: pins, courtyard: { w: p.width, h: p.length } };
49
49
  }
50
50
  // Where a Pico pin is, from its centre
51
51
  export const picoPin = (n, p) => { const left = n <= 20, i = left ? n - 1 : 40 - n; return { x: (left ? -1 : 1) * p.pin_rows / 2, y: (19 / 2 - i) * p.pin_pitch }; };
@@ -56,7 +56,7 @@ export const picoGpio = (side) => Object.entries(loadRuleSet('pico').rules[`gpio
56
56
  // Parts for any board, not only keyboards. Each returns a part as circuit.mjs describes it: put them in board.parts, join
57
57
  // their pins with board.nets, and set board.autoroute. o (all optional): { rotation: 0 | 90 | 180 | 270, layer,
58
58
  // mpn, labels: { pin1: 'GND', ... }, sch: { x, y } }. Pin labels name the pins in nets ('U1.GND') and on the schematic.
59
- const chip = (name, x, y, o, more) => ({ name, ftype: 'simple_chip', x, y, layer: o.layer ?? 'top', rotation: o.rotation ?? 0, mpn: o.mpn,
59
+ const chip = (name, x, y, o, more) => ({ name, ftype: 'simple_chip', x, y, layer: o.layer ?? 'top', rotation: o.rotation ?? 0, mpn: o.mpn, ...(o.package ? { package: o.package } : {}),
60
60
  courtyard: o.courtyard ?? null, sch: { x: o.sch?.x ?? x / 2, y: o.sch?.y ?? y / 2, pinLabels: o.labels ?? {} }, ...more });
61
61
  const pinNo = (p) => Number(p.pin.replace(/\D/g, ''));
62
62
  // A rule set's pin map ({ "1": "GND", ... }) as pin labels ({ pin1: 'GND', ... })
@@ -80,25 +80,25 @@ export function header(name, x, y, r, o = {}) {
80
80
  pads.push(pad(`pin${i + 1}`, two ? -r.row_spacing / 2 : 0, py, r.drill, r.pad));
81
81
  if (two) pads.push(pad(`pin${2 * n - i}`, r.row_spacing / 2, py, r.drill, r.pad));
82
82
  }
83
- return chip(name, x, y, o, { pads: pads.sort((a, b) => pinNo(a) - pinNo(b)) });
83
+ return chip(name, x, y, { package: `${two ? '2 × ' : ''}${n}-pin header, ${r.pitch} mm`, ...o }, { pads: pads.sort((a, b) => pinNo(a) - pinNo(b)) });
84
84
  }
85
85
 
86
86
  /** A Seeed Studio XIAO module (any of the family) on header pins, USB at +y, from the xiao rules; pins labelled D0..D10, 5V, GND, 3V3. */
87
87
  export const xiao = (name, x, y, r, o = {}) =>
88
- header(name, x, y, r, { pins: r.pins / 2, rows: 2, mpn: 'Seeed Studio XIAO', courtyard: { w: r.width, h: r.length }, labels: labelsFrom('xiao', 'pins'), ...o });
88
+ header(name, x, y, r, { pins: r.pins / 2, rows: 2, mpn: 'Seeed Studio XIAO', package: 'Seeed Studio XIAO, 0.1 in header pins', courtyard: { w: r.width, h: r.length }, labels: labelsFrom('xiao', 'pins'), ...o });
89
89
 
90
90
  /** A Qwiic / STEMMA QT socket (JST SH, 4 pins, side entry), from the qwiic rules: the plug goes in from +y, the tabs' side. */
91
91
  export function qwiic(name, x, y, r, o = {}) {
92
92
  const n = r.pins, smd = (k, x, y, w, h) => ({ pin: `pin${k}`, smd: true, hint: String(k), x, y, w, h });
93
93
  const pads = Array.from({ length: n }, (_, i) => smd(i + 1, (i - (n - 1) / 2) * r.pitch, r.pad_y, r.pad_w, r.pad_h))
94
94
  .concat([-1, 1].map((side, i) => smd(n + i + 1, side * r.tab_x, r.tab_y, r.tab_w, r.tab_h)));
95
- return chip(name, x, y, { mpn: 'JST SM04B-SRSS-TB', labels: { ...labelsFrom('qwiic', 'pins'), pin5: 'TAB1', pin6: 'TAB2' }, ...o }, { pads });
95
+ return chip(name, x, y, { mpn: 'JST SM04B-SRSS-TB', package: 'JST SH, 4 pins, side entry', labels: { ...labelsFrom('qwiic', 'pins'), pin5: 'TAB1', pin6: 'TAB2' }, ...o }, { pads });
96
96
  }
97
97
 
98
98
  /** A JST PH socket (2.0 mm, through-hole), from the jstph rules: o.pins pins in a row along x (default 2). */
99
99
  export function jstph(name, x, y, r, o = {}) {
100
100
  const n = o.pins ?? 2;
101
- return chip(name, x, y, { mpn: `JST B${n}B-PH-K-S`, ...o }, { pads: Array.from({ length: n }, (_, i) => pad(`pin${i + 1}`, (i - (n - 1) / 2) * r.pitch, 0, r.drill, r.pad)) });
101
+ return chip(name, x, y, { mpn: `JST B${n}B-PH-K-S`, package: `JST PH, ${n} pins`, ...o }, { pads: Array.from({ length: n }, (_, i) => pad(`pin${i + 1}`, (i - (n - 1) / 2) * r.pitch, 0, r.drill, r.pad)) });
102
102
  }
103
103
 
104
104
  // ---------- the keyboard ----------
@@ -203,7 +203,7 @@ export function keyboard(v, keys) {
203
203
  pico0 = { x: cx, y: cy };
204
204
  right = cx + p.width / 2 + v.margin;
205
205
  }
206
- const picoPart = { name: 'U1', ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', x: pico0.x, y: pico0.y, layer: 'top', sch,
206
+ const picoPart = { name: 'U1', ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', package: 'Raspberry Pi Pico, 0.1 in header pins', x: pico0.x, y: pico0.y, layer: 'top', sch,
207
207
  pads: Array.from({ length: 40 }, (_, i) => { const q = pinAt(i + 1); return pad(`pin${i + 1}`, q.x - pico0.x, q.y - pico0.y, p.pin_hole, p.pin_pad); }),
208
208
  courtyard: under ? null : { w: p.width, h: p.length } };
209
209
 
@@ -211,7 +211,7 @@ export function keyboard(v, keys) {
211
211
  const pts = (list) => list.map(([x, y]) => ({ x, y })); // a track's corners between its two pads, on the board
212
212
  for (const k of keys) {
213
213
  parts.push(mx(`K${k.n}`, k.x, k.y, m, { x: k.c * SX, y: -k.r * SY }),
214
- { name: `D${k.n}`, ftype: 'simple_diode', footprint: 'sod123', mpn: '1N4148W', x: k.x + diode.x, y: k.y + diode.y, layer: 'bottom', sch: { x: k.c * SX + 1, y: -k.r * SY - 0.8 } });
214
+ { name: `D${k.n}`, ftype: 'simple_diode', footprint: 'sod123', package: 'SOD-123', mpn: '1N4148W', x: k.x + diode.x, y: k.y + diode.y, layer: 'bottom', sch: { x: k.c * SX + 1, y: -k.r * SY - 0.8 } });
215
215
  traces.push({ from: [`D${k.n}`, 'anode'], to: [`K${k.n}`, 'pin1'], width: v.track, path: pts([[k.x + anodeX, k.y + m.pcb_pin1_y]]) });
216
216
  }
217
217
 
@@ -339,7 +339,7 @@ export function keyboard(v, keys) {
339
339
  ...keys.map((k) => rect(k.x + cathodeX + d.pad_w / 2 + silk * 2, k.y + diode.y, silk, d.pad_h, 'bottom')),
340
340
  ...(v.margin >= text * 2 ? [{ text: 'rulecad: diodes point to the rows', x: (keyBox.left + keyBox.right) / 2, y: bottom + v.margin / 2, size: text, layer: 'bottom' }] : [])];
341
341
  const board = { center: { x: cx, y: cy }, width: right - left, height: top - bottom, thickness: v.thickness, autoroute: under,
342
- silk_line: v.jlcpcb.silk_line, silk_text: v.jlcpcb.silk_text, via_hole: 0.3, via_pad: 0.3 + 2 * v.jlcpcb.annular, // (vias with the ring the fab recommends)
342
+ silk_line: v.jlcpcb.silk_line, silk_text: v.jlcpcb.silk_text, via_hole: 0.3, via_pad: 0.3 + 2 * v.jlcpcb.annular, fab: v.jlcpcb, // (vias with the ring the fab recommends; the fab's minimums for the router)
343
343
  parts, traces, silk: marks, holes: corners.map(([x, y]) => hole(x, y, v.m2.clearance)) };
344
344
  const matrix = {
345
345
  keys: keys.map((k) => ({ key: `K${k.n}`, ...(k.label ? { label: k.label } : {}), row: k.r, col: k.c })),
@@ -354,25 +354,37 @@ export function keyboard(v, keys) {
354
354
  * A KiCad footprint (.kicad_mod text) as pad data: { pads, courtyard: { w, h } }, in mm, y up (KiCad's y is down).
355
355
  * Keep the result in a rule set's "footprints" (with its source), and place it with footprint(): a design never
356
356
  * reads files. SMD pads: { pin, smd: true, x, y, w, h } (a turned pad's w and h swapped); plated holes: { pin, x, y,
357
- * hole, outer }. Pads named alike (several GND pads) keep their name; unnamed pads (mechanical) are left out.
358
- * @param {string} text @returns {{ pads: object[], courtyard: { w: number, h: number } | null }}
357
+ * hole, outer }, an oval one with rect: { w, h } (its copper) and slot: [w, h] (drilled round at the narrow width);
358
+ * unplated holes in holes: [{ x, y, d }]. Pads named alike (several GND pads) keep their name; unnamed plated pads
359
+ * (mechanical) are left out. Text that isn't a footprint, or one with nothing on it, is refused.
360
+ * @param {string} text @returns {{ pads: object[], holes?: object[], courtyard: { w: number, h: number } | null }}
359
361
  */
360
362
  export function fromKicad(text) {
361
- const num = (s) => Number(s), pads = [];
363
+ if (!/^\s*\((?:footprint|module)\s/.test(text)) throw new Error('fromKicad: not a KiCad footprint (a .kicad_mod starts with "(footprint")');
364
+ const num = (s) => Number(s), pads = [], holes = [];
362
365
  for (const m of text.matchAll(/\(pad\s+"([^"]*)"\s+(smd|thru_hole|np_thru_hole)\s+(\w+)([\s\S]*?)\(layers/g)) {
363
- const [, name, kind, , rest] = m;
364
- if (!name) continue;
366
+ const [, name, kind, shape, rest] = m;
365
367
  const at = rest.match(/\(at\s+([-\d.]+)\s+([-\d.]+)(?:\s+([-\d.]+))?\)/), sz = rest.match(/\(size\s+([-\d.]+)\s+([-\d.]+)\)/);
366
368
  if (!at || !sz) continue;
367
369
  const turn = ((num(at[3] || 0) % 180) + 180) % 180 === 90, w = num(turn ? sz[2] : sz[1]), h = num(turn ? sz[1] : sz[2]);
368
370
  const x = +num(at[1]).toFixed(4), y = +(-num(at[2])).toFixed(4);
371
+ const drill = rest.match(/\(drill\s+(oval\s+)?([-\d.]+)(?:\s+([-\d.]+))?/);
372
+ if (kind === 'np_thru_hole') { if (drill) holes.push({ x, y, d: num(drill[2]) }); continue; } // a locating peg's hole: unplated, nothing to connect
373
+ if (!name) continue; // (an unnamed plated pad: mechanical)
369
374
  if (kind === 'smd') pads.push({ pin: name, smd: true, x, y, w, h });
370
- else if (kind === 'thru_hole') { const d = rest.match(/\(drill\s+(?:oval\s+)?([-\d.]+)/); pads.push({ pin: name, x, y, hole: num(d[1]), outer: Math.max(w, h) }); }
375
+ else if (kind === 'thru_hole') {
376
+ // An oval pad keeps its oval copper; a slot is drilled round at its narrow width (boards here can't carry slots),
377
+ // and says so
378
+ const d = num(drill[2]), slot = drill[1] && drill[3] && num(drill[3]) !== d ? (turn ? [num(drill[3]), d] : [d, num(drill[3])]) : null;
379
+ const oval = shape === 'oval' || (shape === 'rect' || shape === 'roundrect') ? w !== h : false;
380
+ pads.push({ pin: name, x, y, hole: slot ? Math.min(...slot) : d, outer: Math.max(w, h), ...(oval ? { rect: { w, h } } : {}), ...(slot ? { slot } : {}) });
381
+ }
371
382
  }
383
+ if (!pads.length && !holes.length) throw new Error('fromKicad: the footprint has no pads');
372
384
  const pts = text.split(/\n\s*(?=\(fp_|\(pad|\(model|\(zone)/).filter((el) => /^\(fp_(?:line|rect|poly)/.test(el) && /\(layer\s+"F\.CrtYd"\)/.test(el)) // the courtyard's corners
373
385
  .flatMap((el) => [...el.matchAll(/\((?:start|end|xy)\s+([-\d.]+)\s+([-\d.]+)\)/g)].map((m) => [num(m[1]), num(m[2])]));
374
386
  const span = (k) => Math.max(...pts.map((p) => p[k])) - Math.min(...pts.map((p) => p[k]));
375
- return { pads, courtyard: pts.length ? { w: +span(0).toFixed(3), h: +span(1).toFixed(3) } : null };
387
+ return { pads, ...(holes.length ? { holes } : {}), courtyard: pts.length ? { w: +span(0).toFixed(3), h: +span(1).toFixed(3) } : null };
376
388
  }
377
389
 
378
390
  /**
@@ -381,8 +393,8 @@ export function fromKicad(text) {
381
393
  * layer, mpn, labels, sch).
382
394
  */
383
395
  export function footprint(name, data, x, y, o = {}) {
384
- const pads = data.pads.map((p, i) => p.smd ? { pin: `pin${p.pin}`, smd: true, hint: String(p.pin), x: p.x, y: p.y, w: p.w, h: p.h } : pad(`pin${p.pin}`, p.x, p.y, p.hole, p.outer));
385
- return chip(name, x, y, { courtyard: data.courtyard, mpn: data.mpn, labels: data.labels, ...o }, { pads });
396
+ const pads = data.pads.map((p, i) => p.smd ? { pin: `pin${p.pin}`, smd: true, hint: String(p.pin), x: p.x, y: p.y, w: p.w, h: p.h } : { ...pad(`pin${p.pin}`, p.x, p.y, p.hole, p.outer), ...(p.rect ? { rect: p.rect } : {}) });
397
+ return chip(name, x, y, { courtyard: data.courtyard, mpn: data.mpn, labels: data.labels, ...o }, { pads, ...(data.holes?.length ? { holes: data.holes.map((h) => hole(h.x, h.y, h.d)) } : {}) });
386
398
  }
387
399
 
388
400
  // ---------- whole boards from KiCad: clones ----------
@@ -1081,7 +1093,7 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1081
1093
  // part is checked here pad by pad against the outline instead (below)
1082
1094
  // Castellated pads sit on the edge by design: half holes the fab cuts through. They're checked against its rules for them below
1083
1095
  // (with the other pads of their pins: a header pad beside a half hole runs into it, as on a Pico)
1084
- const castellated = json.filter((e) => e.type === 'pcb_plated_hole' && e.port_hints?.includes('castellated'));
1096
+ const b = board, castellated = json.filter((e) => e.type === 'pcb_plated_hole' && e.port_hints?.includes('castellated'));
1085
1097
  const pinOf = (e) => `${e.pcb_component_id}:${e.port_hints?.[1]}`, edgePins = new Set(castellated.map(pinOf));
1086
1098
  const halves = new Set(json.filter((e) => e.type === 'pcb_plated_hole' && edgePins.has(pinOf(e))).map((e) => e.pcb_plated_hole_id));
1087
1099
  const padsOf = (id) => json.filter((e) => e.pcb_component_id === id && ['pcb_smtpad', 'pcb_plated_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id));
@@ -1133,8 +1145,39 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1133
1145
  out.push(moved.length || strays.length ? { level: 'fail', text: `${moved.length + strays.length} of the source's own tracks and vias aren't where the source has them` }
1134
1146
  : { level: 'pass', text: `the source's own routing as it was: ${laid.length - vias - short} tracks and ${vias} vias exactly where the source has them${cutBy.length ? `, but for ${escapes} escapes cut back where a routed track turned straight back on them (${gone.length} segments gone, ${short} shortened: ${mm(total)} mm of track in all)` : ''} (only the router's tracks are tidied)` });
1135
1147
  }
1136
- const thin = traces.flatMap((t) => t.route).filter((p) => p.width != null && p.width < j.track_min);
1137
- out.push(thin.length ? { level: 'fail', text: `tracks under JLCPCB's ${j.track_min} mm` } : { level: 'pass', text: `tracks ${mm(v.track ?? Math.min(...traces.flatMap((t) => t.route).map((p) => p.width).filter((w) => w != null)))} mm${v.clear != null ? `, gaps ${mm(v.clear)} mm` : ''}: over JLCPCB's ${j.track_min} / ${j.gap_min} mm` });
1148
+ // Tracks and the gaps between them, measured from the board as drawn (not the design's variables): the narrowest
1149
+ // track, and the nearest two tracks of different connections come on one layer, edge to edge
1150
+ const segs = traces.flatMap((t) => t.route.slice(1).map((q, i) => ({ a: t.route[i], b: q, id: t.source_trace_id ?? t.pcb_trace_id, w: Math.max(t.route[i].width ?? 0, q.width ?? 0), layer: q.layer ?? t.route[i].layer })))
1151
+ .filter((g) => g.a.route_type !== 'via' && g.b.route_type !== 'via' && g.a.layer === g.b.layer);
1152
+ const widths = segs.map((g) => g.w).filter((w) => w > 0), narrow = widths.length ? Math.min(...widths) : null;
1153
+ let tight = null;
1154
+ const segGap = (g, h) => { const pts = [[g.a, h], [g.b, h], [h.a, g], [h.b, g]].map(([p, o]) => { const dx = o.b.x - o.a.x, dy = o.b.y - o.a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l)) : 0; return Math.hypot(p.x - o.a.x - t * dx, p.y - o.a.y - t * dy); }); return Math.min(...pts) - (g.w + h.w) / 2; };
1155
+ const crosses = (g, h) => { const o = (p, q, r) => Math.sign((q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x)); return o(g.a, g.b, h.a) * o(g.a, g.b, h.b) < 0 && o(h.a, h.b, g.a) * o(h.a, h.b, g.b) < 0; };
1156
+ // (tracks of one net may run close or meet: connections are grouped into nets by the ports and nets they share)
1157
+ const parent = new Map(), root = (x) => { while (parent.get(x) !== x) x = parent.get(x); return x; }, join = (x, y) => { parent.set(root(x), root(y)); };
1158
+ for (const t of json.filter((e) => e.type === 'source_trace')) {
1159
+ const ends = [t.source_trace_id, ...(t.connected_source_port_ids || []), ...(t.connected_source_net_ids || [])];
1160
+ for (const e of ends) if (!parent.has(e)) parent.set(e, e);
1161
+ for (const e of ends.slice(1)) join(ends[0], e);
1162
+ }
1163
+ const netOf = (id) => (parent.has(id) ? root(id) : id);
1164
+ const byLayer = new Map(); for (const g of segs) byLayer.set(g.layer, [...(byLayer.get(g.layer) || []), g]);
1165
+ for (const list of byLayer.values()) for (let x = 0; x < list.length; x++) for (let y = x + 1; y < list.length; y++) {
1166
+ const g = list[x], h = list[y];
1167
+ if (g.id === h.id || netOf(g.id) === netOf(h.id)) continue;
1168
+ const d = crosses(g, h) ? -1 : segGap(g, h);
1169
+ if (d <= 1e-6) continue; // touching: two pieces of one net meeting at a pad (the design checks catch real shorts)
1170
+ if (!tight || d < tight.d) tight = { d, at: [(g.a.x + g.b.x) / 2, (g.a.y + g.b.y) / 2] };
1171
+ }
1172
+ const thinTrack = narrow != null && narrow < j.track_min - 1e-9, closeGap = tight && tight.d < j.gap_min - 1e-9;
1173
+ if (narrow != null) out.push(thinTrack || closeGap
1174
+ ? { level: 'fail', text: [thinTrack && `a track ${mm(narrow)} mm wide, under JLCPCB's ${j.track_min} mm`, closeGap && `two tracks ${mm(tight.d)} mm apart near (${mm(tight.at[0])}, ${mm(tight.at[1])}), under JLCPCB's ${j.gap_min} mm`].filter(Boolean).join('; ') }
1175
+ : { level: 'pass', text: `tracks ${mm(narrow)} mm or wider${tight ? `, ${mm(tight.d)} mm or more apart` : ''}, measured on the board: over JLCPCB's ${j.track_min} / ${j.gap_min} mm` });
1176
+ // A board that can't be made: no size, a hole through its edge, two parts of one name, a pin in two nets
1177
+ const named = json.filter((e) => e.type === 'source_component').map((e) => e.name), twice = named.filter((n, i) => named.indexOf(n) !== i);
1178
+ const edgeHoles = b.outline ? [] : json.filter((e) => (e.type === 'pcb_hole' || e.type === 'pcb_plated_hole') && !halves.has(e.pcb_plated_hole_id)).filter((e) => { const r = (e.outer_diameter ?? e.hole_diameter ?? e.hole_width ?? 0) / 2; return Math.abs(e.x - b.center.x) + r > b.width / 2 + 1e-6 || Math.abs(e.y - b.center.y) + r > b.height / 2 + 1e-6; });
1179
+ const broken = [!(b.width > 0 && b.height > 0) && `the board is ${mm(b.width)} × ${mm(b.height)} mm`, edgeHoles.length && `${edgeHoles.length} holes break through the board's edge`, twice.length && `two parts named ${[...new Set(twice)].join(', ')}`].filter(Boolean); // (a pin in two nets is refused as the board is built)
1180
+ if (broken.length) out.push({ level: 'fail', text: `the board can't be made as drawn: ${broken.join('; ')}` });
1138
1181
  // Vias and plated holes against the fab's sizes, each measured from the board: the hole, the pad, and the ring
1139
1182
  // between them (under the recommended ring a warning, under the least a failure). A clone's vias as its source
1140
1183
  // has them are the source's design: said, not failed
@@ -1154,9 +1197,11 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1154
1197
  if (json.some((e) => /^pcb_silkscreen_/.test(e.type))) out.push(silkLines.length || silkTexts.length
1155
1198
  ? { level: 'fail', text: `silkscreen the fab can't print: ${[silkLines.length && `${silkLines.length} lines under ${j.silk_line} mm (${mm(Math.min(...silkLines.map((e) => e.stroke_width)))})`, silkTexts.length && `${silkTexts.length} texts under ${j.silk_text} mm high (${mm(Math.min(...silkTexts.map((e) => e.font_size)))})`].filter(Boolean).join(', ')}` }
1156
1199
  : { level: 'pass', text: `silkscreen: lines ${j.silk_line} mm or wider, text ${j.silk_text} mm or taller (JLCPCB's least)` });
1200
+ const unplated = json.filter((e) => e.type === 'pcb_hole').map((e) => e.hole_diameter ?? e.hole_width), npth = j.npth_min ?? 0.5;
1201
+ if (unplated.length && Math.min(...unplated) < npth - 1e-9) out.push({ level: 'fail', text: `an unplated hole of ${mm(Math.min(...unplated))} mm, under JLCPCB's ${npth} mm for unplated holes` });
1157
1202
  const drills = json.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole' || e.type === 'pcb_via').map((e) => e.hole_diameter ?? e.hole_width);
1158
1203
  if (drills.length) out.push(Math.min(...drills) < j.drill_min ? { level: 'fail', text: `a hole under JLCPCB's ${j.drill_min} mm` } : { level: 'pass', text: `${drills.length} holes, smallest ${Math.min(...drills)} mm (JLCPCB: ${j.drill_min} mm)` });
1159
- const b = json.find((e) => e.type === 'pcb_board'), size = `${b.width.toFixed(1)} × ${b.height.toFixed(1)} mm`;
1204
+ const size = `${b.width.toFixed(1)} × ${b.height.toFixed(1)} mm`;
1160
1205
  if (b.outline) { // a shaped board: every pad and hole inside it
1161
1206
  const reaching = same ? same.reaching : new Set();
1162
1207
  const pads = json.filter((e) => ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id) && !reaching.has(e.pcb_component_id)), out_ = pads.filter((e) => (e.points || [e]).some((q) => !inside(b.outline, q.x, q.y)));
@@ -1258,12 +1303,11 @@ export async function fabFiles(json, name) {
1258
1303
  // The BOM in JLCPCB's columns (Comment, Designator, Footprint, LCSC Part #), one line per kind of part. A part's LCSC
1259
1304
  // number comes with it when it has one (a clone's parts keep the source's); otherwise it's blank until parts are chosen
1260
1305
  // for assembly, and a hand-soldered board doesn't need them.
1261
- const FOOTPRINT = { K: 'Cherry MX, PCB mount', U: 'Raspberry Pi Pico, 0.1 in header pins', D: 'SOD-123' };
1262
1306
  function bom(json) {
1263
1307
  const lines = new Map(), q = (x) => `"${String(x).replace(/"/g, '""')}"`;
1264
1308
  for (const c of json.filter((e) => e.type === 'source_component' && !e.exclude_from_bom)) {
1265
1309
  const lcsc = c.supplier_part_numbers?.jlcpcb?.[0] ?? '', comment = c.display_value || c.manufacturer_part_number || c.name;
1266
- const footprint = lcsc ? '' : FOOTPRINT[c.name[0]] || ''; // a keyboard's parts by their letter; a part with an LCSC number is known by that
1310
+ const footprint = lcsc ? '' : c.rulecad_package || ''; // the part's own package (a part with an LCSC number is known by that)
1267
1311
  const key = `${comment}|${footprint}|${lcsc}`;
1268
1312
  if (!lines.has(key)) lines.set(key, { comment, footprint, lcsc, refs: [] });
1269
1313
  lines.get(key).refs.push(c.name);