dsh-stm32 0.1.3 → 0.1.4

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 (221) hide show
  1. package/README.md +52 -38
  2. package/README_EN.md +44 -33
  3. package/assets/README.md +85 -0
  4. package/assets/VERSION +1 -0
  5. package/assets/device/c0/chips.json +1108 -0
  6. package/assets/device/f0/chips.json +1570 -0
  7. package/assets/device/f1/chips.json +1238 -0
  8. package/assets/device/f1/svd/100.json +943 -0
  9. package/assets/device/f1/svd/101.json +901 -0
  10. package/assets/device/f1/svd/102.json +522 -0
  11. package/assets/device/f1/svd/103.json +1139 -0
  12. package/assets/device/f1/svd/105.json +1117 -0
  13. package/assets/device/f1/svd/107.json +1195 -0
  14. package/assets/device/f2/chips.json +674 -0
  15. package/assets/device/f3/chips.json +1318 -0
  16. package/assets/device/f4/chips.json +2942 -0
  17. package/assets/device/f7/chips.json +1710 -0
  18. package/assets/device/g0/chips.json +2102 -0
  19. package/assets/device/g4/chips.json +2494 -0
  20. package/assets/device/h5/chips.json +898 -0
  21. package/assets/device/h7/chips.json +1948 -0
  22. package/assets/device/l0/chips.json +2494 -0
  23. package/assets/device/l1/chips.json +1234 -0
  24. package/assets/device/l4/chips.json +2130 -0
  25. package/assets/device/l4+/chips.json +856 -0
  26. package/assets/device/l5/chips.json +226 -0
  27. package/assets/device/u0/chips.json +688 -0
  28. package/assets/device/u3/chips.json +310 -0
  29. package/assets/device/u5/chips.json +884 -0
  30. package/assets/device/wba/chips.json +506 -0
  31. package/assets/device/wl/chips.json +184 -0
  32. package/assets/headers/f1/stm32f100xb.h +5972 -0
  33. package/assets/headers/f1/stm32f100xe.h +6587 -0
  34. package/assets/headers/f1/stm32f101x6.h +5315 -0
  35. package/assets/headers/f1/stm32f101xb.h +5446 -0
  36. package/assets/headers/f1/stm32f101xe.h +6503 -0
  37. package/assets/headers/f1/stm32f101xg.h +6713 -0
  38. package/assets/headers/f1/stm32f102x6.h +6448 -0
  39. package/assets/headers/f1/stm32f102xb.h +6570 -0
  40. package/assets/headers/f1/stm32f103x6.h +10109 -0
  41. package/assets/headers/f1/stm32f103xb.h +10240 -0
  42. package/assets/headers/f1/stm32f103xe.h +11767 -0
  43. package/assets/headers/f1/stm32f103xg.h +11951 -0
  44. package/assets/headers/f1/stm32f105xc.h +14340 -0
  45. package/assets/headers/f1/stm32f107xc.h +15253 -0
  46. package/assets/headers/f1/stm32f1xx.h +273 -0
  47. package/assets/headers/f1/system_stm32f1xx.h +96 -0
  48. package/assets/ioc/family/C0.ioc +82 -0
  49. package/assets/ioc/family/F0.ioc +71 -0
  50. package/assets/ioc/family/F2.ioc +91 -0
  51. package/assets/ioc/family/F3.ioc +94 -0
  52. package/assets/ioc/family/F4.ioc +91 -0
  53. package/assets/ioc/family/F7.ioc +102 -0
  54. package/assets/ioc/family/G0.ioc +90 -0
  55. package/assets/ioc/family/G4.ioc +110 -0
  56. package/assets/ioc/family/H5.ioc +116 -0
  57. package/assets/ioc/family/H7.ioc +133 -0
  58. package/assets/ioc/family/L0.ioc +92 -0
  59. package/assets/ioc/family/L1.ioc +87 -0
  60. package/assets/ioc/family/L4+.ioc +92 -0
  61. package/assets/ioc/family/L4.ioc +93 -0
  62. package/assets/ioc/family/L5.ioc +91 -0
  63. package/assets/ioc/family/U0.ioc +103 -0
  64. package/assets/ioc/family/U3.ioc +113 -0
  65. package/assets/ioc/family/U5.ioc +102 -0
  66. package/assets/ioc/family/WBA.ioc +100 -0
  67. package/assets/ioc/family/WL.ioc +93 -0
  68. package/assets/ioc/minimal/STM32F100C8Tx.ioc +113 -0
  69. package/assets/ioc/minimal/STM32F100RCTx.ioc +113 -0
  70. package/assets/ioc/minimal/STM32F101C4Tx.ioc +113 -0
  71. package/assets/ioc/minimal/STM32F101C8Tx.ioc +113 -0
  72. package/assets/ioc/minimal/STM32F101RCTx.ioc +113 -0
  73. package/assets/ioc/minimal/STM32F101RFTx.ioc +113 -0
  74. package/assets/ioc/minimal/STM32F102C4Tx.ioc +113 -0
  75. package/assets/ioc/minimal/STM32F102C8Tx.ioc +113 -0
  76. package/assets/ioc/minimal/STM32F103C4Tx.ioc +113 -0
  77. package/assets/ioc/minimal/STM32F103C8Tx.ioc +113 -0
  78. package/assets/ioc/minimal/STM32F103RCTx.ioc +113 -0
  79. package/assets/ioc/minimal/STM32F103RFTx.ioc +113 -0
  80. package/assets/ioc/minimal/STM32F105RCTx.ioc +113 -0
  81. package/assets/ioc/minimal/STM32F107RCTx.ioc +113 -0
  82. package/assets/ld/f1/STM32F100C8Tx_FLASH.ld +249 -0
  83. package/assets/ld/f1/STM32F100RCTx_FLASH.ld +249 -0
  84. package/assets/ld/f1/STM32F101C4Tx_FLASH.ld +249 -0
  85. package/assets/ld/f1/STM32F101C8Tx_FLASH.ld +249 -0
  86. package/assets/ld/f1/STM32F101RCTx_FLASH.ld +249 -0
  87. package/assets/ld/f1/STM32F101RFTx_FLASH.ld +249 -0
  88. package/assets/ld/f1/STM32F102C4Tx_FLASH.ld +249 -0
  89. package/assets/ld/f1/STM32F102C8Tx_FLASH.ld +249 -0
  90. package/assets/ld/f1/STM32F103C4Tx_FLASH.ld +249 -0
  91. package/assets/ld/f1/STM32F103C8Tx_FLASH.ld +249 -0
  92. package/assets/ld/f1/STM32F103RCTx_FLASH.ld +249 -0
  93. package/assets/ld/f1/STM32F103RFTx_FLASH.ld +249 -0
  94. package/assets/ld/f1/STM32F105RCTx_FLASH.ld +249 -0
  95. package/assets/ld/f1/STM32F107RCTx_FLASH.ld +249 -0
  96. package/assets/manifest.json +1130 -0
  97. package/assets/startup/f1/startup_stm32f100xb.s +407 -0
  98. package/assets/startup/f1/startup_stm32f100xe.s +449 -0
  99. package/assets/startup/f1/startup_stm32f101x6.s +322 -0
  100. package/assets/startup/f1/startup_stm32f101xb.s +338 -0
  101. package/assets/startup/f1/startup_stm32f101xe.s +423 -0
  102. package/assets/startup/f1/startup_stm32f101xg.s +439 -0
  103. package/assets/startup/f1/startup_stm32f102x6.s +330 -0
  104. package/assets/startup/f1/startup_stm32f102xb.s +346 -0
  105. package/assets/startup/f1/startup_stm32f103x6.s +348 -0
  106. package/assets/startup/f1/startup_stm32f103xb.s +364 -0
  107. package/assets/startup/f1/startup_stm32f103xe.s +470 -0
  108. package/assets/startup/f1/startup_stm32f103xg.s +466 -0
  109. package/assets/startup/f1/startup_stm32f105xc.s +463 -0
  110. package/assets/startup/f1/startup_stm32f107xc.s +472 -0
  111. package/assets/templates/family/C0.ioc +82 -0
  112. package/assets/templates/family/F0.ioc +71 -0
  113. package/assets/templates/family/F2.ioc +91 -0
  114. package/assets/templates/family/F3.ioc +94 -0
  115. package/assets/templates/family/F4.ioc +91 -0
  116. package/assets/templates/family/F7.ioc +102 -0
  117. package/assets/templates/family/G0.ioc +90 -0
  118. package/assets/templates/family/G4.ioc +110 -0
  119. package/assets/templates/family/H5.ioc +116 -0
  120. package/assets/templates/family/H7.ioc +133 -0
  121. package/assets/templates/family/L0.ioc +92 -0
  122. package/assets/templates/family/L1.ioc +87 -0
  123. package/assets/templates/family/L4+.ioc +92 -0
  124. package/assets/templates/family/L4.ioc +93 -0
  125. package/assets/templates/family/L5.ioc +91 -0
  126. package/assets/templates/family/U0.ioc +103 -0
  127. package/assets/templates/family/U3.ioc +113 -0
  128. package/assets/templates/family/U5.ioc +102 -0
  129. package/assets/templates/family/WB.ioc +81 -0
  130. package/assets/templates/family/WBA.ioc +100 -0
  131. package/assets/templates/family/WL.ioc +93 -0
  132. package/docs/reading-guide.md +37 -35
  133. package/lib/data/chips.js +3 -3
  134. package/lib/data/clock-db.js +830 -0
  135. package/lib/data/clock-f1.js +12 -45
  136. package/lib/data/cmsis-sources.js +239 -18
  137. package/lib/data/db-presets.js +252 -0
  138. package/lib/data/device-facts.js +99 -26
  139. package/lib/data/family.js +515 -0
  140. package/lib/data/firmware-packages.js +562 -0
  141. package/lib/data/install-guides.js +2 -2
  142. package/lib/data/ioc-presets.js +248 -0
  143. package/lib/data/ioc-schema.js +1058 -0
  144. package/lib/data/rm-topics/stm32c0.json +227 -0
  145. package/lib/data/rm-topics.js +103 -0
  146. package/lib/data/search-roots.js +42 -1
  147. package/lib/data/stm32f1.js +15 -14
  148. package/lib/data/svd.js +32 -16
  149. package/lib/data/toolchain-config.js +0 -14
  150. package/lib/engine/assets.js +191 -456
  151. package/lib/engine/breakpoints.js +66 -11
  152. package/lib/engine/clock-derived.js +101 -0
  153. package/lib/engine/clock-direct.js +313 -0
  154. package/lib/engine/clock-plan.js +96 -52
  155. package/lib/engine/clock-pllmn.js +319 -0
  156. package/lib/engine/cmake-sources.js +67 -13
  157. package/lib/engine/cube-mx-guard.js +44 -0
  158. package/lib/engine/cube-programmer.js +137 -0
  159. package/lib/engine/cubemx-db.js +273 -0
  160. package/lib/engine/debug-session.js +423 -17
  161. package/lib/engine/debug.js +25 -6
  162. package/lib/engine/doctor.js +160 -17
  163. package/lib/engine/facts-acquire.js +416 -0
  164. package/lib/engine/facts.js +134 -0
  165. package/lib/engine/firmware-install.js +176 -5
  166. package/lib/engine/firmware-official.js +451 -0
  167. package/lib/engine/flash.js +290 -21
  168. package/lib/engine/gdb-mi.js +476 -0
  169. package/lib/engine/generate.js +9 -2
  170. package/lib/engine/hal-chip.js +124 -41
  171. package/lib/engine/ioc-plan.js +1244 -60
  172. package/lib/engine/ioc-rules.js +698 -0
  173. package/lib/engine/ioc-verify.js +706 -0
  174. package/lib/engine/ioc.js +43 -4
  175. package/lib/engine/msys2-install.js +4 -4
  176. package/lib/engine/probe-error.js +25 -6
  177. package/lib/engine/probe-session.js +50 -14
  178. package/lib/engine/probe.js +18 -3
  179. package/lib/engine/register-clock.js +41 -0
  180. package/lib/engine/register-gpio.js +115 -0
  181. package/lib/engine/register-linker.js +12 -7
  182. package/lib/engine/register-template.js +101 -40
  183. package/lib/engine/regs.js +41 -8
  184. package/lib/engine/rm-extract.js +144 -0
  185. package/lib/engine/rm-sources.js +360 -0
  186. package/lib/engine/rm-text.js +56 -0
  187. package/lib/engine/rtt.js +188 -30
  188. package/lib/engine/scaffold.js +185 -18
  189. package/lib/engine/toolchain-gate.js +0 -4
  190. package/lib/engine/watch.js +227 -0
  191. package/lib/index.js +4 -2
  192. package/lib/skill/stm32-workflow.js +2 -2
  193. package/lib/tools/assets.js +39 -108
  194. package/lib/tools/cache.js +2 -2
  195. package/lib/tools/debug-session.js +2 -2
  196. package/lib/tools/doctor.js +55 -5
  197. package/lib/tools/firmware-install.js +31 -6
  198. package/lib/tools/flash.js +32 -4
  199. package/lib/tools/generate.js +22 -0
  200. package/lib/tools/ioc-inspect.js +1 -1
  201. package/lib/tools/ioc-plan.js +56 -2
  202. package/lib/tools/ioc-verify.js +237 -0
  203. package/lib/tools/project-create.js +41 -5
  204. package/lib/tools/regs.js +8 -8
  205. package/lib/tools/route-plan.js +1 -1
  206. package/lib/tools/rtt.js +157 -34
  207. package/lib/tools/watch.js +256 -0
  208. package/package.json +5 -4
  209. package/templates/openocd/stm32c0x.cfg +83 -0
  210. package/templates/openocd/stm32u0x.cfg +64 -0
  211. package/templates/register/CMakeLists.txt +2 -2
  212. package/templates/register/Core/Inc/rtt.h +37 -2
  213. package/templates/register/Core/Src/main.c +17 -25
  214. package/templates/register/Core/Src/rtt.c +85 -9
  215. package/templates/scaffold/RTT.md +6 -2
  216. package/templates/scaffold/STM32F103XX_FLASH.ld +3 -0
  217. package/templates/scaffold/openocd.cfg +5 -3
  218. package/templates/scaffold/vscode/launch.json +8 -4
  219. package/docs/development-notes.md +0 -2487
  220. package/docs/dsh-stm32-plugin-/350/247/204/346/240/274.md +0 -673
  221. package/docs/logic-audit.md +0 -607
