@huaqiu/hardware-artifacts 0.7.13 → 0.7.15

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/lib/service.mjs CHANGED
@@ -1,838 +1,2 @@
1
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
2
- import { execFile, execFileSync, spawn } from "node:child_process";
3
- import { createHash } from "node:crypto";
4
- import { readFile } from "node:fs/promises";
5
- import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
- import { tmpdir } from "node:os";
7
- //#region src/service.ts
8
- /**
9
- * Hardware Engineering artifact model and host operations.
10
- *
11
- * This module deliberately has no Cordis dependency: it is the testable core
12
- * behind `hardwareArtifacts`. Native project files remain authoritative; the
13
- * objects here are path pointers, verified installation facts and disposable
14
- * derived outputs, never a shadow project database.
15
- */
16
- const EXCLUDED_DIRS = /* @__PURE__ */ new Set([
17
- ".git",
18
- ".cache",
19
- "node_modules",
20
- "dist",
21
- "build",
22
- "out",
23
- "tmp",
24
- "temp",
25
- "archive",
26
- "archives",
27
- "backup",
28
- "backups",
29
- "export",
30
- "exports"
31
- ]);
32
- const MECHANICAL_EXTENSIONS = /* @__PURE__ */ new Set([
33
- ".step",
34
- ".stp",
35
- ".glb"
36
- ]);
37
- const SOURCE_EXTENSIONS = {
38
- ".kicad_sch": "schematic",
39
- ".kicad_pcb": "pcb"
40
- };
41
- const MAX_DEPTH = 5;
42
- /** KiCad writes each child sheet as `(property "Sheetfile" "child.kicad_sch")`. */
43
- const SHEET_FILE_PATTERN = /\(property\s+"Sheetfile"\s+"((?:[^"\\]|\\.)*)"/gu;
44
- function canonical(path) {
45
- return resolve(path);
46
- }
47
- function isInside(child, parent) {
48
- const rel = relative(parent, child);
49
- return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
50
- }
51
- function isExcluded(name) {
52
- return EXCLUDED_DIRS.has(name.toLowerCase());
53
- }
54
- function realOrUndefined(path) {
55
- try {
56
- return realpathSync(path);
57
- } catch {
58
- return;
59
- }
60
- }
61
- function errorWithCode(message, code, status) {
62
- return Object.assign(new Error(message), {
63
- code,
64
- status
65
- });
66
- }
67
- function walkFiles(root, predicate) {
68
- const found = [];
69
- const visit = (dir, depth) => {
70
- if (depth > MAX_DEPTH || !existsSync(dir)) return;
71
- let entries;
72
- try {
73
- entries = readdirSync(dir, { withFileTypes: true });
74
- } catch {
75
- return;
76
- }
77
- for (const entry of entries) {
78
- const full = join(dir, entry.name);
79
- if (entry.isDirectory()) {
80
- if (!isExcluded(entry.name)) visit(full, depth + 1);
81
- } else if (entry.isFile() && predicate(entry.name)) found.push(canonical(full));
82
- }
83
- };
84
- visit(root, 0);
85
- return found.sort();
86
- }
87
- /** Child schematics declared by sheet references in one saved schematic. */
88
- function childSheetFiles(path) {
89
- let text;
90
- try {
91
- text = readFileSync(path, "utf8");
92
- } catch {
93
- return [];
94
- }
95
- const dir = dirname(path);
96
- const children = [];
97
- for (const match of text.matchAll(SHEET_FILE_PATTERN)) {
98
- const raw = match[1];
99
- if (raw === void 0 || raw === "") continue;
100
- const declared = raw.replace(/\\(["\\])/gu, "$1");
101
- const target = isAbsolute(declared) ? canonical(declared) : resolve(dir, declared);
102
- children.push(target);
103
- }
104
- return children.sort();
105
- }
106
- function artifact(kind, path, projectPath, sourcePath) {
107
- const full = canonical(path);
108
- return {
109
- id: `${kind}:${full}`,
110
- kind,
111
- path: full,
112
- ...projectPath === void 0 ? {} : { projectPath: canonical(projectPath) },
113
- ...sourcePath === void 0 ? {} : { sourcePath: canonical(sourcePath) },
114
- title: basename(full),
115
- format: extname(full).toLowerCase().replace(/^\./, "") || kind
116
- };
117
- }
118
- function defaultVersionProbe(executable) {
119
- if (!existsSync(executable)) return void 0;
120
- try {
121
- return execFileSync(executable, ["version"], {
122
- encoding: "utf8",
123
- timeout: 5e3,
124
- stdio: [
125
- "ignore",
126
- "pipe",
127
- "ignore"
128
- ]
129
- }).trim().split("\n")[0] || void 0;
130
- } catch {
131
- return;
132
- }
133
- }
134
- function defaultRunCommand(command, args, options) {
135
- return new Promise((resolvePromise, reject) => {
136
- execFile(command, [...args], {
137
- cwd: options.cwd,
138
- timeout: options.timeoutMs,
139
- encoding: "utf8",
140
- windowsHide: true,
141
- shell: false,
142
- ...options.signal === void 0 ? {} : { signal: options.signal },
143
- maxBuffer: 8388608
144
- }, (error, stdout, stderr) => {
145
- if (error === null) {
146
- resolvePromise({
147
- exitCode: 0,
148
- stdout: String(stdout),
149
- stderr: String(stderr),
150
- timedOut: false
151
- });
152
- return;
153
- }
154
- const killed = error.killed === true;
155
- const signal = error.signal;
156
- if (killed || signal !== null && signal !== void 0) {
157
- resolvePromise({
158
- exitCode: null,
159
- stdout: String(stdout),
160
- stderr: String(stderr),
161
- timedOut: true
162
- });
163
- return;
164
- }
165
- const code = typeof error.code === "number" ? Number(error.code) : null;
166
- if (code === null) {
167
- reject(error);
168
- return;
169
- }
170
- resolvePromise({
171
- exitCode: code,
172
- stdout: String(stdout),
173
- stderr: String(stderr),
174
- timedOut: false
175
- });
176
- });
177
- });
178
- }
179
- function existing(paths) {
180
- return paths.find((candidate) => {
181
- try {
182
- return existsSync(candidate) && statSync(candidate).isFile();
183
- } catch {
184
- return false;
185
- }
186
- });
187
- }
188
- function kicadCandidates(root) {
189
- const app = basename(root).toLowerCase().endsWith(".app");
190
- if (app || process.platform === "darwin") {
191
- const base = app ? root : join(root, "KiCad.app");
192
- return {
193
- cli: [join(base, "Contents/MacOS/kicad-cli")],
194
- kicad: [join(base, "Contents/MacOS/kicad")],
195
- eeschema: [join(base, "Contents/Applications/eeschema.app/Contents/MacOS/eeschema")],
196
- pcbnew: [join(base, "Contents/Applications/pcbnew.app/Contents/MacOS/pcbnew")]
197
- };
198
- }
199
- const exe = process.platform === "win32" ? ".exe" : "";
200
- const bin = app ? root : basename(root).toLowerCase() === "bin" ? root : join(root, "bin");
201
- return {
202
- cli: [join(bin, `kicad-cli${exe}`), join(root, `kicad-cli${exe}`)],
203
- kicad: [join(bin, `kicad${exe}`)],
204
- eeschema: [join(bin, `eeschema${exe}`)],
205
- pcbnew: [join(bin, `pcbnew${exe}`)]
206
- };
207
- }
208
- /** Install root that owns one resolved `kicad-cli`, per layout convention. */
209
- function installRootFromCli(cli) {
210
- const segments = cli.split(sep);
211
- const macIndex = segments.indexOf("Contents");
212
- if (macIndex > 0) return segments.slice(0, macIndex).join(sep) || sep;
213
- if (segments[segments.length - 2]?.toLowerCase() === "bin") return segments.slice(0, -2).join(sep) || sep;
214
- return dirname(cli);
215
- }
216
- function solidcraftCandidates(root) {
217
- const exe = process.platform === "win32" ? ".exe" : "";
218
- const app = basename(root).toLowerCase().endsWith(".app");
219
- if (app || process.platform === "darwin") {
220
- const base = app ? root : join(root, "SolidCraft.app");
221
- return [join(base, `Contents/MacOS/SolidCraft`), join(base, `Contents/MacOS/solidcraft`)];
222
- }
223
- return [
224
- root,
225
- join(root, `SolidCraft${exe}`),
226
- join(root, `solidcraft${exe}`),
227
- join(root, "bin", `SolidCraft${exe}`),
228
- join(root, "bin", `solidcraft${exe}`)
229
- ];
230
- }
231
- /** Small, immutable host capability implementation. */
232
- var HardwareArtifactService = class {
233
- config;
234
- options;
235
- cacheRoot;
236
- glbTimeoutMs;
237
- maxSourceBytes;
238
- lastDiscovery;
239
- /** Completed GLB exports keyed by `sourcePath:revision`. */
240
- glbCache = /* @__PURE__ */ new Map();
241
- /** In-flight GLB exports keyed by the same key, so concurrent callers share one run. */
242
- glbPending = /* @__PURE__ */ new Map();
243
- /** BOM projections keyed by `sourcePath:revision`. */
244
- bomCache = /* @__PURE__ */ new Map();
245
- constructor(config = {}) {
246
- this.config = config;
247
- this.options = {
248
- probeVersion: config.probeVersion ?? defaultVersionProbe,
249
- spawnProcess: config.spawnProcess ?? ((command, args, settings) => spawn(command, [...args], settings)),
250
- runCommand: config.runCommand ?? defaultRunCommand
251
- };
252
- this.cacheRoot = canonical(config.cacheRoot ?? join(tmpdir(), "huaqiu-hardware-artifacts"));
253
- this.glbTimeoutMs = config.glbTimeoutMs ?? 12e4;
254
- this.maxSourceBytes = config.maxSourceBytes ?? 33554432;
255
- }
256
- /** Resolve configured installations from validated absolute paths only. */
257
- installations() {
258
- const kicadRoot = this.config.kicadRoot ? canonical(this.config.kicadRoot) : void 0;
259
- let kicadCli;
260
- if (kicadRoot !== void 0) kicadCli = existing(basename(kicadRoot).toLowerCase().startsWith("kicad-cli") ? [kicadRoot] : kicadCandidates(kicadRoot).cli);
261
- const candidates = kicadRoot === void 0 ? {
262
- cli: [],
263
- kicad: [],
264
- eeschema: [],
265
- pcbnew: []
266
- } : kicadCandidates(kicadCli === void 0 ? kicadRoot : installRootFromCli(kicadCli));
267
- const pcbEditor = existing(candidates.pcbnew);
268
- const schematicEditor = existing(candidates.eeschema);
269
- const projectManager = existing(candidates.kicad);
270
- const version = kicadCli === void 0 ? void 0 : this.options.probeVersion(kicadCli);
271
- const kicad = kicadCli === void 0 ? {
272
- configured: false,
273
- error: "KiCad installation is not configured"
274
- } : version === void 0 ? {
275
- configured: false,
276
- root: kicadRoot,
277
- cli: kicadCli,
278
- error: `${kicadCli} did not answer a version probe`
279
- } : {
280
- configured: true,
281
- root: kicadRoot,
282
- cli: kicadCli,
283
- version,
284
- ...projectManager === void 0 ? {} : { projectManager },
285
- ...pcbEditor === void 0 ? {} : { pcbEditor },
286
- ...schematicEditor === void 0 ? {} : { schematicEditor }
287
- };
288
- const solidRoot = this.config.solidcraftRoot ? canonical(this.config.solidcraftRoot) : void 0;
289
- const solidExecutable = solidRoot === void 0 ? void 0 : existing(solidcraftCandidates(solidRoot));
290
- return {
291
- kicad,
292
- solidcraft: solidExecutable === void 0 ? {
293
- configured: false,
294
- error: "SolidCraft installation is not configured"
295
- } : {
296
- configured: true,
297
- root: solidRoot,
298
- executable: solidExecutable
299
- }
300
- };
301
- }
302
- /** Paths passed to agent child processes. Never assign these globally. */
303
- childEnvironment() {
304
- const installed = this.installations();
305
- const env = {};
306
- if (installed.kicad.cli !== void 0) env.HUAQIU_KICAD_CLI = installed.kicad.cli;
307
- if (installed.kicad.pcbEditor !== void 0) env.HUAQIU_KICAD_PCBNEW = installed.kicad.pcbEditor;
308
- if (installed.kicad.schematicEditor !== void 0) env.HUAQIU_KICAD_EESCHEMA = installed.kicad.schematicEditor;
309
- if (installed.solidcraft.executable !== void 0) env.HUAQIU_SOLIDCRAFT = installed.solidcraft.executable;
310
- return env;
311
- }
312
- /** Compact agent context: validated paths only, no project inventory dump. */
313
- environmentText(current) {
314
- const installed = this.installations();
315
- const lines = ["<hardware_environment>"];
316
- lines.push("KiCad:");
317
- lines.push(` configured: ${String(installed.kicad.configured)}`);
318
- for (const key of [
319
- "version",
320
- "cli",
321
- "pcbEditor",
322
- "schematicEditor"
323
- ]) {
324
- const value = installed.kicad[key];
325
- if (value !== void 0) lines.push(` ${key}: ${value}`);
326
- }
327
- if (installed.kicad.error !== void 0) lines.push(` error: ${installed.kicad.error}`);
328
- lines.push("SolidCraft:");
329
- lines.push(` configured: ${String(installed.solidcraft.configured)}`);
330
- if (installed.solidcraft.executable !== void 0) lines.push(` executable: ${installed.solidcraft.executable}`);
331
- if (installed.solidcraft.error !== void 0) lines.push(` error: ${installed.solidcraft.error}`);
332
- if (current?.selected !== void 0) {
333
- lines.push("Current project:");
334
- lines.push(` root: ${current.cwd}`);
335
- lines.push(` project: ${current.selected.path}`);
336
- if (current.selected.schematic !== void 0) lines.push(` schematic: ${current.selected.schematic.path}`);
337
- const board = current.selected.boards[0];
338
- if (board !== void 0) lines.push(` selected_pcb: ${board.path}`);
339
- }
340
- lines.push("</hardware_environment>");
341
- return lines.join("\n");
342
- }
343
- /**
344
- * Deterministic discovery. An explicit project or manifest wins; otherwise
345
- * exactly one `.kicad_pro` may be selected automatically. Ambiguity is
346
- * returned as a selection requirement, never resolved by taking the first.
347
- */
348
- discover(cwdInput, explicitProject) {
349
- const cwd = canonical(cwdInput);
350
- const manifestPath = join(cwd, ".hardware-engineering.json");
351
- let manifest;
352
- if (existsSync(manifestPath)) try {
353
- manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
354
- } catch (error) {
355
- const result = {
356
- cwd,
357
- manifestPath,
358
- projects: [],
359
- issue: {
360
- code: "bad-manifest",
361
- message: `invalid .hardware-engineering.json: ${String(error)}`
362
- }
363
- };
364
- this.lastDiscovery = result;
365
- return result;
366
- }
367
- const projectPaths = /* @__PURE__ */ new Set();
368
- if (explicitProject !== void 0 && explicitProject.trim() !== "") {
369
- const requested = isAbsolute(explicitProject) ? canonical(explicitProject) : resolve(cwd, explicitProject);
370
- if (!existsSync(requested)) {
371
- const result = {
372
- cwd,
373
- ...manifest === void 0 ? {} : { manifestPath },
374
- projects: [],
375
- issue: {
376
- code: "missing-project",
377
- message: `${requested} does not exist`
378
- }
379
- };
380
- this.lastDiscovery = result;
381
- return result;
382
- }
383
- projectPaths.add(requested);
384
- } else if (manifest?.project !== void 0 && manifest.project.trim() !== "") projectPaths.add(isAbsolute(manifest.project) ? canonical(manifest.project) : resolve(cwd, manifest.project));
385
- else for (const path of walkFiles(cwd, (name) => name.toLowerCase().endsWith(".kicad_pro"))) projectPaths.add(path);
386
- const projects = [...projectPaths].sort().map((path) => this.projectFrom(path, cwd, manifest));
387
- if (projects.length === 0) {
388
- const result = {
389
- cwd,
390
- ...manifest === void 0 ? {} : { manifestPath },
391
- projects,
392
- issue: {
393
- code: "no-project",
394
- message: `no .kicad_pro found under ${cwd}`
395
- }
396
- };
397
- this.lastDiscovery = result;
398
- return result;
399
- }
400
- if (projects.length > 1) {
401
- const result = {
402
- cwd,
403
- ...manifest === void 0 ? {} : { manifestPath },
404
- projects,
405
- issue: {
406
- code: "selection-required",
407
- message: `${projects.length} projects found; select one explicitly`
408
- }
409
- };
410
- this.lastDiscovery = result;
411
- return result;
412
- }
413
- const selected = projects[0];
414
- const result = {
415
- cwd,
416
- ...manifest === void 0 ? {} : { manifestPath },
417
- projects,
418
- selected,
419
- ...selected.selectionRequired ? { issue: {
420
- code: "selection-required",
421
- message: "select an artifact explicitly"
422
- } } : {}
423
- };
424
- this.lastDiscovery = result;
425
- return result;
426
- }
427
- /** The most recent discovery, used to authorize source reads. */
428
- discovery() {
429
- return this.lastDiscovery;
430
- }
431
- projectFrom(projectPath, cwd, manifest) {
432
- const dir = dirname(projectPath);
433
- const name = basename(projectPath, extname(projectPath));
434
- const resolvePath = (value) => isAbsolute(value) ? canonical(value) : resolve(dir, value);
435
- const explicitSchematic = manifest?.schematic === void 0 ? void 0 : resolvePath(manifest.schematic);
436
- let schematicPath = explicitSchematic !== void 0 && existsSync(explicitSchematic) ? explicitSchematic : void 0;
437
- if (schematicPath === void 0) {
438
- const named = join(dir, `${name}.kicad_sch`);
439
- if (existsSync(named)) schematicPath = named;
440
- else {
441
- const candidates = readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".kicad_sch")).map((entry) => join(dir, entry.name)).sort();
442
- if (candidates.length === 1) schematicPath = candidates[0];
443
- }
444
- }
445
- const sheets = [];
446
- if (schematicPath !== void 0) {
447
- const visited = /* @__PURE__ */ new Set([canonical(schematicPath)]);
448
- const queue = childSheetFiles(canonical(schematicPath));
449
- while (queue.length > 0) {
450
- const canonicalNext = canonical(queue.shift());
451
- if (visited.has(canonicalNext)) continue;
452
- visited.add(canonicalNext);
453
- if (!existsSync(canonicalNext) || extname(canonicalNext).toLowerCase() !== ".kicad_sch") continue;
454
- sheets.push(artifact("schematic", canonicalNext, projectPath, canonical(schematicPath)));
455
- queue.push(...childSheetFiles(canonicalNext));
456
- }
457
- }
458
- const manifestBoards = manifest?.boards === void 0 ? [] : manifest.boards.filter((entry) => existsSync(resolvePath(entry.path))).map((entry) => artifact("pcb", resolvePath(entry.path), projectPath));
459
- const scannedBoards = walkFiles(dir, (file) => file.toLowerCase().endsWith(".kicad_pcb")).map((path) => artifact("pcb", path, projectPath));
460
- const boards = manifestBoards.length > 0 ? manifestBoards : [...scannedBoards].sort((left, right) => boardRank(left, right, name));
461
- const owned = boards.find((board) => basename(board.path, ".kicad_pcb") === name) ?? boards[0];
462
- const ownershipAmbiguous = manifestBoards.length === 0 && boards.length > 1 && basename(owned?.path ?? "", ".kicad_pcb") !== name;
463
- const mechanical = manifest?.mechanical !== void 0 ? manifest.mechanical.map((model) => artifact("mechanical-3d", resolvePath(model.path), projectPath)) : walkFiles(dir, (file) => MECHANICAL_EXTENSIONS.has(extname(file).toLowerCase())).map((path) => artifact("mechanical-3d", path, projectPath));
464
- const sourceSchematic = schematicPath === void 0 ? void 0 : artifact("schematic", schematicPath, projectPath);
465
- const sourceBoard = ownershipAmbiguous ? void 0 : owned;
466
- return {
467
- path: projectPath,
468
- name,
469
- ...sourceSchematic === void 0 ? {} : {
470
- rootSheet: sourceSchematic,
471
- schematic: sourceSchematic
472
- },
473
- ...sourceSchematic === void 0 ? {} : { bom: {
474
- ...artifact("bom", sourceSchematic.path, projectPath, sourceSchematic.path),
475
- title: `BOM — ${sourceSchematic.title}`
476
- } },
477
- ...sourceBoard === void 0 ? {} : {
478
- pcb3d: {
479
- ...artifact("pcb-3d", sourceBoard.path, projectPath, sourceBoard.path),
480
- title: `3D — ${sourceBoard.title}`
481
- },
482
- defaultBoard: sourceBoard.path
483
- },
484
- sheets,
485
- boards,
486
- mechanical,
487
- selectionRequired: boards.length > 1 && ownershipAmbiguous
488
- };
489
- }
490
- /** Validate and launch a native application without a shell. */
491
- open(request) {
492
- const path = canonical(request.artifactPath);
493
- if (!existsSync(path)) throw errorWithCode(`artifact does not exist: ${path}`, "missing-artifact", 404);
494
- const installed = this.installations();
495
- const ext = extname(path).toLowerCase();
496
- let command;
497
- if (ext === ".kicad_sch") command = installed.kicad.schematicEditor;
498
- else if (ext === ".kicad_pcb") command = installed.kicad.pcbEditor;
499
- else if (ext === ".kicad_pro") command = installed.kicad.projectManager;
500
- else throw errorWithCode(`unsupported KiCad artifact: ${ext}`, "unsupported-artifact", 415);
501
- if (command === void 0) throw errorWithCode("the configured KiCad installation has no editor for this artifact", "missing-executable", 412);
502
- const settings = {
503
- cwd: dirname(path),
504
- detached: true,
505
- stdio: "ignore",
506
- windowsHide: true,
507
- shell: false
508
- };
509
- const child = this.options.spawnProcess(command, [path], settings);
510
- return {
511
- launched: true,
512
- command,
513
- args: [path],
514
- cwd: settings.cwd,
515
- ...child.pid === void 0 ? {} : { pid: child.pid }
516
- };
517
- }
518
- /** Workspace roots a read may target: explicit request, last discovery, config. */
519
- authorizedRoots(roots) {
520
- const candidates = /* @__PURE__ */ new Set();
521
- for (const root of roots ?? []) if (root !== void 0 && root.trim() !== "") candidates.add(canonical(root));
522
- const discovered = this.lastDiscovery?.cwd;
523
- if (discovered !== void 0) candidates.add(canonical(discovered));
524
- return [...candidates];
525
- }
526
- /**
527
- * Authorize one artifact path: canonical, realpath-checked, inside a
528
- * workspace root, and of an expected type. A browser request cannot turn
529
- * this into an arbitrary filesystem read, even from loopback.
530
- */
531
- authorize(artifactPath, roots) {
532
- if (!isAbsolute(artifactPath)) throw errorWithCode("artifact identity must be an absolute path", "invalid-identity", 400);
533
- const requested = canonical(artifactPath);
534
- if (SOURCE_EXTENSIONS[extname(requested).toLowerCase()] === void 0) throw errorWithCode(`unsupported artifact type: ${extname(requested)}`, "unsupported-artifact", 415);
535
- const authorized = this.authorizedRoots(roots);
536
- if (authorized.length === 0) throw errorWithCode("no authorized workspace is known to the host", "unauthorized", 403);
537
- if (!authorized.some((root) => isInside(requested, canonical(root)))) throw errorWithCode("artifact is outside the authorized workspace", "unauthorized", 403);
538
- if (!existsSync(requested)) throw errorWithCode(`artifact does not exist: ${requested}`, "missing-artifact", 404);
539
- const real = realOrUndefined(requested);
540
- if (real === void 0) throw errorWithCode(`artifact cannot be resolved: ${requested}`, "invalid-identity", 400);
541
- if (!authorized.some((root) => {
542
- const realRoot = realOrUndefined(root) ?? root;
543
- return isInside(real, realRoot);
544
- })) throw errorWithCode("artifact is outside the authorized workspace", "unauthorized", 403);
545
- if (!statSync(real).isFile()) throw errorWithCode(`artifact is not a regular file: ${requested}`, "invalid-identity", 400);
546
- if (SOURCE_EXTENSIONS[extname(real).toLowerCase()] === void 0) throw errorWithCode("artifact type changed during resolution", "unsupported-artifact", 415);
547
- return {
548
- path: real,
549
- kind: SOURCE_EXTENSIONS[extname(real).toLowerCase()]
550
- };
551
- }
552
- /** Saved source text plus a content-addressed revision. */
553
- async readSource(request) {
554
- const { path, kind } = this.authorize(request.artifactPath, request.roots);
555
- const info = statSync(path);
556
- if (info.size > this.maxSourceBytes) throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, "too-large", 413);
557
- const body = await readFile(path);
558
- const revision = createHash("sha256").update(body).digest("hex");
559
- if (request.expectedRevision !== void 0 && request.expectedRevision !== "" && request.expectedRevision !== revision) throw errorWithCode(`source changed since it was selected (expected ${request.expectedRevision}, found ${revision})`, "stale-revision", 409);
560
- return {
561
- path,
562
- kind,
563
- revision,
564
- bytes: body.byteLength,
565
- mtimeMs: info.mtimeMs,
566
- text: body.toString("utf8")
567
- };
568
- }
569
- sourceRevision(path) {
570
- if (statSync(path).size > this.maxSourceBytes) throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, "too-large", 413);
571
- return createHash("sha256").update(readFileSync(path)).digest("hex");
572
- }
573
- /** Cache directory for one board's derived outputs. */
574
- glbDirectory(boardPath) {
575
- const digest = createHash("sha256").update(boardPath).digest("hex").slice(0, 16);
576
- return join(this.cacheRoot, "glb", digest);
577
- }
578
- /**
579
- * Generate (or reuse) the GLB for one board.
580
- *
581
- * - cache key includes the source content hash, so same-size/same-mtime edits invalidate
582
- * - one in-flight export is shared by concurrent callers for the same revision
583
- * - output is written to a temp file and renamed only after it validates
584
- * - a timeout or abort leaves no partial file behind
585
- */
586
- async exportGlb(request) {
587
- const { path } = this.authorize(request.artifactPath, request.roots);
588
- if (extname(path).toLowerCase() !== ".kicad_pcb") throw errorWithCode("GLB export requires a .kicad_pcb artifact", "unsupported-artifact", 415);
589
- const installed = this.installations();
590
- if (!installed.kicad.configured || installed.kicad.cli === void 0) throw errorWithCode(installed.kicad.error ?? "the configured KiCad installation has no kicad-cli", "not-configured", 412);
591
- const cli = installed.kicad.cli;
592
- const revision = this.sourceRevision(path);
593
- const key = `${path}:${revision}`;
594
- const cached = this.glbCache.get(key);
595
- if (cached !== void 0 && existsSync(cached.file)) {
596
- const info = statSync(cached.file);
597
- return {
598
- ...cached,
599
- bytes: info.size,
600
- cached: true
601
- };
602
- }
603
- const pending = this.glbPending.get(key);
604
- if (pending !== void 0) return pending;
605
- const directory = this.glbDirectory(path);
606
- const target = join(directory, `board-${revision.slice(0, 16)}.glb`);
607
- const running = (async () => {
608
- mkdirSync(directory, { recursive: true });
609
- const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`);
610
- mkdirSync(tempDirectory, { recursive: true });
611
- const tempFile = join(tempDirectory, "board.glb");
612
- try {
613
- const result = await this.options.runCommand(cli, [
614
- "pcb",
615
- "export",
616
- "glb",
617
- "--output",
618
- tempFile,
619
- path
620
- ], {
621
- cwd: dirname(path),
622
- timeoutMs: this.glbTimeoutMs,
623
- ...request.signal === void 0 ? {} : { signal: request.signal }
624
- });
625
- if (result.timedOut) throw errorWithCode(`kicad-cli pcb export glb timed out after ${this.glbTimeoutMs} ms`, "export-timeout", 504);
626
- if (result.exitCode !== 0) throw errorWithCode(`kicad-cli pcb export glb failed: ${(result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)}`, "export-failed", 502);
627
- if (!existsSync(tempFile)) throw errorWithCode("kicad-cli pcb export glb produced no output", "export-failed", 502);
628
- const bytes = statSync(tempFile).size;
629
- if (bytes === 0 || readFileSync(tempFile).subarray(0, 4).toString("ascii") !== "glTF") throw errorWithCode("kicad-cli wrote an invalid GLB", "export-failed", 502);
630
- renameSync(tempFile, target);
631
- const generated = {
632
- path,
633
- revision,
634
- bytes,
635
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
636
- cached: false,
637
- file: target
638
- };
639
- this.glbCache.set(key, generated);
640
- return generated;
641
- } finally {
642
- rmSync(tempDirectory, {
643
- recursive: true,
644
- force: true
645
- });
646
- }
647
- })();
648
- this.glbPending.set(key, running);
649
- try {
650
- return await running;
651
- } finally {
652
- this.glbPending.delete(key);
653
- }
654
- }
655
- /**
656
- * Grouped BOM for one saved root schematic.
657
- *
658
- * Reuses KiCad's own BOM extraction (`kicad-cli sch export bom`), the same
659
- * authoritative source `analyze_kicad_module` consumes, rather than building a
660
- * second component analyser. Grouping key is every non-reference column, so
661
- * different MPNs never merge and DNP stays explicit.
662
- */
663
- async exportBom(request) {
664
- const { path, kind } = this.authorize(request.artifactPath, request.roots);
665
- if (kind !== "schematic") throw errorWithCode("BOM export requires a .kicad_sch artifact", "unsupported-artifact", 415);
666
- const installed = this.installations();
667
- if (!installed.kicad.configured || installed.kicad.cli === void 0) throw errorWithCode(installed.kicad.error ?? "the configured KiCad installation has no kicad-cli", "not-configured", 412);
668
- const revision = this.sourceRevision(path);
669
- const key = `${path}:${revision}`;
670
- const cached = this.bomCache.get(key);
671
- if (cached !== void 0) return {
672
- ...cached,
673
- cached: true
674
- };
675
- const directory = join(this.cacheRoot, "bom", createHash("sha256").update(path).digest("hex").slice(0, 16));
676
- const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`);
677
- mkdirSync(tempDirectory, { recursive: true });
678
- const tempFile = join(tempDirectory, "bom.csv");
679
- try {
680
- const result = await this.options.runCommand(installed.kicad.cli, [
681
- "sch",
682
- "export",
683
- "bom",
684
- "--output",
685
- tempFile,
686
- path
687
- ], {
688
- cwd: dirname(path),
689
- timeoutMs: 6e4,
690
- ...request.signal === void 0 ? {} : { signal: request.signal }
691
- });
692
- if (result.timedOut) throw errorWithCode("kicad-cli sch export bom timed out", "export-timeout", 504);
693
- if (result.exitCode !== 0) throw errorWithCode(`kicad-cli sch export bom failed: ${(result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)}`, "export-failed", 502);
694
- if (!existsSync(tempFile)) throw errorWithCode("kicad-cli produced no BOM output", "export-failed", 502);
695
- const rows = groupBomRows(parseCsv(readFileSync(tempFile, "utf8")));
696
- const generated = {
697
- path,
698
- revision,
699
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
700
- cached: false,
701
- rows,
702
- source: "kicad-cli-bom"
703
- };
704
- this.bomCache.set(key, generated);
705
- return generated;
706
- } finally {
707
- rmSync(tempDirectory, {
708
- recursive: true,
709
- force: true
710
- });
711
- }
712
- }
713
- /** Serve a generated GLB file, re-validating the cache entry first. */ glbFile(boardPath, revision) {
714
- const key = `${canonical(boardPath)}:${revision}`;
715
- const entry = this.glbCache.get(key);
716
- if (entry === void 0 || !existsSync(entry.file)) throw errorWithCode("generated GLB is not available for this revision", "stale-revision", 409);
717
- return entry.file;
718
- }
719
- /** Drop cached derived outputs for one board (or all of them). */
720
- clearCache(boardPath) {
721
- if (boardPath === void 0) {
722
- this.glbCache.clear();
723
- rmSync(this.cacheRoot, {
724
- recursive: true,
725
- force: true
726
- });
727
- return;
728
- }
729
- const prefix = `${canonical(boardPath)}:`;
730
- for (const key of [...this.glbCache.keys()]) if (key.startsWith(prefix)) this.glbCache.delete(key);
731
- rmSync(this.glbDirectory(canonical(boardPath)), {
732
- recursive: true,
733
- force: true
734
- });
735
- }
736
- };
737
- /** Ownership order: project-named board first, then shallower, then alphabetical. */
738
- function boardRank(left, right, projectName) {
739
- const leftNamed = basename(left.path, ".kicad_pcb") === projectName ? 0 : 1;
740
- const rightNamed = basename(right.path, ".kicad_pcb") === projectName ? 0 : 1;
741
- if (leftNamed !== rightNamed) return leftNamed - rightNamed;
742
- const leftDepth = left.path.split(sep).length;
743
- const rightDepth = right.path.split(sep).length;
744
- if (leftDepth !== rightDepth) return leftDepth - rightDepth;
745
- return left.path.localeCompare(right.path);
746
- }
747
- /** RFC4180-style CSV reader: quoted fields, doubled quotes, CRLF rows. */
748
- function parseCsv(text) {
749
- const rows = [];
750
- let row = [];
751
- let field = "";
752
- let quoted = false;
753
- const source = text.replace(/^\uFEFF/u, "");
754
- for (let index = 0; index < source.length; index += 1) {
755
- const char = source[index];
756
- if (quoted) {
757
- if (char === "\"") {
758
- if (source[index + 1] === "\"") {
759
- field += "\"";
760
- index += 1;
761
- } else quoted = false;
762
- } else field += char;
763
- continue;
764
- }
765
- if (char === "\"") quoted = true;
766
- else if (char === ",") {
767
- row.push(field);
768
- field = "";
769
- } else if (char === "\r") continue;
770
- else if (char === "\n") {
771
- row.push(field);
772
- rows.push(row);
773
- row = [];
774
- field = "";
775
- } else field += char;
776
- }
777
- if (field !== "" || row.length > 0) {
778
- row.push(field);
779
- rows.push(row);
780
- }
781
- return rows.filter((cells) => cells.some((cell) => cell.trim() !== ""));
782
- }
783
- /**
784
- * Group KiCad's per-reference BOM rows.
785
- *
786
- * Identity is every column except the reference and quantity columns, so a
787
- * different MPN or a DNP flag always produces a separate line; ordering follows
788
- * the first reference seen, which keeps the table stable between reads.
789
- */
790
- function groupBomRows(table) {
791
- const [header, ...body] = table;
792
- if (header === void 0) return [];
793
- const columns = header.map((cell) => cell.trim());
794
- const referenceIndex = columns.findIndex((cell) => /^reference$/iu.test(cell));
795
- const quantityIndex = columns.findIndex((cell) => /^quantity$/iu.test(cell));
796
- const valueIndex = columns.findIndex((cell) => /^value$/iu.test(cell));
797
- const footprintIndex = columns.findIndex((cell) => /^footprint$/iu.test(cell));
798
- const dnpIndex = columns.findIndex((cell) => /^dnp$/iu.test(cell));
799
- const groups = /* @__PURE__ */ new Map();
800
- for (const cells of body) {
801
- const reference = referenceIndex === -1 ? "" : (cells[referenceIndex] ?? "").trim();
802
- if (reference === "") continue;
803
- const fields = {};
804
- columns.forEach((column, index) => {
805
- if (index === referenceIndex || index === quantityIndex || index === valueIndex || index === footprintIndex || index === dnpIndex) return;
806
- const text = (cells[index] ?? "").trim();
807
- if (text !== "") fields[column] = text;
808
- });
809
- const dnpText = dnpIndex === -1 ? "" : (cells[dnpIndex] ?? "").trim();
810
- const dnp = /^(1|true|yes|dnp|x)$/iu.test(dnpText);
811
- const identity = JSON.stringify([
812
- valueIndex === -1 ? "" : (cells[valueIndex] ?? "").trim(),
813
- footprintIndex === -1 ? "" : (cells[footprintIndex] ?? "").trim(),
814
- dnp,
815
- Object.fromEntries(Object.entries(fields).sort(([a], [b]) => a.localeCompare(b)))
816
- ]);
817
- const group = groups.get(identity) ?? {
818
- references: [],
819
- fields,
820
- dnp
821
- };
822
- group.references.push(reference);
823
- groups.set(identity, group);
824
- }
825
- return [...groups.entries()].map(([identity, group]) => {
826
- const [value, footprint, dnp] = JSON.parse(identity);
827
- return {
828
- references: group.references,
829
- quantity: group.references.length,
830
- value,
831
- footprint,
832
- dnp,
833
- fields: group.fields
834
- };
835
- });
836
- }
837
- //#endregion
1
+ import { n as groupBomRows, r as parseCsv, t as HardwareArtifactService } from "./service-Yrc2C_eo.mjs";
838
2
  export { HardwareArtifactService, groupBomRows, parseCsv };