@huaqiu/hardware-artifacts 0.7.12 → 0.7.13

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/src/service.ts CHANGED
@@ -3,15 +3,19 @@
3
3
  *
4
4
  * This module deliberately has no Cordis dependency: it is the testable core
5
5
  * behind `hardwareArtifacts`. Native project files remain authoritative; the
6
- * objects here are path pointers and verified installation facts, never a
7
- * shadow project database.
6
+ * objects here are path pointers, verified installation facts and disposable
7
+ * derived outputs, never a shadow project database.
8
8
  */
9
- import { execFileSync, spawn, type ChildProcess } from 'node:child_process'
10
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
9
+ import { execFile, execFileSync, spawn, type ChildProcess } from 'node:child_process'
10
+ import { createHash } from 'node:crypto'
11
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from 'node:fs'
12
+ import { readFile } from 'node:fs/promises'
11
13
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
14
+ import { tmpdir } from 'node:os'
12
15
 
13
16
  export type ArtifactKind = 'schematic' | 'pcb' | 'pcb-3d' | 'bom' | 'mechanical-3d'
14
- export type NativeApplication = 'kicad' | 'solidcraft'
17
+ /** Native handoff is KiCad-only in this POC; SolidCraft stays agent context. */
18
+ export type NativeApplication = 'kicad'
15
19
 