@@ -1,53 +1,31 @@
1
1
  /**
2
- * 资源包(dsh-stm32-assets)下载器:manifest → 逐文件 sha256 → 本地缓存。
2
+ * 内置资源层:assets/ 随插件包发布,读 manifest + 逐文件 sha256 校验。
3
3
  *
4
- * 为什么要有这一层:插件已经不再内置任何芯片表(chip-table.json / F1_LINES / 引脚表 2026-10-31 全删),
5
- * 设备事实(chips.json / memory.json / svd/<line>.json)、ioc 模板、链接脚本全部来自独立仓库
6
- * dsh-stm32-assets,按 profile 按需下载到 <home>/.dsh-stm32/assets/<version>/,之后复用;
7
- * 每个文件都带 sha256,装坏/装半截宁可整次拒绝,也不给上层一份"看起来装好了"的目录。
4
+ * 2026-11 之前资源放在独立仓库 dsh-stm32-assets,第一次用要联网下载到 ~/.dsh-stm32/assets/<version>/。
5
+ * 资产总共 12.5 MB,拆两个仓库的维护成本(发版要对齐、下载会失败、离线不可用)大于收益,于是整体并入插件:
6
+ * · 默认根 = 插件包内的 assets/(flat:manifest.json 与 device/、ioc/ 同层);
7
+ * · DSH_STM32_ASSETS 仍可覆盖(测试夹具、以及老用户留着旧版本缓存时继续可读);
8
+ * · 老布局 <root>/<version>/install.json 继续认,flat 优先。
8
9
  *
9
10
  * 关键约定:
10
- * · 多源:GitHub raw → jsDelivr → GitCode,manifest 与文件各自逐源回退(写死一个源就是押注线路);
11
- * · 失败不抛:下载/校验失败都变成 ok:false + 人话原因,工具卡片照常渲染;
12
- * · 没有内置表可退:装不上就等于没有设备事实,所以 ensureAssets 的报错必须说清
13
- * "缺的是什么、先跑 stm32_assets refresh 或检查网络";
14
- * · 半成品必须删干净:先下到 <version>.tmp-<pid>-<seq>/,全部哈希通过才搬进 <version>/,
15
- * 中途失败只删临时目录,旧版本一个字节都不动。
11
+ * · 不再有网络下载器:ensureAssets 是纯本地检查,缺文件只可能是插件安装不完整;
12
+ * · sha256 仍逐文件校验(verify):内置不等于可信,装坏/被杀软改过要能查出来;
13
+ * · 失败不抛:都变成 ok:false + 人话原因,工具卡片照常渲染;
14
+ * · prune 绝不删内置 flat 根,只清 DSH_STM32_ASSETS 下的历史版本目录。
16
15
  *
17
- * 零运行时依赖:只用 node:fs / node:path / node:crypto / node:os 与全局 fetch(Node 18+),
18
- * 测试通过 fetchImpl 注入假 fetch,一次网络都不发。
16
+ * 零运行时依赖:只用 node:fs / node:path / node:crypto / node:url。
19
17
  */
