dsh-stm32 0.1.4 → 0.1.6

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 (38) hide show
  1. package/README.md +517 -459
  2. package/README_EN.md +510 -453
  3. package/assets/device/h7/chips.json +831 -140
  4. package/assets/device/u5/chips.json +375 -64
  5. package/assets/manifest.json +4 -4
  6. package/docs/reading-guide.md +114 -16
  7. package/lib/commands/register.js +1 -1
  8. package/lib/data/cmsis-sources.js +136 -4
  9. package/lib/data/device-facts.js +14 -0
  10. package/lib/data/family.js +14 -14
  11. package/lib/data/firmware-packages.js +35 -14
  12. package/lib/data/firmware-pins.js +128 -0
  13. package/lib/data/search-roots.js +17 -3
  14. package/lib/data/serial-config.js +430 -0
  15. package/lib/engine/doctor.js +85 -8
  16. package/lib/engine/download.js +242 -0
  17. package/lib/engine/fetch.js +1 -1
  18. package/lib/engine/firmware-install.js +158 -35
  19. package/lib/engine/firmware-official.js +113 -65
  20. package/lib/engine/ioc-plan.js +28 -6
  21. package/lib/engine/msys2-install.js +237 -88
  22. package/lib/engine/probe.js +4 -2
  23. package/lib/engine/register-gpio.js +18 -1
  24. package/lib/engine/register-linker.js +25 -6
  25. package/lib/engine/register-template.js +25 -1
  26. package/lib/engine/serial.js +1696 -0
  27. package/lib/engine/tar.js +235 -3
  28. package/lib/index.js +12 -0
  29. package/lib/skill/stm32-workflow.js +2 -2
  30. package/lib/tools/assets.js +8 -3
  31. package/lib/tools/build.js +0 -1
  32. package/lib/tools/doctor.js +9 -3
  33. package/lib/tools/download.js +303 -0
  34. package/lib/tools/ioc-plan.js +17 -7
  35. package/lib/tools/project-create.js +1 -1
  36. package/lib/tools/serial.js +737 -0
  37. package/package.json +70 -70
  38. package/templates/serial/bridge.ps1 +477 -0
