@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/order.ts ADDED
@@ -0,0 +1,778 @@
1
+ /**
2
+ * Fabrication packaging and place-order submission.
3
+ *
4
+ * KiCad's own "Place order" action is a thin wrapper around the Huaqiu
5
+ * (eda.cn) openapi: it exports gerber + drill files, zips them, posts the board
6
+ * form plus the archive as multipart, composes the order page URL the backend
7
+ * describes, and loads that URL in its order webview. Without a KiCad GUI
8
+ * process there is no in-process exporter or webview, so this module reproduces
9
+ * the flow with `kicad-cli` for the artifacts, plain multipart HTTP for the
10
+ * submit, and hands the same final URL to the system default browser. It is the
11
+ * same contract, not a second order backend:
12
+ *
13
+ * PCB POST <base>/openapi/api/hqpcb/External/fileQuote
14
+ * SMT POST <base>/openapi/pcba/saveDfmTmpOrder
15
+ *
16
+ * Nothing here computes a price. The backend owns the quote and the order id;
17
+ * this module packages files, forwards the response, and composes the final
18
+ * webview URL the way the reference does. The `token` in that URL is the
19
+ * signed-in Huaqiu access token — hqpcb is a Huaqiu business, so one login
20
+ * covers the API and the order page.
21
+ *
22
+ * Reference: `pcbnew/fab/place_order_form_builder.h`,
23
+ * `pcbnew/fab/place_order_for_pcb.h`, `pcbnew/fab/place_order_for_smt.h`,
24
+ * `copilot/assistant/quote/{pcb_quote,smt_quote}.cpp`.
25
+ * Endpoints: `copilot/interface/settings/{site_env,site_paths}.h`
26
+ * (`www.eda.cn`, `/openapi/api/hqpcb/External/fileQuote`,
27
+ * `/openapi/pcba/saveDfmTmpOrder`).
28
+ *
29
+ * @module
30
+ */
31
+
32
+ import { readFileSync } from 'node:fs'
33
+ import { basename } from 'node:path'
34
+ import { zipSync } from 'fflate'
35
+ import type { BomRow } from './service.js'
36
+
37
+ /** Endpoint paths relative to the order base URL (the host, not a DSH route). */
38
+ export const ORDER_PATHS = Object.freeze({
39
+ pcb: '/openapi/api/hqpcb/External/fileQuote',
40
+ smt: '/openapi/pcba/saveDfmTmpOrder',
41
+ })
42
+
43
+ /** Default origin serving the two endpoints. */
44
+ export const DEFAULT_ORDER_BASE_URL = 'https://www.eda.cn'
45
+
46
+ /** Order page host the webview loads after both submissions. */
47
+ export const DEFAULT_ORDER_PAGE_BASE = 'https://www.hqpcb.com'
48
+
49
+ /** `tid` the reference client sends for a board quoted from a file. */
50
+ export const ORDER_SOURCE_TID = '354'
51
+
52
+ export interface BoardFacts {
53
+ /** Copper layer count, as KiCad counts them (F.Cu, In*.Cu, B.Cu). */
54
+ readonly layers: number
55
+ readonly widthMm: number
56
+ readonly heightMm: number
57
+ readonly thicknessMm: number
58
+ readonly minTrackMm?: number
59
+ readonly minViaDrillMm?: number
60
+ readonly outerOz?: number
61
+ readonly innerOz?: number
62
+ /** Placed pads, used for the assembly form's `patch_pad_number`. */
63
+ readonly padCount?: number
64
+ }
65
+
66
+ /** One file inside the fabrication zip. */
67
+ export interface PackageFile {
68
+ readonly name: string
69
+ readonly bytes: number
70
+ }
71
+
72
+ export interface FabricationPackage {
73
+ readonly boardPath: string
74
+ readonly revision: string
75
+ readonly zipName: string
76
+ readonly zipBytes: number
77
+ /** `Uint8Array` of the zip, ready to attach. */
78
+ readonly archive: Uint8Array
79
+ readonly files: readonly PackageFile[]
80
+ readonly facts: BoardFacts
81
+ readonly generatedAt: string
82
+ }
83
+
84
+ // ---------------------------------------------------------------------------
85
+ // S-expression reading (board facts without a second KiCad parser)
86
+ // ---------------------------------------------------------------------------
87
+
88
+ type SExpr = string | SExpr[]
89
+
90
+ function tokenize(text: string): string[] {
91
+ const tokens: string[] = []
92
+ let index = 0
93
+ while (index < text.length) {
94
+ const char = text[index]
95
+ if (char === '(' || char === ')') {
96
+ tokens.push(char)
97
+ index += 1
98
+ continue
99
+ }
100
+ if (char === '"') {
101
+ let value = ''
102
+ index += 1
103
+ while (index < text.length) {
104
+ const current = text[index]
105
+ if (current === '\\') {
106
+ value += text[index + 1] ?? ''
107
+ index += 2
108
+ continue
109
+ }
110
+ if (current === '"') {
111
+ index += 1
112
+ break
113
+ }
114
+ value += current
115
+ index += 1
116
+ }
117
+ // Quoted atoms keep a marker so they are never confused with structure.
118
+ tokens.push(`\u0000${value}`)
119
+ continue
120
+ }
121
+ if (/\s/u.test(char ?? '')) {
122
+ index += 1
123
+ continue
124
+ }
125
+ let end = index
126
+ while (end < text.length && !/[\s()]/u.test(text[end] ?? '')) end += 1
127
+ tokens.push(text.slice(index, end))
128
+ index = end
129
+ }
130
+ return tokens
131
+ }
132
+
133
+ function atom(token: string): string {
134
+ return token.startsWith('\u0000') ? token.slice(1) : token
135
+ }
136
+
137
+ /** Parse a KiCad s-expression document into nested arrays. */
138
+ export function parseSexpr(text: string): SExpr[] {
139
+ const root: SExpr[] = []
140
+ const stack: SExpr[][] = [root]
141
+ for (const token of tokenize(text)) {
142
+ if (token === '(') {
143
+ const node: SExpr[] = []
144
+ stack[stack.length - 1]?.push(node)
145
+ stack.push(node)
146
+ continue
147
+ }
148
+ if (token === ')') {
149
+ if (stack.length > 1) stack.pop()
150
+ continue
151
+ }
152
+ stack[stack.length - 1]?.push(atom(token))
153
+ }
154
+ return root
155
+ }
156
+
157
+ function head(node: SExpr): string | undefined {
158
+ return Array.isArray(node) && typeof node[0] === 'string' ? node[0] : undefined
159
+ }
160
+
161
+ function isNode(value: SExpr | undefined): value is SExpr[] {
162
+ return Array.isArray(value)
163
+ }
164
+
165
+ function child(node: SExpr[], name: string): SExpr[] | undefined {
166
+ return node.find((entry): entry is SExpr[] => isNode(entry) && head(entry) === name)
167
+ }
168
+
169
+ function numberAt(node: SExpr[] | undefined, index: number): number | undefined {
170
+ const value = node?.[index]
171
+ return typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : undefined
172
+ }
173
+
174
+ /** Every `(head x y)` point under one graphic item. */
175
+ function pointsOf(node: SExpr[]): { x: number; y: number }[] {
176
+ const points: { x: number; y: number }[] = []
177
+ const visit = (entry: SExpr): void => {
178
+ if (!isNode(entry)) return
179
+ const name = head(entry)
180
+ if (name === 'start' || name === 'end' || name === 'mid' || name === 'center' || name === 'at' || name === 'xy') {
181
+ const x = numberAt(entry, 1)
182
+ const y = numberAt(entry, 2)
183
+ if (x !== undefined && y !== undefined && Number.isFinite(x) && Number.isFinite(y)) points.push({ x, y })
184
+ }
185
+ for (const inner of entry) visit(inner)
186
+ }
187
+ visit(node)
188
+ return points
189
+ }
190
+
191
+ /** The layers/node children of the document root. */
192
+ function rootOf(tree: SExpr[]): SExpr[] | undefined {
193
+ return tree.find((node): node is SExpr[] => isNode(node) && head(node) === 'kicad_pcb')
194
+ }
195
+
196
+ function isEdgeCuts(node: SExpr[]): boolean {
197
+ const layer = child(node, 'layer')
198
+ return layer !== undefined && layer[1] === 'Edge.Cuts'
199
+ }
200
+
201
+ /** Snap a copper thickness in mm to the ounce weights the order form offers. */
202
+ function snapOz(thicknessMm: number, allowed: readonly number[]): number {
203
+ const oz = (thicknessMm * 1000) / 34.7
204
+ let best = allowed[0] ?? 1
205
+ for (const candidate of allowed) {
206
+ if (Math.abs(oz - candidate) < Math.abs(oz - best)) best = candidate
207
+ }
208
+ return best
209
+ }
210
+
211
+ /**
212
+ * Derive the fabrication facts the order form needs from a saved board.
213
+ *
214
+ * Only values the file actually carries are returned; the caller keeps the
215
+ * reference defaults for anything missing instead of inventing a measurement.
216
+ */
217
+ export function readBoardFacts(text: string): BoardFacts {
218
+ const root = rootOf(parseSexpr(text))
219
+ if (root === undefined) throw new Error('not a kicad_pcb document')
220
+
221
+ const layersNode = child(root, 'layers')
222
+ const copperLayers = (layersNode ?? []).filter(entry =>
223
+ isNode(entry) && typeof entry[1] === 'string' && entry[1].endsWith('.Cu'))
224
+ const layers = copperLayers.length
225
+
226
+ const general = child(root, 'general')
227
+ const thicknessMm = numberAt(child(general ?? [], 'thickness'), 1) ?? 1.6
228
+
229
+ let minX = Number.POSITIVE_INFINITY
230
+ let minY = Number.POSITIVE_INFINITY
231
+ let maxX = Number.NEGATIVE_INFINITY
232
+ let maxY = Number.NEGATIVE_INFINITY
233
+ let minTrackMm: number | undefined
234
+ let minViaDrillMm: number | undefined
235
+ let smdPads = 0
236
+ let allPads = 0
237
+
238
+ for (const node of root) {
239
+ if (!isNode(node)) continue
240
+ const name = head(node)
241
+ if (name === undefined) continue
242
+ if (name.startsWith('gr_') && isEdgeCuts(node)) {
243
+ for (const point of pointsOf(node)) {
244
+ minX = Math.min(minX, point.x)
245
+ minY = Math.min(minY, point.y)
246
+ maxX = Math.max(maxX, point.x)
247
+ maxY = Math.max(maxY, point.y)
248
+ }
249
+ continue
250
+ }
251
+ if (name === 'footprint') {
252
+ const pads = node.filter((entry): entry is SExpr[] => isNode(entry) && head(entry) === 'pad').length
253
+ allPads += pads
254
+ const attr = child(node, 'attr') ?? []
255
+ if (attr.some(entry => entry === 'smd')) smdPads += pads
256
+ continue
257
+ }
258
+ if (name === 'segment' || name === 'arc') {
259
+ const width = numberAt(child(node, 'width'), 1)
260
+ if (width !== undefined && width > 0) minTrackMm = Math.min(minTrackMm ?? width, width)
261
+ continue
262
+ }
263
+ if (name === 'via') {
264
+ const drill = numberAt(child(node, 'drill'), 1)
265
+ if (drill !== undefined && drill > 0) minViaDrillMm = Math.min(minViaDrillMm ?? drill, drill)
266
+ }
267
+ }
268
+
269
+ const widthMm = Number.isFinite(minX) ? maxX - minX : 0
270
+ const heightMm = Number.isFinite(minY) ? maxY - minY : 0
271
+
272
+ const stackup = child(child(root, 'setup') ?? [], 'stackup')
273
+ let outerThickness: number | undefined
274
+ let innerThickness: number | undefined
275
+ for (const entry of stackup ?? []) {
276
+ if (!isNode(entry) || head(entry) !== 'layer') continue
277
+ const name = typeof entry[1] === 'string' ? entry[1] : ''
278
+ if (child(entry, 'type')?.[1] !== 'copper') continue
279
+ const thickness = numberAt(child(entry, 'thickness'), 1)
280
+ if (thickness === undefined || thickness <= 0) continue
281
+ if (name === 'F.Cu' || name === 'B.Cu') outerThickness = Math.max(outerThickness ?? 0, thickness)
282
+ else if (name.endsWith('.Cu')) innerThickness = Math.max(innerThickness ?? 0, thickness)
283
+ }
284
+
285
+ return {
286
+ layers: layers > 0 ? layers : 2,
287
+ widthMm,
288
+ heightMm,
289
+ thicknessMm,
290
+ ...(minTrackMm === undefined ? {} : { minTrackMm }),
291
+ ...(minViaDrillMm === undefined ? {} : { minViaDrillMm }),
292
+ ...(outerThickness === undefined ? {} : { outerOz: snapOz(outerThickness, [1, 2, 3, 4]) }),
293
+ ...(innerThickness === undefined ? {} : { innerOz: snapOz(innerThickness, [0.5, 1, 2, 3, 4]) }),
294
+ ...(allPads === 0 ? {} : { padCount: smdPads > 0 ? smdPads : allPads }),
295
+ }
296
+ }
297
+
298
+ // ---------------------------------------------------------------------------
299
+ // Order form (PCB_FORM / SMT_FORM wire shape)
300
+ // ---------------------------------------------------------------------------
301
+
302
+ const THICKNESS_TIERS: Readonly<Record<number, readonly number[]>> = Object.freeze({
303
+ 1: [0.6, 0.8, 1.0, 1.2, 1.6, 2.0],
304
+ 2: [0.6, 0.8, 1.0, 1.2, 1.6, 2.0],
305
+ 4: [0.6, 0.8, 1.0, 1.2, 1.6, 2.0],
306
+ 6: [0.8, 1.0, 1.2, 1.6, 2.0, 2.5],
307
+ 8: [1.0, 1.2, 1.6, 2.0, 2.5],
308
+ 10: [1.2, 1.6, 2.0, 2.5],
309
+ 12: [1.6, 2.0, 2.5],
310
+ 14: [1.6, 2.0, 2.5, 3.0],
311
+ 16: [2.0, 2.5, 3.0],
312
+ 18: [2.0, 2.5, 3.0, 3.2],
313
+ 20: [2.0, 2.5, 3.0, 3.2],
314
+ })
315
+
316
+ const TRACE_TIERS = [4, 5, 6, 8, 10] as const
317
+
318
+ /** Snap a board thickness onto the tier list for its layer count. */
319
+ export function snapThickness(layers: number, thicknessMm: number): string {
320
+ const tiers = THICKNESS_TIERS[layers] ?? THICKNESS_TIERS[20] ?? [1.6]
321
+ for (const nominal of tiers) {
322
+ if (thicknessMm >= nominal * 0.9 && thicknessMm <= nominal * 1.1) return nominal.toFixed(1)
323
+ }
324
+ for (const nominal of tiers) {
325
+ if (nominal >= thicknessMm) return nominal.toFixed(1)
326
+ }
327
+ return (tiers[tiers.length - 1] ?? 3.2).toFixed(1)
328
+ }
329
+
330
+ /** Snap a measured minimum trace/space (mm) onto the mil tier list. */
331
+ export function snapTraceTier(minTrackMm: number | undefined): string {
332
+ if (minTrackMm === undefined || !Number.isFinite(minTrackMm) || minTrackMm <= 0) return '6'
333
+ const mils = minTrackMm / 0.0254
334
+ for (const tier of TRACE_TIERS) {
335
+ if (mils <= tier + 1e-9) return String(tier)
336
+ }
337
+ return String(TRACE_TIERS[TRACE_TIERS.length - 1])
338
+ }
339
+
340
+ /** Snap a measured hole (mm) onto the drill tiers the form accepts. */
341
+ export function snapHoleTier(minHoleMm: number | undefined, thicknessMm: number): string {
342
+ const all = thicknessMm <= 1.2 ? ['0.15', '0.2', '0.25', '0.3'] : ['0.2', '0.25', '0.3']
343
+ if (minHoleMm === undefined || !Number.isFinite(minHoleMm) || minHoleMm <= 0) return all[0] ?? '0.3'
344
+ const first = Number(all[0])
345
+ const last = Number(all[all.length - 1])
346
+ if (minHoleMm <= first) return all[0] ?? '0.3'
347
+ if (minHoleMm >= last) return all[all.length - 1] ?? '0.3'
348
+ for (const tier of all) {
349
+ if (minHoleMm <= Number(tier) + 1e-9) return tier
350
+ }
351
+ return all[all.length - 1] ?? '0.3'
352
+ }
353
+
354
+ export interface PcbFormOverrides {
355
+ /** Production quantity (the form's `bcount`). */
356
+ readonly quantity?: number
357
+ readonly solderMaskColor?: string
358
+ readonly surfaceFinish?: string
359
+ readonly thicknessMm?: number
360
+ }
361
+
362
+ /**
363
+ * The PCB order form exactly as the reference client posts it.
364
+ *
365
+ * Every field of `PCB_FORM` is present, including empty optionals, because the
366
+ * endpoint validates the full base/process/special/personalized blocks. Only
367
+ * geometry and process ability are derived from the board; everything else
368
+ * keeps the reference default rather than inventing a preference.
369
+ */
370
+ export function pcbOrderForm(facts: BoardFacts, overrides: PcbFormOverrides = {}): Record<string, string> {
371
+ const thickness = overrides.thicknessMm ?? facts.thicknessMm
372
+ return {
373
+ // BaseInfoModel
374
+ blayer: String(facts.layers),
375
+ blength: (facts.heightMm / 10).toFixed(2),
376
+ bwidth: (facts.widthMm / 10).toFixed(2),
377
+ bcount: String(overrides.quantity ?? 5),
378
+ sidedirection: '无',
379
+ plate_type: 'FR-4',
380
+ units: '1',
381
+ layoutx: '0',
382
+ layouty: '0',
383
+ sidewidth: '0',
384
+ testpoint: '0',
385
+ pbnum: '1',
386
+ board_tg: facts.layers >= 4 ? 'TG150' : '',
387
+ // ProcessInfoModel
388
+ bheight: snapThickness(facts.layers, thickness),
389
+ copper: String(facts.outerOz ?? 1),
390
+ lineweight: snapTraceTier(facts.minTrackMm),
391
+ vias: snapHoleTier(facts.minViaDrillMm, thickness),
392
+ color: overrides.solderMaskColor ?? '绿色',
393
+ charcolor: '白色',
394
+ cover: '过孔盖油',
395
+ spray: overrides.surfaceFinish ?? '无铅喷锡',
396
+ insidecopper: String(facts.innerOz ?? (facts.layers >= 4 ? 0.5 : 0)),
397
+ // SpecialProcessModel
398
+ impendance: '0',
399
+ bankong: '0',
400
+ blind: '0',
401
+ via_in_pad: '无',
402
+ beveledge: '0',
403
+ pressing: '',
404
+ baobian: '0',
405
+ bga: '',
406
+ zknum: '',
407
+ // PersonalizedInfoModel
408
+ test: 'Sample Test Free',
409
+ shipment_report: '0',
410
+ slice_report: '0',
411
+ report_type: '0',
412
+ review_file: '0',
413
+ has_period: '2',
414
+ period_format: '',
415
+ film_report: '0',
416
+ pcb_note: '',
417
+ cross_board: '1',
418
+ paper: '1',
419
+ user_stamp: '1',
420
+ hq_pack: '1',
421
+ // Transport
422
+ service: '',
423
+ region_id: 'cn',
424
+ country: 'CN',
425
+ express: '',
426
+ type: '',
427
+ }
428
+ }
429
+
430
+ export interface SmtFormOverrides {
431
+ readonly quantity?: number
432
+ readonly bomFileName: string
433
+ readonly coordFileName: string
434
+ readonly materialTypes: number
435
+ readonly padCount?: number
436
+ }
437
+
438
+ /** The `smt_order` half of `PCB_SMT_FORM`, with file names attached. */
439
+ export function smtOrderForm(facts: BoardFacts, overrides: SmtFormOverrides): Record<string, string | number> {
440
+ return {
441
+ bom_file_name: overrides.bomFileName,
442
+ bom_file_path: '',
443
+ coord_file_name: overrides.coordFileName,
444
+ coord_file_path: '',
445
+ // The reference copies `pcb_form.bheight` and `pcb_form.blength` verbatim,
446
+ // so the assembly form and the board form always describe one panel size.
447
+ pcb_ban_height: snapThickness(facts.layers, facts.thicknessMm),
448
+ pcb_ban_width: (facts.heightMm / 10).toFixed(2),
449
+ bom_material_type_number: String(overrides.materialTypes),
450
+ is_plug: '1',
451
+ number: String(overrides.quantity ?? 5),
452
+ // KiCad ships 1133 as the form default; the board's own pad count is used
453
+ // when it can be read, so a small board is never quoted as a dense one.
454
+ patch_pad_number: String(overrides.padCount ?? facts.padCount ?? 1133),
455
+ plug_number: '64',
456
+ single_or_double_technique: '1',
457
+ plug_material_type: '',
458
+ buy_bom: 4,
459
+ }
460
+ }
461
+
462
+ // ---------------------------------------------------------------------------
463
+ // Positions and BOM CSVs the assembly endpoint expects
464
+ // ---------------------------------------------------------------------------
465
+
466
+ export interface PositionRow {
467
+ readonly designator: string
468
+ readonly footprint: string
469
+ readonly x: string
470
+ readonly y: string
471
+ readonly layer: 'T' | 'B'
472
+ readonly rotation: string
473
+ readonly comment: string
474
+ }
475
+
476
+ function splitCsvLine(line: string): string[] {
477
+ const cells: string[] = []
478
+ let cell = ''
479
+ let quoted = false
480
+ for (let index = 0; index < line.length; index += 1) {
481
+ const char = line[index]
482
+ if (quoted) {
483
+ if (char === '"' && line[index + 1] === '"') {
484
+ cell += '"'
485
+ index += 1
486
+ } else if (char === '"') {
487
+ quoted = false
488
+ } else {
489
+ cell += char
490
+ }
491
+ continue
492
+ }
493
+ if (char === '"') {
494
+ quoted = true
495
+ continue
496
+ }
497
+ if (char === ',') {
498
+ cells.push(cell)
499
+ cell = ''
500
+ continue
501
+ }
502
+ cell += char
503
+ }
504
+ cells.push(cell)
505
+ return cells
506
+ }
507
+
508
+ /**
509
+ * Convert `kicad-cli pcb export pos --format csv` rows into the
510
+ * `Designator,Footprint,PosX,PosY,Layer,Rotation,Comment` table the assembly
511
+ * endpoint parses (see `write_positions_to_csv` in the reference).
512
+ */
513
+ export function parsePositions(csv: string): PositionRow[] {
514
+ const lines = csv.split(/\r?\n/u).filter(line => line.trim() !== '')
515
+ const header = lines.shift()
516
+ if (header === undefined) return []
517
+ const columns = splitCsvLine(header).map(cell => cell.trim().toLowerCase())
518
+ const column = (name: string): number => columns.indexOf(name)
519
+ const refIndex = column('ref')
520
+ const valueIndex = column('val')
521
+ const packageIndex = column('package')
522
+ const xIndex = column('posx')
523
+ const yIndex = column('posy')
524
+ const rotationIndex = column('rot')
525
+ const sideIndex = column('side')
526
+ if (refIndex === -1 || xIndex === -1 || yIndex === -1) return []
527
+
528
+ const rows: PositionRow[] = []
529
+ for (const line of lines) {
530
+ const cells = splitCsvLine(line)
531
+ const designator = (cells[refIndex] ?? '').trim()
532
+ if (designator === '') continue
533
+ const side = (cells[sideIndex] ?? '').trim().toLowerCase()
534
+ rows.push({
535
+ designator,
536
+ footprint: (cells[packageIndex] ?? '').trim(),
537
+ x: `${(cells[xIndex] ?? '').trim()}mm`,
538
+ y: `${(cells[yIndex] ?? '').trim()}mm`,
539
+ layer: side.startsWith('b') ? 'B' : 'T',
540
+ rotation: (cells[rotationIndex] ?? '0').trim(),
541
+ comment: (cells[valueIndex] ?? '').trim(),
542
+ })
543
+ }
544
+ return rows
545
+ }
546
+
547
+ function csvCell(value: string): string {
548
+ return /[",\n\r]/u.test(value) ? `"${value.replace(/"/gu, '""')}"` : value
549
+ }
550
+
551
+ /** The positions table, with the UTF-8 BOM the reference writes. */
552
+ export function positionsCsv(rows: readonly PositionRow[]): string {
553
+ const header = 'Designator,Footprint,PosX,PosY,Layer,Rotation,Comment'
554
+ const body = rows.map(row =>
555
+ [row.designator, row.footprint, row.x, row.y, row.layer, row.rotation, row.comment].map(csvCell).join(','))
556
+ return `\uFEFF${[header, ...body].join('\n')}\n`
557
+ }
558
+
559
+ export interface OrderBomRow {
560
+ readonly designators: readonly string[]
561
+ readonly mpn: string
562
+ readonly description: string
563
+ readonly footprint: string
564
+ readonly quantity: number
565
+ }
566
+
567
+ /**
568
+ * Group placed designators into assembly lines.
569
+ *
570
+ * Positions are the board truth for what will be placed, so they drive the
571
+ * grouping; the schematic BOM only supplies value/MPN for a designator. A
572
+ * designator with no BOM entry keeps its position data instead of being
573
+ * dropped, which is what the reference does (it never consults the schematic).
574
+ */
575
+ export function orderBomRows(
576
+ positions: readonly PositionRow[],
577
+ bom: readonly BomRow[] | undefined,
578
+ ): OrderBomRow[] {
579
+ const byReference = new Map<string, BomRow>()
580
+ for (const row of bom ?? []) {
581
+ for (const reference of row.references) byReference.set(reference.trim(), row)
582
+ }
583
+ const groups = new Map<string, { designators: string[]; row: OrderBomRow }>()
584
+ for (const position of positions) {
585
+ const entry = byReference.get(position.designator)
586
+ const mpnField = entry === undefined
587
+ ? ''
588
+ : (entry.fields.MPN ?? entry.fields.Mpn ?? entry.fields.mpn ?? '')
589
+ const mpn = mpnField !== '' ? mpnField : (entry?.value ?? position.comment)
590
+ const description = entry?.value ?? position.comment
591
+ const footprint = entry?.footprint !== undefined && entry.footprint !== ''
592
+ ? entry.footprint
593
+ : position.footprint
594
+ const key = JSON.stringify([mpn, description, footprint])
595
+ const group = groups.get(key)
596
+ if (group === undefined) {
597
+ groups.set(key, {
598
+ designators: [position.designator],
599
+ row: { designators: [], mpn, description, footprint, quantity: 1 },
600
+ })
601
+ continue
602
+ }
603
+ group.designators.push(position.designator)
604
+ }
605
+ return [...groups.values()].map(group => ({ ...group.row, designators: group.designators }))
606
+ }
607
+
608
+ /** The assembly BOM table (`序号,型号,规格参数,封装,品牌,位号,单机用量`). */
609
+ export function orderBomCsv(rows: readonly OrderBomRow[]): string {
610
+ const header = '序号,型号,规格参数,封装,品牌,位号,单机用量'
611
+ const body = rows.map((row, index) => [
612
+ String(index + 1),
613
+ csvCell(row.mpn),
614
+ csvCell(row.description),
615
+ csvCell(row.footprint),
616
+ '',
617
+ csvCell(row.designators.join(',')),
618
+ String(row.designators.length),
619
+ ].join(','))
620
+ return `\uFEFF${[header, ...body].join('\n')}\n`
621
+ }
622
+
623
+ // ---------------------------------------------------------------------------
624
+ // Packaging and transport
625
+ // ---------------------------------------------------------------------------
626
+
627
+ /** Zip a directory listing of already-read files. */
628
+ export function zipPackage(files: readonly { name: string; data: Uint8Array }[]): Uint8Array {
629
+ const entries: Record<string, Uint8Array> = {}
630
+ for (const file of files) entries[file.name] = file.data
631
+ return zipSync(entries, { level: 6 })
632
+ }
633
+
634
+ /** Read every file a `kicad-cli` export wrote into one directory. */
635
+ export function readExportDirectory(directory: string, names: readonly string[]): { name: string; data: Uint8Array }[] {
636
+ return names.map(name => ({ name, data: new Uint8Array(readFileSync(`${directory}/${name}`)) }))
637
+ }
638
+
639
+ export interface MultipartPart {
640
+ readonly name: string
641
+ readonly value: string
642
+ }
643
+
644
+ export interface MultipartFile {
645
+ readonly field: string
646
+ readonly name: string
647
+ readonly type: string
648
+ readonly data: Uint8Array
649
+ }
650
+
651
+ /** Build `multipart/form-data` without a runtime dependency. */
652
+ export function multipartBody(
653
+ parts: readonly MultipartPart[],
654
+ files: readonly MultipartFile[],
655
+ boundary: string,
656
+ ): { body: Buffer; contentType: string } {
657
+ const chunks: Buffer[] = []
658
+ for (const part of parts) {
659
+ chunks.push(Buffer.from(
660
+ `--${boundary}\r\nContent-Disposition: form-data; name="${part.name}"\r\nContent-Type: text/plain\r\n\r\n${part.value}\r\n`,
661
+ 'utf8',
662
+ ))
663
+ }
664
+ for (const file of files) {
665
+ chunks.push(Buffer.from(
666
+ `--${boundary}\r\nContent-Disposition: form-data; name="${file.field}"; filename="${file.name}"\r\nContent-Type: ${file.type}\r\n\r\n`,
667
+ 'utf8',
668
+ ))
669
+ chunks.push(Buffer.from(file.data))
670
+ chunks.push(Buffer.from('\r\n', 'utf8'))
671
+ }
672
+ chunks.push(Buffer.from(`--${boundary}--\r\n`, 'utf8'))
673
+ return {
674
+ body: Buffer.concat(chunks),
675
+ contentType: `multipart/form-data; boundary=${boundary}`,
676
+ }
677
+ }
678
+
679
+ /** Read `id` / `guid` out of the redirect URL the PCB endpoint returns. */
680
+ export function orderIdsFromUrl(url: string): { id?: string; guid?: string } {
681
+ const parsed = ((): URL | undefined => {
682
+ try {
683
+ return new URL(url)
684
+ } catch {
685
+ return undefined
686
+ }
687
+ })()
688
+ const query = parsed?.searchParams
689
+ const id = query?.get('id') ?? /[?&]id=([^&]+)/u.exec(url)?.[1]
690
+ const guid = query?.get('guid') ?? /[?&]guid=([^&]+)/u.exec(url)?.[1]
691
+ return {
692
+ ...(id === undefined || id === '' ? {} : { id: decodeURIComponent(id) }),
693
+ ...(guid === undefined || guid === '' ? {} : { guid: decodeURIComponent(guid) }),
694
+ }
695
+ }
696
+
697
+ /** Set query parameters without dropping empty strings, preserving insertion order. */
698
+ function withParams(url: string, params: readonly (readonly [string, string])[]): string | undefined {
699
+ try {
700
+ const parsed = new URL(url)
701
+ for (const [name, value] of params) parsed.searchParams.set(name, value)
702
+ return parsed.toString()
703
+ } catch {
704
+ return undefined
705
+ }
706
+ }
707
+
708
+ /**
709
+ * The final PCB page KiCad loads into its order webview.
710
+ *
711
+ * Mirrors `place_order_for_pcb.h` exactly:
712
+ * `<page>/mycenter/orders/pcb/quote?type=PCB&id=…&guid=…&tid=354&token=…`, e.g.
713
+ * `https://www.hqpcb.com/mycenter/orders/pcb/quote?type=PCB&id=4679157&guid=19c1…&tid=354&token=7047…`
714
+ *
715
+ * Values are query-encoded, which is the only deviation from the C++ string
716
+ * concatenation — a token with `+` or `/` must not corrupt the query. Parameter
717
+ * order is the reference order; the page is not sensitive to it, but a stable
718
+ * order keeps the URL comparable with a KiCad-generated one.
719
+ */
720
+ export function pcbOrderUrl(
721
+ pageBase: string,
722
+ ids: { id?: string; guid?: string },
723
+ token: string | undefined,
724
+ ): string | undefined {
725
+ if (ids.id === undefined && ids.guid === undefined) return undefined
726
+ const base = pageBase.replace(/\/+$/u, '')
727
+ const params: [string, string][] = [['type', 'PCB']]
728
+ if (ids.id !== undefined) params.push(['id', ids.id])
729
+ if (ids.guid !== undefined) params.push(['guid', ids.guid])
730
+ params.push(['tid', ORDER_SOURCE_TID])
731
+ if (token !== undefined && token !== '') params.push(['token', token])
732
+ return withParams(`${base}/mycenter/orders/pcb/quote`, params)
733
+ }
734
+
735
+ /**
736
+ * The final assembly page KiCad loads into its order webview.
737
+ *
738
+ * The reference appends `token` and `source=bom` to the URL the SMT endpoint
739
+ * returns (`place_order_for_smt.h`); the endpoint's URL is the hqpcb quote page
740
+ * itself, so the page is composed here from its `id` — the same page, with the
741
+ * query exactly as the webview ends up showing it:
742
+ *
743
+ * `https://www.hqpcb.com/mycenter/orders/smt/quote?id=1309829474627354699&source=bom&token=7047…`
744
+ *
745
+ * Composing rather than patching the backend string keeps the page host
746
+ * independent of whichever origin answered the POST, and keeps `source=bom`
747
+ * (which switches the page into BOM matching) even if the response omits it.
748
+ */
749
+ export function smtOrderUrl(
750
+ pageBase: string,
751
+ ids: { id?: string },
752
+ token: string | undefined,
753
+ ): string | undefined {
754
+ if (ids.id === undefined) return undefined
755
+ const base = pageBase.replace(/\/+$/u, '')
756
+ const params: [string, string][] = [['id', ids.id], ['source', 'bom']]
757
+ if (token !== undefined && token !== '') params.push(['token', token])
758
+ return withParams(`${base}/mycenter/orders/smt/quote`, params)
759
+ }
760
+
761
+ /**
762
+ * Fallback for an SMT response whose URL carries no `id`: append `token` and
763
+ * `source=bom` to the backend URL exactly as the reference does.
764
+ *
765
+ * This is the literal `add_parameter_to_url(result.url, {token, source})`
766
+ * behaviour; it is only used when the response cannot supply an order id.
767
+ */
768
+ export function smtOrderUrlFromBackend(orderUrl: string, token: string | undefined): string | undefined {
769
+ const params: [string, string][] = []
770
+ if (token !== undefined && token !== '') params.push(['token', token])
771
+ params.push(['source', 'bom'])
772
+ return withParams(orderUrl, params)
773
+ }
774
+
775
+ /** File name a package is uploaded under: `<board>.zip`, like the reference. */
776
+ export function packageName(boardPath: string): string {
777
+ return basename(boardPath).replace(/\.kicad_pcb$/iu, '')
778
+ }