20
18
  import { createHash } from "node:crypto";
21
19
  import fs from "node:fs";
22
- import os from "node:os";
23
20
  import path from "node:path";
21
+ import { fileURLToPath } from "node:url";
24
22
  export const ASSETS_MANIFEST_FILE = "manifest.json";
23
+ /** 老版本安装布局的标记文件(flat 内置资源没有它)。 */
25
24
  export const ASSETS_INSTALL_FILE = "install.json";
26
- /** 设备事实在资源包里的相对路径(插件唯一的芯片事实来源)。 */
25
+ /** 设备事实在资源根里的相对路径(插件唯一的芯片事实来源)。 */
27
26
  export const ASSETS_DEVICE_FACTS_FILE = "device/f1/chips.json";
28
- /** 缺资源包时对用户说的那句话(工具卡片、错误、note 都复用它,避免各写一套)。 */
29
- export const ASSETS_REFRESH_HINT = "先跑 stm32_assets refresh,或检查网络";
30
- /**
31
- * 候选源与顺序。顺序不是随便排的:GitHub raw 是上游真身(版本与 README 一致),
32
- * jsDelivr 在部分网络里更快、且能吃缓存,GitCode 是最后一条独立线路(前两个同源)。
33
- */
34
- export const ASSETS_SOURCES = [
35
- {
36
- id: "github",
37
- label: "GitHub raw(主源)",
38
- baseUrl: "https://raw.githubusercontent.com/JingYu-er/dsh-stm32-assets/main/",
39
- },
40
- {
41
- id: "jsdelivr",
42
- label: "jsDelivr CDN(备用)",
43
- baseUrl: "https://cdn.jsdelivr.net/gh/JingYu-er/dsh-stm32-assets@main/",
44
- },
45
- {
46
- id: "gitcode",
47
- label: "GitCode 镜像(再备用)",
48
- baseUrl: "https://raw.gitcode.com/qq_66375182/dsh-stm32-assets/raw/main/",
49
- },
50
- ];
27
+ /** 缺资源时对用户说的那句话(工具卡片、错误、note 都复用它,避免各写一套)。 */
28
+ export const ASSETS_REFRESH_HINT = "资源随插件内置(assets/):缺文件说明插件安装不完整,重装插件后重试;stm32_assets verify 可定位缺了哪些";
51
29
  /** 只给 core / full;空串按 core 处理,别的值返回 null(由调用方给可读报错,不瞎猜)。 */
