pi-flash 0.8.2 → 0.9.1
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/bin/lib.js +452 -15
- package/package.json +1 -1
package/bin/lib.js
CHANGED
|
@@ -7,6 +7,9 @@
|
|
|
7
7
|
// <pkg>/payload/pi-flash.exe 稳定入口(npm 命令与快捷方式都指它)
|
|
8
8
|
// <pkg>/payload-<版本>/.payload-version 应用内更新(081)解压出的新载荷目录
|
|
9
9
|
// <pkg>/payload-<版本>/pi-flash.exe ——只解压不 rename,启动时跑版本最高者
|
|
10
|
+
// <pkg>/payload/.payload-modules.json 模块戳(080-模块化载荷更新 §5):每模块 zip 哈希 +
|
|
11
|
+
// 文件清单,组件式更新据此复用未变模块;只有组件式
|
|
12
|
+
// 安装落的载荷才有,随版本戳同窗、先于它写
|
|
10
13
|
//
|
|
11
14
|
// 下载源:GitHub 直连优先,测速不过阈值自动按序切默认镜像列表(080 §3.2);
|
|
12
15
|
// PI_FLASH_MIRROR 指定唯一源、PI_FLASH_MIRRORS 追加候选。镜像须保持同构布局
|
|
@@ -17,6 +20,7 @@ const crypto = require("crypto");
|
|
|
17
20
|
const http = require("http");
|
|
18
21
|
const https = require("https");
|
|
19
22
|
const { spawnSync } = require("child_process");
|
|
23
|
+
const zlib = require("zlib"); // extractZipInProc 第三段兜底解 deflate 用
|
|
20
24
|
|
|
21
25
|
const pkgDir = path.join(__dirname, "..");
|
|
22
26
|
const pkgVersion = require(path.join(pkgDir, "package.json")).version;
|
|
@@ -29,6 +33,9 @@ const SUPPORTED_TAGS = ["win32-x64", "darwin-arm64"];
|
|
|
29
33
|
const TMP_PREFIX = "payload.tmp-";
|
|
30
34
|
const PAYLOAD_DIR = path.join(pkgDir, "payload");
|
|
31
35
|
const STAMP_FILE = path.join(PAYLOAD_DIR, ".payload-version");
|
|
36
|
+
const MODULES_STAMP_FILE = path.join(PAYLOAD_DIR, ".payload-modules.json");
|
|
37
|
+
// manifest 固定四模块(080-模块化载荷更新 §3),与发版侧 module_pack.mjs 同名同序
|
|
38
|
+
const MODULE_NAMES = ["app", "node", "pi-core", "exts"];
|
|
32
39
|
|
|
33
40
|
// --- Node 版本 -------------------------------------------------------------
|
|
34
41
|
|
|
@@ -204,6 +211,48 @@ function payloadOk(tag = platformTag()) {
|
|
|
204
211
|
return fs.existsSync(path.join(best.dir, exeRelPath(tag)));
|
|
205
212
|
}
|
|
206
213
|
|
|
214
|
+
// --- 复用源(080-模块化载荷更新 §7)---------------------------------------------
|
|
215
|
+
// 组件式安装前找「带模块戳的版本最高载荷目录」:未变模块从这里 copy,免掉约七成下载。
|
|
216
|
+
// 候选与 resolvePayload 同一套——稳定 payload/ 加每个完整的 payload-<版本>/(081 应用内
|
|
217
|
+
// 更新落的目录同住 <pkg>,可直接复用)。没有 = 首装或旧版载荷 → null,全模块下载,不是错误。
|
|
218
|
+
|
|
219
|
+
// 读模块戳:读不到 / 不是 JSON / 顶层不是对象,一律当没有(半截、旧版、被改坏同类)
|
|
220
|
+
function readModulesStamp(dir) {
|
|
221
|
+
let raw;
|
|
222
|
+
try {
|
|
223
|
+
raw = JSON.parse(fs.readFileSync(path.join(dir, ".payload-modules.json"), "utf8"));
|
|
224
|
+
} catch {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
228
|
+
return raw;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function resolveReuseSource(tag = platformTag()) {
|
|
232
|
+
const candidates = [{ dir: PAYLOAD_DIR, version: stampOfDir(PAYLOAD_DIR) }];
|
|
233
|
+
// 完整目录判据与 resolvePayload 逐条相同(目录名 -<x.y.z>、戳与目录版本吻合、exe 在位),
|
|
234
|
+
// 改一处须同步另一处
|
|
235
|
+
let entries = [];
|
|
236
|
+
try {
|
|
237
|
+
entries = fs.readdirSync(pkgDir);
|
|
238
|
+
} catch {}
|
|
239
|
+
for (const entry of entries) {
|
|
240
|
+
const m = /^(.+)-(\d+(?:\.\d+)+)$/.exec(entry);
|
|
241
|
+
if (!m) continue;
|
|
242
|
+
const dir = path.join(pkgDir, entry);
|
|
243
|
+
if (stampOfDir(dir) !== m[2]) continue;
|
|
244
|
+
if (!fs.existsSync(path.join(dir, exeRelPath(tag)))) continue;
|
|
245
|
+
candidates.push({ dir, version: m[2] });
|
|
246
|
+
}
|
|
247
|
+
// 版本降序取第一个带可解析模块戳者;同版本稳定目录优先(sort 稳定,payload/ 本就在首位)
|
|
248
|
+
candidates.sort((a, b) => compareVersions(b.version || "0", a.version || "0"));
|
|
249
|
+
for (const { dir, version } of candidates) {
|
|
250
|
+
const stamp = readModulesStamp(dir);
|
|
251
|
+
if (stamp) return { dir, version, stamp };
|
|
252
|
+
}
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
|
|
207
256
|
// --- 网络 -------------------------------------------------------------------
|
|
208
257
|
|
|
209
258
|
// 测速切换:开传 probeMs(默认 3s)时平均速度仍低于 minSpeedBps(默认
|
|
@@ -247,7 +296,8 @@ function clearProgress() {
|
|
|
247
296
|
}
|
|
248
297
|
}
|
|
249
298
|
|
|
250
|
-
|
|
299
|
+
// 单次请求(不重试);err.reusedSocket 标给 httpGet 判「是不是断在复用的 keep-alive 连接上」
|
|
300
|
+
function httpGetOnce(url, redirectsLeft = 5, timeoutMs = 30_000) {
|
|
251
301
|
return new Promise((resolve, reject) => {
|
|
252
302
|
const lib = url.startsWith("http:") ? http : https;
|
|
253
303
|
const req = lib.get(url, { headers: { "user-agent": "pi-flash-installer" } }, (res) => {
|
|
@@ -266,7 +316,23 @@ function httpGet(url, redirectsLeft = 5, timeoutMs = 30_000) {
|
|
|
266
316
|
resolve(res);
|
|
267
317
|
});
|
|
268
318
|
req.setTimeout(timeoutMs, () => req.destroy(new Error(`请求超时:${url}`)));
|
|
269
|
-
req.on("error",
|
|
319
|
+
req.on("error", (err) => {
|
|
320
|
+
err.reusedSocket = req.reusedSocket === true;
|
|
321
|
+
reject(err);
|
|
322
|
+
});
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// keep-alive 竞态兜底:两次请求之间夹着同步重活(组件式通道每个模块下完要 spawnSync 解压,
|
|
327
|
+
// pi-core 约 1.9 万文件,事件循环阻塞数十秒)时,客户端处理不了服务端的空闲关闭,下一个
|
|
328
|
+
// 请求会抓到那根已被关闭的连接 → ECONNRESET(Node 不自动重试,只在 req.reusedSocket 留
|
|
329
|
+
// 标记;实测超时 5s 的服务端 + 阻塞 8s 必现)。GET 幂等:响应头到达之前断在复用连接上就
|
|
330
|
+
// 换新连接重试一次,其余错误原样上抛(超时 / 真断流照旧走换源)。
|
|
331
|
+
function httpGet(url, redirectsLeft = 5, timeoutMs = 30_000) {
|
|
332
|
+
return httpGetOnce(url, redirectsLeft, timeoutMs).catch((err) => {
|
|
333
|
+
if (err.code !== "ECONNRESET" || !err.reusedSocket) throw err;
|
|
334
|
+
console.error(" 连接已被服务端关闭(keep-alive 空闲超时),重连重试");
|
|
335
|
+
return httpGetOnce(url, redirectsLeft, timeoutMs);
|
|
270
336
|
});
|
|
271
337
|
}
|
|
272
338
|
|
|
@@ -319,6 +385,7 @@ async function downloadToFile(url, dest, { onProgress } = {}) {
|
|
|
319
385
|
// 供校验和钉定官方源用(080 §3.2)。
|
|
320
386
|
async function downloadAssetFile(asset, dest, version = pkgVersion) {
|
|
321
387
|
const errors = [];
|
|
388
|
+
const statuses = []; // 各源失败的 HTTP 状态(网络错误/超时/过慢 = 0),只给调用方判失败性质
|
|
322
389
|
for (const base of downloadBases()) {
|
|
323
390
|
const label = baseLabel(base);
|
|
324
391
|
process.stderr.write(` 源:${label}\n`);
|
|
@@ -334,13 +401,16 @@ async function downloadAssetFile(asset, dest, version = pkgVersion) {
|
|
|
334
401
|
err.code === "ETOO_SLOW" ? `测速不过(${err.message})` : err.message;
|
|
335
402
|
console.error(` ${label} 不可用(${why}),换下一个源`);
|
|
336
403
|
errors.push(`${label}:${why}`);
|
|
404
|
+
statuses.push(err.status || 0);
|
|
337
405
|
}
|
|
338
406
|
}
|
|
339
|
-
|
|
407
|
+
const failed = new Error(
|
|
340
408
|
`所有下载源均失败:\n ${errors.join("\n ")}\n` +
|
|
341
409
|
` 可设 PI_FLASH_MIRROR=<base> 指定唯一源(布局 <base>/v<version>/<asset>),\n` +
|
|
342
410
|
` 或手动下载:${assetUrls(platformTag()).releasePage}`,
|
|
343
411
|
);
|
|
412
|
+
failed.statuses = statuses;
|
|
413
|
+
throw failed;
|
|
344
414
|
}
|
|
345
415
|
|
|
346
416
|
async function fetchText(url) {
|
|
@@ -411,30 +481,53 @@ function extractZip(zipPath, destDir) {
|
|
|
411
481
|
const args = ["-xf", zipPath, "-C", destDir];
|
|
412
482
|
const quiet = { stdio: ["ignore", "pipe", "pipe"], encoding: "utf8" };
|
|
413
483
|
if (process.platform === "win32") {
|
|
414
|
-
// 条目名无需任何特判:release
|
|
415
|
-
// (zip_name_check.mjs
|
|
416
|
-
//
|
|
417
|
-
//
|
|
418
|
-
// "tar":git-bash 环境会抢到 GNU tar,而它把 "D:" 当远程主机名直接报错。
|
|
484
|
+
// 条目名无需任何特判:release 产物非 ASCII 名一律 EFS/UTF-8
|
|
485
|
+
// (zip_name_check.mjs 硬门禁)。首选系统自带 bsdtar 的绝对路径(Win10 1803+
|
|
486
|
+
// 支持 zip)。不能裸调 PATH 里的 "tar":git-bash 环境会抢到 GNU tar,而它把
|
|
487
|
+
// "D:" 当远程主机名直接报错。
|
|
419
488
|
const sysTar = process.env.SystemRoot
|
|
420
489
|
? path.join(process.env.SystemRoot, "System32", "tar.exe")
|
|
421
490
|
: null;
|
|
422
491
|
const tarBin = sysTar && fs.existsSync(sysTar) ? sysTar : "tar";
|
|
423
|
-
//
|
|
492
|
+
// 首选 bsdtar:快、静默。但它有 Windows 专属硬伤(2026-12 runner bsdtar 3.8.9 实录):
|
|
493
|
+
// 解压期条目名走 wchar↔MBS(ACP) 往返转换,ACP 表不出的名字(en-US/1252 遇 UTF-8 中文)
|
|
494
|
+
// 直接报 "Archive entry has empty or unreadable filename" 跳条目、退出码 1;
|
|
495
|
+
// --options hdrcharset=UTF-8 也救不了(runner 实测同报错;读侧选项管不到解压期 MBS
|
|
496
|
+
// 往返)。本机 ACP=65001 全绿纯属侥幸。zh-CN(936) 名字表得出,不受影响。
|
|
424
497
|
let r = spawnSync(tarBin, args, { ...quiet, windowsHide: true });
|
|
425
498
|
if (r.status === 0) return;
|
|
426
499
|
const tarErr = (r.error ? r.error.message : r.stderr || "").trim() || "(无输出)";
|
|
500
|
+
// 必须让 PowerShell 显式 exit:-Command 下 Expand-Archive 失败只往 stderr 写错误、进程
|
|
501
|
+
// 仍退 0(实测「中央目录损坏」即如此),只看退出码会把空解压 / 半截解压当成成功
|
|
427
502
|
const ps =
|
|
428
|
-
|
|
429
|
-
`-DestinationPath '${destDir.replace(/'/g, "''")}' -Force
|
|
503
|
+
`$ErrorActionPreference = 'Stop'; try { Expand-Archive -LiteralPath '${zipPath.replace(/'/g, "''")}' ` +
|
|
504
|
+
`-DestinationPath '${destDir.replace(/'/g, "''")}' -Force -ErrorAction Stop } ` +
|
|
505
|
+
`catch { [Console]::Error.WriteLine($_.Exception.Message); exit 1 }`;
|
|
506
|
+
// PSModulePath 必须摘掉:pwsh 7 父进程(CI 步骤 shell、终端用户壳)会把它传给
|
|
507
|
+
// powershell.exe 5.1,5.1 按 PATH 优先误载 PS7 的 Microsoft.PowerShell.Archive,
|
|
508
|
+
// 其内部的三参 ExtractToDirectory 在 .NET Framework 不存在 → "Cannot find an
|
|
509
|
+
// overload for \"ExtractToDirectory\" and the argument count: \"3\""(bun/posthog
|
|
510
|
+
// 同款实录)。删掉让它回退内建默认模块路径,加载 5.1 自己的 Archive。
|
|
511
|
+
const psEnv = { ...process.env };
|
|
512
|
+
delete psEnv.PSModulePath;
|
|
430
513
|
r = spawnSync(
|
|
431
514
|
"powershell.exe",
|
|
432
515
|
["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps],
|
|
433
|
-
{ ...quiet, windowsHide: true },
|
|
516
|
+
{ ...quiet, windowsHide: true, env: psEnv },
|
|
434
517
|
);
|
|
435
518
|
if (r.status === 0) return;
|
|
436
519
|
const psErr = (r.error ? r.error.message : r.stderr || "").trim() || "(无输出)";
|
|
437
|
-
|
|
520
|
+
// 末段兜底:纯 Node 进程内解包(零依赖,条目名永远按 UTF-8/EFS 解,不吃 ACP)——
|
|
521
|
+
// 前两段都是外部进程,各有环境性死法;我们自己压的 zip 形状自可知(经典 zip:store
|
|
522
|
+
// 目录 / deflate 文件 / 无加密 / 无 zip64),读它只要几十行,换来 en-US 裸机也能装。
|
|
523
|
+
try {
|
|
524
|
+
extractZipInProc(zipPath, destDir);
|
|
525
|
+
return;
|
|
526
|
+
} catch (nodeErr) {
|
|
527
|
+
throw new Error(
|
|
528
|
+
`解压失败:\n ${tarBin}: ${tarErr}\n PowerShell: ${psErr}\n Node: ${nodeErr.message}`,
|
|
529
|
+
);
|
|
530
|
+
}
|
|
438
531
|
}
|
|
439
532
|
const r = spawnSync("tar", args, quiet);
|
|
440
533
|
if (r.status !== 0) {
|
|
@@ -442,6 +535,76 @@ function extractZip(zipPath, destDir) {
|
|
|
442
535
|
}
|
|
443
536
|
}
|
|
444
537
|
|
|
538
|
+
// zip 根布局:win32 带 pi-flash/ 包装目录(release.sh 压缩产物约定,压缩器无关),darwin 根即 .app
|
|
539
|
+
|
|
540
|
+
// 进程内 zip 解包器(extractZip 第三段兜底专用):只认自家/常规工具产的经典 zip——
|
|
541
|
+
// store(0) 与 deflate(8)、目录条目尾部 '/'、可选 EFS 标志(Bit 11,名字一律按 UTF-8 解,
|
|
542
|
+
// 纯 ASCII 名两种编码字节相同)、经典 EOCD。其余形状(加密 Bit 0、数据描述符、zip64、
|
|
543
|
+
// 其他压缩方法)一律报错走人——载荷 zip 由 release 链生成,形状自可知,碰到不认识的
|
|
544
|
+
// 宁可失败让上层报出来,也不解出半截载荷。逐条目 CRC32 校验后才落盘。
|
|
545
|
+
function extractZipInProc(zipPath, destDir) {
|
|
546
|
+
const buf = fs.readFileSync(zipPath);
|
|
547
|
+
// EOCD:签名 0x06054b50,从尾部往前找(zip 允许注释尾随,最长相邻 0xffff)
|
|
548
|
+
let eocd = -1;
|
|
549
|
+
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 0xffff); i--) {
|
|
550
|
+
if (buf.readUInt32LE(i) === 0x06054b50) {
|
|
551
|
+
eocd = i;
|
|
552
|
+
break;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
if (eocd < 0) throw new Error("未找到 EOCD(非经典 zip)");
|
|
556
|
+
const count = buf.readUInt16LE(eocd + 10);
|
|
557
|
+
let off = buf.readUInt32LE(eocd + 16);
|
|
558
|
+
if (count === 0xffff || off === 0xffffffff) throw new Error("zip64 不支持");
|
|
559
|
+
for (let n = 0; n < count; n++) {
|
|
560
|
+
if (off + 46 > buf.length || buf.readUInt32LE(off) !== 0x02014b50)
|
|
561
|
+
throw new Error(`中央目录第 ${n + 1} 条签名不符`);
|
|
562
|
+
const flags = buf.readUInt16LE(off + 8);
|
|
563
|
+
const method = buf.readUInt16LE(off + 10);
|
|
564
|
+
const crc = buf.readUInt32LE(off + 16);
|
|
565
|
+
const compSize = buf.readUInt32LE(off + 20);
|
|
566
|
+
const nameLen = buf.readUInt16LE(off + 28);
|
|
567
|
+
const extraLen = buf.readUInt16LE(off + 30);
|
|
568
|
+
const commentLen = buf.readUInt16LE(off + 32);
|
|
569
|
+
const lhoOff = buf.readUInt32LE(off + 42);
|
|
570
|
+
const name = buf.toString("utf8", off + 46, off + 46 + nameLen);
|
|
571
|
+
off += 46 + nameLen + extraLen + commentLen;
|
|
572
|
+
if (flags & 0x0001) throw new Error(`条目 ${name} 加密,不支持`);
|
|
573
|
+
if (flags & 0x0008) throw new Error(`条目 ${name} 用数据描述符,不支持`);
|
|
574
|
+
if (method !== 0 && method !== 8) throw new Error(`条目 ${name} 压缩方法 ${method},不支持`);
|
|
575
|
+
// 本地头里也有尺寸/名字(同值,但本地头有自己的 extra,得按它的头长跳到数据)
|
|
576
|
+
if (lhoOff + 30 > buf.length || buf.readUInt32LE(lhoOff) !== 0x04034b50)
|
|
577
|
+
throw new Error(`条目 ${name} 本地头签名不符`);
|
|
578
|
+
const lhNameLen = buf.readUInt16LE(lhoOff + 26);
|
|
579
|
+
const lhExtraLen = buf.readUInt16LE(lhoOff + 28);
|
|
580
|
+
const dataAt = lhoOff + 30 + lhNameLen + lhExtraLen;
|
|
581
|
+
if (dataAt + compSize > buf.length) throw new Error(`条目 ${name} 数据越界`);
|
|
582
|
+
if (name.endsWith("/")) continue; // 目录条目:落盘时 mkdir 顺带建,不单独立项
|
|
583
|
+
let data;
|
|
584
|
+
if (method === 0) data = buf.subarray(dataAt, dataAt + compSize);
|
|
585
|
+
else data = zlib.inflateRawSync(buf.subarray(dataAt, dataAt + compSize));
|
|
586
|
+
if (crc32Of(data) !== crc) throw new Error(`条目 ${name} CRC32 不符`);
|
|
587
|
+
const to = path.join(destDir, ...name.split("/"));
|
|
588
|
+
if (!to.startsWith(destDir + path.sep)) throw new Error(`条目 ${name} 越出目标目录`);
|
|
589
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
590
|
+
fs.writeFileSync(to, data);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
const CRC_TABLE = (() => {
|
|
594
|
+
const t = new Uint32Array(256);
|
|
595
|
+
for (let n = 0; n < 256; n++) {
|
|
596
|
+
let c = n;
|
|
597
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
598
|
+
t[n] = c;
|
|
599
|
+
}
|
|
600
|
+
return t;
|
|
601
|
+
})();
|
|
602
|
+
function crc32Of(buf) {
|
|
603
|
+
let c = 0xffffffff;
|
|
604
|
+
for (const b of buf) c = CRC_TABLE[(c ^ b) & 0xff] ^ (c >>> 8);
|
|
605
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
606
|
+
}
|
|
607
|
+
|
|
445
608
|
// zip 根布局:win32 带 pi-flash/ 包装目录(release.sh 压缩产物约定,压缩器无关),darwin 根即 .app
|
|
446
609
|
function locateContentRoot(extractDir, tag) {
|
|
447
610
|
const exeRel = exeRelPath(tag);
|
|
@@ -451,6 +614,143 @@ function locateContentRoot(extractDir, tag) {
|
|
|
451
614
|
throw new Error(`载荷结构异常:${extractDir} 下找不到 ${exeRel}`);
|
|
452
615
|
}
|
|
453
616
|
|
|
617
|
+
// --- 组件式载荷(080-模块化载荷更新 §4/§5/§7)-----------------------------------
|
|
618
|
+
//
|
|
619
|
+
// manifest 在位 → 只下变更模块、未变模块验本地后复用;没有 / 不识别 → 整包通道(迁移期
|
|
620
|
+
// 回落,见 ensure)。模块 zip 条目 = 载荷根(无 pi-flash/ 包装目录),四模块路径空间不相交,
|
|
621
|
+
// 并集即整棵载荷树。
|
|
622
|
+
|
|
623
|
+
// manifest 解析:任何一项不合规都抛错,调用方按「不识别」回落整包——绝不猜。format 非 1、
|
|
624
|
+
// 模块不是恰好那四个、条目的 tag / asset / sha256 形状不对都算。version 给了就必须与
|
|
625
|
+
// manifest 自述一致:/v<x>/ 下放着别的版本 = 源不对,装上去就是「戳写 x、字节是 y」。
|
|
626
|
+
// tree 是发版侧的内容键,客户端不消费,不取。
|
|
627
|
+
function parseManifest(text, version = null) {
|
|
628
|
+
let raw;
|
|
629
|
+
try {
|
|
630
|
+
raw = JSON.parse(text);
|
|
631
|
+
} catch (err) {
|
|
632
|
+
throw new Error(`不是合法 JSON(${err.message})`);
|
|
633
|
+
}
|
|
634
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
635
|
+
throw new Error("顶层不是对象");
|
|
636
|
+
}
|
|
637
|
+
if (raw.format !== 1) {
|
|
638
|
+
throw new Error(`format ${JSON.stringify(raw.format)} 不识别(须为 1)`);
|
|
639
|
+
}
|
|
640
|
+
if (!Array.isArray(raw.modules)) throw new Error("缺 modules 数组");
|
|
641
|
+
if (version !== null && raw.version !== version) {
|
|
642
|
+
throw new Error(`版本不符(v${version} 下是 ${JSON.stringify(raw.version)})`);
|
|
643
|
+
}
|
|
644
|
+
const seen = new Set();
|
|
645
|
+
const modules = raw.modules.map((m) => {
|
|
646
|
+
const bad = (why) => new Error(`模块条目不合规(${why}):${JSON.stringify(m)}`);
|
|
647
|
+
if (!m || typeof m !== "object" || Array.isArray(m)) throw bad("不是对象");
|
|
648
|
+
if (!MODULE_NAMES.includes(m.name)) {
|
|
649
|
+
throw bad(`模块名须为 ${MODULE_NAMES.join(" / ")}`);
|
|
650
|
+
}
|
|
651
|
+
if (seen.has(m.name)) throw bad("模块重复");
|
|
652
|
+
seen.add(m.name);
|
|
653
|
+
if (typeof m.tag !== "string" || !/^v\d+\.\d+\.\d+$/.test(m.tag)) {
|
|
654
|
+
throw bad("tag 须形如 v0.9.1");
|
|
655
|
+
}
|
|
656
|
+
if (typeof m.asset !== "string" || !/^[A-Za-z0-9._-]+\.zip$/.test(m.asset)) {
|
|
657
|
+
throw bad("asset 文件名异常");
|
|
658
|
+
}
|
|
659
|
+
if (typeof m.sha256 !== "string" || !/^[a-fA-F0-9]{64}$/.test(m.sha256)) {
|
|
660
|
+
throw bad("sha256 须为 64 位十六进制");
|
|
661
|
+
}
|
|
662
|
+
return { name: m.name, tag: m.tag, asset: m.asset, sha256: m.sha256.toLowerCase() };
|
|
663
|
+
});
|
|
664
|
+
if (modules.length !== MODULE_NAMES.length) {
|
|
665
|
+
throw new Error(
|
|
666
|
+
`模块须恰好 ${MODULE_NAMES.length} 个(${MODULE_NAMES.join(" / ")}),实际 ${modules.length}`,
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
return { format: 1, version: String(raw.version ?? ""), modules };
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// 拉 manifest:候选源与次序同 downloadAssetFile。直连优先钉定——某个源只要答了 404,就是
|
|
673
|
+
// 该版没有 manifest(早于组件式发布,或 release 资产还没挂全):镜像只是同一 origin 的
|
|
674
|
+
// 反代,不再逐个问,直接回落;非 404(网络 / 超时)才换下一个源。返回 null = 无 manifest
|
|
675
|
+
// 或不识别,调用方走整包通道(迁移期整包每版照发,§8)。
|
|
676
|
+
async function fetchManifest(version = pkgVersion) {
|
|
677
|
+
let lastWhy = "";
|
|
678
|
+
for (const base of downloadBases()) {
|
|
679
|
+
const label = baseLabel(base);
|
|
680
|
+
let text;
|
|
681
|
+
try {
|
|
682
|
+
text = await fetchText(`${base}/v${version}/manifest.json`);
|
|
683
|
+
} catch (err) {
|
|
684
|
+
if (err.status === 404) {
|
|
685
|
+
console.error(` ${label}:v${version} 无 manifest.json,回落整包`);
|
|
686
|
+
return null;
|
|
687
|
+
}
|
|
688
|
+
lastWhy = `${label}:${err.message}`;
|
|
689
|
+
console.error(` ${label} 取 manifest 失败(${err.message}),换下一个源`);
|
|
690
|
+
continue;
|
|
691
|
+
}
|
|
692
|
+
try {
|
|
693
|
+
return parseManifest(text, version);
|
|
694
|
+
} catch (err) {
|
|
695
|
+
console.error(` manifest.json 不识别(${err.message}),回落整包`);
|
|
696
|
+
return null;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
console.error(` manifest.json 取不到(${lastWhy}),回落整包`);
|
|
700
|
+
return null;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
// 载荷根相对路径的形状:/ 分隔、无盘符、无空段与 ./..(同 module_pack.mjs 的条目名校验)。
|
|
704
|
+
// 戳里的路径来自本地文件,照样要卡——越界路径会把载荷树外的文件拷进载荷。
|
|
705
|
+
function isPayloadRel(rel) {
|
|
706
|
+
if (typeof rel !== "string" || rel.includes("\\") || /^[A-Za-z]:/.test(rel)) return false;
|
|
707
|
+
return rel.split("/").every((part) => part && part !== "." && part !== "..");
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const byRel = (a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
|
|
711
|
+
|
|
712
|
+
// 载荷树文件清单 [[相对路径, 字节数]…]:只收文件(目录不记,同戳的约定),按路径排序
|
|
713
|
+
function listPayloadFiles(dir) {
|
|
714
|
+
const out = [];
|
|
715
|
+
const walk = (abs, rel) => {
|
|
716
|
+
for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
|
|
717
|
+
const childRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
718
|
+
const childAbs = path.join(abs, entry.name);
|
|
719
|
+
if (entry.isDirectory()) walk(childAbs, childRel);
|
|
720
|
+
else out.push([childRel, fs.statSync(childAbs).size]);
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
walk(dir, "");
|
|
724
|
+
return out.sort(byRel);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
// 复用前校验(§5):清单里每个文件都在、字节数都吻合才算过。不重算哈希——哈希在安装时
|
|
728
|
+
// 已对下载字节验过,磁盘文件被认为不会被改到长度不变。过 → { files }(规范化:去重、
|
|
729
|
+
// 排序,写戳直接用);不过 → { why }(首条失配,供降级日志),调用方把该模块降级为下载。
|
|
730
|
+
function verifyModuleFiles(dir, files) {
|
|
731
|
+
if (!Array.isArray(files) || files.length === 0) return { why: "清单缺失或为空" };
|
|
732
|
+
const seen = new Map();
|
|
733
|
+
for (const entry of files) {
|
|
734
|
+
if (!Array.isArray(entry) || entry.length !== 2) {
|
|
735
|
+
return { why: `清单条目形状异常:${JSON.stringify(entry)}` };
|
|
736
|
+
}
|
|
737
|
+
const [rel, size] = entry;
|
|
738
|
+
if (!isPayloadRel(rel) || !Number.isSafeInteger(size) || size < 0) {
|
|
739
|
+
return { why: `清单条目不合规:${JSON.stringify(entry)}` };
|
|
740
|
+
}
|
|
741
|
+
let stat;
|
|
742
|
+
try {
|
|
743
|
+
stat = fs.statSync(path.join(dir, ...rel.split("/")));
|
|
744
|
+
} catch {
|
|
745
|
+
return { why: `${rel} 不存在` };
|
|
746
|
+
}
|
|
747
|
+
if (!stat.isFile()) return { why: `${rel} 不是文件` };
|
|
748
|
+
if (stat.size !== size) return { why: `${rel} 字节数 ${stat.size} ≠ 戳 ${size}` };
|
|
749
|
+
seen.set(rel, size);
|
|
750
|
+
}
|
|
751
|
+
return { files: [...seen].sort(byRel) };
|
|
752
|
+
}
|
|
753
|
+
|
|
454
754
|
// --- 落位 ---------------------------------------------------------------------
|
|
455
755
|
|
|
456
756
|
function isBusyError(err) {
|
|
@@ -502,21 +802,145 @@ function replacePayload(contentRoot) {
|
|
|
502
802
|
}
|
|
503
803
|
}
|
|
504
804
|
|
|
805
|
+
// --- 组件式安装 -----------------------------------------------------------------
|
|
806
|
+
//
|
|
807
|
+
// 组装树 tmp/asm/ = 四模块并集(变更的解压后搬入、未变的从复用源 copy),整目录替换落位,
|
|
808
|
+
// 再写两枚戳。源载荷在替换前只读不写:中途失败旧载荷原样保留,与整包通道同一纪律。
|
|
809
|
+
|
|
810
|
+
// 单模块落进组装树,返回写戳用的 { sha256, files };任何失败直接上抛,由 installModules
|
|
811
|
+
// 统一回落整包(§8)。tag = 该模块字节所属的 release(未变时指回首发它的旧版),所以下载
|
|
812
|
+
// 地址用 tag、不用本次要装的版本。placed = 已落进组装树的路径。
|
|
813
|
+
async function stageModule(mod, source, { tmp, assembly, placed }) {
|
|
814
|
+
const local = source && source.stamp[mod.name];
|
|
815
|
+
if (local && String(local.sha256 || "").toLowerCase() === mod.sha256) {
|
|
816
|
+
const check = verifyModuleFiles(source.dir, local.files);
|
|
817
|
+
// 模块路径空间不相交:清单里出现别的模块已落的路径 = 本地清单不可信,同样降级——
|
|
818
|
+
// 否则后处理的复用模块会拿旧文件盖掉先处理的变更模块(app 先落位、被 node 的清单盖掉)
|
|
819
|
+
const clash = check.files && check.files.find(([rel]) => placed.has(rel));
|
|
820
|
+
if (check.files && !clash) {
|
|
821
|
+
for (const [rel] of check.files) {
|
|
822
|
+
const to = path.join(assembly, ...rel.split("/"));
|
|
823
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
824
|
+
fs.copyFileSync(path.join(source.dir, ...rel.split("/")), to);
|
|
825
|
+
}
|
|
826
|
+
console.error(` 复用本地 ${mod.name}(${check.files.length} 文件,免下载)`);
|
|
827
|
+
return { sha256: mod.sha256, files: check.files };
|
|
828
|
+
}
|
|
829
|
+
console.error(
|
|
830
|
+
` 本地 ${mod.name} 与模块戳不符(${clash ? `${clash[0]} 与其他模块路径重叠` : check.why}),重新下载`,
|
|
831
|
+
);
|
|
832
|
+
}
|
|
833
|
+
const zipPath = path.join(tmp, mod.asset);
|
|
834
|
+
const tagVersion = mod.tag.replace(/^v/, "");
|
|
835
|
+
console.error(` 下载模块 ${mod.name}:${mod.asset}(${mod.tag})`);
|
|
836
|
+
const t0 = Date.now();
|
|
837
|
+
const chosen = await downloadAssetFile(mod.asset, zipPath, tagVersion);
|
|
838
|
+
console.error(
|
|
839
|
+
` ${mod.name} 下载完成,用时 ${Math.max(1, Math.round((Date.now() - t0) / 1000))}s(源:${baseLabel(chosen)})`,
|
|
840
|
+
);
|
|
841
|
+
// 模块哈希以 manifest 为唯一权威(钉定点前移,不再走 sidecar 链)
|
|
842
|
+
const actual = await sha256File(zipPath);
|
|
843
|
+
if (actual !== mod.sha256) {
|
|
844
|
+
throw new Error(
|
|
845
|
+
`SHA-256 不符(期望 ${mod.sha256},实际 ${actual})。\n` +
|
|
846
|
+
` 已删除下载文件。请到 ${assetUrls(platformTag(), tagVersion).releasePage} 手动核对,或稍后重试。`,
|
|
847
|
+
);
|
|
848
|
+
}
|
|
849
|
+
const modDir = path.join(tmp, "x", mod.name);
|
|
850
|
+
fs.mkdirSync(modDir, { recursive: true });
|
|
851
|
+
extractZip(zipPath, modDir);
|
|
852
|
+
const files = listPayloadFiles(modDir);
|
|
853
|
+
// 解压「成功」却一个文件都没有(空包 / 工具静默失败):四模块每版必有内容,缺位不能
|
|
854
|
+
// 装作就位——否则装出一份缺模块的载荷还写下模块戳
|
|
855
|
+
if (files.length === 0) {
|
|
856
|
+
throw new Error(`解压后没有文件(${mod.asset})`);
|
|
857
|
+
}
|
|
858
|
+
for (const [rel] of files) {
|
|
859
|
+
if (placed.has(rel)) {
|
|
860
|
+
throw new Error(`载荷结构异常:${rel} 与其他模块路径重叠`);
|
|
861
|
+
}
|
|
862
|
+
const to = path.join(assembly, ...rel.split("/"));
|
|
863
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
864
|
+
fs.renameSync(path.join(modDir, ...rel.split("/")), to);
|
|
865
|
+
}
|
|
866
|
+
fs.rmSync(modDir, { recursive: true, force: true }); // 只剩空目录
|
|
867
|
+
return { sha256: mod.sha256, files };
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// 模块化组装失败的一行原因(回落日志用):哪个模块、什么性质。只取错误信息首行——
|
|
871
|
+
// 各源的逐条失败原因 downloadAssetFile 已经打过了。
|
|
872
|
+
function moduleFailureWhy(mod, err) {
|
|
873
|
+
const firstLine = String((err && err.message) || err).split("\n")[0].replace(/[::。\s]+$/, "");
|
|
874
|
+
if (!mod) return `模块化组装未完成(${firstLine})`;
|
|
875
|
+
const statuses = err.statuses || [];
|
|
876
|
+
if (statuses.includes(404)) return `模块 ${mod.name} 资产缺失(${mod.tag}/${mod.asset})`;
|
|
877
|
+
if (statuses.length) return `模块 ${mod.name} 下载失败(所有源均不可用)`;
|
|
878
|
+
return `模块 ${mod.name} ${firstLine}`;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
// 组件式安装主流程:选复用源 → 逐模块落进组装树 → 整目录替换 → 写模块戳 → 版本戳最后写
|
|
882
|
+
// (戳在 = 完整,且模块戳在、清单可信,半截 / 中断天然落选)。
|
|
883
|
+
//
|
|
884
|
+
// §8 回落规则:组装阶段任何一步失败都不让安装失败——某个模块 zip 下载失败(404 / 被引用的
|
|
885
|
+
// 旧 release 资产被清 / 网络错)、sha256 不符、解压失败、复用失配后重下也失败……一律清掉
|
|
886
|
+
// 本次组装残骸、返回 false,交给 ensure 按整包路径重来(迁移期整包每版照发)。只有 manifest
|
|
887
|
+
// 拿得到且四个模块全部就位才算模块化成功。落位与写戳在回落域之外:四模块已就位后的失败
|
|
888
|
+
// (如载荷目录被占用)整包重下只会撞同一堵墙,照旧报错。
|
|
889
|
+
async function installModules(manifest, { ver, tmp, tag = platformTag() } = {}) {
|
|
890
|
+
const source = resolveReuseSource(tag);
|
|
891
|
+
const from = source
|
|
892
|
+
? `,复用源 ${path.basename(source.dir)}/${source.version ? `(v${source.version})` : ""}`
|
|
893
|
+
: "";
|
|
894
|
+
console.error(` 组件式载荷 v${ver}:${manifest.modules.length} 模块${from}`);
|
|
895
|
+
const assembly = path.join(tmp, "asm");
|
|
896
|
+
fs.mkdirSync(assembly, { recursive: true });
|
|
897
|
+
const stamps = {};
|
|
898
|
+
const placed = new Set(); // 已落进组装树的路径,验模块路径空间不相交
|
|
899
|
+
let current = null; // 正在处理的模块,失败日志用
|
|
900
|
+
try {
|
|
901
|
+
for (const mod of manifest.modules) {
|
|
902
|
+
current = mod;
|
|
903
|
+
const staged = await stageModule(mod, source, { tmp, assembly, placed });
|
|
904
|
+
for (const [rel] of staged.files) placed.add(rel);
|
|
905
|
+
stamps[mod.name] = staged;
|
|
906
|
+
}
|
|
907
|
+
// 同整包通道的结构门禁:装出来的树必须带 exe
|
|
908
|
+
if (!fs.existsSync(path.join(assembly, exeRelPath(tag)))) {
|
|
909
|
+
throw new Error(`载荷结构异常:v${ver} 的模块清单里没有 ${exeRelPath(tag)}`);
|
|
910
|
+
}
|
|
911
|
+
} catch (err) {
|
|
912
|
+
console.error(` ${moduleFailureWhy(current, err)},回落整包`);
|
|
913
|
+
fs.rmSync(assembly, { recursive: true, force: true });
|
|
914
|
+
fs.rmSync(path.join(tmp, "x"), { recursive: true, force: true });
|
|
915
|
+
return false;
|
|
916
|
+
}
|
|
917
|
+
replacePayload(assembly);
|
|
918
|
+
fs.writeFileSync(MODULES_STAMP_FILE, `${JSON.stringify(stamps, null, 2)}\n`);
|
|
919
|
+
fs.writeFileSync(STAMP_FILE, `${ver}\n`); // 版本戳最后写:中途崩溃 = 未完成,下次重来
|
|
920
|
+
console.error(` 载荷就绪:${exePath(tag)}(v${ver})`);
|
|
921
|
+
return true;
|
|
922
|
+
}
|
|
923
|
+
|
|
505
924
|
// 主流程:版本戳不合 → 清残留 → 预取真实最新版(壳可能来自滞后的 npm 镜像,
|
|
506
|
-
// 载荷版本以 GitHub releases 为准)→
|
|
507
|
-
//
|
|
925
|
+
// 载荷版本以 GitHub releases 为准)→ 有 manifest 走组件式(只下变更模块、未变复用
|
|
926
|
+
// 本地);没有 / 不识别 / 组装失败 → 整包:测速选源下载 → 校验 → 解压 →
|
|
927
|
+
// 落位 → 最后写版本戳
|
|
508
928
|
async function ensure({ force = false, version = null } = {}) {
|
|
509
929
|
const tag = platformTag(); // 不支持的平台在这里就明确报错
|
|
510
930
|
if (!force && payloadOk(tag)) return;
|
|
511
931
|
|
|
512
932
|
const ver = version || (await resolveLatestVersion());
|
|
513
933
|
const urls = assetUrls(tag, ver);
|
|
934
|
+
const manifest = await fetchManifest(ver); // null = 走下方整包通道(迁移期回落)
|
|
514
935
|
rmLeftovers();
|
|
515
936
|
const tmp = path.join(pkgDir, `${TMP_PREFIX}${process.pid}`);
|
|
516
937
|
fs.rmSync(tmp, { recursive: true, force: true });
|
|
517
938
|
fs.mkdirSync(tmp, { recursive: true });
|
|
518
939
|
|
|
519
940
|
try {
|
|
941
|
+
// 组件式通道落位即返回(finally 照常清 tmp);返回 false = 组装阶段任一步失败(§8),落到整包
|
|
942
|
+
if (manifest && (await installModules(manifest, { ver, tmp, tag }))) return;
|
|
943
|
+
|
|
520
944
|
const zipPath = path.join(tmp, urls.asset);
|
|
521
945
|
const t0 = Date.now();
|
|
522
946
|
console.error(` 下载载荷 ${urls.asset}`);
|
|
@@ -550,6 +974,8 @@ module.exports = {
|
|
|
550
974
|
pkgDir,
|
|
551
975
|
pkgVersion,
|
|
552
976
|
MIN_NODE,
|
|
977
|
+
MODULE_NAMES,
|
|
978
|
+
MODULES_STAMP_FILE,
|
|
553
979
|
parseNodeVersion,
|
|
554
980
|
isNodeVersionSupported,
|
|
555
981
|
nodeVersionMessage,
|
|
@@ -563,17 +989,28 @@ module.exports = {
|
|
|
563
989
|
resolvePayload,
|
|
564
990
|
payloadOk,
|
|
565
991
|
compareVersions,
|
|
992
|
+
readModulesStamp,
|
|
993
|
+
resolveReuseSource,
|
|
566
994
|
minSpeedBps,
|
|
567
995
|
probeMs,
|
|
568
996
|
fmtMB,
|
|
569
997
|
fmtSpeed,
|
|
570
998
|
sha256File,
|
|
571
999
|
parseHashFor,
|
|
1000
|
+
parseManifest,
|
|
572
1001
|
resolveExpectedHash,
|
|
573
1002
|
downloadToFile,
|
|
574
1003
|
downloadAssetFile,
|
|
1004
|
+
fetchManifest,
|
|
575
1005
|
resolveLatestVersion,
|
|
576
1006
|
extractZip,
|
|
1007
|
+
extractZipInProc, // 测试直接测第三段兜底
|
|
1008
|
+
isPayloadRel,
|
|
1009
|
+
listPayloadFiles,
|
|
1010
|
+
verifyModuleFiles,
|
|
1011
|
+
moduleFailureWhy,
|
|
1012
|
+
stageModule,
|
|
1013
|
+
installModules,
|
|
577
1014
|
ensure,
|
|
578
1015
|
busyMessage,
|
|
579
1016
|
rmLeftovers,
|
package/package.json
CHANGED