@huaqiu/hardware-artifacts 0.7.12 → 0.7.14

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.
@@ -0,0 +1,2005 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
2
+ import { execFile, execFileSync, spawn } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { readFile } from "node:fs/promises";
5
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
+ import { tmpdir } from "node:os";
7
+ import { zipSync } from "fflate";
8
+ //#region src/order.ts
9
+ /**
10
+ * Fabrication packaging and place-order submission.
11
+ *
12
+ * KiCad's own "Place order" action is a thin wrapper around the Huaqiu
13
+ * (eda.cn) openapi: it exports gerber + drill files, zips them, posts the board
14
+ * form plus the archive as multipart, composes the order page URL the backend
15
+ * describes, and loads that URL in its order webview. Without a KiCad GUI
16
+ * process there is no in-process exporter or webview, so this module reproduces
17
+ * the flow with `kicad-cli` for the artifacts, plain multipart HTTP for the
18
+ * submit, and hands the same final URL to the system default browser. It is the
19
+ * same contract, not a second order backend:
20
+ *
21
+ * PCB POST <base>/openapi/api/hqpcb/External/fileQuote
22
+ * SMT POST <base>/openapi/pcba/saveDfmTmpOrder
23
+ *
24
+ * Nothing here computes a price. The backend owns the quote and the order id;
25
+ * this module packages files, forwards the response, and composes the final
26
+ * webview URL the way the reference does. The `token` in that URL is the
27
+ * signed-in Huaqiu access token — hqpcb is a Huaqiu business, so one login
28
+ * covers the API and the order page.
29
+ *
30
+ * Reference: `pcbnew/fab/place_order_form_builder.h`,
31
+ * `pcbnew/fab/place_order_for_pcb.h`, `pcbnew/fab/place_order_for_smt.h`,
32
+ * `copilot/assistant/quote/{pcb_quote,smt_quote}.cpp`.
33
+ * Endpoints: `copilot/interface/settings/{site_env,site_paths}.h`
34
+ * (`www.eda.cn`, `/openapi/api/hqpcb/External/fileQuote`,
35
+ * `/openapi/pcba/saveDfmTmpOrder`).
36
+ *
37
+ * @module
38
+ */
39
+ /** Endpoint paths relative to the order base URL (the host, not a DSH route). */
40
+ const ORDER_PATHS = Object.freeze({
41
+ pcb: "/openapi/api/hqpcb/External/fileQuote",
42
+ smt: "/openapi/pcba/saveDfmTmpOrder"
43
+ });
44
+ /** Default origin serving the two endpoints. */
45
+ const DEFAULT_ORDER_BASE_URL = "https://www.eda.cn";
46
+ /** Order page host the webview loads after both submissions. */
47
+ const DEFAULT_ORDER_PAGE_BASE = "https://www.hqpcb.com";
48
+ /** `tid` the reference client sends for a board quoted from a file. */
49
+ const ORDER_SOURCE_TID = "354";
50
+ function tokenize(text) {
51
+ const tokens = [];
52
+ let index = 0;
53
+ while (index < text.length) {
54
+ const char = text[index];
55
+ if (char === "(" || char === ")") {
56
+ tokens.push(char);
57
+ index += 1;
58
+ continue;
59
+ }
60
+ if (char === "\"") {
61
+ let value = "";
62
+ index += 1;
63
+ while (index < text.length) {
64
+ const current = text[index];
65
+ if (current === "\\") {
66
+ value += text[index + 1] ?? "";
67
+ index += 2;
68
+ continue;
69
+ }
70
+ if (current === "\"") {
71
+ index += 1;
72
+ break;
73
+ }
74
+ value += current;
75
+ index += 1;
76
+ }
77
+ tokens.push(`\u0000${value}`);
78
+ continue;
79
+ }
80
+ if (/\s/u.test(char ?? "")) {
81
+ index += 1;
82
+ continue;
83
+ }
84
+ let end = index;
85
+ while (end < text.length && !/[\s()]/u.test(text[end] ?? "")) end += 1;
86
+ tokens.push(text.slice(index, end));
87
+ index = end;
88
+ }
89
+ return tokens;
90
+ }
91
+ function atom(token) {
92
+ return token.startsWith("\0") ? token.slice(1) : token;
93
+ }
94
+ /** Parse a KiCad s-expression document into nested arrays. */
95
+ function parseSexpr(text) {
96
+ const root = [];
97
+ const stack = [root];
98
+ for (const token of tokenize(text)) {
99
+ if (token === "(") {
100
+ const node = [];
101
+ stack[stack.length - 1]?.push(node);
102
+ stack.push(node);
103
+ continue;
104
+ }
105
+ if (token === ")") {
106
+ if (stack.length > 1) stack.pop();
107
+ continue;
108
+ }
109
+ stack[stack.length - 1]?.push(atom(token));
110
+ }
111
+ return root;
112
+ }
113
+ function head(node) {
114
+ return Array.isArray(node) && typeof node[0] === "string" ? node[0] : void 0;
115
+ }
116
+ function isNode(value) {
117
+ return Array.isArray(value);
118
+ }
119
+ function child(node, name) {
120
+ return node.find((entry) => isNode(entry) && head(entry) === name);
121
+ }
122
+ function numberAt(node, index) {
123
+ const value = node?.[index];
124
+ return typeof value === "number" ? value : typeof value === "string" ? Number(value) : void 0;
125
+ }
126
+ /** Every `(head x y)` point under one graphic item. */
127
+ function pointsOf(node) {
128
+ const points = [];
129
+ const visit = (entry) => {
130
+ if (!isNode(entry)) return;
131
+ const name = head(entry);
132
+ if (name === "start" || name === "end" || name === "mid" || name === "center" || name === "at" || name === "xy") {
133
+ const x = numberAt(entry, 1);
134
+ const y = numberAt(entry, 2);
135
+ if (x !== void 0 && y !== void 0 && Number.isFinite(x) && Number.isFinite(y)) points.push({
136
+ x,
137
+ y
138
+ });
139
+ }
140
+ for (const inner of entry) visit(inner);
141
+ };
142
+ visit(node);
143
+ return points;
144
+ }
145
+ /** The layers/node children of the document root. */
146
+ function rootOf$1(tree) {
147
+ return tree.find((node) => isNode(node) && head(node) === "kicad_pcb");
148
+ }
149
+ function isEdgeCuts(node) {
150
+ const layer = child(node, "layer");
151
+ return layer !== void 0 && layer[1] === "Edge.Cuts";
152
+ }
153
+ /** Snap a copper thickness in mm to the ounce weights the order form offers. */
154
+ function snapOz(thicknessMm, allowed) {
155
+ const oz = thicknessMm * 1e3 / 34.7;
156
+ let best = allowed[0] ?? 1;
157
+ for (const candidate of allowed) if (Math.abs(oz - candidate) < Math.abs(oz - best)) best = candidate;
158
+ return best;
159
+ }
160
+ /**
161
+ * Derive the fabrication facts the order form needs from a saved board.
162
+ *
163
+ * Only values the file actually carries are returned; the caller keeps the
164
+ * reference defaults for anything missing instead of inventing a measurement.
165
+ */
166
+ function readBoardFacts(text) {
167
+ const root = rootOf$1(parseSexpr(text));
168
+ if (root === void 0) throw new Error("not a kicad_pcb document");
169
+ const layers = (child(root, "layers") ?? []).filter((entry) => isNode(entry) && typeof entry[1] === "string" && entry[1].endsWith(".Cu")).length;
170
+ const thicknessMm = numberAt(child(child(root, "general") ?? [], "thickness"), 1) ?? 1.6;
171
+ let minX = Number.POSITIVE_INFINITY;
172
+ let minY = Number.POSITIVE_INFINITY;
173
+ let maxX = Number.NEGATIVE_INFINITY;
174
+ let maxY = Number.NEGATIVE_INFINITY;
175
+ let minTrackMm;
176
+ let minViaDrillMm;
177
+ let smdPads = 0;
178
+ let allPads = 0;
179
+ for (const node of root) {
180
+ if (!isNode(node)) continue;
181
+ const name = head(node);
182
+ if (name === void 0) continue;
183
+ if (name.startsWith("gr_") && isEdgeCuts(node)) {
184
+ for (const point of pointsOf(node)) {
185
+ minX = Math.min(minX, point.x);
186
+ minY = Math.min(minY, point.y);
187
+ maxX = Math.max(maxX, point.x);
188
+ maxY = Math.max(maxY, point.y);
189
+ }
190
+ continue;
191
+ }
192
+ if (name === "footprint") {
193
+ const pads = node.filter((entry) => isNode(entry) && head(entry) === "pad").length;
194
+ allPads += pads;
195
+ if ((child(node, "attr") ?? []).some((entry) => entry === "smd")) smdPads += pads;
196
+ continue;
197
+ }
198
+ if (name === "segment" || name === "arc") {
199
+ const width = numberAt(child(node, "width"), 1);
200
+ if (width !== void 0 && width > 0) minTrackMm = Math.min(minTrackMm ?? width, width);
201
+ continue;
202
+ }
203
+ if (name === "via") {
204
+ const drill = numberAt(child(node, "drill"), 1);
205
+ if (drill !== void 0 && drill > 0) minViaDrillMm = Math.min(minViaDrillMm ?? drill, drill);
206
+ }
207
+ }
208
+ const widthMm = Number.isFinite(minX) ? maxX - minX : 0;
209
+ const heightMm = Number.isFinite(minY) ? maxY - minY : 0;
210
+ const stackup = child(child(root, "setup") ?? [], "stackup");
211
+ let outerThickness;
212
+ let innerThickness;
213
+ for (const entry of stackup ?? []) {
214
+ if (!isNode(entry) || head(entry) !== "layer") continue;
215
+ const name = typeof entry[1] === "string" ? entry[1] : "";
216
+ if (child(entry, "type")?.[1] !== "copper") continue;
217
+ const thickness = numberAt(child(entry, "thickness"), 1);
218
+ if (thickness === void 0 || thickness <= 0) continue;
219
+ if (name === "F.Cu" || name === "B.Cu") outerThickness = Math.max(outerThickness ?? 0, thickness);
220
+ else if (name.endsWith(".Cu")) innerThickness = Math.max(innerThickness ?? 0, thickness);
221
+ }
222
+ return {
223
+ layers: layers > 0 ? layers : 2,
224
+ widthMm,
225
+ heightMm,
226
+ thicknessMm,
227
+ ...minTrackMm === void 0 ? {} : { minTrackMm },
228
+ ...minViaDrillMm === void 0 ? {} : { minViaDrillMm },
229
+ ...outerThickness === void 0 ? {} : { outerOz: snapOz(outerThickness, [
230
+ 1,
231
+ 2,
232
+ 3,
233
+ 4
234
+ ]) },
235
+ ...innerThickness === void 0 ? {} : { innerOz: snapOz(innerThickness, [
236
+ .5,
237
+ 1,
238
+ 2,
239
+ 3,
240
+ 4
241
+ ]) },
242
+ ...allPads === 0 ? {} : { padCount: smdPads > 0 ? smdPads : allPads }
243
+ };
244
+ }
245
+ const THICKNESS_TIERS = Object.freeze({
246
+ 1: [
247
+ .6,
248
+ .8,
249
+ 1,
250
+ 1.2,
251
+ 1.6,
252
+ 2
253
+ ],
254
+ 2: [
255
+ .6,
256
+ .8,
257
+ 1,
258
+ 1.2,
259
+ 1.6,
260
+ 2
261
+ ],
262
+ 4: [
263
+ .6,
264
+ .8,
265
+ 1,
266
+ 1.2,
267
+ 1.6,
268
+ 2
269
+ ],
270
+ 6: [
271
+ .8,
272
+ 1,
273
+ 1.2,
274
+ 1.6,
275
+ 2,
276
+ 2.5
277
+ ],
278
+ 8: [
279
+ 1,
280
+ 1.2,
281
+ 1.6,
282
+ 2,
283
+ 2.5
284
+ ],
285
+ 10: [
286
+ 1.2,
287
+ 1.6,
288
+ 2,
289
+ 2.5
290
+ ],
291
+ 12: [
292
+ 1.6,
293
+ 2,
294
+ 2.5
295
+ ],
296
+ 14: [
297
+ 1.6,
298
+ 2,
299
+ 2.5,
300
+ 3
301
+ ],
302
+ 16: [
303
+ 2,
304
+ 2.5,
305
+ 3
306
+ ],
307
+ 18: [
308
+ 2,
309
+ 2.5,
310
+ 3,
311
+ 3.2
312
+ ],
313
+ 20: [
314
+ 2,
315
+ 2.5,
316
+ 3,
317
+ 3.2
318
+ ]
319
+ });
320
+ const TRACE_TIERS = [
321
+ 4,
322
+ 5,
323
+ 6,
324
+ 8,
325
+ 10
326
+ ];
327
+ /** Snap a board thickness onto the tier list for its layer count. */
328
+ function snapThickness(layers, thicknessMm) {
329
+ const tiers = THICKNESS_TIERS[layers] ?? THICKNESS_TIERS[20] ?? [1.6];
330
+ for (const nominal of tiers) if (thicknessMm >= nominal * .9 && thicknessMm <= nominal * 1.1) return nominal.toFixed(1);
331
+ for (const nominal of tiers) if (nominal >= thicknessMm) return nominal.toFixed(1);
332
+ return (tiers[tiers.length - 1] ?? 3.2).toFixed(1);
333
+ }
334
+ /** Snap a measured minimum trace/space (mm) onto the mil tier list. */
335
+ function snapTraceTier(minTrackMm) {
336
+ if (minTrackMm === void 0 || !Number.isFinite(minTrackMm) || minTrackMm <= 0) return "6";
337
+ const mils = minTrackMm / .0254;
338
+ for (const tier of TRACE_TIERS) if (mils <= tier + 1e-9) return String(tier);
339
+ return String(TRACE_TIERS[TRACE_TIERS.length - 1]);
340
+ }
341
+ /** Snap a measured hole (mm) onto the drill tiers the form accepts. */
342
+ function snapHoleTier(minHoleMm, thicknessMm) {
343
+ const all = thicknessMm <= 1.2 ? [
344
+ "0.15",
345
+ "0.2",
346
+ "0.25",
347
+ "0.3"
348
+ ] : [
349
+ "0.2",
350
+ "0.25",
351
+ "0.3"
352
+ ];
353
+ if (minHoleMm === void 0 || !Number.isFinite(minHoleMm) || minHoleMm <= 0) return all[0] ?? "0.3";
354
+ const first = Number(all[0]);
355
+ const last = Number(all[all.length - 1]);
356
+ if (minHoleMm <= first) return all[0] ?? "0.3";
357
+ if (minHoleMm >= last) return all[all.length - 1] ?? "0.3";
358
+ for (const tier of all) if (minHoleMm <= Number(tier) + 1e-9) return tier;
359
+ return all[all.length - 1] ?? "0.3";
360
+ }
361
+ /**
362
+ * The PCB order form exactly as the reference client posts it.
363
+ *
364
+ * Every field of `PCB_FORM` is present, including empty optionals, because the
365
+ * endpoint validates the full base/process/special/personalized blocks. Only
366
+ * geometry and process ability are derived from the board; everything else
367
+ * keeps the reference default rather than inventing a preference.
368
+ */
369
+ function pcbOrderForm(facts, overrides = {}) {
370
+ const thickness = overrides.thicknessMm ?? facts.thicknessMm;
371
+ return {
372
+ blayer: String(facts.layers),
373
+ blength: (facts.heightMm / 10).toFixed(2),
374
+ bwidth: (facts.widthMm / 10).toFixed(2),
375
+ bcount: String(overrides.quantity ?? 5),
376
+ sidedirection: "无",
377
+ plate_type: "FR-4",
378
+ units: "1",
379
+ layoutx: "0",
380
+ layouty: "0",
381
+ sidewidth: "0",
382
+ testpoint: "0",
383
+ pbnum: "1",
384
+ board_tg: facts.layers >= 4 ? "TG150" : "",
385
+ bheight: snapThickness(facts.layers, thickness),
386
+ copper: String(facts.outerOz ?? 1),
387
+ lineweight: snapTraceTier(facts.minTrackMm),
388
+ vias: snapHoleTier(facts.minViaDrillMm, thickness),
389
+ color: overrides.solderMaskColor ?? "绿色",
390
+ charcolor: "白色",
391
+ cover: "过孔盖油",
392
+ spray: overrides.surfaceFinish ?? "无铅喷锡",
393
+ insidecopper: String(facts.innerOz ?? (facts.layers >= 4 ? .5 : 0)),
394
+ impendance: "0",
395
+ bankong: "0",
396
+ blind: "0",
397
+ via_in_pad: "无",
398
+ beveledge: "0",
399
+ pressing: "",
400
+ baobian: "0",
401
+ bga: "",
402
+ zknum: "",
403
+ test: "Sample Test Free",
404
+ shipment_report: "0",
405
+ slice_report: "0",
406
+ report_type: "0",
407
+ review_file: "0",
408
+ has_period: "2",
409
+ period_format: "",
410
+ film_report: "0",
411
+ pcb_note: "",
412
+ cross_board: "1",
413
+ paper: "1",
414
+ user_stamp: "1",
415
+ hq_pack: "1",
416
+ service: "",
417
+ region_id: "cn",
418
+ country: "CN",
419
+ express: "",
420
+ type: ""
421
+ };
422
+ }
423
+ /** The `smt_order` half of `PCB_SMT_FORM`, with file names attached. */
424
+ function smtOrderForm(facts, overrides) {
425
+ return {
426
+ bom_file_name: overrides.bomFileName,
427
+ bom_file_path: "",
428
+ coord_file_name: overrides.coordFileName,
429
+ coord_file_path: "",
430
+ pcb_ban_height: snapThickness(facts.layers, facts.thicknessMm),
431
+ pcb_ban_width: (facts.heightMm / 10).toFixed(2),
432
+ bom_material_type_number: String(overrides.materialTypes),
433
+ is_plug: "1",
434
+ number: String(overrides.quantity ?? 5),
435
+ patch_pad_number: String(overrides.padCount ?? facts.padCount ?? 1133),
436
+ plug_number: "64",
437
+ single_or_double_technique: "1",
438
+ plug_material_type: "",
439
+ buy_bom: 4
440
+ };
441
+ }
442
+ function splitCsvLine(line) {
443
+ const cells = [];
444
+ let cell = "";
445
+ let quoted = false;
446
+ for (let index = 0; index < line.length; index += 1) {
447
+ const char = line[index];
448
+ if (quoted) {
449
+ if (char === "\"" && line[index + 1] === "\"") {
450
+ cell += "\"";
451
+ index += 1;
452
+ } else if (char === "\"") quoted = false;
453
+ else cell += char;
454
+ continue;
455
+ }
456
+ if (char === "\"") {
457
+ quoted = true;
458
+ continue;
459
+ }
460
+ if (char === ",") {
461
+ cells.push(cell);
462
+ cell = "";
463
+ continue;
464
+ }
465
+ cell += char;
466
+ }
467
+ cells.push(cell);
468
+ return cells;
469
+ }
470
+ /**
471
+ * Convert `kicad-cli pcb export pos --format csv` rows into the
472
+ * `Designator,Footprint,PosX,PosY,Layer,Rotation,Comment` table the assembly
473
+ * endpoint parses (see `write_positions_to_csv` in the reference).
474
+ */
475
+ function parsePositions(csv) {
476
+ const lines = csv.split(/\r?\n/u).filter((line) => line.trim() !== "");
477
+ const header = lines.shift();
478
+ if (header === void 0) return [];
479
+ const columns = splitCsvLine(header).map((cell) => cell.trim().toLowerCase());
480
+ const column = (name) => columns.indexOf(name);
481
+ const refIndex = column("ref");
482
+ const valueIndex = column("val");
483
+ const packageIndex = column("package");
484
+ const xIndex = column("posx");
485
+ const yIndex = column("posy");
486
+ const rotationIndex = column("rot");
487
+ const sideIndex = column("side");
488
+ if (refIndex === -1 || xIndex === -1 || yIndex === -1) return [];
489
+ const rows = [];
490
+ for (const line of lines) {
491
+ const cells = splitCsvLine(line);
492
+ const designator = (cells[refIndex] ?? "").trim();
493
+ if (designator === "") continue;
494
+ const side = (cells[sideIndex] ?? "").trim().toLowerCase();
495
+ rows.push({
496
+ designator,
497
+ footprint: (cells[packageIndex] ?? "").trim(),
498
+ x: `${(cells[xIndex] ?? "").trim()}mm`,
499
+ y: `${(cells[yIndex] ?? "").trim()}mm`,
500
+ layer: side.startsWith("b") ? "B" : "T",
501
+ rotation: (cells[rotationIndex] ?? "0").trim(),
502
+ comment: (cells[valueIndex] ?? "").trim()
503
+ });
504
+ }
505
+ return rows;
506
+ }
507
+ function csvCell(value) {
508
+ return /[",\n\r]/u.test(value) ? `"${value.replace(/"/gu, "\"\"")}"` : value;
509
+ }
510
+ /** The positions table, with the UTF-8 BOM the reference writes. */
511
+ function positionsCsv(rows) {
512
+ return `\uFEFF${["Designator,Footprint,PosX,PosY,Layer,Rotation,Comment", ...rows.map((row) => [
513
+ row.designator,
514
+ row.footprint,
515
+ row.x,
516
+ row.y,
517
+ row.layer,
518
+ row.rotation,
519
+ row.comment
520
+ ].map(csvCell).join(","))].join("\n")}\n`;
521
+ }
522
+ /**
523
+ * Group placed designators into assembly lines.
524
+ *
525
+ * Positions are the board truth for what will be placed, so they drive the
526
+ * grouping; the schematic BOM only supplies value/MPN for a designator. A
527
+ * designator with no BOM entry keeps its position data instead of being
528
+ * dropped, which is what the reference does (it never consults the schematic).
529
+ */
530
+ function orderBomRows(positions, bom) {
531
+ const byReference = /* @__PURE__ */ new Map();
532
+ for (const row of bom ?? []) for (const reference of row.references) byReference.set(reference.trim(), row);
533
+ const groups = /* @__PURE__ */ new Map();
534
+ for (const position of positions) {
535
+ const entry = byReference.get(position.designator);
536
+ const mpnField = entry === void 0 ? "" : entry.fields.MPN ?? entry.fields.Mpn ?? entry.fields.mpn ?? "";
537
+ const mpn = mpnField !== "" ? mpnField : entry?.value ?? position.comment;
538
+ const description = entry?.value ?? position.comment;
539
+ const footprint = entry?.footprint !== void 0 && entry.footprint !== "" ? entry.footprint : position.footprint;
540
+ const key = JSON.stringify([
541
+ mpn,
542
+ description,
543
+ footprint
544
+ ]);
545
+ const group = groups.get(key);
546
+ if (group === void 0) {
547
+ groups.set(key, {
548
+ designators: [position.designator],
549
+ row: {
550
+ designators: [],
551
+ mpn,
552
+ description,
553
+ footprint,
554
+ quantity: 1
555
+ }
556
+ });
557
+ continue;
558
+ }
559
+ group.designators.push(position.designator);
560
+ }
561
+ return [...groups.values()].map((group) => ({
562
+ ...group.row,
563
+ designators: group.designators
564
+ }));
565
+ }
566
+ /** The assembly BOM table (`序号,型号,规格参数,封装,品牌,位号,单机用量`). */
567
+ function orderBomCsv(rows) {
568
+ return `\uFEFF${["序号,型号,规格参数,封装,品牌,位号,单机用量", ...rows.map((row, index) => [
569
+ String(index + 1),
570
+ csvCell(row.mpn),
571
+ csvCell(row.description),
572
+ csvCell(row.footprint),
573
+ "",
574
+ csvCell(row.designators.join(",")),
575
+ String(row.designators.length)
576
+ ].join(","))].join("\n")}\n`;
577
+ }
578
+ /** Zip a directory listing of already-read files. */
579
+ function zipPackage(files) {
580
+ const entries = {};
581
+ for (const file of files) entries[file.name] = file.data;
582
+ return zipSync(entries, { level: 6 });
583
+ }
584
+ /** Read every file a `kicad-cli` export wrote into one directory. */
585
+ function readExportDirectory(directory, names) {
586
+ return names.map((name) => ({
587
+ name,
588
+ data: new Uint8Array(readFileSync(`${directory}/${name}`))
589
+ }));
590
+ }
591
+ /** Build `multipart/form-data` without a runtime dependency. */
592
+ function multipartBody(parts, files, boundary) {
593
+ const chunks = [];
594
+ for (const part of parts) chunks.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${part.name}"\r\nContent-Type: text/plain\r\n\r\n${part.value}\r\n`, "utf8"));
595
+ for (const file of files) {
596
+ chunks.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${file.field}"; filename="${file.name}"\r\nContent-Type: ${file.type}\r\n\r\n`, "utf8"));
597
+ chunks.push(Buffer.from(file.data));
598
+ chunks.push(Buffer.from("\r\n", "utf8"));
599
+ }
600
+ chunks.push(Buffer.from(`--${boundary}--\r\n`, "utf8"));
601
+ return {
602
+ body: Buffer.concat(chunks),
603
+ contentType: `multipart/form-data; boundary=${boundary}`
604
+ };
605
+ }
606
+ /** Read `id` / `guid` out of the redirect URL the PCB endpoint returns. */
607
+ function orderIdsFromUrl(url) {
608
+ const query = (() => {
609
+ try {
610
+ return new URL(url);
611
+ } catch {
612
+ return;
613
+ }
614
+ })()?.searchParams;
615
+ const id = query?.get("id") ?? /[?&]id=([^&]+)/u.exec(url)?.[1];
616
+ const guid = query?.get("guid") ?? /[?&]guid=([^&]+)/u.exec(url)?.[1];
617
+ return {
618
+ ...id === void 0 || id === "" ? {} : { id: decodeURIComponent(id) },
619
+ ...guid === void 0 || guid === "" ? {} : { guid: decodeURIComponent(guid) }
620
+ };
621
+ }
622
+ /** Set query parameters without dropping empty strings, preserving insertion order. */
623
+ function withParams(url, params) {
624
+ try {
625
+ const parsed = new URL(url);
626
+ for (const [name, value] of params) parsed.searchParams.set(name, value);
627
+ return parsed.toString();
628
+ } catch {
629
+ return;
630
+ }
631
+ }
632
+ /**
633
+ * The final PCB page KiCad loads into its order webview.
634
+ *
635
+ * Mirrors `place_order_for_pcb.h` exactly:
636
+ * `<page>/mycenter/orders/pcb/quote?type=PCB&id=…&guid=…&tid=354&token=…`, e.g.
637
+ * `https://www.hqpcb.com/mycenter/orders/pcb/quote?type=PCB&id=4679157&guid=19c1…&tid=354&token=7047…`
638
+ *
639
+ * Values are query-encoded, which is the only deviation from the C++ string
640
+ * concatenation — a token with `+` or `/` must not corrupt the query. Parameter
641
+ * order is the reference order; the page is not sensitive to it, but a stable
642
+ * order keeps the URL comparable with a KiCad-generated one.
643
+ */
644
+ function pcbOrderUrl(pageBase, ids, token) {
645
+ if (ids.id === void 0 && ids.guid === void 0) return void 0;
646
+ const base = pageBase.replace(/\/+$/u, "");
647
+ const params = [["type", "PCB"]];
648
+ if (ids.id !== void 0) params.push(["id", ids.id]);
649
+ if (ids.guid !== void 0) params.push(["guid", ids.guid]);
650
+ params.push(["tid", "354"]);
651
+ if (token !== void 0 && token !== "") params.push(["token", token]);
652
+ return withParams(`${base}/mycenter/orders/pcb/quote`, params);
653
+ }
654
+ /**
655
+ * The final assembly page KiCad loads into its order webview.
656
+ *
657
+ * The reference appends `token` and `source=bom` to the URL the SMT endpoint
658
+ * returns (`place_order_for_smt.h`); the endpoint's URL is the hqpcb quote page
659
+ * itself, so the page is composed here from its `id` — the same page, with the
660
+ * query exactly as the webview ends up showing it:
661
+ *
662
+ * `https://www.hqpcb.com/mycenter/orders/smt/quote?id=1309829474627354699&source=bom&token=7047…`
663
+ *
664
+ * Composing rather than patching the backend string keeps the page host
665
+ * independent of whichever origin answered the POST, and keeps `source=bom`
666
+ * (which switches the page into BOM matching) even if the response omits it.
667
+ */
668
+ function smtOrderUrl(pageBase, ids, token) {
669
+ if (ids.id === void 0) return void 0;
670
+ const base = pageBase.replace(/\/+$/u, "");
671
+ const params = [["id", ids.id], ["source", "bom"]];
672
+ if (token !== void 0 && token !== "") params.push(["token", token]);
673
+ return withParams(`${base}/mycenter/orders/smt/quote`, params);
674
+ }
675
+ /**
676
+ * Fallback for an SMT response whose URL carries no `id`: append `token` and
677
+ * `source=bom` to the backend URL exactly as the reference does.
678
+ *
679
+ * This is the literal `add_parameter_to_url(result.url, {token, source})`
680
+ * behaviour; it is only used when the response cannot supply an order id.
681
+ */
682
+ function smtOrderUrlFromBackend(orderUrl, token) {
683
+ const params = [];
684
+ if (token !== void 0 && token !== "") params.push(["token", token]);
685
+ params.push(["source", "bom"]);
686
+ return withParams(orderUrl, params);
687
+ }
688
+ /** File name a package is uploaded under: `<board>.zip`, like the reference. */
689
+ function packageName(boardPath) {
690
+ return basename(boardPath).replace(/\.kicad_pcb$/iu, "");
691
+ }
692
+ //#endregion
693
+ //#region src/service.ts
694
+ /**
695
+ * Hardware Engineering artifact model and host operations.
696
+ *
697
+ * This module deliberately has no Cordis dependency: it is the testable core
698
+ * behind `hardwareArtifacts`. Native project files remain authoritative; the
699
+ * objects here are path pointers, verified installation facts and disposable
700
+ * derived outputs, never a shadow project database.
701
+ */
702
+ const EXCLUDED_DIRS = /* @__PURE__ */ new Set([
703
+ ".git",
704
+ ".cache",
705
+ "node_modules",
706
+ "dist",
707
+ "build",
708
+ "out",
709
+ "tmp",
710
+ "temp",
711
+ "archive",
712
+ "archives",
713
+ "backup",
714
+ "backups",
715
+ "export",
716
+ "exports"
717
+ ]);
718
+ const MECHANICAL_EXTENSIONS = /* @__PURE__ */ new Set([
719
+ ".step",
720
+ ".stp",
721
+ ".glb"
722
+ ]);
723
+ const SOURCE_EXTENSIONS = {
724
+ ".kicad_sch": "schematic",
725
+ ".kicad_pcb": "pcb"
726
+ };
727
+ const MAX_DEPTH = 5;
728
+ /** KiCad writes each child sheet as `(property "Sheetfile" "child.kicad_sch")`. */
729
+ const SHEET_FILE_PATTERN = /\(property\s+"Sheetfile"\s+"((?:[^"\\]|\\.)*)"/gu;
730
+ function canonical(path) {
731
+ return resolve(path);
732
+ }
733
+ function isInside(child, parent) {
734
+ const rel = relative(parent, child);
735
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
736
+ }
737
+ function isExcluded(name) {
738
+ return EXCLUDED_DIRS.has(name.toLowerCase());
739
+ }
740
+ function realOrUndefined(path) {
741
+ try {
742
+ return realpathSync(path);
743
+ } catch {
744
+ return;
745
+ }
746
+ }
747
+ /**
748
+ * Identity of one authorization scope. DSH sessions are the scope; an embed
749
+ * without sessions (tests, a bare host) shares the default entry.
750
+ */
751
+ function scopeKey(sessionId) {
752
+ return sessionId === void 0 || sessionId === "" ? "" : sessionId;
753
+ }
754
+ /**
755
+ * A caller-named root, read as "the workspace this artifact belongs to".
756
+ *
757
+ * Callers may name a project file by mistake (the project `.kicad_pro` is the
758
+ * path the panel holds), and a file path authorizes nothing: no artifact is
759
+ * inside another file's path. Resolving to the containing directory keeps the
760
+ * caller's intent without widening beyond it.
761
+ */
762
+ function rootOf(root) {
763
+ const real = realOrUndefined(root) ?? canonical(root);
764
+ try {
765
+ return statSync(real).isDirectory() ? real : dirname(real);
766
+ } catch {
767
+ return real;
768
+ }
769
+ }
770
+ /** Roots a discovery proved reachable: the workspace and every adopted project. */
771
+ function discoveredRoots(discovery) {
772
+ if (discovery === void 0) return [];
773
+ const roots = /* @__PURE__ */ new Set([discovery.cwd]);
774
+ for (const project of discovery.projects) roots.add(dirname(project.path));
775
+ return [...roots];
776
+ }
777
+ function errorWithCode(message, code, status) {
778
+ return Object.assign(new Error(message), {
779
+ code,
780
+ status
781
+ });
782
+ }
783
+ /**
784
+ * POST one multipart order payload.
785
+ *
786
+ * Kept out of the class so tests can inject their own transport; the default
787
+ * has a hard timeout and never logs the body (it carries the access token).
788
+ */
789
+ async function defaultPostOrder(url, init) {
790
+ const controller = new AbortController();
791
+ const timer = setTimeout(() => {
792
+ controller.abort();
793
+ }, 9e4);
794
+ const forward = () => {
795
+ controller.abort();
796
+ };
797
+ init.signal?.addEventListener("abort", forward, { once: true });
798
+ try {
799
+ const response = await fetch(url, {
800
+ method: "POST",
801
+ headers: {
802
+ ...init.headers,
803
+ "content-type": init.contentType,
804
+ "content-length": String(init.body.byteLength)
805
+ },
806
+ body: init.body,
807
+ signal: controller.signal
808
+ });
809
+ return {
810
+ status: response.status,
811
+ text: await response.text()
812
+ };
813
+ } finally {
814
+ clearTimeout(timer);
815
+ init.signal?.removeEventListener("abort", forward);
816
+ }
817
+ }
818
+ /**
819
+ * Command that opens one URL in the OS default browser.
820
+ *
821
+ * A URL argument is passed to a fixed executable with `shell: false`, so the
822
+ * page can never become a shell command.
823
+ */
824
+ function defaultOpenExternal(url) {
825
+ if (process.platform === "darwin") return {
826
+ command: "open",
827
+ args: [url]
828
+ };
829
+ if (process.platform === "win32") return {
830
+ command: "rundll32",
831
+ args: ["url.dll,FileProtocolHandler", url]
832
+ };
833
+ return {
834
+ command: "xdg-open",
835
+ args: [url]
836
+ };
837
+ }
838
+ /**
839
+ * Validate an order page URL before handing it to the OS.
840
+ *
841
+ * The backend owns this URL, so the check is deliberately about *shape*, not
842
+ * about a specific host: HTTPS anywhere, plain HTTP only on loopback (local
843
+ * stubs), and never a URL with embedded credentials or a non-web scheme.
844
+ */
845
+ function externalUrlTarget(raw) {
846
+ if (raw.length === 0 || raw.length > 4096) throw errorWithCode("the order URL is empty or too long", "invalid-order-url", 400);
847
+ let parsed;
848
+ try {
849
+ parsed = new URL(raw);
850
+ } catch {
851
+ throw errorWithCode("the order URL is not a valid absolute URL", "invalid-order-url", 400);
852
+ }
853
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw errorWithCode(`refusing to open a ${parsed.protocol} URL`, "invalid-order-url", 400);
854
+ if (parsed.username !== "" || parsed.password !== "") throw errorWithCode("refusing to open a URL with embedded credentials", "invalid-order-url", 400);
855
+ const host = parsed.hostname.replace(/^\[|\]$/gu, "");
856
+ const loopback = host === "localhost" || host === "::1" || host === "127.0.0.1" || host.startsWith("127.");
857
+ if (parsed.protocol === "http:" && !loopback) throw errorWithCode("refusing to open a plain-HTTP order URL outside loopback", "invalid-order-url", 400);
858
+ return parsed.toString();
859
+ }
860
+ /** First backend-owned order URL in a place-order response. */
861
+ function orderUrlOf(body) {
862
+ if (body === null || typeof body !== "object") return void 0;
863
+ const record = body;
864
+ for (const key of [
865
+ "url",
866
+ "redirect",
867
+ "data"
868
+ ]) {
869
+ const value = record[key];
870
+ if (typeof value === "string" && value !== "") return value;
871
+ if (value !== null && typeof value === "object") {
872
+ const nested = orderUrlOf(value);
873
+ if (nested !== void 0) return nested;
874
+ }
875
+ }
876
+ const result = record.result;
877
+ return result === void 0 ? void 0 : orderUrlOf(result);
878
+ }
879
+ function walkFiles(root, predicate) {
880
+ const found = [];
881
+ const visit = (dir, depth) => {
882
+ if (depth > MAX_DEPTH || !existsSync(dir)) return;
883
+ let entries;
884
+ try {
885
+ entries = readdirSync(dir, { withFileTypes: true });
886
+ } catch {
887
+ return;
888
+ }
889
+ for (const entry of entries) {
890
+ const full = join(dir, entry.name);
891
+ if (entry.isDirectory()) {
892
+ if (!isExcluded(entry.name)) visit(full, depth + 1);
893
+ } else if (entry.isFile() && predicate(entry.name)) found.push(canonical(full));
894
+ }
895
+ };
896
+ visit(root, 0);
897
+ return found.sort();
898
+ }
899
+ /** Child schematics declared by sheet references in one saved schematic. */
900
+ function childSheetFiles(path) {
901
+ let text;
902
+ try {
903
+ text = readFileSync(path, "utf8");
904
+ } catch {
905
+ return [];
906
+ }
907
+ const dir = dirname(path);
908
+ const children = [];
909
+ for (const match of text.matchAll(SHEET_FILE_PATTERN)) {
910
+ const raw = match[1];
911
+ if (raw === void 0 || raw === "") continue;
912
+ const declared = raw.replace(/\\(["\\])/gu, "$1");
913
+ const target = isAbsolute(declared) ? canonical(declared) : resolve(dir, declared);
914
+ children.push(target);
915
+ }
916
+ return children.sort();
917
+ }
918
+ function artifact(kind, path, projectPath, sourcePath) {
919
+ const full = canonical(path);
920
+ return {
921
+ id: `${kind}:${full}`,
922
+ kind,
923
+ path: full,
924
+ ...projectPath === void 0 ? {} : { projectPath: canonical(projectPath) },
925
+ ...sourcePath === void 0 ? {} : { sourcePath: canonical(sourcePath) },
926
+ title: basename(full),
927
+ format: extname(full).toLowerCase().replace(/^\./, "") || kind
928
+ };
929
+ }
930
+ function defaultVersionProbe(executable) {
931
+ if (!existsSync(executable)) return void 0;
932
+ try {
933
+ return execFileSync(executable, ["version"], {
934
+ encoding: "utf8",
935
+ timeout: 5e3,
936
+ stdio: [
937
+ "ignore",
938
+ "pipe",
939
+ "ignore"
940
+ ]
941
+ }).trim().split("\n")[0] || void 0;
942
+ } catch {
943
+ return;
944
+ }
945
+ }
946
+ function defaultRunCommand(command, args, options) {
947
+ return new Promise((resolvePromise, reject) => {
948
+ execFile(command, [...args], {
949
+ cwd: options.cwd,
950
+ timeout: options.timeoutMs,
951
+ encoding: "utf8",
952
+ windowsHide: true,
953
+ shell: false,
954
+ ...options.signal === void 0 ? {} : { signal: options.signal },
955
+ maxBuffer: 8388608
956
+ }, (error, stdout, stderr) => {
957
+ if (error === null) {
958
+ resolvePromise({
959
+ exitCode: 0,
960
+ stdout: String(stdout),
961
+ stderr: String(stderr),
962
+ timedOut: false
963
+ });
964
+ return;
965
+ }
966
+ const killed = error.killed === true;
967
+ const signal = error.signal;
968
+ if (killed || signal !== null && signal !== void 0) {
969
+ resolvePromise({
970
+ exitCode: null,
971
+ stdout: String(stdout),
972
+ stderr: String(stderr),
973
+ timedOut: true
974
+ });
975
+ return;
976
+ }
977
+ const code = typeof error.code === "number" ? Number(error.code) : null;
978
+ if (code === null) {
979
+ reject(error);
980
+ return;
981
+ }
982
+ resolvePromise({
983
+ exitCode: code,
984
+ stdout: String(stdout),
985
+ stderr: String(stderr),
986
+ timedOut: false
987
+ });
988
+ });
989
+ });
990
+ }
991
+ function existing(paths) {
992
+ return paths.find((candidate) => {
993
+ try {
994
+ return existsSync(candidate) && statSync(candidate).isFile();
995
+ } catch {
996
+ return false;
997
+ }
998
+ });
999
+ }
1000
+ function kicadCandidates(root) {
1001
+ const app = basename(root).toLowerCase().endsWith(".app");
1002
+ if (app || process.platform === "darwin") {
1003
+ const base = app ? root : join(root, "KiCad.app");
1004
+ return {
1005
+ cli: [join(base, "Contents/MacOS/kicad-cli")],
1006
+ kicad: [join(base, "Contents/MacOS/kicad")],
1007
+ eeschema: [join(base, "Contents/Applications/eeschema.app/Contents/MacOS/eeschema")],
1008
+ pcbnew: [join(base, "Contents/Applications/pcbnew.app/Contents/MacOS/pcbnew")]
1009
+ };
1010
+ }
1011
+ const exe = process.platform === "win32" ? ".exe" : "";
1012
+ const bin = app ? root : basename(root).toLowerCase() === "bin" ? root : join(root, "bin");
1013
+ return {
1014
+ cli: [join(bin, `kicad-cli${exe}`), join(root, `kicad-cli${exe}`)],
1015
+ kicad: [join(bin, `kicad${exe}`)],
1016
+ eeschema: [join(bin, `eeschema${exe}`)],
1017
+ pcbnew: [join(bin, `pcbnew${exe}`)]
1018
+ };
1019
+ }
1020
+ /** Install root that owns one resolved `kicad-cli`, per layout convention. */
1021
+ function installRootFromCli(cli) {
1022
+ const segments = cli.split(sep);
1023
+ const macIndex = segments.indexOf("Contents");
1024
+ if (macIndex > 0) return segments.slice(0, macIndex).join(sep) || sep;
1025
+ if (segments[segments.length - 2]?.toLowerCase() === "bin") return segments.slice(0, -2).join(sep) || sep;
1026
+ return dirname(cli);
1027
+ }
1028
+ function solidcraftCandidates(root) {
1029
+ const exe = process.platform === "win32" ? ".exe" : "";
1030
+ const app = basename(root).toLowerCase().endsWith(".app");
1031
+ if (app || process.platform === "darwin") {
1032
+ const base = app ? root : join(root, "SolidCraft.app");
1033
+ return [join(base, `Contents/MacOS/SolidCraft`), join(base, `Contents/MacOS/solidcraft`)];
1034
+ }
1035
+ return [
1036
+ root,
1037
+ join(root, `SolidCraft${exe}`),
1038
+ join(root, `solidcraft${exe}`),
1039
+ join(root, "bin", `SolidCraft${exe}`),
1040
+ join(root, "bin", `solidcraft${exe}`)
1041
+ ];
1042
+ }
1043
+ /** Small, immutable host capability implementation. */
1044
+ var HardwareArtifactService = class {
1045
+ config;
1046
+ options;
1047
+ cacheRoot;
1048
+ glbTimeoutMs;
1049
+ maxSourceBytes;
1050
+ /**
1051
+ * Last discovery per scope — one entry per DSH session, plus the unscoped
1052
+ * default used by tests and non-DSH embeds.
1053
+ *
1054
+ * It is a map rather than one field on purpose: a single "most recent
1055
+ * discovery" is shared by every open viewer, so switching to a session in
1056
+ * another workspace silently revoked the authorization of the viewer that
1057
+ * stayed open. Authorization must never depend on who asked last.
1058
+ */
1059
+ discoveries = /* @__PURE__ */ new Map();
1060
+ /** Completed GLB exports keyed by `sourcePath:revision`. */
1061
+ glbCache = /* @__PURE__ */ new Map();
1062
+ /** In-flight GLB exports keyed by the same key, so concurrent callers share one run. */
1063
+ glbPending = /* @__PURE__ */ new Map();
1064
+ /** BOM projections keyed by `sourcePath:revision`. */
1065
+ bomCache = /* @__PURE__ */ new Map();
1066
+ /** Prepared fabrication packages keyed by board, revision and schematic. */
1067
+ packageCache = /* @__PURE__ */ new Map();
1068
+ constructor(config = {}) {
1069
+ this.config = config;
1070
+ this.options = {
1071
+ probeVersion: config.probeVersion ?? defaultVersionProbe,
1072
+ spawnProcess: config.spawnProcess ?? ((command, args, settings) => spawn(command, [...args], settings)),
1073
+ runCommand: config.runCommand ?? defaultRunCommand,
1074
+ openExternal: config.openExternal ?? defaultOpenExternal
1075
+ };
1076
+ this.cacheRoot = canonical(config.cacheRoot ?? join(tmpdir(), "huaqiu-hardware-artifacts"));
1077
+ this.glbTimeoutMs = config.glbTimeoutMs ?? 12e4;
1078
+ this.maxSourceBytes = config.maxSourceBytes ?? 33554432;
1079
+ }
1080
+ /** Configured roots, read live so a settings write is visible immediately. */
1081
+ roots() {
1082
+ const live = this.config.settings?.();
1083
+ const kicadRoot = live?.kicadRoot ?? this.config.kicadRoot;
1084
+ const solidcraftRoot = live?.solidcraftRoot ?? this.config.solidcraftRoot;
1085
+ return {
1086
+ ...kicadRoot === void 0 ? {} : { kicadRoot },
1087
+ ...solidcraftRoot === void 0 ? {} : { solidcraftRoot }
1088
+ };
1089
+ }
1090
+ /** Resolve configured installations from validated absolute paths only. */
1091
+ installations() {
1092
+ const roots = this.roots();
1093
+ const kicadRoot = roots.kicadRoot ? canonical(roots.kicadRoot) : void 0;
1094
+ let kicadCli;
1095
+ if (kicadRoot !== void 0) kicadCli = existing(basename(kicadRoot).toLowerCase().startsWith("kicad-cli") ? [kicadRoot] : kicadCandidates(kicadRoot).cli);
1096
+ const candidates = kicadRoot === void 0 ? {
1097
+ cli: [],
1098
+ kicad: [],
1099
+ eeschema: [],
1100
+ pcbnew: []
1101
+ } : kicadCandidates(kicadCli === void 0 ? kicadRoot : installRootFromCli(kicadCli));
1102
+ const pcbEditor = existing(candidates.pcbnew);
1103
+ const schematicEditor = existing(candidates.eeschema);
1104
+ const projectManager = existing(candidates.kicad);
1105
+ const version = kicadCli === void 0 ? void 0 : this.options.probeVersion(kicadCli);
1106
+ const kicad = kicadCli === void 0 ? {
1107
+ configured: false,
1108
+ error: "KiCad installation is not configured"
1109
+ } : version === void 0 ? {
1110
+ configured: false,
1111
+ root: kicadRoot,
1112
+ cli: kicadCli,
1113
+ error: `${kicadCli} did not answer a version probe`
1114
+ } : {
1115
+ configured: true,
1116
+ root: kicadRoot,
1117
+ cli: kicadCli,
1118
+ version,
1119
+ ...projectManager === void 0 ? {} : { projectManager },
1120
+ ...pcbEditor === void 0 ? {} : { pcbEditor },
1121
+ ...schematicEditor === void 0 ? {} : { schematicEditor }
1122
+ };
1123
+ const solidRoot = roots.solidcraftRoot ? canonical(roots.solidcraftRoot) : void 0;
1124
+ const solidExecutable = solidRoot === void 0 ? void 0 : existing(solidcraftCandidates(solidRoot));
1125
+ return {
1126
+ kicad,
1127
+ solidcraft: solidExecutable === void 0 ? {
1128
+ configured: false,
1129
+ error: "SolidCraft installation is not configured"
1130
+ } : {
1131
+ configured: true,
1132
+ root: solidRoot,
1133
+ executable: solidExecutable
1134
+ }
1135
+ };
1136
+ }
1137
+ /** Paths passed to agent child processes. Never assign these globally. */
1138
+ childEnvironment() {
1139
+ const installed = this.installations();
1140
+ const env = {};
1141
+ if (installed.kicad.cli !== void 0) env.HUAQIU_KICAD_CLI = installed.kicad.cli;
1142
+ if (installed.kicad.pcbEditor !== void 0) env.HUAQIU_KICAD_PCBNEW = installed.kicad.pcbEditor;
1143
+ if (installed.kicad.schematicEditor !== void 0) env.HUAQIU_KICAD_EESCHEMA = installed.kicad.schematicEditor;
1144
+ if (installed.solidcraft.executable !== void 0) env.HUAQIU_SOLIDCRAFT = installed.solidcraft.executable;
1145
+ return env;
1146
+ }
1147
+ /** Compact agent context: validated paths only, no project inventory dump. */
1148
+ environmentText(current) {
1149
+ const installed = this.installations();
1150
+ const scope = current ?? this.soleDiscovery();
1151
+ const lines = ["<hardware_environment>"];
1152
+ lines.push("KiCad:");
1153
+ lines.push(` configured: ${String(installed.kicad.configured)}`);
1154
+ for (const key of [
1155
+ "version",
1156
+ "cli",
1157
+ "pcbEditor",
1158
+ "schematicEditor"
1159
+ ]) {
1160
+ const value = installed.kicad[key];
1161
+ if (value !== void 0) lines.push(` ${key}: ${value}`);
1162
+ }
1163
+ if (installed.kicad.error !== void 0) lines.push(` error: ${installed.kicad.error}`);
1164
+ lines.push("SolidCraft:");
1165
+ lines.push(` configured: ${String(installed.solidcraft.configured)}`);
1166
+ if (installed.solidcraft.executable !== void 0) lines.push(` executable: ${installed.solidcraft.executable}`);
1167
+ if (installed.solidcraft.error !== void 0) lines.push(` error: ${installed.solidcraft.error}`);
1168
+ if (scope?.selected !== void 0) {
1169
+ lines.push("Current project:");
1170
+ lines.push(` root: ${scope.cwd}`);
1171
+ lines.push(` project: ${scope.selected.path}`);
1172
+ if (scope.selected.schematic !== void 0) lines.push(` schematic: ${scope.selected.schematic.path}`);
1173
+ const board = scope.selected.boards[0];
1174
+ if (board !== void 0) lines.push(` selected_pcb: ${board.path}`);
1175
+ }
1176
+ lines.push("</hardware_environment>");
1177
+ return lines.join("\n");
1178
+ }
1179
+ /**
1180
+ * Deterministic discovery. An explicit project or manifest wins; otherwise
1181
+ * exactly one `.kicad_pro` may be selected automatically. Ambiguity is
1182
+ * returned as a selection requirement, never resolved by taking the first.
1183
+ *
1184
+ * @param cwdInput - workspace directory to walk.
1185
+ * @param explicitProject - project chosen by the user, absolute or cwd-relative.
1186
+ * @param sessionId - DSH session the discovery belongs to. Recording it per
1187
+ * session is what keeps one open viewer from revoking another's roots.
1188
+ */
1189
+ discover(cwdInput, explicitProject, sessionId) {
1190
+ const cwd = canonical(cwdInput);
1191
+ const manifestPath = join(cwd, ".hardware-engineering.json");
1192
+ let manifest;
1193
+ if (existsSync(manifestPath)) try {
1194
+ manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
1195
+ } catch (error) {
1196
+ return this.remember({
1197
+ cwd,
1198
+ manifestPath,
1199
+ projects: [],
1200
+ issue: {
1201
+ code: "bad-manifest",
1202
+ message: `invalid .hardware-engineering.json: ${String(error)}`
1203
+ }
1204
+ }, sessionId);
1205
+ }
1206
+ const projectPaths = /* @__PURE__ */ new Set();
1207
+ if (explicitProject !== void 0 && explicitProject.trim() !== "") {
1208
+ const requested = isAbsolute(explicitProject) ? canonical(explicitProject) : resolve(cwd, explicitProject);
1209
+ if (!existsSync(requested)) return this.remember({
1210
+ cwd,
1211
+ ...manifest === void 0 ? {} : { manifestPath },
1212
+ projects: [],
1213
+ issue: {
1214
+ code: "missing-project",
1215
+ message: `${requested} does not exist`
1216
+ }
1217
+ }, sessionId);
1218
+ projectPaths.add(requested);
1219
+ } else if (manifest?.project !== void 0 && manifest.project.trim() !== "") projectPaths.add(isAbsolute(manifest.project) ? canonical(manifest.project) : resolve(cwd, manifest.project));
1220
+ else for (const path of walkFiles(cwd, (name) => name.toLowerCase().endsWith(".kicad_pro"))) projectPaths.add(path);
1221
+ const projects = [...projectPaths].sort().map((path) => this.projectFrom(path, cwd, manifest));
1222
+ if (projects.length === 0) return this.remember({
1223
+ cwd,
1224
+ ...manifest === void 0 ? {} : { manifestPath },
1225
+ projects,
1226
+ issue: {
1227
+ code: "no-project",
1228
+ message: `no .kicad_pro found under ${cwd}`
1229
+ }
1230
+ }, sessionId);
1231
+ if (projects.length > 1) return this.remember({
1232
+ cwd,
1233
+ ...manifest === void 0 ? {} : { manifestPath },
1234
+ projects,
1235
+ issue: {
1236
+ code: "selection-required",
1237
+ message: `${projects.length} projects found; select one explicitly`
1238
+ }
1239
+ }, sessionId);
1240
+ const selected = projects[0];
1241
+ return this.remember({
1242
+ cwd,
1243
+ ...manifest === void 0 ? {} : { manifestPath },
1244
+ projects,
1245
+ selected,
1246
+ ...selected.selectionRequired ? { issue: {
1247
+ code: "selection-required",
1248
+ message: "select an artifact explicitly"
1249
+ } } : {}
1250
+ }, sessionId);
1251
+ }
1252
+ /** Last discovery for one scope, never another session's. */
1253
+ discovery(sessionId) {
1254
+ return this.discoveries.get(scopeKey(sessionId));
1255
+ }
1256
+ /** The only discovery the host can speak for without being told a session. */
1257
+ soleDiscovery() {
1258
+ if (this.discoveries.size !== 1) return void 0;
1259
+ return [...this.discoveries.values()][0];
1260
+ }
1261
+ remember(result, sessionId) {
1262
+ this.discoveries.set(scopeKey(sessionId), result);
1263
+ return result;
1264
+ }
1265
+ projectFrom(projectPath, cwd, manifest) {
1266
+ const dir = dirname(projectPath);
1267
+ const name = basename(projectPath, extname(projectPath));
1268
+ const resolvePath = (value) => isAbsolute(value) ? canonical(value) : resolve(dir, value);
1269
+ const explicitSchematic = manifest?.schematic === void 0 ? void 0 : resolvePath(manifest.schematic);
1270
+ let schematicPath = explicitSchematic !== void 0 && existsSync(explicitSchematic) ? explicitSchematic : void 0;
1271
+ if (schematicPath === void 0) {
1272
+ const named = join(dir, `${name}.kicad_sch`);
1273
+ if (existsSync(named)) schematicPath = named;
1274
+ else {
1275
+ const candidates = readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".kicad_sch")).map((entry) => join(dir, entry.name)).sort();
1276
+ if (candidates.length === 1) schematicPath = candidates[0];
1277
+ }
1278
+ }
1279
+ const sheets = [];
1280
+ if (schematicPath !== void 0) {
1281
+ const visited = /* @__PURE__ */ new Set([canonical(schematicPath)]);
1282
+ const queue = childSheetFiles(canonical(schematicPath));
1283
+ while (queue.length > 0) {
1284
+ const canonicalNext = canonical(queue.shift());
1285
+ if (visited.has(canonicalNext)) continue;
1286
+ visited.add(canonicalNext);
1287
+ if (!existsSync(canonicalNext) || extname(canonicalNext).toLowerCase() !== ".kicad_sch") continue;
1288
+ sheets.push(artifact("schematic", canonicalNext, projectPath, canonical(schematicPath)));
1289
+ queue.push(...childSheetFiles(canonicalNext));
1290
+ }
1291
+ }
1292
+ const manifestBoards = manifest?.boards === void 0 ? [] : manifest.boards.filter((entry) => existsSync(resolvePath(entry.path))).map((entry) => artifact("pcb", resolvePath(entry.path), projectPath));
1293
+ const scannedBoards = walkFiles(dir, (file) => file.toLowerCase().endsWith(".kicad_pcb")).map((path) => artifact("pcb", path, projectPath));
1294
+ const boards = manifestBoards.length > 0 ? manifestBoards : [...scannedBoards].sort((left, right) => boardRank(left, right, name));
1295
+ const owned = boards.find((board) => basename(board.path, ".kicad_pcb") === name) ?? boards[0];
1296
+ const ownershipAmbiguous = manifestBoards.length === 0 && boards.length > 1 && basename(owned?.path ?? "", ".kicad_pcb") !== name;
1297
+ const mechanical = manifest?.mechanical !== void 0 ? manifest.mechanical.map((model) => artifact("mechanical-3d", resolvePath(model.path), projectPath)) : walkFiles(dir, (file) => MECHANICAL_EXTENSIONS.has(extname(file).toLowerCase())).map((path) => artifact("mechanical-3d", path, projectPath));
1298
+ const sourceSchematic = schematicPath === void 0 ? void 0 : artifact("schematic", schematicPath, projectPath);
1299
+ const sourceBoard = ownershipAmbiguous ? void 0 : owned;
1300
+ return {
1301
+ path: projectPath,
1302
+ name,
1303
+ ...sourceSchematic === void 0 ? {} : {
1304
+ rootSheet: sourceSchematic,
1305
+ schematic: sourceSchematic
1306
+ },
1307
+ ...sourceSchematic === void 0 ? {} : { bom: {
1308
+ ...artifact("bom", sourceSchematic.path, projectPath, sourceSchematic.path),
1309
+ title: `BOM — ${sourceSchematic.title}`
1310
+ } },
1311
+ ...sourceBoard === void 0 ? {} : {
1312
+ pcb3d: {
1313
+ ...artifact("pcb-3d", sourceBoard.path, projectPath, sourceBoard.path),
1314
+ title: `3D — ${sourceBoard.title}`
1315
+ },
1316
+ defaultBoard: sourceBoard.path
1317
+ },
1318
+ sheets,
1319
+ boards,
1320
+ mechanical,
1321
+ selectionRequired: boards.length > 1 && ownershipAmbiguous
1322
+ };
1323
+ }
1324
+ /** Validate and launch a native application without a shell. */
1325
+ open(request) {
1326
+ const path = canonical(request.artifactPath);
1327
+ if (!existsSync(path)) throw errorWithCode(`artifact does not exist: ${path}`, "missing-artifact", 404);
1328
+ const installed = this.installations();
1329
+ const ext = extname(path).toLowerCase();
1330
+ let command;
1331
+ if (ext === ".kicad_sch") command = installed.kicad.schematicEditor;
1332
+ else if (ext === ".kicad_pcb") command = installed.kicad.pcbEditor;
1333
+ else if (ext === ".kicad_pro") command = installed.kicad.projectManager;
1334
+ else throw errorWithCode(`unsupported KiCad artifact: ${ext}`, "unsupported-artifact", 415);
1335
+ if (command === void 0) throw errorWithCode("the configured KiCad installation has no editor for this artifact", "missing-executable", 412);
1336
+ const settings = {
1337
+ cwd: dirname(path),
1338
+ detached: true,
1339
+ stdio: "ignore",
1340
+ windowsHide: true,
1341
+ shell: false
1342
+ };
1343
+ const child = this.options.spawnProcess(command, [path], settings);
1344
+ return {
1345
+ launched: true,
1346
+ command,
1347
+ args: [path],
1348
+ cwd: settings.cwd,
1349
+ ...child.pid === void 0 ? {} : { pid: child.pid }
1350
+ };
1351
+ }
1352
+ /**
1353
+ * Workspace roots a read may target: what this scope discovered, plus what
1354
+ * the caller named.
1355
+ *
1356
+ * Additive on purpose. The previous shape unioned the caller's roots with one
1357
+ * process-wide "last discovery", so any other session's discovery — a
1358
+ * workspace switch is exactly that — replaced the root the open viewer was
1359
+ * authorized by, and its next read failed with "artifact is outside the
1360
+ * authorized workspace". Roots now only ever accumulate within their scope.
1361
+ */
1362
+ authorizedRoots(roots, sessionId) {
1363
+ const candidates = /* @__PURE__ */ new Set();
1364
+ for (const root of discoveredRoots(this.discovery(sessionId))) candidates.add(canonical(root));
1365
+ for (const root of roots ?? []) {
1366
+ if (root === void 0 || root.trim() === "") continue;
1367
+ candidates.add(rootOf(root));
1368
+ }
1369
+ return [...candidates];
1370
+ }
1371
+ /**
1372
+ * Authorize one artifact path: canonical, realpath-checked, inside a
1373
+ * workspace root, and of an expected type. A browser request cannot turn
1374
+ * this into an arbitrary filesystem read, even from loopback.
1375
+ */
1376
+ authorize(artifactPath, roots, sessionId) {
1377
+ if (!isAbsolute(artifactPath)) throw errorWithCode("artifact identity must be an absolute path", "invalid-identity", 400);
1378
+ const requested = canonical(artifactPath);
1379
+ if (SOURCE_EXTENSIONS[extname(requested).toLowerCase()] === void 0) throw errorWithCode(`unsupported artifact type: ${extname(requested)}`, "unsupported-artifact", 415);
1380
+ const authorized = this.authorizedRoots(roots, sessionId);
1381
+ if (authorized.length === 0) throw errorWithCode("no authorized workspace is known to the host", "unauthorized", 403);
1382
+ if (!authorized.some((root) => isInside(requested, canonical(root)))) throw errorWithCode("artifact is outside the authorized workspace", "unauthorized", 403);
1383
+ if (!existsSync(requested)) throw errorWithCode(`artifact does not exist: ${requested}`, "missing-artifact", 404);
1384
+ const real = realOrUndefined(requested);
1385
+ if (real === void 0) throw errorWithCode(`artifact cannot be resolved: ${requested}`, "invalid-identity", 400);
1386
+ if (!authorized.some((root) => {
1387
+ const realRoot = realOrUndefined(root) ?? root;
1388
+ return isInside(real, realRoot);
1389
+ })) throw errorWithCode("artifact is outside the authorized workspace", "unauthorized", 403);
1390
+ if (!statSync(real).isFile()) throw errorWithCode(`artifact is not a regular file: ${requested}`, "invalid-identity", 400);
1391
+ if (SOURCE_EXTENSIONS[extname(real).toLowerCase()] === void 0) throw errorWithCode("artifact type changed during resolution", "unsupported-artifact", 415);
1392
+ return {
1393
+ path: real,
1394
+ kind: SOURCE_EXTENSIONS[extname(real).toLowerCase()]
1395
+ };
1396
+ }
1397
+ /** Saved source text plus a content-addressed revision. */
1398
+ async readSource(request) {
1399
+ const { path, kind } = this.authorize(request.artifactPath, request.roots, request.sessionId);
1400
+ const info = statSync(path);
1401
+ if (info.size > this.maxSourceBytes) throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, "too-large", 413);
1402
+ const body = await readFile(path);
1403
+ const revision = createHash("sha256").update(body).digest("hex");
1404
+ if (request.expectedRevision !== void 0 && request.expectedRevision !== "" && request.expectedRevision !== revision) throw errorWithCode(`source changed since it was selected (expected ${request.expectedRevision}, found ${revision})`, "stale-revision", 409);
1405
+ return {
1406
+ path,
1407
+ kind,
1408
+ revision,
1409
+ bytes: body.byteLength,
1410
+ mtimeMs: info.mtimeMs,
1411
+ text: body.toString("utf8")
1412
+ };
1413
+ }
1414
+ sourceRevision(path) {
1415
+ if (statSync(path).size > this.maxSourceBytes) throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, "too-large", 413);
1416
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
1417
+ }
1418
+ /** Cache directory for one board's derived outputs. */
1419
+ glbDirectory(boardPath) {
1420
+ const digest = createHash("sha256").update(boardPath).digest("hex").slice(0, 16);
1421
+ return join(this.cacheRoot, "glb", digest);
1422
+ }
1423
+ /**
1424
+ * Generate (or reuse) the GLB for one board.
1425
+ *
1426
+ * - cache key includes the source content hash, so same-size/same-mtime edits invalidate
1427
+ * - one in-flight export is shared by concurrent callers for the same revision
1428
+ * - output is written to a temp file and renamed only after it validates
1429
+ * - a timeout or abort leaves no partial file behind
1430
+ */
1431
+ async exportGlb(request) {
1432
+ const { path } = this.authorize(request.artifactPath, request.roots, request.sessionId);
1433
+ if (extname(path).toLowerCase() !== ".kicad_pcb") throw errorWithCode("GLB export requires a .kicad_pcb artifact", "unsupported-artifact", 415);
1434
+ const installed = this.installations();
1435
+ if (!installed.kicad.configured || installed.kicad.cli === void 0) throw errorWithCode(installed.kicad.error ?? "the configured KiCad installation has no kicad-cli", "not-configured", 412);
1436
+ const cli = installed.kicad.cli;
1437
+ const revision = this.sourceRevision(path);
1438
+ const key = `${path}:${revision}`;
1439
+ const cached = this.glbCache.get(key);
1440
+ if (cached !== void 0 && existsSync(cached.file)) {
1441
+ const info = statSync(cached.file);
1442
+ return {
1443
+ ...cached,
1444
+ bytes: info.size,
1445
+ cached: true
1446
+ };
1447
+ }
1448
+ const pending = this.glbPending.get(key);
1449
+ if (pending !== void 0) return pending;
1450
+ const directory = this.glbDirectory(path);
1451
+ const target = join(directory, `board-${revision.slice(0, 16)}.glb`);
1452
+ const running = (async () => {
1453
+ mkdirSync(directory, { recursive: true });
1454
+ const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`);
1455
+ mkdirSync(tempDirectory, { recursive: true });
1456
+ const tempFile = join(tempDirectory, "board.glb");
1457
+ try {
1458
+ const result = await this.options.runCommand(cli, [
1459
+ "pcb",
1460
+ "export",
1461
+ "glb",
1462
+ "--output",
1463
+ tempFile,
1464
+ path
1465
+ ], {
1466
+ cwd: dirname(path),
1467
+ timeoutMs: this.glbTimeoutMs,
1468
+ ...request.signal === void 0 ? {} : { signal: request.signal }
1469
+ });
1470
+ if (result.timedOut) throw errorWithCode(`kicad-cli pcb export glb timed out after ${this.glbTimeoutMs} ms`, "export-timeout", 504);
1471
+ if (result.exitCode !== 0) throw errorWithCode(`kicad-cli pcb export glb failed: ${(result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)}`, "export-failed", 502);
1472
+ if (!existsSync(tempFile)) throw errorWithCode("kicad-cli pcb export glb produced no output", "export-failed", 502);
1473
+ const bytes = statSync(tempFile).size;
1474
+ if (bytes === 0 || readFileSync(tempFile).subarray(0, 4).toString("ascii") !== "glTF") throw errorWithCode("kicad-cli wrote an invalid GLB", "export-failed", 502);
1475
+ renameSync(tempFile, target);
1476
+ const generated = {
1477
+ path,
1478
+ revision,
1479
+ bytes,
1480
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1481
+ cached: false,
1482
+ file: target
1483
+ };
1484
+ this.glbCache.set(key, generated);
1485
+ return generated;
1486
+ } finally {
1487
+ rmSync(tempDirectory, {
1488
+ recursive: true,
1489
+ force: true
1490
+ });
1491
+ }
1492
+ })();
1493
+ this.glbPending.set(key, running);
1494
+ try {
1495
+ return await running;
1496
+ } finally {
1497
+ this.glbPending.delete(key);
1498
+ }
1499
+ }
1500
+ /**
1501
+ * Grouped BOM for one saved root schematic.
1502
+ *
1503
+ * Reuses KiCad's own BOM extraction (`kicad-cli sch export bom`), the same
1504
+ * authoritative source `analyze_kicad_module` consumes, rather than building a
1505
+ * second component analyser. Grouping key is every non-reference column, so
1506
+ * different MPNs never merge and DNP stays explicit.
1507
+ */
1508
+ async exportBom(request) {
1509
+ const { path, kind } = this.authorize(request.artifactPath, request.roots, request.sessionId);
1510
+ if (kind !== "schematic") throw errorWithCode("BOM export requires a .kicad_sch artifact", "unsupported-artifact", 415);
1511
+ const installed = this.installations();
1512
+ if (!installed.kicad.configured || installed.kicad.cli === void 0) throw errorWithCode(installed.kicad.error ?? "the configured KiCad installation has no kicad-cli", "not-configured", 412);
1513
+ const revision = this.sourceRevision(path);
1514
+ const key = `${path}:${revision}`;
1515
+ const cached = this.bomCache.get(key);
1516
+ if (cached !== void 0) return {
1517
+ ...cached,
1518
+ cached: true
1519
+ };
1520
+ const directory = join(this.cacheRoot, "bom", createHash("sha256").update(path).digest("hex").slice(0, 16));
1521
+ const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`);
1522
+ mkdirSync(tempDirectory, { recursive: true });
1523
+ const tempFile = join(tempDirectory, "bom.csv");
1524
+ try {
1525
+ const result = await this.options.runCommand(installed.kicad.cli, [
1526
+ "sch",
1527
+ "export",
1528
+ "bom",
1529
+ "--output",
1530
+ tempFile,
1531
+ path
1532
+ ], {
1533
+ cwd: dirname(path),
1534
+ timeoutMs: 6e4,
1535
+ ...request.signal === void 0 ? {} : { signal: request.signal }
1536
+ });
1537
+ if (result.timedOut) throw errorWithCode("kicad-cli sch export bom timed out", "export-timeout", 504);
1538
+ if (result.exitCode !== 0) throw errorWithCode(`kicad-cli sch export bom failed: ${(result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)}`, "export-failed", 502);
1539
+ if (!existsSync(tempFile)) throw errorWithCode("kicad-cli produced no BOM output", "export-failed", 502);
1540
+ const rows = groupBomRows(parseCsv(readFileSync(tempFile, "utf8")));
1541
+ const generated = {
1542
+ path,
1543
+ revision,
1544
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1545
+ cached: false,
1546
+ rows,
1547
+ source: "kicad-cli-bom"
1548
+ };
1549
+ this.bomCache.set(key, generated);
1550
+ return generated;
1551
+ } finally {
1552
+ rmSync(tempDirectory, {
1553
+ recursive: true,
1554
+ force: true
1555
+ });
1556
+ }
1557
+ }
1558
+ /** Live order settings, read at call time so a settings write is immediate. */
1559
+ orderSettings() {
1560
+ const live = this.config.settings?.();
1561
+ const baseUrl = ([
1562
+ live?.orderBaseUrl,
1563
+ this.config.orderBaseUrl,
1564
+ process.env.HUAQIU_ORDER_BASE_URL
1565
+ ].find((value) => value !== void 0 && value.trim() !== "") ?? "https://www.eda.cn").replace(/\/+$/u, "");
1566
+ const pageBase = (this.config.orderPageBase ?? "https://www.hqpcb.com").replace(/\/+$/u, "");
1567
+ const token = live?.accessToken ?? this.config.accessToken ?? process.env.HUAQIU_ACCESS_TOKEN;
1568
+ return {
1569
+ baseUrl,
1570
+ pageBase,
1571
+ ...token === void 0 || token.trim() === "" ? {} : { accessToken: token.trim() }
1572
+ };
1573
+ }
1574
+ /** What the Order destination may do right now, without contacting anything. */
1575
+ async orderConfig() {
1576
+ const installed = this.installations();
1577
+ const settings = this.orderSettings();
1578
+ return {
1579
+ configured: installed.kicad.configured,
1580
+ baseUrl: settings.baseUrl,
1581
+ hasToken: await this.orderToken() !== void 0,
1582
+ provider: "huaqiu"
1583
+ };
1584
+ }
1585
+ /**
1586
+ * The token the order page must carry.
1587
+ *
1588
+ * An explicitly configured token wins (it makes a scripted run possible);
1589
+ * otherwise the signed-in Huaqiu session is used, which is the same token the
1590
+ * eda.cn API accepts. Absent both, ordering is refused before anything is
1591
+ * uploaded — the page would render signed out otherwise.
1592
+ */
1593
+ async orderToken() {
1594
+ const settings = this.orderSettings();
1595
+ if (settings.accessToken !== void 0) return settings.accessToken;
1596
+ if (this.config.authToken === void 0) return void 0;
1597
+ try {
1598
+ const token = await this.config.authToken();
1599
+ return token === null || token.trim() === "" ? void 0 : token.trim();
1600
+ } catch {
1601
+ return;
1602
+ }
1603
+ }
1604
+ /**
1605
+ * Build the fabrication archive and the assembly inputs for one board.
1606
+ *
1607
+ * The gerber/drill export is `kicad-cli`'s own plotter, so the archive is the
1608
+ * same set of files a KiCad "Place order" would upload. Cached by source
1609
+ * revision: reopening the panel must not re-run the exporter.
1610
+ */
1611
+ async fabricate(request) {
1612
+ const { path } = this.authorize(request.boardPath, request.roots, request.sessionId);
1613
+ if (extname(path).toLowerCase() !== ".kicad_pcb") throw errorWithCode("Fabrication packaging requires a .kicad_pcb artifact", "unsupported-artifact", 415);
1614
+ const installed = this.installations();
1615
+ if (!installed.kicad.configured || installed.kicad.cli === void 0) throw errorWithCode(installed.kicad.error ?? "the configured KiCad installation has no kicad-cli", "not-configured", 412);
1616
+ const cli = installed.kicad.cli;
1617
+ const revision = this.sourceRevision(path);
1618
+ const schematicPath = request.schematicPath === void 0 ? void 0 : this.authorize(request.schematicPath, request.roots, request.sessionId).path;
1619
+ const key = `${path}:${revision}:${schematicPath ?? ""}`;
1620
+ const cached = this.packageCache.get(key);
1621
+ if (cached !== void 0) return cached;
1622
+ const directory = join(this.cacheRoot, "fabrication", createHash("sha256").update(path).digest("hex").slice(0, 16));
1623
+ const work = join(directory, `tmp-${process.pid}-${String(Date.now())}`);
1624
+ const plots = join(work, "plots");
1625
+ const positionsFile = join(work, "positions.raw.csv");
1626
+ mkdirSync(plots, { recursive: true });
1627
+ const signal = request.signal;
1628
+ const run = async (args, what, timeoutMs = 12e4) => {
1629
+ const result = await this.options.runCommand(cli, args, {
1630
+ cwd: dirname(path),
1631
+ timeoutMs,
1632
+ ...signal === void 0 ? {} : { signal }
1633
+ });
1634
+ if (result.timedOut) throw errorWithCode(`kicad-cli ${what} timed out`, "export-timeout", 504);
1635
+ if (result.exitCode !== 0) throw errorWithCode(`kicad-cli ${what} failed: ${(result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)}`, "export-failed", 502);
1636
+ };
1637
+ try {
1638
+ await run([
1639
+ "pcb",
1640
+ "export",
1641
+ "gerbers",
1642
+ "--output",
1643
+ plots,
1644
+ path
1645
+ ], "pcb export gerbers");
1646
+ await run([
1647
+ "pcb",
1648
+ "export",
1649
+ "drill",
1650
+ "--output",
1651
+ plots,
1652
+ "--format",
1653
+ "excellon",
1654
+ "--excellon-units",
1655
+ "mm",
1656
+ "--drill-origin",
1657
+ "absolute",
1658
+ path
1659
+ ], "pcb export drill");
1660
+ const plotNames = readdirSync(plots).filter((name) => statSync(join(plots, name)).isFile()).sort();
1661
+ if (plotNames.length === 0) throw errorWithCode("kicad-cli wrote no fabrication files", "export-failed", 502);
1662
+ const plotted = readExportDirectory(plots, plotNames);
1663
+ const archiveData = zipPackage(plotted);
1664
+ const facts = readBoardFacts(readFileSync(path, "utf8"));
1665
+ let assembly;
1666
+ let assemblyFiles;
1667
+ if (schematicPath !== void 0) {
1668
+ await run([
1669
+ "pcb",
1670
+ "export",
1671
+ "pos",
1672
+ "--format",
1673
+ "csv",
1674
+ "--units",
1675
+ "mm",
1676
+ "--side",
1677
+ "both",
1678
+ "--output",
1679
+ positionsFile,
1680
+ path
1681
+ ], "pcb export pos");
1682
+ const positions = parsePositions(readFileSync(positionsFile, "utf8"));
1683
+ const bomRows = orderBomRows(positions, (await this.exportBom({
1684
+ artifactPath: schematicPath,
1685
+ ...request.roots === void 0 ? {} : { roots: request.roots },
1686
+ ...signal === void 0 ? {} : { signal }
1687
+ })).rows);
1688
+ const positionsText = positionsCsv(positions);
1689
+ const bomText = orderBomCsv(bomRows);
1690
+ assemblyFiles = {
1691
+ positions: positionsText,
1692
+ bom: bomText
1693
+ };
1694
+ assembly = {
1695
+ positions: positions.length,
1696
+ bomLines: bomRows.length,
1697
+ positionsBytes: Buffer.byteLength(positionsText, "utf8"),
1698
+ bomBytes: Buffer.byteLength(bomText, "utf8")
1699
+ };
1700
+ }
1701
+ const result = {
1702
+ boardPath: path,
1703
+ revision,
1704
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1705
+ facts,
1706
+ archive: {
1707
+ zipName: `${packageName(path)}.zip`,
1708
+ zipBytes: archiveData.byteLength,
1709
+ files: plotted.map((file) => ({
1710
+ name: file.name,
1711
+ bytes: file.data.byteLength
1712
+ }))
1713
+ },
1714
+ archiveData,
1715
+ ...assembly === void 0 ? {} : { assembly },
1716
+ ...assemblyFiles === void 0 ? {} : { assemblyFiles }
1717
+ };
1718
+ this.packageCache.set(key, result);
1719
+ return result;
1720
+ } finally {
1721
+ rmSync(work, {
1722
+ recursive: true,
1723
+ force: true
1724
+ });
1725
+ }
1726
+ }
1727
+ /**
1728
+ * Submit one order to the Huaqiu openapi, exactly as the KiCad action does.
1729
+ *
1730
+ * PCB: every `PCB_FORM` field plus the gerber/drill archive as `file`.
1731
+ * SMT: `pcbFile` + `coordFile` + `bomFile` and `reqParseVO`, with the caller's
1732
+ * access token in `authorization`. The backend owns the order; this method
1733
+ * forwards the files and composes the final page URL from the returned id the
1734
+ * way the reference does.
1735
+ */
1736
+ async placeOrder(request) {
1737
+ const settings = this.orderSettings();
1738
+ const bundle = await this.fabricate({
1739
+ boardPath: request.boardPath,
1740
+ ...request.schematicPath === void 0 ? {} : { schematicPath: request.schematicPath },
1741
+ ...request.roots === void 0 ? {} : { roots: request.roots },
1742
+ ...request.sessionId === void 0 ? {} : { sessionId: request.sessionId },
1743
+ ...request.signal === void 0 ? {} : { signal: request.signal }
1744
+ });
1745
+ const token = await this.orderToken();
1746
+ if (token === void 0) throw errorWithCode("placing an order requires a signed-in Huaqiu account (or HUAQIU_ACCESS_TOKEN)", "unauthorized", 401);
1747
+ const facts = bundle.facts;
1748
+ const endpoint = `${settings.baseUrl}${ORDER_PATHS[request.kind]}`;
1749
+ let parts;
1750
+ let files;
1751
+ let headers;
1752
+ if (request.kind === "pcb") {
1753
+ const form = pcbOrderForm(facts, request.quantity === void 0 ? {} : { quantity: request.quantity });
1754
+ parts = Object.entries(form).map(([name, value]) => ({
1755
+ name,
1756
+ value
1757
+ }));
1758
+ files = [{
1759
+ field: "file",
1760
+ name: bundle.archive.zipName,
1761
+ type: "application/zip",
1762
+ data: bundle.archiveData
1763
+ }];
1764
+ } else {
1765
+ if (bundle.assemblyFiles === void 0) throw errorWithCode("SMT order placement requires the project root schematic", "invalid-request", 400);
1766
+ const smt = smtOrderForm(facts, {
1767
+ bomFileName: `${packageName(bundle.boardPath)}-bom.csv`,
1768
+ coordFileName: `${packageName(bundle.boardPath)}-positions.csv`,
1769
+ materialTypes: bundle.assembly?.bomLines ?? 0,
1770
+ ...request.quantity === void 0 ? {} : { quantity: request.quantity }
1771
+ });
1772
+ parts = [{
1773
+ name: "reqParseVO",
1774
+ value: JSON.stringify({
1775
+ pcb_order: pcbOrderForm(facts, request.quantity === void 0 ? {} : { quantity: request.quantity }),
1776
+ smt_order: smt
1777
+ })
1778
+ }];
1779
+ files = [
1780
+ {
1781
+ field: "pcbFile",
1782
+ name: bundle.archive.zipName,
1783
+ type: "application/zip",
1784
+ data: bundle.archiveData
1785
+ },
1786
+ {
1787
+ field: "coordFile",
1788
+ name: String(smt.coord_file_name),
1789
+ type: "application/octet-stream",
1790
+ data: new TextEncoder().encode(bundle.assemblyFiles.positions)
1791
+ },
1792
+ {
1793
+ field: "bomFile",
1794
+ name: String(smt.bom_file_name),
1795
+ type: "application/octet-stream",
1796
+ data: new TextEncoder().encode(bundle.assemblyFiles.bom)
1797
+ }
1798
+ ];
1799
+ headers = { authorization: token };
1800
+ }
1801
+ const boundary = `----huaqiu${createHash("sha256").update(`${endpoint}:${String(Date.now())}`).digest("hex").slice(0, 24)}`;
1802
+ const payload = multipartBody(parts, files, boundary);
1803
+ const post = this.config.postOrder ?? defaultPostOrder;
1804
+ let response;
1805
+ try {
1806
+ response = await post(endpoint, {
1807
+ body: payload.body,
1808
+ contentType: payload.contentType,
1809
+ ...headers === void 0 ? {} : { headers },
1810
+ ...request.signal === void 0 ? {} : { signal: request.signal }
1811
+ });
1812
+ } catch (error) {
1813
+ throw errorWithCode(`the order endpoint could not be reached: ${error instanceof Error ? error.message : String(error)}`, "order-unreachable", 502);
1814
+ }
1815
+ if (response.status < 200 || response.status >= 300) throw errorWithCode(`the order endpoint rejected the request (HTTP ${String(response.status)}): ${response.text.slice(0, 400)}`, "order-rejected", 502);
1816
+ let json;
1817
+ try {
1818
+ json = JSON.parse(response.text);
1819
+ } catch {
1820
+ throw errorWithCode("the order endpoint returned an unreadable response", "order-rejected", 502);
1821
+ }
1822
+ const responseUrl = orderUrlOf(json);
1823
+ if (responseUrl === void 0) throw errorWithCode("the order endpoint returned no order URL", "order-rejected", 502);
1824
+ const ids = orderIdsFromUrl(responseUrl);
1825
+ const orderUrl = request.kind === "pcb" ? pcbOrderUrl(settings.pageBase, ids, token) : smtOrderUrl(settings.pageBase, ids, token) ?? smtOrderUrlFromBackend(responseUrl, token);
1826
+ if (orderUrl === void 0) throw errorWithCode("the order endpoint returned an order id that cannot form a page URL", "order-rejected", 502);
1827
+ const launch = request.launch !== false;
1828
+ let opened = { launched: false };
1829
+ if (launch) try {
1830
+ opened = {
1831
+ launched: true,
1832
+ launcher: this.openOrderUrl(orderUrl).command
1833
+ };
1834
+ } catch {
1835
+ opened = { launched: false };
1836
+ }
1837
+ return {
1838
+ kind: request.kind,
1839
+ orderUrl,
1840
+ responseUrl,
1841
+ ...opened,
1842
+ status: opened.launched ? "launched" : "ready",
1843
+ message: opened.launched ? `Opened the ${request.kind === "pcb" ? "PCB" : "assembly"} order page in your default browser.` : `The ${request.kind === "pcb" ? "PCB" : "assembly"} order page is ready; open the URL to continue.`,
1844
+ endpoint,
1845
+ facts,
1846
+ archive: bundle.archive,
1847
+ ...bundle.assembly === void 0 ? {} : { assembly: bundle.assembly }
1848
+ };
1849
+ }
1850
+ /**
1851
+ * Open one order page in the OS default browser.
1852
+ *
1853
+ * This is the only place a URL reaches an external program; the URL is
1854
+ * validated by shape first and passed as a plain argument.
1855
+ */
1856
+ openOrderUrl(raw) {
1857
+ const url = externalUrlTarget(raw);
1858
+ const spec = this.options.openExternal(url);
1859
+ this.options.spawnProcess(spec.command, spec.args, {
1860
+ cwd: tmpdir(),
1861
+ detached: true,
1862
+ stdio: "ignore",
1863
+ windowsHide: true,
1864
+ shell: false
1865
+ });
1866
+ return {
1867
+ launched: true,
1868
+ command: spec.command,
1869
+ url
1870
+ };
1871
+ }
1872
+ /** Serve a generated GLB file, re-validating the cache entry first. */
1873
+ glbFile(boardPath, revision) {
1874
+ const key = `${canonical(boardPath)}:${revision}`;
1875
+ const entry = this.glbCache.get(key);
1876
+ if (entry === void 0 || !existsSync(entry.file)) throw errorWithCode("generated GLB is not available for this revision", "stale-revision", 409);
1877
+ return entry.file;
1878
+ }
1879
+ /** Drop cached derived outputs for one board (or all of them). */
1880
+ clearCache(boardPath) {
1881
+ this.packageCache.clear();
1882
+ if (boardPath === void 0) {
1883
+ this.glbCache.clear();
1884
+ rmSync(this.cacheRoot, {
1885
+ recursive: true,
1886
+ force: true
1887
+ });
1888
+ return;
1889
+ }
1890
+ const prefix = `${canonical(boardPath)}:`;
1891
+ for (const key of [...this.glbCache.keys()]) if (key.startsWith(prefix)) this.glbCache.delete(key);
1892
+ rmSync(this.glbDirectory(canonical(boardPath)), {
1893
+ recursive: true,
1894
+ force: true
1895
+ });
1896
+ }
1897
+ };
1898
+ /** Ownership order: project-named board first, then shallower, then alphabetical. */
1899
+ function boardRank(left, right, projectName) {
1900
+ const leftNamed = basename(left.path, ".kicad_pcb") === projectName ? 0 : 1;
1901
+ const rightNamed = basename(right.path, ".kicad_pcb") === projectName ? 0 : 1;
1902
+ if (leftNamed !== rightNamed) return leftNamed - rightNamed;
1903
+ const leftDepth = left.path.split(sep).length;
1904
+ const rightDepth = right.path.split(sep).length;
1905
+ if (leftDepth !== rightDepth) return leftDepth - rightDepth;
1906
+ return left.path.localeCompare(right.path);
1907
+ }
1908
+ /** RFC4180-style CSV reader: quoted fields, doubled quotes, CRLF rows. */
1909
+ function parseCsv(text) {
1910
+ const rows = [];
1911
+ let row = [];
1912
+ let field = "";
1913
+ let quoted = false;
1914
+ const source = text.replace(/^\uFEFF/u, "");
1915
+ for (let index = 0; index < source.length; index += 1) {
1916
+ const char = source[index];
1917
+ if (quoted) {
1918
+ if (char === "\"") {
1919
+ if (source[index + 1] === "\"") {
1920
+ field += "\"";
1921
+ index += 1;
1922
+ } else quoted = false;
1923
+ } else field += char;
1924
+ continue;
1925
+ }
1926
+ if (char === "\"") quoted = true;
1927
+ else if (char === ",") {
1928
+ row.push(field);
1929
+ field = "";
1930
+ } else if (char === "\r") continue;
1931
+ else if (char === "\n") {
1932
+ row.push(field);
1933
+ rows.push(row);
1934
+ row = [];
1935
+ field = "";
1936
+ } else field += char;
1937
+ }
1938
+ if (field !== "" || row.length > 0) {
1939
+ row.push(field);
1940
+ rows.push(row);
1941
+ }
1942
+ return rows.filter((cells) => cells.some((cell) => cell.trim() !== ""));
1943
+ }
1944
+ /**
1945
+ * Group KiCad's per-reference BOM rows.
1946
+ *
1947
+ * Identity is every column except the reference and quantity columns, so a
1948
+ * different MPN or a DNP flag always produces a separate line; ordering follows
1949
+ * the first reference seen, which keeps the table stable between reads.
1950
+ *
1951
+ * Column names follow `kicad-cli sch export bom`'s default field set, which is
1952
+ * `Refs,Value,Footprint,Qty,DNP`; a customized `--fields` header may spell the
1953
+ * same columns out in full, and a grouped export may pack several references
1954
+ * into one cell, so both spellings and both shapes are accepted.
1955
+ */
1956
+ function groupBomRows(table) {
1957
+ const [header, ...body] = table;
1958
+ if (header === void 0) return [];
1959
+ const columns = header.map((cell) => cell.trim());
1960
+ const find = (...aliases) => columns.findIndex((cell) => aliases.some((alias) => alias.test(cell)));
1961
+ const referenceIndex = find(/^refs?$/iu, /^references?$/iu);
1962
+ const quantityIndex = find(/^qty$/iu, /^quantity$/iu);
1963
+ const valueIndex = find(/^value$/iu);
1964
+ const footprintIndex = find(/^footprint$/iu);
1965
+ const dnpIndex = find(/^dnp$/iu);
1966
+ const groups = /* @__PURE__ */ new Map();
1967
+ for (const cells of body) {
1968
+ const references = referenceIndex === -1 ? [] : (cells[referenceIndex] ?? "").split(/[,;\s]+/u).map((reference) => reference.trim()).filter((reference) => reference !== "");
1969
+ if (references.length === 0) continue;
1970
+ const fields = {};
1971
+ columns.forEach((column, index) => {
1972
+ if (index === referenceIndex || index === quantityIndex || index === valueIndex || index === footprintIndex || index === dnpIndex) return;
1973
+ const text = (cells[index] ?? "").trim();
1974
+ if (text !== "") fields[column] = text;
1975
+ });
1976
+ const dnpText = dnpIndex === -1 ? "" : (cells[dnpIndex] ?? "").trim();
1977
+ const dnp = /^(1|true|yes|dnp|x)$/iu.test(dnpText);
1978
+ const identity = JSON.stringify([
1979
+ valueIndex === -1 ? "" : (cells[valueIndex] ?? "").trim(),
1980
+ footprintIndex === -1 ? "" : (cells[footprintIndex] ?? "").trim(),
1981
+ dnp,
1982
+ Object.fromEntries(Object.entries(fields).sort(([a], [b]) => a.localeCompare(b)))
1983
+ ]);
1984
+ const group = groups.get(identity) ?? {
1985
+ references: [],
1986
+ fields,
1987
+ dnp
1988
+ };
1989
+ group.references.push(...references);
1990
+ groups.set(identity, group);
1991
+ }
1992
+ return [...groups.entries()].map(([identity, group]) => {
1993
+ const [value, footprint, dnp] = JSON.parse(identity);
1994
+ return {
1995
+ references: group.references,
1996
+ quantity: group.references.length,
1997
+ value,
1998
+ footprint,
1999
+ dnp,
2000
+ fields: group.fields
2001
+ };
2002
+ });
2003
+ }
2004
+ //#endregion
2005
+ export { smtOrderUrl as _, DEFAULT_ORDER_PAGE_BASE as a, snapThickness as b, orderBomCsv as c, parsePositions as d, pcbOrderForm as f, smtOrderForm as g, readBoardFacts as h, DEFAULT_ORDER_BASE_URL as i, orderBomRows as l, positionsCsv as m, groupBomRows as n, ORDER_PATHS as o, pcbOrderUrl as p, parseCsv as r, ORDER_SOURCE_TID as s, HardwareArtifactService as t, orderIdsFromUrl as u, smtOrderUrlFromBackend as v, snapTraceTier as x, snapHoleTier as y };