@@ -0,0 +1,242 @@
1
+ /**
2
+ * 安装包下载(只下载,不执行安装器)。
3
+ *
4
+ * 设计边界:
5
+ * - J-Link:SEGGER 安装包有稳定直链与官方哈希,可以下载到本地并校验;
6
+ * - STM32CubeMX / STM32CubeProgrammer:ST 官网通常要求登录/接受许可,直链会过期,
7
+ * 所以默认只给官方页面;用户自己下载后可以把本地安装包路径交给工具做校验。
8
+ * - 本模块绝不 spawn 安装器,也不请求管理员权限。
9
+ *
10
+ * 下载目录:DSH_STM32_DOWNLOADS 覆盖,默认 %LOCALAPPDATA%\dsh-stm32\downloads。
11
+ */
12
+ import { createHash } from "node:crypto";
13
+ import { createReadStream, existsSync, mkdirSync, statSync, unlinkSync } from "node:fs";
14
+ import { open } from "node:fs/promises";
15
+ import { homedir, tmpdir } from "node:os";
16
+ import path from "node:path";
17
+ /** 2026-11-10 从 winget 的 NordicSemiconductor.JLink 8.18.0 manifest 取的值;升级要同步改这里。 */
18
+ export const JLINK_DOWNLOAD = {
19
+ version: "8.18.0",
20
+ url: "https://files.nordicsemi.com/artifactory/swtools/external/jlink/JLink_Windows_V818_x86_64.exe",
21
+ sha256: "63110b6fc55e494d197d6efa156d7f61c0dd0c1f776424995a05407e2d7f566f",
22
+ fileName: "JLink_Windows_V818_x86_64.exe",
23
+ page: "https://www.segger.com/downloads/jlink/",
24
+ };
25
+ const ST_PAGES = {
26
+ cubemx: {
27
+ label: "STM32CubeMX",
28
+ page: "https://www.st.com/en/development-tools/stm32cubemx.html",
29
+ installHint: "从官方页登录 myST、接受许可并下载安装包;默认目录 C:/Program Files/STMicroelectronics/STM32Cube/STM32CubeMX 会被 stm32_doctor 自动发现。",
30
+ },
31
+ cubeprogrammer: {
32
+ label: "STM32CubeProgrammer",
33
+ page: "https://www.st.com/en/development-tools/stm32cubeprog.html",
34
+ installHint: "从官方页登录 myST、接受许可并下载安装包;默认路径会被 stm32_doctor 自动发现。它的 SWD 路径只认 ST-LINK。",
35
+ },
36
+ };
37
+ export class DownloadError extends Error {
38
+ kind;
39
+ retryable;
40
+ constructor(kind, message, retryable = false) {
41
+ super(message);
42
+ this.name = "DownloadError";
43
+ this.kind = kind;
44
+ this.retryable = retryable;
45
+ }
46
+ }
47
+ export function isDownloadComponent(value) {
48
+ return value === "jlink" || value === "cubemx" || value === "cubeprogrammer";
49
+ }
50
+ /** 下载目录:DSH_STM32_DOWNLOADS 覆盖,其次 LOCALAPPDATA,再退 USERPROFILE、临时目录。 */
51
+ export function downloadRootInfo(env = process.env) {
52
+ const override = (env.DSH_STM32_DOWNLOADS ?? "").trim();
53
+ if (override !== "") {
54
+ return { root: path.resolve(expandHome(override, env)), origin: "DSH_STM32_DOWNLOADS" };
55
+ }
56
+ const localAppData = (env.LOCALAPPDATA ?? "").trim();
57
+ if (localAppData !== "") {
58
+ return { root: path.join(localAppData, "dsh-stm32", "downloads"), origin: "LOCALAPPDATA" };
59
+ }
60
+ const userProfile = (env.USERPROFILE ?? "").trim();
61
+ if (userProfile !== "") {
62
+ return { root: path.join(userProfile, "AppData", "Local", "dsh-stm32", "downloads"), origin: "USERPROFILE" };
63
+ }
64
+ return { root: path.join(tmpdir(), "dsh-stm32-downloads"), origin: "临时目录(没有 LOCALAPPDATA/USERPROFILE)" };
65
+ }
66
+ function expandHome(value, env) {
67
+ if (value === "~" || value.startsWith("~/") || value.startsWith("~\\")) {
68
+ const home = (env.USERPROFILE ?? env.HOME ?? homedir()).trim();
69
+ if (home !== "")
70
+ return path.join(home, value.slice(1));
71
+ }
72
+ return value;
73
+ }
74
+ export function planDownload(component, options = {}) {
75
+ const env = options.env ?? process.env;
76
+ const info = downloadRootInfo(env);
77
+ const root = options.outDir !== undefined && options.outDir.trim() !== "" ? path.resolve(options.outDir) : info.root;
78
+ if (component === "jlink") {
79
+ // 官方只有一条可校验的直链。允许内网镜像覆盖,但必须同时给 sha256——
80
+ // 没有哈希的覆盖会让"下载 J-Link"变成"执行一个来源不明的 exe",一律拒绝并回默认源。
81
+ const overrideUrl = (env.DSH_STM32_JLINK_URL ?? "").trim();
82
+ const overrideSha = (env.DSH_STM32_JLINK_SHA256 ?? "").trim().toLowerCase();
83
+ const useOverride = /^https?:\/\//iu.test(overrideUrl) && /^[0-9a-f]{64}$/u.test(overrideSha);
84
+ const url = useOverride ? overrideUrl : JLINK_DOWNLOAD.url;
85
+ const sha256 = useOverride ? overrideSha : JLINK_DOWNLOAD.sha256;
86
+ const fileName = useOverride ? path.basename(new URL(overrideUrl).pathname) : JLINK_DOWNLOAD.fileName;
87
+ return {
88
+ component,
89
+ label: "SEGGER J-Link Software and Documentation Pack",
90
+ mode: "direct",
91
+ version: JLINK_DOWNLOAD.version,
92
+ url,
93
+ page: JLINK_DOWNLOAD.page,
94
+ expectedSha256: sha256,
95
+ fileName,
96
+ targetPath: path.join(root, fileName),
97
+ installHint: "下载后双击安装。只装软件可不请求管理员;要装 USB 驱动需要在安装器里选 all users 并允许 UAC。现代 J-Link 探针默认 WinUSB,老探针才需要 legacy USB 驱动。",
98
+ licenseNote: "SEGGER 软件许可;插件只下载,不执行安装器。",
99
+ };
100
+ }
101
+ const st = ST_PAGES[component];
102
+ return {
103
+ component,
104
+ label: st.label,
105
+ mode: "manual",
106
+ version: "",
107
+ url: "",
108
+ page: st.page,
109
+ expectedSha256: "",
110
+ fileName: "",
111
+ targetPath: "",
112
+ installHint: st.installHint,
113
+ licenseNote: "ST 官网需要登录 myST 并接受许可,插件不绕过;请自己下载,或把已下载的安装包路径传给 file。",
114
+ };
115
+ }
116
+ /**
117
+ * 下载到 targetPath 并校验 SHA256。
118
+ *
119
+ * 写临时文件再 rename,下载失败/哈希不符不会留下半个“安装包”。
120
+ * 目标已存在且哈希正确时直接复用;哈希不符则重新下载。
121
+ */
122
+ export async function downloadUrlToFile(url, targetPath, expectedSha256, options = {}) {
123
+ const expected = expectedSha256.trim().toLowerCase();
124
+ if (existsSync(targetPath)) {
125
+ const existing = statSync(targetPath);
126
+ if (existing.isFile()) {
127
+ const hash = await sha256File(targetPath);
128
+ if (expected === "" || hash === expected) {
129
+ return { path: targetPath, bytes: existing.size, sha256: hash, cached: true };
130
+ }
131
+ }
132
+ }
133
+ mkdirSync(path.dirname(targetPath), { recursive: true });
134
+ const part = targetPath + ".part-" + String(process.pid) + "-" + String(Date.now());
135
+ const timeoutMs = Math.max(5_000, options.timeoutMs ?? 10 * 60_000);
136
+ const maxBytes = options.maxBytes ?? 300 * 1024 * 1024;
137
+ const controller = new AbortController();
138
+ let timedOut = false;
139
+ const onAbort = () => controller.abort();
140
+ if (options.signal !== undefined) {
141
+ if (options.signal.aborted)
142
+ controller.abort();
143
+ else
144
+ options.signal.addEventListener("abort", onAbort, { once: true });
145
+ }
146
+ const timer = setTimeout(() => {
147
+ timedOut = true;
148
+ controller.abort();
149
+ }, timeoutMs);
150
+ let handle;
151
+ try {
152
+ const response = await fetch(url, { signal: controller.signal, redirect: "follow" });
153
+ if (!response.ok) {
154
+ throw new DownloadError("download-failed", "下载失败:HTTP " + String(response.status) + " " + response.statusText, response.status >= 500);
155
+ }
156
+ if (response.body === null)
157
+ throw new DownloadError("download-failed", "下载失败:响应没有 body", true);
158
+ const announced = Number(response.headers.get("content-length") ?? "0");
159
+ if (Number.isFinite(announced) && announced > maxBytes) {
160
+ throw new DownloadError("too-large", "安装包超过上限 " + String(maxBytes) + " 字节(服务器声明 " + String(announced) + ")");
161
+ }
162
+ handle = await open(part, "w");
163
+ const hash = createHash("sha256");
164
+ let bytes = 0;
165
+ const reader = response.body.getReader();
166
+ for (;;) {
167
+ const chunk = await reader.read();
168
+ if (chunk.done)
169
+ break;
170
+ const value = chunk.value;
171
+ bytes += value.byteLength;
172
+ if (bytes > maxBytes)
173
+ throw new DownloadError("too-large", "安装包超过上限 " + String(maxBytes) + " 字节");
174
+ hash.update(value);
175
+ await handle.write(value);
176
+ }
177
+ await handle.close();
178
+ handle = undefined;
179
+ const actual = hash.digest("hex");
180
+ if (expected !== "" && actual !== expected) {
181
+ throw new DownloadError("checksum-mismatch", "SHA256 不符:期望 " + expected + ",实际 " + actual + "(已删除临时文件)", true);
182
+ }
183
+ // Windows 的 rename 不覆盖已存在文件;先删旧目标(旧目标哈希已不符),再原子换名。
184
+ if (existsSync(targetPath))
185
+ unlinkSync(targetPath);
186
+ const fs = await import("node:fs");
187
+ fs.renameSync(part, targetPath);
188
+ return { path: targetPath, bytes, sha256: actual, cached: false };
189
+ }
190
+ catch (error) {
191
+ if (handle !== undefined) {
192
+ try {
193
+ await handle.close();
194
+ }
195
+ catch { /* 已关 */ }
196
+ }
197
+ try {
198
+ if (existsSync(part))
199
+ unlinkSync(part);
200
+ }
201
+ catch { /* 清理失败不掩盖主错误 */ }
202
+ if (error instanceof DownloadError)
203
+ throw error;
204
+ if (timedOut)
205
+ throw new DownloadError("timeout", "下载超时(" + String(timeoutMs) + " ms)", true);
206
+ if (controller.signal.aborted)
207
+ throw new DownloadError("cancelled", "下载已取消", false);
208
+ throw new DownloadError("download-failed", "下载失败:" + (error instanceof Error ? error.message : String(error)), true);
209
+ }
210
+ finally {
211
+ clearTimeout(timer);
212
+ if (options.signal !== undefined)
213
+ options.signal.removeEventListener("abort", onAbort);
214
+ }
215
+ }
216
+ /** 计算文件 SHA256(流式,不把安装包读进内存)。 */
217
+ export async function sha256File(file) {
218
+ return new Promise((resolve, reject) => {
219
+ const hash = createHash("sha256");
220
+ const stream = createReadStream(file);
221
+ stream.on("data", (chunk) => hash.update(chunk));
222
+ stream.once("error", reject);
223
+ stream.once("end", () => resolve(hash.digest("hex")));
224
+ });
225
+ }
226
+ /** 校验用户已经下载好的安装包;不复制、不执行。 */
227
+ export async function inspectInstallerFile(file, expectedSha256 = "") {
228
+ const resolved = path.resolve(expandHome(file.trim(), process.env));
229
+ const stat = statSync(resolved, { throwIfNoEntry: false });
230
+ if (stat === undefined || !stat.isFile()) {
231
+ throw new DownloadError("file-not-found", "找不到安装包文件:" + resolved);
232
+ }
233
+ if (stat.size <= 0)
234
+ throw new DownloadError("file-invalid", "安装包是空文件:" + resolved);
235
+ const hash = await sha256File(resolved);
236
+ const expected = expectedSha256.trim().toLowerCase();
237
+ const verified = expected === "" ? false : hash === expected;
238
+ if (expected !== "" && !verified) {
239
+ throw new DownloadError("checksum-mismatch", "SHA256 不符:期望 " + expected + ",实际 " + hash, false);
240
+ }
241
+ return { path: resolved, bytes: stat.size, sha256: hash, expectedSha256: expected, verified };
242
+ }
@@ -217,7 +217,7 @@ export async function fetchOne(target, destRoot, options = {}) {
217
217
  const actual = createHash("sha256").update(buffer).digest("hex");
218
218
  if (actual !== target.sha256.toLowerCase()) {
219
219
  reject("sha256 对不上(期望 " + target.sha256.toLowerCase().slice(0, 16) + "…,实际 " + actual.slice(0, 16) +
220
- "…)。多半是上游 master 挪动了内容:用真实 URL 重新实测哈希并更新 cmsis-sources。");
220
+ "…)。多半是上游 master 挪动了内容:用真实 URL 重新实测哈希并更新 cmsis-sources(CMSIS 头)或 firmware-pins(固件归档/内核头)。");
221
221
  continue;
222
222
  }
