dsh-stm32 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -21
- package/README_EN.md +59 -21
- package/docs/development-notes.md +374 -3
- package/docs/reading-guide.md +87 -66
- package/lib/data/chips.js +38 -51
- package/lib/data/cmsis-sources.js +27 -1
- package/lib/data/device-facts.js +201 -0
- package/lib/data/stm32f1.js +94 -150
- package/lib/data/svd.js +627 -0
- package/lib/engine/assets.js +924 -0
- package/lib/engine/breakpoints.js +242 -0
- package/lib/engine/debug-session.js +153 -5
- package/lib/engine/debug.js +75 -41
- package/lib/engine/doctor.js +2 -2
- package/lib/engine/flash.js +31 -59
- package/lib/engine/ioc-plan.js +5 -5
- package/lib/engine/probe-error.js +212 -0
- package/lib/engine/probe-session.js +311 -0
- package/lib/engine/register-template.js +32 -8
- package/lib/engine/regs.js +2 -0
- package/lib/engine/rtt.js +600 -0
- package/lib/index.js +8 -0
- package/lib/tools/assets.js +341 -0
- package/lib/tools/cache.js +8 -0
- package/lib/tools/debug-session.js +40 -5
- package/lib/tools/debug.js +41 -11
- package/lib/tools/doctor.js +11 -0
- package/lib/tools/flash.js +15 -6
- package/lib/tools/generate.js +3 -0
- package/lib/tools/ioc-apply.js +2 -0
- package/lib/tools/ioc-inspect.js +2 -0
- package/lib/tools/ioc-plan.js +3 -0
- package/lib/tools/project-create.js +24 -0
- package/lib/tools/regs.js +453 -61
- package/lib/tools/route-plan.js +3 -0
- package/lib/tools/rtt.js +347 -0
- package/package.json +1 -1
- package/templates/register/CMakeLists.txt +7 -1
- package/templates/register/Core/Inc/rtt.h +103 -0
- package/templates/register/Core/Src/main.c +25 -0
- package/templates/register/Core/Src/rtt.c +297 -0
- package/templates/scaffold/RTT.md +86 -0
- package/templates/scaffold/cmake/user/CMakeLists.txt +7 -0
- package/lib/data/f1-ram.generated.js +0 -34
|
@@ -0,0 +1,924 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 资源包(dsh-stm32-assets)下载器:manifest → 逐文件 sha256 → 本地缓存。
|
|
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,装坏/装半截宁可整次拒绝,也不给上层一份"看起来装好了"的目录。
|
|
8
|
+
*
|
|
9
|
+
* 关键约定:
|
|
10
|
+
* · 多源:GitHub raw → jsDelivr → GitCode,manifest 与文件各自逐源回退(写死一个源就是押注线路);
|
|
11
|
+
* · 失败不抛:下载/校验失败都变成 ok:false + 人话原因,工具卡片照常渲染;
|
|
12
|
+
* · 没有内置表可退:装不上就等于没有设备事实,所以 ensureAssets 的报错必须说清
|
|
13
|
+
* "缺的是什么、先跑 stm32_assets refresh 或检查网络";
|
|
14
|
+
* · 半成品必须删干净:先下到 <version>.tmp-<pid>-<seq>/,全部哈希通过才搬进 <version>/,
|
|
15
|
+
* 中途失败只删临时目录,旧版本一个字节都不动。
|
|
16
|
+
*
|
|
17
|
+
* 零运行时依赖:只用 node:fs / node:path / node:crypto / node:os 与全局 fetch(Node 18+),
|
|
18
|
+
* 测试通过 fetchImpl 注入假 fetch,一次网络都不发。
|
|
19
|
+
*/
|
|
20
|
+
import { createHash } from "node:crypto";
|
|
21
|
+
import fs from "node:fs";
|
|
22
|
+
import os from "node:os";
|
|
23
|
+
import path from "node:path";
|
|
24
|
+
export const ASSETS_MANIFEST_FILE = "manifest.json";
|
|
25
|
+
export const ASSETS_INSTALL_FILE = "install.json";
|
|
26
|
+
/** 设备事实在资源包里的相对路径(插件唯一的芯片事实来源)。 */
|
|
27
|
+
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
|
+
];
|
|
51
|
+
/** 只给 core / full;空串按 core 处理,别的值返回 null(由调用方给可读报错,不瞎猜)。 */
|
|
52
|
+
export function normalizeProfile(value) {
|
|
53
|
+
const text = (value ?? "core").trim().toLowerCase();
|
|
54
|
+
if (text === "")
|
|
55
|
+
return "core";
|
|
56
|
+
if (text === "core" || text === "full")
|
|
57
|
+
return text;
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
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 }];
|
|
74
|
+
}
|
|
75
|
+
function expandHome(value, env) {
|
|
76
|
+
if (value === "~" || value.startsWith("~/") || value.startsWith("~\\")) {
|
|
77
|
+
const home = (env.USERPROFILE ?? env.HOME ?? "").trim();
|
|
78
|
+
if (home !== "")
|
|
79
|
+
return path.join(home, value.slice(1));
|
|
80
|
+
}
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
/** 资源根目录:DSH_STM32_ASSETS 覆盖,默认 ~/.dsh-stm32/assets(每个版本一个子目录)。 */
|
|
84
|
+
export function assetsRootInfo(env = process.env) {
|
|
85
|
+
const override = (env.DSH_STM32_ASSETS ?? "").trim();
|
|
86
|
+
if (override !== "") {
|
|
87
|
+
return { root: path.resolve(expandHome(override, env)), origin: "DSH_STM32_ASSETS" };
|
|
88
|
+
}
|
|
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: "用户主目录" };
|
|
97
|
+
}
|
|
98
|
+
/** 资源根(不含版本号)。测试里用 DSH_STM32_ASSETS 指到临时目录,绝不碰真实 home。 */
|
|
99
|
+
export function localAssetsRoot(env = process.env) {
|
|
100
|
+
return assetsRootInfo(env).root;
|
|
101
|
+
}
|
|
102
|
+
/** 某个版本的安装目录:<root>/<version>/。 */
|
|
103
|
+
export function versionDir(version, env = process.env) {
|
|
104
|
+
return path.join(localAssetsRoot(env), version);
|
|
105
|
+
}
|
|
106
|
+
const SHA256_RE = /^[0-9a-f]{64}$/u;
|
|
107
|
+
function isRecord(value) {
|
|
108
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
109
|
+
}
|
|
110
|
+
export function sha256Hex(buffer) {
|
|
111
|
+
return createHash("sha256").update(buffer).digest("hex");
|
|
112
|
+
}
|
|
113
|
+
export function errText(error) {
|
|
114
|
+
if (error instanceof Error) {
|
|
115
|
+
const cause = error.cause;
|
|
116
|
+
if (cause !== undefined && cause !== null && cause !== "") {
|
|
117
|
+
const causeText = cause instanceof Error ? cause.message : String(cause);
|
|
118
|
+
return error.message + "(" + causeText + ")";
|
|
119
|
+
}
|
|
120
|
+
return error.message;
|
|
121
|
+
}
|
|
122
|
+
return String(error);
|
|
123
|
+
}
|
|
124
|
+
function shortHash(value) {
|
|
125
|
+
return value.length > 16 ? value.slice(0, 16) + "…" : value;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* 解析并校验 manifest。校验不过返回 error(调用方换源),不抛异常。
|
|
129
|
+
* 为什么严:manifest 是"装什么、装成后该是什么"的唯一事实来源,少一个 sha256 就等于放弃校验。
|
|
130
|
+
*/
|
|
131
|
+
export function parseManifest(text) {
|
|
132
|
+
let parsed;
|
|
133
|
+
try {
|
|
134
|
+
parsed = JSON.parse(text);
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
return { manifest: null, error: "manifest.json 不是合法 JSON:" + errText(error) };
|
|
138
|
+
}
|
|
139
|
+
if (!isRecord(parsed))
|
|
140
|
+
return { manifest: null, error: "manifest.json 顶层不是对象" };
|
|
141
|
+
const version = parsed["version"];
|
|
142
|
+
if (typeof version !== "string" || version.trim() === "") {
|
|
143
|
+
return {
|
|
144
|
+
manifest: null,
|
|
145
|
+
error: "manifest.json 缺 version(没有版本号就不知道该往哪个目录装)。" +
|
|
146
|
+
"如果资源仓库里还是老的 v1 manifest(只有 plugin/cubeMx 路径、没有 version/schema/profiles)," +
|
|
147
|
+
"先把带 version 与 profiles 的 schema 2 manifest 推上去再刷新。",
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
const rawFiles = parsed["files"];
|
|
151
|
+
if (!Array.isArray(rawFiles))
|
|
152
|
+
return { manifest: null, error: "manifest.json 缺 files 数组" };
|
|
153
|
+
const files = [];
|
|
154
|
+
const seen = new Set();
|
|
155
|
+
for (let index = 0; index < rawFiles.length; index += 1) {
|
|
156
|
+
const item = rawFiles[index];
|
|
157
|
+
const where = "files[" + String(index) + "]";
|
|
158
|
+
if (!isRecord(item))
|
|
159
|
+
return { manifest: null, error: where + " 不是对象" };
|
|
160
|
+
const relPath = item["path"];
|
|
161
|
+
if (typeof relPath !== "string" || relPath.trim() === "") {
|
|
162
|
+
return { manifest: null, error: where + " 缺 path" };
|
|
163
|
+
}
|
|
164
|
+
const normalized = normalizeAssetPath(relPath);
|
|
165
|
+
if (normalized === null)
|
|
166
|
+
return { manifest: null, error: where + " 的 path 不合法(必须是资源根内的相对路径):" + relPath };
|
|
167
|
+
if (seen.has(normalized))
|
|
168
|
+
return { manifest: null, error: "manifest.json 里 path 重复:" + normalized };
|
|
169
|
+
seen.add(normalized);
|
|
170
|
+
const sha256 = item["sha256"];
|
|
171
|
+
if (typeof sha256 !== "string" || !SHA256_RE.test(sha256.toLowerCase())) {
|
|
172
|
+
return { manifest: null, error: where + "(" + normalized + ")缺 sha256 或不是 64 位十六进制;没有哈希就无法校验,拒绝安装" };
|
|
173
|
+
}
|
|
174
|
+
const bytes = item["bytes"];
|
|
175
|
+
if (typeof bytes !== "number" || !Number.isFinite(bytes) || bytes < 0) {
|
|
176
|
+
return { manifest: null, error: where + "(" + normalized + ")的 bytes 不是非负数" };
|
|
177
|
+
}
|
|
178
|
+
const profile = typeof item["profile"] === "string" && item["profile"] !== "" ? item["profile"] : "core";
|
|
179
|
+
const source = typeof item["source"] === "string" ? item["source"] : "";
|
|
180
|
+
files.push({ path: normalized, bytes, sha256: sha256.toLowerCase(), source, profile });
|
|
181
|
+
}
|
|
182
|
+
const profiles = {};
|
|
183
|
+
const rawProfiles = parsed["profiles"];
|
|
184
|
+
if (isRecord(rawProfiles)) {
|
|
185
|
+
for (const [key, value] of Object.entries(rawProfiles)) {
|
|
186
|
+
if (!Array.isArray(value))
|
|
187
|
+
return { manifest: null, error: "manifest.json 的 profiles." + key + " 不是数组" };
|
|
188
|
+
const globs = [];
|
|
189
|
+
for (const glob of value) {
|
|
190
|
+
if (typeof glob !== "string" || glob.trim() === "") {
|
|
191
|
+
return { manifest: null, error: "manifest.json 的 profiles." + key + " 里有非字符串 glob" };
|
|
192
|
+
}
|
|
193
|
+
globs.push(glob);
|
|
194
|
+
}
|
|
195
|
+
profiles[key] = globs;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const skipped = Array.isArray(parsed["skipped"]) ? parsed["skipped"].filter((item) => typeof item === "string") : [];
|
|
199
|
+
const name = typeof parsed["name"] === "string" ? parsed["name"] : "dsh-stm32-assets";
|
|
200
|
+
const schema = typeof parsed["schema"] === "number" ? parsed["schema"] : 1;
|
|
201
|
+
return { manifest: { ...parsed, name, version, schema, profiles, files, skipped }, error: "" };
|
|
202
|
+
}
|
|
203
|
+
/** 相对路径规整:反斜杠转正斜杠、拒绝绝对路径/盘符/.. —— 防止 manifest 把文件写到资源根以外。 */
|
|
204
|
+
export function normalizeAssetPath(raw) {
|
|
205
|
+
const text = raw.split("\\").join("/").trim();
|
|
206
|
+
if (text === "" || text.startsWith("/") || /^[A-Za-z]:/u.test(text))
|
|
207
|
+
return null;
|
|
208
|
+
const parts = text.split("/").filter((part) => part !== "" && part !== ".");
|
|
209
|
+
if (parts.length === 0)
|
|
210
|
+
return null;
|
|
211
|
+
if (parts.some((part) => part === ".."))
|
|
212
|
+
return null;
|
|
213
|
+
return parts.join("/");
|
|
214
|
+
}
|
|
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
|
+
/** glob → 正则:** 跨目录,* 不跨目录,? 单字符。manifest 的 profiles 就靠它筛文件。 */
|
|
223
|
+
function globToRegExp(pattern) {
|
|
224
|
+
let out = "^";
|
|
225
|
+
let index = 0;
|
|
226
|
+
while (index < pattern.length) {
|
|
227
|
+
const ch = pattern.charAt(index);
|
|
228
|
+
if (ch === "*") {
|
|
229
|
+
if (pattern.charAt(index + 1) === "*") {
|
|
230
|
+
const followedBySlash = pattern.charAt(index + 2) === "/";
|
|
231
|
+
out += followedBySlash ? "(?:[^/]+/)*" : ".*";
|
|
232
|
+
index += followedBySlash ? 3 : 2;
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
out += "[^/]*";
|
|
236
|
+
index += 1;
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (ch === "?") {
|
|
240
|
+
out += "[^/]";
|
|
241
|
+
index += 1;
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
out += ch.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
245
|
+
index += 1;
|
|
246
|
+
}
|
|
247
|
+
return new RegExp(out + "$", "u");
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* profile 里的文件。优先用 manifest.profiles 的 glob(v2 的标准做法);
|
|
251
|
+
* 老 manifest 没有 profiles 时退回每条的 profile 字段(full 包含 core)。
|
|
252
|
+
*/
|
|
253
|
+
export function profileFiles(manifest, profile) {
|
|
254
|
+
const globs = manifest.profiles[profile];
|
|
255
|
+
if (globs !== undefined) {
|
|
256
|
+
const patterns = globs.map((glob) => globToRegExp(glob));
|
|
257
|
+
return manifest.files.filter((file) => patterns.some((pattern) => pattern.test(file.path)));
|
|
258
|
+
}
|
|
259
|
+
return manifest.files.filter((file) => file.profile === profile || (profile === "full" && file.profile === "core"));
|
|
260
|
+
}
|
|
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
|
+
}
|
|
355
|
+
function scanDirStats(dir, skipNames = []) {
|
|
356
|
+
let files = 0;
|
|
357
|
+
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;
|
|
378
|
+
try {
|
|
379
|
+
bytes += fs.statSync(full).size;
|
|
380
|
+
}
|
|
381
|
+
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 + "(必须是资源根内的相对路径)。什么都没装。");
|
|
431
|
+
}
|
|
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
|
+
});
|
|
460
|
+
}
|
|
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
|
+
});
|
|
467
|
+
}
|
|
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);
|
|
485
|
+
}
|
|
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
|
+
}
|
|
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
|
+
}
|
|
528
|
+
}
|
|
529
|
+
function readInstallRecord(dir) {
|
|
530
|
+
try {
|
|
531
|
+
const raw = fs.readFileSync(path.join(dir, ASSETS_INSTALL_FILE), "utf8");
|
|
532
|
+
const parsed = JSON.parse(raw);
|
|
533
|
+
if (!isRecord(parsed))
|
|
534
|
+
return null;
|
|
535
|
+
const version = parsed["version"];
|
|
536
|
+
if (typeof version !== "string" || version === "")
|
|
537
|
+
return null;
|
|
538
|
+
const profiles = Array.isArray(parsed["profiles"])
|
|
539
|
+
? parsed["profiles"].filter((item) => typeof item === "string")
|
|
540
|
+
: [];
|
|
541
|
+
return {
|
|
542
|
+
version,
|
|
543
|
+
profiles,
|
|
544
|
+
installedAt: typeof parsed["installedAt"] === "string" ? parsed["installedAt"] : "",
|
|
545
|
+
source: typeof parsed["source"] === "string" ? parsed["source"] : "",
|
|
546
|
+
schema: typeof parsed["schema"] === "number" ? parsed["schema"] : 0,
|
|
547
|
+
fileCount: typeof parsed["fileCount"] === "number" ? parsed["fileCount"] : 0,
|
|
548
|
+
totalBytes: typeof parsed["totalBytes"] === "number" ? parsed["totalBytes"] : 0,
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
catch {
|
|
552
|
+
return null;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
/** 版本比较:按数字段比(2026.10.30-1 > 2026.9.1),非数字段按字典序。 */
|
|
556
|
+
export function compareVersions(a, b) {
|
|
557
|
+
const tokenize = (value) => value.match(/\d+|[A-Za-z]+/gu) ?? [];
|
|
558
|
+
const left = tokenize(a);
|
|
559
|
+
const right = tokenize(b);
|
|
560
|
+
const length = Math.max(left.length, right.length);
|
|
561
|
+
for (let index = 0; index < length; index += 1) {
|
|
562
|
+
const l = left[index];
|
|
563
|
+
const r = right[index];
|
|
564
|
+
if (l === undefined)
|
|
565
|
+
return r === undefined ? 0 : -1;
|
|
566
|
+
if (r === undefined)
|
|
567
|
+
return 1;
|
|
568
|
+
const ln = /^\d+$/u.test(l);
|
|
569
|
+
const rn = /^\d+$/u.test(r);
|
|
570
|
+
if (ln && rn) {
|
|
571
|
+
const diff = Number(l) - Number(r);
|
|
572
|
+
if (diff !== 0)
|
|
573
|
+
return diff;
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
if (l !== r)
|
|
577
|
+
return l < r ? -1 : 1;
|
|
578
|
+
}
|
|
579
|
+
return 0;
|
|
580
|
+
}
|
|
581
|
+
/** 扫描本地装过哪些版本(有新到旧)。只认带 install.json 的目录,所以半成品不会被当成"已安装"。 */
|
|
582
|
+
export function listInstalledVersions(env = process.env, root) {
|
|
583
|
+
const base = root !== undefined && root !== "" ? root : localAssetsRoot(env);
|
|
584
|
+
let entries;
|
|
585
|
+
try {
|
|
586
|
+
entries = fs.readdirSync(base, { withFileTypes: true });
|
|
587
|
+
}
|
|
588
|
+
catch {
|
|
589
|
+
return [];
|
|
590
|
+
}
|
|
591
|
+
const found = [];
|
|
592
|
+
for (const entry of entries) {
|
|
593
|
+
if (!entry.isDirectory())
|
|
594
|
+
continue;
|
|
595
|
+
if (entry.name.startsWith("."))
|
|
596
|
+
continue;
|
|
597
|
+
if (entry.name.includes(".tmp-"))
|
|
598
|
+
continue;
|
|
599
|
+
const dir = path.join(base, entry.name);
|
|
600
|
+
const record = readInstallRecord(dir);
|
|
601
|
+
if (record === null)
|
|
602
|
+
continue;
|
|
603
|
+
const stats = scanDirStats(dir, [ASSETS_MANIFEST_FILE, ASSETS_INSTALL_FILE]);
|
|
604
|
+
found.push({
|
|
605
|
+
version: record.version,
|
|
606
|
+
dir,
|
|
607
|
+
profiles: record.profiles.length > 0 ? record.profiles : ["core"],
|
|
608
|
+
installedAt: record.installedAt,
|
|
609
|
+
fileCount: stats.files,
|
|
610
|
+
totalBytes: stats.bytes,
|
|
611
|
+
current: false,
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
found.sort((left, right) => {
|
|
615
|
+
const byVersion = compareVersions(right.version, left.version);
|
|
616
|
+
if (byVersion !== 0)
|
|
617
|
+
return byVersion;
|
|
618
|
+
return right.installedAt.localeCompare(left.installedAt);
|
|
619
|
+
});
|
|
620
|
+
const first = found[0];
|
|
621
|
+
if (first !== undefined)
|
|
622
|
+
first.current = true;
|
|
623
|
+
return found;
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* 读本地装好的 manifest(默认最新一版)。读不到/坏 JSON 不抛:返回 error 文本,
|
|
627
|
+
* 调用方(工具卡片)把"还没装 / 装坏了"讲清楚,action=refresh 就能修。
|
|
628
|
+
*/
|
|
629
|
+
export function readLocalManifest(env = process.env, version) {
|
|
630
|
+
const info = assetsRootInfo(env);
|
|
631
|
+
const versions = listInstalledVersions(env);
|
|
632
|
+
const wanted = (version ?? "").trim();
|
|
633
|
+
const picked = wanted === ""
|
|
634
|
+
? versions[0]
|
|
635
|
+
: versions.find((item) => item.version === wanted) ?? null;
|
|
636
|
+
if (picked === undefined || picked === null) {
|
|
637
|
+
return {
|
|
638
|
+
manifest: null,
|
|
639
|
+
install: null,
|
|
640
|
+
root: info.root,
|
|
641
|
+
version: "",
|
|
642
|
+
versionDir: "",
|
|
643
|
+
error: wanted === "" ? "本地还没装资源包(先 action=refresh 下载)" : "本地没有版本 " + wanted + "(action=list 看已装版本)",
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
const manifestPath = path.join(picked.dir, ASSETS_MANIFEST_FILE);
|
|
647
|
+
let text;
|
|
648
|
+
try {
|
|
649
|
+
text = fs.readFileSync(manifestPath, "utf8");
|
|
650
|
+
}
|
|
651
|
+
catch (error) {
|
|
652
|
+
return {
|
|
653
|
+
manifest: null,
|
|
654
|
+
install: null,
|
|
655
|
+
root: info.root,
|
|
656
|
+
version: picked.version,
|
|
657
|
+
versionDir: picked.dir,
|
|
658
|
+
error: "本地 manifest 读不了(" + manifestPath + "):" + errText(error) + ";action=refresh 可以重装。",
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
const parsed = parseManifest(text);
|
|
662
|
+
if (parsed.manifest === null) {
|
|
663
|
+
return {
|
|
664
|
+
manifest: null,
|
|
665
|
+
install: null,
|
|
666
|
+
root: info.root,
|
|
667
|
+
version: picked.version,
|
|
668
|
+
versionDir: picked.dir,
|
|
669
|
+
error: "本地 manifest 坏了(" + manifestPath + "):" + parsed.error + ";action=refresh 可以重装。",
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
return {
|
|
673
|
+
manifest: parsed.manifest,
|
|
674
|
+
install: readInstallRecord(picked.dir),
|
|
675
|
+
root: info.root,
|
|
676
|
+
version: picked.version,
|
|
677
|
+
versionDir: picked.dir,
|
|
678
|
+
error: "",
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* 设备事实的就绪保证:本地有缓存就直接用,没有就自动装一次(首次使用要联网一次)。
|
|
683
|
+
*
|
|
684
|
+
* 三条硬约定:
|
|
685
|
+
* · 缓存命中不发网络请求(工具调用不该为了"确认一下"去联网);
|
|
686
|
+
* · 装不上返回 ok:false + status="missing",message 里一定有 ASSETS_REFRESH_HINT——
|
|
687
|
+
* 上层把它原样贴进报告,绝不静默失败、也绝不退回内置表(内置表已经删了);
|
|
688
|
+
* · 只有真装完并且 device/f1/chips.json 确实落盘才算 ok(profile 不对/包不全都算失败)。
|
|
689
|
+
*/
|
|
690
|
+
export async function ensureAssets(options = {}) {
|
|
691
|
+
const env = options.env ?? process.env;
|
|
692
|
+
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: "",
|
|
701
|
+
profile: normalizedProfile,
|
|
702
|
+
source: "",
|
|
703
|
+
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)) {
|
|
710
|
+
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 + ")",
|
|
721
|
+
};
|
|
722
|
+
}
|
|
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] });
|
|
769
|
+
}
|
|
770
|
+
return {
|
|
771
|
+
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,
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* 把"profile + 相对路径"解析成本地文件:要判断三件事——装了没、这份文件属不属于该 profile、
|
|
787
|
+
* 本地文件在不在。三者都过才返回路径,否则给一句能照着修的话。
|
|
788
|
+
*/
|
|
789
|
+
export function resolveAssetFile(profile, relPath, env = process.env) {
|
|
790
|
+
const empty = (error) => ({ ok: false, path: "", version: "", bytes: 0, error });
|
|
791
|
+
const normalizedProfile = normalizeProfile(profile);
|
|
792
|
+
if (normalizedProfile === null)
|
|
793
|
+
return empty("不认识的 profile:" + String(profile) + "(只有 core / full)");
|
|
794
|
+
const normalized = normalizeAssetPath(relPath);
|
|
795
|
+
if (normalized === null)
|
|
796
|
+
return empty("路径不合法:" + String(relPath) + "(必须是资源根内的相对路径)");
|
|
797
|
+
const state = readLocalManifest(env);
|
|
798
|
+
if (state.manifest === null)
|
|
799
|
+
return empty(state.error === "" ? "本地还没装资源包" : state.error);
|
|
800
|
+
const entry = state.manifest.files.find((file) => file.path === normalized);
|
|
801
|
+
if (entry === undefined)
|
|
802
|
+
return empty("资源包里没有这个文件:" + normalized + "(action=list 看这一版有哪些文件)");
|
|
803
|
+
const allowed = profileFiles(state.manifest, normalizedProfile).some((file) => file.path === normalized);
|
|
804
|
+
if (!allowed) {
|
|
805
|
+
return empty("文件 " + normalized + " 不在 profile=" + normalizedProfile + " 里(它属于 profile=" + entry.profile + ");用 profile=full 装一次,或改问 core 里的文件。");
|
|
806
|
+
}
|
|
807
|
+
const localPath = path.join(state.versionDir, normalized);
|
|
808
|
+
try {
|
|
809
|
+
const stat = fs.statSync(localPath);
|
|
810
|
+
if (!stat.isFile())
|
|
811
|
+
return empty("本地路径不是文件:" + localPath + ";action=refresh 可以重装。");
|
|
812
|
+
return { ok: true, path: localPath, version: state.version, bytes: stat.size, error: "" };
|
|
813
|
+
}
|
|
814
|
+
catch {
|
|
815
|
+
return empty("本地缺这个文件:" + localPath + "(action=refresh 可以重装 " + state.version + ")");
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
/** 逐文件 sha256 复核本地安装。缺文件算 missing,哈希/大小不对算 changed。 */
|
|
819
|
+
export function verifyInstalled(request = {}) {
|
|
820
|
+
const env = request.env ?? process.env;
|
|
821
|
+
const profile = normalizeProfile(request.profile);
|
|
822
|
+
const info = assetsRootInfo(env);
|
|
823
|
+
const state = readLocalManifest(env, request.version);
|
|
824
|
+
const common = {
|
|
825
|
+
root: info.root,
|
|
826
|
+
version: state.version,
|
|
827
|
+
versionDir: state.versionDir,
|
|
828
|
+
profile: profile ?? (request.profile ?? "").trim(),
|
|
829
|
+
files: [],
|
|
830
|
+
fileCount: 0,
|
|
831
|
+
totalBytes: 0,
|
|
832
|
+
};
|
|
833
|
+
if (profile === null)
|
|
834
|
+
return { ...common, ok: false, message: "不认识的 profile:" + String(request.profile) + "(只有 core / full)。" };
|
|
835
|
+
if (state.manifest === null)
|
|
836
|
+
return { ...common, ok: false, message: state.error + (state.error === "" ? "" : "。") };
|
|
837
|
+
const targets = profileFiles(state.manifest, profile);
|
|
838
|
+
let bad = 0;
|
|
839
|
+
for (const target of targets) {
|
|
840
|
+
const localPath = path.join(state.versionDir, target.path);
|
|
841
|
+
let buffer;
|
|
842
|
+
try {
|
|
843
|
+
buffer = fs.readFileSync(localPath);
|
|
844
|
+
}
|
|
845
|
+
catch {
|
|
846
|
+
bad += 1;
|
|
847
|
+
common.files.push({ path: target.path, bytes: 0, sha256: "", status: "missing", detail: "本地缺这个文件(action=refresh 修复)" });
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
const actual = sha256Hex(buffer);
|
|
851
|
+
if (actual !== target.sha256 || (target.bytes > 0 && buffer.byteLength !== target.bytes)) {
|
|
852
|
+
bad += 1;
|
|
853
|
+
common.files.push({
|
|
854
|
+
path: target.path,
|
|
855
|
+
bytes: buffer.byteLength,
|
|
856
|
+
sha256: actual,
|
|
857
|
+
status: "changed",
|
|
858
|
+
detail: "sha256 对不上(期望 " + shortHash(target.sha256) + ",实际 " + shortHash(actual) + ")",
|
|
859
|
+
});
|
|
860
|
+
continue;
|
|
861
|
+
}
|
|
862
|
+
common.files.push({ path: target.path, bytes: buffer.byteLength, sha256: actual, status: "ok", detail: "" });
|
|
863
|
+
common.totalBytes += buffer.byteLength;
|
|
864
|
+
}
|
|
865
|
+
common.fileCount = common.files.length;
|
|
866
|
+
return {
|
|
867
|
+
...common,
|
|
868
|
+
ok: bad === 0 && common.files.length > 0,
|
|
869
|
+
message: "校验 " + state.version + "(profile=" + profile + "):" + String(common.files.length) + " 个文件里 " +
|
|
870
|
+
String(bad) + " 个有问题" + (bad === 0 ? ",全部对得上。" : "。action=refresh 重装这一版即可。"),
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* 只留当前与上一版(keep=2),其它版本目录删掉;顺手清掉 .tmp-* 残留(下载中断留下的)。
|
|
875
|
+
* 版本按版本号排序,不按目录名,避免 "2026.9.1" 排到 "2026.10.30" 后面。
|
|
876
|
+
*/
|
|
877
|
+
export function pruneOldVersions(env = process.env, keep = 2, root) {
|
|
878
|
+
const base = root !== undefined && root !== "" ? root : localAssetsRoot(env);
|
|
879
|
+
const versions = listInstalledVersions(env, base);
|
|
880
|
+
const keepCount = Math.max(1, Math.floor(keep));
|
|
881
|
+
const removed = [];
|
|
882
|
+
const kept = [];
|
|
883
|
+
let reclaimedBytes = 0;
|
|
884
|
+
versions.forEach((item, index) => {
|
|
885
|
+
if (index < keepCount) {
|
|
886
|
+
kept.push(item.version);
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
const stats = scanDirStats(item.dir);
|
|
890
|
+
try {
|
|
891
|
+
fs.rmSync(item.dir, { recursive: true, force: true });
|
|
892
|
+
removed.push(item.version);
|
|
893
|
+
reclaimedBytes += stats.bytes;
|
|
894
|
+
}
|
|
895
|
+
catch {
|
|
896
|
+
// 删不掉的版本保留在磁盘上,但也不谎报 removed。
|
|
897
|
+
}
|
|
898
|
+
});
|
|
899
|
+
// 半成品(.tmp-*)一律清:它们不参与安装判断,只会占地方。
|
|
900
|
+
try {
|
|
901
|
+
for (const entry of fs.readdirSync(base, { withFileTypes: true })) {
|
|
902
|
+
if (!entry.isDirectory() || !entry.name.includes(".tmp-"))
|
|
903
|
+
continue;
|
|
904
|
+
const dir = path.join(base, entry.name);
|
|
905
|
+
const stats = scanDirStats(dir);
|
|
906
|
+
try {
|
|
907
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
908
|
+
reclaimedBytes += stats.bytes;
|
|
909
|
+
}
|
|
910
|
+
catch {
|
|
911
|
+
// 同上。
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
catch {
|
|
916
|
+
// 根目录不存在:没什么可清的。
|
|
917
|
+
}
|
|
918
|
+
const message = versions.length === 0
|
|
919
|
+
? "本地没有装过资源包,没什么可清理的。"
|
|
920
|
+
: removed.length === 0
|
|
921
|
+
? "保留 " + kept.join("、") + "(不超过 " + String(keepCount) + " 个版本),没有旧版本要删。"
|
|
922
|
+
: "删掉 " + String(removed.length) + " 个旧版本(" + removed.join("、") + "),回收 " + String(reclaimedBytes) + " 字节;保留 " + kept.join("、") + "。";
|
|
923
|
+
return { removed, kept, reclaimedBytes, message };
|
|
924
|
+
}
|