52
30
  export function normalizeProfile(value) {
53
31
  const text = (value ?? "core").trim().toLowerCase();
@@ -57,20 +35,10 @@ export function normalizeProfile(value) {
57
35
  return text;
58
36
  return null;
59
37
  }
60
- /**
61
- * 解析调用方指定的源:认 github / jsdelivr / gitcode,或者一个完整的 base URL。
62
- * 显式指定 = 只走它(用户说"我只想从 GitHub 下"时不该偷偷换源);
63
- * 不指定 = 按 ASSETS_SOURCES 顺序回退。
64
- */
65
- export function resolveSources(override) {
66
- const text = (override ?? "").trim();
67
- if (text === "")
68
- return [...ASSETS_SOURCES];
69
- const match = ASSETS_SOURCES.find((source) => source.id === text.toLowerCase());
70
- if (match !== undefined)
71
- return [match];
72
- const baseUrl = text.endsWith("/") ? text : text + "/";
73
- return [{ id: "custom", label: "调用方指定的源", baseUrl }];
38
+ /** 插件包内的 assets/:lib/engine/assets.js 往上两级就是包根。 */
39
+ export function bundledAssetsRoot() {
40
+ const here = path.dirname(fileURLToPath(import.meta.url));
41
+ return path.resolve(here, "..", "..", "assets");
74
42
  }
75
43
  function expandHome(value, env) {
76
44
  if (value === "~" || value.startsWith("~/") || value.startsWith("~\\")) {
@@ -80,26 +48,19 @@ function expandHome(value, env) {
80
48
  }
81
49
  return value;
82
50
  }
83
- /** 资源根目录:DSH_STM32_ASSETS 覆盖,默认 ~/.dsh-stm32/assets(每个版本一个子目录)。 */
51
+ /** 资源根目录:DSH_STM32_ASSETS 覆盖,默认插件包内 assets/。 */
84
52
  export function assetsRootInfo(env = process.env) {
85
53
  const override = (env.DSH_STM32_ASSETS ?? "").trim();
86
54
  if (override !== "") {
87
- return { root: path.resolve(expandHome(override, env)), origin: "DSH_STM32_ASSETS" };
55
+ return { root: path.resolve(expandHome(override, env)), origin: "DSH_STM32_ASSETS(覆盖内置资源)" };
88
56
  }
89
- const userProfile = (env.USERPROFILE ?? "").trim();
90
- if (userProfile !== "") {
91
- return { root: path.join(userProfile, ".dsh-stm32", "assets"), origin: "USERPROFILE" };
92
- }
93
- const home = (env.HOME ?? "").trim();
94
- if (home !== "")
95
- return { root: path.join(home, ".dsh-stm32", "assets"), origin: "HOME" };
96
- return { root: path.join(os.homedir(), ".dsh-stm32", "assets"), origin: "用户主目录" };
57
+ return { root: bundledAssetsRoot(), origin: "插件内置(assets/)" };
97
58
  }
98
- /** 资源根(不含版本号)。测试里用 DSH_STM32_ASSETS 指到临时目录,绝不碰真实 home。 */
59
+ /** 资源根(不含版本号)。测试里用 DSH_STM32_ASSETS 指到临时目录,绝不碰真实 assets/。 */
99
60
  export function localAssetsRoot(env = process.env) {
100
61
  return assetsRootInfo(env).root;
101
62
  }
102
- /** 某个版本的安装目录:<root>/<version>/。 */
63
+ /** 老布局里某个版本的安装目录:<root>/<version>/。 */
103
64
  export function versionDir(version, env = process.env) {
104
65
  return path.join(localAssetsRoot(env), version);
105
66
  }
@@ -125,8 +86,8 @@ function shortHash(value) {
125
86
  return value.length > 16 ? value.slice(0, 16) + "…" : value;
126
87
  }
127
88
  /**
128
- * 解析并校验 manifest。校验不过返回 error(调用方换源),不抛异常。
129
- * 为什么严:manifest 是"装什么、装成后该是什么"的唯一事实来源,少一个 sha256 就等于放弃校验。
89
+ * 解析并校验 manifest。校验不过返回 error,不抛异常。
90
+ * 为什么严:manifest 是"有哪些文件、该是什么内容"的唯一事实来源,少一个 sha256 就等于放弃校验。
130
91
  */
131
92
  export function parseManifest(text) {
132
93
  let parsed;
@@ -142,9 +103,7 @@ export function parseManifest(text) {
142
103
  if (typeof version !== "string" || version.trim() === "") {
143
104
  return {
144
105
  manifest: null,
145
- error: "manifest.json 缺 version(没有版本号就不知道该往哪个目录装)。" +
146
- "如果资源仓库里还是老的 v1 manifest(只有 plugin/cubeMx 路径、没有 version/schema/profiles)," +
147
- "先把带 version 与 profiles 的 schema 2 manifest 推上去再刷新。",
106
+ error: "manifest.json 缺 version。资源现在随插件内置,正常安装不会缺;用 scripts/assets/build-assets.mjs 重新生成。",
148
107
  };
149
108
  }
150
109
  const rawFiles = parsed["files"];
@@ -169,7 +128,7 @@ export function parseManifest(text) {
169
128
  seen.add(normalized);
170
129
  const sha256 = item["sha256"];
171
130
  if (typeof sha256 !== "string" || !SHA256_RE.test(sha256.toLowerCase())) {
172
- return { manifest: null, error: where + "(" + normalized + ")缺 sha256 或不是 64 位十六进制;没有哈希就无法校验,拒绝安装" };
131
+ return { manifest: null, error: where + "(" + normalized + ")缺 sha256 或不是 64 位十六进制;没有哈希就无法校验" };
173
132
  }
174
133
  const bytes = item["bytes"];
175
134
  if (typeof bytes !== "number" || !Number.isFinite(bytes) || bytes < 0) {
@@ -200,7 +159,7 @@ export function parseManifest(text) {
200
159
  const schema = typeof parsed["schema"] === "number" ? parsed["schema"] : 1;
201
160
  return { manifest: { ...parsed, name, version, schema, profiles, files, skipped }, error: "" };
202
161
  }
203
- /** 相对路径规整:反斜杠转正斜杠、拒绝绝对路径/盘符/.. —— 防止 manifest 把文件写到资源根以外。 */
162
+ /** 相对路径规整:反斜杠转正斜杠、拒绝绝对路径/盘符/.. —— 防止 manifest 把文件指到资源根以外。 */
204
163
  export function normalizeAssetPath(raw) {
205
164
  const text = raw.split("\\").join("/").trim();
206
165
  if (text === "" || text.startsWith("/") || /^[A-Za-z]:/u.test(text))
@@ -212,13 +171,6 @@ export function normalizeAssetPath(raw) {
212
171
  return null;
213
172
  return parts.join("/");
214
173
  }
215
- function urlPath(relPath) {
216
- return relPath.split("/").map((segment) => encodeURIComponent(segment)).join("/");
217
- }
218
- function joinUrl(baseUrl, relPath) {
219
- const base = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
220
- return base + urlPath(relPath);
221
- }
222
174
  /** glob → 正则:** 跨目录,* 不跨目录,? 单字符。manifest 的 profiles 就靠它筛文件。 */
223
175
  function globToRegExp(pattern) {
224
176
  let out = "^";
@@ -241,7 +193,7 @@ function globToRegExp(pattern) {
241
193
  index += 1;
242
194
  continue;
243
195
  }
244
- out += ch.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
196
+ out += ch.replace(/[.*+?^$()|[\]\\]/gu, "\\$&");
245
197
  index += 1;
246
198
  }
247
199
  return new RegExp(out + "$", "u");
@@ -258,273 +210,38 @@ export function profileFiles(manifest, profile) {
258
210
  }
259
211
  return manifest.files.filter((file) => file.profile === profile || (profile === "full" && file.profile === "core"));
260
212
  }
261
- async function requestBuffer(url, fetchImpl, timeoutMs, signal) {
262
- const controller = new AbortController();
263
- let timedOut = false;
264
- const timer = setTimeout(() => {
265
- timedOut = true;
266
- controller.abort();
267
- }, timeoutMs);
268
- const onAbort = () => controller.abort();
269
- if (signal !== undefined) {
270
- if (signal.aborted)
271
- controller.abort();
272
- else
273
- signal.addEventListener("abort", onAbort, { once: true });
274
- }
275
- try {
276
- const response = await fetchImpl(url, { signal: controller.signal, redirect: "follow" });
277
- if (!response.ok) {
278
- const hint = response.status === 404 ? "(源上没有这个文件)" : response.status === 403 ? "(被拒绝或限流)" : "";
279
- throw new Error("HTTP " + String(response.status) + hint);
280
- }
281
- return Buffer.from(await response.arrayBuffer());
282
- }
283
- catch (error) {
284
- if (timedOut)
285
- throw new Error("超时(" + String(timeoutMs) + " ms 没响应)");
286
- if (signal?.aborted === true)
287
- throw new Error("已取消");
288
- throw new Error(errText(error));
289
- }
290
- finally {
291
- clearTimeout(timer);
292
- signal?.removeEventListener?.("abort", onAbort);
293
- }
294
- }
295
- /** 拉 manifest:逐源试,成功一个就停;全失败返回 ok:false + 每个源的原因(不抛)。 */
296
- export async function fetchManifest(options = {}) {
297
- const sources = options.sources ?? ASSETS_SOURCES;
298
- const fetchImpl = options.fetchImpl ?? fetch;
299
- const timeoutMs = options.timeoutMs ?? 20_000;
300
- const attempts = [];
301
- for (const source of sources) {
302
- if (options.signal?.aborted === true) {
303
- attempts.push(source.id + " → 已取消(没再试)");
304
- break;
305
- }
306
- const url = joinUrl(source.baseUrl, ASSETS_MANIFEST_FILE);
307
- try {
308
- const buffer = await requestBuffer(url, fetchImpl, timeoutMs, options.signal);
309
- const text = buffer.toString("utf8");
310
- const parsed = parseManifest(text);
311
- if (parsed.manifest === null) {
312
- attempts.push(source.id + "(" + source.label + ")→ " + parsed.error);
313
- continue;
314
- }
315
- return { ok: true, manifest: parsed.manifest, text, source, attempts, error: "" };
316
- }
317
- catch (error) {
318
- attempts.push(source.id + "(" + source.label + ")→ " + errText(error));
319
- }
320
- }
321
- return {
322
- ok: false,
323
- manifest: null,
324
- text: "",
325
- source: null,
326
- attempts,
327
- error: attempts.length === 0 ? "没有可用的源(sources 为空)" : "所有源都没拉到 manifest.json:" + attempts.join(";"),
328
- };
329
- }
330
- let stagingSeq = 0;
331
- async function downloadAsset(relPath, sources, fetchImpl, timeoutMs, signal) {
332
- const attempts = [];
333
- for (const source of sources) {
334
- if (signal?.aborted === true) {
335
- attempts.push(source.id + " → 已取消(没再试)");
336
- break;
337
- }
338
- const url = joinUrl(source.baseUrl, relPath);
339
- try {
340
- const buffer = await requestBuffer(url, fetchImpl, timeoutMs, signal);
341
- return { ok: true, buffer, source, attempts, reason: "" };
342
- }
343
- catch (error) {
344
- attempts.push(source.id + "(" + source.label + ")→ " + errText(error));
345
- }
346
- }
347
- return {
348
- ok: false,
349
- buffer: Buffer.alloc(0),
350
- source: null,
351
- attempts,
352
- reason: attempts.length === 0 ? "没有可用的源" : "所有源都没下下来:" + attempts.join(";"),
353
- };
354
- }
213
+ /* ------------------------------ 本地安装 ------------------------------ */
355
214
  function scanDirStats(dir, skipNames = []) {
356
215
  let files = 0;
357
216
  let bytes = 0;
358
- let entries;
359
- try {
360
- entries = fs.readdirSync(dir, { withFileTypes: true });
361
- }
362
- catch {
363
- return { files, bytes };
364
- }
365
- for (const entry of entries) {
366
- if (skipNames.includes(entry.name))
367
- continue;
368
- const full = path.join(dir, entry.name);
369
- if (entry.isDirectory()) {
370
- const nested = scanDirStats(full, skipNames);
371
- files += nested.files;
372
- bytes += nested.bytes;
373
- continue;
374
- }
375
- if (!entry.isFile())
376
- continue;
377
- files += 1;
217
+ const walk = (current) => {
218
+ let entries;
378
219
  try {
379
- bytes += fs.statSync(full).size;
220
+ entries = fs.readdirSync(current, { withFileTypes: true });
380
221
  }
381
222
  catch {
382
- // 统计不到大小不影响"有几个文件"的结论。
383
- }
384
- }
385
- return { files, bytes };
386
- }
387
- /**
388
- * 按 profile 安装到本地:逐文件下载 → 逐文件 sha256 → 全绿才搬进 <version>/。
389
- *
390
- * 失败语义(这是这一层的硬承诺):
391
- * · 任何一个文件下载失败 / 哈希不符 / 字节数不符 → 整次 ok:false;
392
- * · 临时目录 <version>.tmp-* 一定删掉,<version>/ 里不留半成品;
393
- * 之前装好的同版本内容不被这次失败影响(旧文件不动);
394
- * · failures 里点名是哪个文件、期望与实际的哈希,调用方能直接说人话。
395
- */
396
- export async function verifyAndInstall(request) {
397
- const env = request.env ?? process.env;
398
- const base = request.root !== undefined && request.root !== "" ? request.root : localAssetsRoot(env);
399
- const version = request.manifest.version;
400
- const destRoot = path.join(base, version);
401
- const profile = normalizeProfile(request.profile);
402
- const common = {
403
- root: base,
404
- versionDir: destRoot,
405
- version,
406
- profile: profile ?? (request.profile ?? "").trim(),
407
- source: "",
408
- files: [],
409
- failures: [],
410
- fileCount: 0,
411
- totalBytes: 0,
412
- attempts: [],
413
- };
414
- const fail = (message, extra = {}) => ({
415
- ...common,
416
- ...extra,
417
- ok: false,
418
- message,
419
- });
420
- if (profile === null) {
421
- return fail("不认识的 profile:" + String(request.profile) + "(只有 core / full)。什么都没装。");
422
- }
423
- const targets = profileFiles(request.manifest, profile);
424
- if (targets.length === 0) {
425
- return fail("manifest 的 profile=" + profile + " 里一个文件都没有,拒绝安装(检查 manifest.profiles 与 files[].profile)。");
426
- }
427
- for (const target of targets) {
428
- const normalized = normalizeAssetPath(target.path);
429
- if (normalized === null || normalized !== target.path) {
430
- return fail("manifest 里的路径不合法:" + target.path + "(必须是资源根内的相对路径)。什么都没装。");
223
+ return;
431
224
  }
432
- }
433
- const sources = request.sources ?? ASSETS_SOURCES;
434
- const fetchImpl = request.fetchImpl ?? fetch;
435
- const timeoutMs = request.timeoutMs ?? 30_000;
436
- stagingSeq += 1;
437
- const staging = path.join(base, version + ".tmp-" + String(process.pid) + "-" + String(stagingSeq));
438
- const destExisted = fs.existsSync(destRoot);
439
- const installed = [];
440
- const usedSources = [];
441
- let totalBytes = 0;
442
- try {
443
- fs.rmSync(staging, { recursive: true, force: true });
444
- fs.mkdirSync(staging, { recursive: true });
445
- for (const target of targets) {
446
- if (request.signal?.aborted === true) {
447
- return fail("已取消:装到 " + String(installed.length) + "/" + String(targets.length) + " 个文件时被取消,临时文件已清掉,旧版本没动。");
448
- }
449
- const download = await downloadAsset(target.path, sources, fetchImpl, timeoutMs, request.signal);
450
- if (!download.ok || download.source === null) {
451
- return fail("下载失败:" + target.path + " —— " + download.reason + "。已回滚(临时文件删掉," + (destExisted ? "原有 " + version + " 内容没动" : "没有留下半成品") + ")。", { failures: [{ path: target.path, expected: target.sha256, actual: "", reason: download.reason, attempts: download.attempts }], attempts: download.attempts });
452
- }
453
- const actual = sha256Hex(download.buffer);
454
- if (actual !== target.sha256) {
455
- const reason = "sha256 对不上(期望 " + shortHash(target.sha256) + ",实际 " + shortHash(actual) + ")";
456
- return fail("校验失败:" + target.path + " 的 " + reason + "。已回滚 —— 临时文件删掉," + (destExisted ? "原有 " + version + " 内容没动" : "没有留下半成品") + "。", {
457
- failures: [{ path: target.path, expected: target.sha256, actual, reason, attempts: download.attempts }],
458
- attempts: download.attempts,
459
- });
225
+ for (const entry of entries) {
226
+ if (skipNames.includes(entry.name))
227
+ continue;
228
+ const abs = path.join(current, entry.name);
229
+ if (entry.isDirectory()) {
230
+ walk(abs);
231
+ continue;
460
232
  }
461
- if (target.bytes > 0 && download.buffer.byteLength !== target.bytes) {
462
- const reason = "字节数对不上(manifest 写 " + String(target.bytes) + ",实际 " + String(download.buffer.byteLength) + ")";
463
- return fail("校验失败:" + target.path + " 的 " + reason + "。已回滚 —— 临时文件删掉," + (destExisted ? "原有 " + version + " 内容没动" : "没有留下半成品") + "。", {
464
- failures: [{ path: target.path, expected: target.sha256, actual, reason, attempts: download.attempts }],
465
- attempts: download.attempts,
466
- });
233
+ try {
234
+ const stat = fs.statSync(abs);
235
+ files += 1;
236
+ bytes += stat.size;
467
237
  }
468
- const dest = path.join(staging, target.path);
469
- fs.mkdirSync(path.dirname(dest), { recursive: true });
470
- fs.writeFileSync(dest, download.buffer);
471
- installed.push({ path: target.path, bytes: download.buffer.byteLength, sha256: actual, source: download.source.id, status: "ok", detail: "" });
472
- totalBytes += download.buffer.byteLength;
473
- if (!usedSources.includes(download.source.id))
474
- usedSources.push(download.source.id);
475
- }
476
- // 全部校验通过才动正式目录:先搬文件,再写 manifest / install.json。
477
- fs.mkdirSync(destRoot, { recursive: true });
478
- try {
479
- for (const file of installed) {
480
- const from = path.join(staging, file.path);
481
- const to = path.join(destRoot, file.path);
482
- fs.mkdirSync(path.dirname(to), { recursive: true });
483
- fs.rmSync(to, { force: true });
484
- fs.renameSync(from, to);
238
+ catch {
239
+ // 读不到就跳过,不因为一个坏文件让整份统计失败。
485
240
  }
486
- const manifestPath = path.join(destRoot, ASSETS_MANIFEST_FILE);
487
- fs.writeFileSync(manifestPath, request.manifestText ?? JSON.stringify(request.manifest, null, 2) + "\n", "utf8");
488
- const previous = readInstallRecord(destRoot);
489
- const profiles = new Set(previous?.profiles ?? []);
490
- profiles.add(profile);
491
- const stats = scanDirStats(destRoot, [ASSETS_MANIFEST_FILE, ASSETS_INSTALL_FILE]);
492
- const record = {
493
- version,
494
- profiles: [...profiles].sort(),
495
- installedAt: new Date().toISOString(),
496
- source: usedSources.join("+"),
497
- schema: request.manifest.schema,
498
- fileCount: stats.files,
499
- totalBytes: stats.bytes,
500
- };
501
- fs.writeFileSync(path.join(destRoot, ASSETS_INSTALL_FILE), JSON.stringify(record, null, 2) + "\n", "utf8");
502
241
  }
503
- catch (error) {
504
- // 搬文件途中失败:至少把这次新出现的版本目录整个撤掉,别留"半个版本"。
505
- if (!destExisted)
506
- fs.rmSync(destRoot, { recursive: true, force: true });
507
- return fail("写盘失败(" + errText(error) + "):已回滚" + (destExisted ? ",原有 " + version + " 内容没动" : ",没有留下半成品") + "。");
508
- }
509
- return {
510
- ...common,
511
- ok: true,
512
- source: usedSources.join("+"),
513
- files: installed,
514
- fileCount: installed.length,
515
- totalBytes,
516
- message: "已安装资源包 " + version + "(profile=" + profile + "):" + String(installed.length) + " 个文件、" +
517
- String(totalBytes) + " 字节,来源 " + usedSources.join("+") + ";目录 " + destRoot + "。",
518
- };
519
- }
520
- catch (error) {
521
- if (!destExisted)
522
- fs.rmSync(destRoot, { recursive: true, force: true });
523
- return fail("安装中断(" + errText(error) + "):临时文件已清掉,没有留下半成品。");
524
- }
525
- finally {
526
- fs.rmSync(staging, { recursive: true, force: true });
527
- }
242
+ };
243
+ walk(dir);
244
+ return { files, bytes };
528
245
  }
529
246
  function readInstallRecord(dir) {
530
247
  try {
@@ -578,17 +295,53 @@ export function compareVersions(a, b) {
578
295
  }
579
296
  return 0;
580
297
  }
581
- /** 扫描本地装过哪些版本(有新到旧)。只认带 install.json 的目录,所以半成品不会被当成"已安装"。 */
298
+ /** 读 flat 资源根的 manifest(有文件但坏了与根本没装要分开报)。 */
299
+ function readFlatManifest(dir) {
300
+ const manifestPath = path.join(dir, ASSETS_MANIFEST_FILE);
301
+ if (!fs.existsSync(manifestPath))
302
+ return { manifest: null, error: "", present: false };
303
+ let text;
304
+ try {
305
+ text = fs.readFileSync(manifestPath, "utf8");
306
+ }
307
+ catch (error) {
308
+ return { manifest: null, error: "内置资源 manifest 读不了(" + manifestPath + "):" + errText(error), present: true };
309
+ }
310
+ const parsed = parseManifest(text);
311
+ if (parsed.manifest === null) {
312
+ return { manifest: null, error: "内置资源 manifest 坏了(" + manifestPath + "):" + parsed.error, present: true };
313
+ }
314
+ return { manifest: parsed.manifest, error: "", present: true };
315
+ }
316
+ /**
317
+ * 扫描本地有哪些资源版本(有新到旧)。flat 内置根排第一(current=true),
318
+ * 然后是 DSH_STM32_ASSETS 下带 install.json 的历史版本目录(半成品不算)。
319
+ */
582
320
  export function listInstalledVersions(env = process.env, root) {
583
321
  const base = root !== undefined && root !== "" ? root : localAssetsRoot(env);
322
+ const found = [];
323
+ const flat = readFlatManifest(base);
324
+ if (flat.manifest !== null) {
325
+ const stats = scanDirStats(base, [ASSETS_MANIFEST_FILE]);
326
+ found.push({
327
+ version: flat.manifest.version,
328
+ dir: base,
329
+ profiles: Object.keys(flat.manifest.profiles).length > 0 ? Object.keys(flat.manifest.profiles) : ["core"],
330
+ installedAt: "插件内置",
331
+ fileCount: stats.files,
332
+ totalBytes: stats.bytes,
333
+ current: true,
334
+ bundled: true,
335
+ });
336
+ }
584
337
  let entries;
585
338
  try {
586
339
  entries = fs.readdirSync(base, { withFileTypes: true });
587
340
  }
588
341
  catch {
589
- return [];
342
+ return found;
590
343
  }
591
- const found = [];
344
+ const older = [];
592
345
  for (const entry of entries) {
593
346
  if (!entry.isDirectory())
594
347
  continue;
@@ -601,38 +354,63 @@ export function listInstalledVersions(env = process.env, root) {
601
354
  if (record === null)
602
355
  continue;
603
356
  const stats = scanDirStats(dir, [ASSETS_MANIFEST_FILE, ASSETS_INSTALL_FILE]);
604
- found.push({
357
+ older.push({
605
358
  version: record.version,
606
359
  dir,
607
360
  profiles: record.profiles.length > 0 ? record.profiles : ["core"],
608
361
  installedAt: record.installedAt,
609
362
  fileCount: stats.files,
610
363
  totalBytes: stats.bytes,
611
- current: false,
364
+ current: found.length === 0,
365
+ bundled: false,
612
366
  });
613
367
  }
614
- found.sort((left, right) => {
368
+ older.sort((left, right) => {
615
369
  const byVersion = compareVersions(right.version, left.version);
616
370
  if (byVersion !== 0)
617
371
  return byVersion;
618
372
  return right.installedAt.localeCompare(left.installedAt);
619
373
  });
620
- const first = found[0];
621
- if (first !== undefined)
622
- first.current = true;
623
- return found;
374
+ if (found.length === 0) {
375
+ const first = older[0];
376
+ if (first !== undefined)
377
+ first.current = true;
378
+ }
379
+ return [...found, ...older];
624
380
  }
625
381
  /**
626
- * 读本地装好的 manifest(默认最新一版)。读不到/坏 JSON 不抛:返回 error 文本,
627
- * 调用方(工具卡片)把"还没装 / 装坏了"讲清楚,action=refresh 就能修。
382
+ * 读本地资源 manifest(默认内置 flat;指定 version 时到历史版本目录里找)。
383
+ * 读不到/坏 JSON 不抛:返回 error 文本,调用方把「装坏了」讲清楚。
628
384
  */
629
385
  export function readLocalManifest(env = process.env, version) {
630
386
  const info = assetsRootInfo(env);
631
- const versions = listInstalledVersions(env);
632
387
  const wanted = (version ?? "").trim();
633
- const picked = wanted === ""
634
- ? versions[0]
635
- : versions.find((item) => item.version === wanted) ?? null;
388
+ const flat = readFlatManifest(info.root);
389
+ const flatMatches = flat.manifest !== null && (wanted === "" || flat.manifest.version === wanted);
390
+ if (flatMatches) {
391
+ return {
392
+ manifest: flat.manifest,
393
+ install: null,
394
+ root: info.root,
395
+ version: flat.manifest?.version ?? "",
396
+ versionDir: info.root,
397
+ error: "",
398
+ bundled: true,
399
+ };
400
+ }
401
+ if (flat.present && wanted === "" && flat.manifest === null) {
402
+ return {
403
+ manifest: null,
404
+ install: null,
405
+ root: info.root,
406
+ version: "",
407
+ versionDir: info.root,
408
+ error: flat.error + "。" + ASSETS_REFRESH_HINT,
409
+ bundled: true,
410
+ };
411
+ }
412
+ const versions = listInstalledVersions(env, info.root);
413
+ const picked = wanted === "" ? versions[0] : versions.find((item) => item.version === wanted) ?? null;
636
414
  if (picked === undefined || picked === null) {
637
415
  return {
638
416
  manifest: null,
@@ -640,7 +418,8 @@ export function readLocalManifest(env = process.env, version) {
640
418
  root: info.root,
641
419
  version: "",
642
420
  versionDir: "",
643
- error: wanted === "" ? "本地还没装资源包(先 action=refresh 下载)" : "本地没有版本 " + wanted + "(action=list 看已装版本)",
421
+ error: wanted === "" ? "找不到资源:" + info.root + " 下没有 manifest.json(" + ASSETS_REFRESH_HINT + ")" : "本地没有资源版本 " + wanted + "(action=list 看已装版本)",
422
+ bundled: false,
644
423
  };
645
424
  }
646
425
  const manifestPath = path.join(picked.dir, ASSETS_MANIFEST_FILE);
@@ -655,7 +434,8 @@ export function readLocalManifest(env = process.env, version) {
655
434
  root: info.root,
656
435
  version: picked.version,
657
436
  versionDir: picked.dir,
658
- error: "本地 manifest 读不了(" + manifestPath + "):" + errText(error) + ";action=refresh 可以重装。",
437
+ error: "资源 manifest 读不了(" + manifestPath + "):" + errText(error) + "。" + ASSETS_REFRESH_HINT,
438
+ bundled: picked.bundled,
659
439
  };
660
440
  }
661
441
  const parsed = parseManifest(text);
@@ -666,124 +446,70 @@ export function readLocalManifest(env = process.env, version) {
666
446
  root: info.root,
667
447
  version: picked.version,
668
448
  versionDir: picked.dir,
669
- error: "本地 manifest 坏了(" + manifestPath + "):" + parsed.error + ";action=refresh 可以重装。",
449
+ error: "资源 manifest 坏了(" + manifestPath + "):" + parsed.error + "。" + ASSETS_REFRESH_HINT,
450
+ bundled: picked.bundled,
670
451
  };
671
452
  }
672
453
  return {
673
454
  manifest: parsed.manifest,
674
- install: readInstallRecord(picked.dir),
455
+ install: picked.bundled ? null : readInstallRecord(picked.dir),
675
456
  root: info.root,
676
457
  version: picked.version,
677
458
  versionDir: picked.dir,
678
459
  error: "",
460
+ bundled: picked.bundled,
679
461
  };
680
462
  }
681
463
  /**
682
- * 设备事实的就绪保证:本地有缓存就直接用,没有就自动装一次(首次使用要联网一次)。
464
+ * 设备事实的就绪保证:读内置 assets/manifest.json,确认 device/f1/chips.json 真在磁盘上。
683
465
  *
684
466
  * 三条硬约定:
685
- * · 缓存命中不发网络请求(工具调用不该为了"确认一下"去联网);
686
- * · 装不上返回 ok:false + status="missing",message 里一定有 ASSETS_REFRESH_HINT——
687
- * 上层把它原样贴进报告,绝不静默失败、也绝不退回内置表(内置表已经删了);
688
- * · 只有真装完并且 device/f1/chips.json 确实落盘才算 ok(profile 不对/包不全都算失败)。
467
+ * · 不发网络请求(资源随包发布,没有任何需要下载的东西);
468
+ * · 缺文件返回 ok:false + status="missing",message 里一定有 ASSETS_REFRESH_HINT;
469
+ * · 只有 manifest 可读并且 device/f1/chips.json 确实落盘才算 ok。
689
470
  */
690
471
  export async function ensureAssets(options = {}) {
691
472
  const env = options.env ?? process.env;
692
473
  const normalizedProfile = normalizeProfile(options.profile) ?? "core";
693
- const root = assetsRootInfo(env).root;
694
- const empty = (status, message, extra = {}) => ({
695
- ok: false,
696
- status,
697
- root,
698
- version: "",
699
- versionDir: "",
700
- filePath: "",
474
+ const state = readLocalManifest(env);
475
+ const base = {
476
+ root: state.root === "" ? assetsRootInfo(env).root : state.root,
477
+ version: state.version,
478
+ versionDir: state.versionDir,
701
479
  profile: normalizedProfile,
702
- source: "",
480
+ source: state.bundled ? "bundled" : "cache",
703
481
  attempts: [],
704
- message,
705
- ...extra,
706
- });
707
- const cached = readLocalManifest(env);
708
- const cachedFile = cached.versionDir === "" ? "" : path.join(cached.versionDir, ASSETS_DEVICE_FACTS_FILE);
709
- if (cached.manifest !== null && cachedFile !== "" && fs.existsSync(cachedFile)) {
482
+ };
483
+ if (state.manifest === null) {
710
484
  return {
711
- ok: true,
712
- status: "cache",
713
- root: cached.root,
714
- version: cached.version,
715
- versionDir: cached.versionDir,
716
- filePath: cachedFile,
717
- profile: normalizedProfile,
718
- source: "cache",
719
- attempts: [],
720
- message: "设备事实来自本地资源包缓存:版本 " + cached.version + "(" + cachedFile + ")",
485
+ ok: false,
486
+ status: "missing",
487
+ ...base,
488
+ filePath: "",
489
+ message: "读不到内置资源:" + (state.error === "" ? "assets/manifest.json 不存在" : state.error) + "。" + ASSETS_REFRESH_HINT + "。",
721
490
  };
722
491
  }
723
- const cacheNote = cached.manifest !== null
724
- ? "本地版本 " + cached.version + " 里没有 " + ASSETS_DEVICE_FACTS_FILE + "(这一版资源包不全);"
725
- : cached.error !== ""
726
- ? "本地缓存:" + cached.error + ";"
727
- : "本地还没有资源包缓存;";
728
- const sources = resolveSources(options.source);
729
- if (sources.length === 0) {
730
- return empty("missing", cacheNote + "没有可用的资源源(source=" + String(options.source ?? "") + ");" + ASSETS_REFRESH_HINT + "。");
731
- }
732
- const manifestTimeout = options.timeoutMs ?? 20_000;
733
- const fileTimeout = options.timeoutMs ?? 60_000;
734
- const fetched = await fetchManifest({
735
- sources,
736
- fetchImpl: options.fetchImpl,
737
- timeoutMs: manifestTimeout,
738
- signal: options.signal,
739
- });
740
- if (!fetched.ok || fetched.manifest === null || fetched.source === null) {
741
- return empty("missing", cacheNote + "拉 manifest.json 失败:" + fetched.error + ";" + ASSETS_REFRESH_HINT + "。", {
742
- attempts: fetched.attempts,
743
- });
744
- }
745
- const manifestSource = fetched.source;
746
- const ordered = [manifestSource, ...sources.filter((source) => source.id !== manifestSource.id)];
747
- const install = await verifyAndInstall({
748
- manifest: fetched.manifest,
749
- manifestText: fetched.text,
750
- profile: normalizedProfile,
751
- sources: ordered,
752
- env,
753
- fetchImpl: options.fetchImpl,
754
- timeoutMs: fileTimeout,
755
- signal: options.signal,
756
- });
757
- if (!install.ok) {
758
- return empty("missing", cacheNote + "资源包" + fetched.manifest.version + "(源 " + manifestSource.id + ")没装成功:" + install.message + ";" + ASSETS_REFRESH_HINT + "。", {
759
- version: install.version,
760
- versionDir: install.versionDir,
761
- source: install.source,
762
- attempts: [...fetched.attempts, ...install.attempts],
763
- });
764
- }
765
- const installedFile = path.join(install.versionDir, ASSETS_DEVICE_FACTS_FILE);
766
- const present = fs.existsSync(installedFile);
767
- if (!present) {
768
- return empty("missing", "资源包 " + install.version + " 装好了(profile=" + normalizedProfile + "," + String(install.fileCount) + " 个文件),但里面没有 " + ASSETS_DEVICE_FACTS_FILE + ":这一版资源包不全;" + ASSETS_REFRESH_HINT + "。", { version: install.version, versionDir: install.versionDir, source: install.source, attempts: [...fetched.attempts, ...install.attempts] });
492
+ const filePath = path.join(state.versionDir, ASSETS_DEVICE_FACTS_FILE);
493
+ if (!fs.existsSync(filePath)) {
494
+ return {
495
+ ok: false,
496
+ status: "missing",
497
+ ...base,
498
+ filePath: "",
499
+ message: "内置资源 " + state.version + " 里没有 " + ASSETS_DEVICE_FACTS_FILE + "(profile=" + normalizedProfile +
500
+ ",资源目录 " + state.versionDir + "):插件安装不完整。" + ASSETS_REFRESH_HINT + "。",
501
+ };
769
502
  }
770
503
  return {
771
504
  ok: true,
772
- status: "refreshed",
773
- root: install.root,
774
- version: install.version,
775
- versionDir: install.versionDir,
776
- filePath: installedFile,
777
- profile: normalizedProfile,
778
- source: install.source === manifestSource.id ? install.source : manifestSource.id + "+" + install.source,
779
- attempts: [...fetched.attempts, ...install.attempts],
780
- message: "首次使用:已自动装好资源包 " + install.version + "(profile=" + normalizedProfile + "," +
781
- String(install.fileCount) + " 个文件 / " + String(install.totalBytes) + " 字节,源 " + manifestSource.id +
782
- "),设备事实来自 " + installedFile,
505
+ status: "cache",
506
+ ...base,
507
+ filePath,
508
+ message: "设备事实来自" + (state.bundled ? "插件内置资源" : "本地资源缓存") + " " + state.version + "(" + filePath + ")",
783
509
  };
784
510
  }
785
511
  /**
786
- * 把"profile + 相对路径"解析成本地文件:要判断三件事——装了没、这份文件属不属于该 profile、
512
+ * 把"profile + 相对路径"解析成本地文件:要判断三件事——资源在不在、这份文件属不属于该 profile、
787
513
  * 本地文件在不在。三者都过才返回路径,否则给一句能照着修的话。
788
514
  */
789
515
  export function resolveAssetFile(profile, relPath, env = process.env) {
@@ -796,26 +522,26 @@ export function resolveAssetFile(profile, relPath, env = process.env) {
796
522
  return empty("路径不合法:" + String(relPath) + "(必须是资源根内的相对路径)");
797
523
  const state = readLocalManifest(env);
798
524
  if (state.manifest === null)
799
- return empty(state.error === "" ? "本地还没装资源包" : state.error);
525
+ return empty(state.error === "" ? "找不到内置资源" : state.error);
800
526
  const entry = state.manifest.files.find((file) => file.path === normalized);
801
527
  if (entry === undefined)
802
- return empty("资源包里没有这个文件:" + normalized + "(action=list 看这一版有哪些文件)");
528
+ return empty("资源清单里没有这个文件:" + normalized + "(action=list 看这一版有哪些文件)");
803
529
  const allowed = profileFiles(state.manifest, normalizedProfile).some((file) => file.path === normalized);
804
530
  if (!allowed) {
805
- return empty("文件 " + normalized + " 不在 profile=" + normalizedProfile + " 里(它属于 profile=" + entry.profile + ");用 profile=full 装一次,或改问 core 里的文件。");
531
+ return empty("文件 " + normalized + " 不在 profile=" + normalizedProfile + " 里(它属于 profile=" + entry.profile + ");用 profile=full 查一次。");
806
532
  }
807
533
  const localPath = path.join(state.versionDir, normalized);
808
534
  try {
809
535
  const stat = fs.statSync(localPath);
810
536
  if (!stat.isFile())
811
- return empty("本地路径不是文件:" + localPath + ";action=refresh 可以重装。");
537
+ return empty("本地路径不是文件:" + localPath + "。" + ASSETS_REFRESH_HINT);
812
538
  return { ok: true, path: localPath, version: state.version, bytes: stat.size, error: "" };
813
539
  }
814
540
  catch {
815
- return empty("本地缺这个文件:" + localPath + "(action=refresh 可以重装 " + state.version + ")");
541
+ return empty("本地缺这个文件:" + localPath + "(资源 " + state.version + ")。" + ASSETS_REFRESH_HINT);
816
542
  }
817
543
  }
818
- /** 逐文件 sha256 复核本地安装。缺文件算 missing,哈希/大小不对算 changed。 */
544
+ /** 逐文件 sha256 复核本地资源。缺文件算 missing,哈希/大小不对算 changed。 */
819
545
  export function verifyInstalled(request = {}) {
820
546
  const env = request.env ?? process.env;
821
547
  const profile = normalizeProfile(request.profile);
@@ -844,7 +570,7 @@ export function verifyInstalled(request = {}) {
844
570
  }
845
571
  catch {
846
572
  bad += 1;
847
- common.files.push({ path: target.path, bytes: 0, sha256: "", status: "missing", detail: "本地缺这个文件(action=refresh 修复)" });
573
+ common.files.push({ path: target.path, bytes: 0, sha256: "", status: "missing", detail: "本地缺这个文件(重装插件修复)" });
848
574
  continue;
849
575
  }
850
576
  const actual = sha256Hex(buffer);
@@ -867,16 +593,26 @@ export function verifyInstalled(request = {}) {
867
593
  ...common,
868
594
  ok: bad === 0 && common.files.length > 0,
869
595
  message: "校验 " + state.version + "(profile=" + profile + "):" + String(common.files.length) + " 个文件里 " +
870
- String(bad) + " 个有问题" + (bad === 0 ? ",全部对得上。" : "。action=refresh 重装这一版即可。"),
596
+ String(bad) + " 个有问题" + (bad === 0 ? ",全部对得上。" : "。重装插件即可恢复(内置资源不能被 refresh 改写)。"),
871
597
  };
872
598
  }
873
599
  /**
874
- * 只留当前与上一版(keep=2),其它版本目录删掉;顺手清掉 .tmp-* 残留(下载中断留下的)。
600
+ * 只清 DSH_STM32_ASSETS 下 .tmp-* 与超出 keep 的历史版本目录;内置 flat 根永不删。
875
601
  * 版本按版本号排序,不按目录名,避免 "2026.9.1" 排到 "2026.10.30" 后面。
876
602
  */
877
603
  export function pruneOldVersions(env = process.env, keep = 2, root) {
878
- const base = root !== undefined && root !== "" ? root : localAssetsRoot(env);
879
- const versions = listInstalledVersions(env, base);
604
+ const info = assetsRootInfo(env);
605
+ const base = root !== undefined && root !== "" ? root : info.root;
606
+ const bundledRoot = path.resolve(bundledAssetsRoot());
607
+ if (path.resolve(base) === bundledRoot) {
608
+ return {
609
+ removed: [],
610
+ kept: [],
611
+ reclaimedBytes: 0,
612
+ message: "资源随插件内置(" + base + "),没有可清理的历史版本;内置文件不会被删除。",
613
+ };
614
+ }
615
+ const versions = listInstalledVersions(env, base).filter((item) => !item.bundled);
880
616
  const keepCount = Math.max(1, Math.floor(keep));
881
617
  const removed = [];
882
618
  const kept = [];
@@ -896,7 +632,6 @@ export function pruneOldVersions(env = process.env, keep = 2, root) {
896
632
  // 删不掉的版本保留在磁盘上,但也不谎报 removed。
897
633
  }
898
634
  });
899
- // 半成品(.tmp-*)一律清:它们不参与安装判断,只会占地方。
900
635
  try {
901
636
  for (const entry of fs.readdirSync(base, { withFileTypes: true })) {
902
637
  if (!entry.isDirectory() || !entry.name.includes(".tmp-"))
@@ -916,7 +651,7 @@ export function pruneOldVersions(env = process.env, keep = 2, root) {
916
651
  // 根目录不存在:没什么可清的。
917
652
  }
918
653
  const message = versions.length === 0
919
- ? "本地没有装过资源包,没什么可清理的。"
654
+ ? "DSH_STM32_ASSETS 下没有历史版本,没什么可清理的(内置资源不受影响)。"
920
655
  : removed.length === 0
921
656
  ? "保留 " + kept.join("、") + "(不超过 " + String(keepCount) + " 个版本),没有旧版本要删。"
922
657
  : "删掉 " + String(removed.length) + " 个旧版本(" + removed.join("、") + "),回收 " + String(reclaimedBytes) + " 字节;保留 " + kept.join("、") + "。";