223
223
  }
@@ -15,7 +15,7 @@
15
15
  *
16
16
  * 刻意不做的事:不覆盖已有官方包(升级走 CubeMX 包管理器)、不动 Repository 里的其它包。
17
17
  */
18
- import { accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
18
+ import { accessSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
19
19
  import path from "node:path";
20
20
  import { dshFirmwareDir, firmwarePlanFor, verifyFirmwarePackage, } from "../data/firmware-packages.js";
21
21
  import { cacheRoot } from "./cache.js";
@@ -24,7 +24,7 @@ import { locateCubemxDb } from "./cubemx-db.js";
24
24
  import { downloadOfficialZip, installViaSwmgr, officialFirmwareUrl, resolveFwLibrary, verifyZipCrc, SWMGR_TIME_LIMIT_MS, } from "./firmware-official.js";
25
25
  import { cubeMxLaunch } from "./generate.js";
26
26
  import { fetchAll } from "./fetch.js";
27
- import { extractTarGz } from "./tar.js";
27
+ import { extractTarGzFile } from "./tar.js";
28
28
  function slash(value) {
29
29
  let out = value.split("\\").join("/");
30
30
  while (out.endsWith("/"))
@@ -461,6 +461,77 @@ function mapperFor(archive) {
461
461
  return null;
462
462
  };
463
463
  }
464
+ /**
465
+ * 同一落点的跨进程安装锁:文件用 O_EXCL 创建,内容是持有者 pid。
466
+ * 崩溃留下的锁在下次进入时按 pid 是否还活着回收;pid 被复用也无害——文件里还有 startedAt,
467
+ * 超过 6 小时一律当陈旧锁。
468
+ */
469
+ function acquireInstallLock(dir) {
470
+ const lockFile = dir + ".dsh-install.lock";
471
+ const parent = path.dirname(dir);
472
+ try {
473
+ mkdirSync(parent, { recursive: true });
474
+ }
475
+ catch (error) {
476
+ return { ok: false, release: () => { }, error: "建不了安装锁目录:" + (error instanceof Error ? error.message : String(error)) };
477
+ }
478
+ for (let attempt = 0; attempt < 2; attempt += 1) {
479
+ try {
480
+ const fd = openSync(lockFile, "wx");
481
+ try {
482
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }), "utf8");
483
+ }
484
+ finally {
485
+ closeSync(fd);
486
+ }
487
+ return {
488
+ ok: true,
489
+ release: () => {
490
+ try {
491
+ rmSync(lockFile, { force: true });
492
+ }
493
+ catch { /* 清不掉就留给陈旧锁回收 */ }
494
+ },
495
+ error: "",
496
+ };
497
+ }
498
+ catch (error) {
499
+ const code = error instanceof Error && "code" in error ? String(error.code) : "";
500
+ if (code !== "EEXIST") {
501
+ return { ok: false, release: () => { }, error: "建不了安装锁:" + (error instanceof Error ? error.message : String(error)) };
502
+ }
503
+ let holder = { pid: 0, startedAt: 0 };
504
+ try {
505
+ const parsed = JSON.parse(readFileSync(lockFile, "utf8"));
506
+ if (parsed !== null && typeof parsed === "object") {
507
+ const record = parsed;
508
+ holder = { pid: Number(record.pid ?? 0), startedAt: Number(record.startedAt ?? 0) };
509
+ }
510
+ }
511
+ catch { /* 半截锁按陈旧处理 */ }
512
+ const staleByAge = holder.startedAt > 0 && Date.now() - holder.startedAt > 6 * 60 * 60 * 1000;
513
+ let alive = false;
514
+ if (holder.pid > 0 && !staleByAge) {
515
+ try {
516
+ process.kill(holder.pid, 0);
517
+ alive = true;
518
+ }
519
+ catch (probe) {
520
+ alive = !(probe instanceof Error && "code" in probe && String(probe.code) === "ESRCH");
521
+ }
522
+ }
523
+ if (!alive) {
524
+ try {
525
+ rmSync(lockFile, { force: true });
526
+ }
527
+ catch { /* 下一轮再试 */ }
528
+ continue;
529
+ }
530
+ return { ok: false, release: () => { }, error: "另一个进程正在装同一个固件包(pid " + String(holder.pid) + ")" };
531
+ }
532
+ }
533
+ return { ok: false, release: () => { }, error: "拿不到安装锁:" + lockFile };
534
+ }
464
535
  const NOTICES_FILE = "THIRD_PARTY_NOTICES.md";