16
20
  export interface HardwareArtifact {
17
21
  readonly id: string
@@ -22,16 +26,22 @@ export interface HardwareArtifact {
22
26
  readonly sourcePath?: string
23
27
  readonly title: string
24
28
  readonly format: string
29
+ /** Content hash of the saved source, filled when the source is read. */
30
+ readonly revision?: string
25
31
  }
26
32
 
27
33
  export interface HardwareProject {
28
34
  readonly path: string
29
35
  readonly name: string
36
+ /** Root schematic: the authoritative project entry point. */
37
+ readonly rootSheet?: HardwareArtifact
30
38
  readonly schematic?: HardwareArtifact
31
39
  /** Semantic views; both keep the identity of their source artifact. */
32
40
  readonly bom?: HardwareArtifact
33
41
  readonly pcb3d?: HardwareArtifact
34
42
  readonly sheets: readonly HardwareArtifact[]
43
+ /** Deterministic default board, only when ownership is unambiguous. */
44
+ readonly defaultBoard?: string
35
45
  readonly boards: readonly HardwareArtifact[]
36
46
  readonly mechanical: readonly HardwareArtifact[]
37
47
  readonly selectionRequired: boolean
@@ -77,6 +87,56 @@ export interface OpenArtifactResult {
77
87
  readonly pid?: number
78
88
  }
79
89
 
90
+ export interface SourceRequest {
91
+ readonly artifactPath: string
92
+ readonly expectedRevision?: string
93
+ /** Workspace roots the caller is currently authorized to read. */
94
+ readonly roots?: readonly string[]
95
+ }
96
+
97
+ export interface SourceResult {
98
+ readonly path: string
99
+ readonly kind: 'schematic' | 'pcb'
100
+ readonly revision: string
101
+ readonly bytes: number
102
+ readonly mtimeMs: number
103
+ readonly text: string
104
+ }
105
+
106
+ export interface GlbRequest {
107
+ readonly artifactPath: string
108
+ readonly roots?: readonly string[]
109
+ readonly signal?: AbortSignal
110
+ }
111
+
112
+ export interface GlbResult {
113
+ readonly path: string
114
+ readonly revision: string
115
+ readonly bytes: number
116
+ readonly generatedAt: string
117
+ readonly cached: boolean
118
+ readonly file: string
119
+ }
120
+
121
+ /** One grouped BOM line, as KiCad's own BOM export groups it. */
122
+ export interface BomRow {
123
+ readonly references: readonly string[]
124
+ readonly quantity: number
125
+ readonly value: string
126
+ readonly footprint: string
127
+ readonly dnp: boolean
128
+ readonly fields: Readonly<Record<string, string>>
129
+ }
130
+
131
+ export interface BomResult {
132
+ readonly path: string
133
+ readonly revision: string
134
+ readonly generatedAt: string
135
+ readonly cached: boolean
136
+ readonly rows: readonly BomRow[]
137
+ readonly source: 'kicad-cli-bom'
138
+ }
139
+
80
140
  export interface HardwareArtifactsOptions {
81
141
  readonly kicadRoot?: string
82
142
  readonly solidcraftRoot?: string
@@ -86,6 +146,17 @@ export interface HardwareArtifactsOptions {
86
146
  args: readonly string[],
87
147
  options: { cwd: string; detached: boolean; stdio: 'ignore'; windowsHide: boolean; shell: false },
88
148
  ) => Pick<ChildProcess, 'pid'>
149
+ /** Runs one short-lived CLI command and returns its exit facts. */
150
+ readonly runCommand?: (
151
+ command: string,
152
+ args: readonly string[],
153
+ options: { cwd: string; timeoutMs: number; signal?: AbortSignal },
154
+ ) => Promise<{ exitCode: number | null; stdout: string; stderr: string; timedOut: boolean }>
155
+ /** Cache directory for derived outputs; defaults to a temp subdirectory. */
156
+ readonly cacheRoot?: string
157
+ readonly glbTimeoutMs?: number
158
+ /** Source text limit; protects the host from pathological files. */
159
+ readonly maxSourceBytes?: number
89
160
  }
90
161
 
91
162
  interface ProjectManifest {
@@ -100,7 +171,13 @@ const EXCLUDED_DIRS = new Set([
100
171
  'archive', 'archives', 'backup', 'backups', 'export', 'exports',
101
172
  ])
102
173
  const MECHANICAL_EXTENSIONS = new Set(['.step', '.stp', '.glb'])
174
+ const SOURCE_EXTENSIONS: Readonly<Record<string, 'schematic' | 'pcb'>> = {
175
+ '.kicad_sch': 'schematic',
176
+ '.kicad_pcb': 'pcb',
177
+ }
103
178
  const MAX_DEPTH = 5
179
+ /** KiCad writes each child sheet as `(property "Sheetfile" "child.kicad_sch")`. */
180
+ const SHEET_FILE_PATTERN = /\(property\s+"Sheetfile"\s+"((?:[^"\\]|\\.)*)"/gu
104
181
 
105
182
  function canonical(path: string): string {
106
183
  return resolve(path)
@@ -115,6 +192,18 @@ function isExcluded(name: string): boolean {
115
192
  return EXCLUDED_DIRS.has(name.toLowerCase())
116
193
  }
117
194
 
195
+ function realOrUndefined(path: string): string | undefined {
196
+ try {
197
+ return realpathSync(path)
198
+ } catch {
199
+ return undefined
200
+ }
201
+ }
202
+
203
+ function errorWithCode(message: string, code: string, status: number): Error {
204
+ return Object.assign(new Error(message), { code, status })
205
+ }
206
+
118
207
  function walkFiles(root: string, predicate: (name: string) => boolean): string[] {
119
208
  const found: string[] = []
120
209
  const visit = (dir: string, depth: number): void => {
@@ -138,6 +227,26 @@ function walkFiles(root: string, predicate: (name: string) => boolean): string[]
138
227
  return found.sort()
139
228
  }
140
229
 
230
+ /** Child schematics declared by sheet references in one saved schematic. */
231
+ function childSheetFiles(path: string): string[] {
232
+ let text: string
233
+ try {
234
+ text = readFileSync(path, 'utf8')
235
+ } catch {
236
+ return []
237
+ }
238
+ const dir = dirname(path)
239
+ const children: string[] = []
240
+ for (const match of text.matchAll(SHEET_FILE_PATTERN)) {
241
+ const raw = match[1]
242
+ if (raw === undefined || raw === '') continue
243
+ const declared = raw.replace(/\\(["\\])/gu, '$1')
244
+ const target = isAbsolute(declared) ? canonical(declared) : resolve(dir, declared)
245
+ children.push(target)
246
+ }
247
+ return children.sort()
248
+ }
249
+
141
250
  function artifact(kind: ArtifactKind, path: string, projectPath?: string, sourcePath?: string): HardwareArtifact {
142
251
  const full = canonical(path)
143
252
  return {
@@ -164,6 +273,41 @@ function defaultVersionProbe(executable: string): string | undefined {
164
273
  }
165
274
  }
166
275
 
276
+ function defaultRunCommand(
277
+ command: string,
278
+ args: readonly string[],
279
+ options: { cwd: string; timeoutMs: number; signal?: AbortSignal },
280
+ ): Promise<{ exitCode: number | null; stdout: string; stderr: string; timedOut: boolean }> {
281
+ return new Promise((resolvePromise, reject) => {
282
+ execFile(command, [...args], {
283
+ cwd: options.cwd,
284
+ timeout: options.timeoutMs,
285
+ encoding: 'utf8',
286
+ windowsHide: true,
287
+ shell: false,
288
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
289
+ maxBuffer: 8 * 1024 * 1024,
290
+ }, (error, stdout, stderr) => {
291
+ if (error === null) {
292
+ resolvePromise({ exitCode: 0, stdout: String(stdout), stderr: String(stderr), timedOut: false })
293
+ return
294
+ }
295
+ const killed = (error as { killed?: boolean }).killed === true
296
+ const signal = (error as { signal?: string | null }).signal
297
+ if (killed || signal !== null && signal !== undefined) {
298
+ resolvePromise({ exitCode: null, stdout: String(stdout), stderr: String(stderr), timedOut: true })
299
+ return
300
+ }
301
+ const code = typeof (error as { code?: unknown }).code === 'number' ? Number((error as { code: number }).code) : null
302
+ if (code === null) {
303
+ reject(error)
304
+ return
305
+ }
306
+ resolvePromise({ exitCode: code, stdout: String(stdout), stderr: String(stderr), timedOut: false })
307
+ })
308
+ })
309
+ }
310
+
167
311
  function existing(paths: readonly string[]): string | undefined {
168
312
  return paths.find((candidate) => {
169
313
  try {
@@ -195,6 +339,15 @@ function kicadCandidates(root: string): { cli: string[]; kicad: string[]; eesche
195
339
  }
196
340
  }
197
341
 
342
+ /** Install root that owns one resolved `kicad-cli`, per layout convention. */
343
+ function installRootFromCli(cli: string): string {
344
+ const segments = cli.split(sep)
345
+ const macIndex = segments.indexOf('Contents')
346
+ if (macIndex > 0) return segments.slice(0, macIndex).join(sep) || sep
347
+ if (segments[segments.length - 2]?.toLowerCase() === 'bin') return segments.slice(0, -2).join(sep) || sep
348
+ return dirname(cli)
349
+ }
350
+
198
351
  function solidcraftCandidates(root: string): string[] {
199
352
  const exe = process.platform === 'win32' ? '.exe' : ''
200
353
  const app = basename(root).toLowerCase().endsWith('.app')
@@ -216,13 +369,27 @@ function solidcraftCandidates(root: string): string[] {
216
369
 
217
370
  /** Small, immutable host capability implementation. */
218
371
  export class HardwareArtifactService {
219
- private readonly options: Required<Pick<HardwareArtifactsOptions, 'spawnProcess' | 'probeVersion'>>
372
+ private readonly options: Required<Pick<HardwareArtifactsOptions, 'spawnProcess' | 'probeVersion' | 'runCommand'>>
373
+ private readonly cacheRoot: string
374
+ private readonly glbTimeoutMs: number
375
+ private readonly maxSourceBytes: number
376
+ private lastDiscovery?: DiscoveryResult
377
+ /** Completed GLB exports keyed by `sourcePath:revision`. */
378
+ private readonly glbCache = new Map<string, GlbResult>()
379
+ /** In-flight GLB exports keyed by the same key, so concurrent callers share one run. */
380
+ private readonly glbPending = new Map<string, Promise<GlbResult>>()
381
+ /** BOM projections keyed by `sourcePath:revision`. */
382
+ private readonly bomCache = new Map<string, BomResult>()
220
383
 
221
384
  constructor(private readonly config: HardwareArtifactsOptions = {}) {
222
385
  this.options = {
223
386
  probeVersion: config.probeVersion ?? defaultVersionProbe,
224
387
  spawnProcess: config.spawnProcess ?? ((command, args, settings) => spawn(command, [...args], settings)),
388
+ runCommand: config.runCommand ?? defaultRunCommand,
225
389
  }
390
+ this.cacheRoot = canonical(config.cacheRoot ?? join(tmpdir(), 'huaqiu-hardware-artifacts'))
391
+ this.glbTimeoutMs = config.glbTimeoutMs ?? 120_000
392
+ this.maxSourceBytes = config.maxSourceBytes ?? 32 * 1024 * 1024
226
393
  }
227
394
 
228
395
  /** Resolve configured installations from validated absolute paths only. */
@@ -237,21 +404,24 @@ export class HardwareArtifactService {
237
404
  }
238
405
  const candidates = kicadRoot === undefined
239
406
  ? { cli: [], kicad: [], eeschema: [], pcbnew: [] }
240
- : kicadCandidates(kicadCli && basename(kicadCli).toLowerCase().startsWith('kicad-cli') ? dirname(dirname(dirname(kicadCli))) : kicadRoot)
407
+ : kicadCandidates(kicadCli === undefined ? kicadRoot : installRootFromCli(kicadCli))
241
408
  const pcbEditor = existing(candidates.pcbnew)
242
409
  const schematicEditor = existing(candidates.eeschema)
243
410
  const projectManager = existing(candidates.kicad)
411
+ const version = kicadCli === undefined ? undefined : this.options.probeVersion(kicadCli)
244
412
  const kicad: InstallationInfo = kicadCli === undefined
245
413
  ? { configured: false, error: 'KiCad installation is not configured' }
246
- : {
247
- configured: true,
248
- root: kicadRoot,
249
- cli: kicadCli,
250
- ...(projectManager === undefined ? {} : { projectManager }),
251
- ...(pcbEditor === undefined ? {} : { pcbEditor }),
252
- ...(schematicEditor === undefined ? {} : { schematicEditor }),
253
- ...(this.options.probeVersion(kicadCli) === undefined ? {} : { version: this.options.probeVersion(kicadCli) }),
254
- }
414
+ : version === undefined
415
+ ? { configured: false, root: kicadRoot, cli: kicadCli, error: `${kicadCli} did not answer a version probe` }
416
+ : {
417
+ configured: true,
418
+ root: kicadRoot,
419
+ cli: kicadCli,
420
+ version,
421
+ ...(projectManager === undefined ? {} : { projectManager }),
422
+ ...(pcbEditor === undefined ? {} : { pcbEditor }),
423
+ ...(schematicEditor === undefined ? {} : { schematicEditor }),
424
+ }
255
425
 
256
426
  const solidRoot = this.config.solidcraftRoot ? canonical(this.config.solidcraftRoot) : undefined
257
427
  const solidExecutable = solidRoot === undefined ? undefined : existing(solidcraftCandidates(solidRoot))
@@ -312,7 +482,9 @@ export class HardwareArtifactService {
312
482
  try {
313
483
  manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as ProjectManifest
314
484
  } catch (error) {
315
- return { cwd, manifestPath, projects: [], issue: { code: 'bad-manifest', message: `invalid .hardware-engineering.json: ${String(error)}` } }
485
+ const result: DiscoveryResult = { cwd, manifestPath, projects: [], issue: { code: 'bad-manifest', message: `invalid .hardware-engineering.json: ${String(error)}` } }
486
+ this.lastDiscovery = result
487
+ return result
316
488
  }
317
489
  }
318
490
 
@@ -320,7 +492,9 @@ export class HardwareArtifactService {
320
492
  if (explicitProject !== undefined && explicitProject.trim() !== '') {
321
493
  const requested = isAbsolute(explicitProject) ? canonical(explicitProject) : resolve(cwd, explicitProject)
322
494
  if (!existsSync(requested)) {
323
- return { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects: [], issue: { code: 'missing-project', message: `${requested} does not exist` } }
495
+ const result: DiscoveryResult = { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects: [], issue: { code: 'missing-project', message: `${requested} does not exist` } }
496
+ this.lastDiscovery = result
497
+ return result
324
498
  }
325
499
  projectPaths.add(requested)
326
500
  } else if (manifest?.project !== undefined && manifest.project.trim() !== '') {
@@ -331,13 +505,17 @@ export class HardwareArtifactService {
331
505
 
332
506
  const projects: HardwareProject[] = [...projectPaths].sort().map(path => this.projectFrom(path, cwd, manifest))
333
507
  if (projects.length === 0) {
334
- return { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects, issue: { code: 'no-project', message: `no .kicad_pro found under ${cwd}` } }
508
+ const result: DiscoveryResult = { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects, issue: { code: 'no-project', message: `no .kicad_pro found under ${cwd}` } }
509
+ this.lastDiscovery = result
510
+ return result
335
511
  }
336
512
  if (projects.length > 1) {
337
- return { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects, issue: { code: 'selection-required', message: `${projects.length} projects found; select one explicitly` } }
513
+ const result: DiscoveryResult = { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects, issue: { code: 'selection-required', message: `${projects.length} projects found; select one explicitly` } }
514
+ this.lastDiscovery = result
515
+ return result
338
516
  }
339
517
  const selected = projects[0] as HardwareProject
340
- return {
518
+ const result: DiscoveryResult = {
341
519
  cwd,
342
520
  ...(manifest === undefined ? {} : { manifestPath }),
343
521
  projects,
@@ -346,6 +524,13 @@ export class HardwareArtifactService {
346
524
  ? { issue: { code: 'selection-required', message: 'select an artifact explicitly' } }
347
525
  : {}),
348
526
  }
527
+ this.lastDiscovery = result
528
+ return result
529
+ }
530
+
531
+ /** The most recent discovery, used to authorize source reads. */
532
+ discovery(): DiscoveryResult | undefined {
533
+ return this.lastDiscovery
349
534
  }
350
535
 
351
536
  private projectFrom(projectPath: string, cwd: string, manifest?: ProjectManifest): HardwareProject {
@@ -354,38 +539,78 @@ export class HardwareArtifactService {
354
539
  const resolvePath = (value: string): string =>
355
540
  isAbsolute(value) ? canonical(value) : resolve(dir, value)
356
541
 
357
- const schematicPath = manifest?.schematic !== undefined
358
- ? resolvePath(manifest.schematic)
359
- : existing([join(dir, `${name}.kicad_sch`), ...walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_sch'))])
360
- const boards = manifest?.boards !== undefined
361
- ? manifest.boards.map(board => artifact('pcb', resolvePath(board.path), projectPath))
362
- : walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_pcb')).map(path => artifact('pcb', path, projectPath))
542
+ // The root schematic is authoritative: an explicit manifest entry, then the
543
+ // project-named file, then a single unambiguous candidate. Unrelated
544
+ // sibling `.kicad_sch` files are never promoted to sheets.
545
+ const explicitSchematic = manifest?.schematic === undefined ? undefined : resolvePath(manifest.schematic)
546
+ let schematicPath = explicitSchematic !== undefined && existsSync(explicitSchematic) ? explicitSchematic : undefined
547
+ if (schematicPath === undefined) {
548
+ const named = join(dir, `${name}.kicad_sch`)
549
+ if (existsSync(named)) schematicPath = named
550
+ else {
551
+ const candidates = readdirSync(dir, { withFileTypes: true })
552
+ .filter(entry => entry.isFile() && entry.name.toLowerCase().endsWith('.kicad_sch'))
553
+ .map(entry => join(dir, entry.name))
554
+ .sort()
555
+ if (candidates.length === 1) schematicPath = candidates[0]
556
+ }
557
+ }
558
+
559
+ // Hierarchy comes from sheet references only, resolved recursively with a
560
+ // cycle guard: parsing the root must never advertise unrelated files.
561
+ const sheets: HardwareArtifact[] = []
562
+ if (schematicPath !== undefined) {
563
+ const visited = new Set<string>([canonical(schematicPath)])
564
+ const queue = childSheetFiles(canonical(schematicPath))
565
+ while (queue.length > 0) {
566
+ const next = queue.shift() as string
567
+ const canonicalNext = canonical(next)
568
+ if (visited.has(canonicalNext)) continue
569
+ visited.add(canonicalNext)
570
+ if (!existsSync(canonicalNext) || extname(canonicalNext).toLowerCase() !== '.kicad_sch') continue
571
+ sheets.push(artifact('schematic', canonicalNext, projectPath, canonical(schematicPath)))
572
+ queue.push(...childSheetFiles(canonicalNext))
573
+ }
574
+ }
575
+
576
+ // Board ranking: manifest ownership first, then the project-named board, then
577
+ // the only candidate. Multiple unowned boards stay ambiguous on purpose.
578
+ const manifestBoards = manifest?.boards === undefined
579
+ ? []
580
+ : manifest.boards
581
+ .filter(entry => existsSync(resolvePath(entry.path)))
582
+ .map(entry => artifact('pcb', resolvePath(entry.path), projectPath))
583
+ const scannedBoards = walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_pcb'))
584
+ .map(path => artifact('pcb', path, projectPath))
585
+ const boards = manifestBoards.length > 0
586
+ ? manifestBoards
587
+ : [...scannedBoards].sort((left, right) => boardRank(left, right, name))
588
+ const owned = boards.find(board => basename(board.path, '.kicad_pcb') === name) ?? boards[0]
589
+ const ownershipAmbiguous = manifestBoards.length === 0 && boards.length > 1
590
+ && basename(owned?.path ?? '', '.kicad_pcb') !== name
591
+
363
592
  const mechanical = manifest?.mechanical !== undefined
364
593
  ? manifest.mechanical.map(model => artifact('mechanical-3d', resolvePath(model.path), projectPath))
365
594
  : walkFiles(dir, file => MECHANICAL_EXTENSIONS.has(extname(file).toLowerCase()))
366
595
  .map(path => artifact('mechanical-3d', path, projectPath))
367
- const sheets = schematicPath === undefined
368
- ? []
369
- : walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_sch'))
370
- .filter(path => path !== schematicPath && isInside(path, dir))
371
- .map(path => artifact('schematic', path, projectPath, schematicPath))
372
596
 
373
597
  const sourceSchematic = schematicPath === undefined ? undefined : artifact('schematic', schematicPath, projectPath)
374
- const sourceBoard = boards[0]
598
+ const sourceBoard = ownershipAmbiguous ? undefined : owned
375
599
  return {
376
600
  path: projectPath,
377
601
  name,
378
- ...(sourceSchematic === undefined ? {} : { schematic: sourceSchematic }),
602
+ ...(sourceSchematic === undefined ? {} : { rootSheet: sourceSchematic, schematic: sourceSchematic }),
379
603
  ...(sourceSchematic === undefined ? {} : {
380
604
  bom: { ...artifact('bom', sourceSchematic.path, projectPath, sourceSchematic.path), title: `BOM — ${sourceSchematic.title}` },
381
605
  }),
382
606
  ...(sourceBoard === undefined ? {} : {
383
607
  pcb3d: { ...artifact('pcb-3d', sourceBoard.path, projectPath, sourceBoard.path), title: `3D — ${sourceBoard.title}` },
608
+ defaultBoard: sourceBoard.path,
384
609
  }),
385
610
  sheets,
386
611
  boards,
387
612
  mechanical,
388
- selectionRequired: boards.length > 1 || sheets.length > 1,
613
+ selectionRequired: boards.length > 1 && ownershipAmbiguous,
389
614
  }
390
615
  }
391
616
 
@@ -393,31 +618,391 @@ export class HardwareArtifactService {
393
618
  open(request: OpenArtifactRequest): OpenArtifactResult {
394
619
  const path = canonical(request.artifactPath)
395
620
  if (!existsSync(path)) {
396
- throw Object.assign(new Error(`artifact does not exist: ${path}`), { code: 'missing-artifact', status: 404 })
621
+ throw errorWithCode(`artifact does not exist: ${path}`, 'missing-artifact', 404)
397
622
  }
398
623
  const installed = this.installations()
399
- const isKicad = request.application === 'kicad'
624
+ const ext = extname(path).toLowerCase()
400
625
  let command: string | undefined
401
- if (isKicad) {
402
- const ext = extname(path).toLowerCase()
403
- if (ext === '.kicad_sch') command = installed.kicad.schematicEditor
404
- else if (ext === '.kicad_pcb') command = installed.kicad.pcbEditor
405
- else if (ext === '.kicad_pro') command = installed.kicad.projectManager
406
- else throw Object.assign(new Error(`unsupported KiCad artifact: ${ext}`), { code: 'unsupported-artifact', status: 415 })
407
- if (command === undefined) {
408
- throw Object.assign(new Error('the configured KiCad installation has no editor for this artifact'), { code: 'missing-executable', status: 412 })
409
- }
410
- } else {
411
- command = installed.solidcraft.executable
412
- if (command === undefined) {
413
- throw Object.assign(new Error('SolidCraft is not configured'), { code: 'not-configured', status: 412 })
414
- }
415
- if (!MECHANICAL_EXTENSIONS.has(extname(path).toLowerCase())) {
416
- throw Object.assign(new Error(`unsupported SolidCraft artifact: ${extname(path)}`), { code: 'unsupported-artifact', status: 415 })
417
- }
626
+ if (ext === '.kicad_sch') command = installed.kicad.schematicEditor
627
+ else if (ext === '.kicad_pcb') command = installed.kicad.pcbEditor
628
+ else if (ext === '.kicad_pro') command = installed.kicad.projectManager
629
+ else throw errorWithCode(`unsupported KiCad artifact: ${ext}`, 'unsupported-artifact', 415)
630
+ if (command === undefined) {
631
+ throw errorWithCode('the configured KiCad installation has no editor for this artifact', 'missing-executable', 412)
418
632
  }
419
633
  const settings = { cwd: dirname(path), detached: true, stdio: 'ignore' as const, windowsHide: true, shell: false as const }
420
634
  const child = this.options.spawnProcess(command, [path], settings)
421
635
  return { launched: true, command, args: [path], cwd: settings.cwd, ...(child.pid === undefined ? {} : { pid: child.pid }) }
422
636
  }
637
+
638
+ /** Workspace roots a read may target: explicit request, last discovery, config. */
639
+ private authorizedRoots(roots?: readonly string[]): string[] {
640
+ const candidates = new Set<string>()
641
+ for (const root of roots ?? []) {
642
+ if (root !== undefined && root.trim() !== '') candidates.add(canonical(root))
643
+ }
644
+ const discovered = this.lastDiscovery?.cwd
645
+ if (discovered !== undefined) candidates.add(canonical(discovered))
646
+ return [...candidates]
647
+ }
648
+
649
+ /**
650
+ * Authorize one artifact path: canonical, realpath-checked, inside a
651
+ * workspace root, and of an expected type. A browser request cannot turn
652
+ * this into an arbitrary filesystem read, even from loopback.
653
+ */
654
+ private authorize(artifactPath: string, roots: readonly string[] | undefined): { path: string; kind: 'schematic' | 'pcb' } {
655
+ if (!isAbsolute(artifactPath)) {
656
+ throw errorWithCode('artifact identity must be an absolute path', 'invalid-identity', 400)
657
+ }
658
+ const requested = canonical(artifactPath)
659
+ const kind = SOURCE_EXTENSIONS[extname(requested).toLowerCase()]
660
+ if (kind === undefined) {
661
+ throw errorWithCode(`unsupported artifact type: ${extname(requested)}`, 'unsupported-artifact', 415)
662
+ }
663
+ const authorized = this.authorizedRoots(roots)
664
+ if (authorized.length === 0) {
665
+ throw errorWithCode('no authorized workspace is known to the host', 'unauthorized', 403)
666
+ }
667
+ // Boundary check before existence: a path outside the workspace is refused
668
+ // whether or not it exists, so the route cannot probe the filesystem.
669
+ const permittedLexically = authorized.some((root) => isInside(requested, canonical(root)))
670
+ if (!permittedLexically) {
671
+ throw errorWithCode('artifact is outside the authorized workspace', 'unauthorized', 403)
672
+ }
673
+ if (!existsSync(requested)) {
674
+ throw errorWithCode(`artifact does not exist: ${requested}`, 'missing-artifact', 404)
675
+ }
676
+ const real = realOrUndefined(requested)
677
+ if (real === undefined) {
678
+ throw errorWithCode(`artifact cannot be resolved: ${requested}`, 'invalid-identity', 400)
679
+ }
680
+ const permitted = authorized.some((root) => {
681
+ const realRoot = realOrUndefined(root) ?? root
682
+ return isInside(real, realRoot)
683
+ })
684
+ if (!permitted) {
685
+ throw errorWithCode('artifact is outside the authorized workspace', 'unauthorized', 403)
686
+ }
687
+ const info = statSync(real)
688
+ if (!info.isFile()) {
689
+ throw errorWithCode(`artifact is not a regular file: ${requested}`, 'invalid-identity', 400)
690
+ }
691
+ if ((SOURCE_EXTENSIONS[extname(real).toLowerCase()]) === undefined) {
692
+ throw errorWithCode('artifact type changed during resolution', 'unsupported-artifact', 415)
693
+ }
694
+ return { path: real, kind: SOURCE_EXTENSIONS[extname(real).toLowerCase()] as 'schematic' | 'pcb' }
695
+ }
696
+
697
+ /** Saved source text plus a content-addressed revision. */
698
+ async readSource(request: SourceRequest): Promise<SourceResult> {
699
+ const { path, kind } = this.authorize(request.artifactPath, request.roots)
700
+ const info = statSync(path)
701
+ if (info.size > this.maxSourceBytes) {
702
+ throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, 'too-large', 413)
703
+ }
704
+ const body = await readFile(path)
705
+ const revision = createHash('sha256').update(body).digest('hex')
706
+ if (request.expectedRevision !== undefined && request.expectedRevision !== ''
707
+ && request.expectedRevision !== revision) {
708
+ throw errorWithCode(
709
+ `source changed since it was selected (expected ${request.expectedRevision}, found ${revision})`,
710
+ 'stale-revision',
711
+ 409,
712
+ )
713
+ }
714
+ return {
715
+ path,
716
+ kind,
717
+ revision,
718
+ bytes: body.byteLength,
719
+ mtimeMs: info.mtimeMs,
720
+ text: body.toString('utf8'),
721
+ }
722
+ }
723
+
724
+ private sourceRevision(path: string): string {
725
+ const info = statSync(path)
726
+ if (info.size > this.maxSourceBytes) {
727
+ throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, 'too-large', 413)
728
+ }
729
+ return createHash('sha256').update(readFileSync(path)).digest('hex')
730
+ }
731
+
732
+ /** Cache directory for one board's derived outputs. */
733
+ private glbDirectory(boardPath: string): string {
734
+ const digest = createHash('sha256').update(boardPath).digest('hex').slice(0, 16)
735
+ return join(this.cacheRoot, 'glb', digest)
736
+ }
737
+
738
+ /**
739
+ * Generate (or reuse) the GLB for one board.
740
+ *
741
+ * - cache key includes the source content hash, so same-size/same-mtime edits invalidate
742
+ * - one in-flight export is shared by concurrent callers for the same revision
743
+ * - output is written to a temp file and renamed only after it validates
744
+ * - a timeout or abort leaves no partial file behind
745
+ */
746
+ async exportGlb(request: GlbRequest): Promise<GlbResult> {
747
+ const { path } = this.authorize(request.artifactPath, request.roots)
748
+ if (extname(path).toLowerCase() !== '.kicad_pcb') {
749
+ throw errorWithCode('GLB export requires a .kicad_pcb artifact', 'unsupported-artifact', 415)
750
+ }
751
+ const installed = this.installations()
752
+ if (!installed.kicad.configured || installed.kicad.cli === undefined) {
753
+ throw errorWithCode(
754
+ installed.kicad.error ?? 'the configured KiCad installation has no kicad-cli',
755
+ 'not-configured',
756
+ 412,
757
+ )
758
+ }
759
+ const cli = installed.kicad.cli
760
+ const revision = this.sourceRevision(path)
761
+ const key = `${path}:${revision}`
762
+ const cached = this.glbCache.get(key)
763
+ if (cached !== undefined && existsSync(cached.file)) {
764
+ const info = statSync(cached.file)
765
+ return { ...cached, bytes: info.size, cached: true }
766
+ }
767
+ const pending = this.glbPending.get(key)
768
+ if (pending !== undefined) return pending
769
+
770
+ const directory = this.glbDirectory(path)
771
+ const target = join(directory, `board-${revision.slice(0, 16)}.glb`)
772
+ const running = (async (): Promise<GlbResult> => {
773
+ mkdirSync(directory, { recursive: true })
774
+ const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`)
775
+ mkdirSync(tempDirectory, { recursive: true })
776
+ const tempFile = join(tempDirectory, 'board.glb')
777
+ try {
778
+ const result = await this.options.runCommand(
779
+ cli,
780
+ ['pcb', 'export', 'glb', '--output', tempFile, path],
781
+ { cwd: dirname(path), timeoutMs: this.glbTimeoutMs, ...(request.signal === undefined ? {} : { signal: request.signal }) },
782
+ )
783
+ if (result.timedOut) {
784
+ throw errorWithCode(`kicad-cli pcb export glb timed out after ${this.glbTimeoutMs} ms`, 'export-timeout', 504)
785
+ }
786
+ if (result.exitCode !== 0) {
787
+ const detail = (result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)
788
+ throw errorWithCode(`kicad-cli pcb export glb failed: ${detail}`, 'export-failed', 502)
789
+ }
790
+ if (!existsSync(tempFile)) {
791
+ throw errorWithCode('kicad-cli pcb export glb produced no output', 'export-failed', 502)
792
+ }
793
+ const bytes = statSync(tempFile).size
794
+ if (bytes === 0 || readFileSync(tempFile).subarray(0, 4).toString('ascii') !== 'glTF') {
795
+ throw errorWithCode('kicad-cli wrote an invalid GLB', 'export-failed', 502)
796
+ }
797
+ renameSync(tempFile, target)
798
+ const generated = {
799
+ path,
800
+ revision,
801
+ bytes,
802
+ generatedAt: new Date().toISOString(),
803
+ cached: false,
804
+ file: target,
805
+ } satisfies GlbResult
806
+ this.glbCache.set(key, generated)
807
+ return generated
808
+ } finally {
809
+ rmSync(tempDirectory, { recursive: true, force: true })
810
+ }
811
+ })()
812
+
813
+ this.glbPending.set(key, running)
814
+ try {
815
+ return await running
816
+ } finally {
817
+ this.glbPending.delete(key)
818
+ }
819
+ }
820
+
821
+ /**
822
+ * Grouped BOM for one saved root schematic.
823
+ *
824
+ * Reuses KiCad's own BOM extraction (`kicad-cli sch export bom`), the same
825
+ * authoritative source `analyze_kicad_module` consumes, rather than building a
826
+ * second component analyser. Grouping key is every non-reference column, so
827
+ * different MPNs never merge and DNP stays explicit.
828
+ */
829
+ async exportBom(request: {
830
+ readonly artifactPath: string
831
+ readonly roots?: readonly string[]
832
+ readonly signal?: AbortSignal
833
+ }): Promise<BomResult> {
834
+ const { path, kind } = this.authorize(request.artifactPath, request.roots)
835
+ if (kind !== 'schematic') {
836
+ throw errorWithCode('BOM export requires a .kicad_sch artifact', 'unsupported-artifact', 415)
837
+ }
838
+ const installed = this.installations()
839
+ if (!installed.kicad.configured || installed.kicad.cli === undefined) {
840
+ throw errorWithCode(installed.kicad.error ?? 'the configured KiCad installation has no kicad-cli', 'not-configured', 412)
841
+ }
842
+ const revision = this.sourceRevision(path)
843
+ const key = `${path}:${revision}`
844
+ const cached = this.bomCache.get(key)
845
+ if (cached !== undefined) return { ...cached, cached: true }
846
+
847
+ const directory = join(this.cacheRoot, 'bom', createHash('sha256').update(path).digest('hex').slice(0, 16))
848
+ const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`)
849
+ mkdirSync(tempDirectory, { recursive: true })
850
+ const tempFile = join(tempDirectory, 'bom.csv')
851
+ try {
852
+ const result = await this.options.runCommand(
853
+ installed.kicad.cli,
854
+ ['sch', 'export', 'bom', '--output', tempFile, path],
855
+ { cwd: dirname(path), timeoutMs: 60_000, ...(request.signal === undefined ? {} : { signal: request.signal }) },
856
+ )
857
+ if (result.timedOut) throw errorWithCode('kicad-cli sch export bom timed out', 'export-timeout', 504)
858
+ if (result.exitCode !== 0) {
859
+ const detail = (result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)
860
+ throw errorWithCode(`kicad-cli sch export bom failed: ${detail}`, 'export-failed', 502)
861
+ }
862
+ if (!existsSync(tempFile)) throw errorWithCode('kicad-cli produced no BOM output', 'export-failed', 502)
863
+ const rows = groupBomRows(parseCsv(readFileSync(tempFile, 'utf8')))
864
+ const generated: BomResult = {
865
+ path,
866
+ revision,
867
+ generatedAt: new Date().toISOString(),
868
+ cached: false,
869
+ rows,
870
+ source: 'kicad-cli-bom',
871
+ }
872
+ this.bomCache.set(key, generated)
873
+ return generated
874
+ } finally {
875
+ rmSync(tempDirectory, { recursive: true, force: true })
876
+ }
877
+ }
878
+
879
+ /** Serve a generated GLB file, re-validating the cache entry first. */ glbFile(boardPath: string, revision: string): string {
880
+ const key = `${canonical(boardPath)}:${revision}`
881
+ const entry = this.glbCache.get(key)
882
+ if (entry === undefined || !existsSync(entry.file)) {
883
+ throw errorWithCode('generated GLB is not available for this revision', 'stale-revision', 409)
884
+ }
885
+ return entry.file
886
+ }
887
+
888
+ /** Drop cached derived outputs for one board (or all of them). */
889
+ clearCache(boardPath?: string): void {
890
+ if (boardPath === undefined) {
891
+ this.glbCache.clear()
892
+ rmSync(this.cacheRoot, { recursive: true, force: true })
893
+ return
894
+ }
895
+ const prefix = `${canonical(boardPath)}:`
896
+ for (const key of [...this.glbCache.keys()]) {
897
+ if (key.startsWith(prefix)) this.glbCache.delete(key)
898
+ }
899
+ rmSync(this.glbDirectory(canonical(boardPath)), { recursive: true, force: true })
900
+ }
901
+ }
902
+
903
+ /** Ownership order: project-named board first, then shallower, then alphabetical. */
904
+ function boardRank(left: HardwareArtifact, right: HardwareArtifact, projectName: string): number { const leftNamed = basename(left.path, '.kicad_pcb') === projectName ? 0 : 1
905
+ const rightNamed = basename(right.path, '.kicad_pcb') === projectName ? 0 : 1
906
+ if (leftNamed !== rightNamed) return leftNamed - rightNamed
907
+ const leftDepth = left.path.split(sep).length
908
+ const rightDepth = right.path.split(sep).length
909
+ if (leftDepth !== rightDepth) return leftDepth - rightDepth
910
+ return left.path.localeCompare(right.path)
911
+ }
912
+
913
+ /** RFC4180-style CSV reader: quoted fields, doubled quotes, CRLF rows. */
914
+ export function parseCsv(text: string): string[][] {
915
+ const rows: string[][] = []
916
+ let row: string[] = []
917
+ let field = ''
918
+ let quoted = false
919
+ const source = text.replace(/^\uFEFF/u, '')
920
+ for (let index = 0; index < source.length; index += 1) {
921
+ const char = source[index]
922
+ if (quoted) {
923
+ if (char === '"') {
924
+ if (source[index + 1] === '"') {
925
+ field += '"'
926
+ index += 1
927
+ } else {
928
+ quoted = false
929
+ }
930
+ } else {
931
+ field += char
932
+ }
933
+ continue
934
+ }
935
+ if (char === '"') {
936
+ quoted = true
937
+ } else if (char === ',') {
938
+ row.push(field)
939
+ field = ''
940
+ } else if (char === '\r') {
941
+ continue
942
+ } else if (char === '\n') {
943
+ row.push(field)
944
+ rows.push(row)
945
+ row = []
946
+ field = ''
947
+ } else {
948
+ field += char
949
+ }
950
+ }
951
+ if (field !== '' || row.length > 0) {
952
+ row.push(field)
953
+ rows.push(row)
954
+ }
955
+ return rows.filter(cells => cells.some(cell => cell.trim() !== ''))
956
+ }
957
+
958
+ /**
959
+ * Group KiCad's per-reference BOM rows.
960
+ *
961
+ * Identity is every column except the reference and quantity columns, so a
962
+ * different MPN or a DNP flag always produces a separate line; ordering follows
963
+ * the first reference seen, which keeps the table stable between reads.
964
+ */
965
+ export function groupBomRows(table: readonly string[][]): BomRow[] {
966
+ const [header, ...body] = table
967
+ if (header === undefined) return []
968
+ const columns = header.map(cell => cell.trim())
969
+ const referenceIndex = columns.findIndex(cell => /^reference$/iu.test(cell))
970
+ const quantityIndex = columns.findIndex(cell => /^quantity$/iu.test(cell))
971
+ const valueIndex = columns.findIndex(cell => /^value$/iu.test(cell))
972
+ const footprintIndex = columns.findIndex(cell => /^footprint$/iu.test(cell))
973
+ const dnpIndex = columns.findIndex(cell => /^dnp$/iu.test(cell))
974
+ const groups = new Map<string, { references: string[]; fields: Record<string, string>; dnp: boolean }>()
975
+ for (const cells of body) {
976
+ const reference = referenceIndex === -1 ? '' : (cells[referenceIndex] ?? '').trim()
977
+ if (reference === '') continue
978
+ const fields: Record<string, string> = {}
979
+ columns.forEach((column, index) => {
980
+ if (index === referenceIndex || index === quantityIndex || index === valueIndex
981
+ || index === footprintIndex || index === dnpIndex) return
982
+ const text = (cells[index] ?? '').trim()
983
+ if (text !== '') fields[column] = text
984
+ })
985
+ const dnpText = dnpIndex === -1 ? '' : (cells[dnpIndex] ?? '').trim()
986
+ const dnp = /^(1|true|yes|dnp|x)$/iu.test(dnpText)
987
+ const identity = JSON.stringify([
988
+ valueIndex === -1 ? '' : (cells[valueIndex] ?? '').trim(),
989
+ footprintIndex === -1 ? '' : (cells[footprintIndex] ?? '').trim(),
990
+ dnp,
991
+ Object.fromEntries(Object.entries(fields).sort(([a], [b]) => a.localeCompare(b))),
992
+ ])
993
+ const group = groups.get(identity) ?? { references: [], fields, dnp }
994
+ group.references.push(reference)
995
+ groups.set(identity, group)
996
+ }
997
+ return [...groups.entries()].map(([identity, group]) => {
998
+ const [value, footprint, dnp] = JSON.parse(identity) as [string, string, boolean]
999
+ return {
1000
+ references: group.references,
1001
+ quantity: group.references.length,
1002
+ value,
1003
+ footprint,
1004
+ dnp,
1005
+ fields: group.fields,
1006
+ } satisfies BomRow
1007
+ })
423
1008
  }