by adom
Lightweight wiki-first component staging area. Add a component, check the Adom wiki for KiCad/Altium/Fusion files, upload what's missing, then file the symbol + footprint + 3D model straight into your EDA libraries — with library destinations matched per manufacturer and a clean 5-field symbol.
← Commit history
Publish 1.1.0
4 files changed
+166−24
DEVELOPING.md+31@@ -80,6 +80,37 @@ His KiCad user libraries: - Symbol descriptions: passives = value/size/power(or voltage/dielectric); ICs = manufacturer, package, pin count, subcategory — all comma-separated into the single Description field (NOT separate fields). +## Filing pitfalls learned at scale (138-part export)++- **Symbols must merge per-library in ONE read→merge-all→write.** A per-component read-modify-write+ of the shared `.kicad_sym` races/sees stale content and leaves each lib with only the LAST symbol.+ `fileSymbolsBatched` groups components by target lib, reads once, merges every symbol, writes once.+ (Footprints/3D are independent files so they don't have this problem.)+- **A symbol's `Footprint` property nickname MUST match the fp-lib-table nickname**, or KiCad shows+ "no pads" (it can't resolve the footprint). If footprint libs are registered with a prefix (e.g.+ `TEMP_Royalohm` for a temp export), the symbol's Footprint must be `TEMP_Royalohm:<fpName>` —+ `buildSymbolBlock(c, {nickPrefix})` handles this. The `<fpName>` is the `.kicad_mod` FILENAME+ (KiCad ids footprints by filename, not the internal `(footprint "…")` name).+- **KiCad reads sym-lib-table/fp-lib-table only at LAUNCH** and may rewrite the global tables on+ exit — so edit the tables while KiCad is CLOSED, and have the user restart KiCad to see new libs.+- **Temp/dry-run export:** `fileToLibrary(comps, {tempRoot})` mirrors Symbols/Footprints/3D under a+ temp dir, skips lib-table registration, copies KiCad STOCK footprints in too (read from the share+ dir), and restores real dests after — non-destructive to the user's real libraries. Temp footprint+ libs are registered with a `TEMP_` nickname, so the symbols' Footprint property must use that prefix+ (`buildSymbolBlock(c, {nickPrefix:'TEMP_'})`) or KiCad shows "no pads".+- **Defensive footprint repair:** `normalizeFpLayers()` requotes `(layers F.Cu,F.Paste,F.Mask)` →+ `(layers "F.Cu" "F.Paste" "F.Mask")` on copy. The `adom-footprint` generator historically emitted the+ comma/unquoted form, which KiCad reads as an SMD *aperture* (no copper). Fixed at the source in+ [email protected], but kept here as belt-and-suspenders for any still-bad source footprint.++## Throughput / what limits requests++- The ONLY self-imposed throttle is `CHECK_CONCURRENCY` (6) on the mass-add wiki checks — each check is+ one `adompkg search` subprocess + 2 wiki GETs; the cap stops a 138-part add from spawning 138 procs.+- Send/file speed is bounded by the **adom-desktop bridge** (serial `send_files`→`mv` round-trips per+ file) + wiki blob download latency. Symbols are batched (one write/lib) so they're no longer the cost.+- Bulk wiki writes are bounded by the **wiki's own rate limit (HTTP 429, ~10/min)** — pace bulk commits.+ ## Hard rules - **Re-checking the wiki must NEVER delete user-uploaded files or user-edited fields.** `runCheck`
package.json+19−3@@ -1,11 +1,27 @@ { "slug": "chip-fetcher-lite", "title": "Chip Fetcher Lite",- "version": "1.0.0",+ "version": "1.1.0", "type": "app", "description": "Lightweight wiki-first component staging area. Add a component, check the Adom wiki for KiCad/Altium/Fusion files, upload what's missing, then file the symbol + footprint + 3D model straight into your EDA libraries — with library destinations matched per manufacturer and a clean 5-field symbol.",- "tags": ["eda", "kicad", "altium", "fusion", "components", "cad", "library", "passives", "jlcpcb", "footprint", "symbol", "staging", "chip-fetcher"],- "hero": { "path": "screenshots/hero.png" },+ "tags": [+ "eda",+ "kicad",+ "altium",+ "fusion",+ "components",+ "cad",+ "library",+ "passives",+ "jlcpcb",+ "footprint",+ "symbol",+ "staging",+ "chip-fetcher"+ ],+ "hero": {+ "path": "screenshots/hero.png"+ }, "dependencies": {}, "files": [ "screenshots/hero.png",
page.json+1−1@@ -1,7 +1,7 @@ { "slug": "chip-fetcher-lite", "title": "Chip Fetcher Lite",- "version": "1.0.0",+ "version": "1.1.0", "type": "app", "description": "Lightweight wiki-first component staging area. Add a component, check the Adom wiki for KiCad/Altium/Fusion files, upload what's missing, then file the symbol + footprint + 3D model straight into your EDA libraries — with library destinations matched per manufacturer and a clean 5-field symbol.", "tags": [
server.js+115−20@@ -56,7 +56,7 @@ function uid() { return crypto.randomBytes(8).toString('hex'); } function find(id) { return DB.components.find(c => c.id === id); } // bounded wiki-check queue so mass-adds don't spawn hundreds of `adompkg` processes at once-const CHECK_CONCURRENCY = 4;+const CHECK_CONCURRENCY = 6; // tuned from the 138-part stress test: fast without overloading adompkg let _checkQueue = [], _checkActive = 0; function enqueueCheck(id) { _checkQueue.push(id); pumpChecks(); } function pumpChecks() {@@ -499,7 +499,7 @@ function regSnippet(table, name, uri) { // append a lib entry to a KiCad lib-tab const entry = ` (lib (name "${name}")(type "KiCad")(uri "${uri}")(options "")(descr ""))`; return `T="${table}"; [ -f "$T" ] && ! grep -qF '(name "${name}")' "$T" && { tmp=$(mktemp); head -n -1 "$T" > "$tmp"; printf '%s\\n)\\n' '${entry}' >> "$tmp"; mv "$tmp" "$T"; echo 'REG=${name}'; }`; }-async function createMissingLibraries(components) {+async function createMissingLibraries(components, opts = {}) { const symLibs = new Map(), fpLibs = new Map(), dirs = new Set(); for (const c of components) { const d = c.dest || {};@@ -512,9 +512,9 @@ async function createMissingLibraries(components) { for (const dir of dirs) sh.push(`mkdir -p ${shq(dir)} && echo "DIR=${dir}"`); for (const [pth, name] of symLibs) { sh.push(`[ -f ${shq(pth)} ] || { printf '(kicad_symbol_lib (version 20211014) (generator chip-fetcher-lite)\\n)\\n' > ${shq(pth)}; echo "SYM=${pth}"; }`);- sh.push(regSnippet('${CFG}sym-lib-table', name, pth));+ if (!opts.skipRegister) sh.push(regSnippet('${CFG}sym-lib-table', name, pth)); // temp dumps don't touch lib tables }- for (const [pth, name] of fpLibs) sh.push(regSnippet('${CFG}fp-lib-table', name, pth));+ if (!opts.skipRegister) for (const [pth, name] of fpLibs) sh.push(regSnippet('${CFG}fp-lib-table', name, pth)); const out = await runDesktopShell(sh.join('\n'), 90); return { created: out.split('\n').map(l => l.trim()).filter(l => /^(DIR|SYM|REG)=/.test(l)), raw: out }; }@@ -555,6 +555,18 @@ function hasAnyCad(c) { return files.some(f => /\.(kicad_sym|kicad_mod|step|stp|wrl|glb|lbr)$/i.test(f)); } // send_files ignores `dest` on Linux (lands in ~/Downloads), so land then move into place+// Defensive repair: some wiki/uploaded .kicad_mod files have pad layers written comma-separated and+// unquoted (`(layers F.Cu,F.Paste,F.Mask)`), which KiCad reads as an SMD *aperture* (no copper).+// Requote to valid KiCad syntax on copy so footprints always land as proper SMD pads.+function normalizeFpLayers(buf) {+ try {+ const txt = buf.toString('utf8');+ if (!/\(layers [^"()]*,/.test(txt)) return buf; // only touch the broken comma form+ const fixed = txt.replace(/\(layers ([^"()]+)\)/g, (m, g) =>+ '(layers ' + g.split(/[,\s]+/).filter(Boolean).map(t => `"${t.replace(/"/g, '')}"`).join(' ') + ')');+ return Buffer.from(fixed, 'utf8');+ } catch { return buf; }+} async function sendFiles(filePaths, destDir) { const r = await adomDesktopJSON('send_files', { filePaths }); const landed = (r.j && r.j.destinationPaths) || [];@@ -616,10 +628,19 @@ function mergeSymbol(destText, block, newN) { async function fileFootprint(c, tmpdir) { const d = c.dest && c.dest.footprint; if (!d || !d.path) return 'no dest';- if (d.source === 'kicad-default') return 'stock (skipped)';- const got = await getFileContent(c, 'footprint'); if (!got) return 'no source file';- const name = ((c.names && c.names.footprint) || c.mpn) + '.kicad_mod';- const tmp = path.join(tmpdir, name); fs.writeFileSync(tmp, got.buf);+ let buf, fname;+ if (d.source === 'kicad-default') {+ // normal mode: the stock footprint is already in KiCad, nothing to copy.+ // temp mode (d.stockPath set): copy the stock .kicad_mod from the desktop into the temp .pretty.+ if (!d.stockPath || !d.fpName) return 'stock (skipped)';+ const r = await adomDesktopJSON('read_file', { path: `${d.stockPath}/${d.fpName}.kicad_mod`, encoding: 'base64' });+ if (!(r.j && r.j.success && r.j.content)) return 'stock (skipped)';+ buf = Buffer.from(r.j.content, 'base64'); fname = `${d.fpName}.kicad_mod`;+ } else {+ const got = await getFileContent(c, 'footprint'); if (!got) return 'no source file';+ buf = normalizeFpLayers(got.buf); fname = ((c.names && c.names.footprint) || c.mpn) + '.kicad_mod';+ }+ const tmp = path.join(tmpdir, fname); fs.writeFileSync(tmp, buf); const r = await sendFiles([tmp], d.path); return (r.j && r.j.success === false) ? ('send failed: ' + (r.j.error || '')) : 'ok'; }@@ -658,23 +679,91 @@ async function fileSymbol(c, tmpdir) { const sr = await sendFiles([tmp], dirOf(d.path)); return (sr.j && sr.j.success === false) ? ('send failed: ' + (sr.j.error || '')) : 'ok'; }-async function fileToLibrary(components) {- DB.send = { status: 'running', total: components.length, done: 0, current: 'creating libraries…', errors: [], startedAt: new Date().toISOString() };+// redirect a component's destinations under a temp root (mirrors Symbols/Footprints/3D), for a+// dry-run export that doesn't touch the user's real libraries or lib tables.+function tempDest(c, tempRoot) {+ const d = c.dest || {}; const base = p => (p || '').split('/').pop();+ const t = (kd, sub) => d[kd] && d[kd].path ? { ...d[kd], path: `${tempRoot}/${sub}/${base(d[kd].path)}`, exists: false } : (d[kd] || null);+ const out = { symbol: t('symbol', 'Symbols'), footprint: t('footprint', 'Footprints'), model3d: t('model3d', '3D') };+ if (out.footprint && d.footprint && d.footprint.source === 'kicad-default') out.footprint.stockPath = d.footprint.path; // copy stock fp from here+ return out;+}+// build the renamed/stripped/propped symbol block for one component.+// opts.nickPrefix is prepended to the footprint-library nickname in the Footprint property so it+// matches how the footprint lib is registered (e.g. "TEMP_" for a temp export).+async function buildSymbolBlock(c, opts = {}) {+ const got = await getFileContent(c, 'symbol'); if (!got) return { err: 'no source file' };+ const block0 = extractSymbolBlock(got.buf.toString('utf8')); if (!block0) return { err: 'no symbol block' };+ const oldN = symbolNameOf(block0) || c.mpn;+ const newN = (c.names && c.names.symbol) || c.mpn;+ let block = renameSymbol(block0, oldN, newN);+ block = stripExtraProps(block);+ if (c.description) block = setSymProp(block, 'Description', c.description);+ const fpd = c.dest && c.dest.footprint;+ if (fpd) {+ const nick = (opts.nickPrefix || '') + baseNoExt(fpd.name);+ const fpName = (fpd.source === 'kicad-default' && fpd.fpName) ? fpd.fpName : ((c.names && c.names.footprint) || c.mpn);+ block = setSymProp(block, 'Footprint', `${nick}:${fpName}`);+ }+ if (c.datasheetUrl) block = setSymProp(block, 'Datasheet', c.datasheetUrl);+ if (c.jlcPart) block = setSymProp(block, 'LCSC', c.jlcPart);+ return { block, newN };+}+// merge ALL symbols destined for the same .kicad_sym in ONE read→merge→write (avoids the+// per-component read-modify-write race that left each lib with only the last symbol)+async function fileSymbolsBatched(components, tmpdir, opts = {}) {+ const byLib = new Map();+ for (const c of components) {+ const d = c.dest && c.dest.symbol; if (!d || !d.path || !hasAnyCad(c)) continue;+ if (!byLib.has(d.path)) byLib.set(d.path, { name: d.name, comps: [] });+ byLib.get(d.path).comps.push(c);+ }+ for (const [pth, grp] of byLib) {+ DB.send.current = `symbols → ${baseNoExt(grp.name)}`; save();+ const r = await adomDesktopJSON('read_file', { path: pth, encoding: 'utf8' });+ let text = (r.j && r.j.success && r.j.content) || '(kicad_symbol_lib (version 20211014) (generator chip-fetcher-lite)\n)\n';+ let added = 0;+ for (const c of grp.comps) {+ try {+ const b = await buildSymbolBlock(c, opts);+ if (b.err) { DB.send.errors.push(`${c.mpn} symbol: ${b.err}`); continue; }+ const m = mergeSymbol(text, b.block, b.newN); text = m.text; if (!m.skipped) added++;+ } catch (e) { DB.send.errors.push(`${c.mpn} symbol: ${e.message || e}`); }+ }+ await runDesktopShell(`cp ${shq(pth)} ${shq(pth + '.bak')} 2>/dev/null || true`, 20);+ const tmp = path.join(tmpdir, baseNoExt(grp.name) + '.kicad_sym'); fs.writeFileSync(tmp, text);+ const sr = await sendFiles([tmp], dirOf(pth));+ if (sr.j && sr.j.success === false) DB.send.errors.push(`symbols ${baseNoExt(grp.name)}: send failed`);+ DB.send.current = `symbols → ${baseNoExt(grp.name)} (${added})`; save();+ }+}+async function fileToLibrary(components, opts = {}) {+ const temp = !!opts.tempRoot;+ DB.send = { status: 'running', total: components.length, done: 0, current: temp ? `exporting to ${opts.tempRoot}…` : 'creating libraries…', errors: [], startedAt: new Date().toISOString(), tempRoot: opts.tempRoot || null }; save();- try { await createMissingLibraries(components); } catch (e) { DB.send.errors.push('create libs: ' + (e.message || e)); }+ const orig = new Map();+ if (temp) for (const c of components) { orig.set(c.id, c.dest); c.dest = tempDest(c, opts.tempRoot); }+ try { await createMissingLibraries(components, { skipRegister: temp }); } catch (e) { DB.send.errors.push('create libs: ' + (e.message || e)); } const tmpdir = path.join(DATA_DIR, 'send'); fs.mkdirSync(tmpdir, { recursive: true });+ // 1) footprints + 3D per component (independent files) for (const c of components) { if (!hasAnyCad(c)) { DB.send.errors.push(`${c.mpn}: skipped — no CAD on the wiki`); DB.send.done++; save(); continue; }- for (const [kind, fn] of [['footprint', fileFootprint], ['3D model', file3D], ['symbol', fileSymbol]]) {+ for (const [kind, fn] of [['footprint', fileFootprint], ['3D model', file3D]]) { DB.send.current = `${c.mpn}: ${kind}`; save(); try { const r = await fn(c, tmpdir); if (r && !/^(ok|stock|already)/.test(r)) DB.send.errors.push(`${c.mpn} ${kind}: ${r}`); } catch (e) { DB.send.errors.push(`${c.mpn} ${kind}: ${e.message || e}`); } }- // mark destinations as now existing- for (const kd of ['symbol', 'footprint', 'model3d']) if (c.dest && c.dest[kd]) c.dest[kd].exists = true;+ if (!temp) for (const kd of ['footprint', 'model3d']) if (c.dest && c.dest[kd]) c.dest[kd].exists = true; DB.send.done++; save(); }- DB.send.status = 'done'; DB.send.current = `Filed ${DB.send.done} component(s)` + (DB.send.errors.length ? ` (${DB.send.errors.length} issue(s))` : '');+ // 2) symbols batched per library (one read→merge-all→write).+ // In temp mode the footprint libs are registered as TEMP_<nick>, so the symbols' Footprint+ // property must use that prefix to resolve.+ await fileSymbolsBatched(components, tmpdir, { nickPrefix: temp ? 'TEMP_' : '' });+ if (!temp) for (const c of components) if (c.dest && c.dest.symbol) c.dest.symbol.exists = true;+ if (temp) for (const c of components) c.dest = orig.get(c.id); // restore real dests; temp send is non-destructive+ DB.send.status = 'done';+ DB.send.current = (temp ? `Exported ${DB.send.done} to temp` : `Filed ${DB.send.done} component(s)`) + (DB.send.errors.length ? ` (${DB.send.errors.length} issue(s))` : ''); DB.send.finishedAt = new Date().toISOString(); save(); } @@ -829,16 +918,22 @@ const server = http.createServer(async (req, res) => { save(); return sendJSON(res, 200, DB.probe); } - // ---- send to library: create any missing libraries on the user's machine, then file in+ // ---- send to library: create any missing libraries on the user's machine, then file in.+ // {temp:true} (or an explicit tempRoot) exports to a temp folder instead of the real libraries. if (p === '/api/send-to-library' && req.method === 'POST') {- const { ids, edas } = await readJSON(req);+ const { ids, edas, temp, tempRoot } = await readJSON(req); const sel = (ids && ids.length) ? ids : DB.components.filter(c => c.selected).map(c => c.id); if (!sel.length) return sendJSON(res, 400, { error: 'no components selected' }); const comps = sel.map(find).filter(Boolean); if (DB.send && DB.send.status === 'running') return sendJSON(res, 409, { error: 'a send is already in progress' });- // create the libs, download the wiki/uploaded CAD, and file symbol+footprint+3D onto the desktop- fileToLibrary(comps).catch(e => { DB.send.status = 'error'; DB.send.current = String(e && e.message || e); save(); });- return sendJSON(res, 200, { status: 'running', total: comps.length });+ let root = tempRoot || null;+ if (!root && temp) { // derive a temp root next to the user's KiCad dir+ const sd = DB.probe && DB.probe.libraries && DB.probe.libraries.kicad && DB.probe.libraries.kicad.symbolsDir;+ root = sd ? dirOf(dirOf(sd)) + '/chip-fetcher-lite-temp' : null;+ if (!root) return sendJSON(res, 400, { error: 'probe libraries first so a temp root can be derived, or pass tempRoot' });+ }+ fileToLibrary(comps, root ? { tempRoot: root } : {}).catch(e => { DB.send.status = 'error'; DB.send.current = String(e && e.message || e); save(); });+ return sendJSON(res, 200, { status: 'running', total: comps.length, tempRoot: root }); } // ---- agent job queue