465
536
  /** 清掉以前崩溃/被杀留下的 .dsh-download-* 暂存目录(只清超过 1 小时的,不碰并发的那一份)。 */
466
537
  function sweepStaleTemps(dir) {
@@ -706,36 +777,39 @@ export async function installFirmware(request) {
706
777
  });
707
778
  }
708
779
  }
709
- try {
710
- mkdirSync(decision.dir, { recursive: true });
711
- prepare.status = "done";
712
- prepare.detail = "已建 " + decision.dir + "(" + kindLabel(decision.kind) + ")";
713
- }
714
- catch (error) {
715
- const message = error instanceof Error ? error.message : String(error);
716
- prepare.status = "failed";
717
- prepare.detail = "建不了 " + decision.dir + ":" + message;
718
- return finish({ ok: false, message: "固件包没装成:建不了目标目录 —— " + message });
719
- }
720
- progress("目标目录:" + decision.dir);
721
- // 暂存目录每次唯一(A11):固定名 .dsh-download 在崩溃/被杀之后会留残渣,
722
- // 下一次安装可能读到上次的半截归档;清理也必须在 try 里——删不掉不能顶掉真正的结果。
723
- const tempDir = path.join(decision.dir, ".dsh-download-" + String(process.pid) + "-" + String(Date.now()));
724
- sweepStaleTemps(decision.dir);
725
- try {
726
- mkdirSync(tempDir, { recursive: true });
727
- }
728
- catch (error) {
729
- const message = error instanceof Error ? error.message : String(error);
730
- return finish({ ok: false, message: "固件包没装成:建不了下载暂存目录 —— " + message });
780
+ const lock = acquireInstallLock(decision.dir);
781
+ if (!lock.ok) {
782
+ return finish({
783
+ ok: false,
784
+ message: "固件包没装成:" + lock.error,
785
+ nextStep: "等另一个安装结束后重试;确认没有别的进程时,可以手工删掉 " + decision.dir + ".dsh-install.lock。",
786
+ });
731
787
  }
788
+ const parentDir = path.dirname(decision.dir);
789
+ const tempDir = path.join(parentDir, ".dsh-download-" + String(process.pid) + "-" + String(Date.now()));
790
+ const stagingDir = path.join(tempDir, "package");
732
791
  try {
792
+ try {
793
+ mkdirSync(parentDir, { recursive: true });
794
+ sweepStaleTemps(parentDir);
795
+ mkdirSync(stagingDir, { recursive: true });
796
+ }
797
+ catch (error) {
798
+ const message = error instanceof Error ? error.message : String(error);
799
+ prepare.status = "failed";
800
+ prepare.detail = "建不了安装暂存目录:" + message;
801
+ return finish({ ok: false, message: "固件包没装成:建不了安装暂存目录 —— " + message });
802
+ }
803
+ prepare.status = "done";
804
+ prepare.detail = "先在暂存目录 " + stagingDir + " 里组装,自检通过后再原子换入 " + decision.dir;
805
+ progress("暂存目录:" + stagingDir);
733
806
  const download = stepOf(steps, "download");
734
807
  download.status = "running";
735
808
  const archiveTargets = plan.archives.map((archive) => ({
736
809
  path: archive.id + ".tgz",
737
810
  urls: archive.urls,
738
811
  minBytes: 100_000,
812
+ sha256: archive.sha256,
739
813
  }));
740
814
  const options = {
741
815
  ...(request.signal === undefined ? {} : { signal: request.signal }),
@@ -748,7 +822,7 @@ export async function installFirmware(request) {
748
822
  },
749
823
  };
750
824
  const archives = await fetchAll(archiveTargets, tempDir, options);
751
- const coreDir = path.join(decision.dir, "Drivers", "CMSIS", "Include");
825
+ const coreDir = path.join(stagingDir, "Drivers", "CMSIS", "Include");
752
826
  mkdirSync(coreDir, { recursive: true });
753
827
  const cores = await fetchAll(plan.coreTargets, coreDir, options);
754
828
  const files = archives.ok + cores.ok;
@@ -768,8 +842,9 @@ export async function installFirmware(request) {
768
842
  let extracted = 0;
769
843
  for (const archive of plan.archives) {
770
844
  const archivePath = path.join(tempDir, archive.id + ".tgz");
771
- const buffer = readFileSync(archivePath);
772
- const result = extractTarGz(buffer, decision.dir, { stripComponents: 1, mapPath: mapperFor(archive) });
845
+ // 流式解包:先落成临时 tar(解压阶段卡上限),再按块写进 staging;
846
+ // 不再 readFileSync 整个归档、也不把解压结果全留在内存里。
847
+ const result = await extractTarGzFile(archivePath, stagingDir, { stripComponents: 1, mapPath: mapperFor(archive) });
773
848
  if (!result.ok) {
774
849
  extract.status = "failed";
775
850
  extract.detail = archive.label + " 解包失败:" + result.error;
@@ -781,25 +856,72 @@ export async function installFirmware(request) {
781
856
  extract.status = "done";
782
857
  extract.detail = "摆了 " + String(extracted) + " 个文件进 " + plan.dirName;
783
858
  const packageStep = stepOf(steps, "package");
784
- writeFileSync(path.join(decision.dir, "package.xml"), plan.packageXml, "utf8");
785
- writeFileSync(path.join(decision.dir, NOTICES_FILE), plan.license, "utf8");
859
+ writeFileSync(path.join(stagingDir, "package.xml"), plan.packageXml, "utf8");
860
+ writeFileSync(path.join(stagingDir, NOTICES_FILE), plan.license, "utf8");
786
861
  packageStep.status = "done";
787
862
  packageStep.detail = "package.xml " + String(plan.packageXml.length) + " B(Release " + plan.releaseTag + " / Patch " + plan.patchTag + ")+ " + NOTICES_FILE;
788
- const verify = verifyFirmwarePackage(decision.dir, plan.family);
789
863
  const verifyStep = stepOf(steps, "verify");
864
+ const stagedVerify = verifyFirmwarePackage(stagingDir, plan.family);
865
+ if (!stagedVerify.ok) {
866
+ verifyStep.status = "failed";
867
+ verifyStep.detail = "暂存目录缺:" + stagedVerify.missing.join("、");
868
+ return finish({
869
+ ok: false,
870
+ download: { files, bytes },
871
+ verify: stagedVerify,
872
+ message: "固件包没装成:暂存包自检缺 " + stagedVerify.missing.join("、") + "。目标目录没有被改动。",
873
+ nextStep: "把这段报错贴给我;或者改用 CubeMX 包管理器装官方包。",
874
+ });
875
+ }
876
+ // 自检通过才换入:旧目录先改名备份,换入失败就还原;成功后才删备份。
877
+ // 这样任何中途失败都不会留下"看起来装好了、实际缺文件"的半截包。
878
+ const backupDir = path.join(parentDir, ".dsh-replaced-" + String(process.pid) + "-" + String(Date.now()));
879
+ let movedOld = false;
880
+ try {
881
+ if (existsSync(decision.dir)) {
882
+ renameSync(decision.dir, backupDir);
883
+ movedOld = true;
884
+ }
885
+ renameSync(stagingDir, decision.dir);
886
+ }
887
+ catch (error) {
888
+ if (movedOld && !existsSync(decision.dir)) {
889
+ try {
890
+ renameSync(backupDir, decision.dir);
891
+ }
892
+ catch { /* 还原失败时下面会说明 */ }
893
+ }
894
+ throw error;
895
+ }
896
+ const verify = verifyFirmwarePackage(decision.dir, plan.family);
790
897
  if (!verify.ok) {
898
+ try {
899
+ rmSync(decision.dir, { recursive: true, force: true });
900
+ }
901
+ catch { /* 尽力清掉刚换入的坏包 */ }
902
+ if (movedOld) {
903
+ try {
904
+ renameSync(backupDir, decision.dir);
905
+ }
906
+ catch { /* 旧包还原失败下面会说明 */ }
907
+ }
791
908
  verifyStep.status = "failed";
792
- verifyStep.detail = "缺:" + verify.missing.join("、");
909
+ verifyStep.detail = "换入后自检缺:" + verify.missing.join("、");
793
910
  return finish({
794
911
  ok: false,
795
912
  download: { files, bytes },
796
913
  verify,
797
- message: "固件包没装成:自检缺 " + verify.missing.join("、") + "。",
798
- nextStep: "把这段报错贴给我;或者改用 CubeMX 包管理器装官方包。",
914
+ message: "固件包没装成:换入后自检缺 " + verify.missing.join("、") + ",已回滚旧目录。",
799
915
  });
800
916
  }
917
+ if (movedOld) {
918
+ try {
919
+ rmSync(backupDir, { recursive: true, force: true });
920
+ }
921
+ catch { /* 备份留着不影响结果 */ }
922
+ }
801
923
  verifyStep.status = "done";
802
- verifyStep.detail = "三条判据全过(" + String(verify.checks.length) + " 项检查)";
924
+ verifyStep.detail = "三条判据全过(" + String(verify.checks.length) + " 项检查;原子换入)";
803
925
  // 落点记进 <cacheRoot>/firmware/installed.json:cubeMx 落点靠扫根就能找到,但 cache / 显式 targetDir
804
926
  // 在 CubeMX 根以外,generate 只能靠这条记录 + 缓存目录把它们找回来(B10)。
805
927
  const recordProblem = rememberFirmwareInstall(request.env ?? process.env, plan.dirName, decision.dir, decision.kind);
@@ -833,7 +955,8 @@ export async function installFirmware(request) {
833
955
  }
834
956
  catch (error) {
835
957
  const message = error instanceof Error ? error.message : String(error);
836
- notes.push("下载暂存目录没清掉(" + message + "):" + tempDir + ",可以手工删。");
958
+ notes.push("下载/暂存目录没清掉(" + message + "):" + tempDir + ",可以手工删。");
837
959
  }
960
+ lock.release();
838
961
  }
839
962
  }