@qmingjun/dsh-eda-mcp 0.0.0-stage → 1.1.12

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.
Files changed (53) hide show
  1. package/AGENTS.md +63 -0
  2. package/CHANGELOG.md +792 -0
  3. package/CONTRIBUTING.md +154 -0
  4. package/LICENSE +55 -0
  5. package/README.md +290 -2
  6. package/README.zh.md +449 -0
  7. package/cordis.patch.yml +7 -0
  8. package/docs/design-rules.md +254 -0
  9. package/docs/dsh-version-sweep.md +73 -0
  10. package/docs/pitfalls.md +99 -0
  11. package/docs/project-status.md +100 -0
  12. package/docs/release.md +215 -0
  13. package/docs/schematic-workflow.md +297 -0
  14. package/docs/tools.md +184 -0
  15. package/jlc-extension/api-bridge.js +879 -0
  16. package/jlc-extension/extension.json +104 -0
  17. package/lib/bridge.mjs +4179 -0
  18. package/lib/client.js +1605 -0
  19. package/lib/extension-digest.json +6 -0
  20. package/lib/index.js +1261 -0
  21. package/package.json +144 -4
  22. package/src/bridge/design-intake.ts +133 -0
  23. package/src/bridge/design-rules.ts +228 -0
  24. package/src/bridge/eda-launch.ts +267 -0
  25. package/src/bridge/extension-package.ts +35 -0
  26. package/src/bridge/index.ts +3576 -0
  27. package/src/bridge/netlist-erc.ts +305 -0
  28. package/src/bridge/schematic-audit.ts +131 -0
  29. package/src/bridge/workflow-guide.ts +65 -0
  30. package/src/bridge-diagnostics.ts +185 -0
  31. package/src/client/EdaMcpSettingsCard.tsx +571 -0
  32. package/src/client/index.ts +40 -0
  33. package/src/client/locales.ts +83 -0
  34. package/src/client/settings-scope.ts +160 -0
  35. package/src/config-values.ts +60 -0
  36. package/src/guidance.ts +35 -0
  37. package/src/index.ts +365 -0
  38. package/src/loopback.ts +48 -0
  39. package/src/node-runtime.ts +120 -0
  40. package/src/routes.ts +377 -0
  41. package/src/skills-content.ts +309 -0
  42. package/src/skills.ts +91 -0
  43. package/test/config-values.test.ts +60 -0
  44. package/test/design-intake.test.ts +40 -0
  45. package/test/design-rules.test.ts +72 -0
  46. package/test/eda-launch.test.ts +114 -0
  47. package/test/extension-package.test.ts +27 -0
  48. package/test/extension-routes.test.ts +116 -0
  49. package/test/netlist-erc.test.ts +90 -0
  50. package/test/node-runtime.test.ts +65 -0
  51. package/test/schematic-audit.test.ts +71 -0
  52. package/test/seams.test.ts +164 -0
  53. package/test/skills.test.ts +68 -0
