@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/src/service.ts CHANGED
@@ -12,6 +12,13 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameS
12
12
  import { readFile } from 'node:fs/promises'
13
13
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
14
14
  import { tmpdir } from 'node:os'
15
+ import {
16
+ DEFAULT_ORDER_BASE_URL, DEFAULT_ORDER_PAGE_BASE, multipartBody,
17
+ ORDER_PATHS, orderBomCsv, orderBomRows, orderIdsFromUrl, packageName, parsePositions,
18
+ pcbOrderForm, pcbOrderUrl, positionsCsv, readBoardFacts, readExportDirectory, smtOrderForm,
19
+ smtOrderUrl, smtOrderUrlFromBackend, zipPackage,
20
+ type BoardFacts,
21
+ } from './order.js'
15
22
 
16
23
  export type ArtifactKind = 'schematic' | 'pcb' | 'pcb-3d' | 'bom' | 'mechanical-3d'
17
24
  /** Native handoff is KiCad-only in this POC; SolidCraft stays agent context. */
@@ -90,8 +97,13 @@ export interface OpenArtifactResult {
90
97
  export interface SourceRequest {
91
98
  readonly artifactPath: string
92
99
  readonly expectedRevision?: string
93
- /** Workspace roots the caller is currently authorized to read. */
100
+ /**
101
+ * Roots the caller names. They are *added* to the roots the host resolved
102
+ * for {@link sessionId}; naming one never revokes another.
103
+ */
94
104
  readonly roots?: readonly string[]
105
+ /** DSH session the read belongs to; its workspace is the authorization base. */
106
+ readonly sessionId?: string
95
107
  }
96
108
 
97
109
  export interface SourceResult {
@@ -106,6 +118,7 @@ export interface SourceResult {
106
118
  export interface GlbRequest {
107
119
  readonly artifactPath: string
108
120
  readonly roots?: readonly string[]
121
+ readonly sessionId?: string
109
122
  readonly signal?: AbortSignal
110
123
  }
111
124
 
@@ -137,15 +150,111 @@ export interface BomResult {
137
150
  readonly source: 'kicad-cli-bom'
138
151
  }
139
152
 
153
+ export interface OrderPackageSummary {
154
+ readonly zipName: string
155
+ readonly zipBytes: number
156
+ readonly files: readonly { readonly name: string; readonly bytes: number }[]
157
+ }
158
+
159
+ /** A prepared fabrication package: what would be uploaded, nothing sent yet. */
160
+ export interface FabricationResult {
161
+ readonly boardPath: string
162
+ readonly revision: string
163
+ readonly generatedAt: string
164
+ readonly facts: BoardFacts
165
+ readonly archive: OrderPackageSummary
166
+ /** Assembly inputs, present when a schematic was supplied. */
167
+ readonly assembly?: {
168
+ readonly positions: number
169
+ readonly bomLines: number
170
+ readonly positionsBytes: number
171
+ readonly bomBytes: number
172
+ }
173
+ }
174
+
175
+ export interface OrderConfigInfo {
176
+ readonly configured: boolean
177
+ readonly baseUrl: string
178
+ /** True when a signed-in session or a configured token can sign the page. */
179
+ readonly hasToken: boolean
180
+ readonly provider: 'huaqiu'
181
+ }
182
+
183
+ export interface PlaceOrderRequest {
184
+ readonly kind: 'pcb' | 'smt'
185
+ readonly boardPath: string
186
+ readonly schematicPath?: string
187
+ readonly roots?: readonly string[]
188
+ readonly sessionId?: string
189
+ readonly quantity?: number
190
+ readonly signal?: AbortSignal
191
+ /** Open the resulting page in the default browser; defaults to true. */
192
+ readonly launch?: boolean
193
+ }
194
+
195
+ export interface PlaceOrderResult {
196
+ readonly kind: 'pcb' | 'smt'
197
+ /** The exact URL KiCad's own action loads into its order webview. */
198
+ readonly orderUrl: string
199
+ /** The backend's raw URL, before KiCad's own query parameters were added. */
200
+ readonly responseUrl: string
201
+ /** True when the host handed `orderUrl` to the OS default browser. */
202
+ readonly launched: boolean
203
+ readonly launcher?: string
204
+ readonly status: 'launched' | 'ready'
205
+ readonly message: string
206
+ readonly endpoint: string
207
+ readonly facts: BoardFacts
208
+ readonly archive: OrderPackageSummary
209
+ readonly assembly?: FabricationResult['assembly']
210
+ }
211
+
140
212
  export interface HardwareArtifactsOptions {
141
213
  readonly kicadRoot?: string
142
214
  readonly solidcraftRoot?: string
215
+ /** Origin for the place-order endpoints; defaults to the Huaqiu host. */
216
+ readonly orderBaseUrl?: string
217
+ readonly orderPageBase?: string
218
+ /** Huaqiu access token; only ever sent to the order endpoint. */
219
+ readonly accessToken?: string
220
+ /**
221
+ * Resolves the signed-in Huaqiu token when no explicit token is configured.
222
+ *
223
+ * hqpcb is a Huaqiu business, so the login that feeds the eda.cn API is also
224
+ * the token the order page expects — there is no second credential.
225
+ */
226
+ readonly authToken?: () => Promise<string | null>
227
+ /** Injectable transport for tests; defaults to global fetch. */
228
+ readonly postOrder?: (url: string, init: {
229
+ readonly body: Buffer
230
+ readonly contentType: string
231
+ readonly headers?: Readonly<Record<string, string>>
232
+ readonly signal?: AbortSignal
233
+ }) => Promise<{ readonly status: number; readonly text: string }>
234
+ /**
235
+ * Live accessor for the user-configured roots.
236
+ *
237
+ * The plugin passes the profile config reference, so a settings write that
238
+ * replaces a volatile field is visible on the next validation without the
239
+ * service caching a start-time snapshot.
240
+ */
241
+ readonly settings?: () => {
242
+ readonly kicadRoot?: string
243
+ readonly solidcraftRoot?: string
244
+ readonly orderBaseUrl?: string
245
+ readonly accessToken?: string
246
+ }
143
247
  readonly probeVersion?: (executable: string) => string | undefined
144
248
  readonly spawnProcess?: (
145
249
  command: string,
146
250
  args: readonly string[],
147
251
  options: { cwd: string; detached: boolean; stdio: 'ignore'; windowsHide: boolean; shell: false },
148
252
  ) => Pick<ChildProcess, 'pid'>
253
+ /**
254
+ * Command used to hand a URL to the OS. Defaults to `open` on macOS,
255
+ * `rundll32 url.dll,FileProtocolHandler` on Windows and `xdg-open` elsewhere.
256
+ */
257
+ readonly openExternal?: (url: string) => { readonly command: string; readonly args: readonly string[] }
149
258
  /** Runs one short-lived CLI command and returns its exit facts. */
150
259
  readonly runCommand?: (
151
260
  command: string,
@@ -200,10 +309,138 @@ function realOrUndefined(path: string): string | undefined {
200
309
  }
201
310
  }
202
311
 
312
+ /**
313
+ * Identity of one authorization scope. DSH sessions are the scope; an embed
314
+ * without sessions (tests, a bare host) shares the default entry.
315
+ */
316
+ function scopeKey(sessionId?: string): string {
317
+ return sessionId === undefined || sessionId === '' ? '' : sessionId
318
+ }
319
+
320
+ /**
321
+ * A caller-named root, read as "the workspace this artifact belongs to".
322
+ *
323
+ * Callers may name a project file by mistake (the project `.kicad_pro` is the
324
+ * path the panel holds), and a file path authorizes nothing: no artifact is
325
+ * inside another file's path. Resolving to the containing directory keeps the
326
+ * caller's intent without widening beyond it.
327
+ */
328
+ function rootOf(root: string): string {
329
+ const real = realOrUndefined(root) ?? canonical(root)
330
+ try {
331
+ return statSync(real).isDirectory() ? real : dirname(real)
332
+ } catch {
333
+ return real
334
+ }
335
+ }
336
+
337
+ /** Roots a discovery proved reachable: the workspace and every adopted project. */
338
+ function discoveredRoots(discovery: DiscoveryResult | undefined): string[] {
339
+ if (discovery === undefined) return []
340
+ const roots = new Set<string>([discovery.cwd])
341
+ for (const project of discovery.projects) roots.add(dirname(project.path))
342
+ return [...roots]
343
+ }
344
+
203
345
  function errorWithCode(message: string, code: string, status: number): Error {
204
346
  return Object.assign(new Error(message), { code, status })
205
347
  }
206
348
 
349
+ /**
350
+ * POST one multipart order payload.
351
+ *
352
+ * Kept out of the class so tests can inject their own transport; the default
353
+ * has a hard timeout and never logs the body (it carries the access token).
354
+ */
355
+ async function defaultPostOrder(url: string, init: {
356
+ readonly body: Buffer
357
+ readonly contentType: string
358
+ readonly headers?: Readonly<Record<string, string>>
359
+ readonly signal?: AbortSignal
360
+ }): Promise<{ readonly status: number; readonly text: string }> {
361
+ const controller = new AbortController()
362
+ const timer = setTimeout(() => { controller.abort() }, 90_000)
363
+ const forward = (): void => { controller.abort() }
364
+ init.signal?.addEventListener('abort', forward, { once: true })
365
+ try {
366
+ const response = await fetch(url, {
367
+ method: 'POST',
368
+ headers: {
369
+ ...init.headers,
370
+ 'content-type': init.contentType,
371
+ 'content-length': String(init.body.byteLength),
372
+ },
373
+ // Node's fetch accepts a Buffer body; the DOM lib's BodyInit typing only
374
+ // names ArrayBuffer views backed by a non-shared buffer.
375
+ body: init.body as unknown as BodyInit,
376
+ signal: controller.signal,
377
+ })
378
+ return { status: response.status, text: await response.text() }
379
+ } finally {
380
+ clearTimeout(timer)
381
+ init.signal?.removeEventListener('abort', forward)
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Command that opens one URL in the OS default browser.
387
+ *
388
+ * A URL argument is passed to a fixed executable with `shell: false`, so the
389
+ * page can never become a shell command.
390
+ */
391
+ function defaultOpenExternal(url: string): { command: string; args: readonly string[] } {
392
+ if (process.platform === 'darwin') return { command: 'open', args: [url] }
393
+ if (process.platform === 'win32') return { command: 'rundll32', args: ['url.dll,FileProtocolHandler', url] }
394
+ return { command: 'xdg-open', args: [url] }
395
+ }
396
+
397
+ /**
398
+ * Validate an order page URL before handing it to the OS.
399
+ *
400
+ * The backend owns this URL, so the check is deliberately about *shape*, not
401
+ * about a specific host: HTTPS anywhere, plain HTTP only on loopback (local
402
+ * stubs), and never a URL with embedded credentials or a non-web scheme.
403
+ */
404
+ function externalUrlTarget(raw: string): string {
405
+ if (raw.length === 0 || raw.length > 4096) {
406
+ throw errorWithCode('the order URL is empty or too long', 'invalid-order-url', 400)
407
+ }
408
+ let parsed: URL
409
+ try {
410
+ parsed = new URL(raw)
411
+ } catch {
412
+ throw errorWithCode('the order URL is not a valid absolute URL', 'invalid-order-url', 400)
413
+ }
414
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
415
+ throw errorWithCode(`refusing to open a ${parsed.protocol} URL`, 'invalid-order-url', 400)
416
+ }
417
+ if (parsed.username !== '' || parsed.password !== '') {
418
+ throw errorWithCode('refusing to open a URL with embedded credentials', 'invalid-order-url', 400)
419
+ }
420
+ const host = parsed.hostname.replace(/^\[|\]$/gu, '')
421
+ const loopback = host === 'localhost' || host === '::1' || host === '127.0.0.1' || host.startsWith('127.')
422
+ if (parsed.protocol === 'http:' && !loopback) {
423
+ throw errorWithCode('refusing to open a plain-HTTP order URL outside loopback', 'invalid-order-url', 400)
424
+ }
425
+ return parsed.toString()
426
+ }
427
+
428
+ /** First backend-owned order URL in a place-order response. */
429
+ function orderUrlOf(body: unknown): string | undefined {
430
+ if (body === null || typeof body !== 'object') return undefined
431
+ const record = body as Record<string, unknown>
432
+ for (const key of ['url', 'redirect', 'data']) {
433
+ const value = record[key]
434
+ if (typeof value === 'string' && value !== '') return value
435
+ if (value !== null && typeof value === 'object') {
436
+ const nested = orderUrlOf(value)
437
+ if (nested !== undefined) return nested
438
+ }
439
+ }
440
+ const result = record.result
441
+ return result === undefined ? undefined : orderUrlOf(result)
442
+ }
443
+
207
444
  function walkFiles(root: string, predicate: (name: string) => boolean): string[] {
208
445
  const found: string[] = []
209
446
  const visit = (dir: string, depth: number): void => {
@@ -369,32 +606,62 @@ function solidcraftCandidates(root: string): string[] {
369
606
 
370
607
  /** Small, immutable host capability implementation. */
371
608
  export class HardwareArtifactService {
372
- private readonly options: Required<Pick<HardwareArtifactsOptions, 'spawnProcess' | 'probeVersion' | 'runCommand'>>
609
+ private readonly options: Required<Pick<
610
+ HardwareArtifactsOptions,
611
+ 'spawnProcess' | 'probeVersion' | 'runCommand' | 'openExternal'
612
+ >>
373
613
  private readonly cacheRoot: string
374
614
  private readonly glbTimeoutMs: number
375
615
  private readonly maxSourceBytes: number
376
- private lastDiscovery?: DiscoveryResult
616
+ /**
617
+ * Last discovery per scope — one entry per DSH session, plus the unscoped
618
+ * default used by tests and non-DSH embeds.
619
+ *
620
+ * It is a map rather than one field on purpose: a single "most recent
621
+ * discovery" is shared by every open viewer, so switching to a session in
622
+ * another workspace silently revoked the authorization of the viewer that
623
+ * stayed open. Authorization must never depend on who asked last.
624
+ */
625
+ private readonly discoveries = new Map<string, DiscoveryResult>()
377
626
  /** Completed GLB exports keyed by `sourcePath:revision`. */
378
627
  private readonly glbCache = new Map<string, GlbResult>()
379
628
  /** In-flight GLB exports keyed by the same key, so concurrent callers share one run. */
380
629
  private readonly glbPending = new Map<string, Promise<GlbResult>>()
381
630
  /** BOM projections keyed by `sourcePath:revision`. */
382
631
  private readonly bomCache = new Map<string, BomResult>()
632
+ /** Prepared fabrication packages keyed by board, revision and schematic. */
633
+ private readonly packageCache = new Map<string, FabricationResult & {
634
+ readonly archiveData: Uint8Array
635
+ readonly assemblyFiles?: { readonly positions: string; readonly bom: string }
636
+ }>()
383
637
 
384
638
  constructor(private readonly config: HardwareArtifactsOptions = {}) {
385
639
  this.options = {
386
640
  probeVersion: config.probeVersion ?? defaultVersionProbe,
387
641
  spawnProcess: config.spawnProcess ?? ((command, args, settings) => spawn(command, [...args], settings)),
388
642
  runCommand: config.runCommand ?? defaultRunCommand,
643
+ openExternal: config.openExternal ?? defaultOpenExternal,
389
644
  }
390
645
  this.cacheRoot = canonical(config.cacheRoot ?? join(tmpdir(), 'huaqiu-hardware-artifacts'))
391
646
  this.glbTimeoutMs = config.glbTimeoutMs ?? 120_000
392
647
  this.maxSourceBytes = config.maxSourceBytes ?? 32 * 1024 * 1024
393
648
  }
394
649
 
650
+ /** Configured roots, read live so a settings write is visible immediately. */
651
+ private roots(): { kicadRoot?: string; solidcraftRoot?: string } {
652
+ const live = this.config.settings?.()
653
+ const kicadRoot = live?.kicadRoot ?? this.config.kicadRoot
654
+ const solidcraftRoot = live?.solidcraftRoot ?? this.config.solidcraftRoot
655
+ return {
656
+ ...(kicadRoot === undefined ? {} : { kicadRoot }),
657
+ ...(solidcraftRoot === undefined ? {} : { solidcraftRoot }),
658
+ }
659
+ }
660
+
395
661
  /** Resolve configured installations from validated absolute paths only. */
396
662
  installations(): Installations {
397
- const kicadRoot = this.config.kicadRoot ? canonical(this.config.kicadRoot) : undefined
663
+ const roots = this.roots()
664
+ const kicadRoot = roots.kicadRoot ? canonical(roots.kicadRoot) : undefined
398
665
  let kicadCli: string | undefined
399
666
  if (kicadRoot !== undefined) {
400
667
  const cliPaths = basename(kicadRoot).toLowerCase().startsWith('kicad-cli')
@@ -423,7 +690,7 @@ export class HardwareArtifactService {
423
690
  ...(schematicEditor === undefined ? {} : { schematicEditor }),
424
691
  }
425
692
 
426
- const solidRoot = this.config.solidcraftRoot ? canonical(this.config.solidcraftRoot) : undefined
693
+ const solidRoot = roots.solidcraftRoot ? canonical(roots.solidcraftRoot) : undefined
427
694
  const solidExecutable = solidRoot === undefined ? undefined : existing(solidcraftCandidates(solidRoot))
428
695
  const solidcraft: InstallationInfo = solidExecutable === undefined
429
696
  ? { configured: false, error: 'SolidCraft installation is not configured' }
@@ -445,6 +712,10 @@ export class HardwareArtifactService {
445
712
  /** Compact agent context: validated paths only, no project inventory dump. */
446
713
  environmentText(current?: DiscoveryResult): string {
447
714
  const installed = this.installations()
715
+ // The prompt has no session of its own; speaking for the only scope that
716
+ // ever discovered is honest, and with several open workspaces it says
717
+ // nothing rather than naming another session's project.
718
+ const scope = current ?? this.soleDiscovery()
448
719
  const lines = ['<hardware_environment>']
449
720
  lines.push('KiCad:')
450
721
  lines.push(` configured: ${String(installed.kicad.configured)}`)
@@ -457,12 +728,12 @@ export class HardwareArtifactService {
457
728
  lines.push(` configured: ${String(installed.solidcraft.configured)}`)
458
729
  if (installed.solidcraft.executable !== undefined) lines.push(` executable: ${installed.solidcraft.executable}`)
459
730
  if (installed.solidcraft.error !== undefined) lines.push(` error: ${installed.solidcraft.error}`)
460
- if (current?.selected !== undefined) {
731
+ if (scope?.selected !== undefined) {
461
732
  lines.push('Current project:')
462
- lines.push(` root: ${current.cwd}`)
463
- lines.push(` project: ${current.selected.path}`)
464
- if (current.selected.schematic !== undefined) lines.push(` schematic: ${current.selected.schematic.path}`)
465
- const board = current.selected.boards[0]
733
+ lines.push(` root: ${scope.cwd}`)
734
+ lines.push(` project: ${scope.selected.path}`)
735
+ if (scope.selected.schematic !== undefined) lines.push(` schematic: ${scope.selected.schematic.path}`)
736
+ const board = scope.selected.boards[0]
466
737
  if (board !== undefined) lines.push(` selected_pcb: ${board.path}`)
467
738
  }
468
739
  lines.push('</hardware_environment>')
@@ -473,8 +744,13 @@ export class HardwareArtifactService {
473
744
  * Deterministic discovery. An explicit project or manifest wins; otherwise
474
745
  * exactly one `.kicad_pro` may be selected automatically. Ambiguity is
475
746
  * returned as a selection requirement, never resolved by taking the first.
747
+ *
748
+ * @param cwdInput - workspace directory to walk.
749
+ * @param explicitProject - project chosen by the user, absolute or cwd-relative.
750
+ * @param sessionId - DSH session the discovery belongs to. Recording it per
751
+ * session is what keeps one open viewer from revoking another's roots.
476
752
  */
477
- discover(cwdInput: string, explicitProject?: string): DiscoveryResult {
753
+ discover(cwdInput: string, explicitProject?: string, sessionId?: string): DiscoveryResult {
478
754
  const cwd = canonical(cwdInput)
479
755
  const manifestPath = join(cwd, '.hardware-engineering.json')
480
756
  let manifest: ProjectManifest | undefined
@@ -482,9 +758,12 @@ export class HardwareArtifactService {
482
758
  try {
483
759
  manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as ProjectManifest
484
760
  } catch (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
761
+ return this.remember({
762
+ cwd,
763
+ manifestPath,
764
+ projects: [],
765
+ issue: { code: 'bad-manifest', message: `invalid .hardware-engineering.json: ${String(error)}` },
766
+ }, sessionId)
488
767
  }
489
768
  }
490
769
 
@@ -492,9 +771,12 @@ export class HardwareArtifactService {
492
771
  if (explicitProject !== undefined && explicitProject.trim() !== '') {
493
772
  const requested = isAbsolute(explicitProject) ? canonical(explicitProject) : resolve(cwd, explicitProject)
494
773
  if (!existsSync(requested)) {
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
774
+ return this.remember({
775
+ cwd,
776
+ ...(manifest === undefined ? {} : { manifestPath }),
777
+ projects: [],
778
+ issue: { code: 'missing-project', message: `${requested} does not exist` },
779
+ }, sessionId)
498
780
  }
499
781
  projectPaths.add(requested)
500
782
  } else if (manifest?.project !== undefined && manifest.project.trim() !== '') {
@@ -505,17 +787,23 @@ export class HardwareArtifactService {
505
787
 
506
788
  const projects: HardwareProject[] = [...projectPaths].sort().map(path => this.projectFrom(path, cwd, manifest))
507
789
  if (projects.length === 0) {
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
790
+ return this.remember({
791
+ cwd,
792
+ ...(manifest === undefined ? {} : { manifestPath }),
793
+ projects,
794
+ issue: { code: 'no-project', message: `no .kicad_pro found under ${cwd}` },
795
+ }, sessionId)
511
796
  }
512
797
  if (projects.length > 1) {
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
798
+ return this.remember({
799
+ cwd,
800
+ ...(manifest === undefined ? {} : { manifestPath }),
801
+ projects,
802
+ issue: { code: 'selection-required', message: `${projects.length} projects found; select one explicitly` },
803
+ }, sessionId)
516
804
  }
517
805
  const selected = projects[0] as HardwareProject
518
- const result: DiscoveryResult = {
806
+ return this.remember({
519
807
  cwd,
520
808
  ...(manifest === undefined ? {} : { manifestPath }),
521
809
  projects,
@@ -523,14 +811,23 @@ export class HardwareArtifactService {
523
811
  ...(selected.selectionRequired
524
812
  ? { issue: { code: 'selection-required', message: 'select an artifact explicitly' } }
525
813
  : {}),
526
- }
527
- this.lastDiscovery = result
528
- return result
814
+ }, sessionId)
815
+ }
816
+
817
+ /** Last discovery for one scope, never another session's. */
818
+ discovery(sessionId?: string): DiscoveryResult | undefined {
819
+ return this.discoveries.get(scopeKey(sessionId))
529
820
  }
530
821
 
531
- /** The most recent discovery, used to authorize source reads. */
532
- discovery(): DiscoveryResult | undefined {
533
- return this.lastDiscovery
822
+ /** The only discovery the host can speak for without being told a session. */
823
+ private soleDiscovery(): DiscoveryResult | undefined {
824
+ if (this.discoveries.size !== 1) return undefined
825
+ return [...this.discoveries.values()][0]
826
+ }
827
+
828
+ private remember(result: DiscoveryResult, sessionId?: string): DiscoveryResult {
829
+ this.discoveries.set(scopeKey(sessionId), result)
830
+ return result
534
831
  }
535
832
 
536
833
  private projectFrom(projectPath: string, cwd: string, manifest?: ProjectManifest): HardwareProject {
@@ -635,14 +932,23 @@ export class HardwareArtifactService {
635
932
  return { launched: true, command, args: [path], cwd: settings.cwd, ...(child.pid === undefined ? {} : { pid: child.pid }) }
636
933
  }
637
934
 
638
- /** Workspace roots a read may target: explicit request, last discovery, config. */
639
- private authorizedRoots(roots?: readonly string[]): string[] {
935
+ /**
936
+ * Workspace roots a read may target: what this scope discovered, plus what
937
+ * the caller named.
938
+ *
939
+ * Additive on purpose. The previous shape unioned the caller's roots with one
940
+ * process-wide "last discovery", so any other session's discovery — a
941
+ * workspace switch is exactly that — replaced the root the open viewer was
942
+ * authorized by, and its next read failed with "artifact is outside the
943
+ * authorized workspace". Roots now only ever accumulate within their scope.
944
+ */
945
+ private authorizedRoots(roots?: readonly string[], sessionId?: string): string[] {
640
946
  const candidates = new Set<string>()
947
+ for (const root of discoveredRoots(this.discovery(sessionId))) candidates.add(canonical(root))
641
948
  for (const root of roots ?? []) {
642
- if (root !== undefined && root.trim() !== '') candidates.add(canonical(root))
949
+ if (root === undefined || root.trim() === '') continue
950
+ candidates.add(rootOf(root))
643
951
  }
644
- const discovered = this.lastDiscovery?.cwd
645
- if (discovered !== undefined) candidates.add(canonical(discovered))
646
952
  return [...candidates]
647
953
  }
648
954
 
@@ -651,7 +957,11 @@ export class HardwareArtifactService {
651
957
  * workspace root, and of an expected type. A browser request cannot turn
652
958
  * this into an arbitrary filesystem read, even from loopback.
653
959
  */
654
- private authorize(artifactPath: string, roots: readonly string[] | undefined): { path: string; kind: 'schematic' | 'pcb' } {
960
+ private authorize(
961
+ artifactPath: string,
962
+ roots: readonly string[] | undefined,
963
+ sessionId?: string,
964
+ ): { path: string; kind: 'schematic' | 'pcb' } {
655
965
  if (!isAbsolute(artifactPath)) {
656
966
  throw errorWithCode('artifact identity must be an absolute path', 'invalid-identity', 400)
657
967
  }
@@ -660,7 +970,7 @@ export class HardwareArtifactService {
660
970
  if (kind === undefined) {
661
971
  throw errorWithCode(`unsupported artifact type: ${extname(requested)}`, 'unsupported-artifact', 415)
662
972
  }
663
- const authorized = this.authorizedRoots(roots)
973
+ const authorized = this.authorizedRoots(roots, sessionId)
664
974
  if (authorized.length === 0) {
665
975
  throw errorWithCode('no authorized workspace is known to the host', 'unauthorized', 403)
666
976
  }
@@ -696,7 +1006,7 @@ export class HardwareArtifactService {
696
1006
 
697
1007
  /** Saved source text plus a content-addressed revision. */
698
1008
  async readSource(request: SourceRequest): Promise<SourceResult> {
699
- const { path, kind } = this.authorize(request.artifactPath, request.roots)
1009
+ const { path, kind } = this.authorize(request.artifactPath, request.roots, request.sessionId)
700
1010
  const info = statSync(path)
701
1011
  if (info.size > this.maxSourceBytes) {
702
1012
  throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, 'too-large', 413)
@@ -744,7 +1054,7 @@ export class HardwareArtifactService {
744
1054
  * - a timeout or abort leaves no partial file behind
745
1055
  */
746
1056
  async exportGlb(request: GlbRequest): Promise<GlbResult> {
747
- const { path } = this.authorize(request.artifactPath, request.roots)
1057
+ const { path } = this.authorize(request.artifactPath, request.roots, request.sessionId)
748
1058
  if (extname(path).toLowerCase() !== '.kicad_pcb') {
749
1059
  throw errorWithCode('GLB export requires a .kicad_pcb artifact', 'unsupported-artifact', 415)
750
1060
  }
@@ -829,9 +1139,10 @@ export class HardwareArtifactService {
829
1139
  async exportBom(request: {
830
1140
  readonly artifactPath: string
831
1141
  readonly roots?: readonly string[]
1142
+ readonly sessionId?: string
832
1143
  readonly signal?: AbortSignal
833
1144
  }): Promise<BomResult> {
834
- const { path, kind } = this.authorize(request.artifactPath, request.roots)
1145
+ const { path, kind } = this.authorize(request.artifactPath, request.roots, request.sessionId)
835
1146
  if (kind !== 'schematic') {
836
1147
  throw errorWithCode('BOM export requires a .kicad_sch artifact', 'unsupported-artifact', 415)
837
1148
  }
@@ -876,7 +1187,329 @@ export class HardwareArtifactService {
876
1187
  }
877
1188
  }
878
1189
 
879
- /** Serve a generated GLB file, re-validating the cache entry first. */ glbFile(boardPath: string, revision: string): string {
1190
+ // -------------------------------------------------------------------------
1191
+ // Fabrication packaging and order submission
1192
+ // -------------------------------------------------------------------------
1193
+
1194
+ /** Live order settings, read at call time so a settings write is immediate. */
1195
+ private orderSettings(): { baseUrl: string; pageBase: string; accessToken?: string } {
1196
+ const live = this.config.settings?.()
1197
+ const configured = [live?.orderBaseUrl, this.config.orderBaseUrl, process.env.HUAQIU_ORDER_BASE_URL]
1198
+ .find(value => value !== undefined && value.trim() !== '')
1199
+ const baseUrl = (configured ?? DEFAULT_ORDER_BASE_URL).replace(/\/+$/u, '')
1200
+ const pageBase = (this.config.orderPageBase ?? DEFAULT_ORDER_PAGE_BASE).replace(/\/+$/u, '')
1201
+ const token = live?.accessToken ?? this.config.accessToken ?? process.env.HUAQIU_ACCESS_TOKEN
1202
+ return {
1203
+ baseUrl,
1204
+ pageBase,
1205
+ ...(token === undefined || token.trim() === '' ? {} : { accessToken: token.trim() }),
1206
+ }
1207
+ }
1208
+
1209
+ /** What the Order destination may do right now, without contacting anything. */
1210
+ async orderConfig(): Promise<OrderConfigInfo> {
1211
+ const installed = this.installations()
1212
+ const settings = this.orderSettings()
1213
+ return {
1214
+ configured: installed.kicad.configured,
1215
+ baseUrl: settings.baseUrl,
1216
+ hasToken: (await this.orderToken()) !== undefined,
1217
+ provider: 'huaqiu',
1218
+ }
1219
+ }
1220
+
1221
+ /**
1222
+ * The token the order page must carry.
1223
+ *
1224
+ * An explicitly configured token wins (it makes a scripted run possible);
1225
+ * otherwise the signed-in Huaqiu session is used, which is the same token the
1226
+ * eda.cn API accepts. Absent both, ordering is refused before anything is
1227
+ * uploaded — the page would render signed out otherwise.
1228
+ */
1229
+ private async orderToken(): Promise<string | undefined> {
1230
+ const settings = this.orderSettings()
1231
+ if (settings.accessToken !== undefined) return settings.accessToken
1232
+ if (this.config.authToken === undefined) return undefined
1233
+ try {
1234
+ const token = await this.config.authToken()
1235
+ return token === null || token.trim() === '' ? undefined : token.trim()
1236
+ } catch {
1237
+ return undefined
1238
+ }
1239
+ }
1240
+
1241
+ /**
1242
+ * Build the fabrication archive and the assembly inputs for one board.
1243
+ *
1244
+ * The gerber/drill export is `kicad-cli`'s own plotter, so the archive is the
1245
+ * same set of files a KiCad "Place order" would upload. Cached by source
1246
+ * revision: reopening the panel must not re-run the exporter.
1247
+ */
1248
+ async fabricate(request: {
1249
+ readonly boardPath: string
1250
+ readonly schematicPath?: string
1251
+ readonly roots?: readonly string[]
1252
+ readonly sessionId?: string
1253
+ readonly signal?: AbortSignal
1254
+ }): Promise<FabricationResult & { readonly archiveData: Uint8Array; readonly assemblyFiles?: {
1255
+ readonly positions: string
1256
+ readonly bom: string
1257
+ } }> {
1258
+ const { path } = this.authorize(request.boardPath, request.roots, request.sessionId)
1259
+ if (extname(path).toLowerCase() !== '.kicad_pcb') {
1260
+ throw errorWithCode('Fabrication packaging requires a .kicad_pcb artifact', 'unsupported-artifact', 415)
1261
+ }
1262
+ const installed = this.installations()
1263
+ if (!installed.kicad.configured || installed.kicad.cli === undefined) {
1264
+ throw errorWithCode(installed.kicad.error ?? 'the configured KiCad installation has no kicad-cli', 'not-configured', 412)
1265
+ }
1266
+ const cli = installed.kicad.cli
1267
+ const revision = this.sourceRevision(path)
1268
+ const schematicPath = request.schematicPath === undefined
1269
+ ? undefined
1270
+ : this.authorize(request.schematicPath, request.roots, request.sessionId).path
1271
+ const key = `${path}:${revision}:${schematicPath ?? ''}`
1272
+ const cached = this.packageCache.get(key)
1273
+ if (cached !== undefined) return cached
1274
+
1275
+ const directory = join(this.cacheRoot, 'fabrication', createHash('sha256').update(path).digest('hex').slice(0, 16))
1276
+ const work = join(directory, `tmp-${process.pid}-${String(Date.now())}`)
1277
+ const plots = join(work, 'plots')
1278
+ const positionsFile = join(work, 'positions.raw.csv')
1279
+ mkdirSync(plots, { recursive: true })
1280
+
1281
+ const signal = request.signal
1282
+ const run = async (args: readonly string[], what: string, timeoutMs = 120_000): Promise<void> => {
1283
+ const result = await this.options.runCommand(cli, args, {
1284
+ cwd: dirname(path),
1285
+ timeoutMs,
1286
+ ...(signal === undefined ? {} : { signal }),
1287
+ })
1288
+ if (result.timedOut) throw errorWithCode(`kicad-cli ${what} timed out`, 'export-timeout', 504)
1289
+ if (result.exitCode !== 0) {
1290
+ const detail = (result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)
1291
+ throw errorWithCode(`kicad-cli ${what} failed: ${detail}`, 'export-failed', 502)
1292
+ }
1293
+ }
1294
+
1295
+ try {
1296
+ await run(['pcb', 'export', 'gerbers', '--output', plots, path], 'pcb export gerbers')
1297
+ await run(['pcb', 'export', 'drill', '--output', plots, '--format', 'excellon',
1298
+ '--excellon-units', 'mm', '--drill-origin', 'absolute', path], 'pcb export drill')
1299
+ const plotNames = readdirSync(plots).filter(name => statSync(join(plots, name)).isFile()).sort()
1300
+ if (plotNames.length === 0) throw errorWithCode('kicad-cli wrote no fabrication files', 'export-failed', 502)
1301
+ const plotted = readExportDirectory(plots, plotNames)
1302
+ const archiveData = zipPackage(plotted)
1303
+ const facts = readBoardFacts(readFileSync(path, 'utf8'))
1304
+
1305
+ let assembly: FabricationResult['assembly']
1306
+ let assemblyFiles: { positions: string; bom: string } | undefined
1307
+ if (schematicPath !== undefined) {
1308
+ await run(['pcb', 'export', 'pos', '--format', 'csv', '--units', 'mm', '--side', 'both',
1309
+ '--output', positionsFile, path], 'pcb export pos')
1310
+ const positions = parsePositions(readFileSync(positionsFile, 'utf8'))
1311
+ const bom = await this.exportBom({
1312
+ artifactPath: schematicPath,
1313
+ ...(request.roots === undefined ? {} : { roots: request.roots }),
1314
+ ...(signal === undefined ? {} : { signal }),
1315
+ })
1316
+ const bomRows = orderBomRows(positions, bom.rows)
1317
+ const positionsText = positionsCsv(positions)
1318
+ const bomText = orderBomCsv(bomRows)
1319
+ assemblyFiles = { positions: positionsText, bom: bomText }
1320
+ assembly = {
1321
+ positions: positions.length,
1322
+ bomLines: bomRows.length,
1323
+ positionsBytes: Buffer.byteLength(positionsText, 'utf8'),
1324
+ bomBytes: Buffer.byteLength(bomText, 'utf8'),
1325
+ }
1326
+ }
1327
+
1328
+ const result: FabricationResult & { archiveData: Uint8Array; assemblyFiles?: { positions: string; bom: string } } = {
1329
+ boardPath: path,
1330
+ revision,
1331
+ generatedAt: new Date().toISOString(),
1332
+ facts,
1333
+ archive: {
1334
+ zipName: `${packageName(path)}.zip`,
1335
+ zipBytes: archiveData.byteLength,
1336
+ files: plotted.map(file => ({ name: file.name, bytes: file.data.byteLength })),
1337
+ },
1338
+ archiveData,
1339
+ ...(assembly === undefined ? {} : { assembly }),
1340
+ ...(assemblyFiles === undefined ? {} : { assemblyFiles }),
1341
+ }
1342
+ this.packageCache.set(key, result)
1343
+ return result
1344
+ } finally {
1345
+ rmSync(work, { recursive: true, force: true })
1346
+ }
1347
+ }
1348
+
1349
+ /**
1350
+ * Submit one order to the Huaqiu openapi, exactly as the KiCad action does.
1351
+ *
1352
+ * PCB: every `PCB_FORM` field plus the gerber/drill archive as `file`.
1353
+ * SMT: `pcbFile` + `coordFile` + `bomFile` and `reqParseVO`, with the caller's
1354
+ * access token in `authorization`. The backend owns the order; this method
1355
+ * forwards the files and composes the final page URL from the returned id the
1356
+ * way the reference does.
1357
+ */
1358
+ async placeOrder(request: PlaceOrderRequest): Promise<PlaceOrderResult> {
1359
+ const settings = this.orderSettings()
1360
+ const bundle = await this.fabricate({
1361
+ boardPath: request.boardPath,
1362
+ ...(request.schematicPath === undefined ? {} : { schematicPath: request.schematicPath }),
1363
+ ...(request.roots === undefined ? {} : { roots: request.roots }),
1364
+ ...(request.sessionId === undefined ? {} : { sessionId: request.sessionId }),
1365
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
1366
+ })
1367
+ // Checked after the install gate so a missing KiCad is reported as such,
1368
+ // but before any upload: the page would open signed out without a token.
1369
+ const token = await this.orderToken()
1370
+ if (token === undefined) {
1371
+ throw errorWithCode(
1372
+ 'placing an order requires a signed-in Huaqiu account (or HUAQIU_ACCESS_TOKEN)',
1373
+ 'unauthorized',
1374
+ 401,
1375
+ )
1376
+ }
1377
+ const facts = bundle.facts
1378
+ const endpoint = `${settings.baseUrl}${ORDER_PATHS[request.kind]}`
1379
+
1380
+ let parts: { name: string; value: string }[]
1381
+ let files: { field: string; name: string; type: string; data: Uint8Array }[]
1382
+ let headers: Record<string, string> | undefined
1383
+
1384
+ if (request.kind === 'pcb') {
1385
+ const form = pcbOrderForm(facts, request.quantity === undefined ? {} : { quantity: request.quantity })
1386
+ parts = Object.entries(form).map(([name, value]) => ({ name, value }))
1387
+ files = [{ field: 'file', name: bundle.archive.zipName, type: 'application/zip', data: bundle.archiveData }]
1388
+ } else {
1389
+ if (bundle.assemblyFiles === undefined) {
1390
+ throw errorWithCode('SMT order placement requires the project root schematic', 'invalid-request', 400)
1391
+ }
1392
+ const smt = smtOrderForm(facts, {
1393
+ bomFileName: `${packageName(bundle.boardPath)}-bom.csv`,
1394
+ coordFileName: `${packageName(bundle.boardPath)}-positions.csv`,
1395
+ materialTypes: bundle.assembly?.bomLines ?? 0,
1396
+ ...(request.quantity === undefined ? {} : { quantity: request.quantity }),
1397
+ })
1398
+ parts = [{
1399
+ name: 'reqParseVO',
1400
+ value: JSON.stringify({
1401
+ pcb_order: pcbOrderForm(facts, request.quantity === undefined ? {} : { quantity: request.quantity }),
1402
+ smt_order: smt,
1403
+ }),
1404
+ }]
1405
+ files = [
1406
+ { field: 'pcbFile', name: bundle.archive.zipName, type: 'application/zip', data: bundle.archiveData },
1407
+ {
1408
+ field: 'coordFile', name: String(smt.coord_file_name), type: 'application/octet-stream',
1409
+ data: new TextEncoder().encode(bundle.assemblyFiles.positions),
1410
+ },
1411
+ {
1412
+ field: 'bomFile', name: String(smt.bom_file_name), type: 'application/octet-stream',
1413
+ data: new TextEncoder().encode(bundle.assemblyFiles.bom),
1414
+ },
1415
+ ]
1416
+ headers = { authorization: token }
1417
+ }
1418
+
1419
+ const boundary = `----huaqiu${createHash('sha256').update(`${endpoint}:${String(Date.now())}`).digest('hex').slice(0, 24)}`
1420
+ const payload = multipartBody(parts, files, boundary)
1421
+ const post = this.config.postOrder ?? defaultPostOrder
1422
+
1423
+ let response: { status: number; text: string }
1424
+ try {
1425
+ response = await post(endpoint, {
1426
+ body: payload.body,
1427
+ contentType: payload.contentType,
1428
+ ...(headers === undefined ? {} : { headers }),
1429
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
1430
+ })
1431
+ } catch (error) {
1432
+ const detail = error instanceof Error ? error.message : String(error)
1433
+ throw errorWithCode(`the order endpoint could not be reached: ${detail}`, 'order-unreachable', 502)
1434
+ }
1435
+ if (response.status < 200 || response.status >= 300) {
1436
+ throw errorWithCode(
1437
+ `the order endpoint rejected the request (HTTP ${String(response.status)}): ${response.text.slice(0, 400)}`,
1438
+ 'order-rejected',
1439
+ 502,
1440
+ )
1441
+ }
1442
+
1443
+ let json: unknown
1444
+ try {
1445
+ json = JSON.parse(response.text)
1446
+ } catch {
1447
+ throw errorWithCode('the order endpoint returned an unreadable response', 'order-rejected', 502)
1448
+ }
1449
+ const responseUrl = orderUrlOf(json)
1450
+ if (responseUrl === undefined) {
1451
+ throw errorWithCode('the order endpoint returned no order URL', 'order-rejected', 502)
1452
+ }
1453
+
1454
+ // Reproduce the URL KiCad's own action loads in its webview, including the
1455
+ // exact query the hqpcb page expects. For PCB that is a page composed
1456
+ // around the returned id/guid; for assembly the same kind of page, composed
1457
+ // from the returned id with `source=bom` (BOM matching). The backend's own
1458
+ // string is kept as `responseUrl` for diagnostics.
1459
+ const ids = orderIdsFromUrl(responseUrl)
1460
+ const orderUrl = request.kind === 'pcb'
1461
+ ? pcbOrderUrl(settings.pageBase, ids, token)
1462
+ : smtOrderUrl(settings.pageBase, ids, token) ?? smtOrderUrlFromBackend(responseUrl, token)
1463
+ if (orderUrl === undefined) {
1464
+ throw errorWithCode('the order endpoint returned an order id that cannot form a page URL', 'order-rejected', 502)
1465
+ }
1466
+
1467
+ // Opening the page is the whole point of the action, but a browser that
1468
+ // will not start must never discard a successfully created order.
1469
+ const launch = request.launch !== false
1470
+ let opened: { launched: boolean; launcher?: string } = { launched: false }
1471
+ if (launch) {
1472
+ try {
1473
+ const result = this.openOrderUrl(orderUrl)
1474
+ opened = { launched: true, launcher: result.command }
1475
+ } catch {
1476
+ opened = { launched: false }
1477
+ }
1478
+ }
1479
+
1480
+ return {
1481
+ kind: request.kind,
1482
+ orderUrl,
1483
+ responseUrl,
1484
+ ...opened,
1485
+ status: opened.launched ? 'launched' : 'ready',
1486
+ message: opened.launched
1487
+ ? `Opened the ${request.kind === 'pcb' ? 'PCB' : 'assembly'} order page in your default browser.`
1488
+ : `The ${request.kind === 'pcb' ? 'PCB' : 'assembly'} order page is ready; open the URL to continue.`,
1489
+ endpoint,
1490
+ facts,
1491
+ archive: bundle.archive,
1492
+ ...(bundle.assembly === undefined ? {} : { assembly: bundle.assembly }),
1493
+ }
1494
+ }
1495
+
1496
+ /**
1497
+ * Open one order page in the OS default browser.
1498
+ *
1499
+ * This is the only place a URL reaches an external program; the URL is
1500
+ * validated by shape first and passed as a plain argument.
1501
+ */
1502
+ openOrderUrl(raw: string): { launched: true; command: string; url: string } {
1503
+ const url = externalUrlTarget(raw)
1504
+ const spec = this.options.openExternal(url)
1505
+ this.options.spawnProcess(spec.command, spec.args, {
1506
+ cwd: tmpdir(), detached: true, stdio: 'ignore', windowsHide: true, shell: false,
1507
+ })
1508
+ return { launched: true, command: spec.command, url }
1509
+ }
1510
+
1511
+ /** Serve a generated GLB file, re-validating the cache entry first. */
1512
+ glbFile(boardPath: string, revision: string): string {
880
1513
  const key = `${canonical(boardPath)}:${revision}`
881
1514
  const entry = this.glbCache.get(key)
882
1515
  if (entry === undefined || !existsSync(entry.file)) {
@@ -887,6 +1520,7 @@ export class HardwareArtifactService {
887
1520
 
888
1521
  /** Drop cached derived outputs for one board (or all of them). */
889
1522
  clearCache(boardPath?: string): void {
1523
+ this.packageCache.clear()
890
1524
  if (boardPath === undefined) {
891
1525
  this.glbCache.clear()
892
1526
  rmSync(this.cacheRoot, { recursive: true, force: true })
@@ -961,20 +1595,29 @@ export function parseCsv(text: string): string[][] {
961
1595
  * Identity is every column except the reference and quantity columns, so a
962
1596
  * different MPN or a DNP flag always produces a separate line; ordering follows
963
1597
  * the first reference seen, which keeps the table stable between reads.
1598
+ *
1599
+ * Column names follow `kicad-cli sch export bom`'s default field set, which is
1600
+ * `Refs,Value,Footprint,Qty,DNP`; a customized `--fields` header may spell the
1601
+ * same columns out in full, and a grouped export may pack several references
1602
+ * into one cell, so both spellings and both shapes are accepted.
964
1603
  */
965
1604
  export function groupBomRows(table: readonly string[][]): BomRow[] {
966
1605
  const [header, ...body] = table
967
1606
  if (header === undefined) return []
968
1607
  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))
1608
+ const find = (...aliases: readonly RegExp[]): number =>
1609
+ columns.findIndex(cell => aliases.some(alias => alias.test(cell)))
1610
+ const referenceIndex = find(/^refs?$/iu, /^references?$/iu)
1611
+ const quantityIndex = find(/^qty$/iu, /^quantity$/iu)
1612
+ const valueIndex = find(/^value$/iu)
1613
+ const footprintIndex = find(/^footprint$/iu)
1614
+ const dnpIndex = find(/^dnp$/iu)
974
1615
  const groups = new Map<string, { references: string[]; fields: Record<string, string>; dnp: boolean }>()
975
1616
  for (const cells of body) {
976
- const reference = referenceIndex === -1 ? '' : (cells[referenceIndex] ?? '').trim()
977
- if (reference === '') continue
1617
+ const references = referenceIndex === -1
1618
+ ? []
1619
+ : (cells[referenceIndex] ?? '').split(/[,;\s]+/u).map(reference => reference.trim()).filter(reference => reference !== '')
1620
+ if (references.length === 0) continue
978
1621
  const fields: Record<string, string> = {}
979
1622
  columns.forEach((column, index) => {
980
1623
  if (index === referenceIndex || index === quantityIndex || index === valueIndex
@@ -991,7 +1634,7 @@ export function groupBomRows(table: readonly string[][]): BomRow[] {
991
1634
  Object.fromEntries(Object.entries(fields).sort(([a], [b]) => a.localeCompare(b))),
992
1635
  ])
993
1636
  const group = groups.get(identity) ?? { references: [], fields, dnp }
994
- group.references.push(reference)
1637
+ group.references.push(...references)
995
1638
  groups.set(identity, group)
996
1639
  }
997
1640
  return [...groups.entries()].map(([identity, group]) => {