package/lib/bridge.mjs ADDED
@@ -0,0 +1,4179 @@
1
+ // src/bridge/index.ts
2
+ import { createHash as createHash2 } from "node:crypto";
3
+ import { execFileSync, spawn } from "node:child_process";
4
+ import { existsSync, statSync } from "node:fs";
5
+ import { readFile } from "node:fs/promises";
6
+ import { mkdir, unlink, writeFile } from "node:fs/promises";
7
+ import { tmpdir } from "node:os";
8
+ import { basename, join } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { createServer } from "node:http";
11
+ import { createInterface } from "node:readline";
12
+
13
+ // src/bridge/eda-launch.ts
14
+ var EXECUTABLE_ENV_KEYS = ["DSH_EDA_EXECUTABLE", "JLCEDA_EXECUTABLE"];
15
+ var EXECUTABLE_NAMES = ["lceda-pro.exe", "lceda-pro", "LCEDA Pro"];
16
+ var PROJECT_EXTENSIONS = [".eprj2", ".eprj"];
17
+ var CN_PRO_EDITION = "\u5609\u7ACB\u521BEDA\u4E13\u4E1A\u7248";
18
+ var CLASSES = "Software\\Classes";
19
+ var INSTALL_SUFFIXES = [
20
+ "lceda-pro",
21
+ "Program Files\\lceda-pro",
22
+ "Program Files (x86)\\lceda-pro",
23
+ "Program Files\\" + CN_PRO_EDITION,
24
+ "Program Files (x86)\\" + CN_PRO_EDITION
25
+ ];
26
+ function trimSeparator(value) {
27
+ let end = value.length;
28
+ while (end > 0) {
29
+ const ch = value[end - 1];
30
+ if (ch !== "\\" && ch !== "/") break;
31
+ end -= 1;
32
+ }
33
+ return value.slice(0, end);
34
+ }
35
+ function trimLeadingSeparators(value) {
36
+ let start = 0;
37
+ while (start < value.length && (value[start] === "\\" || value[start] === "/")) start += 1;
38
+ return value.slice(start);
39
+ }
40
+ function joinPath(platform, ...parts) {
41
+ const separator = platform === "win32" ? "\\" : "/";
42
+ return parts.filter((part) => part !== "").map((part, index) => index === 0 ? part : trimLeadingSeparators(part)).join(separator);
43
+ }
44
+ function splitSegments(value) {
45
+ return value.split("\\").join("/").split("/").filter((part) => part !== "");
46
+ }
47
+ function parseExecutableFromCommand(command) {
48
+ const text = (command ?? "").trim();
49
+ if (text === "") return void 0;
50
+ if (text.startsWith('"')) {
51
+ const end2 = text.indexOf('"', 1);
52
+ if (end2 === -1) return void 0;
53
+ const quoted = text.slice(1, end2).trim();
54
+ return quoted === "" ? void 0 : quoted;
55
+ }
56
+ const space = text.indexOf(" ");
57
+ const tab = text.indexOf(String.fromCharCode(9));
58
+ const stops = [space, tab].filter((index) => index > 0);
59
+ const end = stops.length === 0 ? text.length : Math.min(...stops);
60
+ const first = text.slice(0, end).trim();
61
+ return first === "" ? void 0 : first;
62
+ }
63
+ function decodeRegistryOutput(raw) {
64
+ const utf8 = new TextDecoder("utf-8").decode(raw);
65
+ if (!utf8.includes(String.fromCharCode(65533))) return utf8;
66
+ try {
67
+ return new TextDecoder("gbk").decode(raw);
68
+ } catch {
69
+ return utf8;
70
+ }
71
+ }
72
+ function parseRegStringValue(output) {
73
+ for (const raw of (output ?? "").split(String.fromCharCode(10))) {
74
+ const line = raw.trim();
75
+ const index = line.toUpperCase().indexOf("REG_SZ");
76
+ if (index === -1) continue;
77
+ const value = line.slice(index + "REG_SZ".length).trim();
78
+ if (value === "" || value.startsWith("(")) continue;
79
+ return value;
80
+ }
81
+ return void 0;
82
+ }
83
+ function parseRegValueNames(output) {
84
+ const names = [];
85
+ for (const raw of (output ?? "").split(String.fromCharCode(10))) {
86
+ const line = raw.trim();
87
+ const marker = line.indexOf("REG_");
88
+ if (marker <= 0) continue;
89
+ const name = line.slice(0, marker).trim();
90
+ if (name !== "" && !name.startsWith("HKEY")) names.push(name);
91
+ }
92
+ return names;
93
+ }
94
+ function firstExisting(probe, candidates) {
95
+ for (const candidate of candidates) {
96
+ if (candidate !== "" && probe.exists(candidate)) return candidate;
97
+ }
98
+ return void 0;
99
+ }
100
+ function envCandidates(probe) {
101
+ const env = probe.env;
102
+ const roots = [
103
+ env.ProgramFiles,
104
+ env["ProgramFiles(x86)"],
105
+ env.LOCALAPPDATA === void 0 ? void 0 : joinPath(probe.platform, env.LOCALAPPDATA, "Programs"),
106
+ env.APPDATA === void 0 ? void 0 : joinPath(probe.platform, env.APPDATA, "Programs"),
107
+ env.SystemDrive,
108
+ env.USERPROFILE,
109
+ env.HOME
110
+ ].filter((root) => typeof root === "string" && root !== "");
111
+ const candidates = [];
112
+ for (const root of roots) {
113
+ for (const suffix of INSTALL_SUFFIXES) {
114
+ for (const name of EXECUTABLE_NAMES) {
115
+ candidates.push(joinPath(probe.platform, trimSeparator(root), ...splitSegments(suffix), name));
116
+ }
117
+ }
118
+ }
119
+ return candidates;
120
+ }
121
+ function pathCandidates(probe) {
122
+ const raw = probe.env.PATH ?? probe.env.Path ?? "";
123
+ const separator = probe.platform === "win32" ? ";" : ":";
124
+ return raw.split(separator).filter((dir) => dir.trim() !== "").flatMap((dir) => EXECUTABLE_NAMES.map((name) => joinPath(probe.platform, trimSeparator(dir), name)));
125
+ }
126
+ function registryCandidates(probe) {
127
+ if (probe.platform !== "win32") return [];
128
+ const found = [];
129
+ for (const hive of ["HKCU", "HKLM"]) {
130
+ for (const extension of PROJECT_EXTENSIONS) {
131
+ const base = hive + "\\" + CLASSES + "\\" + extension;
132
+ const defaults = [parseRegStringValue(probe.registryQuery(base, "")), parseRegStringValue(probe.registryQuery(base))];
133
+ const progids = [
134
+ ...defaults.filter((value) => value !== void 0),
135
+ ...parseRegValueNames(probe.registryQuery(base + "\\OpenWithProgids"))
136
+ ];
137
+ for (const progid of progids) {
138
+ if (progid.startsWith("Applications\\")) continue;
139
+ const command = parseRegStringValue(
140
+ probe.registryQuery(hive + "\\" + CLASSES + "\\" + progid + "\\shell\\open\\command")
141
+ );
142
+ const executable = parseExecutableFromCommand(command);
143
+ if (executable !== void 0) found.push(executable);
144
+ }
145
+ }
146
+ }
147
+ return found;
148
+ }
149
+ function resolveExecutable(probe, options = {}) {
150
+ const override = options.executable?.trim();
151
+ if (override !== void 0 && override !== "" && probe.exists(override)) {
152
+ return { executable: override, source: "config" };
153
+ }
154
+ for (const key of EXECUTABLE_ENV_KEYS) {
155
+ const value = probe.env[key]?.trim();
156
+ if (value !== void 0 && value !== "" && probe.exists(value)) return { executable: value, source: "env" };
157
+ }
158
+ const fromRegistry = firstExisting(probe, registryCandidates(probe));
159
+ if (fromRegistry !== void 0) return { executable: fromRegistry, source: "registry" };
160
+ const fromInstallDir = firstExisting(probe, envCandidates(probe));
161
+ if (fromInstallDir !== void 0) return { executable: fromInstallDir, source: "install-dir" };
162
+ const fromPath = firstExisting(probe, pathCandidates(probe));
163
+ if (fromPath !== void 0) return { executable: fromPath, source: "path" };
164
+ return void 0;
165
+ }
166
+ function buildLaunchArgs(platform, executable, project) {
167
+ const target = project?.trim();
168
+ const hasProject = target !== void 0 && target !== "";
169
+ if (platform === "darwin") {
170
+ return hasProject ? { command: "open", args: ["-a", executable, target] } : { command: "open", args: ["-a", executable] };
171
+ }
172
+ return hasProject ? { command: executable, args: [target] } : { command: executable, args: [] };
173
+ }
174
+ function buildLaunchScript(executable, project) {
175
+ const target = project?.trim();
176
+ const args = target === void 0 || target === "" ? "" : ' "' + target + '"';
177
+ return ["@echo off", 'start "" "' + executable + '"' + args, ""].join(String.fromCharCode(13, 10));
178
+ }
179
+
180
+ // src/bridge/design-intake.ts
181
+ var INTAKE_SECTIONS = [
182
+ {
183
+ id: "power",
184
+ title: "\u4F9B\u7535\u4E0E\u7535\u6D41",
185
+ questions: [
186
+ { id: "powerSource", question: "\u677F\u5B50\u600E\u4E48\u4F9B\u7535\uFF1F\uFF08USB-C / USB-A / DC \u5EA7 / \u7535\u6C60 / \u5916\u90E8\u7AEF\u5B50\uFF09", why: "\u51B3\u5B9A\u63A5\u53E3\u5668\u4EF6\u3001\u8FDE\u63A5\u5668\u671D\u5411\u548C ESD \u4FDD\u62A4", critical: true, options: ["USB-C", "USB-A", "DC \u5EA7", "\u9502\u7535\u6C60", "\u5916\u90E8\u7AEF\u5B50", "\u591A\u79CD"] },
187
+ { id: "inputVoltage", question: "\u8F93\u5165\u7535\u538B\u8303\u56F4\u4E0E\u6700\u5927\u7535\u6D41\u662F\u591A\u5C11\uFF1F", why: "\u51B3\u5B9A\u7A33\u538B\u65B9\u6848\u3001\u7EBF\u5BBD\u3001\u94DC\u539A\u4E0E\u6563\u70ED", critical: true, fallback: "5 V / < 500 mA" },
188
+ { id: "railNeeds", question: "\u9700\u8981\u54EA\u4E9B\u7535\u6E90\u8F68\uFF083V3 / 5V / 1V8 / \u6A21\u62DF\u8F68\uFF09\uFF1F\u5404\u81EA\u8D1F\u8F7D\u591A\u5927\uFF1F", why: "\u51B3\u5B9A LDO \u8FD8\u662F DC-DC\u3001\u53BB\u8026\u6570\u91CF", critical: true },
189
+ { id: "battery", question: "\u662F\u5426\u9700\u8981\u7535\u6C60\u5145\u7535/\u5207\u6362\uFF1F", why: "\u5145\u7535 IC \u4E0E\u8DEF\u5F84\u7BA1\u7406\u4F1A\u6539\u53D8\u5E03\u5C40", critical: false, fallback: "\u4E0D\u9700\u8981" }
190
+ ]
191
+ },
192
+ {
193
+ id: "core",
194
+ title: "\u4E3B\u63A7\u4E0E\u56FA\u4EF6\u7EA6\u675F",
195
+ questions: [
196
+ { id: "mcu", question: "\u4E3B\u63A7\u578B\u53F7\uFF08\u6216\u5FC5\u987B\u517C\u5BB9\u7684\u7CFB\u5217\uFF09\uFF1F", why: "\u5F15\u811A\u3001\u65F6\u949F\u3001\u5C01\u88C5\u51B3\u5B9A\u5E03\u5C40\u4E0E\u8D70\u7EBF", critical: true },
197
+ { id: "clock", question: "\u65F6\u949F\u6765\u6E90\uFF1A\u5185\u90E8 RC / \u5916\u90E8\u6676\u632F\uFF08\u9891\u7387\uFF09\uFF1F", why: "\u6676\u632F\u8981\u8D34\u811A\u3001\u8D1F\u8F7D\u7535\u5BB9\u8981\u914D\u3001\u4E0B\u65B9\u7981\u94FA\u94DC", critical: true, options: ["\u5185\u90E8 RC", "8 MHz \u6676\u632F", "16 MHz \u6676\u632F", "32.768 kHz", "\u5176\u5B83"] },
198
+ { id: "programming", question: "\u70E7\u5199/\u8C03\u8BD5\u63A5\u53E3\uFF08SWD / JTAG / USB DFU / \u4E32\u53E3\uFF09\uFF1F", why: "\u51B3\u5B9A\u6392\u9488\u4E0E USB \u6570\u636E\u7EBF", critical: true, options: ["SWD 4 \u7EBF", "SWD 2 \u7EBF", "JTAG", "USB DFU", "\u4E32\u53E3 ISP", "\u4E0D\u9700\u8981"] },
199
+ { id: "boot", question: "\u542F\u52A8\u65B9\u5F0F\u662F\u5426\u9700\u8981\u53EF\u5207\u6362\uFF08BOOT0 \u8DF3\u7EBF/\u6309\u952E\uFF09\uFF1F", why: "\u51B3\u5B9A\u4E0B\u62C9\u7535\u963B\u4E0E\u8DF3\u7EBF\u6392\u9488", critical: false, fallback: "\u56FA\u5B9A\u4ECE Flash \u542F\u52A8\uFF0CBOOT0 \u4E0B\u62C9" }
200
+ ]
201
+ },
202
+ {
203
+ id: "io",
204
+ title: "\u63A5\u53E3\u4E0E\u5916\u8BBE",
205
+ questions: [
206
+ { id: "interfaces", question: "\u9700\u8981\u54EA\u4E9B\u5BF9\u5916\u63A5\u53E3\uFF1F\uFF08USB / UART / I2C / SPI / CAN / \u4EE5\u592A\u7F51 / \u663E\u793A\u5C4F / \u4F20\u611F\u5668\uFF09", why: "\u6BCF\u4E00\u79CD\u90FD\u5E26\u8FDE\u63A5\u5668\u3001\u4FDD\u62A4\u5668\u4EF6\u548C\u5E03\u7EBF\u7EA6\u675F", critical: true },
207
+ { id: "isolation", question: "\u662F\u5426\u6709\u9694\u79BB/\u9AD8\u538B/\u5F3A\u7535\u90E8\u5206\uFF1F\u5B89\u5168\u8DDD\u79BB\u8981\u6C42\uFF1F", why: "\u9700\u8981\u722C\u7535\u95F4\u8DDD\u3001\u5F00\u69FD\u3001\u9694\u79BB\u5668\u4EF6", critical: true, options: ["\u65E0", "\u6709\u4F4E\u538B\u9694\u79BB", "\u6709\u5E02\u7535/\u9AD8\u538B"] },
208
+ { id: "esd", question: "\u5BF9\u5916\u63A5\u53E3\u662F\u5426\u8981 ESD/\u6D6A\u6D8C\u4FDD\u62A4\uFF1F", why: "USBLC6 \u4E4B\u7C7B\u5668\u4EF6\u7684\u5730\u5FC5\u987B\u5355\u72EC\u56DE\u6D41", critical: false, fallback: "\u5BF9\u5916\u63A5\u53E3\u90FD\u52A0 ESD" }
209
+ ]
210
+ },
211
+ {
212
+ id: "mechanical",
213
+ title: "\u673A\u68B0\u4E0E\u7ED3\u6784",
214
+ questions: [
215
+ { id: "size", question: "\u677F\u6846\u5C3A\u5BF8\u9650\u5236\uFF08\u957F\xD7\u5BBD mm\uFF09\u4E0E\u5F62\u72B6\uFF08\u77E9\u5F62/\u5E26\u7F3A\u53E3/\u5706\u89D2\u534A\u5F84\uFF09\uFF1F", why: "\u51B3\u5B9A\u5E03\u5C40\u5BC6\u5EA6\u4E0E\u8FDE\u63A5\u5668\u4F4D\u7F6E", critical: true },
216
+ { id: "mounting", question: "\u5B9A\u4F4D\u5B54\u6570\u91CF\u3001\u5B54\u5F84\u3001\u4F4D\u7F6E\uFF1F", why: "\u975E\u91D1\u5C5E\u5316\u5B54\u8981\u907F\u5F00\u8D70\u7EBF\u4E0E\u5668\u4EF6", critical: true, fallback: "4 \u4E2A \u03C63.2 mm\uFF0C\u56DB\u89D2\u5185\u7F29 3 mm" },
217
+ { id: "connectorFacing", question: "\u5404\u8FDE\u63A5\u5668\u7684\u671D\u5411/\u4F4D\u7F6E\uFF08USB \u671D\u677F\u8FB9\u54EA\u4E00\u4FA7\uFF09\uFF1F", why: "\u63D2\u53E3\u5FC5\u987B\u671D\u677F\u5916\uFF0C\u5426\u5219\u88C5\u4E0D\u8FDB\u5916\u58F3", critical: true },
218
+ { id: "enclosure", question: "\u662F\u5426\u6709\u5916\u58F3/\u88C5\u914D\u9650\u5236\uFF08\u9AD8\u5EA6\u3001\u5E72\u6D89\u533A\uFF09\uFF1F", why: "\u9650\u5236\u5668\u4EF6\u9AD8\u5EA6\u4E0E\u6446\u653E", critical: false, fallback: "\u65E0\u5916\u58F3\uFF0C\u4EC5\u88F8\u677F" }
219
+ ]
220
+ },
221
+ {
222
+ id: "process",
223
+ title: "\u5DE5\u827A\u4E0E\u5236\u9020",
224
+ questions: [
225
+ { id: "layers", question: "\u5C42\u6570\uFF082 \u5C42 / 4 \u5C42\uFF09\uFF1F", why: "\u51B3\u5B9A\u5730\u5E73\u9762\u3001\u963B\u6297\u4E0E\u5E03\u7EBF\u7B56\u7565", critical: true, options: ["2 \u5C42", "4 \u5C42"] },
226
+ { id: "copper", question: "\u94DC\u539A\uFF081 oz / 2 oz\uFF09\uFF1F", why: "\u5F71\u54CD\u8F7D\u6D41\u4E0E\u6700\u5C0F\u7EBF\u5BBD", critical: false, fallback: "1 oz" },
227
+ { id: "assembly", question: "\u8D34\u7247\u8FD8\u662F\u624B\u710A\uFF1F\u53CC\u9762\u8D34\u7247\uFF1F", why: "\u51B3\u5B9A\u5C01\u88C5\u9009\u578B\u3001\u4E1D\u5370\u6807\u6CE8\u4E0E\u710A\u76D8\u5916\u6269", critical: true, options: ["\u5355\u9762\u8D34\u7247", "\u53CC\u9762\u8D34\u7247", "\u624B\u5DE5\u710A\u63A5"] },
228
+ { id: "quantity", question: "\u6253\u6837\u6570\u91CF\u4E0E\u9884\u7B97\u533A\u95F4\uFF1F", why: "\u5F71\u54CD\u5DE5\u827A\u9009\u62E9\uFF08\u62FC\u677F\u3001\u963B\u6297\u3001\u6C89\u91D1\uFF09", critical: false, fallback: "5 \u7247\u6253\u6837" }
229
+ ]
230
+ },
231
+ {
232
+ id: "delivery",
233
+ title: "\u4EA4\u4ED8\u4E0E\u9A8C\u8BC1",
234
+ questions: [
235
+ { id: "deliverable", question: "\u8981\u4EA4\u4ED8\u5230\u4EC0\u4E48\u7A0B\u5EA6\uFF1F\uFF08\u539F\u7406\u56FE / PCB / Gerber+BOM+\u5750\u6807 / \u5168\u6D41\u7A0B\u53EF\u4E0B\u5355\uFF09", why: "\u51B3\u5B9A\u9A8C\u8BC1\u6DF1\u5EA6\u4E0E\u6587\u6863\u91CF", critical: true, options: ["\u4EC5\u539F\u7406\u56FE", "\u539F\u7406\u56FE+PCB", "\u53EF\u4E0B\u5355\uFF08Gerber+BOM+\u5750\u6807\uFF09"] },
236
+ { id: "validation", question: "\u8981\u54EA\u4E9B\u9A8C\u8BC1\uFF1F\uFF08DRC / \u7F51\u8868 ERC / \u8BBE\u8BA1\u5BA1\u8BA1 / \u5B9E\u673A\u70B9\u4EAE\uFF09", why: "\u51B3\u5B9A\u4EA4\u4ED8\u524D\u5FC5\u987B\u8DD1\u7684\u68C0\u67E5", critical: false, fallback: "DRC + \u7F51\u8868 ERC + \u8BBE\u8BA1\u5BA1\u8BA1" },
237
+ { id: "constraints", question: "\u8FD8\u6709\u5176\u5B83\u786C\u7EA6\u675F\uFF08\u7981\u7528\u7684\u5668\u4EF6\u3001\u5FC5\u987B\u590D\u7528\u5DF2\u6709\u5DE5\u7A0B\u3001\u8BA4\u8BC1\u8981\u6C42\uFF09\uFF1F", why: "\u907F\u514D\u8FD4\u5DE5", critical: false }
238
+ ]
239
+ }
240
+ ];
241
+ function buildIntake(answers) {
242
+ const provided = answers !== null && typeof answers === "object" ? answers : {};
243
+ const known = /* @__PURE__ */ new Set();
244
+ for (const section of INTAKE_SECTIONS) for (const question of section.questions) known.add(question.id);
245
+ const brief = {};
246
+ const answered = [];
247
+ const unknownAnswerKeys = [];
248
+ for (const [key, value] of Object.entries(provided)) {
249
+ if (!known.has(key)) {
250
+ unknownAnswerKeys.push(key);
251
+ continue;
252
+ }
253
+ const text = String(value ?? "").trim();
254
+ if (text === "") continue;
255
+ brief[key] = text;
256
+ answered.push(key);
257
+ }
258
+ const missingCritical = [];
259
+ let criticalCount = 0;
260
+ let questionCount = 0;
261
+ for (const section of INTAKE_SECTIONS) {
262
+ for (const question of section.questions) {
263
+ questionCount += 1;
264
+ if (!question.critical) continue;
265
+ criticalCount += 1;
266
+ if (brief[question.id] === void 0) missingCritical.push(question.id);
267
+ }
268
+ }
269
+ return {
270
+ sections: INTAKE_SECTIONS,
271
+ questionCount,
272
+ criticalCount,
273
+ answered,
274
+ missingCritical,
275
+ unknownAnswerKeys,
276
+ ready: missingCritical.length === 0,
277
+ brief
278
+ };
279
+ }
280
+
281
+ // src/bridge/schematic-audit.ts
282
+ var EPS = 0.5;
283
+ function intersects(a, b) {
284
+ return a.left < b.right - EPS && b.left < a.right - EPS && a.bottom < b.top - EPS && b.bottom < a.top - EPS;
285
+ }
286
+ function area(b) {
287
+ return Math.max(0, b.right - b.left) * Math.max(0, b.top - b.bottom);
288
+ }
289
+ function inside(inner, outer) {
290
+ return inner.left >= outer.left - EPS && inner.right <= outer.right + EPS && inner.bottom >= outer.bottom - EPS && inner.top <= outer.top + EPS;
291
+ }
292
+ function auditSchematicGeometry(input) {
293
+ const grid = input.grid === void 0 ? 10 : input.grid;
294
+ const checks = [];
295
+ const add = (id, status, message, details) => {
296
+ checks.push(details && details.length > 0 ? { id, status, message, details } : { id, status, message });
297
+ };
298
+ const withBounds = input.components.filter((component) => component.bounds !== void 0);
299
+ if (input.components.length === 0) {
300
+ add("sheet", "skip", "no component on the active schematic page");
301
+ return { ok: false, counts: { pass: 0, fail: 0, warn: 0, skip: 1 }, componentCount: 0, checks };
302
+ }
303
+ add("sheet", "pass", input.components.length + " component(s) read from the active page, " + withBounds.length + " with bounds");
304
+ const outside = withBounds.filter((component) => !inside(component.bounds, input.frame)).map((component) => component.designator);
305
+ add(
306
+ "outside-frame",
307
+ outside.length === 0 ? "pass" : "fail",
308
+ outside.length === 0 ? "every symbol sits inside the frame" : outside.length + " symbol(s) stick out of the frame",
309
+ outside.slice(0, 20)
310
+ );
311
+ if (input.titleBlock === void 0) {
312
+ add("title-block", "skip", "no title block range supplied");
313
+ } else {
314
+ const block = input.titleBlock;
315
+ const intruding = withBounds.filter((component) => intersects(component.bounds, block)).map((component) => component.designator);
316
+ add(
317
+ "title-block",
318
+ intruding.length === 0 ? "pass" : "fail",
319
+ intruding.length === 0 ? "nothing overlaps the title block" : intruding.length + " symbol(s) overlap the title block",
320
+ intruding.slice(0, 20)
321
+ );
322
+ }
323
+ const overlaps = [];
324
+ for (let i = 0; i < withBounds.length; i++) {
325
+ for (let j = i + 1; j < withBounds.length; j++) {
326
+ const a = withBounds[i];
327
+ const b = withBounds[j];
328
+ if (!intersects(a.bounds, b.bounds)) continue;
329
+ const sharedW = Math.min(a.bounds.right, b.bounds.right) - Math.max(a.bounds.left, b.bounds.left);
330
+ const sharedH = Math.min(a.bounds.top, b.bounds.top) - Math.max(a.bounds.bottom, b.bounds.bottom);
331
+ const shared = Math.max(0, sharedW) * Math.max(0, sharedH);
332
+ const smaller = Math.min(area(a.bounds), area(b.bounds));
333
+ if (smaller > 0 && shared / smaller > 0.08) overlaps.push(a.designator + " x " + b.designator);
334
+ }
335
+ }
336
+ add(
337
+ "symbol-overlap",
338
+ overlaps.length === 0 ? "pass" : "fail",
339
+ overlaps.length === 0 ? "no two symbols overlap" : overlaps.length + " overlapping symbol pair(s)",
340
+ overlaps.slice(0, 20)
341
+ );
342
+ const offGrid = input.components.filter((component) => Math.abs(component.x / grid - Math.round(component.x / grid)) > 0.01 || Math.abs(component.y / grid - Math.round(component.y / grid)) > 0.01).map((component) => component.designator + " @" + component.x + "," + component.y);
343
+ add(
344
+ "grid",
345
+ offGrid.length === 0 ? "pass" : "warn",
346
+ offGrid.length === 0 ? "every symbol sits on the " + grid + "-unit grid" : offGrid.length + " symbol(s) are off the " + grid + "-unit grid",
347
+ offGrid.slice(0, 20)
348
+ );
349
+ const labels = input.labels ?? [];
350
+ if (labels.length === 0) {
351
+ add("label-overlap", "skip", "no label anchors supplied");
352
+ } else {
353
+ const crowded = labels.filter((label) => withBounds.some((component) => label.x > component.bounds.left && label.x < component.bounds.right && label.y > component.bounds.bottom && label.y < component.bounds.top)).map((label) => label.text + " @" + label.x + "," + label.y);
354
+ add(
355
+ "label-overlap",
356
+ crowded.length === 0 ? "pass" : "warn",
357
+ crowded.length === 0 ? "no label anchor lands inside a symbol" : crowded.length + " label(s) anchored inside a symbol body",
358
+ crowded.slice(0, 20)
359
+ );
360
+ }
361
+ const counts = { pass: 0, fail: 0, warn: 0, skip: 0 };
362
+ for (const check of checks) counts[check.status] += 1;
363
+ return { ok: counts.fail === 0, counts, componentCount: input.components.length, checks };
364
+ }
365
+
366
+ // src/bridge/netlist-erc.ts
367
+ var POWER_NET = /^(?:\+?\d+V\d*|V?(?:CC|DD|BAT|IN|BUS|SYS|MOTOR)|AVDD|DVDD|VBUS|VUSB|VBAT|3V3|5V|12V)$/i;
368
+ var GROUND_NET = /^(?:GND|AGND|DGND|PGND|GNDA|GNDD|VSS|0V|EARTH)$/i;
369
+ var USD_DP = /(?:^|_)(?:USB_?D\+?P|D\+|USB_?DP|DP)$/i;
370
+ var USD_DM = /(?:^|_)(?:USB_?D-?M|D-|USB_?DM|DM)$/i;
371
+ var CRYSTAL_HINT = /crystal|xtal|osc|谐振|晶振|5032|3225/i;
372
+ var MCU_PART = /STM32|GD32|ATmega|ATMEGA|ESP32|ESP8266|CH32|HC32|MM32|APM32|N76|PIC\d|RP2040|MSP430/i;
373
+ function normNet(value) {
374
+ return typeof value === "string" ? value.trim() : "";
375
+ }
376
+ function parseNetlist(raw) {
377
+ const source = raw && typeof raw === "object" && raw.components ? raw : {};
378
+ const map = source.components ?? {};
379
+ const components = [];
380
+ const pins = [];
381
+ for (const key of Object.keys(map)) {
382
+ const entry = map[key] ?? {};
383
+ const props = entry.props ?? {};
384
+ const designator = String(props.Designator ?? props.designator ?? key);
385
+ const pinInfoMap = entry.pinInfoMap ?? {};
386
+ const own = [];
387
+ for (const pinKey of Object.keys(pinInfoMap)) {
388
+ const pin = pinInfoMap[pinKey] ?? {};
389
+ const number = String(pin.number ?? pin.props?.["Pin Number"] ?? pinKey);
390
+ const name = String(pin.name ?? "");
391
+ const net = normNet(pin.net);
392
+ own.push({ number, name, net });
393
+ pins.push({ designator, number, name, net });
394
+ }
395
+ const flag = (value, fallback) => {
396
+ if (value === void 0 || value === null || value === "") return fallback;
397
+ return !/^(?:no|false|0)$/i.test(String(value).trim());
398
+ };
399
+ components.push({
400
+ designator,
401
+ part: String(props["Manufacturer Part"] ?? props.Device ?? ""),
402
+ footprint: String(props.Footprint ?? ""),
403
+ supplierPart: String(props["Supplier Part"] ?? props["LCSC Part"] ?? ""),
404
+ addIntoBom: flag(props["Add into BOM"], true),
405
+ convertToPcb: flag(props["Convert to PCB"], true),
406
+ pins: own
407
+ });
408
+ }
409
+ return { components, pins };
410
+ }
411
+ function netsOf(pins) {
412
+ const nets = /* @__PURE__ */ new Map();
413
+ for (const pin of pins) {
414
+ if (pin.net === "") continue;
415
+ const list = nets.get(pin.net);
416
+ if (list) list.push(pin);
417
+ else nets.set(pin.net, [pin]);
418
+ }
419
+ return nets;
420
+ }
421
+ function capsBridging(net, groundNet, components) {
422
+ let count = 0;
423
+ for (const component of components) {
424
+ if (!/^C\d*$/i.test(component.designator)) continue;
425
+ const onNet = component.pins.some((pin) => pin.net === net);
426
+ const onGround = component.pins.some((pin) => pin.net === groundNet);
427
+ if (onNet && onGround) count++;
428
+ }
429
+ return count;
430
+ }
431
+ function resistorsOn(net, components, otherNet) {
432
+ const found = [];
433
+ for (const component of components) {
434
+ if (!/^R\d*$/i.test(component.designator)) continue;
435
+ const onNet = component.pins.some((pin) => pin.net === net);
436
+ if (!onNet) continue;
437
+ if (otherNet === void 0) {
438
+ found.push(component.designator);
439
+ continue;
440
+ }
441
+ const others = component.pins.filter((pin) => pin.net !== net).map((pin) => pin.net);
442
+ if (others.some((name) => name === otherNet)) found.push(component.designator);
443
+ }
444
+ return found;
445
+ }
446
+ function runNetlistErc(rawNetlist) {
447
+ const { components, pins } = parseNetlist(rawNetlist);
448
+ const nets = netsOf(pins);
449
+ const checks = [];
450
+ const add = (id, status, message, details) => {
451
+ checks.push(details && details.length > 0 ? { id, status, message, details } : { id, status, message });
452
+ };
453
+ if (components.length === 0) {
454
+ add("netlist", "skip", "netlist has no components: open a schematic page first (eda_open_document)");
455
+ return { ok: false, counts: { pass: 0, fail: 0, warn: 0, skip: 1 }, componentCount: 0, netCount: 0, checks };
456
+ }
457
+ const seen = /* @__PURE__ */ new Map();
458
+ for (const component of components) seen.set(component.designator, (seen.get(component.designator) ?? 0) + 1);
459
+ const duplicates = [...seen.entries()].filter(([, n]) => n > 1).map(([name, n]) => name + " x" + n);
460
+ add(
461
+ "duplicate-designator",
462
+ duplicates.length === 0 ? "pass" : "fail",
463
+ duplicates.length === 0 ? "every designator is unique" : duplicates.length + " duplicated designator(s)",
464
+ duplicates
465
+ );
466
+ const floating = pins.filter((pin) => pin.net === "").map((pin) => pin.designator + "." + pin.number + (pin.name ? " (" + pin.name + ")" : ""));
467
+ add(
468
+ "unconnected-pin",
469
+ floating.length === 0 ? "pass" : "warn",
470
+ floating.length === 0 ? "every pin is on a net" : floating.length + " pin(s) are on no net (mark unused pins with eda_set_no_connect or wire them)",
471
+ floating.slice(0, 25)
472
+ );
473
+ const dangling = [...nets.entries()].filter(([, list]) => list.length < 2).map(([name, list]) => name + " <- " + list.map((p) => p.designator + "." + p.number).join(","));
474
+ add(
475
+ "dangling-net",
476
+ dangling.length === 0 ? "pass" : "fail",
477
+ dangling.length === 0 ? "every net has at least two endpoints" : dangling.length + " net(s) have a single endpoint",
478
+ dangling.slice(0, 25)
479
+ );
480
+ const groundNet = [...nets.keys()].find((name) => GROUND_NET.test(name)) ?? "";
481
+ add(
482
+ "ground-net",
483
+ groundNet === "" ? "fail" : nets.get(groundNet).length >= 3 ? "pass" : "warn",
484
+ groundNet === "" ? "no ground net (GND/VSS/AGND) found" : "ground net " + groundNet + " has " + nets.get(groundNet).length + " pins"
485
+ );
486
+ const shorted = components.filter((component) => {
487
+ const names = new Set(component.pins.map((pin) => pin.net).filter((name) => name !== ""));
488
+ return component.pins.length >= 2 && names.size === 1;
489
+ }).map((component) => component.designator);
490
+ add(
491
+ "shorted-component",
492
+ shorted.length === 0 ? "pass" : "fail",
493
+ shorted.length === 0 ? "no component has all pins on one net" : shorted.length + " component(s) have every pin on one net",
494
+ shorted
495
+ );
496
+ const powerNets = [...nets.keys()].filter((name) => POWER_NET.test(name) && !GROUND_NET.test(name));
497
+ if (powerNets.length === 0) {
498
+ add("power-rail", "warn", "no power net recognised (3V3/5V/VCC/VDD/VBAT)");
499
+ } else {
500
+ const icPowerPins = pins.filter((pin) => /^(?:VDD|VCC|VBAT|VDDA|AVDD|DVDD|VIN|V\+)/i.test(pin.name) && !GROUND_NET.test(pin.net));
501
+ const unpowered = icPowerPins.filter((pin) => pin.net === "").map((pin) => pin.designator + "." + pin.number);
502
+ add(
503
+ "power-rail",
504
+ unpowered.length === 0 ? "pass" : "fail",
505
+ unpowered.length === 0 ? powerNets.length + " power net(s) (" + powerNets.slice(0, 4).join(", ") + ") feed " + icPowerPins.length + " IC power pin(s)" : unpowered.length + " IC power pin(s) are not on any net",
506
+ unpowered
507
+ );
508
+ if (groundNet !== "") {
509
+ const thin = powerNets.filter((name) => capsBridging(name, groundNet, components) === 0);
510
+ add(
511
+ "decoupling",
512
+ thin.length === 0 ? "pass" : "warn",
513
+ thin.length === 0 ? "every power rail has a capacitor to " + groundNet : thin.length + " power rail(s) have no capacitor to " + groundNet + " (decoupling missing)",
514
+ thin
515
+ );
516
+ } else {
517
+ add("decoupling", "skip", "no ground net, decoupling cannot be judged");
518
+ }
519
+ }
520
+ const dp = [...nets.keys()].filter((name) => USD_DP.test(name));
521
+ const dm = [...nets.keys()].filter((name) => USD_DM.test(name));
522
+ if (dp.length === 0 && dm.length === 0) {
523
+ add("usb-data-pair", "skip", "no USB D+/D- net, skipped");
524
+ } else {
525
+ const missing = dp.length === 0 ? "D+ net missing" : dm.length === 0 ? "D- net missing" : "";
526
+ const halves = dp.length === 0 || dm.length === 0 ? ["D+/D- are not a pair: " + (dp.concat(dm).join(", ") || "none")] : [];
527
+ add(
528
+ "usb-data-pair",
529
+ missing === "" ? "pass" : "fail",
530
+ missing === "" ? "D+ (" + dp.join(",") + ") and D- (" + dm.join(",") + ") both exist" : missing,
531
+ halves
532
+ );
533
+ }
534
+ const crystals = components.filter((component) => /^[XY]\d*$/i.test(component.designator) || CRYSTAL_HINT.test(component.part) || CRYSTAL_HINT.test(component.footprint));
535
+ const realCrystals = crystals.filter((component) => {
536
+ const names = new Set(component.pins.map((pin) => pin.net).filter((name) => name !== ""));
537
+ return component.pins.length === 2 || component.pins.length >= 2 && names.size === 2;
538
+ });
539
+ if (realCrystals.length === 0) {
540
+ add("crystal", "skip", "no crystal found, skipped (an RC oscillator design is fine)");
541
+ } else if (groundNet === "") {
542
+ add("crystal", "skip", "crystal present but no ground net, load caps cannot be judged");
543
+ } else {
544
+ const problems = [];
545
+ for (const crystal of realCrystals) {
546
+ const own = crystal.pins.map((pin) => pin.net).filter((name) => name !== "");
547
+ if (new Set(own).size < 2) problems.push(crystal.designator + ": both pins are on " + (own[0] ?? "no net"));
548
+ for (const net of new Set(own)) {
549
+ if (capsBridging(net, groundNet, components) === 0) problems.push(crystal.designator + ": " + net + " has no load capacitor to " + groundNet);
550
+ }
551
+ const touchesMcu = pins.some((pin) => own.includes(pin.net) && MCU_PART.test(components.find((c) => c.designator === pin.designator)?.part ?? ""));
552
+ if (!touchesMcu) problems.push(crystal.designator + ": neither pin reaches an MCU clock pin");
553
+ }
554
+ add(
555
+ "crystal",
556
+ problems.length === 0 ? "pass" : "warn",
557
+ problems.length === 0 ? realCrystals.length + " crystal(s) have two nets, load caps and an MCU connection" : problems.length + " crystal problem(s)",
558
+ problems
559
+ );
560
+ }
561
+ const resetNet = [...nets.keys()].find((name) => /^(?:N?RST|RESET|RESET_N|MCLR)$/i.test(name));
562
+ if (resetNet === void 0) {
563
+ add("reset", "skip", "no reset net, skipped");
564
+ } else if (groundNet === "") {
565
+ add("reset", "skip", "reset net present but no ground net");
566
+ } else {
567
+ const cap = capsBridging(resetNet, groundNet, components);
568
+ const pullup = resistorsOn(resetNet, components).length;
569
+ const problems = [];
570
+ if (cap === 0) problems.push(resetNet + " has no capacitor to " + groundNet);
571
+ if (pullup === 0) problems.push(resetNet + " has no series/pull resistor");
572
+ add(
573
+ "reset",
574
+ problems.length === 0 ? "pass" : "warn",
575
+ problems.length === 0 ? resetNet + " has a capacitor and a resistor" : problems.length + " reset problem(s)",
576
+ problems
577
+ );
578
+ }
579
+ const bootNet = [...nets.keys()].find((name) => /^BOOT\d$/i.test(name));
580
+ if (bootNet === void 0) {
581
+ add("boot", "skip", "no BOOT0 net, skipped");
582
+ } else {
583
+ const resistors = resistorsOn(bootNet, components);
584
+ add(
585
+ "boot",
586
+ resistors.length > 0 ? "pass" : "warn",
587
+ resistors.length > 0 ? bootNet + " has resistor(s): " + resistors.join(",") : bootNet + " has no pull resistor (floating boot pin)"
588
+ );
589
+ }
590
+ const ccPins = pins.filter((pin) => /^CC[12]$/i.test(pin.name));
591
+ if (ccPins.length === 0) {
592
+ add("type-c-cc", "skip", "no CC1/CC2 pins, skipped");
593
+ } else {
594
+ const missing = ccPins.filter((pin) => pin.net === "" || groundNet !== "" && resistorsOn(pin.net, components, groundNet).length === 0).map((pin) => pin.designator + "." + pin.name + " on " + (pin.net || "<no net>") + " without a resistor to GND");
595
+ add(
596
+ "type-c-cc",
597
+ missing.length === 0 ? "pass" : "warn",
598
+ missing.length === 0 ? "CC1/CC2 each have a resistor to ground" : missing.length + " CC pin(s) lack a 5.1k pull-down",
599
+ missing
600
+ );
601
+ }
602
+ const missingSupplier = components.filter((component) => component.supplierPart.trim() === "").map((component) => component.designator + (component.part ? " (" + component.part + ")" : ""));
603
+ add(
604
+ "bom-part-number",
605
+ missingSupplier.length === 0 ? "pass" : "warn",
606
+ missingSupplier.length === 0 ? "every part carries a supplier part number" : missingSupplier.length + " part(s) have no supplier/LPSC part number (not orderable by number)",
607
+ missingSupplier.slice(0, 20)
608
+ );
609
+ const excluded = components.filter((component) => !component.convertToPcb).map((component) => component.designator);
610
+ add(
611
+ "pcb-conversion",
612
+ excluded.length === 0 ? "pass" : "warn",
613
+ excluded.length === 0 ? "every part is marked Convert to PCB" : excluded.length + " part(s) are excluded from the PCB conversion (they will be missing on the board)",
614
+ excluded.slice(0, 20)
615
+ );
616
+ const noFootprint = components.filter((component) => component.convertToPcb && component.footprint.trim() === "").map((component) => component.designator);
617
+ add(
618
+ "footprint",
619
+ noFootprint.length === 0 ? "pass" : "fail",
620
+ noFootprint.length === 0 ? "every PCB-bound part has a footprint" : noFootprint.length + " PCB-bound part(s) have no footprint and cannot be placed",
621
+ noFootprint.slice(0, 20)
622
+ );
623
+ const counts = { pass: 0, fail: 0, warn: 0, skip: 0 };
624
+ for (const check of checks) counts[check.status] += 1;
625
+ return { ok: counts.fail === 0, counts, componentCount: components.length, netCount: nets.size, checks };
626
+ }
627
+
628
+ // src/bridge/extension-package.ts
629
+ import { createHash } from "node:crypto";
630
+ function sha256Of(bytes) {
631
+ return createHash("sha256").update(bytes).digest("hex");
632
+ }
633
+ function extensionZipName(version) {
634
+ return "dsh-eda-bridge-extension-" + version + ".zip";
635
+ }
636
+ function extensionDownloadUrl(base, version) {
637
+ const normalised = base.endsWith("/") ? base : base + "/";
638
+ return new URL(extensionZipName(version), normalised).toString();
639
+ }
640
+ function compareDigest(expected, actual) {
641
+ if (typeof expected !== "string" || typeof actual !== "string") return "unverified";
642
+ const left = expected.trim().toLowerCase();
643
+ const right = actual.trim().toLowerCase();
644
+ if (left === "" || right === "") return "unverified";
645
+ return left === right ? "match" : "mismatch";
646
+ }
647
+
648
+ // src/bridge/design-rules.ts
649
+ var MIL_PER_MM = 39.37007874015748;
650
+ function milToMm(mil) {
651
+ return mil / MIL_PER_MM;
652
+ }
653
+ function roundToFiveHundredthsMm(mil) {
654
+ const mm = milToMm(mil);
655
+ return Math.round(mm / 0.05) * 0.05 * MIL_PER_MM;
656
+ }
657
+ function result(errors, warnings) {
658
+ return { ok: errors.length === 0, errors, warnings };
659
+ }
660
+ var NET_NAME_MAX_LENGTH = 255;
661
+ var NET_NAME_ALLOWED = /^[A-Za-z0-9_.+-]+$/;
662
+ function checkNetName(net) {
663
+ const errors = [];
664
+ const warnings = [];
665
+ if (net === "") errors.push("net name is empty");
666
+ if (net.length > NET_NAME_MAX_LENGTH) errors.push(`net name is longer than ${NET_NAME_MAX_LENGTH} characters`);
667
+ const autoGenerated = /^\$?\d+N\d+$/.test(net) || /^\$/.test(net);
668
+ if (net !== "" && !NET_NAME_ALLOWED.test(net) && !autoGenerated) {
669
+ errors.push(`net name "${net}" contains characters the JLCEDA backend cannot parse (allowed: letters, digits, "_", ".", "+", "-")`);
670
+ }
671
+ if (/[a-z]/.test(net)) warnings.push(`net name "${net}" is not uppercase; the official advice is uppercase letters, digits and "_" only`);
672
+ return { ...result(errors, warnings), net };
673
+ }
674
+ function assertNetName(net, tool) {
675
+ const check = checkNetName(net);
676
+ if (!check.ok) throw new Error(`${tool}: ${check.errors.join("; ")} (see docs/design-rules.md \xA72.1)`);
677
+ }
678
+ var TRACK_WIDTH_MIL = {
679
+ /** 0.15 mm — ordinary signals, also the free-prototyping lower bound. */
680
+ signal: 6,
681
+ /** 0.25 mm — device-to-decoupling branch power. */
682
+ branchPower: 10,
683
+ /** 0.4 mm — main power trunk. */
684
+ mainPower: 16,
685
+ /** 0.5 mm — more than ~500 mA. */
686
+ highCurrent: 20
687
+ };
688
+ var MIN_TRACK_WIDTH_MIL = TRACK_WIDTH_MIL.signal;
689
+ var GROUND_PATTERN = /^(?:A|D|P)?GND[A-Z0-9_]*$|^(?:VSS|EARTH|0V)/i;
690
+ var POWER_PATTERN = /^(?:VCC|VDD|VEE|VBAT|VIN|VOUT|VBUS|PWR|VSYS|VCORE|AVDD|DVDD|3V3|5V|12V|24V|1V8|1V2|2V5)/i;
691
+ function classifyNet(net) {
692
+ if (GROUND_PATTERN.test(net)) return "ground";
693
+ if (POWER_PATTERN.test(net)) return "power";
694
+ return "signal";
695
+ }
696
+ function suggestTrackWidthMil(net) {
697
+ const role = classifyNet(net);
698
+ if (role === "ground") return TRACK_WIDTH_MIL.mainPower;
699
+ if (role === "power") return TRACK_WIDTH_MIL.mainPower;
700
+ return TRACK_WIDTH_MIL.signal;
701
+ }
702
+ function checkTrackWidth(net, lineWidth, force = false) {
703
+ const errors = [];
704
+ const warnings = [];
705
+ const role = classifyNet(net);
706
+ const suggestedMil = suggestTrackWidthMil(net);
707
+ const widthMil = lineWidth === void 0 ? suggestedMil : lineWidth;
708
+ if (!Number.isFinite(widthMil) || widthMil <= 0) {
709
+ errors.push(`track width must be a positive number of mil (got ${String(lineWidth)})`);
710
+ } else if (widthMil < MIN_TRACK_WIDTH_MIL && !force) {
711
+ errors.push(`track width ${widthMil} mil is below the ${MIN_TRACK_WIDTH_MIL} mil (0.15 mm) design minimum; pass force:true to override`);
712
+ }
713
+ if (widthMil > 0 && widthMil < suggestedMil && Number.isFinite(widthMil) && !force) {
714
+ warnings.push(`track width ${widthMil} mil is below the ${suggestedMil} mil suggested for ${role} net "${net}"`);
715
+ }
716
+ const isTierValue = Object.values(TRACK_WIDTH_MIL).includes(widthMil) || widthMil === 15 || widthMil === 25 || widthMil === 12;
717
+ const stepRemainder = (() => {
718
+ const mm = milToMm(widthMil);
719
+ if (mm <= 0) return 0;
720
+ const nearest = Math.round(mm / 0.05) * 0.05;
721
+ return Math.abs(mm - nearest);
722
+ })();
723
+ if (widthMil > 0 && !isTierValue && stepRemainder > 0.01) {
724
+ warnings.push(`track width ${Math.round(widthMil * 100) / 100} mil (${milToMm(widthMil).toFixed(3)} mm) is not on a 0.05 mm step; ${Math.round(roundToFiveHundredthsMm(widthMil) * 100) / 100} mil aligns better with JLC parameters`);
725
+ }
726
+ return { ...result(errors, warnings), widthMil, role, suggestedMil };
727
+ }
728
+ var VIA_SIZES_MM = [
729
+ { hole: 0.2, pad: 0.4, role: "signal" },
730
+ { hole: 0.3, pad: 0.6, role: "power" },
731
+ { hole: 0.4, pad: 0.8, role: "highCurrent" }
732
+ ];
733
+ var VIA_HOLE_MIN_MM = 0.3;
734
+ var VIA_HOLE_ABSOLUTE_MIN_MM = 0.2;
735
+ var ANNULUS_MIN_MM = 0.2;
736
+ function checkVia(net, holeDiameterMil, diameterMil, force = false) {
737
+ const errors = [];
738
+ const warnings = [];
739
+ const holeMm = milToMm(holeDiameterMil);
740
+ const padMm = milToMm(diameterMil);
741
+ const ringMm = padMm - holeMm;
742
+ const annulusMm = ringMm / 2;
743
+ const role = classifyNet(net);
744
+ const suggestedMm = role === "signal" ? { hole: 0.2, pad: 0.4 } : { hole: 0.3, pad: 0.6 };
745
+ if (!Number.isFinite(holeMm) || !Number.isFinite(padMm) || holeMm <= 0 || padMm <= 0) {
746
+ errors.push("via hole and pad must be positive numbers of mil");
747
+ } else {
748
+ if (holeMm < VIA_HOLE_ABSOLUTE_MIN_MM) {
749
+ errors.push(`via hole ${holeMm.toFixed(2)} mm is below the ${VIA_HOLE_ABSOLUTE_MIN_MM} mm manufacturable minimum`);
750
+ } else if (holeMm < VIA_HOLE_MIN_MM) {
751
+ warnings.push(`via hole ${holeMm.toFixed(2)} mm is below the ${VIA_HOLE_MIN_MM} mm free-prototyping lower bound; confirm the capability on the order page`);
752
+ }
753
+ if (ringMm < ANNULUS_MIN_MM - 1e-3) {
754
+ errors.push(`via annular ring ${ringMm.toFixed(2)} mm (pad ${padMm.toFixed(2)} - hole ${holeMm.toFixed(2)}) is below the ${ANNULUS_MIN_MM} mm minimum`);
755
+ }
756
+ const standard = VIA_SIZES_MM.find((size) => Math.abs(size.hole - holeMm) < 0.01 && Math.abs(size.pad - padMm) < 0.01);
757
+ if (standard === void 0) {
758
+ warnings.push(`via ${holeMm.toFixed(2)}/${padMm.toFixed(2)} mm is not one of the standard sizes (0.2/0.4, 0.3/0.6, 0.4/0.8 mm)`);
759
+ }
760
+ if (role !== "signal" && holeMm < 0.3 && !force) {
761
+ warnings.push(`power/ground net "${net}" uses a ${holeMm.toFixed(2)} mm hole; 0.3/0.6 mm is recommended for current-carrying vias`);
762
+ }
763
+ }
764
+ return { ...result(errors, warnings), holeMm, padMm, annulusMm, ringMm, suggestedMm };
765
+ }
766
+ var POUR_CLEARANCE_MIN_MIL = 6;
767
+ var POUR_CLEARANCE_RECOMMENDED_MIL = 10;
768
+ var BOARD_OUTLINE_WIDTH_MIL = 10;
769
+ var SILKSCREEN_HEIGHT_MIN_MM = 1;
770
+ var SILKSCREEN_WIDTH_MIN_MM = 0.15;
771
+
772
+ // src/bridge/workflow-guide.ts
773
+ var WORKFLOW_SUMMARY = [
774
+ "\u539F\u7406\u56FE\u5DE5\u4F5C\u89C4\u8303\uFF08\u9ED8\u8BA4\u5168\u90E8\u624B\u5DE5\uFF0C\u7981\u6B62\u56FE\u7701\u4E8B\u7528\u81EA\u52A8\u5E03\u5C40/\u81EA\u52A8\u5E03\u7EBF\uFF09\uFF1A",
775
+ "1) \u5E03\u5C40\uFF1A\u6309 10 \u5355\u4F4D\u6805\u683C\u5BF9\u9F50\uFF1B\u4FE1\u53F7\u4ECE\u5DE6\u5230\u53F3\u3001\u7535\u6E90\u5728\u4E0A\u3001\u5730\u5728\u4E0B\uFF1B\u540C\u7EA7\u5668\u4EF6\u7B49\u95F4\u8DDD\uFF1B\u4E0D\u538B\u5B57\u3001\u4E0D\u538B\u6807\u9898\u680F\uFF1B\u5148\u770B eda_get_page_info \u7684\u5B89\u5168\u533A\u518D\u6446\u4F4D\u3002",
776
+ "2) \u8FDE\u7EBF\uFF1A\u53EA\u7528 eda_draw_wire \u8D70\u76F4\u7EBF/45 \u5EA6\uFF1B**\u8DE8\u533A\u57DF\u540C\u540D\u7F51\u7EDC\u5FC5\u987B\u7528\u7F51\u7EDC\u7AEF\u53E3\uFF08eda_place_net_port\uFF09\u6216\u7F51\u7EDC\u6807\u7B7E**\uFF0C\u4E0D\u80FD\u9760\u5728\u4E24\u5904\u753B\u4E00\u6761\u53EB\u540C\u540D\u7684\u5BFC\u7EBF\u2014\u2014\u5BFC\u7EBF\u4E00\u65E6\u63A5\u89E6\u5F15\u811A\uFF0Cnet \u4F1A\u88AB\u8FDE\u901A\u6027\u91CD\u7B97\uFF0C\u6307\u5B9A\u540D\u4F1A\u88AB\u8986\u76D6\u3002",
777
+ "3) \u7F51\u7EDC\u6807\u7B7E\uFF1A\u5148\u8BD5 eda_place_net_label\uFF1B\u82E5\u8BE5\u6784\u5EFA\u7684 createNetLabel \u4E0D\u54CD\u5E94\uFF0C\u4F1A\u81EA\u52A8\u964D\u7EA7\u4E3A\u7EAF\u6587\u672C\u6807\u7B7E\uFF08\u65E0\u7535\u6C14\u8BED\u4E49\uFF09\uFF0C\u6B64\u65F6\u9760 stub \u5BFC\u7EBF\u627F\u8F7D\u7F51\u7EDC\uFF1B\u6279\u91CF\u7528 eda_place_net_labels \u4E00\u6B21\u8C03\u7528\uFF0C\u4E0D\u8981\u4E32\u884C\u4E0A\u767E\u6B21\u3002",
778
+ "4) \u6821\u9A8C\uFF1Aeda_export_netlist \u770B\u6BCF\u4E2A\u7F51\u7EDC\u7684\u7AEF\u70B9\u662F\u5426 \u22652\uFF1Beda_run_drc \u770B\u9010\u6761 DRC \u660E\u7EC6\u3002",
779
+ "5) \u770B\u56FE\uFF08eda_capture\uFF09\u53EA\u5728\u8FD9 4 \u4E2A\u65F6\u523B\uFF1A\u5E03\u5C40\u5B8C\u6210\u5F85\u5E03\u7EBF\u3001\u5E03\u7EBF\u5B8C\u6210\u5F85 DRC\u3001\u4E1D\u5370\u6587\u5B57\u653E\u5B8C\u3001\u5750\u6807\u4E0E\u76F4\u89C9\u51B2\u7A81\u65F6\uFF1B\u4E0D\u8981\u6BCF\u6539\u4E00\u4E2A\u56FE\u5143\u622A\u4E00\u6B21\uFF0C\u770B\u5B8C eda_capture({cleanup:true}) \u5220\u6389\u4E34\u65F6 PNG\u3002",
780
+ "6) \u53EA\u6709\u7528\u6237\u660E\u786E\u8981\u6C42\u65F6\u624D eda_auto_layout / eda_auto_route\uFF08\u9700 force:true \u4E14\u8BBE\u7F6E\u91CC\u653E\u884C\uFF09\u3002",
781
+ "7) \u5F15\u811A\u4FE1\u606F\u7528 eda_get_pins \u4E00\u6B21\u62FF\u5168\uFF08\u542B pinName/pinNumber\uFF09\uFF0C\u4E0D\u8981\u9010\u811A\u8C03 raw API\u3002"
782
+ ].join("\n");
783
+ var WORKFLOW_GUIDE = WORKFLOW_SUMMARY + "\n\n" + [
784
+ "## \u5E03\u5C40\u7EC6\u5219\u662F\u600E\u4E48\u843D\u5730\u7684",
785
+ "",
786
+ "- \u5750\u6807\u5355\u4F4D\u662F 0.01 \u82F1\u5BF8\uFF08MCP \u5355\u4F4D\uFF09\uFF1BA4 \u56FE\u6846 0..1170 / 0..825\uFF0C\u6807\u9898\u680F\u5360 right 460..1160 / bottom 10..190\uFF0C\u5B89\u5168\u533A\u89C1 eda_get_page_info\u3002",
787
+ "- \u4E00\u9875\u53EA\u653E\u4E00\u4E2A\u529F\u80FD\u5757\uFF1B\u5668\u4EF6\u6309\u4FE1\u53F7\u6D41\u4ECE\u5DE6\u5230\u53F3\u6392\uFF0C\u53CD\u9988\u5143\u4EF6\u653E\u5728\u653E\u5927\u5668\u4E0B\u65B9\uFF0C\u53BB\u8026\u7535\u5BB9\u8D34\u8FD1\u7535\u6E90\u811A\u3002",
788
+ "- \u5668\u4EF6\u4E4B\u95F4\u7559\u51FA\u81F3\u5C11 20 \u5355\u4F4D\u7528\u4E8E\u8D70\u7EBF\u548C\u6807\u7B7E\uFF1B\u7F51\u7EDC\u7AEF\u53E3\u653E\u5728\u6A21\u5757\u8FB9\u7F18\uFF0C\u5DE6\u53F3\u5404\u4E00\u5217\u3002",
789
+ "- \u6446\u597D\u4E00\u4E2A\u6A21\u5757\u518D\u6446\u4E0B\u4E00\u4E2A\uFF1B\u6BCF\u6B21\u6446\u5B8C\u7528 eda_get_components \u68C0\u67E5\u6CA1\u6709\u91CD\u53E0\uFF08\u5305\u56F4\u76D2\u76F8\u4EA4\uFF09\u3002",
790
+ "",
791
+ "## \u7F51\u7EDC\u4E0E\u6807\u7B7E",
792
+ "",
793
+ "- eda_place_net_port \u4EA7\u751F\u771F\u6B63\u7684\u7F51\u7EDC\u7AEF\u53E3\u56FE\u5143\uFF0C\u662F\u8DE8\u533A\u57DF\u8FDE\u63A5\u7684\u9996\u9009\u3002",
794
+ "- eda_place_net_label \u4F18\u5148\u8C03 sch_PrimitiveAttribute.createNetLabel\uFF1B\u8BE5 API \u5728 3.2.186 \u4E0A\u4E0D\u54CD\u5E94\uFF0C\u63A2\u6D4B\u7ED3\u8BBA\u6309\u4F1A\u8BDD\u7F13\u5B58\uFF0C\u4E4B\u540E\u76F4\u63A5\u964D\u7EA7\u4E3A\u6587\u672C\u6807\u7B7E\uFF08\u4E0D\u518D\u6BCF\u6B21\u4ED8 4 \u79D2\u8D85\u65F6\uFF09\u3002",
795
+ "- \u964D\u7EA7\u540E\u7684\u6587\u672C\u6807\u7B7E\u6CA1\u6709\u7535\u6C14\u8BED\u4E49\uFF1A\u8FDE\u901A\u6027\u7531 eda_place_net_label_at_pin \u540C\u65F6\u753B\u7684 stub \u5BFC\u7EBF\u627F\u62C5\u3002",
796
+ "- eda_get_net_labels \u4F1A\u540C\u65F6\u5217\u51FA\u5C5E\u6027\u56FE\u5143\uFF08netlabel/netport/netflag\uFF09\u548C\u6587\u672C\u6807\u7B7E\uFF0C\u5220\u9664\u7528 eda_delete_primitive \u7684\u5BF9\u5E94 kind\u3002",
797
+ "- \u6279\u91CF\u653E\u7F6E\u7528 eda_place_net_labels([{pinPrimitiveId, net}, ...])\uFF0C\u4E00\u6B21\u8C03\u7528\u5B8C\u6210\u5E76\u9010\u6761\u56DE\u62A5\u6210\u8D25\u3002",
798
+ "",
799
+ "## \u5BFC\u7EBF net \u88AB\u8986\u76D6\uFF08\u52A1\u5FC5\u77E5\u9053\uFF09",
800
+ "",
801
+ "eda_draw_wire \u4F20\u7684 net \u53EA\u5BF9**\u60AC\u7A7A\u5BFC\u7EBF**\u6709\u6548\uFF1B\u5BFC\u7EBF\u7AEF\u70B9\u4E00\u65E6\u843D\u5728\u5F15\u811A/\u7F51\u7EDC\u4E0A\uFF0CEDA \u4F1A\u6309\u8FDE\u901A\u6027\u91CD\u7B97\u7F51\u7EDC\u540D\uFF08\u5B9E\u6D4B TESTNET \u5E76\u5165\u4E86 LED_A\uFF09\u3002\u6240\u4EE5\u201C\u540C\u540D\u5BFC\u7EBF = \u540C\u540D\u7F51\u7EDC\u201D\u4E0D\u6210\u7ACB\uFF0C\u8DE8\u533A\u57DF\u540C\u540D\u5FC5\u987B\u7528\u7F51\u7EDC\u6807\u7B7E\u6216\u7F51\u7EDC\u7AEF\u53E3\u3002",
802
+ "",
803
+ "## \u4EC0\u4E48\u65F6\u5019\u5FC5\u987B\u770B\u56FE\uFF08eda_capture\uFF09\uFF0C\u4EC0\u4E48\u65F6\u5019\u4E0D\u8981",
804
+ "",
805
+ '\u770B\u56FE\u4E0D\u662F"\u53EF\u9009\u52A0\u5206\u9879"\uFF0C\u4E5F\u4E0D\u662F"\u6BCF\u6B65\u90FD\u622A"\u3002\u5224\u636E\u6309\u98CE\u9669\u800C\u4E0D\u662F\u6309\u4E60\u60EF\uFF1A',
806
+ "",
807
+ "**\u5FC5\u987B\u770B\u56FE\uFF084 \u4E2A\u65F6\u523B\uFF09**",
808
+ "",
809
+ "1. \u5E03\u5C40\u5B8C\u6210\u3001\u5E03\u7EBF\u4E4B\u524D\uFF1A\u677F\u9762\u6700\u7A7A\uFF0C\u6700\u5BB9\u6613\u4E00\u773C\u770B\u51FA\u5668\u4EF6\u8D8A\u754C\u3001\u5668\u4EF6\u4E92\u76F8\u538B\u4F4F\u3001\u8FDE\u63A5\u5668\u671D\u5411\u53CD\u4E86\u3001\u5B89\u88C5\u5B54\u538B\u5230\u5668\u4EF6\u3002",
810
+ "2. \u5E03\u7EBF\u5B8C\u6210\u3001DRC \u4E4B\u524D\uFF1A\u770B\u6709\u6CA1\u6709\u8DE8\u7F51\u7EDC\u8D34\u5408\u3001\u5929\u7EBF stub\u3001\u7ED5\u8FDC\u7684\u957F\u8D70\u7EBF\u3001GND \u88AB\u6253\u6563\u6210\u5B64\u5C9B\u3002",
811
+ "3. \u4E1D\u5370/\u5DE5\u827A\u6587\u5B57\u653E\u5B8C\uFF1A\u770B\u6587\u5B57\u6709\u6CA1\u6709\u538B\u710A\u76D8\u3001\u88AB\u677F\u8FB9\u88C1\u5207\u3001\u65B9\u5411\u53CD\u4E86\uFF1B\u539F\u7406\u56FE\u540C\u7406\u770B\u6807\u7B7E\u91CD\u53E0\u3001\u56FE\u6846\u7EBF\u7A7F\u8FC7\u5668\u4EF6\u3002",
812
+ "4. \u5750\u6807\u7B97\u672F\u4E0E\u76F4\u89C9\u51B2\u7A81\u65F6\uFF08\u5DE5\u5177\u8BF4\u5728\u6846\u5185\u4F46\u4F60\u6000\u7591\u8D8A\u754C\u3001audit \u8BF4\u6CA1\u95EE\u9898\u4F46\u7528\u6237\u8BF4\u96BE\u770B\uFF09\uFF1A\u8FD9\u65F6\u56FE\u662F\u552F\u4E00\u88C1\u51B3\u8005\u3002",
813
+ "",
814
+ "**\u4E0D\u8981\u770B\u56FE**",
815
+ "",
816
+ "- \u6BCF\u653E\u4E00\u4E2A\u56FE\u5143\u5C31\u622A\u4E00\u6B21\uFF1A\u5355\u6B21\u7EA6 2.7 s\u30010.4 MB\uFF0C\u8FD8\u4F1A\u6324\u5360\u4E0A\u4E0B\u6587\u9884\u7B97\u2014\u2014\u6279\u91CF\u6539\u5B8C\u518D\u622A\u3002",
817
+ "- \u53EA\u662F\u786E\u8BA4\u67D0\u4E2A\u8FD4\u56DE\u503C/\u5C5E\u6027\uFF1A\u7528 eda_get_* \u8BFB\u6570\u636E\u6BD4\u56FE\u51C6\u3002",
818
+ "- DRC \u5DF2\u7ED9\u51FA primitiveId/\u5750\u6807\u7684\u9519\u8BEF\uFF1A\u76F4\u63A5\u5B9A\u4F4D\uFF0C\u4E0D\u7528\u56FE\u3002",
819
+ "",
820
+ "**\u770B\u5B8C\u7ACB\u523B\u5220**\uFF1Aeda_capture({cleanup:true})\u3002",
821
+ "",
822
+ "## \u6821\u9A8C\u987A\u5E8F",
823
+ "",
824
+ "1. eda_get_active_document \u786E\u8BA4\u5728\u539F\u7406\u56FE\u9875\uFF08\u4E0D\u662F HOME/PCB\uFF09\u3002",
825
+ "2. eda_export_netlist\uFF08\u5DF2\u89E3\u6790\u6210\u5BF9\u8C61\uFF09\u68C0\u67E5\u6BCF\u4E2A\u7F51\u7EDC \u22652 \u7AEF\u70B9\u3001\u65E0\u60AC\u7A7A\u3002",
826
+ "3. eda_run_drc \u770B\u9010\u6761\u660E\u7EC6\uFF08\u542B primitiveId \u4E0E\u5750\u6807\uFF09\u3002",
827
+ "4. \u9700\u8981\u4EBA\u770B\u6548\u679C\u5C31\u5BFC\u51FA\u56FE\u7247\u81EA\u884C\u8BC6\u522B\uFF0C\u4E0D\u8981\u7528\u81EA\u52A8\u5E03\u5C40\u201C\u4FEE\u201D\u7248\u9762\u3002"
828
+ ].join("\n");
829
+
830
+ // src/bridge/index.ts
831
+ var VERSION = "0.4.11";
832
+ var WS_PORT = Number(process.env.DSH_EDA_MCP_WS_PORT ?? 39009);
833
+ var WS_HOST = "127.0.0.1";
834
+ var ALLOW_RAW_API = (process.env.DSH_EDA_MCP_ALLOW_RAW_API ?? "1") !== "0";
835
+ var ALLOW_AUTO_LAYOUT = (process.env.DSH_EDA_ALLOW_AUTO_LAYOUT ?? "0") === "1";
836
+ var TOOL_TIMEOUT_MS = Number(process.env.DSH_EDA_MCP_TOOL_TIMEOUT_MS ?? 6e4);
837
+ var MCP_UNITS_PER_INCH = 100;
838
+ var PAPER_SIZES = {
839
+ A4: {
840
+ name: "A4",
841
+ widthInch: 11.7,
842
+ heightInch: 8.25,
843
+ frame: { left: 0, bottom: 0, right: 1170, top: 825 },
844
+ titleBlock: { left: 460, bottom: 10, right: 1160, top: 190 }
845
+ }
846
+ };
847
+ var DEFAULT_PAPER = "A4";
848
+ function paperOf(name) {
849
+ const key = String(name ?? DEFAULT_PAPER).toUpperCase();
850
+ return PAPER_SIZES[key] ?? PAPER_SIZES[DEFAULT_PAPER];
851
+ }
852
+ function safeAreas(paperName) {
853
+ const paper = paperOf(paperName);
854
+ return {
855
+ main: { left: 40, bottom: 200, right: paper.frame.right - 40, top: paper.frame.top - 25 },
856
+ lowerLeft: { left: 40, bottom: 40, right: paper.titleBlock.left - 20, top: paper.titleBlock.top - 10 }
857
+ };
858
+ }
859
+ function decodeTextPayload(value) {
860
+ const text = typeof value === "string" ? value : "";
861
+ if (text === "") return text;
862
+ if (text.charCodeAt(0) === 65279) return text.slice(1);
863
+ if (text.charCodeAt(0) === 255 && text.charCodeAt(1) === 254) {
864
+ return Buffer.from(text.slice(2), "latin1").toString("utf16le");
865
+ }
866
+ if (text.length > 3 && text.charCodeAt(1) === 0 && text.charCodeAt(3) === 0) {
867
+ return Buffer.from(text, "latin1").toString("utf16le");
868
+ }
869
+ return text;
870
+ }
871
+ function checkPointInFrame(x, y, paperName, margin = 0) {
872
+ const paper = paperOf(paperName);
873
+ const f = paper.frame;
874
+ if (x < f.left + margin || x > f.right - margin || y < f.bottom + margin || y > f.top - margin) {
875
+ return "point (" + x + ", " + y + ") is outside the " + paper.name + " frame " + f.left + ".." + f.right + " x " + f.bottom + ".." + f.top + " (MCP units, 0.01 inch)";
876
+ }
877
+ return void 0;
878
+ }
879
+ function checkPointAgainstTitleBlock(x, y, paperName, margin = 0) {
880
+ const paper = paperOf(paperName);
881
+ const t = paper.titleBlock;
882
+ if (x > t.left - margin && x < t.right + margin && y > t.bottom - margin && y < t.top + margin) {
883
+ return "point (" + x + ", " + y + ") overlaps the title block " + t.left + ".." + t.right + " x " + t.bottom + ".." + t.top + " (MCP units)";
884
+ }
885
+ return void 0;
886
+ }
887
+ function checkBBoxInFrame(bbox, paperName, margin = 0) {
888
+ const paper = paperOf(paperName);
889
+ const f = paper.frame;
890
+ if (bbox.minX < f.left + margin || bbox.maxX > f.right - margin || bbox.minY < f.bottom + margin || bbox.maxY > f.top - margin) {
891
+ return "bounding box [" + bbox.minX + "," + bbox.minY + "]..[" + bbox.maxX + "," + bbox.maxY + "] is outside the " + paper.name + " frame";
892
+ }
893
+ const t = paper.titleBlock;
894
+ if (bbox.maxX > t.left - margin && bbox.minX < t.right + margin && bbox.maxY > t.bottom - margin && bbox.minY < t.top + margin) {
895
+ return "bounding box [" + bbox.minX + "," + bbox.minY + "]..[" + bbox.maxX + "," + bbox.maxY + "] overlaps the title block";
896
+ }
897
+ return void 0;
898
+ }
899
+ var ALLOWED_API = /* @__PURE__ */ new Set([
900
+ "sch_Document.save",
901
+ "sch_Document.navigateToCoordinates",
902
+ "sch_Document.navigateToRegion",
903
+ "sch_Document.getPrimitiveAtPoint",
904
+ "sch_Document.getPrimitivesInRegion",
905
+ "sch_Document.autoLayout",
906
+ "sch_Document.autoRouting",
907
+ "sch_Drc.check",
908
+ "sch_Net.getAllNets",
909
+ "sch_Net.getCurrentProjectAllNets",
910
+ "sch_Net.getAllNetsName",
911
+ "sch_Net.getNet",
912
+ "sch_ManufactureData.getNetlistFile",
913
+ "sch_ManufactureData.getBomFile",
914
+ "sch_Primitive.getPrimitivesBBox",
915
+ "sch_PrimitiveComponent.create",
916
+ "sch_PrimitiveComponent.createNetFlag",
917
+ "sch_PrimitiveComponent.createNetPort",
918
+ "sch_PrimitiveComponent.createShortCircuitFlag",
919
+ "sch_PrimitiveComponent.delete",
920
+ "sch_PrimitiveComponent.modify",
921
+ "sch_PrimitiveComponent.get",
922
+ "sch_PrimitiveComponent.getAll",
923
+ "sch_PrimitiveComponent.getAllPrimitiveId",
924
+ "sch_PrimitiveComponent.getAllPinsByPrimitiveId",
925
+ "sch_PrimitiveComponent.getAllPropertyNames",
926
+ "sch_PrimitiveWire.create",
927
+ "sch_PrimitiveWire.delete",
928
+ "sch_PrimitiveWire.modify",
929
+ "sch_PrimitiveWire.get",
930
+ "sch_PrimitiveWire.getAll",
931
+ "sch_PrimitiveWire.getAllPrimitiveId",
932
+ "sch_PrimitiveRectangle.create",
933
+ "sch_PrimitiveRectangle.delete",
934
+ "sch_PrimitiveRectangle.modify",
935
+ "sch_PrimitiveRectangle.get",
936
+ "sch_PrimitiveRectangle.getAll",
937
+ "sch_PrimitiveRectangle.getAllPrimitiveId",
938
+ "sch_PrimitiveCircle.create",
939
+ "sch_PrimitiveCircle.delete",
940
+ "sch_PrimitiveCircle.modify",
941
+ "sch_PrimitiveCircle.get",
942
+ "sch_PrimitiveCircle.getAll",
943
+ "sch_PrimitiveCircle.getAllPrimitiveId",
944
+ "sch_PrimitiveArc.create",
945
+ "sch_PrimitiveArc.delete",
946
+ "sch_PrimitiveArc.modify",
947
+ "sch_PrimitiveArc.get",
948
+ "sch_PrimitiveArc.getAll",
949
+ "sch_PrimitiveArc.getAllPrimitiveId",
950
+ "sch_PrimitivePolygon.create",
951
+ "sch_PrimitivePolygon.delete",
952
+ "sch_PrimitivePolygon.modify",
953
+ "sch_PrimitivePolygon.get",
954
+ "sch_PrimitivePolygon.getAll",
955
+ "sch_PrimitivePolygon.getAllPrimitiveId",
956
+ "sch_PrimitiveText.create",
957
+ "sch_PrimitiveText.delete",
958
+ "sch_PrimitiveText.modify",
959
+ "sch_PrimitiveText.get",
960
+ "sch_PrimitiveText.getAll",
961
+ "sch_PrimitiveText.getAllPrimitiveId",
962
+ "sch_PrimitivePin.get",
963
+ "sch_PrimitivePin.modify",
964
+ "lib_Device.search",
965
+ "lib_Device.getByLcscIds",
966
+ "lib_Symbol.search",
967
+ "lib_Footprint.search",
968
+ "dmt_Schematic.getCurrentSchematicInfo",
969
+ "dmt_Schematic.getCurrentSchematicPageInfo",
970
+ "dmt_Schematic.getCurrentSchematicAllSchematicPagesInfo",
971
+ "dmt_Schematic.getSchematicInfo",
972
+ "dmt_Schematic.getSchematicPageInfo",
973
+ "dmt_Schematic.getAllSchematicPagesInfo",
974
+ "dmt_Board.createBoard",
975
+ "dmt_Board.getAllBoardsInfo",
976
+ "dmt_Board.getCurrentBoardInfo",
977
+ "dmt_EditorControl.getSplitScreenTree",
978
+ "dmt_EditorControl.getTabsBySplitScreenId",
979
+ "dmt_EditorControl.openDocument",
980
+ "dmt_EditorControl.activateDocument",
981
+ "dmt_EditorControl.zoomToRegion",
982
+ "dmt_EditorControl.zoomToAllPrimitives",
983
+ "dmt_EditorControl.getCurrentRenderedAreaImage",
984
+ "dmt_EditorControl.generateIndicatorMarkers",
985
+ "dmt_EditorControl.removeIndicatorMarkers",
986
+ "pcb_Document.save",
987
+ "pcb_Document.importChanges",
988
+ "pcb_Document.getPrimitivesInRegion",
989
+ "pcb_Document.navigateToRegion",
990
+ "pcb_Document.navigateToCoordinates",
991
+ "pcb_Document.zoomToBoardOutline",
992
+ "pcb_Document.getCanvasOrigin",
993
+ "pcb_Primitive.getPrimitivesBBox",
994
+ "pcb_PrimitiveComponent.create",
995
+ "pcb_PrimitiveComponent.getAll",
996
+ "pcb_PrimitiveComponent.getAllPrimitiveId",
997
+ "pcb_PrimitiveComponent.getAllPinsByPrimitiveId",
998
+ "pcb_PrimitiveLine.create",
999
+ "pcb_PrimitiveVia.create",
1000
+ "pcb_Net.getAllNets",
1001
+ "pcb_Net.getAllNetsName",
1002
+ "pcb_Layer.getAllLayers",
1003
+ "pcb_Layer.getCurrentLayer",
1004
+ "pcb_PrimitiveComponent.modify",
1005
+ "pcb_PrimitiveComponent.delete",
1006
+ "pcb_PrimitiveLine.getAll",
1007
+ "pcb_PrimitiveLine.getAllPrimitiveId",
1008
+ "pcb_PrimitiveLine.modify",
1009
+ "pcb_PrimitiveLine.delete",
1010
+ "pcb_PrimitiveVia.getAll",
1011
+ "pcb_PrimitiveVia.getAllPrimitiveId",
1012
+ "pcb_PrimitiveVia.modify",
1013
+ "pcb_PrimitiveVia.delete",
1014
+ "pcb_PrimitivePolyline.create",
1015
+ "pcb_PrimitivePolyline.modify",
1016
+ "pcb_PrimitivePolyline.delete",
1017
+ "pcb_PrimitivePolyline.getAll",
1018
+ "pcb_PrimitivePolyline.getAllPrimitiveId",
1019
+ "pcb_Document.clearRouting",
1020
+ "pcb_PrimitiveRegion.create",
1021
+ "pcb_PrimitiveRegion.getAll",
1022
+ "pcb_PrimitiveRegion.getAllPrimitiveId",
1023
+ "pcb_PrimitiveRegion.modify",
1024
+ "pcb_PrimitiveRegion.delete",
1025
+ "pcb_MathPolygon.createPolygon",
1026
+ "pcb_PrimitivePour.create",
1027
+ "pcb_PrimitivePour.modify",
1028
+ "pcb_PrimitivePour.delete",
1029
+ "pcb_PrimitivePour.getAll",
1030
+ "pcb_PrimitivePour.getAllPrimitiveId",
1031
+ "pcb_Drc.check",
1032
+ "pcb_Drc.getCurrentRuleConfiguration",
1033
+ "pcb_Drc.getCurrentRuleConfigurationName",
1034
+ "pcb_Drc.getRealTimeDrcStatus",
1035
+ "pcb_Drc.startRealTimeDrc",
1036
+ "pcb_Drc.stopRealTimeDrc",
1037
+ "sch_PrimitiveAttribute.createNetLabel",
1038
+ "sch_PrimitiveAttribute.modify",
1039
+ "sch_PrimitiveAttribute.delete",
1040
+ "sch_PrimitiveAttribute.getAll",
1041
+ "sch_Netlist.getNetlist",
1042
+ "dmt_SelectControl.getCurrentDocumentInfo",
1043
+ "pcb_PrimitiveComponent.getAllPinsByPrimitiveId",
1044
+ "pcb_Document.autoLayout",
1045
+ "pcb_Document.autoRouting",
1046
+ "pcb_ManufactureData.getGerberFile"
1047
+ ]);
1048
+ function objectSchema(properties, required = []) {
1049
+ return { type: "object", properties, required, additionalProperties: false };
1050
+ }
1051
+ var TOOLS = [
1052
+ { name: "eda_status", description: "Get the dsh-eda-mcp bridge status and how many JLCEDA Pro bridge extensions are connected.", inputSchema: objectSchema({}) },
1053
+ { name: "eda_list_projects", description: "List project UUIDs in the workspace (dmt_Project.getAllProjectsUuid). resolveNames=true (default) also reads getProjectInfo per project so callers can match by friendly name.", inputSchema: objectSchema({ teamUuid: { type: "string" }, folderUuid: { type: "string" }, workspaceUuid: { type: "string" }, resolveNames: { type: "boolean" }, limit: { type: "integer" } }) },
1054
+ { name: "eda_get_project", description: "Read the current project (dmt_Project.getCurrentProjectInfo): uuid, friendly name, folder/team and other brief fields.", inputSchema: objectSchema({}) },
1055
+ { name: "eda_open_project", description: "Open a project by uuid, or by friendly name when only a name is known (the name is resolved through getAllProjectsUuid + getProjectInfo, exact match first, then case-insensitive substring).", inputSchema: objectSchema({ uuid: { type: "string" }, name: { type: "string" } }) },
1056
+ { name: "eda_create_project", description: "Create a project (dmt_Project.createProject) and return its uuid; open=true (default false) also opens it. friendlyName is required; name and folder/team default to the app defaults.", inputSchema: objectSchema({ friendlyName: { type: "string" }, name: { type: "string" }, teamUuid: { type: "string" }, folderUuid: { type: "string" }, description: { type: "string" }, open: { type: "boolean" } }, ["friendlyName"]) },
1057
+ { name: "eda_get_workspace", description: "Read the current workspace and team (dmt_Workspace.getCurrentWorkspaceInfo / dmt_Team.getCurrentTeamInfo). Needed before creating a project, which requires a team (and usually a folder) uuid.", inputSchema: objectSchema({}) },
1058
+ { name: "eda_list_teams", description: "List teams (dmt_Team.getAllTeamsInfo), optionally including the teams this account is involved in.", inputSchema: objectSchema({ involved: { type: "boolean" } }) },
1059
+ { name: "eda_list_folders", description: "List folder uuids of one team (dmt_Folder.getAllFoldersUuid), optionally resolved through getFolderInfo.", inputSchema: objectSchema({ teamUuid: { type: "string" }, resolveNames: { type: "boolean" } }) },
1060
+ { name: "eda_delete_project", description: "Delete a project (dmt_Project.deleteProject) by uuid or friendly name.", inputSchema: objectSchema({ uuid: { type: "string" }, name: { type: "string" } }) },
1061
+ { name: "eda_modify_project", description: "Rename a project or change its description (dmt_Project.modifyProjectFriendlyName / modifyProjectDescription), addressed by uuid or current friendly name.", inputSchema: objectSchema({ uuid: { type: "string" }, name: { type: "string" }, friendlyName: { type: "string" }, description: { type: "string" } }) },
1062
+ { name: "eda_copy_project", description: "Copy a project (dmt_Project.copyProject), optionally into another team/folder and with a new friendly name; returns the new uuid.", inputSchema: objectSchema({ sourceUuid: { type: "string" }, sourceName: { type: "string" }, targetTeamUuid: { type: "string" }, targetFolderUuid: { type: "string" }, newFriendlyName: { type: "string" }, newName: { type: "string" } }) },
1063
+ { name: "eda_close_document", description: "Close one editor tab (dmt_EditorControl.closeDocument).", inputSchema: objectSchema({ tabId: { type: "string" } }, ["tabId"]) },
1064
+ { name: "eda_export_project", description: "Export a project file (sys_FileManager.getProjectFile / getProjectFileByProjectUuid). With outPath the bridge writes the bytes to disk and returns the path; without it the base64 payload is returned only when inline=true.", inputSchema: objectSchema({ uuid: { type: "string" }, fileName: { type: "string" }, fileType: { type: "string", enum: ["epro", "epro2"] }, outPath: { type: "string" }, inline: { type: "boolean" } }) },
1065
+ { name: "eda_import_project", description: "Import a local project file (.eprj2/.epro/...) into a team (sys_FileManager.importProjectByProjectFile with a saveTo target). teamUuid is required in local mode: without a target team the app imports nothing. Returns whether the import actually landed.", inputSchema: objectSchema({ path: { type: "string" }, teamUuid: { type: "string" }, folderUuid: { type: "string" }, friendlyName: { type: "string" }, fileType: { type: "string" }, open: { type: "boolean" } }, ["path"]) },
1066
+ { name: "eda_close", description: "Close JLCEDA Pro gracefully (taskkill /T on Windows, SIGTERM elsewhere), then force-kill if it is still running after waitMs (default 8000). Returns the remaining process count.", inputSchema: objectSchema({ force: { type: "boolean" }, waitMs: { type: "integer" } }) },
1067
+ { name: "eda_launch", description: "Launch JLCEDA Pro (EasyEDA Pro), optionally opening a .eprj2/.eprj project, then wait until the bridge extension connects. The executable is resolved from DSH_EDA_EXECUTABLE/JLCEDA_EXECUTABLE, the registry handler the installer registered, conventional install directories, then PATH - so it works on any machine without configuration.", inputSchema: objectSchema({ project: { type: "string" }, executable: { type: "string" }, waitForExtension: { type: "boolean" }, timeoutMs: { type: "integer" } }) },
1068
+ { name: "eda_get_page_info", description: "Return the current schematic page, the A4 frame range, the title-block keep-out range, and the recommended safe placement areas. All coordinates are MCP units (0.01 inch).", inputSchema: objectSchema({ paper: { type: "string" } }) },
1069
+ { name: "eda_get_schematic_pages", description: "List the schematic pages of the current schematic, or fetch one page by uuid.", inputSchema: objectSchema({ pageUuid: { type: "string" } }) },
1070
+ { name: "eda_search_components", description: "Search JLCEDA library devices by keyword. Returns candidate components with uuid/libraryUuid needed by eda_place_component.", inputSchema: objectSchema({ keyword: { type: "string" }, limit: { type: "integer" } }, ["keyword"]) },
1071
+ { name: "eda_place_component", description: "Place a JLCEDA library component on the active schematic page. Coordinates are MCP units (0.01 inch), origin at the lower-left of the A4 frame. Placement is rejected when the symbol leaves the frame or overlaps the title block unless allowOutsideFrame is true.", inputSchema: objectSchema({
1072
+ libraryUuid: { type: "string" },
1073
+ uuid: { type: "string" },
1074
+ x: { type: "number" },
1075
+ y: { type: "number" },
1076
+ subPartName: { type: "string" },
1077
+ rotation: { type: "integer", enum: [0, 90, 180, 270] },
1078
+ mirror: { type: "boolean" },
1079
+ addIntoBom: { type: "boolean" },
1080
+ addIntoPcb: { type: "boolean" },
1081
+ designator: { type: "string" },
1082
+ value: { type: "string" },
1083
+ name: { type: "string" },
1084
+ paper: { type: "string" },
1085
+ allowOutsideFrame: { type: "boolean" }
1086
+ }, ["libraryUuid", "uuid", "x", "y"]) },
1087
+ { name: "eda_place_net_flag", description: "Place a power/ground net flag (VCC/GND etc.) on the active schematic page.", inputSchema: objectSchema({ identification: { type: "string", enum: ["Power", "Ground", "AnalogGround", "ProtectGround"] }, net: { type: "string" }, x: { type: "number" }, y: { type: "number" }, rotation: { type: "integer", enum: [0, 90, 180, 270] }, mirror: { type: "boolean" }, paper: { type: "string" }, allowOutsideFrame: { type: "boolean" } }, ["identification", "net", "x", "y"]) },
1088
+ { name: "eda_place_net_port", description: "Place a net port on the active schematic page.", inputSchema: objectSchema({ direction: { type: "string", enum: ["IN", "OUT", "BI"] }, net: { type: "string" }, x: { type: "number" }, y: { type: "number" }, rotation: { type: "integer", enum: [0, 90, 180, 270] }, mirror: { type: "boolean" }, paper: { type: "string" }, allowOutsideFrame: { type: "boolean" } }, ["direction", "net", "x", "y"]) },
1089
+ { name: "eda_get_pins", description: "List pins of one schematic component in a single round trip, including pinName and pinNumber (no per-pin sch_PrimitivePin.get needed). Use the returned primitiveId with eda_place_net_flag_at_pin, eda_place_net_label_at_pin, or eda_set_no_connect.", inputSchema: objectSchema({ componentPrimitiveId: { type: "string" } }, ["componentPrimitiveId"]) },
1090
+ { name: "eda_place_net_flag_at_pin", description: "Place a power/ground net flag at a pin WITHOUT covering the symbol: the pin direction is read from the pin rotation, a stub wire of stubLength MCP units (default 20) is drawn outwards from the pin with the net name, and the flag is placed at its end. Pass offsetX/offsetY to place it manually (that disables the stub) or stubLength=0 for the old on-pin behaviour.", inputSchema: objectSchema({ pinPrimitiveId: { type: "string" }, identification: { type: "string", enum: ["Power", "Ground", "AnalogGround", "ProtectGround"] }, net: { type: "string" }, stubLength: { type: "number" }, offsetX: { type: "number" }, offsetY: { type: "number" }, rotation: { type: "integer", enum: [0, 90, 180, 270] }, mirror: { type: "boolean" }, color: { type: "string" }, lineWidth: { type: "integer" }, lineType: { type: "integer" }, paper: { type: "string" }, allowOutsideFrame: { type: "boolean" } }, ["pinPrimitiveId", "identification", "net"]) },
1091
+ { name: "eda_place_net_label_at_pin", description: "Place a REAL net label at a pin (sch_PrimitiveAttribute.createNetLabel; falls back to text and reports method) WITHOUT covering the symbol: a stub wire of stubLength MCP units (default 20) is drawn outwards along the pin direction and the label goes at its end. offsetX/offsetY place it manually (disables the stub); stubLength=0 keeps the old on-pin behaviour.", inputSchema: objectSchema({ pinPrimitiveId: { type: "string" }, net: { type: "string" }, stubLength: { type: "number" }, offsetX: { type: "number" }, offsetY: { type: "number" }, rotation: { type: "integer", enum: [0, 90, 180, 270] }, fontSize: { type: "number" }, color: { type: "string" }, lineWidth: { type: "integer" }, lineType: { type: "integer" }, paper: { type: "string" }, allowOutsideFrame: { type: "boolean" } }, ["pinPrimitiveId", "net"]) },
1092
+ { name: "eda_set_no_connect", description: "Set or clear the no-connect flag on one or more schematic pins via sch_PrimitivePin.modify.", inputSchema: objectSchema({ primitiveIds: { type: "array", items: { type: "string" } }, noConnected: { type: "boolean" } }, ["primitiveIds"]) },
1093
+ { name: "eda_draw_wire", description: "Draw a schematic wire (polyline). Coordinates are MCP units (0.01 inch). IMPORTANT: the net argument only sticks on a floating wire \u2014 as soon as an endpoint touches a pin, EDA recomputes the net from connectivity and the name you passed is overwritten (measured: TESTNET merged into LED_A). To join same-named nets across regions use eda_place_net_port or a net label; do not rely on two distantly drawn wires sharing a name.", inputSchema: objectSchema({ points: { type: "array", items: { type: "number" } }, net: { type: "string" }, color: { type: "string" }, lineWidth: { type: "integer", minimum: 1, maximum: 10 }, lineType: { type: "integer", enum: [0, 1, 2, 3] } }, ["points"]) },
1094
+ { name: "eda_draw_rectangle", description: "Draw a rectangle. topLeftY is the UPPER y coordinate (max y); height extends downward. Coordinates are MCP units.", inputSchema: objectSchema({ topLeftX: { type: "number" }, topLeftY: { type: "number" }, width: { type: "number" }, height: { type: "number" }, cornerRadius: { type: "number" }, rotation: { type: "integer", enum: [0, 90, 180, 270] }, color: { type: "string" }, fillColor: { type: "string" }, lineWidth: { type: "integer", minimum: 1, maximum: 10 }, lineType: { type: "integer", enum: [0, 1, 2, 3] }, fillStyle: { type: "string" } }, ["topLeftX", "topLeftY", "width", "height"]) },
1095
+ { name: "eda_draw_functional_box", description: "Draw a dashed functional-group box around one group of components, with an optional label. Margins and coordinates are MCP units; default margin 1 unit (about 0.254 mm).", inputSchema: objectSchema({ componentIds: { type: "array", items: { type: "string" } }, label: { type: "string" }, margin: { type: "number" }, color: { type: "string" }, lineWidth: { type: "integer", minimum: 1, maximum: 10 }, lineType: { type: "integer", enum: [0, 1, 2, 3] } }) },
1096
+ { name: "eda_draw_circle", description: "Draw a circle. Coordinates are MCP units.", inputSchema: objectSchema({ centerX: { type: "number" }, centerY: { type: "number" }, radius: { type: "number" }, color: { type: "string" }, fillColor: { type: "string" }, lineWidth: { type: "integer", minimum: 1, maximum: 10 }, lineType: { type: "integer", enum: [0, 1, 2, 3] }, fillStyle: { type: "string" } }, ["centerX", "centerY", "radius"]) },
1097
+ { name: "eda_draw_text", description: "Draw text. Coordinates are MCP units.", inputSchema: objectSchema({ x: { type: "number" }, y: { type: "number" }, content: { type: "string" }, rotation: { type: "integer", enum: [0, 90, 180, 270] }, textColor: { type: "string" }, fontName: { type: "string" }, fontSize: { type: "number" }, bold: { type: "boolean" }, italic: { type: "boolean" }, underLine: { type: "boolean" }, alignMode: { type: "integer", minimum: 1, maximum: 9 } }, ["x", "y", "content"]) },
1098
+ { name: "eda_save_document", description: "Save the active schematic document.", inputSchema: objectSchema({}) },
1099
+ { name: "eda_zoom_to_fit", description: "Zoom to fit all primitives in the active document.", inputSchema: objectSchema({ tabId: { type: "string" } }) },
1100
+ { name: "eda_zoom_to_region", description: "Zoom to a region. Schematic coordinates are MCP units.", inputSchema: objectSchema({ left: { type: "number" }, right: { type: "number" }, top: { type: "number" }, bottom: { type: "number" }, tabId: { type: "string" } }, ["left", "right", "top", "bottom"]) },
1101
+ { name: "eda_get_components", description: "List components on the active schematic page (or all pages). Returns designator, value, x, y, rotation and bounding box when available.", inputSchema: objectSchema({ allSchematicPages: { type: "boolean" }, includeBounds: { type: "boolean" } }) },
1102
+ { name: "eda_get_wires", description: "List wires on the active schematic page.", inputSchema: objectSchema({}) },
1103
+ { name: "eda_get_nets", description: "List nets of the current schematic project. Uses sch_Net.* first; when the schematic is not the active document those APIs return [] and this tool falls back to parsing sch_Netlist.getNetlist, reporting which source was used.", inputSchema: objectSchema({ name: { type: "string" }, parseNetlist: { type: "boolean" } }) },
1104
+ { name: "eda_get_active_document", description: "Return the document/tab that is currently active (documentType, uuid, tabId, parent project). Most tab-dependent APIs (sch_Net.*, netlist export, DRC) only work when the matching document is active - use eda_open_document to switch.", inputSchema: objectSchema({}) },
1105
+ { name: "eda_open_document", description: "Open/activate a document tab by uuid (dmt_EditorControl.openDocument). Works for a schematic page or a PCB, so tab-dependent APIs can run.", inputSchema: objectSchema({ documentUuid: { type: "string" }, splitScreenId: { type: "string" } }, ["documentUuid"]) },
1106
+ { name: "eda_get_net_labels", description: "List every label-like primitive on the active schematic page: attribute primitives (netlabel/netport/netflag) PLUS plain texts left by the createNetLabel fallback, so they can be audited and deleted. Reports kind/primitiveId/net per entry.", inputSchema: objectSchema({ parentPrimitiveId: { type: "string" } }) },
1107
+ { name: "eda_place_net_label", description: "Place a net label at x/y. The real API (sch_PrimitiveAttribute.createNetLabel) is probed once per session; when the build never answers, a plain TEXT label is placed instead, which carries no electrical meaning and must be paired with a stub wire. Pass probe:true to re-check.", inputSchema: objectSchema({ x: { type: "number" }, y: { type: "number" }, net: { type: "string" }, fontSize: { type: "number" }, rotation: { type: "integer", enum: [0, 90, 180, 270] }, probe: { type: "boolean" }, textLabel: { type: "boolean" } }, ["x", "y", "net"]) },
1108
+ { name: "eda_place_net_labels", description: "Place many net labels in ONE call (per-pin or by coordinate) and report done/failed per item: a 133-label schematic used to exceed the caller timeout with no progress. items: [{ pinPrimitiveId, net, stubLength?, offsetX?, offsetY? }] or [{ x, y, net, fontSize? }].", inputSchema: objectSchema({ items: { type: "array", items: { type: "object", additionalProperties: true } }, probe: { type: "boolean" }, textLabel: { type: "boolean" }, concurrency: { type: "integer", minimum: 1, maximum: 8 } }, ["items"]) },
1109
+ { name: "eda_run_drc", description: 'Run schematic DRC with includeVerboseError. On EDA 3.2.186 the app still returns AGGREGATED entries ({type:"warn",count:N}) with no primitiveId/coordinates, so entries are reported as-is and raw keeps the untouched payload; expect counts plus a hint until the app exposes details.', inputSchema: objectSchema({ strict: { type: "boolean" } }) },
1110
+ { name: "eda_auto_layout", description: "Run schematic auto-layout (sch_Document.autoLayout). DISABLED by default: automated layout is not used unless the user asks for it. Pass force:true only then.", inputSchema: objectSchema({ uuids: { type: "array", items: { type: "string" } }, force: { type: "boolean" } }) },
1111
+ { name: "eda_auto_route", description: "Run schematic auto-routing (sch_Document.autoRouting). DISABLED by default: route by hand unless the user explicitly asks. Pass force:true only then.", inputSchema: objectSchema({ uuids: { type: "array", items: { type: "string" } }, force: { type: "boolean" } }) },
1112
+ { name: "eda_export_netlist", description: "Export the schematic netlist as text (default JLCEDA format). Returns null when no schematic is active - check eda_get_active_document / open the schematic page first.", inputSchema: objectSchema({ type: { type: "string" } }) },
1113
+ { name: "eda_export_bom", description: "Export the schematic BOM. csv is decoded from UTF-16 to readable text; xlsx returns a base64 data URL.", inputSchema: objectSchema({ format: { type: "string", enum: ["csv", "xlsx"] } }) },
1114
+ { name: "eda_move_component", description: "Move/rotate/mirror a schematic component (sch_PrimitiveComponent.modify) without deleting and re-placing it, so the designator and value survive.", inputSchema: objectSchema({ primitiveId: { type: "string" }, x: { type: "number" }, y: { type: "number" }, rotation: { type: "number" }, mirror: { type: "boolean" } }, ["primitiveId"]) },
1115
+ { name: "pcb_draw_text", description: "Put text on a PCB layer - silkscreen by default (3 top silk / 4 bottom silk). Use it for pin functions, board markings, version and fabrication notes; silkscreen text must not cover pads.", inputSchema: objectSchema({ x: { type: "number" }, y: { type: "number" }, text: { type: "string" }, layer: { type: "string" }, fontSize: { type: "number" }, lineWidth: { type: "number" }, rotation: { type: "number" }, mirror: { type: "boolean" }, alignMode: { type: "integer" }, locked: { type: "boolean" } }, ["x", "y", "text"]) },
1116
+ { name: "pcb_draw_mounting_hole", description: 'Place a NON-plated mounting hole or a slot (pcb_PrimitivePad with metallization:false). shape "round" is a drill-sized hole, shape "slot" an oval cut-out. Use this for mounting holes and connector slots instead of hacking the board outline.', inputSchema: objectSchema({ x: { type: "number" }, y: { type: "number" }, diameter: { type: "number" }, shape: { type: "string", enum: ["round", "slot"] }, slotLength: { type: "number" }, rotation: { type: "number" }, plated: { type: "boolean" }, annulus: { type: "number" }, padNumber: { type: "string" }, layer: { type: "string" } }, ["x", "y", "diameter"]) },
1117
+ { name: "eda_schematic_audit", description: "Geometry audit of the active schematic page (the netlist ERC only judges connectivity): symbols outside the frame, symbols overlapping the title block, body-on-body symbol overlap, off-grid placement, and labels anchored inside a symbol body. Read-only; pair it with eda_netlist_erc before routing.", inputSchema: objectSchema({ grid: { type: "number" }, includeOk: { type: "boolean" } }) },
1118
+ { name: "eda_delivery_checklist", description: "Delivery checklist: run connectivity (eda_netlist_erc), PCB audit + DRC, Gerber export and BOM export in ONE read-only call and report per-step pass/fail with counts. It switches to the schematic and the PCB itself (switchDocuments:false keeps the current document and reports the other steps as skipped). verdict is pass / incomplete / fail; pass outPath to also write a Markdown report you can hand to a reviewer.", inputSchema: objectSchema({ outPath: { type: "string" }, pcbDrc: { type: "boolean" }, switchDocuments: { type: "boolean" } }) },
1119
+ { name: "eda_design_intake", description: "Requirement intake for a new board: call it BEFORE placing anything when the request is vague (for example: draw me an X board). Without answers it returns the questions in 6 sections (power, core, IO, mechanical, process, delivery), each marked critical or fallback-able with the reason it changes the drawing; pass answers:{questionId:value} to record them and see what is still missing. Ask the user with ask_user_question for the critical ones instead of guessing.", inputSchema: objectSchema({ answers: { type: "object", additionalProperties: true }, reset: { type: "boolean" } }) },
1120
+ { name: "eda_netlist_erc", description: "Read-only electrical smoke test over the schematic NETLIST (no application DRC needed): duplicate designators, unconnected pins, single-endpoint nets, shorted parts, power rails and decoupling, USB D+/D- pair, crystal (two nets + load caps + reaches the MCU), reset RC, BOOT pull resistor, Type-C CC pull-downs. DRC can be clean while the circuit is still wrong; these failures all show up in the netlist. Pass includeOk:true to see passing checks too.", inputSchema: objectSchema({ includeOk: { type: "boolean" } }) },
1121
+ { name: "eda_pcb_canvas_origin", description: "Read (or align) the PCB canvas origin and convert points between the two coordinate spaces. JLCEDA displays CANVAS coordinates in its UI but every API takes DATA coordinates; the two differ by this offset, so a coordinate read off the screen will land somewhere else unless you convert or align. align:true calls setCanvasOrigin(0,0) so the display matches the API.", inputSchema: objectSchema({ align: { type: "boolean" }, offsetX: { type: "number" }, offsetY: { type: "number" }, point: { type: "object", additionalProperties: true } }) },
1122
+ { name: "eda_capture", description: "Render the active document to a PNG (dmt_EditorControl.getCurrentRenderedAreaImage) and write it to outPath or return a data URL. Use it to LOOK at the sheet/board instead of trusting coordinate math. The PNG is a scratch file: read it, then call eda_capture({cleanup:true}) to delete every capture path this session wrote.", inputSchema: objectSchema({ outPath: { type: "string" }, inline: { type: "boolean" }, cleanup: { type: "boolean" } }) },
1123
+ { name: "eda_workflow_guide", description: "Return the schematic working standard: grid-aligned manual placement, signal flow, when net labels/ports are required (a wire net name is overridden by connectivity), net-label fallback behaviour, batch placement and the verification order. Read it before laying out a sheet.", inputSchema: objectSchema({}) },
1124
+ { name: "eda_extension_package", description: "Report the extension zip this plugin ships (absolute path, bytes, sha256) and, with download:true, fetch the copy served at the download base URL and compare the two byte for byte. On a match the served file is saved to outDir (default: the temp directory) so it can be imported into JLCEDA Pro; on a mismatch nothing is written and the tool says to re-upload. base defaults to DSH_EDA_EXTENSION_BASE or the project download server.", inputSchema: objectSchema({ download: { type: "boolean" }, outDir: { type: "string" }, base: { type: "string" } }, []) },
1125
+ { name: "eda_list_api_methods", description: "Ask the CONNECTED EXTENSION for the API methods it accepts right now (dsh.internal.listApiMethods) and report source/version/counts. Falls back to the bridge copy with stale:true only when the extension is an older zip. Use refresh:true to re-query.", inputSchema: objectSchema({ refresh: { type: "boolean" } }) },
1126
+ { name: "eda_delete_primitive", description: 'Delete a schematic primitive by kind and primitive id. Net ports, net flags and net labels are attribute primitives and need kind "netport"/"netflag"/"netlabel"; the text fallback labels are kind "text".', inputSchema: objectSchema({ kind: { type: "string", enum: ["component", "wire", "rectangle", "circle", "arc", "polygon", "text", "netport", "netflag", "netlabel"] }, primitiveId: { type: "string" } }, ["kind", "primitiveId"]) },
1127
+ { name: "eda_create_board", description: "Create a board linking a schematic and a PCB (dmt_Board.createBoard).", inputSchema: objectSchema({ schematicUuid: { type: "string" }, pcbUuid: { type: "string" } }) },
1128
+ { name: "eda_api_call", description: "Call an allow-listed JLCEDA Pro extension API method directly.", inputSchema: objectSchema({ method: { type: "string" }, args: { type: "array" } }, ["method", "args"]) },
1129
+ { name: "pcb_get_components", description: "List PCB components (mil). includePins=true also reads pcb_PrimitiveComponent.getAllPinsByPrimitiveId per component, which is the accurate pad/net source; the fast summary pad list can be stale.", inputSchema: objectSchema({ layer: { type: ["string", "integer"] }, locked: { type: "boolean" }, includeBounds: { type: "boolean" }, includePins: { type: "boolean" } }) },
1130
+ { name: "pcb_get_nets", description: "List PCB nets. Set detail=true for full net info.", inputSchema: objectSchema({ detail: { type: "boolean" }, name: { type: "string" } }) },
1131
+ { name: "pcb_get_layers", description: "List PCB layers.", inputSchema: objectSchema({}) },
1132
+ { name: "pcb_place_component", description: "Place a PCB component/footprint. Coordinates are mil.", inputSchema: objectSchema({ libraryUuid: { type: "string" }, uuid: { type: "string" }, layer: { type: ["string", "integer"] }, x: { type: "number" }, y: { type: "number" }, rotation: { type: "number" } }, ["libraryUuid", "uuid", "layer", "x", "y"]) },
1133
+ { name: "pcb_draw_track", description: "Draw a PCB track segment. Coordinates are mil. lineWidth defaults to the role-based rule value (signal 6 mil / power 16 mil / GND 16 mil) and is rejected below the 6 mil (0.15 mm) design minimum unless force=true.", inputSchema: objectSchema({ net: { type: "string" }, layer: { type: ["string", "integer"] }, startX: { type: "number" }, startY: { type: "number" }, endX: { type: "number" }, endY: { type: "number" }, lineWidth: { type: "number" }, force: { type: "boolean" } }, ["net", "layer", "startX", "startY", "endX", "endY"]) },
1134
+ { name: "pcb_draw_via", description: "Place a PCB via. Coordinates and sizes are mil. holeDiameter/diameter default to a standard drill pair (0.2/0.4 mm signal, 0.3/0.6 mm power); the annular ring must be >= 0.2 mm and the hole >= 0.2 mm, and a hole below 0.3 mm (free-prototyping bound) is reported as a warning.", inputSchema: objectSchema({ net: { type: "string" }, x: { type: "number" }, y: { type: "number" }, holeDiameter: { type: "number" }, diameter: { type: "number" }, viaType: { type: "integer", enum: [0, 1, 2] }, force: { type: "boolean" } }, ["net", "x", "y"]) },
1135
+ { name: "pcb_draw_board_outline", description: "Create a closed board outline on the BoardOutline layer (layer 11) from a flat [x1,y1,x2,y2,...] point list in mil. Implemented as ONE pcb_PrimitivePolyline built from a pcb_MathPolygon polygon - the primitive JLCEDA itself stores for a board outline. pcb_PrimitiveLine cannot create it (that API is a copper track and rejects layer 11).", inputSchema: objectSchema({ points: { type: "array", items: { type: "number" } }, lineWidth: { type: "number" }, net: { type: "string" }, locked: { type: "boolean" } }, ["points"]) },
1136
+ { name: "pcb_draw_polyline", description: "Create a closed polyline (pcb_PrimitivePolyline) on any line layer: board outline 11, silkscreen 3/4, assembly 9/10, mechanical 14, document 13, copper 1/2. points is a flat [x1,y1,x2,y2,...] array in mil and is closed automatically.", inputSchema: objectSchema({ points: { type: "array", items: { type: "number" } }, layer: { type: ["string", "integer"] }, net: { type: "string" }, lineWidth: { type: "number" }, locked: { type: "boolean" } }, ["points", "layer"]) },
1137
+ { name: "pcb_save_document", description: "Save the active PCB document.", inputSchema: objectSchema({}) },
1138
+ { name: "pcb_import_changes", description: "Import schematic changes into the active PCB (pcb_Document.importChanges). DEFAULT IS ASYNCHRONOUS because the call opens EDA own sync-confirmation dialog and blocks until the user answers it: the import runs as a background job, the tool returns immediately with componentsBefore, and the answer is detected by eda_pcb_wait_for_components. wait=true blocks instead (only when no dialog appears).", inputSchema: objectSchema({ schematicUuid: { type: "string" }, wait: { type: "boolean" }, timeoutMs: { type: "integer" } }) },
1139
+ { name: "eda_pcb_wait_for_components", description: 'Low-frequency poll (default every 5 s, minimum 3 s) that treats "new PCB components appeared" as "the user clicked OK in the schematic-sync confirmation dialog". Returns confirmed/waitedMs/newComponentIds, or confirmed=false after maxWaitMs (default 45 s) so the caller can ask the user and call again.', inputSchema: objectSchema({ pollIntervalMs: { type: "integer", minimum: 3e3 }, maxWaitMs: { type: "integer" }, baseline: { type: "array", items: { type: "string" } } }) },
1140
+ { name: "pcb_get_primitives_in_region", description: "List PCB primitives inside a region. Coordinates are mil.", inputSchema: objectSchema({ left: { type: "number" }, right: { type: "number" }, top: { type: "number" }, bottom: { type: "number" }, leftToRight: { type: "boolean" } }, ["left", "right", "top", "bottom"]) },
1141
+ { name: "pcb_navigate_to_region", description: "Navigate the PCB canvas to a region. Coordinates are mil.", inputSchema: objectSchema({ left: { type: "number" }, right: { type: "number" }, top: { type: "number" }, bottom: { type: "number" } }, ["left", "right", "top", "bottom"]) },
1142
+ // ---- eda_pcb_* aliases and new PCB tools ----
1143
+ { name: "eda_pcb_get_components", description: "Alias of pcb_get_components. List PCB components (mil).", inputSchema: objectSchema({ layer: { type: ["string", "integer"] }, locked: { type: "boolean" }, includeBounds: { type: "boolean" } }) },
1144
+ { name: "eda_pcb_get_nets", description: "Alias of pcb_get_nets.", inputSchema: objectSchema({ detail: { type: "boolean" }, name: { type: "string" } }) },
1145
+ { name: "eda_pcb_get_layers", description: "Alias of pcb_get_layers.", inputSchema: objectSchema({}) },
1146
+ { name: "eda_pcb_place_component", description: "Alias of pcb_place_component.", inputSchema: objectSchema({ libraryUuid: { type: "string" }, uuid: { type: "string" }, layer: { type: ["string", "integer"] }, x: { type: "number" }, y: { type: "number" }, rotation: { type: "number" } }, ["libraryUuid", "uuid", "layer", "x", "y"]) },
1147
+ { name: "eda_pcb_move_component", description: "Move/rotate/modify an existing PCB component (pcb_PrimitiveComponent.modify). Coordinates are mil.", inputSchema: objectSchema({ primitiveId: { type: "string" }, x: { type: "number" }, y: { type: "number" }, rotation: { type: "number" }, layer: { type: ["string", "integer"] }, locked: { type: "boolean" }, designator: { type: "string" }, name: { type: "string" } }, ["primitiveId"]) },
1148
+ { name: "eda_pcb_delete_component", description: "Delete a PCB component (pcb_PrimitiveComponent.delete).", inputSchema: objectSchema({ primitiveId: { type: "string" } }, ["primitiveId"]) },
1149
+ { name: "eda_pcb_draw_track", description: "Alias of pcb_draw_track.", inputSchema: objectSchema({ net: { type: "string" }, layer: { type: ["string", "integer"] }, startX: { type: "number" }, startY: { type: "number" }, endX: { type: "number" }, endY: { type: "number" }, lineWidth: { type: "number" } }, ["net", "layer", "startX", "startY", "endX", "endY"]) },
1150
+ { name: "eda_pcb_get_tracks", description: "List PCB tracks (pcb_PrimitiveLine.getAll). Optional net/layer/locked filters.", inputSchema: objectSchema({ net: { type: "string" }, layer: { type: ["string", "integer"] }, locked: { type: "boolean" } }) },
1151
+ { name: "eda_pcb_modify_track", description: "Modify a PCB track (pcb_PrimitiveLine.modify). Coordinates are mil.", inputSchema: objectSchema({ primitiveId: { type: "string" }, net: { type: "string" }, layer: { type: ["string", "integer"] }, startX: { type: "number" }, startY: { type: "number" }, endX: { type: "number" }, endY: { type: "number" }, lineWidth: { type: "number" }, locked: { type: "boolean" } }, ["primitiveId"]) },
1152
+ { name: "eda_pcb_delete_track", description: "Delete a PCB track (pcb_PrimitiveLine.delete).", inputSchema: objectSchema({ primitiveId: { type: "string" } }, ["primitiveId"]) },
1153
+ { name: "eda_pcb_draw_via", description: "Alias of pcb_draw_via.", inputSchema: objectSchema({ net: { type: "string" }, x: { type: "number" }, y: { type: "number" }, holeDiameter: { type: "number" }, diameter: { type: "number" }, viaType: { type: "integer", enum: [0, 1, 2] } }, ["net", "x", "y", "holeDiameter", "diameter"]) },
1154
+ { name: "eda_pcb_get_vias", description: "List PCB vias (pcb_PrimitiveVia.getAll). Optional net/locked filters.", inputSchema: objectSchema({ net: { type: "string" }, locked: { type: "boolean" } }) },
1155
+ { name: "eda_pcb_delete_via", description: "Delete a PCB via (pcb_PrimitiveVia.delete).", inputSchema: objectSchema({ primitiveId: { type: "string" } }, ["primitiveId"]) },
1156
+ { name: "eda_pcb_create_region", description: "Create a PCB region (pcb_PrimitiveRegion.create). points is a flat [x1,y1,x2,y2,...] array in mil and is closed automatically. Allowed layers are copper only: top(1), bottom(2), inner(15-44) and multi(12) - the official API type is TPCB_LayersOfRegion = copper | MULTI, so the board-outline layer (11) is rejected. ruleType uses EPCB_PrimitiveRegionRuleType: 2 noComponents, 5 noWires, 6 noFills, 7 noPours, 8 noInnerElectricalLayers, 9 followRegionRule.", inputSchema: objectSchema({ layer: { type: ["string", "integer"] }, points: { type: "array", items: { type: "number" } }, ruleType: { type: "array", items: { type: "integer" } }, regionName: { type: "string" }, lineWidth: { type: "number" }, locked: { type: "boolean" } }, ["layer", "points"]) },
1157
+ { name: "eda_pcb_draw_board_outline", description: "Alias-style name for pcb_draw_board_outline: draws a closed board outline as line segments on layer 11 (mil).", inputSchema: objectSchema({ points: { type: "array", items: { type: "number" } }, lineWidth: { type: "number" } }, ["points"]) },
1158
+ { name: "eda_pcb_get_polylines", description: "List PCB polylines (pcb_PrimitivePolyline.getAll) - board outline, silkscreen shapes, mechanical drawings. Optional net/layer/locked filters.", inputSchema: objectSchema({ net: { type: "string" }, layer: { type: ["string", "integer"] }, locked: { type: "boolean" } }) },
1159
+ { name: "eda_pcb_delete_polyline", description: "Delete a PCB polyline (pcb_PrimitivePolyline.delete).", inputSchema: objectSchema({ primitiveId: { type: "string" } }, ["primitiveId"]) },
1160
+ { name: "eda_pcb_clear_routing", description: "Clear PCB routing. DEFAULT IS A BACKGROUND JOB (pcb_Document.clearRouting): clearing a whole board easily exceeds the MCP timeout while EDA keeps working, so the tool returns immediately and you poll eda_pcb_job_status until running=false. With an older EDA extension it automatically degrades to bounded batches (see batchSize) that you repeat until done=true. type: all | net | connection (net/connection act on the current selection). mode=batched forces the batched path; net/layer filter it.", inputSchema: objectSchema({ type: { type: "string", enum: ["all", "net", "connection"] }, wait: { type: "boolean" }, mode: { type: "string", enum: ["native", "batched"] }, net: { type: "string" }, layer: { type: ["string", "integer"] }, batchSize: { type: "integer", minimum: 1, maximum: 2e3 }, timeoutMs: { type: "integer" } }) },
1161
+ { name: "eda_pcb_create_pour", description: "Create a copper pour (\u8986\u94DC, pcb_MathPolygon.createPolygon + pcb_PrimitivePour.create). points is a flat [x1,y1,x2,y2,...] array in mil, closed automatically. layer must be a copper layer (top 1 / bottom 2 / inner 15-44). pourFillMethod: 45grid | 90grid | solid.", inputSchema: objectSchema({ net: { type: "string" }, layer: { type: ["string", "integer"] }, points: { type: "array", items: { type: "number" } }, pourFillMethod: { type: "string", enum: ["45grid", "90grid", "solid"] }, preserveSilos: { type: "boolean" }, pourName: { type: "string" }, pourPriority: { type: "integer" }, lineWidth: { type: "number" }, locked: { type: "boolean" } }, ["net", "layer", "points"]) },
1162
+ { name: "eda_pcb_get_pours", description: "List PCB copper pours (pcb_PrimitivePour.getAll). Optional net/layer/locked filters.", inputSchema: objectSchema({ net: { type: "string" }, layer: { type: ["string", "integer"] }, locked: { type: "boolean" } }) },
1163
+ { name: "eda_pcb_delete_pour", description: "Delete a copper pour (pcb_PrimitivePour.delete).", inputSchema: objectSchema({ primitiveId: { type: "string" } }, ["primitiveId"]) },
1164
+ { name: "eda_pcb_run_drc", description: "Run PCB DRC (pcb_Drc.check). includeVerboseError=true returns the verbose error array (strict=true also reports warnings). Set userInterface=true only if the user should see the DRC panel.", inputSchema: objectSchema({ strict: { type: "boolean" }, userInterface: { type: "boolean" }, includeVerboseError: { type: "boolean" } }) },
1165
+ { name: "eda_pcb_get_drc_rules", description: "Return the current PCB DRC rule configuration name and content.", inputSchema: objectSchema({}) },
1166
+ { name: "eda_pcb_set_net_track_width", description: "Set the track width of every existing track of one net (iterates pcb_PrimitiveLine.getAll + pcb_PrimitiveLine.modify). Use it to thicken power/GND nets after auto-routing.", inputSchema: objectSchema({ net: { type: "string" }, lineWidth: { type: "number" }, layer: { type: ["string", "integer"] } }, ["net", "lineWidth"]) },
1167
+ { name: "eda_design_audit", description: "Read-only audit of the active PCB against docs/design-rules.md: per-net track widths (min 6 mil, role suggestions), via drill/annular ring, net-name legality, board outline, copper pour, and PCB DRC. Returns violations, warnings, a checklist, the per-net minimum widths, and the rule values used. drc=false skips the DRC run.", inputSchema: objectSchema({ net: { type: "string" }, drc: { type: "boolean" } }) },
1168
+ { name: "eda_pcb_get_regions", description: "List PCB regions (pcb_PrimitiveRegion.getAll). layer must be a copper layer (top 1 / bottom 2 / inner 15-44) or MULTI 12.", inputSchema: objectSchema({ layer: { type: ["string", "integer"] }, ruleType: { type: "array", items: { type: "integer" } }, locked: { type: "boolean" } }) },
1169
+ { name: "eda_pcb_delete_region", description: "Delete a PCB region (pcb_PrimitiveRegion.delete).", inputSchema: objectSchema({ primitiveId: { type: "string" } }, ["primitiveId"]) },
1170
+ { name: "eda_pcb_auto_place", description: "Run PCB auto-layout (pcb_Document.autoLayout). Blocking by default (layout is fast); pass wait=false to start it as a background job and poll eda_pcb_job_status.", inputSchema: objectSchema({ wait: { type: "boolean" }, timeoutMs: { type: "integer" } }) },
1171
+ { name: "eda_pcb_job_status", description: "Poll the background PCB job started by eda_pcb_auto_route (or eda_pcb_auto_place with wait=false): running, elapsedMs, result, error. EDA keeps its own progress bar while running.", inputSchema: objectSchema({}) },
1172
+ { name: "eda_pcb_auto_route", description: "Start PCB auto-routing (pcb_Document.autoRouting). DEFAULT IS ASYNCHRONOUS: the call returns as soon as EDA starts routing (EDA shows its own progress bar) and you poll eda_pcb_job_status until running=false - a long routing job must NOT be awaited, otherwise the MCP call times out while EDA keeps working. Without nets/RoutingNets the bridge enumerates every net, because this EDA build fails every net (success=false, duration=0) when routingRange is empty. wait=true blocks until done (only for small jobs). cornerStyle: 0=45deg, 1=90deg; optimization: 1=completion, 0=faster; existingPrimitiveMode: keep|remove.", inputSchema: objectSchema({ nets: { type: "array", items: { type: "string" } }, RoutingNets: { type: ["array", "string"] }, ignoreNets: { type: "array", items: { type: "string" } }, layers: { type: "array", items: { type: "integer" } }, cornerStyle: { type: "integer", enum: [0, 1] }, optimization: { type: "integer", enum: [0, 1] }, existingPrimitiveMode: { type: "string", enum: ["keep", "remove"] }, wait: { type: "boolean" }, timeoutMs: { type: "integer" }, props: { type: "object" } }) },
1173
+ { name: "eda_pcb_export_gerber", description: "Export PCB Gerber (pcb_ManufactureData.getGerberFile). Returns { name, size, dataUrl } - the zip is base64 encoded, so large boards can produce a big payload.", inputSchema: objectSchema({ fileName: { type: "string" }, colorSilkscreen: { type: "boolean" }, unit: { type: "string", enum: ["mm", "inch"] }, integerNumber: { type: "integer" }, decimalNumber: { type: "integer" }, other: { type: "object" }, layers: { type: "array" }, objects: { type: "array" } }) },
1174
+ { name: "eda_pcb_save_document", description: "Alias of pcb_save_document.", inputSchema: objectSchema({}) },
1175
+ { name: "eda_pcb_import_changes", description: "Alias of pcb_import_changes.", inputSchema: objectSchema({ schematicUuid: { type: "string" } }) },
1176
+ { name: "eda_pcb_get_primitives_in_region", description: "Alias of pcb_get_primitives_in_region.", inputSchema: objectSchema({ left: { type: "number" }, right: { type: "number" }, top: { type: "number" }, bottom: { type: "number" }, leftToRight: { type: "boolean" } }, ["left", "right", "top", "bottom"]) },
1177
+ { name: "eda_pcb_navigate_to_region", description: "Alias of pcb_navigate_to_region.", inputSchema: objectSchema({ left: { type: "number" }, right: { type: "number" }, top: { type: "number" }, bottom: { type: "number" } }, ["left", "right", "top", "bottom"]) }
1178
+ ];
1179
+ function toolResult(value) {
1180
+ return { content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }] };
1181
+ }
1182
+ function toolError(message) {
1183
+ return { content: [{ type: "text", text: message }], isError: true };
1184
+ }
1185
+ var WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1186
+ function parseFrame(buffer) {
1187
+ if (buffer.length < 2) return void 0;
1188
+ const fin = (buffer[0] & 128) !== 0;
1189
+ const opcode = buffer[0] & 15;
1190
+ const masked = (buffer[1] & 128) !== 0;
1191
+ let length = buffer[1] & 127;
1192
+ let offset = 2;
1193
+ if (length === 126) {
1194
+ if (buffer.length < offset + 2) return void 0;
1195
+ length = buffer.readUInt16BE(offset);
1196
+ offset += 2;
1197
+ } else if (length === 127) {
1198
+ if (buffer.length < offset + 8) return void 0;
1199
+ const big = buffer.readBigUInt64BE(offset);
1200
+ if (big > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error("websocket frame too large");
1201
+ length = Number(big);
1202
+ offset += 8;
1203
+ }
1204
+ let maskKey;
1205
+ if (masked) {
1206
+ if (buffer.length < offset + 4) return void 0;
1207
+ maskKey = buffer.subarray(offset, offset + 4);
1208
+ offset += 4;
1209
+ }
1210
+ if (buffer.length < offset + length) return void 0;
1211
+ const payload = Buffer.from(buffer.subarray(offset, offset + length));
1212
+ if (maskKey !== void 0) {
1213
+ for (let i = 0; i < payload.length; i++) payload[i] ^= maskKey[i % 4];
1214
+ }
1215
+ return { fin, opcode, payload, consumed: offset + length };
1216
+ }
1217
+ function encodeFrame(opcode, payload, fin = true) {
1218
+ const header = Buffer.alloc(payload.length < 126 ? 2 : payload.length < 65536 ? 4 : 10);
1219
+ header[0] = (fin ? 128 : 0) | opcode;
1220
+ if (payload.length < 126) header[1] = payload.length;
1221
+ else if (payload.length < 65536) {
1222
+ header[1] = 126;
1223
+ header.writeUInt16BE(payload.length, 2);
1224
+ } else {
1225
+ header[1] = 127;
1226
+ header.writeBigUInt64BE(BigInt(payload.length), 2);
1227
+ }
1228
+ return Buffer.concat([header, payload]);
1229
+ }
1230
+ var WsConnection = class {
1231
+ constructor(socket) {
1232
+ this.socket = socket;
1233
+ this.ready = false;
1234
+ this.buffer = Buffer.alloc(0);
1235
+ this.fragments = [];
1236
+ }
1237
+ sendText(text) {
1238
+ if (this.socket.destroyed) return;
1239
+ this.socket.write(encodeFrame(1, Buffer.from(text, "utf8")));
1240
+ }
1241
+ sendControl(opcode, payload) {
1242
+ if (this.socket.destroyed) return;
1243
+ this.socket.write(encodeFrame(opcode, payload));
1244
+ }
1245
+ close() {
1246
+ try {
1247
+ this.sendControl(8, Buffer.alloc(0));
1248
+ } catch {
1249
+ }
1250
+ this.socket.destroy();
1251
+ }
1252
+ handleData(chunk) {
1253
+ this.lastSeenAt = Date.now();
1254
+ this.buffer = Buffer.concat([this.buffer, chunk]);
1255
+ for (; ; ) {
1256
+ const frame = parseFrame(this.buffer);
1257
+ if (frame === void 0) return;
1258
+ this.buffer = this.buffer.subarray(frame.consumed);
1259
+ this.handleFrame(frame);
1260
+ }
1261
+ }
1262
+ handleFrame(frame) {
1263
+ if (frame.opcode === 8) {
1264
+ this.close();
1265
+ return;
1266
+ }
1267
+ if (frame.opcode === 9) {
1268
+ this.sendControl(10, frame.payload);
1269
+ return;
1270
+ }
1271
+ if (frame.opcode === 10) return;
1272
+ if (frame.opcode === 0 || frame.opcode === 1 || frame.opcode === 2) {
1273
+ this.fragments.push(frame.payload);
1274
+ if (!frame.fin) return;
1275
+ const payload = Buffer.concat(this.fragments);
1276
+ this.fragments = [];
1277
+ if (frame.opcode === 1 || frame.opcode === 0) this.emitText(payload.toString("utf8"));
1278
+ }
1279
+ }
1280
+ emitText(text) {
1281
+ let message;
1282
+ try {
1283
+ message = JSON.parse(text);
1284
+ } catch {
1285
+ return;
1286
+ }
1287
+ if (message === null || typeof message !== "object") return;
1288
+ if (message.type === "hello") {
1289
+ this.ready = true;
1290
+ if (typeof message.version === "string") this.extensionVersion = message.version;
1291
+ return;
1292
+ }
1293
+ if (message.type === "ping") {
1294
+ this.sendText(JSON.stringify({ type: "pong" }));
1295
+ return;
1296
+ }
1297
+ if (typeof message.id === "number" && typeof message.ok === "boolean") {
1298
+ const pending = pendingCalls.get(message.id);
1299
+ if (pending === void 0) return;
1300
+ pendingCalls.delete(message.id);
1301
+ clearTimeout(pending.timer);
1302
+ if (message.ok) pending.resolve(message.result);
1303
+ else pending.reject(new Error(message.error && message.error.message ? message.error.message : "JLCEDA bridge call failed"));
1304
+ }
1305
+ }
1306
+ };
1307
+ var clients = /* @__PURE__ */ new Set();
1308
+ var pendingCalls = /* @__PURE__ */ new Map();
1309
+ var pcbComponentBaseline = null;
1310
+ var netLabelSupport = null;
1311
+ var placedTextLabels = [];
1312
+ function sleep(ms) {
1313
+ return new Promise((resolve) => setTimeout(resolve, ms));
1314
+ }
1315
+ async function pcbComponentIds(timeoutMs) {
1316
+ const raw = await callExtension("pcb_PrimitiveComponent.getAllPrimitiveId", [], timeoutMs);
1317
+ return Array.isArray(raw) ? raw.map(String) : [];
1318
+ }
1319
+ var nextCallId = 1;
1320
+ var extensionApiCache = null;
1321
+ var designBrief = null;
1322
+ var capturedFiles = [];
1323
+ async function extensionApiMethods(timeoutMs, refresh = false) {
1324
+ if (!refresh && extensionApiCache !== null) return extensionApiCache;
1325
+ try {
1326
+ const raw = await callExtension("dsh.internal.listApiMethods", [], Math.min(timeoutMs, 5e3));
1327
+ const record = asRecord(raw);
1328
+ const allowed = Array.isArray(record.allowed) ? record.allowed.map(String) : [];
1329
+ const files = Array.isArray(record.files) ? record.files.map(String) : [];
1330
+ if (allowed.length === 0 && files.length === 0) return void 0;
1331
+ extensionApiCache = {
1332
+ version: typeof record.version === "string" ? record.version : null,
1333
+ allowed,
1334
+ files,
1335
+ all: [...allowed, ...files].sort(),
1336
+ allowedSet: new Set(allowed),
1337
+ fileSet: new Set(files)
1338
+ };
1339
+ return extensionApiCache;
1340
+ } catch {
1341
+ return void 0;
1342
+ }
1343
+ }
1344
+ var CLIENT_STALE_MS = 6e4;
1345
+ function pickClients() {
1346
+ const now = Date.now();
1347
+ const ready = [...clients].filter((client) => client.ready);
1348
+ const fresh = ready.filter((client) => now - (client.lastSeenAt ?? 0) < CLIENT_STALE_MS);
1349
+ const pool = fresh.length > 0 ? fresh : ready;
1350
+ return pool.sort((left, right) => (right.lastSeenAt ?? 0) - (left.lastSeenAt ?? 0));
1351
+ }
1352
+ function isIdempotentRead(method) {
1353
+ const fn = method.slice(method.lastIndexOf(".") + 1).toLowerCase();
1354
+ return fn.startsWith("get") || fn.startsWith("is") || fn.startsWith("has") || fn.startsWith("list") || fn.startsWith("search");
1355
+ }
1356
+ function sendToClient(client, method, args, timeoutMs) {
1357
+ const id = nextCallId++;
1358
+ return new Promise((resolve, reject) => {
1359
+ const timer = setTimeout(() => {
1360
+ pendingCalls.delete(id);
1361
+ reject(new Error("JLCEDA bridge call timed out after " + timeoutMs + "ms: " + method));
1362
+ }, timeoutMs);
1363
+ pendingCalls.set(id, { resolve, reject, timer });
1364
+ client.sendText(JSON.stringify({ id, method, args }));
1365
+ });
1366
+ }
1367
+ async function callExtension(method, args, timeoutMs) {
1368
+ const pool = pickClients();
1369
+ if (pool.length === 0) {
1370
+ throw new Error("JLCEDA bridge extension is not connected. Open JLCEDA Pro, import dsh-eda-bridge-extension-" + VERSION + '.zip, enable "Allow interactive with external", and keep a schematic or PCB page open.');
1371
+ }
1372
+ const deadline = Date.now() + timeoutMs;
1373
+ let lastError;
1374
+ for (const client of pool) {
1375
+ const remaining = deadline - Date.now();
1376
+ if (remaining <= 100) break;
1377
+ try {
1378
+ return await sendToClient(client, method, args, remaining);
1379
+ } catch (error) {
1380
+ lastError = error;
1381
+ if (!isIdempotentRead(method) || !/timed out/.test(String(error?.message))) throw error;
1382
+ }
1383
+ }
1384
+ throw lastError ?? new Error("JLCEDA bridge call timed out after " + timeoutMs + "ms: " + method);
1385
+ }
1386
+ function asRecord(value) {
1387
+ if (value === null || typeof value !== "object") return {};
1388
+ return value;
1389
+ }
1390
+ function flattenPoints(points) {
1391
+ const flat = [];
1392
+ if (!Array.isArray(points)) return flat;
1393
+ for (const item of points) {
1394
+ if (Array.isArray(item)) flat.push(...item.map(Number));
1395
+ else flat.push(Number(item));
1396
+ }
1397
+ return flat;
1398
+ }
1399
+ function primitiveKindToClass(kind) {
1400
+ switch (kind) {
1401
+ case "component":
1402
+ return "sch_PrimitiveComponent";
1403
+ case "wire":
1404
+ return "sch_PrimitiveWire";
1405
+ case "rectangle":
1406
+ return "sch_PrimitiveRectangle";
1407
+ case "circle":
1408
+ return "sch_PrimitiveCircle";
1409
+ case "arc":
1410
+ return "sch_PrimitiveArc";
1411
+ case "polygon":
1412
+ return "sch_PrimitivePolygon";
1413
+ case "text":
1414
+ return "sch_PrimitiveText";
1415
+ default:
1416
+ throw new Error("unknown primitive kind: " + kind);
1417
+ }
1418
+ }
1419
+ function pickValue(raw, ...keys) {
1420
+ for (const key of keys) {
1421
+ if (raw && raw[key] !== void 0 && raw[key] !== null) return raw[key];
1422
+ }
1423
+ return void 0;
1424
+ }
1425
+ function summarizePrimitive(raw) {
1426
+ if (raw === null || typeof raw !== "object") return { value: raw };
1427
+ const summary = {};
1428
+ const primitiveId = pickValue(raw, "PrimitiveId", "primitiveId", "$id");
1429
+ const primitiveType = pickValue(raw, "PrimitiveType", "primitiveType");
1430
+ const x = pickValue(raw, "X", "x", "CenterX", "centerX", "StartX", "startX");
1431
+ const y = pickValue(raw, "Y", "y", "CenterY", "centerY", "StartY", "startY");
1432
+ const rotation = pickValue(raw, "Rotation", "rotation");
1433
+ if (primitiveId !== void 0) summary.primitiveId = primitiveId;
1434
+ if (primitiveType !== void 0) summary.primitiveType = primitiveType;
1435
+ if (x !== void 0) summary.x = x;
1436
+ if (y !== void 0) summary.y = y;
1437
+ if (rotation !== void 0) summary.rotation = rotation;
1438
+ for (const key of ["Designator", "Name", "Content", "Net", "ComponentType", "Layer", "LayerId"]) {
1439
+ const value2 = raw[key];
1440
+ if (value2 !== void 0) summary[key.charAt(0).toLowerCase() + key.slice(1)] = value2;
1441
+ }
1442
+ const other = raw.OtherProperty ?? raw.otherProperty;
1443
+ if (other !== void 0) summary.otherProperty = other;
1444
+ const value = (other && (other.Value ?? other.value)) ?? raw.Value;
1445
+ if (value !== void 0) summary.value = value;
1446
+ return summary;
1447
+ }
1448
+ async function mapLimit(items, limit, fn) {
1449
+ const results = new Array(items.length);
1450
+ let cursor = 0;
1451
+ const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
1452
+ for (; ; ) {
1453
+ const index = cursor++;
1454
+ if (index >= items.length) return;
1455
+ results[index] = await fn(items[index], index);
1456
+ }
1457
+ });
1458
+ await Promise.all(workers);
1459
+ return results;
1460
+ }
1461
+ function extractPrimitiveId(result2) {
1462
+ if (result2 === null || typeof result2 !== "object") return void 0;
1463
+ return pickValue(result2, "PrimitiveId", "primitiveId");
1464
+ }
1465
+ async function bboxOf(primitiveIds, timeoutMs) {
1466
+ if (primitiveIds.length === 0) return void 0;
1467
+ const raw = await callExtension("sch_Primitive.getPrimitivesBBox", [primitiveIds], timeoutMs);
1468
+ if (raw === null || typeof raw !== "object") return void 0;
1469
+ const minX = Number(raw.minX);
1470
+ const minY = Number(raw.minY);
1471
+ const maxX = Number(raw.maxX);
1472
+ const maxY = Number(raw.maxY);
1473
+ if (![minX, minY, maxX, maxY].every(Number.isFinite)) return void 0;
1474
+ return { minX, minY, maxX, maxY };
1475
+ }
1476
+ var PCB_LAYERS = {
1477
+ top: 1,
1478
+ bottom: 2,
1479
+ topSilkscreen: 3,
1480
+ bottomSilkscreen: 4,
1481
+ topSolderMask: 5,
1482
+ bottomSolderMask: 6,
1483
+ topPasteMask: 7,
1484
+ bottomPasteMask: 8,
1485
+ topAssembly: 9,
1486
+ bottomAssembly: 10,
1487
+ boardOutline: 11,
1488
+ multi: 12,
1489
+ document: 13,
1490
+ mechanical: 14
1491
+ };
1492
+ function resolvePcbLayer(value) {
1493
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1494
+ if (typeof value === "string") {
1495
+ const key = value.trim();
1496
+ if (/^[0-9]+$/.test(key)) return Number(key);
1497
+ const lower = key.charAt(0).toLowerCase() + key.slice(1);
1498
+ if (PCB_LAYERS[lower] !== void 0) return PCB_LAYERS[lower];
1499
+ const upper = key.toUpperCase();
1500
+ if (upper === "TOP") return 1;
1501
+ if (upper === "BOTTOM") return 2;
1502
+ if (upper === "BOARD_OUTLINE") return 11;
1503
+ }
1504
+ return void 0;
1505
+ }
1506
+ var PCB_TOOL_ALIASES = {
1507
+ eda_pcb_get_components: "pcb_get_components",
1508
+ eda_pcb_get_nets: "pcb_get_nets",
1509
+ eda_pcb_get_layers: "pcb_get_layers",
1510
+ eda_pcb_place_component: "pcb_place_component",
1511
+ eda_pcb_draw_track: "pcb_draw_track",
1512
+ eda_pcb_draw_via: "pcb_draw_via",
1513
+ eda_pcb_save_document: "pcb_save_document",
1514
+ eda_pcb_import_changes: "pcb_import_changes",
1515
+ eda_pcb_get_primitives_in_region: "pcb_get_primitives_in_region",
1516
+ eda_pcb_navigate_to_region: "pcb_navigate_to_region",
1517
+ eda_pcb_draw_board_outline: "pcb_draw_board_outline"
1518
+ };
1519
+ function isRegionLayer(layer) {
1520
+ return layer === 1 || layer === 2 || layer === 12 || layer >= 15 && layer <= 44;
1521
+ }
1522
+ function resolveRegionLayer(value, tool) {
1523
+ const layer = resolvePcbLayer(value);
1524
+ if (layer === void 0) throw new Error(tool + " requires a valid layer");
1525
+ if (!isRegionLayer(layer)) {
1526
+ throw new Error(tool + ": layer " + layer + " cannot hold a region (official type TPCB_LayersOfRegion = copper top/bottom/inner(15-44) | MULTI(12))");
1527
+ }
1528
+ return layer;
1529
+ }
1530
+ var BRIEF_TAG = "[dsh-eda-spec]";
1531
+ function briefBlock(brief) {
1532
+ return BRIEF_TAG + " " + JSON.stringify(brief);
1533
+ }
1534
+ function specFilePath(project) {
1535
+ const dir = String(project?.teamUuid ?? "");
1536
+ const uuid2 = String(project?.uuid ?? "");
1537
+ if (dir === "" || uuid2 === "") return "";
1538
+ if (!/^[A-Za-z]:[\\/]/.test(dir) && !dir.startsWith("/")) return "";
1539
+ return join(dir, ".dsh-eda-spec", uuid2 + ".json");
1540
+ }
1541
+ function parseBriefBlock(description) {
1542
+ const text = typeof description === "string" ? description : "";
1543
+ const index = text.indexOf(BRIEF_TAG);
1544
+ if (index < 0) return null;
1545
+ const body = text.slice(index + BRIEF_TAG.length).trim();
1546
+ const close = body.indexOf("}");
1547
+ try {
1548
+ const parsed = JSON.parse(close < 0 ? body : body.slice(0, close + 1));
1549
+ return parsed !== null && typeof parsed === "object" ? parsed : null;
1550
+ } catch {
1551
+ return null;
1552
+ }
1553
+ }
1554
+ async function fetchParsedNetlist(timeoutMs) {
1555
+ const payload = await callExtension("sch_ManufactureData.getNetlistFile", [void 0, void 0], timeoutMs);
1556
+ const text = typeof payload === "string" ? payload : payload !== null && typeof payload === "object" && typeof payload.text === "string" ? payload.text : void 0;
1557
+ if (text === void 0) return null;
1558
+ try {
1559
+ return JSON.parse(text);
1560
+ } catch {
1561
+ return null;
1562
+ }
1563
+ }
1564
+ function buildPolygonSource(points) {
1565
+ const source = [points[0], points[1], "L"];
1566
+ for (let i = 2; i < points.length; i += 2) source.push(points[i], points[i + 1]);
1567
+ return source;
1568
+ }
1569
+ function packageRoot() {
1570
+ return fileURLToPath(new URL("../", import.meta.url));
1571
+ }
1572
+ function requireFlatPoints(value, tool) {
1573
+ const points = flattenPoints(value);
1574
+ if (points.length < 6 || points.length % 2 !== 0 || !points.every(Number.isFinite)) {
1575
+ throw new Error(tool + ": points must be a flat array of finite numbers shaped [x1,y1,x2,y2,...] with at least 3 points");
1576
+ }
1577
+ if (points.length >= 8 && points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) {
1578
+ points.length -= 2;
1579
+ }
1580
+ return points;
1581
+ }
1582
+ function pinDirection(rotation) {
1583
+ const normalized = (Math.round(Number(rotation) / 90) * 90 % 360 + 360) % 360;
1584
+ if (normalized === 90) return { dx: 0, dy: 1 };
1585
+ if (normalized === 180) return { dx: -1, dy: 0 };
1586
+ if (normalized === 270) return { dx: 0, dy: -1 };
1587
+ return { dx: 1, dy: 0 };
1588
+ }
1589
+ var DOCUMENT_TYPES = {
1590
+ "-1": "HOME",
1591
+ 0: "BLANK",
1592
+ 1: "SCHEMATIC_PAGE",
1593
+ 2: "SYMBOL_COMPONENT",
1594
+ 3: "PCB",
1595
+ 5: "PROJECT",
1596
+ 12: "PCB_2D_PREVIEW",
1597
+ 15: "PCB_3D_PREVIEW",
1598
+ 18: "SYMBOL_NET_FLAG",
1599
+ 19: "SYMBOL_NET_PORT",
1600
+ 20: "SYMBOL_DRAWING",
1601
+ 21: "SYMBOL_NON_ELECTRICAL",
1602
+ 26: "PANEL",
1603
+ 27: "PANEL_3D_PREVIEW"
1604
+ };
1605
+ var NET_EMPTY_HINT = "sch_Net.* returned no nets. Those APIs only report the ACTIVE document, so the schematic page must be the active tab: call eda_get_active_document, then eda_open_document with the schematic page uuid (eda_get_schematic_pages) and retry.";
1606
+ async function pcbPrimitiveList(method, callArgs, timeoutMs) {
1607
+ try {
1608
+ const raw = await callExtension(method, callArgs, timeoutMs);
1609
+ return Array.isArray(raw) ? raw : [];
1610
+ } catch (error) {
1611
+ const message = error instanceof Error ? error.message : String(error);
1612
+ if (/null|undefined|map/i.test(message)) {
1613
+ throw new Error("PCB primitives could not be read (" + message + "). The PCB document is probably not the active tab: bring the PCB page to the front (eda_get_active_document / eda_open_document) and retry.");
1614
+ }
1615
+ throw error;
1616
+ }
1617
+ }
1618
+ async function auditPcb(args, timeoutMs) {
1619
+ const netFilter = args.net === void 0 ? void 0 : String(args.net);
1620
+ const tracks = await pcbPrimitiveList("pcb_PrimitiveLine.getAll", [netFilter, void 0, void 0], timeoutMs);
1621
+ const vias = await pcbPrimitiveList("pcb_PrimitiveVia.getAll", [netFilter, void 0], timeoutMs);
1622
+ const pours = await pcbPrimitiveList("pcb_PrimitivePour.getAll", [netFilter, void 0, void 0], timeoutMs);
1623
+ const outline = await pcbPrimitiveList("pcb_PrimitivePolyline.getAll", [void 0, PCB_LAYERS.boardOutline, void 0], timeoutMs);
1624
+ const pcbComponents = await callExtension("pcb_PrimitiveComponent.getAll", [resolvePcbLayer(void 0), void 0], timeoutMs).then((raw) => Array.isArray(raw) ? raw : []).catch(() => []);
1625
+ const violations = [];
1626
+ const warnings = [];
1627
+ const add = (bucket, rule, message, samples) => {
1628
+ const entry = bucket.find((item) => item.rule === rule);
1629
+ if (entry === void 0) bucket.push({ rule, message, count: 1, samples: samples.slice(0, 5) });
1630
+ else {
1631
+ entry.count += 1;
1632
+ if (entry.samples.length < 5) entry.samples.push(samples[0]);
1633
+ }
1634
+ };
1635
+ const widthByNet = /* @__PURE__ */ new Map();
1636
+ for (const track of tracks) {
1637
+ const record = asRecord(track);
1638
+ const net = String(pickValue(record, "Net", "net") ?? "");
1639
+ const width = Number(pickValue(record, "LineWidth", "lineWidth"));
1640
+ if (!Number.isFinite(width) || width <= 0) continue;
1641
+ const seen = widthByNet.get(net);
1642
+ if (seen === void 0 || width < seen) widthByNet.set(net, width);
1643
+ const check = checkTrackWidth(net, width, false);
1644
+ if (!check.ok) add(violations, "track-width-min", check.errors.join("; "), [pickValue(record, "PrimitiveId", "primitiveId")]);
1645
+ else if (check.warnings.length > 0) add(warnings, "track-width-role", check.warnings.join("; "), [pickValue(record, "PrimitiveId", "primitiveId")]);
1646
+ }
1647
+ for (const via of vias) {
1648
+ const record = asRecord(via);
1649
+ const net = String(pickValue(record, "Net", "net") ?? "");
1650
+ const hole = Number(pickValue(record, "HoleDiameter", "holeDiameter"));
1651
+ const pad = Number(pickValue(record, "Diameter", "diameter"));
1652
+ if (!Number.isFinite(hole) || !Number.isFinite(pad)) continue;
1653
+ const check = checkVia(net, hole, pad, false);
1654
+ if (!check.ok) add(violations, "via-geometry", check.errors.join("; "), [pickValue(record, "PrimitiveId", "primitiveId")]);
1655
+ else if (check.warnings.length > 0) add(warnings, "via-standard", check.warnings.join("; "), [pickValue(record, "PrimitiveId", "primitiveId")]);
1656
+ }
1657
+ let netNames = [];
1658
+ try {
1659
+ netNames = await callExtension("pcb_Net.getAllNetsName", [], timeoutMs);
1660
+ } catch {
1661
+ netNames = [];
1662
+ }
1663
+ if (!Array.isArray(netNames)) netNames = [];
1664
+ for (const name of netNames) {
1665
+ const text = String(name);
1666
+ const check = checkNetName(text);
1667
+ if (!check.ok) add(violations, "net-name", check.errors.join("; "), [text]);
1668
+ else if (check.warnings.length > 0) add(warnings, "net-name-style", check.warnings.join("; "), [text]);
1669
+ }
1670
+ if (outline.length === 0) violations.push({ rule: "board-outline", message: "No board outline on layer 11: auto-routing and Gerber export need a closed outline (pcb_draw_board_outline)", count: 1, samples: [] });
1671
+ if (pours.length === 0) warnings.push({ rule: "copper-pour", message: "No copper pour: a GND pour on the top/bottom layer is the recommended way to carry ground (eda_pcb_create_pour)", count: 1, samples: [] });
1672
+ try {
1673
+ const silk = await callExtension("pcb_PrimitiveString.getAll", [PCB_LAYERS.topSilkscreen], timeoutMs);
1674
+ const silkCount = Array.isArray(silk) ? silk.length : 0;
1675
+ if (silkCount === 0) {
1676
+ warnings.push({ rule: "silkscreen-text", message: "No silkscreen text primitive: the official example board carries 19 (function labels, version, fab notes). Add board identity and pin functions with pcb_draw_text." });
1677
+ }
1678
+ } catch {
1679
+ }
1680
+ try {
1681
+ const pads = await callExtension("pcb_PrimitivePad.getAll", [PCB_LAYERS.multi], timeoutMs);
1682
+ const holes = (Array.isArray(pads) ? pads : []).filter((pad) => (pad?.metallization ?? pad?.Metallization) === false);
1683
+ const flatX = [];
1684
+ for (const entry of outline) {
1685
+ const source = entry?.polygon?.polygon ?? entry?.Polygon?.polygon ?? [];
1686
+ for (let i = 0; i + 1 < source.length; i += 2) {
1687
+ if (typeof source[i] === "number") flatX.push(source[i]);
1688
+ }
1689
+ }
1690
+ const wide = flatX.length > 0 ? Math.max(...flatX) - Math.min(...flatX) : 0;
1691
+ if (holes.length === 0 && wide > 1200) {
1692
+ warnings.push({ rule: "mounting-hole", message: "No non-plated mounting hole on a board wider than 1200 mil: use pcb_draw_mounting_hole (3.2 mm) in the corners." });
1693
+ }
1694
+ } catch {
1695
+ }
1696
+ const boundsOfComponent = (entry) => {
1697
+ const x = Number(entry?.x ?? entry?.X);
1698
+ const y = Number(entry?.y ?? entry?.Y);
1699
+ const w = Number(entry?.width ?? entry?.Width);
1700
+ const h = Number(entry?.height ?? entry?.Height);
1701
+ if (![x, y, w, h].every(Number.isFinite) || w <= 0 || h <= 0) return void 0;
1702
+ return { left: x - w / 2, right: x + w / 2, bottom: y - h / 2, top: y + h / 2 };
1703
+ };
1704
+ const bodies = pcbComponents.map((entry) => ({
1705
+ name: String(entry?.designator ?? entry?.Designator ?? entry?.primitiveId ?? "?"),
1706
+ bounds: boundsOfComponent(entry)
1707
+ })).filter((entry) => entry.bounds !== void 0);
1708
+ if (bodies.length >= 2) {
1709
+ for (let i = 0; i < bodies.length; i++) {
1710
+ for (let j = i + 1; j < bodies.length; j++) {
1711
+ const a = bodies[i].bounds;
1712
+ const b = bodies[j].bounds;
1713
+ const sharedX = Math.min(a.right, b.right) - Math.max(a.left, b.left);
1714
+ const sharedY = Math.min(a.top, b.top) - Math.max(a.bottom, b.bottom);
1715
+ if (sharedX > 2 && sharedY > 2) add(violations, "component-overlap", "Two component bodies overlap; a placement collision here becomes a placement error at assembly.", [bodies[i].name + " x " + bodies[j].name]);
1716
+ }
1717
+ }
1718
+ }
1719
+ const outlineX = [];
1720
+ const outlineY = [];
1721
+ for (const entry of outline) {
1722
+ const source = entry?.polygon?.polygon ?? entry?.Polygon?.polygon ?? [];
1723
+ for (let i = 0; i + 1 < source.length; i += 2) {
1724
+ if (typeof source[i] === "number") {
1725
+ outlineX.push(source[i]);
1726
+ outlineY.push(source[i + 1]);
1727
+ }
1728
+ }
1729
+ }
1730
+ if (bodies.length > 0 && outlineX.length >= 3) {
1731
+ const box = { left: Math.min(...outlineX), right: Math.max(...outlineX), bottom: Math.min(...outlineY), top: Math.max(...outlineY) };
1732
+ for (const body of bodies) {
1733
+ const b = body.bounds;
1734
+ if (b.left < box.left - 5 || b.right > box.right + 5 || b.bottom < box.bottom - 5 || b.top > box.top + 5) {
1735
+ add(warnings, "component-off-board", "A component body extends past the board outline; on a real assembly it either hangs in the air or collides with the enclosure.", [body.name]);
1736
+ }
1737
+ }
1738
+ }
1739
+ let drc = { ran: false, reason: null, violationCount: null };
1740
+ if (args.drc !== false) {
1741
+ try {
1742
+ const outcome = await callExtension("pcb_Drc.check", [true, false, true], toolTimeout(args, timeoutMs));
1743
+ drc = { ran: true, reason: null, violationCount: Array.isArray(outcome) ? outcome.length : outcome === true ? 0 : null };
1744
+ } catch (error) {
1745
+ drc = { ran: false, reason: error instanceof Error ? error.message : String(error), violationCount: null };
1746
+ }
1747
+ }
1748
+ if (drc.ran && drc.violationCount !== null && drc.violationCount > 0) {
1749
+ violations.push({ rule: "drc", message: `PCB DRC reports ${drc.violationCount} violation(s)`, count: drc.violationCount, samples: [] });
1750
+ }
1751
+ const checklist = [
1752
+ { item: "\u677F\u6846\u5B58\u5728\uFF08\u5C42 11 \u95ED\u5408\u6298\u7EBF\uFF09", status: outline.length > 0 ? "pass" : "fail" },
1753
+ { item: "\u8D70\u7EBF\u5BBD\u5EA6 \u2265 " + MIN_TRACK_WIDTH_MIL + " mil\uFF080.15 mm\uFF09", status: violations.some((item) => item.rule === "track-width-min") ? "fail" : "pass" },
1754
+ { item: "\u8FC7\u5B54\u5B54\u5F84/\u710A\u73AF\u5408\u89C4\uFF08\u2265" + VIA_HOLE_MIN_MM + " mm \u5EFA\u8BAE\uFF0C\u710A\u73AF \u2265" + ANNULUS_MIN_MM + " mm\uFF09", status: violations.some((item) => item.rule === "via-geometry") ? "fail" : "pass" },
1755
+ { item: "\u7F51\u7EDC\u540D\u4EC5\u542B\u53EF\u89E3\u6790\u5B57\u7B26", status: violations.some((item) => item.rule === "net-name") ? "fail" : "pass" },
1756
+ { item: "GND \u94FA\u94DC", status: pours.length > 0 ? "pass" : "warn" },
1757
+ { item: "PCB DRC", status: drc.violationCount === 0 ? "pass" : drc.violationCount === null ? "unknown" : "fail" }
1758
+ ];
1759
+ return {
1760
+ ok: violations.length === 0,
1761
+ counts: { tracks: tracks.length, vias: vias.length, pours: pours.length, outlinePolylines: outline.length, nets: netNames.length, componentsRead: pcbComponents.length },
1762
+ minWidthByNet: Object.fromEntries([...widthByNet.entries()].map(([net, width]) => [net, { widthMil: width, role: classifyNet(net), suggestedMil: suggestTrackWidthMil(net) }])),
1763
+ violations,
1764
+ warnings,
1765
+ checklist,
1766
+ drc,
1767
+ rules: {
1768
+ minTrackMil: MIN_TRACK_WIDTH_MIL,
1769
+ trackWidthTiers: TRACK_WIDTH_MIL,
1770
+ viaSizesMm: VIA_SIZES_MM,
1771
+ viaHoleMinMm: VIA_HOLE_MIN_MM,
1772
+ annulusMinMm: ANNULUS_MIN_MM,
1773
+ pourClearanceMil: { required: POUR_CLEARANCE_MIN_MIL, recommended: POUR_CLEARANCE_RECOMMENDED_MIL },
1774
+ silkscreenMinMm: { height: SILKSCREEN_HEIGHT_MIN_MM, width: SILKSCREEN_WIDTH_MIN_MM },
1775
+ boardOutlineWidthMil: BOARD_OUTLINE_WIDTH_MIL
1776
+ }
1777
+ };
1778
+ }
1779
+ function launchProbe() {
1780
+ const cache = /* @__PURE__ */ new Map();
1781
+ return {
1782
+ platform: process.platform,
1783
+ env: process.env,
1784
+ exists(path) {
1785
+ try {
1786
+ return statSync(path).isFile();
1787
+ } catch {
1788
+ return false;
1789
+ }
1790
+ },
1791
+ registryQuery(key, valueName) {
1792
+ if (process.platform !== "win32") return void 0;
1793
+ const cacheKey = key + "|" + (valueName === void 0 ? "LIST" : valueName === "" ? "DEFAULT" : "V:" + valueName);
1794
+ if (cache.has(cacheKey)) return cache.get(cacheKey);
1795
+ let output;
1796
+ try {
1797
+ const extra = valueName === void 0 ? ["/s"] : valueName === "" ? ["/ve"] : ["/v", valueName];
1798
+ const raw = execFileSync("reg", ["query", key, ...extra], {
1799
+ timeout: 5e3,
1800
+ windowsHide: true,
1801
+ stdio: ["ignore", "pipe", "ignore"]
1802
+ });
1803
+ output = decodeRegistryOutput(raw);
1804
+ } catch {
1805
+ output = void 0;
1806
+ }
1807
+ cache.set(cacheKey, output);
1808
+ return output;
1809
+ }
1810
+ };
1811
+ }
1812
+ function processCountByName(imageName) {
1813
+ if (process.platform !== "win32") {
1814
+ try {
1815
+ const out = execFileSync("pgrep", ["-f", imageName], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
1816
+ return out.split(/\r?\n/).filter((line) => line.trim() !== "").length;
1817
+ } catch {
1818
+ return 0;
1819
+ }
1820
+ }
1821
+ try {
1822
+ const out = execFileSync("tasklist", ["/FI", "IMAGENAME eq " + imageName, "/FO", "CSV", "/NH"], {
1823
+ encoding: "utf8",
1824
+ timeout: 5e3,
1825
+ stdio: ["ignore", "pipe", "ignore"]
1826
+ });
1827
+ return out.split(/\r?\n/).filter((line) => line.trim().startsWith('"')).length;
1828
+ } catch {
1829
+ return 0;
1830
+ }
1831
+ }
1832
+ function terminateByName(imageName, force) {
1833
+ if (process.platform === "win32") {
1834
+ execFileSync("taskkill", ["/IM", imageName, "/T"].concat(force ? ["/F"] : []), {
1835
+ timeout: 1e4,
1836
+ stdio: ["ignore", "ignore", "ignore"]
1837
+ });
1838
+ return;
1839
+ }
1840
+ execFileSync("pkill", [force ? "-9" : "-TERM", "-f", imageName], { timeout: 1e4, stdio: ["ignore", "ignore", "ignore"] });
1841
+ }
1842
+ async function waitForExtensionConnection(timeoutMs) {
1843
+ const started = Date.now();
1844
+ const readyCount = () => pickClients().length;
1845
+ while (Date.now() - started < timeoutMs) {
1846
+ if (readyCount() > 0) return { connected: true, clients: readyCount(), waitedMs: Date.now() - started };
1847
+ await new Promise((resolve) => setTimeout(resolve, 500));
1848
+ }
1849
+ return { connected: false, clients: readyCount(), waitedMs: Date.now() - started };
1850
+ }
1851
+ async function clearRoutingBatched(args, type, timeoutMs) {
1852
+ if (type === "connection") throw new Error("eda_pcb_clear_routing: type=connection needs the EDA user interface; use type=all/net with mode=batched");
1853
+ const net = args.net === void 0 ? void 0 : String(args.net);
1854
+ const layer = args.layer === void 0 ? void 0 : resolvePcbLayer(args.layer);
1855
+ if (args.layer !== void 0 && layer === void 0) throw new Error("eda_pcb_clear_routing: invalid layer " + String(args.layer));
1856
+ const batchSize = Math.max(1, Math.min(2e3, Number(args.batchSize ?? 200) || 200));
1857
+ const tracks = await pcbPrimitiveList("pcb_PrimitiveLine.getAll", [net, layer, void 0], timeoutMs);
1858
+ const vias = await pcbPrimitiveList("pcb_PrimitiveVia.getAll", [net, void 0], timeoutMs);
1859
+ const trackIds = (Array.isArray(tracks) ? tracks : []).map((item) => pickValue(asRecord(item), "PrimitiveId", "primitiveId")).filter((id) => typeof id === "string");
1860
+ const viaIds = (Array.isArray(vias) ? vias : []).map((item) => pickValue(asRecord(item), "PrimitiveId", "primitiveId")).filter((id) => typeof id === "string");
1861
+ const batch = [...trackIds.map((id) => ({ kind: "track", id })), ...viaIds.map((id) => ({ kind: "via", id }))].slice(0, batchSize);
1862
+ let deleted = 0;
1863
+ const failed = [];
1864
+ for (const item of batch) {
1865
+ try {
1866
+ await callExtension(item.kind === "track" ? "pcb_PrimitiveLine.delete" : "pcb_PrimitiveVia.delete", [item.id], timeoutMs);
1867
+ deleted += 1;
1868
+ } catch (error) {
1869
+ failed.push({ primitiveId: item.id, error: error instanceof Error ? error.message : String(error) });
1870
+ }
1871
+ }
1872
+ const remaining = trackIds.length + viaIds.length - deleted;
1873
+ return {
1874
+ mode: "batched",
1875
+ type,
1876
+ net: net ?? null,
1877
+ layer: layer ?? null,
1878
+ batchSize,
1879
+ matched: trackIds.length + viaIds.length,
1880
+ deleted,
1881
+ remaining,
1882
+ done: remaining <= 0,
1883
+ failed,
1884
+ hint: remaining <= 0 ? "Routing cleared." : "Call eda_pcb_clear_routing again (same arguments) until done=true."
1885
+ };
1886
+ }
1887
+ async function parseNetlist2(previous, timeoutMs) {
1888
+ let text;
1889
+ try {
1890
+ text = await callExtension("sch_Netlist.getNetlist", [void 0], timeoutMs);
1891
+ } catch (error) {
1892
+ return { source: "sch_Net.*", count: Array.isArray(previous) ? previous.length : 0, nets: previous, hint: NET_EMPTY_HINT, netlistError: error instanceof Error ? error.message : String(error) };
1893
+ }
1894
+ if (typeof text !== "string" || text.trim() === "") {
1895
+ return { source: "sch_Net.*", count: Array.isArray(previous) ? previous.length : 0, nets: previous, hint: NET_EMPTY_HINT };
1896
+ }
1897
+ const byNet = /* @__PURE__ */ new Map();
1898
+ for (const match of text.matchAll(/NET\s+"?([^"\s()]+)"?\s*\(([^)]*)\)/gi)) {
1899
+ const name = match[1];
1900
+ const pins = match[2].split(/\s+/).map((part) => part.trim()).filter((part) => part !== "");
1901
+ const existing = byNet.get(name);
1902
+ if (existing === void 0) byNet.set(name, pins);
1903
+ else byNet.set(name, [.../* @__PURE__ */ new Set([...existing, ...pins])]);
1904
+ }
1905
+ const nets = [...byNet.entries()].map(([net, pins]) => ({ net, pins, pinCount: pins.length }));
1906
+ return { source: "sch_Netlist.getNetlist", count: nets.length, nets, netlistBytes: text.length };
1907
+ }
1908
+ async function placeNetLabel(net, x, y, fontSize, timeoutMs, options = {}) {
1909
+ if (net === "" || net === "undefined") throw new Error("a net name is required");
1910
+ assertNetName(String(net), "eda_place_net_label");
1911
+ const size = fontSize === void 0 ? 12 : Number(fontSize);
1912
+ if (options.probe === true) netLabelSupport = null;
1913
+ let failure = null;
1914
+ if (netLabelSupport !== false) {
1915
+ try {
1916
+ const raw2 = await callExtension("sch_PrimitiveAttribute.createNetLabel", [x, y, net], Math.min(timeoutMs, 4e3));
1917
+ if (raw2 === void 0 || raw2 === null) throw new Error("createNetLabel returned nothing");
1918
+ netLabelSupport = true;
1919
+ return { method: "netLabel", net, x, y, label: summarizePrimitive(raw2) };
1920
+ } catch (error) {
1921
+ const message = error instanceof Error ? error.message : String(error);
1922
+ if (!/not found|not available|not allowed|timed out|timeout|nothing|undefined/i.test(message)) throw error;
1923
+ failure = message;
1924
+ netLabelSupport = false;
1925
+ }
1926
+ }
1927
+ if (options.textLabel !== true) {
1928
+ return { method: "stub", net, x, y, created: false, warning: "createNetLabel is unavailable on this EDA build (" + (failure ?? "probe already failed this session") + "); the net is carried by the stub wire, and no text label was added (pass textLabel:true if you want one)." };
1929
+ }
1930
+ const raw = await callExtension("sch_PrimitiveText.create", [x, y, net, 0, null, null, size, false, false, false, 1], timeoutMs);
1931
+ const label = summarizePrimitive(raw);
1932
+ if (label.primitiveId !== void 0) {
1933
+ placedTextLabels.push({ net: String(net), x, y, primitiveId: label.primitiveId });
1934
+ if (placedTextLabels.length > 2e3) placedTextLabels.shift();
1935
+ }
1936
+ return {
1937
+ method: "text",
1938
+ net,
1939
+ x,
1940
+ y,
1941
+ created: label.primitiveId !== void 0,
1942
+ warning: "createNetLabel is unavailable on this EDA build (" + (failure ?? "probe already failed this session") + "), so a plain TEXT label was placed: it carries no electrical meaning. The stub wire drawn by the caller is what joins the net; eda_get_net_labels lists these texts by name and id.",
1943
+ ...label.primitiveId === void 0 ? { hint: "No label primitive was created: the schematic page must be the ACTIVE document (sch_PrimitiveText.create is tab-dependent). Use eda_get_active_document / eda_open_document, then retry." } : {},
1944
+ label
1945
+ };
1946
+ }
1947
+ async function placeAtPin(toolName, args, timeoutMs) {
1948
+ const pinPrimitiveId = String(args.pinPrimitiveId ?? "");
1949
+ if (pinPrimitiveId === "") throw new Error("pinPrimitiveId is required");
1950
+ const isFlag = toolName === "eda_place_net_flag_at_pin";
1951
+ assertNetName(String(args.net ?? ""), toolName);
1952
+ const pin = await callExtension("sch_PrimitivePin.get", [pinPrimitiveId], timeoutMs);
1953
+ const pinRecord = asRecord(pin);
1954
+ const pinX = Number(pickValue(pinRecord, "X", "x"));
1955
+ const pinY = Number(pickValue(pinRecord, "Y", "y"));
1956
+ if (!Number.isFinite(pinX) || !Number.isFinite(pinY)) throw new Error("could not read pin position for " + pinPrimitiveId);
1957
+ const pinRotation = Number(pickValue(pinRecord, "Rotation", "rotation") ?? 0);
1958
+ const direction = pinDirection(pinRotation);
1959
+ const explicitOffset = args.offsetX !== void 0 || args.offsetY !== void 0;
1960
+ const stubLength = args.stubLength === void 0 ? explicitOffset ? 0 : 20 : Math.max(0, Number(args.stubLength));
1961
+ const x = pinX + direction.dx * stubLength + Number(args.offsetX ?? 0);
1962
+ const y = pinY + direction.dy * stubLength + Number(args.offsetY ?? 0);
1963
+ if (args.allowOutsideFrame !== true) {
1964
+ const problem = checkPointInFrame(x, y, args.paper, 5) ?? checkPointAgainstTitleBlock(x, y, args.paper, 5);
1965
+ if (problem !== void 0) {
1966
+ throw new Error(toolName + " refused: " + problem + " - reduce stubLength or pass offsetX/offsetY to place it elsewhere.");
1967
+ }
1968
+ }
1969
+ let stub;
1970
+ if (stubLength > 0 && typeof args.net === "string" && args.net !== "") {
1971
+ stub = summarizePrimitive(await callExtension("sch_PrimitiveWire.create", [
1972
+ [pinX, pinY, x, y],
1973
+ String(args.net),
1974
+ args.color === void 0 ? void 0 : String(args.color),
1975
+ args.lineWidth === void 0 ? void 0 : Number(args.lineWidth),
1976
+ args.lineType === void 0 ? void 0 : Number(args.lineType)
1977
+ ], timeoutMs));
1978
+ }
1979
+ const placement = { pin: { primitiveId: pinPrimitiveId, x: pinX, y: pinY, rotation: pinRotation }, direction, stubLength, x, y, stub };
1980
+ if (isFlag) {
1981
+ const flag = await callExtension("sch_PrimitiveComponent.createNetFlag", [
1982
+ String(args.identification),
1983
+ String(args.net),
1984
+ x,
1985
+ y,
1986
+ args.rotation === void 0 ? pinRotation : Number(args.rotation),
1987
+ Boolean(args.mirror ?? false)
1988
+ ], timeoutMs);
1989
+ return { ...placement, flag: summarizePrimitive(flag) };
1990
+ }
1991
+ const label = await placeNetLabel(String(args.net), x, y, args.fontSize, timeoutMs);
1992
+ return { ...label, ...placement };
1993
+ }
1994
+ function isInternalHelperMissing(error) {
1995
+ const message = error instanceof Error ? error.message : String(error);
1996
+ if (/unsupported job kind/i.test(message)) return true;
1997
+ return /not allowed|not found|not available/i.test(message) && /dsh\.internal|API method/i.test(message);
1998
+ }
1999
+ function toolTimeout(args, fallback) {
2000
+ const value = Number(args.timeoutMs);
2001
+ return Number.isFinite(value) && value > 0 ? Math.max(value, fallback) : fallback;
2002
+ }
2003
+ function pickDefined(source, keys) {
2004
+ const out = {};
2005
+ for (const key of keys) {
2006
+ const value = source[key];
2007
+ if (value !== void 0 && value !== null) out[key] = value;
2008
+ }
2009
+ return out;
2010
+ }
2011
+ async function resolveProjectUuid(args, timeoutMs) {
2012
+ const direct = args.uuid === void 0 ? "" : String(args.uuid).trim();
2013
+ if (direct !== "") return { uuid: direct, matched: null };
2014
+ const name = args.name === void 0 ? "" : String(args.name).trim();
2015
+ if (name === "") throw new Error("provide uuid or name");
2016
+ const unfiltered = await callExtension("dmt_Project.getAllProjectsUuid", [], toolTimeout(args, timeoutMs));
2017
+ const candidates = Array.isArray(unfiltered) ? unfiltered.map(String) : [];
2018
+ if (candidates.length === 0) {
2019
+ const teams = await callExtension("dmt_Team.getAllTeamsInfo", [], toolTimeout(args, timeoutMs)).catch(() => []);
2020
+ const seen = /* @__PURE__ */ new Set();
2021
+ for (const team of Array.isArray(teams) ? teams : []) {
2022
+ const teamUuid = String(pickValue(asRecord(team), "uuid", "Uuid") ?? "");
2023
+ if (teamUuid === "") continue;
2024
+ const owned = await callExtension("dmt_Project.getAllProjectsUuid", [teamUuid], toolTimeout(args, timeoutMs)).catch(() => []);
2025
+ for (const uuid2 of Array.isArray(owned) ? owned.map(String) : []) {
2026
+ if (seen.has(uuid2)) continue;
2027
+ seen.add(uuid2);
2028
+ candidates.push(uuid2);
2029
+ }
2030
+ }
2031
+ }
2032
+ const resolved = [];
2033
+ for (const candidate of candidates) {
2034
+ try {
2035
+ const info = asRecord(await callExtension("dmt_Project.getProjectInfo", [candidate], toolTimeout(args, timeoutMs)));
2036
+ resolved.push({ uuid: candidate, friendly: String(pickValue(info, "FriendlyName", "friendlyName", "Name", "name") ?? "") });
2037
+ } catch {
2038
+ resolved.push({ uuid: candidate, friendly: "" });
2039
+ }
2040
+ }
2041
+ const matched = resolved.find((item) => item.friendly === name) ?? resolved.find((item) => item.friendly.toLowerCase().includes(name.toLowerCase())) ?? null;
2042
+ if (matched === null) {
2043
+ throw new Error('no project matches "' + name + '"; known names: ' + resolved.map((item) => item.friendly || item.uuid).slice(0, 20).join(", "));
2044
+ }
2045
+ return { uuid: matched.uuid, matched };
2046
+ }
2047
+ async function waitForActiveProject(uuid2, timeoutMs = 4e3) {
2048
+ const deadline = Date.now() + timeoutMs;
2049
+ let lastActive = null;
2050
+ for (; ; ) {
2051
+ try {
2052
+ const info = asRecord(await callExtension("dmt_Project.getCurrentProjectInfo", [], 3e3));
2053
+ lastActive = String(pickValue(info, "uuid", "Uuid") ?? "") || null;
2054
+ if (lastActive === uuid2) return { active: true, project: info };
2055
+ } catch {
2056
+ }
2057
+ if (Date.now() > deadline) return { active: false, project: null, lastActive };
2058
+ await sleep(400);
2059
+ }
2060
+ }
2061
+ function internalIdsOf(info) {
2062
+ const ids = /* @__PURE__ */ new Set();
2063
+ const boards = Array.isArray(asRecord(info).data) ? asRecord(info).data : [];
2064
+ for (const board of boards) {
2065
+ const record = asRecord(board);
2066
+ const boardUuid = String(pickValue(record, "uuid", "Uuid") ?? "");
2067
+ if (boardUuid !== "") ids.add(boardUuid);
2068
+ for (const docKey of ["schematic", "pcb"]) {
2069
+ const doc = asRecord(record[docKey]);
2070
+ const docUuid = String(pickValue(doc, "uuid", "Uuid") ?? "");
2071
+ if (docUuid !== "") ids.add(docUuid);
2072
+ const pages = Array.isArray(doc.pages) ? doc.pages : [];
2073
+ for (const page of pages) {
2074
+ const pageUuid = String(pickValue(asRecord(page), "uuid", "Uuid") ?? "");
2075
+ if (pageUuid !== "") ids.add(pageUuid);
2076
+ }
2077
+ }
2078
+ }
2079
+ return ids;
2080
+ }
2081
+ async function assertKnownPcbNet(toolName, net, timeoutMs, force) {
2082
+ const name = String(net ?? "").trim();
2083
+ if (name === "") throw new Error(toolName + " requires a net name");
2084
+ if (force === true) return;
2085
+ let names;
2086
+ try {
2087
+ const raw = await callExtension("pcb_Net.getAllNetsName", [], Math.min(timeoutMs, 8e3));
2088
+ names = new Set((Array.isArray(raw) ? raw : []).map((value) => String(value)));
2089
+ } catch {
2090
+ return;
2091
+ }
2092
+ if (names.size === 0) return;
2093
+ if (names.has(name)) return;
2094
+ const sample = [...names].slice(0, 12).join(", ");
2095
+ throw new Error(toolName + ': net "' + name + '" is not on this PCB (' + names.size + " nets: " + sample + "\u2026). A write on an unknown net creates a phantom net that DRC reports as a netlist error; pass force:true if that is really intended.");
2096
+ }
2097
+ async function executeTool(name, rawArgs, timeoutMs) {
2098
+ const args = asRecord(rawArgs);
2099
+ const tool = PCB_TOOL_ALIASES[name] ?? name;
2100
+ switch (tool) {
2101
+ case "eda_status": {
2102
+ const ready = pickClients();
2103
+ const versions = ready.map((client) => typeof client.extensionVersion === "string" ? client.extensionVersion : null);
2104
+ const extensionVersion = versions.find((value) => typeof value === "string") ?? null;
2105
+ const stale = versions.filter((value) => value !== VERSION);
2106
+ return {
2107
+ ok: true,
2108
+ bridgeVersion: VERSION,
2109
+ wsPort: WS_PORT,
2110
+ allowRawApi: ALLOW_RAW_API,
2111
+ connectedClients: ready.length,
2112
+ extensionVersion: extensionVersion ?? null,
2113
+ extensionVersions: versions,
2114
+ versionMismatch: stale.length > 0,
2115
+ mcpUnits: "0.01 inch",
2116
+ defaultPaper: DEFAULT_PAPER,
2117
+ hint: ready.length === 0 ? "No JLCEDA extension is connected. Open JLCEDA Pro and click DSH MCP -> connect, or re-import dsh-eda-bridge-extension-" + VERSION + ".zip." : stale.length > 0 ? "Connected EDA extension " + stale.join(", ") + " does not match bridge " + VERSION + ". In JLCEDA Pro remove the OLD dsh-eda-bridge extension first, import dsh-eda-bridge-extension-" + VERSION + ".zip again, then restart the app; a simple reload keeps the old copy." : "ok"
2118
+ };
2119
+ }
2120
+ case "eda_close_document":
2121
+ return await callExtension("dmt_EditorControl.closeDocument", [String(args.tabId ?? "")], timeoutMs);
2122
+ case "eda_export_project": {
2123
+ const result2 = await callExtension("dsh.internal.exportProjectFile", [
2124
+ args.uuid === void 0 ? null : String(args.uuid),
2125
+ args.fileName === void 0 ? void 0 : String(args.fileName),
2126
+ void 0,
2127
+ args.fileType === void 0 ? void 0 : String(args.fileType)
2128
+ ], toolTimeout(args, timeoutMs));
2129
+ const base64 = typeof result2?.base64 === "string" ? result2.base64 : "";
2130
+ const outPath = args.outPath === void 0 ? "" : String(args.outPath).trim();
2131
+ if (outPath !== "") {
2132
+ await writeFile(outPath, Buffer.from(base64, "base64"));
2133
+ return { ok: true, written: outPath, name: result2?.name ?? null, size: base64 === "" ? 0 : Buffer.from(base64, "base64").length };
2134
+ }
2135
+ if (args.inline !== true) {
2136
+ return { ok: true, name: result2?.name ?? null, base64Length: base64.length, hint: "Pass outPath to write the file, or inline=true to receive the base64 payload." };
2137
+ }
2138
+ return { ok: true, name: result2?.name ?? null, base64 };
2139
+ }
2140
+ case "eda_import_project": {
2141
+ const path = String(args.path ?? "").trim();
2142
+ if (path === "") throw new Error("eda_import_project requires path");
2143
+ let bytes;
2144
+ try {
2145
+ bytes = await readFile(path);
2146
+ } catch {
2147
+ throw new Error('eda_import_project: cannot read "' + path + '"');
2148
+ }
2149
+ let teamUuid = args.teamUuid === void 0 ? "" : String(args.teamUuid).trim();
2150
+ if (teamUuid === "") {
2151
+ const current = await callExtension("dmt_Team.getCurrentTeamInfo", [], timeoutMs).catch(() => void 0);
2152
+ teamUuid = String(pickValue(asRecord(current), "uuid", "Uuid") ?? "");
2153
+ }
2154
+ if (teamUuid === "") {
2155
+ throw new Error("eda_import_project needs teamUuid: the app imports nothing without a target team. Use a team uuid from eda_list_teams (local mode reports project directories) or the teamUuid of an existing project (eda_list_projects).");
2156
+ }
2157
+ const saveTo = { operation: "New Project", newProjectOwnerTeamUuid: teamUuid };
2158
+ if (args.folderUuid !== void 0) saveTo.newProjectOwnerFolderUuid = String(args.folderUuid);
2159
+ if (args.friendlyName !== void 0) saveTo.newProjectFriendlyName = String(args.friendlyName);
2160
+ const imported = await callExtension("dsh.internal.importProjectFile", [
2161
+ bytes.toString("base64"),
2162
+ basename(path),
2163
+ args.fileType === void 0 ? void 0 : String(args.fileType),
2164
+ saveTo
2165
+ ], toolTimeout(args, timeoutMs));
2166
+ const raw = imported?.result ?? imported;
2167
+ const uuid2 = typeof raw === "string" ? raw : typeof raw?.uuid === "string" ? raw.uuid : void 0;
2168
+ const landed = raw !== null && raw !== void 0;
2169
+ let opened = false;
2170
+ if (args.open === true && uuid2 !== void 0) {
2171
+ try {
2172
+ await callExtension("dmt_Project.openProject", [uuid2], timeoutMs);
2173
+ opened = (await waitForActiveProject(uuid2, 4e3)).active;
2174
+ } catch {
2175
+ opened = false;
2176
+ }
2177
+ }
2178
+ let collisions = null;
2179
+ if (landed && uuid2 !== void 0 && args.checkCollisions !== false) {
2180
+ try {
2181
+ const mine = await callExtension("dmt_Project.getProjectInfo", [uuid2], toolTimeout(args, timeoutMs));
2182
+ const myIds = internalIdsOf(mine);
2183
+ const others = await callExtension("dmt_Project.getAllProjectsUuid", [], toolTimeout(args, timeoutMs));
2184
+ const list = (Array.isArray(others) ? others.map(String) : []).filter((other) => other !== uuid2).slice(0, 20);
2185
+ collisions = [];
2186
+ for (const other of list) {
2187
+ const info = await callExtension("dmt_Project.getProjectInfo", [other], timeoutMs).catch(() => void 0);
2188
+ const shared = [...internalIdsOf(info)].filter((sharedId) => myIds.has(sharedId));
2189
+ if (shared.length > 0) {
2190
+ collisions.push({ projectUuid: other, friendlyName: pickValue(asRecord(info), "friendlyName", "FriendlyName") ?? null, sharedIds: shared });
2191
+ }
2192
+ }
2193
+ } catch {
2194
+ collisions = null;
2195
+ }
2196
+ }
2197
+ return {
2198
+ ok: landed,
2199
+ imported: landed,
2200
+ name: basename(path),
2201
+ size: bytes.length,
2202
+ teamUuid,
2203
+ uuid: uuid2 ?? null,
2204
+ opened,
2205
+ collisions,
2206
+ result: raw ?? null,
2207
+ hint: landed ? null : "The app returned nothing: the import did not create a project. That means this build ignores the saveTo target (same limitation as createProject), so import cannot be used to create projects here."
2208
+ };
2209
+ }
2210
+ case "eda_close": {
2211
+ const resolved = resolveExecutable(launchProbe(), {
2212
+ executable: args.executable === void 0 ? void 0 : String(args.executable)
2213
+ });
2214
+ const imageName = resolved === void 0 ? "lceda-pro.exe" : basename(resolved.executable);
2215
+ const before = processCountByName(imageName);
2216
+ const waitMs = Number.isFinite(Number(args.waitMs)) ? Math.max(1e3, Number(args.waitMs)) : 8e3;
2217
+ let error = null;
2218
+ try {
2219
+ terminateByName(imageName, false);
2220
+ } catch (failure) {
2221
+ error = failure instanceof Error ? failure.message : String(failure);
2222
+ }
2223
+ const started = Date.now();
2224
+ let remaining = processCountByName(imageName);
2225
+ while (remaining > 0 && Date.now() - started < waitMs) {
2226
+ await new Promise((resolve) => setTimeout(resolve, 500));
2227
+ remaining = processCountByName(imageName);
2228
+ }
2229
+ let forced = false;
2230
+ if (remaining > 0) {
2231
+ try {
2232
+ terminateByName(imageName, true);
2233
+ forced = true;
2234
+ await new Promise((resolve) => setTimeout(resolve, 1500));
2235
+ remaining = processCountByName(imageName);
2236
+ } catch (failure) {
2237
+ error = error ?? (failure instanceof Error ? failure.message : String(failure));
2238
+ }
2239
+ }
2240
+ const connected = pickClients().length;
2241
+ return {
2242
+ ok: remaining <= 0,
2243
+ closed: remaining <= 0,
2244
+ forced,
2245
+ imageName,
2246
+ processesBefore: before,
2247
+ processesAfter: remaining,
2248
+ connectedClients: connected,
2249
+ waitedMs: Date.now() - started,
2250
+ error
2251
+ };
2252
+ }
2253
+ case "eda_list_projects": {
2254
+ const filters = [];
2255
+ if (args.teamUuid !== void 0) filters.push(String(args.teamUuid));
2256
+ if (args.folderUuid !== void 0 || args.workspaceUuid !== void 0) filters.push(args.folderUuid === void 0 ? null : String(args.folderUuid));
2257
+ if (args.workspaceUuid !== void 0) filters.push(String(args.workspaceUuid));
2258
+ let uuids = await callExtension("dmt_Project.getAllProjectsUuid", filters, toolTimeout(args, timeoutMs));
2259
+ let list = Array.isArray(uuids) ? uuids.map(String) : [];
2260
+ let aggregated = false;
2261
+ if (list.length === 0 && filters.length === 0) {
2262
+ const teams = await callExtension("dmt_Team.getAllTeamsInfo", [], toolTimeout(args, timeoutMs)).catch(() => []);
2263
+ const seen = /* @__PURE__ */ new Set();
2264
+ for (const team of Array.isArray(teams) ? teams : []) {
2265
+ const teamUuid = String(pickValue(asRecord(team), "uuid", "Uuid") ?? "");
2266
+ if (teamUuid === "") continue;
2267
+ const owned = await callExtension("dmt_Project.getAllProjectsUuid", [teamUuid], toolTimeout(args, timeoutMs)).catch(() => []);
2268
+ for (const uuid2 of Array.isArray(owned) ? owned.map(String) : []) {
2269
+ if (seen.has(uuid2)) continue;
2270
+ seen.add(uuid2);
2271
+ list.push(uuid2);
2272
+ }
2273
+ }
2274
+ aggregated = true;
2275
+ }
2276
+ if (args.resolveNames === false) return { count: list.length, uuids: list, aggregated };
2277
+ const limit = Number.isFinite(Number(args.limit)) ? Math.max(1, Number(args.limit)) : list.length;
2278
+ const projects = [];
2279
+ for (const uuid2 of list.slice(0, limit)) {
2280
+ try {
2281
+ projects.push(await callExtension("dmt_Project.getProjectInfo", [uuid2], toolTimeout(args, timeoutMs)));
2282
+ } catch {
2283
+ projects.push({ uuid: uuid2 });
2284
+ }
2285
+ }
2286
+ return { count: list.length, resolved: projects.length, aggregated, projects };
2287
+ }
2288
+ case "eda_get_project": {
2289
+ const project = await callExtension("dmt_Project.getCurrentProjectInfo", [], timeoutMs);
2290
+ return project === void 0 || project === null ? { project: null, hint: "No project is open: JLCEDA Pro is on the HOME page. Use eda_list_projects + eda_open_project, or open one in the app." } : project;
2291
+ }
2292
+ case "eda_open_project": {
2293
+ const resolvedProject = await resolveProjectUuid(args, timeoutMs);
2294
+ const uuid2 = resolvedProject.uuid;
2295
+ const returned = await callExtension("dmt_Project.openProject", [uuid2], toolTimeout(args, timeoutMs));
2296
+ const activation = await waitForActiveProject(uuid2, args.verifyMs === void 0 ? 4e3 : Number(args.verifyMs));
2297
+ return {
2298
+ opened: activation.active,
2299
+ openReturned: returned !== false,
2300
+ uuid: uuid2,
2301
+ matched: resolvedProject.matched,
2302
+ current: activation.active ? summarizePrimitive(activation.project) : null,
2303
+ ...activation.active ? {} : { hint: "The project did not become active within the verification window (last active: " + (activation.lastActive ?? "unknown") + "); it may still be loading, or the app refused the switch." }
2304
+ };
2305
+ }
2306
+ case "eda_get_workspace": {
2307
+ const workspace = await callExtension("dmt_Workspace.getCurrentWorkspaceInfo", [], timeoutMs).catch(() => void 0);
2308
+ const team = await callExtension("dmt_Team.getCurrentTeamInfo", [], timeoutMs).catch(() => void 0);
2309
+ return {
2310
+ workspace: workspace === void 0 ? null : workspace,
2311
+ team: team === void 0 ? null : team,
2312
+ hint: workspace === void 0 && team === void 0 ? "No workspace/team is available: start JLCEDA Pro and sign in to a JLC account. Workspace projects cannot be created or listed without one." : "ok"
2313
+ };
2314
+ }
2315
+ case "eda_list_teams": {
2316
+ const teams = await callExtension(args.involved === true ? "dmt_Team.getAllInvolvedTeamInfo" : "dmt_Team.getAllTeamsInfo", [], toolTimeout(args, timeoutMs));
2317
+ const list = Array.isArray(teams) ? teams : [];
2318
+ return { count: list.length, teams: list };
2319
+ }
2320
+ case "eda_list_folders": {
2321
+ const teamUuid = args.teamUuid === void 0 ? "" : String(args.teamUuid).trim();
2322
+ let resolvedTeam = teamUuid;
2323
+ if (resolvedTeam === "") {
2324
+ const current = await callExtension("dmt_Team.getCurrentTeamInfo", [], timeoutMs).catch(() => void 0);
2325
+ resolvedTeam = String(pickValue(asRecord(current), "Uuid", "uuid") ?? "");
2326
+ }
2327
+ if (resolvedTeam === "") throw new Error("eda_list_folders needs teamUuid (eda_list_teams shows them)");
2328
+ let uuids;
2329
+ try {
2330
+ uuids = await callExtension("dmt_Folder.getAllFoldersUuid", [resolvedTeam], toolTimeout(args, timeoutMs));
2331
+ } catch (failure) {
2332
+ throw new Error('eda_list_folders: the app rejected team "' + resolvedTeam + '" (' + (failure instanceof Error ? failure.message : String(failure)) + "); pass the uuid from a project record (eda_list_projects) or eda_list_teams");
2333
+ }
2334
+ const list = Array.isArray(uuids) ? uuids.map(String) : [];
2335
+ if (args.resolveNames === false) return { teamUuid: resolvedTeam, count: list.length, uuids: list };
2336
+ const folders = [];
2337
+ for (const folderUuid of list.slice(0, 20)) {
2338
+ try {
2339
+ folders.push({ folderUuid, info: await callExtension("dmt_Folder.getFolderInfo", [resolvedTeam, folderUuid], timeoutMs) });
2340
+ } catch {
2341
+ folders.push({ folderUuid, info: null });
2342
+ }
2343
+ }
2344
+ return { teamUuid: resolvedTeam, count: list.length, folders };
2345
+ }
2346
+ case "eda_delete_project": {
2347
+ const resolvedProject = await resolveProjectUuid(args, timeoutMs);
2348
+ const deleted = await callExtension("dmt_Project.deleteProject", [resolvedProject.uuid], toolTimeout(args, timeoutMs));
2349
+ const ok = deleted !== false;
2350
+ return {
2351
+ deleted: ok,
2352
+ uuid: resolvedProject.uuid,
2353
+ matched: resolvedProject.matched,
2354
+ hint: ok ? null : "The app returned false and the project still exists: this build refuses deleteProject for local projects (verified with the project open and after switching away), so remove it in the app."
2355
+ };
2356
+ }
2357
+ case "eda_modify_project": {
2358
+ const resolvedProject = await resolveProjectUuid(args, timeoutMs);
2359
+ const changes = [];
2360
+ if (args.friendlyName !== void 0) {
2361
+ changes.push(["friendlyName", await callExtension("dmt_Project.modifyProjectFriendlyName", [resolvedProject.uuid, String(args.friendlyName)], timeoutMs)]);
2362
+ }
2363
+ if (args.description !== void 0) {
2364
+ changes.push(["description", await callExtension("dmt_Project.modifyProjectDescription", [resolvedProject.uuid, String(args.description)], timeoutMs)]);
2365
+ }
2366
+ if (changes.length === 0) throw new Error("eda_modify_project requires friendlyName or description");
2367
+ return {
2368
+ ok: changes.every(([, value]) => value !== false),
2369
+ uuid: resolvedProject.uuid,
2370
+ matched: resolvedProject.matched,
2371
+ applied: changes.map(([field, value]) => ({ field, ok: value !== false }))
2372
+ };
2373
+ }
2374
+ case "eda_copy_project": {
2375
+ const source = await resolveProjectUuid({
2376
+ uuid: args.sourceUuid,
2377
+ name: args.sourceName
2378
+ }, timeoutMs);
2379
+ let copyRaw;
2380
+ try {
2381
+ copyRaw = await callExtension("dmt_Project.copyProject", [
2382
+ source.uuid,
2383
+ args.targetTeamUuid === void 0 ? void 0 : String(args.targetTeamUuid),
2384
+ args.targetFolderUuid === void 0 ? void 0 : String(args.targetFolderUuid),
2385
+ args.newFriendlyName === void 0 ? void 0 : String(args.newFriendlyName),
2386
+ args.newName === void 0 ? void 0 : String(args.newName)
2387
+ ], toolTimeout(args, timeoutMs));
2388
+ } catch (failure) {
2389
+ throw new Error("eda_copy_project failed: " + (failure instanceof Error ? failure.message : String(failure)));
2390
+ }
2391
+ const copyUuid = typeof copyRaw === "string" ? copyRaw : String(pickValue(asRecord(copyRaw), "uuid", "Uuid") ?? "");
2392
+ return {
2393
+ copied: copyUuid !== "",
2394
+ sourceUuid: source.uuid,
2395
+ uuid: copyUuid === "" ? null : copyUuid,
2396
+ raw: copyRaw ?? null,
2397
+ hint: copyUuid === "" ? "The app returned no uuid and created nothing: copyProject does not work on this build for local projects (same family as createProject/deleteProject). Duplicate it in the app, or export with eda_export_project and import it back with eda_import_project to get an independent copy." : null
2398
+ };
2399
+ return { copied: typeof uuid === "string" && uuid !== "", sourceUuid: source.uuid, uuid: uuid ?? null };
2400
+ }
2401
+ case "eda_create_project": {
2402
+ const friendlyName = String(args.friendlyName ?? "").trim();
2403
+ if (friendlyName === "") throw new Error("eda_create_project requires friendlyName");
2404
+ let teamUuid = args.teamUuid === void 0 ? "" : String(args.teamUuid).trim();
2405
+ let teamSource = "argument";
2406
+ if (teamUuid === "") {
2407
+ const current = await callExtension("dmt_Team.getCurrentTeamInfo", [], timeoutMs).catch(() => void 0);
2408
+ teamUuid = String(pickValue(asRecord(current), "Uuid", "uuid") ?? "");
2409
+ teamSource = teamUuid === "" ? "unavailable" : "current-team";
2410
+ }
2411
+ if (teamUuid === "") {
2412
+ throw new Error("eda_create_project: no team is available (sign in to a JLC account in JLCEDA Pro, or pass teamUuid from eda_list_teams)");
2413
+ }
2414
+ const folderUuid = args.folderUuid === void 0 ? "" : String(args.folderUuid).trim();
2415
+ const uuid2 = await callExtension("dmt_Project.createProject", [
2416
+ friendlyName,
2417
+ args.name === void 0 ? void 0 : String(args.name),
2418
+ teamUuid,
2419
+ folderUuid === "" ? void 0 : folderUuid,
2420
+ args.description === void 0 ? void 0 : String(args.description)
2421
+ ], toolTimeout(args, timeoutMs));
2422
+ if (typeof uuid2 !== "string" || uuid2 === "") {
2423
+ throw new Error("eda_create_project: the app returned no project uuid (team " + teamUuid + " from " + teamSource + "; the app may have shown a dialog or rejected the name)");
2424
+ }
2425
+ let opened = false;
2426
+ if (args.open === true) {
2427
+ try {
2428
+ await callExtension("dmt_Project.openProject", [uuid2], timeoutMs);
2429
+ opened = (await waitForActiveProject(uuid2, 4e3)).active;
2430
+ } catch {
2431
+ opened = false;
2432
+ }
2433
+ }
2434
+ return { created: true, uuid: uuid2, friendlyName, teamUuid, teamSource, folderUuid: folderUuid === "" ? null : folderUuid, opened };
2435
+ }
2436
+ case "eda_launch": {
2437
+ const probe = launchProbe();
2438
+ const resolved = resolveExecutable(probe, {
2439
+ executable: args.executable === void 0 ? void 0 : String(args.executable),
2440
+ project: args.project === void 0 ? void 0 : String(args.project)
2441
+ });
2442
+ if (resolved === void 0) {
2443
+ throw new Error([
2444
+ "eda_launch: could not find the JLCEDA Pro executable on this machine.",
2445
+ "Set `DSH_EDA_EXECUTABLE` (or the plugin setting edaExecutable) to the full path of lceda-pro.exe.",
2446
+ "Searched: DSH_EDA_EXECUTABLE / JLCEDA_EXECUTABLE, the registry handler registered for .eprj2/.eprj,",
2447
+ "conventional install directories under Program Files / LOCALAPPDATA / the system drive, and PATH."
2448
+ ].join(" "));
2449
+ }
2450
+ const alreadyConnected = pickClients().length;
2451
+ const project = args.project === void 0 ? void 0 : String(args.project);
2452
+ if (project !== void 0 && project !== "") {
2453
+ try {
2454
+ if (!statSync(project).isFile()) throw new Error("not a file");
2455
+ } catch {
2456
+ throw new Error('eda_launch: project "' + project + '" does not exist or is not a file');
2457
+ }
2458
+ }
2459
+ const plan = buildLaunchArgs(process.platform, resolved.executable, project);
2460
+ let child;
2461
+ let via = "direct";
2462
+ if (process.platform === "win32") {
2463
+ try {
2464
+ const scriptPath = join(tmpdir(), "dsh-eda-launch-" + process.pid + "-" + Date.now() + ".cmd");
2465
+ await writeFile(scriptPath, buildLaunchScript(resolved.executable, project), "utf8");
2466
+ child = spawn(process.env.SystemRoot ? join(process.env.SystemRoot, "explorer.exe") : "explorer.exe", [scriptPath], {
2467
+ detached: true,
2468
+ stdio: "ignore",
2469
+ windowsHide: false
2470
+ });
2471
+ via = "explorer";
2472
+ } catch {
2473
+ child = spawn(plan.command, plan.args, { detached: true, stdio: "ignore", windowsHide: false });
2474
+ via = "direct";
2475
+ }
2476
+ } else {
2477
+ child = spawn(plan.command, plan.args, { detached: true, stdio: "ignore", windowsHide: false });
2478
+ }
2479
+ child.unref();
2480
+ const shouldWait = args.waitForExtension !== false;
2481
+ const timeoutMs2 = Number.isFinite(Number(args.timeoutMs)) ? Math.max(1e3, Number(args.timeoutMs)) : 3e4;
2482
+ const waited = shouldWait ? await waitForExtensionConnection(timeoutMs2) : { connected: alreadyConnected > 0, clients: alreadyConnected, waitedMs: 0 };
2483
+ return {
2484
+ ok: true,
2485
+ launched: true,
2486
+ pid: child.pid ?? null,
2487
+ via,
2488
+ executable: resolved.executable,
2489
+ source: resolved.source,
2490
+ project: project ?? null,
2491
+ // Verified on JLCEDA Pro 3.2.186: the app starts but ignores the project
2492
+ // argument passed on the command line (it opens on HOME), so the caller must
2493
+ // not assume the project was opened.
2494
+ projectOpenedByArgument: false,
2495
+ projectNote: project === void 0 || project === "" ? null : "The app was started with the project path, but this JLCEDA Pro build ignores it and opens on HOME; open the project from the app itself.",
2496
+ target: { command: plan.command, args: plan.args },
2497
+ connected: waited.connected,
2498
+ connectedClients: waited.clients,
2499
+ waitedMs: waited.waitedMs,
2500
+ hint: waited.connected ? "JLCEDA is connected; the eda_* tools can be used now." : "The app was started but no EDA extension connected yet. In JLCEDA Pro: \u6269\u5C55 \u2192 DSH MCP \u2192 \u8FDE\u63A5 (and enable \u201C\u5141\u8BB8\u5916\u90E8\u4EA4\u4E92\u201D); the extension must be imported once from dsh-eda-bridge-extension-" + VERSION + ".zip."
2501
+ };
2502
+ }
2503
+ case "eda_get_page_info": {
2504
+ const paper = paperOf(args.paper);
2505
+ let page;
2506
+ try {
2507
+ page = await callExtension("dmt_Schematic.getCurrentSchematicPageInfo", [], timeoutMs);
2508
+ } catch {
2509
+ page = void 0;
2510
+ }
2511
+ return {
2512
+ page,
2513
+ units: { mcp: "0.01 inch", internal: "inch", factor: MCP_UNITS_PER_INCH },
2514
+ paper: paper.name,
2515
+ frame: paper.frame,
2516
+ titleBlock: paper.titleBlock,
2517
+ safeAreas: safeAreas(paper.name),
2518
+ note: "Coordinates are MCP units (0.01 inch). Frame origin is the lower-left corner, y grows upward. Title-block overlap is rejected by eda_place_component."
2519
+ };
2520
+ }
2521
+ case "eda_get_schematic_pages": {
2522
+ if (typeof args.pageUuid === "string" && args.pageUuid !== "") {
2523
+ return await callExtension("dmt_Schematic.getSchematicPageInfo", [args.pageUuid], timeoutMs);
2524
+ }
2525
+ return await callExtension("dmt_Schematic.getCurrentSchematicAllSchematicPagesInfo", [], timeoutMs);
2526
+ }
2527
+ case "eda_search_components": {
2528
+ const keyword = String(args.keyword ?? "");
2529
+ if (keyword.trim() === "") throw new Error("keyword is required");
2530
+ const limit = Math.max(1, Math.min(50, Number(args.limit ?? 20)));
2531
+ return await callExtension("lib_Device.search", [keyword, void 0, void 0, void 0, limit, 1], timeoutMs);
2532
+ }
2533
+ case "eda_place_component": {
2534
+ const x = Number(args.x);
2535
+ const y = Number(args.y);
2536
+ const paper = args.paper;
2537
+ const allowOutside = args.allowOutsideFrame === true;
2538
+ if (!allowOutside) {
2539
+ const problem = checkPointInFrame(x, y, paper, 5) ?? checkPointAgainstTitleBlock(x, y, paper, 5);
2540
+ if (problem !== void 0) throw new Error("eda_place_component refused: " + problem);
2541
+ }
2542
+ const component = { libraryUuid: String(args.libraryUuid), uuid: String(args.uuid) };
2543
+ const result2 = await callExtension("sch_PrimitiveComponent.create", [
2544
+ component,
2545
+ x,
2546
+ y,
2547
+ args.subPartName,
2548
+ Number(args.rotation ?? 0),
2549
+ Boolean(args.mirror ?? false),
2550
+ args.addIntoBom === void 0 ? true : Boolean(args.addIntoBom),
2551
+ args.addIntoPcb === void 0 ? true : Boolean(args.addIntoPcb)
2552
+ ], timeoutMs);
2553
+ const primitiveId = extractPrimitiveId(result2);
2554
+ if (primitiveId !== void 0 && (args.designator !== void 0 || args.value !== void 0 || args.name !== void 0)) {
2555
+ const otherProperty = {};
2556
+ if (args.value !== void 0) otherProperty.Value = String(args.value);
2557
+ const property = {};
2558
+ if (args.designator !== void 0) property.designator = String(args.designator);
2559
+ if (args.name !== void 0) property.name = String(args.name);
2560
+ if (Object.keys(otherProperty).length > 0) property.otherProperty = otherProperty;
2561
+ await callExtension("sch_PrimitiveComponent.modify", [primitiveId, property], timeoutMs);
2562
+ }
2563
+ if (primitiveId !== void 0 && !allowOutside) {
2564
+ const bbox = await bboxOf([primitiveId], timeoutMs);
2565
+ if (bbox !== void 0) {
2566
+ const problem = checkBBoxInFrame(bbox, paper, 0);
2567
+ if (problem !== void 0) {
2568
+ try {
2569
+ await callExtension("sch_PrimitiveComponent.delete", [primitiveId], timeoutMs);
2570
+ } catch {
2571
+ }
2572
+ throw new Error("eda_place_component rolled back: " + problem + ". Move the component into a safe area or pass allowOutsideFrame=true.");
2573
+ }
2574
+ }
2575
+ }
2576
+ if (designBrief === null) {
2577
+ const intake = buildIntake(null);
2578
+ return {
2579
+ primitiveId,
2580
+ result: result2,
2581
+ intakeWarning: {
2582
+ message: "No design parameters confirmed this session: supply, MCU, clocks, connectors, board size, layer count and fabrication were not agreed. Confirm them with eda_design_intake + ask_user_question before continuing, or the board may be electrically correct and practically wrong.",
2583
+ criticalCount: intake.criticalCount,
2584
+ firstMissing: intake.missingCritical.slice(0, 8)
2585
+ }
2586
+ };
2587
+ }
2588
+ return { primitiveId, result: result2 };
2589
+ }
2590
+ case "eda_place_net_flag": {
2591
+ const x = Number(args.x);
2592
+ const y = Number(args.y);
2593
+ assertNetName(String(args.net), "eda_place_net_flag");
2594
+ if (args.allowOutsideFrame !== true) {
2595
+ const problem = checkPointInFrame(x, y, args.paper, 5) ?? checkPointAgainstTitleBlock(x, y, args.paper, 5);
2596
+ if (problem !== void 0) throw new Error("eda_place_net_flag refused: " + problem);
2597
+ }
2598
+ return await callExtension("sch_PrimitiveComponent.createNetFlag", [
2599
+ String(args.identification),
2600
+ String(args.net),
2601
+ x,
2602
+ y,
2603
+ Number(args.rotation ?? 0),
2604
+ Boolean(args.mirror ?? false)
2605
+ ], timeoutMs);
2606
+ }
2607
+ case "eda_place_net_port": {
2608
+ const x = Number(args.x);
2609
+ const y = Number(args.y);
2610
+ assertNetName(String(args.net), "eda_place_net_port");
2611
+ if (args.allowOutsideFrame !== true) {
2612
+ const problem = checkPointInFrame(x, y, args.paper, 5) ?? checkPointAgainstTitleBlock(x, y, args.paper, 5);
2613
+ if (problem !== void 0) throw new Error("eda_place_net_port refused: " + problem);
2614
+ }
2615
+ return await callExtension("sch_PrimitiveComponent.createNetPort", [
2616
+ String(args.direction),
2617
+ String(args.net),
2618
+ x,
2619
+ y,
2620
+ Number(args.rotation ?? 0),
2621
+ Boolean(args.mirror ?? false)
2622
+ ], timeoutMs);
2623
+ }
2624
+ case "eda_get_pins": {
2625
+ const componentPrimitiveId = String(args.componentPrimitiveId ?? "");
2626
+ if (componentPrimitiveId === "") throw new Error("componentPrimitiveId is required");
2627
+ const raw = await callExtension("sch_PrimitiveComponent.getAllPinsByPrimitiveId", [componentPrimitiveId], timeoutMs);
2628
+ if (!Array.isArray(raw)) return raw;
2629
+ return raw.map((entry) => {
2630
+ const record = asRecord(entry);
2631
+ return {
2632
+ primitiveId: pickValue(record, "PrimitiveId", "primitiveId"),
2633
+ pinNumber: pickValue(record, "PinNumber", "pinNumber") ?? null,
2634
+ pinName: pickValue(record, "PinName", "pinName") ?? null,
2635
+ x: pickValue(record, "X", "x"),
2636
+ y: pickValue(record, "Y", "y"),
2637
+ rotation: pickValue(record, "Rotation", "rotation") ?? 0,
2638
+ pinLength: pickValue(record, "PinLength", "pinLength") ?? null,
2639
+ noConnected: pickValue(record, "NoConnected", "noConnected") ?? null
2640
+ };
2641
+ });
2642
+ }
2643
+ case "eda_place_net_flag_at_pin":
2644
+ case "eda_place_net_label_at_pin":
2645
+ return await placeAtPin(name, args, timeoutMs);
2646
+ case "eda_place_net_label": {
2647
+ const x = Number(args.x);
2648
+ const y = Number(args.y);
2649
+ if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error("eda_place_net_label requires numeric x/y");
2650
+ return await placeNetLabel(String(args.net), x, y, args.fontSize, timeoutMs, {
2651
+ probe: args.probe === true,
2652
+ textLabel: args.textLabel === true
2653
+ });
2654
+ }
2655
+ case "eda_place_net_labels": {
2656
+ const items = Array.isArray(args.items) ? args.items.map(asRecord) : [];
2657
+ if (items.length === 0) throw new Error("eda_place_net_labels requires items: [{ pinPrimitiveId, net }] or [{ x, y, net }]");
2658
+ const concurrency = Number.isFinite(Number(args.concurrency)) ? Math.max(1, Math.min(8, Number(args.concurrency))) : 4;
2659
+ const results = await mapLimit(items, concurrency, async (item) => {
2660
+ const net = item.net === void 0 ? "" : String(item.net);
2661
+ try {
2662
+ const placed = item.pinPrimitiveId !== void 0 ? await placeAtPin("eda_place_net_label_at_pin", { ...item, net }, timeoutMs) : await placeNetLabel(net, Number(item.x), Number(item.y), item.fontSize, timeoutMs, {
2663
+ probe: args.probe === true,
2664
+ textLabel: args.textLabel === true
2665
+ });
2666
+ return { ok: true, net, ...placed };
2667
+ } catch (error) {
2668
+ return { ok: false, net, error: error instanceof Error ? error.message : String(error) };
2669
+ }
2670
+ });
2671
+ const done = results.filter((entry) => entry.ok).length;
2672
+ return {
2673
+ total: items.length,
2674
+ done,
2675
+ failed: items.length - done,
2676
+ method: netLabelSupport === true ? "netLabel" : "text",
2677
+ results
2678
+ };
2679
+ }
2680
+ case "eda_get_net_labels": {
2681
+ const attributes = await callExtension("sch_PrimitiveAttribute.getAll", [
2682
+ args.parentPrimitiveId === void 0 ? void 0 : String(args.parentPrimitiveId)
2683
+ ], timeoutMs).catch(() => []);
2684
+ const texts = args.parentPrimitiveId === void 0 ? await callExtension("sch_PrimitiveText.getAll", [], timeoutMs).catch(() => []) : [];
2685
+ const entries = [];
2686
+ for (const entry of Array.isArray(attributes) ? attributes : []) {
2687
+ const record = asRecord(entry);
2688
+ entries.push({
2689
+ primitiveId: pickValue(record, "PrimitiveId", "primitiveId"),
2690
+ kind: String(pickValue(record, "PrimitiveType", "primitiveType", "Type", "type") ?? "attribute"),
2691
+ net: pickValue(record, "Net", "net") ?? null,
2692
+ userValue: pickValue(record, "UserValue", "userValue", "Value", "value") ?? null,
2693
+ x: pickValue(record, "X", "x"),
2694
+ y: pickValue(record, "Y", "y")
2695
+ });
2696
+ }
2697
+ for (const entry of Array.isArray(texts) ? texts : []) {
2698
+ const record = asRecord(entry);
2699
+ const content = String(pickValue(record, "Content", "content", "Text", "text") ?? "");
2700
+ if (content === "") continue;
2701
+ entries.push({
2702
+ primitiveId: pickValue(record, "PrimitiveId", "primitiveId"),
2703
+ kind: "text",
2704
+ net: content,
2705
+ userValue: content,
2706
+ x: pickValue(record, "X", "x"),
2707
+ y: pickValue(record, "Y", "y")
2708
+ });
2709
+ }
2710
+ return {
2711
+ count: entries.length,
2712
+ attributeCount: Array.isArray(attributes) ? attributes.length : 0,
2713
+ textCount: Array.isArray(texts) ? texts.length : 0,
2714
+ sessionTextLabels: placedTextLabels.length,
2715
+ note: 'kind "text" entries are plain texts (no electrical meaning). Delete any entry with eda_delete_primitive(kind: "netlabel"|"netport"|"netflag"|"text", primitiveId).',
2716
+ labels: entries
2717
+ };
2718
+ }
2719
+ case "eda_get_active_document": {
2720
+ const info = await callExtension("dmt_SelectControl.getCurrentDocumentInfo", [], timeoutMs);
2721
+ const record = asRecord(info);
2722
+ const type = Number(record.documentType);
2723
+ return { document: info, documentTypeName: DOCUMENT_TYPES[type] ?? String(record.documentType ?? "unknown"), documentType: record.documentType };
2724
+ }
2725
+ case "eda_open_document": {
2726
+ const documentUuid = String(args.documentUuid ?? "");
2727
+ if (documentUuid === "") throw new Error("documentUuid is required");
2728
+ const raw = await callExtension("dmt_EditorControl.openDocument", [
2729
+ documentUuid,
2730
+ args.splitScreenId === void 0 ? void 0 : String(args.splitScreenId)
2731
+ ], timeoutMs);
2732
+ await sleep(600);
2733
+ let tabIds = [];
2734
+ try {
2735
+ const tree = asRecord(await callExtension("dmt_EditorControl.getSplitScreenTree", [], Math.min(timeoutMs, 4e3)));
2736
+ tabIds = (Array.isArray(tree.tabs) ? tree.tabs : []).map((tab) => String(pickValue(asRecord(tab), "tabId") ?? ""));
2737
+ } catch {
2738
+ }
2739
+ let activeUuid = "";
2740
+ try {
2741
+ const info = asRecord(await callExtension("dmt_SelectControl.getCurrentDocumentInfo", [], Math.min(timeoutMs, 4e3)));
2742
+ activeUuid = String(pickValue(info, "uuid", "Uuid") ?? "");
2743
+ } catch {
2744
+ }
2745
+ const activeIsTarget = activeUuid === documentUuid;
2746
+ const tabOpened = activeIsTarget || tabIds.some((tab) => tab.startsWith(documentUuid + "@"));
2747
+ return {
2748
+ ...raw !== null && typeof raw === "object" ? raw : { result: raw ?? null },
2749
+ opened: tabOpened,
2750
+ activated: activeIsTarget,
2751
+ activeDocumentUuid: activeUuid || null,
2752
+ tabIds,
2753
+ hint: tabOpened ? null : "The app accepted openDocument but the document is not active (activeDocumentUuid=" + (activeUuid || "unknown") + ", tabs: " + (tabIds.join(", ") || "none") + "). After an app restart the editor sits on the Start Page: open the project first (eda_open_project), then open the document. This build cannot open a document from the HOME screen programmatically, so never assume a page is active without checking activeDocumentUuid."
2754
+ };
2755
+ }
2756
+ case "eda_set_no_connect": {
2757
+ const ids = Array.isArray(args.primitiveIds) ? args.primitiveIds.map(String) : [];
2758
+ if (ids.length === 0) throw new Error("primitiveIds is required");
2759
+ const noConnected = args.noConnected === void 0 ? true : Boolean(args.noConnected);
2760
+ const results = await mapLimit(ids, 8, async (id) => {
2761
+ try {
2762
+ return { id, ok: true, result: await callExtension("sch_PrimitivePin.modify", [id, { noConnected }], timeoutMs) };
2763
+ } catch (error) {
2764
+ return { id, ok: false, error: error instanceof Error ? error.message : String(error) };
2765
+ }
2766
+ });
2767
+ return { noConnected, results };
2768
+ }
2769
+ case "eda_draw_wire": {
2770
+ const points = flattenPoints(args.points);
2771
+ if (points.length < 4 || points.length % 2 !== 0) throw new Error("points must be a flat array with an even length >= 4");
2772
+ if (args.net !== void 0 && String(args.net) !== "") assertNetName(String(args.net), "eda_draw_wire");
2773
+ const wire = await callExtension("sch_PrimitiveWire.create", [
2774
+ points,
2775
+ args.net,
2776
+ args.color,
2777
+ args.lineWidth === void 0 ? void 0 : Number(args.lineWidth),
2778
+ args.lineType === void 0 ? void 0 : Number(args.lineType)
2779
+ ], timeoutMs);
2780
+ const warnings = args.net === void 0 || String(args.net) === "" ? [] : checkNetName(String(args.net)).warnings;
2781
+ return warnings.length === 0 ? wire : { created: wire, rules: { warnings } };
2782
+ }
2783
+ case "eda_draw_rectangle":
2784
+ return await callExtension("sch_PrimitiveRectangle.create", [
2785
+ Number(args.topLeftX),
2786
+ Number(args.topLeftY),
2787
+ Number(args.width),
2788
+ Number(args.height),
2789
+ args.cornerRadius === void 0 ? void 0 : Number(args.cornerRadius),
2790
+ args.rotation === void 0 ? void 0 : Number(args.rotation),
2791
+ args.color,
2792
+ args.fillColor,
2793
+ args.lineWidth === void 0 ? void 0 : Number(args.lineWidth),
2794
+ args.lineType === void 0 ? void 0 : Number(args.lineType),
2795
+ args.fillStyle
2796
+ ], timeoutMs);
2797
+ case "eda_draw_functional_box": {
2798
+ const margin = args.margin === void 0 ? 1 : Number(args.margin);
2799
+ let ids = Array.isArray(args.componentIds) ? args.componentIds.map(String) : [];
2800
+ if (ids.length === 0) {
2801
+ const all = await callExtension("sch_PrimitiveComponent.getAll", ["part", false], timeoutMs);
2802
+ if (Array.isArray(all)) ids = all.map((item) => extractPrimitiveId(item)).filter((id) => typeof id === "string");
2803
+ }
2804
+ if (ids.length === 0) throw new Error("no components found to box");
2805
+ const bbox = await bboxOf(ids, timeoutMs);
2806
+ if (bbox === void 0) throw new Error("could not compute component bounding box");
2807
+ const left = bbox.minX - margin;
2808
+ const right = bbox.maxX + margin;
2809
+ const bottom = bbox.minY - margin;
2810
+ const top = bbox.maxY + margin;
2811
+ const rectangle = await callExtension("sch_PrimitiveRectangle.create", [
2812
+ left,
2813
+ top,
2814
+ right - left,
2815
+ top - bottom,
2816
+ 0,
2817
+ 0,
2818
+ args.color ?? null,
2819
+ "none",
2820
+ args.lineWidth === void 0 ? 1 : Number(args.lineWidth),
2821
+ args.lineType === void 0 ? 1 : Number(args.lineType),
2822
+ "None"
2823
+ ], timeoutMs);
2824
+ let label;
2825
+ if (typeof args.label === "string" && args.label.trim() !== "") {
2826
+ label = await callExtension("sch_PrimitiveText.create", [
2827
+ left + 4,
2828
+ top - 14,
2829
+ args.label,
2830
+ 0,
2831
+ null,
2832
+ null,
2833
+ 12,
2834
+ false,
2835
+ false,
2836
+ false,
2837
+ 1
2838
+ ], timeoutMs);
2839
+ }
2840
+ return { bbox, box: { left, right, bottom, top }, rectangle, label };
2841
+ }
2842
+ case "eda_draw_circle":
2843
+ return await callExtension("sch_PrimitiveCircle.create", [
2844
+ Number(args.centerX),
2845
+ Number(args.centerY),
2846
+ Number(args.radius),
2847
+ args.color,
2848
+ args.fillColor,
2849
+ args.lineWidth === void 0 ? void 0 : Number(args.lineWidth),
2850
+ args.lineType === void 0 ? void 0 : Number(args.lineType),
2851
+ args.fillStyle
2852
+ ], timeoutMs);
2853
+ case "eda_draw_text":
2854
+ return await callExtension("sch_PrimitiveText.create", [
2855
+ Number(args.x),
2856
+ Number(args.y),
2857
+ String(args.content),
2858
+ Number(args.rotation ?? 0),
2859
+ args.textColor,
2860
+ args.fontName,
2861
+ args.fontSize === void 0 ? void 0 : Number(args.fontSize),
2862
+ Boolean(args.bold ?? false),
2863
+ Boolean(args.italic ?? false),
2864
+ Boolean(args.underLine ?? false),
2865
+ args.alignMode === void 0 ? void 0 : Number(args.alignMode)
2866
+ ], timeoutMs);
2867
+ case "eda_save_document":
2868
+ return await callExtension("sch_Document.save", [], timeoutMs);
2869
+ case "eda_zoom_to_fit": {
2870
+ const raw = await callExtension("dmt_EditorControl.zoomToAllPrimitives", [args.tabId], timeoutMs);
2871
+ const record = asRecord(raw);
2872
+ const left = Number(pickValue(record, "left", "Left"));
2873
+ const right = Number(pickValue(record, "right", "Right"));
2874
+ const bottom = Number(pickValue(record, "bottom", "Bottom"));
2875
+ const top = Number(pickValue(record, "top", "Top"));
2876
+ if (![left, right, bottom, top].every((value) => Number.isFinite(value))) return raw;
2877
+ const frame = paperOf(args.paper).frame;
2878
+ const clamped = {
2879
+ left: Math.max(frame.left, left),
2880
+ right: Math.min(frame.right, right),
2881
+ bottom: Math.max(frame.bottom, bottom),
2882
+ top: Math.min(frame.top, top)
2883
+ };
2884
+ if (clamped.left >= clamped.right || clamped.bottom >= clamped.top) {
2885
+ return { ...record, requested: { left, right, bottom, top }, clamped: null, note: "the primitive bounds do not overlap the page frame" };
2886
+ }
2887
+ await callExtension("dmt_EditorControl.zoomToRegion", [
2888
+ clamped.left,
2889
+ clamped.right,
2890
+ clamped.top,
2891
+ clamped.bottom,
2892
+ args.tabId
2893
+ ], timeoutMs);
2894
+ return { ...record, requested: { left, right, bottom, top }, clamped };
2895
+ }
2896
+ case "eda_zoom_to_region":
2897
+ return await callExtension("dmt_EditorControl.zoomToRegion", [
2898
+ Number(args.left),
2899
+ Number(args.right),
2900
+ Number(args.top),
2901
+ Number(args.bottom),
2902
+ args.tabId
2903
+ ], timeoutMs);
2904
+ case "eda_get_components": {
2905
+ const raw = await callExtension("sch_PrimitiveComponent.getAll", ["part", Boolean(args.allSchematicPages ?? false)], timeoutMs);
2906
+ if (!Array.isArray(raw)) return raw;
2907
+ const summarized = raw.map(summarizePrimitive);
2908
+ if (args.includeBounds === false) return summarized;
2909
+ return await mapLimit(summarized, 8, async (item) => {
2910
+ const id = typeof item.primitiveId === "string" ? item.primitiveId : void 0;
2911
+ if (id === void 0) return item;
2912
+ try {
2913
+ const bbox = await bboxOf([id], timeoutMs);
2914
+ return bbox === void 0 ? item : { ...item, bbox, width: bbox.maxX - bbox.minX, height: bbox.maxY - bbox.minY };
2915
+ } catch {
2916
+ return item;
2917
+ }
2918
+ });
2919
+ }
2920
+ case "eda_get_wires": {
2921
+ const raw = await callExtension("sch_PrimitiveWire.getAll", [], timeoutMs);
2922
+ if (Array.isArray(raw)) return raw.map(summarizePrimitive);
2923
+ return raw;
2924
+ }
2925
+ case "eda_get_nets": {
2926
+ if (typeof args.name === "string" && args.name !== "") {
2927
+ const single = await callExtension("sch_Net.getNet", [args.name], timeoutMs);
2928
+ if (single !== void 0 && single !== null) return { source: "sch_Net.getNet", net: single };
2929
+ return { source: "sch_Net.getNet", net: null, hint: NET_EMPTY_HINT };
2930
+ }
2931
+ const project = await callExtension("sch_Net.getCurrentProjectAllNets", [], timeoutMs);
2932
+ if (Array.isArray(project) && project.length > 0) return { source: "sch_Net.getCurrentProjectAllNets", count: project.length, nets: project };
2933
+ const all = await callExtension("sch_Net.getAllNets", [], timeoutMs);
2934
+ if (Array.isArray(all) && all.length > 0) return { source: "sch_Net.getAllNets", count: all.length, nets: all };
2935
+ if (args.parseNetlist === false) return { source: "sch_Net.*", count: 0, nets: [], hint: NET_EMPTY_HINT };
2936
+ const parsed = await parseNetlist2(Array.isArray(all) ? all : project, timeoutMs);
2937
+ return parsed;
2938
+ }
2939
+ case "eda_run_drc": {
2940
+ const verbose = await callExtension("sch_Drc.check", [
2941
+ args.strict === void 0 ? true : Boolean(args.strict),
2942
+ false,
2943
+ true
2944
+ ], toolTimeout(args, timeoutMs));
2945
+ if (Array.isArray(verbose)) {
2946
+ return {
2947
+ ok: verbose.length === 0,
2948
+ count: verbose.length,
2949
+ entries: verbose.map((entry) => {
2950
+ const record = asRecord(entry);
2951
+ return {
2952
+ type: pickValue(record, "Type", "type", "Level", "level") ?? null,
2953
+ message: pickValue(record, "Message", "message", "Error", "error", "Description", "description") ?? null,
2954
+ primitiveId: pickValue(record, "PrimitiveId", "primitiveId") ?? null,
2955
+ x: pickValue(record, "X", "x") ?? null,
2956
+ y: pickValue(record, "Y", "y") ?? null,
2957
+ raw: entry
2958
+ };
2959
+ }),
2960
+ hint: 'EDA 3.2.186 returns AGGREGATED entries only (e.g. {type:"warn",count:1}) even with includeVerboseError, so message/primitiveId stay null \u2014 "raw" carries exactly what the app sent. Per-problem coordinates are not available on this build; use eda_pcb_run_drc for the PCB side and the DRC panel for details.'
2961
+ };
2962
+ }
2963
+ return { ok: Boolean(verbose), count: null, entries: [], raw: verbose };
2964
+ }
2965
+ case "eda_auto_layout":
2966
+ case "eda_auto_route": {
2967
+ if (ALLOW_AUTO_LAYOUT !== true && args.force !== true) {
2968
+ throw new Error(
2969
+ name + " is disabled by policy (settings allowAutoLayoutRouting=false, env DSH_EDA_ALLOW_AUTO_LAYOUT). Do NOT retry with force:true unless the user explicitly asked for automatic layout/routing.",
2970
+ "",
2971
+ "Do this instead, in order:",
2972
+ "1. eda_get_active_document \u2014 make sure a schematic page is active (eda_open_document if not).",
2973
+ "2. eda_get_page_info \u2014 read the A4 frame and the safe areas before placing anything.",
2974
+ "3. eda_get_components \u2014 see what is already placed and where (x/y + bounding boxes) to avoid overlap.",
2975
+ "4. Place or move parts yourself on a 10-unit grid: eda_place_component for new ones, eda_move_component (keeps designator/value) to re-grid existing ones. Signal flow left to right, power rails on top, ground at the bottom, >=20 units between symbols for wires and labels.",
2976
+ "5. Connect with eda_draw_wire for local nets; for anything that spans the sheet use eda_place_net_port or a net label (a wire net name is overridden by connectivity once an endpoint touches a pin).",
2977
+ "6. Verify: eda_export_netlist (every net should have >=2 endpoints) and eda_run_drc (per-problem entries). For a visual check export the canvas to an image and look at it, rather than letting EDA rearrange the sheet.",
2978
+ "7. Call eda_workflow_guide for the full standard."
2979
+ );
2980
+ }
2981
+ const payload = Array.isArray(args.uuids) ? { uuids: args.uuids.map(String) } : void 0;
2982
+ return await callExtension(name === "eda_auto_layout" ? "sch_Document.autoLayout" : "sch_Document.autoRouting", [payload], toolTimeout(args, timeoutMs));
2983
+ }
2984
+ case "eda_export_netlist": {
2985
+ const payload = await callExtension("sch_ManufactureData.getNetlistFile", [
2986
+ void 0,
2987
+ typeof args.type === "string" && args.type !== "" ? args.type : void 0
2988
+ ], toolTimeout(args, timeoutMs));
2989
+ const text = typeof payload === "string" ? payload : payload !== null && typeof payload === "object" && typeof payload.text === "string" ? payload.text : void 0;
2990
+ if (text === void 0) return { parsed: false, netlist: payload ?? null };
2991
+ if (args.format === "text") return { parsed: false, netlistText: text, bytes: text.length };
2992
+ try {
2993
+ return { parsed: true, bytes: text.length, netlist: JSON.parse(text) };
2994
+ } catch {
2995
+ return { parsed: false, bytes: text.length, netlistText: text };
2996
+ }
2997
+ }
2998
+ case "eda_export_bom": {
2999
+ const format = args.format === "xlsx" ? "xlsx" : "csv";
3000
+ const payload = await callExtension("sch_ManufactureData.getBomFile", [void 0, format], toolTimeout(args, timeoutMs));
3001
+ if (format === "xlsx") return payload;
3002
+ const raw = typeof payload === "string" ? payload : payload !== null && typeof payload === "object" && typeof payload.text === "string" ? payload.text : "";
3003
+ if (raw === "") {
3004
+ throw new Error("eda_export_bom: no BOM data (the schematic page must be the active document; call eda_get_active_document, then eda_open_document on the schematic page and retry)");
3005
+ }
3006
+ const encoding = payload !== null && typeof payload === "object" ? payload.encoding : void 0;
3007
+ return { format, bom: decodeTextPayload(raw), encoding: encoding ?? "unknown" };
3008
+ }
3009
+ case "eda_delete_primitive": {
3010
+ const kind = String(args.kind);
3011
+ const className = kind === "netport" || kind === "netflag" || kind === "netlabel" ? "sch_PrimitiveAttribute" : primitiveKindToClass(kind);
3012
+ return await callExtension(className + ".delete", [String(args.primitiveId)], timeoutMs);
3013
+ }
3014
+ case "eda_move_component":
3015
+ return await callExtension("sch_PrimitiveComponent.modify", [String(args.primitiveId), {
3016
+ x: args.x === void 0 ? void 0 : Number(args.x),
3017
+ y: args.y === void 0 ? void 0 : Number(args.y),
3018
+ rotation: args.rotation === void 0 ? void 0 : Number(args.rotation),
3019
+ mirror: args.mirror === void 0 ? void 0 : Boolean(args.mirror)
3020
+ }], timeoutMs);
3021
+ case "eda_extension_package": {
3022
+ const manifestPath = join(packageRoot(), "lib", "extension-digest.json");
3023
+ let expected = {};
3024
+ try {
3025
+ expected = JSON.parse(await readFile(manifestPath, "utf8"));
3026
+ } catch {
3027
+ expected = {};
3028
+ }
3029
+ const version = typeof expected.version === "string" && expected.version !== "" ? expected.version : VERSION;
3030
+ const expectedSha256 = typeof expected.sha256 === "string" ? expected.sha256 : "";
3031
+ const localPath = join(packageRoot(), extensionZipName(version));
3032
+ const localSource = existsSync(localPath) ? localPath : null;
3033
+ const localBytes = localSource === null ? null : await readFile(localSource);
3034
+ const base = typeof args.base === "string" && args.base !== "" ? args.base : process.env.DSH_EDA_EXTENSION_BASE ?? "http://159.75.130.207/eda/";
3035
+ const url = extensionDownloadUrl(base, version);
3036
+ const report = {
3037
+ version,
3038
+ expected: { bytes: Number(expected.bytes ?? 0), sha256: expectedSha256, manifest: manifestPath },
3039
+ localZip: localSource === null ? null : { path: localSource, bytes: localBytes.byteLength, sha256: sha256Of(localBytes) },
3040
+ url
3041
+ };
3042
+ if (args.download !== true) return report;
3043
+ const response = await fetch(url, { signal: AbortSignal.timeout(3e4) });
3044
+ if (!response.ok) {
3045
+ const throttled = response.status === 429;
3046
+ return {
3047
+ ...report,
3048
+ verified: "unverified",
3049
+ httpStatus: response.status,
3050
+ error: throttled ? "the download server throttled this IP (HTTP 429, 5 downloads/min per IP \u2014 burst 5). Wait about a minute and retry; nothing is wrong with the zip or the upload." : "download failed: HTTP " + response.status + " from " + url
3051
+ };
3052
+ }
3053
+ const remoteBytes = new Uint8Array(await response.arrayBuffer());
3054
+ const remoteSha256 = sha256Of(remoteBytes);
3055
+ const verdict = compareDigest(expectedSha256, remoteSha256);
3056
+ const result2 = {
3057
+ ...report,
3058
+ served: { url, bytes: remoteBytes.byteLength, sha256: remoteSha256 },
3059
+ verified: verdict
3060
+ };
3061
+ if (verdict === "match") {
3062
+ const outDir = typeof args.outDir === "string" && args.outDir !== "" ? args.outDir : tmpdir();
3063
+ await mkdir(outDir, { recursive: true });
3064
+ const savedPath = join(outDir, extensionZipName(version));
3065
+ await writeFile(savedPath, remoteBytes);
3066
+ result2.savedPath = savedPath;
3067
+ result2.next = "In JLCEDA Pro: \u6269\u5C55 \u2192 \u5BFC\u5165\u6269\u5C55 \u2192 select this zip \u2192 restart the application (not a reload).";
3068
+ } else if (verdict === "mismatch") {
3069
+ result2.next = "The served copy differs from the digest this plugin was built with (wire version " + version + "). Do not import it: re-upload " + extensionZipName(version) + " from the build output to the download server.";
3070
+ } else {
3071
+ result2.next = "No expected digest in " + manifestPath + "; rebuild the plugin so it records one.";
3072
+ }
3073
+ return result2;
3074
+ }
3075
+ case "eda_list_api_methods": {
3076
+ const live = await extensionApiMethods(timeoutMs, args.refresh === true);
3077
+ if (live !== void 0) {
3078
+ return {
3079
+ source: "extension",
3080
+ extensionVersion: live.version,
3081
+ count: live.all.length,
3082
+ allowedCount: live.allowed.length,
3083
+ fileCount: live.files.length,
3084
+ fileMethods: live.files,
3085
+ methods: live.all,
3086
+ note: "This is the list the connected extension enforces (dsh.internal.listApiMethods). sendable:true means eda_api_call will forward it."
3087
+ };
3088
+ }
3089
+ return {
3090
+ source: "bridge-local-copy",
3091
+ stale: true,
3092
+ count: ALLOWED_API.size,
3093
+ methods: [...ALLOWED_API].sort(),
3094
+ note: "The connected extension does not expose its list (older zip), so this is the bridge copy \u2014 it may be narrower than what the extension accepts. eda_api_call forwards unknown methods and reports the extension verdict, so try the call instead of trusting this list."
3095
+ };
3096
+ }
3097
+ case "pcb_draw_text": {
3098
+ const text = String(args.text ?? "");
3099
+ if (text.trim() === "") throw new Error("pcb_draw_text requires text");
3100
+ if (text.length > 200) throw new Error("pcb_draw_text: longer than 200 characters is probably a mistake; split it");
3101
+ const silkLayer = args.layer === void 0 ? PCB_LAYERS.topSilkscreen : resolvePcbLayer(args.layer);
3102
+ const fontSize = args.fontSize === void 0 ? 40 : Number(args.fontSize);
3103
+ return await callExtension("pcb_PrimitiveString.create", [
3104
+ silkLayer,
3105
+ Number(args.x),
3106
+ Number(args.y),
3107
+ text,
3108
+ "Arial",
3109
+ fontSize,
3110
+ args.lineWidth === void 0 ? Math.max(6, Math.round(fontSize / 6)) : Number(args.lineWidth),
3111
+ args.alignMode === void 0 ? 1 : Number(args.alignMode),
3112
+ args.rotation === void 0 ? 0 : Number(args.rotation),
3113
+ false,
3114
+ 0,
3115
+ Boolean(args.mirror ?? false),
3116
+ Boolean(args.locked ?? false)
3117
+ ], timeoutMs);
3118
+ }
3119
+ case "pcb_draw_mounting_hole": {
3120
+ const holeX = Number(args.x);
3121
+ const holeY = Number(args.y);
3122
+ const holeDiameter = Number(args.diameter);
3123
+ if (![holeX, holeY, holeDiameter].every((value) => Number.isFinite(value)) || holeDiameter <= 0) {
3124
+ throw new Error("pcb_draw_mounting_hole requires numeric x/y and a positive diameter (mil)");
3125
+ }
3126
+ if (holeDiameter < 20) throw new Error("pcb_draw_mounting_hole: " + holeDiameter + " mil is smaller than any drill (>= 20 mil)");
3127
+ const holeShape = String(args.shape ?? "round");
3128
+ const holeRotation = args.rotation === void 0 ? 0 : Number(args.rotation);
3129
+ const metallization = args.plated === true;
3130
+ let holeSpec;
3131
+ if (holeShape === "slot") {
3132
+ const slotLength = args.slotLength === void 0 ? holeDiameter * 2 : Number(args.slotLength);
3133
+ if (!Number.isFinite(slotLength) || slotLength <= holeDiameter) {
3134
+ throw new Error("pcb_draw_mounting_hole: slotLength must exceed the slot width (diameter)");
3135
+ }
3136
+ holeSpec = ["SLOT", holeDiameter, slotLength];
3137
+ } else {
3138
+ holeSpec = ["ROUND", holeDiameter];
3139
+ }
3140
+ const holeLayer = args.layer === void 0 ? PCB_LAYERS.multi : resolvePcbLayer(args.layer);
3141
+ const annulus = args.annulus === void 0 ? 0 : Number(args.annulus);
3142
+ if (!Number.isFinite(annulus) || annulus < 0) throw new Error("pcb_draw_mounting_hole: annulus must be >= 0 (mil)");
3143
+ const slotLengthValue = args.slotLength === void 0 ? holeDiameter * 2 : Number(args.slotLength);
3144
+ const padShape = holeShape === "slot" ? ["ELLIPSE", slotLengthValue + annulus * 2, holeDiameter + annulus * 2] : ["ELLIPSE", holeDiameter + annulus * 2, holeDiameter + annulus * 2];
3145
+ return await callExtension("pcb_PrimitivePad.create", [
3146
+ holeLayer,
3147
+ String(args.padNumber ?? ""),
3148
+ holeX,
3149
+ holeY,
3150
+ holeRotation,
3151
+ padShape,
3152
+ void 0,
3153
+ holeSpec,
3154
+ 0,
3155
+ 0,
3156
+ 0,
3157
+ metallization,
3158
+ void 0,
3159
+ void 0,
3160
+ void 0,
3161
+ void 0,
3162
+ false
3163
+ ], timeoutMs);
3164
+ }
3165
+ case "eda_schematic_audit": {
3166
+ const paper = paperOf(args.paper);
3167
+ const frame = paper.frame;
3168
+ const frameArea = (frame.right - frame.left) * (frame.top - frame.bottom);
3169
+ const rawList = await callExtension("sch_PrimitiveComponent.getAll", [], timeoutMs);
3170
+ const list = Array.isArray(rawList) ? rawList.slice(0, 200) : [];
3171
+ const components = [];
3172
+ let droppedSheetPrimitives = 0;
3173
+ for (let index = 0; index < list.length; index += 1) {
3174
+ const entry = list[index] ?? {};
3175
+ const designator = String(entry.designator ?? entry.Designator ?? entry.Name ?? entry.name ?? "#" + index);
3176
+ const id = String(entry.primitiveId ?? entry.PrimitiveId ?? "");
3177
+ let bounds;
3178
+ if (id !== "") {
3179
+ const box = await bboxOf([id], timeoutMs);
3180
+ if (box !== void 0) bounds = { left: box.minX, right: box.maxX, bottom: box.minY, top: box.maxY };
3181
+ }
3182
+ if (bounds !== void 0) {
3183
+ const boundsArea = (bounds.right - bounds.left) * (bounds.top - bounds.bottom);
3184
+ if (boundsArea > frameArea * 0.4) {
3185
+ bounds = void 0;
3186
+ droppedSheetPrimitives += 1;
3187
+ }
3188
+ }
3189
+ components.push({ designator, x: Number(entry.x ?? entry.X ?? 0), y: Number(entry.y ?? entry.Y ?? 0), bounds });
3190
+ }
3191
+ const report = auditSchematicGeometry({
3192
+ components,
3193
+ frame,
3194
+ titleBlock: paper.titleBlock,
3195
+ grid: args.grid === void 0 ? 10 : Number(args.grid)
3196
+ });
3197
+ const checks = args.includeOk === true ? report.checks : report.checks.filter((check) => check.status !== "pass");
3198
+ return {
3199
+ ok: report.ok,
3200
+ counts: report.counts,
3201
+ componentCount: report.componentCount,
3202
+ boxesRead: components.filter((component) => component.bounds !== void 0).length,
3203
+ droppedSheetPrimitives,
3204
+ checks,
3205
+ notes: droppedSheetPrimitives > 0 ? ["Skipped " + droppedSheetPrimitives + " primitive(s) whose box covers the whole sheet (frame/title block); counting them made every symbol look overlapped."] : []
3206
+ };
3207
+ }
3208
+ case "eda_delivery_checklist": {
3209
+ const steps = [];
3210
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
3211
+ const project = await callExtension("dmt_Project.getCurrentProjectInfo", [], timeoutMs).catch(() => null);
3212
+ const boards = Array.isArray(project?.data) ? project.data : [];
3213
+ const schematicPage = boards[0]?.schematic?.page?.[0]?.uuid ?? "";
3214
+ const pcbUuid = boards.find((board) => board?.pcb?.uuid)?.pcb?.uuid ?? "";
3215
+ const switchDocuments = args.switchDocuments !== false;
3216
+ const documentType = async () => {
3217
+ try {
3218
+ const info = await callExtension("dmt_SelectControl.getCurrentDocumentInfo", [], timeoutMs);
3219
+ return Number(info?.documentType);
3220
+ } catch {
3221
+ return NaN;
3222
+ }
3223
+ };
3224
+ const activate = async (uuid2) => {
3225
+ if (typeof uuid2 !== "string" || uuid2 === "") return false;
3226
+ try {
3227
+ await callExtension("dmt_EditorControl.openDocument", [uuid2], timeoutMs);
3228
+ await new Promise((resolve) => setTimeout(resolve, 1500));
3229
+ return true;
3230
+ } catch {
3231
+ return false;
3232
+ }
3233
+ };
3234
+ let netlistErc = null;
3235
+ const onSchematic = switchDocuments ? await activate(schematicPage) : await documentType() === 1;
3236
+ if (!onSchematic) {
3237
+ steps.push({ step: "netlist-erc", document: "schematic", ok: false, skipped: "schematic page is not the active document" });
3238
+ steps.push({ step: "bom", document: "schematic", ok: false, skipped: "schematic page is not the active document" });
3239
+ } else {
3240
+ try {
3241
+ const parsedNetlist = await fetchParsedNetlist(timeoutMs);
3242
+ netlistErc = runNetlistErc(parsedNetlist);
3243
+ steps.push({
3244
+ step: "netlist-erc",
3245
+ document: "schematic",
3246
+ ok: netlistErc.ok,
3247
+ detail: netlistErc.counts,
3248
+ failing: netlistErc.checks.filter((check) => check.status === "fail").map((check) => check.id)
3249
+ });
3250
+ } catch (error) {
3251
+ steps.push({ step: "netlist-erc", document: "schematic", ok: false, error: error instanceof Error ? error.message : String(error) });
3252
+ }
3253
+ }
3254
+ let bom = null;
3255
+ if (onSchematic) {
3256
+ try {
3257
+ const payload = await callExtension("sch_ManufactureData.getBomFile", [void 0, "csv"], timeoutMs);
3258
+ const text = typeof payload === "string" ? payload : typeof payload?.text === "string" ? payload.text : "";
3259
+ const lines = text === "" ? 0 : text.split(/\r?\n/).filter((line) => line.trim() !== "").length;
3260
+ bom = { rows: Math.max(0, lines - 1), ok: lines > 1 };
3261
+ steps.push({ step: "bom", document: "schematic", ok: bom.ok, detail: { rows: bom.rows }, ...bom.ok ? {} : { error: "no BOM rows exported" } });
3262
+ } catch (error) {
3263
+ steps.push({ step: "bom", document: "schematic", ok: false, error: error instanceof Error ? error.message : String(error) });
3264
+ }
3265
+ }
3266
+ const onPcb = switchDocuments ? await activate(pcbUuid) : await documentType() === 3;
3267
+ let pcbAudit = null;
3268
+ if (!onPcb) {
3269
+ steps.push({ step: "pcb-audit", document: "pcb", ok: false, skipped: "PCB is not the active document" });
3270
+ steps.push({ step: "gerber", document: "pcb", ok: false, skipped: "PCB is not the active document" });
3271
+ } else {
3272
+ try {
3273
+ pcbAudit = await auditPcb({ drc: args.pcbDrc !== false }, timeoutMs);
3274
+ steps.push({
3275
+ step: "pcb-audit",
3276
+ document: "pcb",
3277
+ ok: (pcbAudit.violations ?? []).length === 0,
3278
+ detail: { violations: pcbAudit.violations?.length ?? null, warnings: pcbAudit.warnings?.length ?? null, drc: pcbAudit.drc },
3279
+ failing: (pcbAudit.violations ?? []).map((entry) => entry.rule)
3280
+ });
3281
+ } catch (error) {
3282
+ steps.push({ step: "pcb-audit", document: "pcb", ok: false, error: error instanceof Error ? error.message : String(error) });
3283
+ }
3284
+ }
3285
+ let gerber = null;
3286
+ if (onPcb) {
3287
+ try {
3288
+ const payload = await callExtension("pcb_ManufactureData.getGerberFile", [void 0, void 0, void 0, void 0, void 0, void 0], timeoutMs);
3289
+ const bytes = payload && typeof payload === "object" ? Number(payload.size ?? payload.bytes ?? 0) : typeof payload === "string" ? payload.length : 0;
3290
+ gerber = { bytes, ok: bytes > 1e3 };
3291
+ steps.push({ step: "gerber", document: "pcb", ok: gerber.ok, detail: { bytes } });
3292
+ } catch (error) {
3293
+ steps.push({ step: "gerber", document: "pcb", ok: false, error: error instanceof Error ? error.message : String(error) });
3294
+ }
3295
+ }
3296
+ const failedSteps = steps.filter((step) => step.ok !== true && step.skipped === void 0);
3297
+ const skippedSteps = steps.filter((step) => step.ok !== true && step.skipped !== void 0);
3298
+ const verdict = failedSteps.length > 0 ? "fail" : skippedSteps.length > 0 ? "incomplete" : "pass";
3299
+ const report = {
3300
+ ok: verdict === "pass",
3301
+ verdict,
3302
+ failedSteps: failedSteps.map((step) => step.step),
3303
+ skippedSteps: skippedSteps.map((step) => step.step),
3304
+ next: verdict === "pass" ? "Every step passed: the board can be ordered." : verdict === "incomplete" ? "Run the checklist again with the other document active (" + skippedSteps.map((step) => step.document).filter((value, index, all) => all.indexOf(value) === index).join(", ") + " needed)." : "Fix the failing steps first; skipped steps are listed separately.",
3305
+ startedAt,
3306
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
3307
+ documents: { schematicPage, pcb: pcbUuid, switched: switchDocuments },
3308
+ netlistErc: netlistErc === null ? null : { ok: netlistErc.ok, counts: netlistErc.counts, componentCount: netlistErc.componentCount, netCount: netlistErc.netCount },
3309
+ pcbAudit: pcbAudit === null ? null : { violations: pcbAudit.violations, warnings: pcbAudit.warnings },
3310
+ gerber,
3311
+ bom
3312
+ };
3313
+ const outPath = args.outPath === void 0 ? "" : String(args.outPath).trim();
3314
+ if (outPath !== "") {
3315
+ const markdown = [
3316
+ "# \u4EA4\u4ED8\u68C0\u67E5\u62A5\u544A",
3317
+ "",
3318
+ "- \u5F00\u59CB\uFF1A" + report.startedAt,
3319
+ "- \u7ED3\u675F\uFF1A" + report.finishedAt,
3320
+ "- \u7ED3\u8BBA\uFF1A" + (report.ok ? "PASS\uFF08\u53EF\u4EE5\u4E0B\u5355\uFF09" : "FAIL\uFF08\u6709\u672A\u901A\u8FC7\u9879\uFF09"),
3321
+ "- \u539F\u7406\u56FE\u9875\uFF1A" + (schematicPage || "\u672A\u53D6\u5230"),
3322
+ "- PCB\uFF1A" + (pcbUuid || "\u672A\u53D6\u5230"),
3323
+ "",
3324
+ "| \u6B65\u9AA4 | \u6587\u6863 | \u7ED3\u679C | \u8BF4\u660E |",
3325
+ "|---|---|---|---|",
3326
+ ...steps.map((step) => "| " + step.step + " | " + step.document + " | " + (step.ok === true ? "PASS" : "FAIL") + " | " + JSON.stringify(step.detail ?? step.error ?? {}) + " |"),
3327
+ "",
3328
+ "## \u7535\u6C14\u68C0\u67E5\uFF08eda_netlist_erc\uFF09",
3329
+ "",
3330
+ ...netlistErc === null ? ["\uFF08\u672A\u6267\u884C\uFF09"] : netlistErc.checks.map((check) => "- [" + check.status + "] " + check.id + "\uFF1A" + check.message),
3331
+ "",
3332
+ "## PCB \u5BA1\u8BA1",
3333
+ "",
3334
+ ...pcbAudit === null ? ["\uFF08\u672A\u6267\u884C\uFF09"] : [
3335
+ "- \u8FDD\u89C4\uFF1A" + (pcbAudit.violations ?? []).length,
3336
+ "- \u8B66\u544A\uFF1A" + (pcbAudit.warnings ?? []).length,
3337
+ ...(pcbAudit.violations ?? []).map((entry) => " - " + entry.rule + "\uFF1A" + entry.message),
3338
+ ...(pcbAudit.warnings ?? []).map((entry) => " - (warn) " + entry.rule + "\uFF1A" + entry.message)
3339
+ ],
3340
+ "",
3341
+ "## \u5236\u9020\u6587\u4EF6",
3342
+ "",
3343
+ "- Gerber\uFF1A" + (gerber === null ? "\u672A\u5BFC\u51FA" : gerber.bytes + " \u5B57\u8282"),
3344
+ "- BOM\uFF1A" + (bom === null ? "\u672A\u5BFC\u51FA" : bom.rows + " \u884C"),
3345
+ ""
3346
+ ].join("\n");
3347
+ await writeFile(outPath, markdown);
3348
+ report.reportPath = outPath;
3349
+ }
3350
+ return report;
3351
+ }
3352
+ case "eda_design_intake": {
3353
+ if (args.reset === true) designBrief = null;
3354
+ if (designBrief === null) {
3355
+ try {
3356
+ const project = await callExtension("dmt_Project.getCurrentProjectInfo", [], timeoutMs);
3357
+ const stored = parseBriefBlock(project?.description);
3358
+ if (stored !== null) designBrief = stored;
3359
+ } catch {
3360
+ }
3361
+ }
3362
+ const answers = args.answers !== void 0 && args.answers !== null ? args.answers : null;
3363
+ const answersReport = buildIntake(answers);
3364
+ const merged = { ...designBrief ?? {}, ...answersReport.brief };
3365
+ const mergedReport = buildIntake(merged);
3366
+ let persisted = false;
3367
+ let persistVia = "none";
3368
+ let persistPath = "";
3369
+ if (Object.keys(merged).length > 0) {
3370
+ designBrief = merged;
3371
+ if (answers !== null) {
3372
+ try {
3373
+ const project = await callExtension("dmt_Project.getCurrentProjectInfo", [], timeoutMs);
3374
+ const projectUuid = String(project?.uuid ?? "");
3375
+ const existing = typeof project?.description === "string" ? project.description : "";
3376
+ const index = existing.indexOf(BRIEF_TAG);
3377
+ const base = index < 0 ? existing : existing.slice(0, index).trimEnd();
3378
+ const next = (base === "" ? "" : base + "\n") + briefBlock(merged);
3379
+ let stored = false;
3380
+ if (projectUuid !== "") {
3381
+ try {
3382
+ await callExtension("dmt_Project.modifyProjectDescription", [projectUuid, next], timeoutMs);
3383
+ const readBack = await callExtension("dmt_Project.getCurrentProjectInfo", [], timeoutMs);
3384
+ stored = String(readBack?.description ?? "").includes(BRIEF_TAG);
3385
+ if (stored) persistVia = "description";
3386
+ } catch {
3387
+ stored = false;
3388
+ }
3389
+ }
3390
+ if (!stored) {
3391
+ const sidecar = specFilePath(project);
3392
+ if (sidecar !== "") {
3393
+ await mkdir(join(sidecar, ".."), { recursive: true });
3394
+ await writeFile(sidecar, JSON.stringify({ projectUuid, brief: merged }, null, 2) + "\n");
3395
+ const check = JSON.parse(await readFile(sidecar, "utf8"));
3396
+ stored = check !== null && typeof check === "object" && Object.keys(merged).every((key) => check.brief?.[key] === merged[key]);
3397
+ if (stored) {
3398
+ persistVia = "file";
3399
+ persistPath = sidecar;
3400
+ }
3401
+ }
3402
+ }
3403
+ persisted = stored === true;
3404
+ } catch {
3405
+ persisted = false;
3406
+ }
3407
+ }
3408
+ }
3409
+ return {
3410
+ ready: mergedReport.ready,
3411
+ questionCount: mergedReport.questionCount,
3412
+ criticalCount: mergedReport.criticalCount,
3413
+ answered: mergedReport.answered,
3414
+ missingCritical: mergedReport.missingCritical,
3415
+ unknownAnswerKeys: mergedReport.unknownAnswerKeys,
3416
+ brief: mergedReport.brief,
3417
+ hydratedFromProject: answers === null && designBrief !== null,
3418
+ persisted,
3419
+ persistVia,
3420
+ persistPath,
3421
+ sections: mergedReport.sections.filter((section) => section.questions.some((question) => mergedReport.brief[question.id] === void 0)),
3422
+ next: mergedReport.ready ? "All critical parameters are known: lay out the schematic, then eda_netlist_erc before routing." : "Ask the user for the missing critical parameters with ask_user_question, grouped by section, before placing parts. Do not invent values."
3423
+ };
3424
+ }
3425
+ case "eda_netlist_erc": {
3426
+ const netlistData = await fetchParsedNetlist(timeoutMs);
3427
+ const report = runNetlistErc(netlistData);
3428
+ const listed = args.includeOk === true ? report.checks : report.checks.filter((check) => check.status !== "pass");
3429
+ return {
3430
+ ok: report.ok,
3431
+ counts: report.counts,
3432
+ componentCount: report.componentCount,
3433
+ netCount: report.netCount,
3434
+ checks: listed,
3435
+ hint: report.ok ? "No electrical failure found. This is a smoke test, not a simulation: run eda_run_drc and review the schematic as well." : "Fix the failing checks before routing; eda_run_drc on this build only returns aggregated counts, so this list is the actionable signal."
3436
+ };
3437
+ }
3438
+ case "eda_pcb_canvas_origin": {
3439
+ const setTo = args.align === true ? [0, 0] : args.offsetX === void 0 && args.offsetY === void 0 ? null : [Number(args.offsetX ?? 0), Number(args.offsetY ?? 0)];
3440
+ let aligned = null;
3441
+ if (setTo !== null) aligned = await callExtension("pcb_Document.setCanvasOrigin", setTo, timeoutMs);
3442
+ const origin = await callExtension("pcb_Document.getCanvasOrigin", [], timeoutMs);
3443
+ const out = {
3444
+ canvasOrigin: origin,
3445
+ aligned,
3446
+ note: "JLCEDA displays canvas coordinates; APIs use data coordinates. align:true sets the offset to zero so both agree."
3447
+ };
3448
+ const point = args.point;
3449
+ if (point !== null && typeof point === "object") {
3450
+ const px = Number(point.x);
3451
+ const py = Number(point.y);
3452
+ if (Number.isFinite(px) && Number.isFinite(py)) {
3453
+ out.point = {
3454
+ input: { x: px, y: py },
3455
+ canvasToData: await callExtension("pcb_Document.convertCanvasOriginToDataOrigin", [px, py], timeoutMs),
3456
+ dataToCanvas: await callExtension("pcb_Document.convertDataOriginToCanvasOrigin", [px, py], timeoutMs)
3457
+ };
3458
+ }
3459
+ }
3460
+ return out;
3461
+ }
3462
+ case "eda_capture": {
3463
+ if (args.cleanup === true) {
3464
+ const removed = [];
3465
+ const failed = [];
3466
+ for (const file of capturedFiles.splice(0, capturedFiles.length)) {
3467
+ try {
3468
+ await unlink(file);
3469
+ removed.push(file);
3470
+ } catch {
3471
+ failed.push(file);
3472
+ }
3473
+ }
3474
+ return { ok: failed.length === 0, removed, failed, hint: "Capture files are scratch: delete them as soon as you have looked at the image." };
3475
+ }
3476
+ const captured = await callExtension("dmt_EditorControl.getCurrentRenderedAreaImage", [], toolTimeout(args, timeoutMs));
3477
+ const dataUrl = typeof captured === "string" ? captured : captured !== null && typeof captured === "object" && typeof captured.dataUrl === "string" ? captured.dataUrl : "";
3478
+ if (dataUrl === "") throw new Error("eda_capture: the app returned no image (is a document tab active?)");
3479
+ const base64 = dataUrl.includes(",") ? dataUrl.slice(dataUrl.indexOf(",") + 1) : dataUrl;
3480
+ const pngBytes = Buffer.from(base64, "base64");
3481
+ const capturePath = args.outPath === void 0 ? "" : String(args.outPath).trim();
3482
+ if (capturePath !== "") {
3483
+ await writeFile(capturePath, pngBytes);
3484
+ capturedFiles.push(capturePath);
3485
+ return {
3486
+ ok: true,
3487
+ written: capturePath,
3488
+ bytes: pngBytes.length,
3489
+ hint: "Read the file with the image reader, then call eda_capture({cleanup:true}) so the scratch PNG does not linger."
3490
+ };
3491
+ }
3492
+ if (args.inline === true) return { ok: true, bytes: pngBytes.length, dataUrl };
3493
+ return { ok: true, bytes: pngBytes.length, dataUrlPrefix: dataUrl.slice(0, 32), hint: "Pass outPath to save a PNG, or inline:true to receive the data URL." };
3494
+ }
3495
+ case "eda_workflow_guide":
3496
+ return { summary: WORKFLOW_SUMMARY, guide: WORKFLOW_GUIDE, autoLayoutAllowed: ALLOW_AUTO_LAYOUT };
3497
+ case "eda_create_board":
3498
+ return await callExtension("dmt_Board.createBoard", [args.schematicUuid, args.pcbUuid], timeoutMs);
3499
+ case "eda_api_call": {
3500
+ if (!ALLOW_RAW_API) throw new Error("eda_api_call is disabled by settings (allowRawApi=false)");
3501
+ const method = String(args.method ?? "");
3502
+ try {
3503
+ return await callExtension(method, Array.isArray(args.args) ? args.args : [], timeoutMs);
3504
+ } catch (failure) {
3505
+ const message = failure instanceof Error ? failure.message : String(failure);
3506
+ if (!/not allowed/i.test(message)) throw failure;
3507
+ const live = await extensionApiMethods(timeoutMs, true);
3508
+ const hint = live === void 0 ? "The connected extension rejected it and does not expose its list (older zip); eda_list_api_methods then shows the bridge copy, which may be narrower than reality." : "The extension enforces " + live.all.length + ' methods right now (eda_list_api_methods source:"extension").';
3509
+ throw new Error("API method not allowed: " + method + ". " + hint + " Wrapped helpers usually exist: eda_get_pins (pins), eda_place_net_labels (labels), eda_pcb_* (PCB primitives).");
3510
+ }
3511
+ }
3512
+ case "pcb_get_components": {
3513
+ const layer = resolvePcbLayer(args.layer);
3514
+ const raw = await callExtension("pcb_PrimitiveComponent.getAll", [layer, args.locked === void 0 ? void 0 : Boolean(args.locked)], timeoutMs);
3515
+ if (!Array.isArray(raw)) return raw;
3516
+ const summarized = raw.map(summarizePrimitive);
3517
+ const enrich = async (item) => {
3518
+ const id = typeof item.primitiveId === "string" ? item.primitiveId : void 0;
3519
+ if (id === void 0) return item;
3520
+ let enriched = item;
3521
+ if (args.includePins === true) {
3522
+ try {
3523
+ const pins = await callExtension("pcb_PrimitiveComponent.getAllPinsByPrimitiveId", [id], timeoutMs);
3524
+ if (Array.isArray(pins)) {
3525
+ enriched = {
3526
+ ...enriched,
3527
+ pins: pins.map((pin) => summarizePrimitive(pin)),
3528
+ padNets: pins.map((pin) => {
3529
+ const record = asRecord(pin);
3530
+ return { num: pickValue(record, "Number", "number", "num", "PadNumber"), net: pickValue(record, "Net", "net") };
3531
+ }).filter((entry) => entry.num !== void 0 || entry.net !== void 0)
3532
+ };
3533
+ }
3534
+ } catch {
3535
+ }
3536
+ }
3537
+ if (args.includeBounds === false) return enriched;
3538
+ try {
3539
+ const bboxRaw = await callExtension("pcb_Primitive.getPrimitivesBBox", [[id]], timeoutMs);
3540
+ const record = asRecord(bboxRaw);
3541
+ if (!Number.isFinite(Number(record.minX))) return enriched;
3542
+ return { ...enriched, bbox: record, width: Number(record.maxX) - Number(record.minX), height: Number(record.maxY) - Number(record.minY) };
3543
+ } catch {
3544
+ return enriched;
3545
+ }
3546
+ };
3547
+ return await mapLimit(summarized, 8, enrich);
3548
+ }
3549
+ case "pcb_get_nets": {
3550
+ if (typeof args.name === "string" && args.name !== "") return await callExtension("pcb_Net.getAllNets", [], timeoutMs);
3551
+ if (args.detail === true) return await callExtension("pcb_Net.getAllNets", [], timeoutMs);
3552
+ return await callExtension("pcb_Net.getAllNetsName", [], timeoutMs);
3553
+ }
3554
+ case "pcb_get_layers":
3555
+ return await callExtension("pcb_Layer.getAllLayers", [], timeoutMs);
3556
+ case "pcb_place_component": {
3557
+ const layer = resolvePcbLayer(args.layer);
3558
+ if (layer === void 0) throw new Error("pcb_place_component requires a valid layer");
3559
+ return await callExtension("pcb_PrimitiveComponent.create", [
3560
+ { libraryUuid: String(args.libraryUuid), uuid: String(args.uuid) },
3561
+ layer,
3562
+ Number(args.x),
3563
+ Number(args.y),
3564
+ args.rotation === void 0 ? void 0 : Number(args.rotation)
3565
+ ], timeoutMs);
3566
+ }
3567
+ case "pcb_draw_track": {
3568
+ const layer = resolvePcbLayer(args.layer);
3569
+ if (layer === void 0) throw new Error("pcb_draw_track requires a valid layer");
3570
+ const net = String(args.net);
3571
+ assertNetName(net, "pcb_draw_track");
3572
+ await assertKnownPcbNet("pcb_draw_track", net, timeoutMs, args.force === true);
3573
+ const width = checkTrackWidth(net, args.lineWidth === void 0 ? void 0 : Number(args.lineWidth), args.force === true);
3574
+ if (!width.ok) throw new Error("pcb_draw_track: " + width.errors.join("; "));
3575
+ const created = await callExtension("pcb_PrimitiveLine.create", [
3576
+ net,
3577
+ layer,
3578
+ Number(args.startX),
3579
+ Number(args.startY),
3580
+ Number(args.endX),
3581
+ Number(args.endY),
3582
+ width.widthMil
3583
+ ], timeoutMs);
3584
+ return { created, rules: { net, role: width.role, widthMil: width.widthMil, suggestedMil: width.suggestedMil, warnings: width.warnings } };
3585
+ }
3586
+ case "pcb_draw_via": {
3587
+ const net = String(args.net);
3588
+ assertNetName(net, "pcb_draw_via");
3589
+ await assertKnownPcbNet("pcb_draw_via", net, timeoutMs, args.force === true);
3590
+ const role = classifyNet(net);
3591
+ const defaultVia = role === "signal" ? VIA_SIZES_MM[0] : VIA_SIZES_MM[1];
3592
+ const hole = args.holeDiameter === void 0 ? defaultVia.hole * 39.37007874015748 : Number(args.holeDiameter);
3593
+ const pad = args.diameter === void 0 ? defaultVia.pad * 39.37007874015748 : Number(args.diameter);
3594
+ const via = checkVia(net, hole, pad, args.force === true);
3595
+ if (!via.ok) throw new Error("pcb_draw_via: " + via.errors.join("; "));
3596
+ const created = await callExtension("pcb_PrimitiveVia.create", [
3597
+ net,
3598
+ Number(args.x),
3599
+ Number(args.y),
3600
+ hole,
3601
+ pad,
3602
+ args.viaType === void 0 ? void 0 : Number(args.viaType)
3603
+ ], timeoutMs);
3604
+ return {
3605
+ created,
3606
+ rules: {
3607
+ net,
3608
+ role,
3609
+ holeMm: Number(via.holeMm.toFixed(3)),
3610
+ padMm: Number(via.padMm.toFixed(3)),
3611
+ annulusMm: Number(via.annulusMm.toFixed(3)),
3612
+ warnings: via.warnings
3613
+ }
3614
+ };
3615
+ }
3616
+ case "pcb_draw_board_outline": {
3617
+ const points = requireFlatPoints(args.points, tool);
3618
+ const lineWidth = args.lineWidth === void 0 ? 10 : Number(args.lineWidth);
3619
+ if (!Number.isFinite(lineWidth) || lineWidth <= 0) throw new Error(tool + ": lineWidth must be a positive number");
3620
+ const raw = await callExtension("dsh.internal.polylineCreate", [
3621
+ args.net === void 0 ? "" : String(args.net),
3622
+ PCB_LAYERS.boardOutline,
3623
+ buildPolygonSource(points),
3624
+ lineWidth,
3625
+ args.locked === void 0 ? void 0 : Boolean(args.locked)
3626
+ ], timeoutMs);
3627
+ return {
3628
+ layer: "BoardOutline",
3629
+ layerId: PCB_LAYERS.boardOutline,
3630
+ lineWidth,
3631
+ pointCount: points.length / 2,
3632
+ closed: true,
3633
+ polyline: summarizePrimitive(raw)
3634
+ };
3635
+ }
3636
+ case "pcb_draw_polyline": {
3637
+ const layer = resolvePcbLayer(args.layer);
3638
+ if (layer === void 0) throw new Error("pcb_draw_polyline requires a valid layer");
3639
+ const points = requireFlatPoints(args.points, "pcb_draw_polyline");
3640
+ const lineWidth = args.lineWidth === void 0 ? 10 : Number(args.lineWidth);
3641
+ if (!Number.isFinite(lineWidth) || lineWidth <= 0) throw new Error("pcb_draw_polyline: lineWidth must be a positive number");
3642
+ const raw = await callExtension("dsh.internal.polylineCreate", [
3643
+ args.net === void 0 ? "" : String(args.net),
3644
+ layer,
3645
+ buildPolygonSource(points),
3646
+ lineWidth,
3647
+ args.locked === void 0 ? void 0 : Boolean(args.locked)
3648
+ ], timeoutMs);
3649
+ return { layer, layerId: layer, lineWidth, pointCount: points.length / 2, closed: true, polyline: summarizePrimitive(raw) };
3650
+ }
3651
+ case "eda_pcb_get_polylines": {
3652
+ const raw = await callExtension("pcb_PrimitivePolyline.getAll", [
3653
+ args.net === void 0 ? void 0 : String(args.net),
3654
+ args.layer === void 0 ? void 0 : resolvePcbLayer(args.layer),
3655
+ args.locked === void 0 ? void 0 : Boolean(args.locked)
3656
+ ], timeoutMs);
3657
+ if (!Array.isArray(raw)) return raw;
3658
+ return { count: raw.length, polylines: raw.map(summarizePrimitive) };
3659
+ }
3660
+ case "eda_pcb_delete_polyline":
3661
+ return await callExtension("pcb_PrimitivePolyline.delete", [String(args.primitiveId)], timeoutMs);
3662
+ case "eda_pcb_clear_routing": {
3663
+ const type = args.type === void 0 ? "all" : String(args.type);
3664
+ if (type !== "all" && type !== "net" && type !== "connection") throw new Error("eda_pcb_clear_routing: type must be all, net or connection");
3665
+ if (args.mode === "batched") return await clearRoutingBatched(args, type, timeoutMs);
3666
+ if (args.wait === true) {
3667
+ return { mode: "native", type, result: await callExtension("pcb_Document.clearRouting", [type], toolTimeout(args, timeoutMs)) };
3668
+ }
3669
+ try {
3670
+ const started = asRecord(await callExtension("dsh.internal.jobStart", ["clearRouting", type], timeoutMs));
3671
+ const running = started.started === true || started.alreadyRunning === true;
3672
+ return {
3673
+ mode: "native",
3674
+ started: started.started === true,
3675
+ alreadyRunning: started.alreadyRunning === true,
3676
+ running,
3677
+ type,
3678
+ startedAt: started.startedAt ?? null,
3679
+ hint: "EDA is clearing the routing in the background. Poll eda_pcb_job_status until running=false (do not raise timeouts)."
3680
+ };
3681
+ } catch (error) {
3682
+ if (!isInternalHelperMissing(error)) throw error;
3683
+ const first = await clearRoutingBatched(args, type, timeoutMs);
3684
+ return { ...first, backgroundUnavailable: true, hint: "The imported EDA extension has no background-job helper, so routing is deleted in bounded batches: call eda_pcb_clear_routing again until done=true." };
3685
+ }
3686
+ }
3687
+ case "pcb_save_document":
3688
+ return await callExtension("pcb_Document.save", [], timeoutMs);
3689
+ case "pcb_import_changes": {
3690
+ const uuid2 = args.schematicUuid === void 0 || args.schematicUuid === null ? null : String(args.schematicUuid);
3691
+ if (args.wait === true) {
3692
+ return await callExtension("pcb_Document.importChanges", [uuid2 === null ? void 0 : uuid2], toolTimeout(args, timeoutMs));
3693
+ }
3694
+ pcbComponentBaseline = await pcbComponentIds(timeoutMs);
3695
+ let started;
3696
+ try {
3697
+ started = asRecord(await callExtension("dsh.internal.jobStart", ["importChanges", uuid2], timeoutMs));
3698
+ } catch (error) {
3699
+ if (!isInternalHelperMissing(error)) throw error;
3700
+ const result2 = await callExtension("pcb_Document.importChanges", [uuid2 === null ? void 0 : uuid2], toolTimeout(args, timeoutMs));
3701
+ const after = await pcbComponentIds(timeoutMs);
3702
+ return {
3703
+ triggered: true,
3704
+ backgroundUnavailable: true,
3705
+ importResult: result2,
3706
+ componentsBefore: pcbComponentBaseline.length,
3707
+ componentsAfter: after.length,
3708
+ confirmedYet: after.length > pcbComponentBaseline.length,
3709
+ hint: "The imported EDA extension has no background-job helper, so the sync was awaited. Re-import dsh-eda-bridge-extension-" + VERSION + ".zip to use the async + polling flow."
3710
+ };
3711
+ }
3712
+ return {
3713
+ triggered: started.started === true || started.alreadyRunning === true,
3714
+ alreadyRunning: started.alreadyRunning === true,
3715
+ confirmedYet: false,
3716
+ componentsBefore: pcbComponentBaseline.length,
3717
+ hint: "EDA is showing the sync confirmation dialog. Ask the user to click OK, then call eda_pcb_wait_for_components (low-frequency polling; it returns confirmed=true as soon as new PCB components appear)."
3718
+ };
3719
+ }
3720
+ case "eda_pcb_wait_for_components": {
3721
+ const interval = Math.max(3e3, Number(args.pollIntervalMs ?? 5e3) || 5e3);
3722
+ const maxWait = Math.min(Math.max(Number(args.maxWaitMs ?? 45e3) || 45e3, interval), 3e5);
3723
+ if (pcbComponentBaseline === null) pcbComponentBaseline = await pcbComponentIds(timeoutMs);
3724
+ const baseline = args.baselineIds === void 0 && Array.isArray(args.baseline) ? args.baseline.map(String) : pcbComponentBaseline;
3725
+ let waited = 0;
3726
+ let ids = await pcbComponentIds(timeoutMs);
3727
+ while (true) {
3728
+ const fresh = ids.filter((id) => !baseline.includes(id));
3729
+ if (fresh.length > 0) {
3730
+ return {
3731
+ confirmed: true,
3732
+ componentsBefore: baseline.length,
3733
+ componentsAfter: ids.length,
3734
+ newComponentIds: fresh,
3735
+ waitedMs: waited,
3736
+ pollIntervalMs: interval,
3737
+ hint: "The user confirmed the sync and the PCB now has the new components. Save the PCB (pcb_save_document) before continuing."
3738
+ };
3739
+ }
3740
+ if (waited >= maxWait) {
3741
+ return {
3742
+ confirmed: false,
3743
+ componentsBefore: baseline.length,
3744
+ componentsAfter: ids.length,
3745
+ waitedMs: waited,
3746
+ pollIntervalMs: interval,
3747
+ hint: "Still no new PCB components - the user has not answered the sync dialog yet (or nothing changed). Ask them to click OK in EDA and call this tool again; polling runs at a deliberately low rate."
3748
+ };
3749
+ }
3750
+ await sleep(interval);
3751
+ waited += interval;
3752
+ ids = await pcbComponentIds(timeoutMs);
3753
+ }
3754
+ }
3755
+ case "pcb_get_primitives_in_region":
3756
+ return await callExtension("pcb_Document.getPrimitivesInRegion", [
3757
+ Number(args.left),
3758
+ Number(args.right),
3759
+ Number(args.top),
3760
+ Number(args.bottom),
3761
+ args.leftToRight === void 0 ? void 0 : Boolean(args.leftToRight)
3762
+ ], timeoutMs);
3763
+ case "pcb_navigate_to_region":
3764
+ return await callExtension("pcb_Document.navigateToRegion", [
3765
+ Number(args.left),
3766
+ Number(args.right),
3767
+ Number(args.top),
3768
+ Number(args.bottom)
3769
+ ], timeoutMs);
3770
+ case "eda_pcb_move_component": {
3771
+ const property = pickDefined({
3772
+ x: args.x === void 0 ? void 0 : Number(args.x),
3773
+ y: args.y === void 0 ? void 0 : Number(args.y),
3774
+ rotation: args.rotation === void 0 ? void 0 : Number(args.rotation),
3775
+ layer: args.layer === void 0 ? void 0 : resolvePcbLayer(args.layer),
3776
+ designator: args.designator,
3777
+ name: args.name,
3778
+ primitiveLock: args.locked === void 0 ? void 0 : Boolean(args.locked)
3779
+ }, ["x", "y", "rotation", "layer", "designator", "name", "primitiveLock"]);
3780
+ const keys = Object.keys(property);
3781
+ if (keys.length === 0) throw new Error("eda_pcb_move_component requires at least one of x, y, rotation, layer, designator, name, locked");
3782
+ for (const key of ["x", "y", "rotation"]) {
3783
+ if (property[key] !== void 0 && !Number.isFinite(property[key])) throw new Error("eda_pcb_move_component: " + key + " must be a finite number");
3784
+ }
3785
+ if (args.layer !== void 0 && property.layer === void 0) throw new Error("eda_pcb_move_component: invalid layer " + String(args.layer));
3786
+ const raw = await callExtension("pcb_PrimitiveComponent.modify", [String(args.primitiveId), property], timeoutMs);
3787
+ return summarizePrimitive(raw);
3788
+ }
3789
+ case "eda_pcb_delete_component":
3790
+ return await callExtension("pcb_PrimitiveComponent.delete", [String(args.primitiveId)], timeoutMs);
3791
+ case "eda_pcb_get_tracks": {
3792
+ const raw = await pcbPrimitiveList("pcb_PrimitiveLine.getAll", [
3793
+ args.net === void 0 ? void 0 : String(args.net),
3794
+ args.layer === void 0 ? void 0 : resolvePcbLayer(args.layer),
3795
+ args.locked === void 0 ? void 0 : Boolean(args.locked)
3796
+ ], timeoutMs);
3797
+ return { count: raw.length, tracks: raw.map(summarizePrimitive) };
3798
+ }
3799
+ case "eda_pcb_modify_track": {
3800
+ const layer = args.layer === void 0 ? void 0 : resolvePcbLayer(args.layer);
3801
+ if (args.layer !== void 0 && layer === void 0) throw new Error("eda_pcb_modify_track: invalid layer " + String(args.layer));
3802
+ const property = pickDefined({
3803
+ net: args.net,
3804
+ layer,
3805
+ startX: args.startX === void 0 ? void 0 : Number(args.startX),
3806
+ startY: args.startY === void 0 ? void 0 : Number(args.startY),
3807
+ endX: args.endX === void 0 ? void 0 : Number(args.endX),
3808
+ endY: args.endY === void 0 ? void 0 : Number(args.endY),
3809
+ lineWidth: args.lineWidth === void 0 ? void 0 : Number(args.lineWidth),
3810
+ primitiveLock: args.locked === void 0 ? void 0 : Boolean(args.locked)
3811
+ }, ["net", "layer", "startX", "startY", "endX", "endY", "lineWidth", "primitiveLock"]);
3812
+ const keys = Object.keys(property);
3813
+ if (keys.length === 0) throw new Error("eda_pcb_modify_track requires at least one of net, layer, startX, startY, endX, endY, lineWidth, locked");
3814
+ for (const key of ["startX", "startY", "endX", "endY", "lineWidth"]) {
3815
+ if (property[key] !== void 0 && !Number.isFinite(property[key])) throw new Error("eda_pcb_modify_track: " + key + " must be a finite number");
3816
+ }
3817
+ const raw = await callExtension("pcb_PrimitiveLine.modify", [String(args.primitiveId), property], timeoutMs);
3818
+ return summarizePrimitive(raw);
3819
+ }
3820
+ case "eda_pcb_delete_track":
3821
+ return await callExtension("pcb_PrimitiveLine.delete", [String(args.primitiveId)], timeoutMs);
3822
+ case "eda_pcb_get_vias": {
3823
+ const raw = await pcbPrimitiveList("pcb_PrimitiveVia.getAll", [
3824
+ args.net === void 0 ? void 0 : String(args.net),
3825
+ args.locked === void 0 ? void 0 : Boolean(args.locked)
3826
+ ], timeoutMs);
3827
+ return { count: raw.length, vias: raw.map(summarizePrimitive) };
3828
+ }
3829
+ case "eda_pcb_delete_via":
3830
+ return await callExtension("pcb_PrimitiveVia.delete", [String(args.primitiveId)], timeoutMs);
3831
+ case "eda_pcb_create_pour": {
3832
+ const layer = resolveRegionLayer(args.layer, "eda_pcb_create_pour");
3833
+ const points = requireFlatPoints(args.points, "eda_pcb_create_pour");
3834
+ assertNetName(String(args.net), "eda_pcb_create_pour");
3835
+ const fill = args.pourFillMethod === void 0 ? void 0 : String(args.pourFillMethod);
3836
+ if (fill !== void 0 && fill !== "45grid" && fill !== "90grid" && fill !== "solid") throw new Error("eda_pcb_create_pour: pourFillMethod must be 45grid, 90grid or solid");
3837
+ let polygonOk = false;
3838
+ try {
3839
+ const probe = await callExtension("pcb_MathPolygon.createPolygon", [buildPolygonSource(points)], timeoutMs);
3840
+ polygonOk = probe !== void 0 && probe !== null;
3841
+ } catch {
3842
+ polygonOk = false;
3843
+ }
3844
+ const attempt = async (fillMethod, preserveSilos) => callExtension("dsh.internal.pourCreate", [
3845
+ String(args.net),
3846
+ layer,
3847
+ buildPolygonSource(points),
3848
+ fillMethod,
3849
+ preserveSilos,
3850
+ args.pourName === void 0 ? void 0 : String(args.pourName),
3851
+ args.pourPriority === void 0 ? void 0 : Number(args.pourPriority),
3852
+ args.lineWidth === void 0 ? void 0 : Number(args.lineWidth),
3853
+ args.locked === void 0 ? void 0 : Boolean(args.locked)
3854
+ ], timeoutMs);
3855
+ let raw;
3856
+ let retried = false;
3857
+ try {
3858
+ raw = await attempt(fill, args.preserveSilos === void 0 ? void 0 : Boolean(args.preserveSilos));
3859
+ } catch (firstFailure) {
3860
+ retried = true;
3861
+ try {
3862
+ raw = await attempt("solid", false);
3863
+ } catch (secondFailure) {
3864
+ const detail = secondFailure instanceof Error ? secondFailure.message : String(secondFailure);
3865
+ throw new Error("eda_pcb_create_pour failed twice (first: " + (firstFailure instanceof Error ? firstFailure.message : String(firstFailure)) + "; retry: " + detail + "). polygonStage=" + (polygonOk ? "ok" : "failed") + ": " + (polygonOk ? "the app accepted the outline but refused the pour itself, and so does the complex polygon the docs require (createComplexPolygon); single and complex polygons, every net/layer/fill combination, all refused, so pour creation is an application limit on this build, not a coordinate problem. Pour by hand in the PCB editor (\u8986\u94DC \u2192 select GND \u2192 top + bottom); eda_design_audit reports it as a warn until then." : "the outline polygon was rejected too: check that every point is inside the board outline and flat [x1,y1,...].") + " retried=" + retried);
3866
+ }
3867
+ }
3868
+ return {
3869
+ net: String(args.net),
3870
+ layer,
3871
+ layerId: layer,
3872
+ pointCount: points.length / 2,
3873
+ pour: summarizePrimitive(raw),
3874
+ retried,
3875
+ rules: {
3876
+ clearanceMil: { required: POUR_CLEARANCE_MIN_MIL, recommended: POUR_CLEARANCE_RECOMMENDED_MIL },
3877
+ note: "The pour/clearance value lives in the board design rules, not in this call: set it in \u8BBE\u8BA1 \u2192 \u8BBE\u8BA1\u89C4\u5219 (recommended " + POUR_CLEARANCE_RECOMMENDED_MIL + " mil) and remove islands before exporting."
3878
+ }
3879
+ };
3880
+ }
3881
+ case "eda_pcb_get_pours": {
3882
+ const raw = await callExtension("pcb_PrimitivePour.getAll", [
3883
+ args.net === void 0 ? void 0 : String(args.net),
3884
+ args.layer === void 0 ? void 0 : resolveRegionLayer(args.layer, "eda_pcb_get_pours"),
3885
+ args.locked === void 0 ? void 0 : Boolean(args.locked)
3886
+ ], timeoutMs);
3887
+ if (!Array.isArray(raw)) return raw;
3888
+ return { count: raw.length, pours: raw.map(summarizePrimitive) };
3889
+ }
3890
+ case "eda_pcb_delete_pour":
3891
+ return await callExtension("pcb_PrimitivePour.delete", [String(args.primitiveId)], timeoutMs);
3892
+ case "eda_pcb_run_drc": {
3893
+ const strict = args.strict === void 0 ? true : Boolean(args.strict);
3894
+ const userInterface = args.userInterface === void 0 ? false : Boolean(args.userInterface);
3895
+ const verbose = args.includeVerboseError === void 0 ? true : Boolean(args.includeVerboseError);
3896
+ const callTimeout = toolTimeout(args, timeoutMs);
3897
+ const result2 = await callExtension("pcb_Drc.check", [strict, userInterface, verbose], callTimeout);
3898
+ if (Array.isArray(result2)) {
3899
+ return { checkPassed: result2.length === 0, violationCount: result2.length, violations: result2, strict, userInterface };
3900
+ }
3901
+ return { checkPassed: result2 === true, result: result2, strict, userInterface };
3902
+ }
3903
+ case "eda_pcb_get_drc_rules": {
3904
+ const name2 = await callExtension("pcb_Drc.getCurrentRuleConfigurationName", [], timeoutMs);
3905
+ let configuration;
3906
+ try {
3907
+ configuration = await callExtension("pcb_Drc.getCurrentRuleConfiguration", [], timeoutMs);
3908
+ } catch {
3909
+ configuration = void 0;
3910
+ }
3911
+ const realTime = await (async () => {
3912
+ try {
3913
+ return await callExtension("pcb_Drc.getRealTimeDrcStatus", [], timeoutMs);
3914
+ } catch {
3915
+ return void 0;
3916
+ }
3917
+ })();
3918
+ return { ruleConfigurationName: name2 ?? null, configuration: configuration ?? null, realTimeDrcRunning: realTime ?? null };
3919
+ }
3920
+ case "eda_pcb_set_net_track_width": {
3921
+ const net = String(args.net);
3922
+ const lineWidth = Number(args.lineWidth);
3923
+ if (!Number.isFinite(lineWidth) || lineWidth <= 0) throw new Error("eda_pcb_set_net_track_width: lineWidth must be a positive number (mil)");
3924
+ const width = checkTrackWidth(net, lineWidth, args.force === true);
3925
+ if (!width.ok) throw new Error("eda_pcb_set_net_track_width: " + width.errors.join("; "));
3926
+ const layer = args.layer === void 0 ? void 0 : resolvePcbLayer(args.layer);
3927
+ if (args.layer !== void 0 && layer === void 0) throw new Error("eda_pcb_set_net_track_width: invalid layer " + String(args.layer));
3928
+ const raw = await callExtension("pcb_PrimitiveLine.getAll", [net, layer, void 0], timeoutMs);
3929
+ if (!Array.isArray(raw)) return raw;
3930
+ const ids = raw.map((track) => pickValue(asRecord(track), "PrimitiveId", "primitiveId")).filter((id) => typeof id === "string");
3931
+ const results = await mapLimit(ids, 8, async (id) => {
3932
+ try {
3933
+ await callExtension("pcb_PrimitiveLine.modify", [id, { lineWidth }], timeoutMs);
3934
+ return { primitiveId: id, ok: true };
3935
+ } catch (error) {
3936
+ return { primitiveId: id, ok: false, error: error instanceof Error ? error.message : String(error) };
3937
+ }
3938
+ });
3939
+ const failed = results.filter((item) => item.ok === false);
3940
+ return { net, lineWidth, layer: layer ?? null, matched: ids.length, updated: ids.length - failed.length, failed, results: args.verbose === true ? results : void 0 };
3941
+ }
3942
+ case "eda_design_audit":
3943
+ return await auditPcb(args, timeoutMs);
3944
+ case "eda_pcb_get_regions": {
3945
+ const raw = await callExtension("pcb_PrimitiveRegion.getAll", [
3946
+ args.layer === void 0 ? void 0 : resolveRegionLayer(args.layer, "eda_pcb_get_regions"),
3947
+ Array.isArray(args.ruleType) ? args.ruleType.map(Number) : void 0,
3948
+ args.locked === void 0 ? void 0 : Boolean(args.locked)
3949
+ ], timeoutMs);
3950
+ if (!Array.isArray(raw)) return raw;
3951
+ return { count: raw.length, regions: raw.map(summarizePrimitive) };
3952
+ }
3953
+ case "eda_pcb_create_region": {
3954
+ const layer = resolveRegionLayer(args.layer, "eda_pcb_create_region");
3955
+ const points = requireFlatPoints(args.points, "eda_pcb_create_region");
3956
+ const ruleType = Array.isArray(args.ruleType) && args.ruleType.length > 0 ? args.ruleType.map(Number) : void 0;
3957
+ const lineWidth = args.lineWidth === void 0 ? void 0 : Number(args.lineWidth);
3958
+ const raw = await callExtension("dsh.internal.pcbCreateRegion", [
3959
+ layer,
3960
+ buildPolygonSource(points),
3961
+ ruleType,
3962
+ args.regionName === void 0 ? void 0 : String(args.regionName),
3963
+ lineWidth,
3964
+ args.locked === void 0 ? void 0 : Boolean(args.locked)
3965
+ ], timeoutMs);
3966
+ return { pointCount: points.length / 2, region: summarizePrimitive(raw) };
3967
+ }
3968
+ case "eda_pcb_delete_region":
3969
+ return await callExtension("pcb_PrimitiveRegion.delete", [String(args.primitiveId)], timeoutMs);
3970
+ case "eda_pcb_auto_place": {
3971
+ if (args.wait === false) {
3972
+ let started;
3973
+ try {
3974
+ started = asRecord(await callExtension("dsh.internal.jobStart", ["autoLayout", null], timeoutMs));
3975
+ } catch (error) {
3976
+ if (!isInternalHelperMissing(error)) throw error;
3977
+ const blocking = await callExtension("pcb_Document.autoLayout", [], toolTimeout(args, timeoutMs));
3978
+ return { backgroundUnavailable: true, result: blocking, hint: "The imported EDA extension has no background-job helper, so layout was awaited." };
3979
+ }
3980
+ return { started: started.started === true, alreadyRunning: started.alreadyRunning === true, running: started.started === true || started.alreadyRunning === true, hint: "Poll eda_pcb_job_status until running=false." };
3981
+ }
3982
+ return await callExtension("pcb_Document.autoLayout", [], toolTimeout(args, timeoutMs));
3983
+ }
3984
+ case "eda_pcb_job_status": {
3985
+ const status = asRecord(await callExtension("dsh.internal.jobStatus", [], timeoutMs));
3986
+ if (status.job === null && status.running === false) {
3987
+ return { running: false, job: null, hint: "No background PCB job has been started in this EDA session (or the extension was reloaded)." };
3988
+ }
3989
+ const finished = asRecord(status.result);
3990
+ const failed = Array.isArray(finished.failedNets) ? finished.failedNets : [];
3991
+ if (typeof status.result === "boolean") {
3992
+ return {
3993
+ ...status,
3994
+ error,
3995
+ hint: status.result === true ? "Finished: EDA reported the operation succeeded. Routing is cleared - re-run eda_pcb_auto_route when you want to route again." : "Finished, but EDA reported failure (nothing was cleared or the operation was rejected)."
3996
+ };
3997
+ }
3998
+ const error = status.error === null || status.error === void 0 ? null : String(status.error);
3999
+ const hint = status.running === true ? "Still running in EDA; poll again in ~10 s." : error !== null ? "The job failed: " + error : finished.success === false ? "Finished with success=false. duration=0 means the engine refused to start (check that the board outline is one closed polyline on layer 11, that design rules exist, and that nets really have unrouted connections)." : failed.length > 0 ? "Finished with " + failed.length + " unrouted net(s); re-run only those nets, then run eda_pcb_run_drc." : "Finished. Next: eda_pcb_run_drc, then eda_pcb_set_net_track_width for power/GND nets.";
4000
+ return { ...status, error, hint };
4001
+ }
4002
+ case "eda_pcb_auto_route": {
4003
+ const extra = args.props === void 0 || args.props === null ? {} : asRecord(args.props);
4004
+ const explicit = args.RoutingNets ?? args.nets ?? extra.RoutingNets ?? extra.nets;
4005
+ let requested;
4006
+ const explicitEmpty = Array.isArray(explicit) && explicit.length === 0;
4007
+ if (explicit !== void 0 && explicit !== null && !explicitEmpty) requested = explicit;
4008
+ else {
4009
+ const names = await callExtension("pcb_Net.getAllNetsName", [], timeoutMs);
4010
+ if (!Array.isArray(names) || names.length === 0) {
4011
+ throw new Error("eda_pcb_auto_route: the active PCB reports no nets. Either the PCB document is not the active tab (PCB APIs only work while the PCB page is in front - check eda_get_active_document / eda_open_document), or the schematic changes have not been imported yet (pcb_import_changes).");
4012
+ }
4013
+ requested = names.map(String);
4014
+ }
4015
+ const extraProps = Object.fromEntries(Object.entries(extra).filter(([key]) => key !== "nets" && key !== "RoutingNets"));
4016
+ const props = { RoutingNets: requested, ...extraProps };
4017
+ if (args.ignoreNets !== void 0) props.ignoreNets = args.ignoreNets;
4018
+ if (args.layers !== void 0) props.layers = args.layers;
4019
+ if (args.cornerStyle !== void 0) props.cornerStyle = args.cornerStyle;
4020
+ if (args.optimization !== void 0) props.optimization = args.optimization;
4021
+ if (args.existingPrimitiveMode !== void 0) props.existingPrimitiveMode = args.existingPrimitiveMode;
4022
+ if (args.wait !== true) {
4023
+ let started;
4024
+ try {
4025
+ started = asRecord(await callExtension("dsh.internal.jobStart", ["autoRoute", props], timeoutMs));
4026
+ } catch (error) {
4027
+ if (!isInternalHelperMissing(error)) throw error;
4028
+ const blocking = asRecord(await callExtension("pcb_Document.autoRouting", [props], toolTimeout(args, timeoutMs)));
4029
+ return { ...blocking, backgroundUnavailable: true, props, hint: "The imported EDA extension has no background-job helper, so routing was awaited. Re-import dsh-eda-bridge-extension-" + VERSION + ".zip to get the async + polling flow." };
4030
+ }
4031
+ const running = started.started === true || started.alreadyRunning === true;
4032
+ return {
4033
+ started: started.started === true,
4034
+ alreadyRunning: started.alreadyRunning === true,
4035
+ running,
4036
+ startedAt: started.startedAt ?? null,
4037
+ requestedNets: Array.isArray(requested) ? requested.length : 0,
4038
+ props,
4039
+ hint: started.started === true ? "EDA is routing in the background (its progress bar is visible in the PCB editor). Poll eda_pcb_job_status until running=false, then run eda_pcb_run_drc. Do not raise timeouts - the job outlives the MCP call." : "A PCB job is already running; poll eda_pcb_job_status."
4040
+ };
4041
+ }
4042
+ const result2 = await callExtension("pcb_Document.autoRouting", [props], toolTimeout(args, timeoutMs));
4043
+ const record = asRecord(result2);
4044
+ const failed = Array.isArray(record.failedNets) ? record.failedNets : [];
4045
+ const requestedCount = Array.isArray(requested) ? requested.length : 0;
4046
+ const hint = record.success === true ? failed.length === 0 ? "ok" : "The router returned success but left " + failed.length + " net(s) unrouted." : "The router failed. duration=0 means it refused to start: check that the board outline is a single closed polyline on layer 11 (use pcb_draw_board_outline / eda_pcb_get_polylines), that the design rules are configured, and that the nets really have unrouted connections.";
4047
+ return { ...record, requestedNets: requestedCount, props, hint };
4048
+ }
4049
+ case "eda_pcb_export_gerber": {
4050
+ const unit = args.unit === void 0 ? void 0 : String(args.unit);
4051
+ if (unit !== void 0 && unit !== "mm" && unit !== "inch") throw new Error('eda_pcb_export_gerber: unit must be "mm" or "inch"');
4052
+ const digitalFormat = args.integerNumber === void 0 && args.decimalNumber === void 0 ? void 0 : {
4053
+ integerNumber: args.integerNumber === void 0 ? 4 : Number(args.integerNumber),
4054
+ decimalNumber: args.decimalNumber === void 0 ? 4 : Number(args.decimalNumber)
4055
+ };
4056
+ const payload = await callExtension("pcb_ManufactureData.getGerberFile", [
4057
+ args.fileName === void 0 ? void 0 : String(args.fileName),
4058
+ args.colorSilkscreen === void 0 ? void 0 : Boolean(args.colorSilkscreen),
4059
+ unit,
4060
+ digitalFormat,
4061
+ args.other === void 0 ? void 0 : asRecord(args.other),
4062
+ Array.isArray(args.layers) ? args.layers : void 0,
4063
+ Array.isArray(args.objects) ? args.objects : void 0
4064
+ ], timeoutMs);
4065
+ if (payload === null || payload === void 0) throw new Error("eda_pcb_export_gerber: the API returned no file (is a PCB document active?)");
4066
+ return payload;
4067
+ }
4068
+ default:
4069
+ throw new Error("unknown tool: " + name);
4070
+ }
4071
+ }
4072
+ function writeJson(value) {
4073
+ process.stdout.write(JSON.stringify(value) + "\n");
4074
+ }
4075
+ async function handleJsonRpc(message) {
4076
+ if (message === null || typeof message !== "object") return;
4077
+ if (message.jsonrpc !== "2.0") return;
4078
+ if (message.id !== void 0 && message.method !== void 0) {
4079
+ try {
4080
+ const result2 = await handleMethod(message.method, message.params ?? {}, message.id);
4081
+ if (result2 !== void 0) writeJson({ jsonrpc: "2.0", id: message.id, result: result2 });
4082
+ } catch (error) {
4083
+ writeJson({ jsonrpc: "2.0", id: message.id, error: { code: -32603, message: error instanceof Error ? error.message : String(error) } });
4084
+ }
4085
+ } else if (message.method !== void 0) {
4086
+ try {
4087
+ await handleMethod(message.method, message.params ?? {}, void 0);
4088
+ } catch {
4089
+ }
4090
+ }
4091
+ }
4092
+ async function handleMethod(method, params, _id) {
4093
+ if (method === "initialize") {
4094
+ const protocolVersion = params && params.protocolVersion ? params.protocolVersion : "2024-11-05";
4095
+ return { protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "dsh-eda-mcp-bridge", version: VERSION } };
4096
+ }
4097
+ if (method === "notifications/initialized") return void 0;
4098
+ if (method === "notifications/cancelled") return void 0;
4099
+ if (method === "ping") return {};
4100
+ if (method === "tools/list") return { tools: TOOLS };
4101
+ if (method === "tools/call") {
4102
+ const name = String(params && params.name || "");
4103
+ const args = params && params.arguments || {};
4104
+ try {
4105
+ return toolResult(await executeTool(name, args, TOOL_TIMEOUT_MS));
4106
+ } catch (error) {
4107
+ return toolError(error instanceof Error ? error.message : String(error));
4108
+ }
4109
+ }
4110
+ throw new Error("method not found: " + method);
4111
+ }
4112
+ var server = createServer((req, res) => {
4113
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
4114
+ if (req.method === "GET" && url.pathname === "/healthz") {
4115
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
4116
+ res.end(JSON.stringify({ status: "ok", version: VERSION, clients: pickClients().length }));
4117
+ return;
4118
+ }
4119
+ res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
4120
+ res.end("not found");
4121
+ });
4122
+ server.on("upgrade", (req, socket) => {
4123
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
4124
+ if (url.pathname !== "/ws") {
4125
+ socket.destroy();
4126
+ return;
4127
+ }
4128
+ const key = req.headers["sec-websocket-key"];
4129
+ if (typeof key !== "string" || key.length === 0) {
4130
+ socket.destroy();
4131
+ return;
4132
+ }
4133
+ const accept = createHash2("sha1").update(key + WS_GUID).digest("base64");
4134
+ socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + accept + "\r\n\r\n");
4135
+ const client = new WsConnection(socket);
4136
+ clients.add(client);
4137
+ socket.on("data", (chunk) => {
4138
+ client.handleData(chunk);
4139
+ });
4140
+ socket.on("close", () => {
4141
+ clients.delete(client);
4142
+ });
4143
+ socket.on("error", () => {
4144
+ clients.delete(client);
4145
+ });
4146
+ });
4147
+ server.on("error", (error) => {
4148
+ process.stderr.write("[dsh-eda-mcp] bridge " + VERSION + " failed to listen on " + WS_HOST + ":" + WS_PORT + " (" + (error && error.code ? error.code : String(error)) + "). Another dsh-eda-mcp bridge process is probably still running; stop the stale process (netstat -ano | findstr " + WS_PORT + ") and reconnect.\n");
4149
+ });
4150
+ server.listen(WS_PORT, WS_HOST, () => {
4151
+ process.stderr.write("[dsh-eda-mcp] bridge " + VERSION + " listening on ws://" + WS_HOST + ":" + WS_PORT + "/ws\n");
4152
+ });
4153
+ var rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
4154
+ rl.on("line", (line) => {
4155
+ try {
4156
+ void handleJsonRpc(JSON.parse(line));
4157
+ } catch {
4158
+ }
4159
+ });
4160
+ var shuttingDown = false;
4161
+ function shutdown() {
4162
+ if (shuttingDown) return;
4163
+ shuttingDown = true;
4164
+ try {
4165
+ for (const client of clients) client.close();
4166
+ } catch {
4167
+ }
4168
+ clients.clear();
4169
+ try {
4170
+ server.close();
4171
+ } catch {
4172
+ }
4173
+ process.exit(0);
4174
+ }
4175
+ process.stdin.on("end", shutdown);
4176
+ process.stdin.on("close", shutdown);
4177
+ process.on("disconnect", shutdown);
4178
+ process.on("SIGTERM", shutdown);
4179
+ process.on("SIGINT", shutdown);