dsh-plugin-snapshot 0.3.7 → 0.3.9
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/lib/allow-builds.js +163 -0
- package/lib/auto-update.js +410 -146
- package/lib/doctor.js +98 -4
- package/lib/dsh-version.js +127 -0
- package/lib/exec.js +39 -0
- package/lib/health-gate.js +192 -0
- package/lib/index.js +49 -7
- package/lib/policy.js +245 -0
- package/lib/routes.js +25 -4
- package/lib/updates.js +97 -19
- package/package.json +2 -2
package/lib/doctor.js
CHANGED
|
@@ -9,6 +9,70 @@ import { parseSemver, cmpSemver, shortVer } from './util.js';
|
|
|
9
9
|
|
|
10
10
|
const MAX_JSON = 4 * 1024 * 1024;
|
|
11
11
|
|
|
12
|
+
/** 解析一条范围 token(支持 >= <= > < ^ ~ = 与裸版本),无法解析返回 null */
|
|
13
|
+
function parseRange(tok) {
|
|
14
|
+
const t = String(tok).trim();
|
|
15
|
+
let op = '=';
|
|
16
|
+
let rest = t;
|
|
17
|
+
for (const o of ['>=', '<=', '^', '~', '>', '<', '=']) {
|
|
18
|
+
if (t.indexOf(o) === 0) { op = o; rest = t.slice(o.length); break; }
|
|
19
|
+
}
|
|
20
|
+
const v = parseSemver(rest);
|
|
21
|
+
return v ? { op, v } : null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* engines.dsh 是否满足:true / false / null(无法判定)。
|
|
26
|
+
*
|
|
27
|
+
* npm 的 engines 常用多段 OR,例如
|
|
28
|
+
* ">=0.1.6-0 <0.2.0 || >=0.2.0-0 <0.3.0 || >=0.2.2-0 <0.3.0"
|
|
29
|
+
* 旧实现按空格切分后一遇到 "||" 就整段放弃,把合法多段范围读成「不满足」,
|
|
30
|
+
* 进而把本该升级的插件判成 incompatible 挡在门外(桌面版 v3.2.9 修复项)。
|
|
31
|
+
* 正确语义:先按 || 切组,组内各段必须全部成立,任一组成立即满足。
|
|
32
|
+
*/
|
|
33
|
+
function satisfiesRange(version, range) {
|
|
34
|
+
const v = parseSemver(version);
|
|
35
|
+
if (!v) return null;
|
|
36
|
+
const groups = String(range).split('||').map((s) => s.trim()).filter(Boolean);
|
|
37
|
+
if (!groups.length) return null;
|
|
38
|
+
let anyKnown = false;
|
|
39
|
+
|
|
40
|
+
const matchGroup = (group) => {
|
|
41
|
+
const parts = group.split(/\s+/).filter(Boolean);
|
|
42
|
+
if (!parts.length) return 'unknown';
|
|
43
|
+
for (const p of parts) {
|
|
44
|
+
if (p.indexOf('*') >= 0) return 'unknown';
|
|
45
|
+
const r = parseRange(p);
|
|
46
|
+
if (!r) return 'unknown';
|
|
47
|
+
/* 丢掉 prerelease 会让 >=3.2.2-beta.1 判错,必须带上 */
|
|
48
|
+
const base = r.v.major + '.' + r.v.minor + '.' + r.v.patch + (r.v.pre ? '-' + r.v.pre : '');
|
|
49
|
+
const c = cmpSemver(version, base);
|
|
50
|
+
if (c === null) return 'unknown';
|
|
51
|
+
if (r.op === '=' && c !== 0) return false;
|
|
52
|
+
if (r.op === '>' && c <= 0) return false;
|
|
53
|
+
if (r.op === '>=' && c < 0) return false;
|
|
54
|
+
if (r.op === '<' && c >= 0) return false;
|
|
55
|
+
if (r.op === '<=' && c > 0) return false;
|
|
56
|
+
/* ^0.2.3 只允许 0.2.x;^0.0.3 只允许 0.0.3 */
|
|
57
|
+
if (r.op === '^') {
|
|
58
|
+
if (c < 0) return false;
|
|
59
|
+
if (r.v.major > 0) { if (v.major !== r.v.major) return false; }
|
|
60
|
+
else if (r.v.minor > 0) { if (v.major !== 0 || v.minor !== r.v.minor) return false; }
|
|
61
|
+
else if (v.major !== 0 || v.minor !== 0 || v.patch !== r.v.patch) return false;
|
|
62
|
+
}
|
|
63
|
+
if (r.op === '~' && (v.major !== r.v.major || v.minor !== r.v.minor || c < 0)) return false;
|
|
64
|
+
}
|
|
65
|
+
return true;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
for (const g of groups) {
|
|
69
|
+
const res = matchGroup(g);
|
|
70
|
+
if (res === true) return true;
|
|
71
|
+
if (res === false) anyKnown = true;
|
|
72
|
+
}
|
|
73
|
+
return anyKnown ? false : null;
|
|
74
|
+
}
|
|
75
|
+
|
|
12
76
|
/** 兼容性判定:否定声明优先于肯定声明(incompatible 绝不能被读成兼容) */
|
|
13
77
|
export function judgeCompatibility(pkg, dshVersion) {
|
|
14
78
|
const cur = parseSemver(dshVersion);
|
|
@@ -51,12 +115,42 @@ export function judgeCompatibility(pkg, dshVersion) {
|
|
|
51
115
|
out.detail = '声明范围不含 ' + (dshVersion || '未知版本') + ';风险未知,建议先在测试环境验证';
|
|
52
116
|
return out;
|
|
53
117
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
118
|
+
/* engines.dsh 与 peerDependencies["@deepseek-ai/dsh"] 都算作者声明的版本要求。
|
|
119
|
+
桌面版 v3.3.2 之前只读 engines,导致把要求写在 peer 里的包
|
|
120
|
+
(如 liangshen 0.4.22)先装机失败再回滚。两个来源都要看,否定优先。 */
|
|
121
|
+
const eng = (pkg && pkg.engines) || {};
|
|
122
|
+
const peer = (pkg && pkg.peerDependencies) || {};
|
|
123
|
+
const ranges = [];
|
|
124
|
+
if (eng.dsh) ranges.push({ from: 'engines.dsh', range: String(eng.dsh) });
|
|
125
|
+
if (peer['@deepseek-ai/dsh']) ranges.push({ from: 'peerDependencies', range: String(peer['@deepseek-ai/dsh']) });
|
|
126
|
+
|
|
127
|
+
if (ranges.length) {
|
|
128
|
+
out.declared = ranges.map((r) => r.from + ': ' + r.range);
|
|
129
|
+
let denied = null;
|
|
130
|
+
let satisfied = null;
|
|
131
|
+
for (const r of ranges) {
|
|
132
|
+
const sat = satisfiesRange(dshVersion, r.range);
|
|
133
|
+
if (sat === false) { denied = r; break; }
|
|
134
|
+
if (sat === true) satisfied = r;
|
|
135
|
+
}
|
|
136
|
+
if (denied) {
|
|
137
|
+
out.state = 'incompatible';
|
|
138
|
+
out.label = '不满足版本约束';
|
|
139
|
+
out.detail = '作者在 ' + denied.from + ' 声明 ' + denied.range + ',当前 DSH ' + (dshVersion || '未知') + ' 不满足';
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
142
|
+
if (satisfied) {
|
|
143
|
+
out.state = 'compatible';
|
|
144
|
+
out.label = '满足版本约束';
|
|
145
|
+
out.detail = '当前 DSH ' + dshVersion + ' 满足 ' + satisfied.from + ' = ' + satisfied.range;
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
out.state = 'untested';
|
|
149
|
+
out.label = '约束无法判定';
|
|
150
|
+
out.detail = '声明了 ' + ranges.map((r) => r.from + '=' + r.range).join('、') + ',但当前版本无法解析,风险未知';
|
|
58
151
|
return out;
|
|
59
152
|
}
|
|
153
|
+
|
|
60
154
|
out.detail = '插件未声明任何 DSH 版本兼容信息';
|
|
61
155
|
return out;
|
|
62
156
|
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DSH 版本解析:兼容性判定的唯一事实来源。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要这个文件:插件跑在 DSH 进程内,`~/.dsh` 下没有版本文件、
|
|
5
|
+
* profile 里也没有 @deepseek-ai/dsh,所以旧实现只能读 DSH_VERSION 环境变量,
|
|
6
|
+
* 实际上恒为 null —— 兼容性判定永远返回 unknown,等于「照装不误」。
|
|
7
|
+
*
|
|
8
|
+
* 兜底链(先到先得):
|
|
9
|
+
* 1) 插件配置 dshVersion(用户显式指定,最可信)
|
|
10
|
+
* 2) DSH_VERSION 环境变量
|
|
11
|
+
* 3) resources/app.asar 里的 dsh/package.json(与桌面版同源)
|
|
12
|
+
* 4) profile 里可能存在的 @deepseek-ai/dsh(旧布局)
|
|
13
|
+
*
|
|
14
|
+
* asar 用「扫描 + 括号配对」而不是硬编码偏移:不同 Electron 版本写出的头部
|
|
15
|
+
* 前缀长度并不一致(实测本机 JSON 从 16 字节才开始),按偏移读必然错位。
|
|
16
|
+
*/
|
|
17
|
+
import { existsSync, openSync, readSync, closeSync, readFileSync } from 'node:fs';
|
|
18
|
+
import { join, dirname } from 'node:path';
|
|
19
|
+
import { createRequire } from 'node:module';
|
|
20
|
+
|
|
21
|
+
/* ESM 里没有裸 require:original-fs 是 Electron 内建模块,只能经 createRequire 取 */
|
|
22
|
+
const nodeRequire = createRequire(import.meta.url);
|
|
23
|
+
|
|
24
|
+
const MAX_HEADER_PROBE = 24 * 1024 * 1024;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 从 asar 头部缓冲区里切出 JSON 文本。
|
|
28
|
+
* @returns {string|null}
|
|
29
|
+
*/
|
|
30
|
+
export function sliceAsarHeader(buf) {
|
|
31
|
+
const anchor = Buffer.from('{"files"', 'utf8');
|
|
32
|
+
const start = buf.indexOf(anchor);
|
|
33
|
+
if (start < 0) return null;
|
|
34
|
+
let depth = 0, inStr = false, esc = false;
|
|
35
|
+
for (let i = start; i < buf.length; i++) {
|
|
36
|
+
const c = buf[i];
|
|
37
|
+
if (inStr) {
|
|
38
|
+
if (esc) esc = false;
|
|
39
|
+
else if (c === 92) esc = true;
|
|
40
|
+
else if (c === 34) inStr = false;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (c === 34) inStr = true;
|
|
44
|
+
else if (c === 123) depth++;
|
|
45
|
+
else if (c === 125) { depth--; if (depth === 0) return buf.slice(start, i + 1).toString('utf8'); }
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 数据区起点 = 8 + 第二个 uint32(header pickle 长度) */
|
|
51
|
+
function asarDataOffset(head) {
|
|
52
|
+
const pickleLen = head.readUInt32LE(4);
|
|
53
|
+
if (!Number.isFinite(pickleLen) || pickleLen <= 0 || pickleLen > MAX_HEADER_PROBE) return -1;
|
|
54
|
+
return 8 + pickleLen;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 读 asar 里任意文件的 Buffer;失败返回 null,不抛异常 */
|
|
58
|
+
function readFromAsar(fd, headerJson, innerPath) {
|
|
59
|
+
const parts = innerPath.split('/');
|
|
60
|
+
let node = { files: JSON.parse(headerJson) };
|
|
61
|
+
for (const p of parts) {
|
|
62
|
+
if (!node || !node.files || !node.files[p]) return null;
|
|
63
|
+
node = node.files[p];
|
|
64
|
+
}
|
|
65
|
+
const head = Buffer.alloc(12);
|
|
66
|
+
readSync(fd, head, 0, 12, 0);
|
|
67
|
+
const base = asarDataOffset(head);
|
|
68
|
+
if (base < 0) return null;
|
|
69
|
+
const buf = Buffer.alloc(Number(node.size));
|
|
70
|
+
readSync(fd, buf, 0, Number(node.size), base + Number(node.offset));
|
|
71
|
+
return buf;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 从安装目录的 app.asar 读 DSH 版本。
|
|
76
|
+
* original-fs 用于绕开 Electron 对 *.asar 的归档拦截(普通 fs 读出来是 0 字节)。
|
|
77
|
+
*/
|
|
78
|
+
export function readDshVersionFromAsar(exePath) {
|
|
79
|
+
try {
|
|
80
|
+
const asarPath = join(dirname(exePath), 'resources', 'app.asar');
|
|
81
|
+
if (!existsSync(asarPath)) return null;
|
|
82
|
+
let rfs = null;
|
|
83
|
+
try {
|
|
84
|
+
const mod = nodeRequire('original-fs');
|
|
85
|
+
rfs = mod && mod.openSync ? mod : null;
|
|
86
|
+
} catch (e) { rfs = null; }
|
|
87
|
+
const io = rfs || { openSync, readSync, closeSync };
|
|
88
|
+
const fd = io.openSync(asarPath, 'r');
|
|
89
|
+
try {
|
|
90
|
+
const probe = Buffer.alloc(Math.min(MAX_HEADER_PROBE, 24 * 1024 * 1024));
|
|
91
|
+
const n = io.readSync(fd, probe, 0, probe.length, 0);
|
|
92
|
+
const headerJson = sliceAsarHeader(probe.slice(0, n));
|
|
93
|
+
if (!headerJson) return null;
|
|
94
|
+
const buf = readFromAsar(fd, headerJson, 'dsh/package.json');
|
|
95
|
+
if (!buf) return null;
|
|
96
|
+
const j = JSON.parse(buf.toString('utf8'));
|
|
97
|
+
return j && j.version ? String(j.version) : null;
|
|
98
|
+
} finally {
|
|
99
|
+
try { io.closeSync(fd); } catch (e) { /* 忽略 */ }
|
|
100
|
+
}
|
|
101
|
+
} catch (e) { return null; }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 解析当前宿主 DSH 版本。
|
|
106
|
+
* @returns {{ version: string|null, source: string }}
|
|
107
|
+
*/
|
|
108
|
+
export function resolveDshVersion(profileDir, cfg) {
|
|
109
|
+
const fromCfg = String((cfg && cfg.dshVersion) || '').trim();
|
|
110
|
+
if (fromCfg) return { version: fromCfg, source: 'config' };
|
|
111
|
+
|
|
112
|
+
const fromEnv = String((process.env && process.env.DSH_VERSION) || '').trim();
|
|
113
|
+
if (fromEnv) return { version: fromEnv, source: 'env' };
|
|
114
|
+
|
|
115
|
+
const fromAsar = readDshVersionFromAsar(process.execPath);
|
|
116
|
+
if (fromAsar) return { version: fromAsar, source: 'asar' };
|
|
117
|
+
|
|
118
|
+
try {
|
|
119
|
+
const p = join(profileDir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json');
|
|
120
|
+
if (existsSync(p)) {
|
|
121
|
+
const j = JSON.parse(readFileSync(p, 'utf8'));
|
|
122
|
+
if (j && j.version) return { version: String(j.version), source: 'profile' };
|
|
123
|
+
}
|
|
124
|
+
} catch (e) { /* 忽略 */ }
|
|
125
|
+
|
|
126
|
+
return { version: null, source: 'none' };
|
|
127
|
+
}
|
package/lib/exec.js
CHANGED
|
@@ -99,3 +99,42 @@ export function runPnpm(pnpmCjs, args, cwd, timeoutMs) {
|
|
|
99
99
|
});
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 解析 pnpm 实际使用的 registry。
|
|
105
|
+
*
|
|
106
|
+
* 为什么必须这么做:检测源与安装源不同源时,会出现「检测到新版、安装报
|
|
107
|
+
* ERR_PNPM_NO_MATCHING_VERSION」的假失败,而且它会被判成确定性错误不再重试。
|
|
108
|
+
* 用户在 .npmrc / pnpm 配置里指向镜像时,只看 env / 默认 npmjs 的检测必然错。
|
|
109
|
+
*
|
|
110
|
+
* 取不到就返回 null,让调用方回落到显式配置或默认源 —— 猜一个源比不猜更危险。
|
|
111
|
+
*/
|
|
112
|
+
const REGISTRY_CACHE = new Map();
|
|
113
|
+
|
|
114
|
+
export async function resolveRegistry(pnpmCjs, cwd) {
|
|
115
|
+
if (!pnpmCjs) return null;
|
|
116
|
+
const key = String(cwd || '');
|
|
117
|
+
if (REGISTRY_CACHE.has(key)) return REGISTRY_CACHE.get(key);
|
|
118
|
+
const value = await new Promise((resolve) => {
|
|
119
|
+
try {
|
|
120
|
+
execFile(process.execPath, [pnpmCjs, 'config', 'get', 'registry'], {
|
|
121
|
+
cwd: cwd || process.cwd(),
|
|
122
|
+
timeout: 20000,
|
|
123
|
+
maxBuffer: 1024 * 1024,
|
|
124
|
+
env: safeEnv()
|
|
125
|
+
}, (err, stdout) => {
|
|
126
|
+
const out = String(stdout || '').trim().replace(/[/]+$/, '');
|
|
127
|
+
/* pnpm 在没配置时会打印 undefined 或空串,这两种都当作「取不到」 */
|
|
128
|
+
if (err || !out || out === 'undefined' || !/^https?:[/][/]/.test(out)) resolve(null);
|
|
129
|
+
else resolve(out);
|
|
130
|
+
});
|
|
131
|
+
} catch (e) { resolve(null); }
|
|
132
|
+
});
|
|
133
|
+
REGISTRY_CACHE.set(key, value);
|
|
134
|
+
return value;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 清缓存:registry 可能在会话中被用户改掉 */
|
|
138
|
+
export function clearRegistryCache() {
|
|
139
|
+
REGISTRY_CACHE.clear();
|
|
140
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 健康闸门:装完之后、宣布成功之前,回答一个问题——
|
|
3
|
+
* 「DSH 下次启动还能把所有启用的插件加载起来吗?」
|
|
4
|
+
*
|
|
5
|
+
* 只看 pnpm 退出码和磁盘版本号是不够的:「装上了但入口文件缺了」
|
|
6
|
+
* 「lockfile 与 node_modules 不一致」这些问题都要等用户重启 DSH 看到崩溃才知道。
|
|
7
|
+
* 这一层是纯静态校验,不执行插件代码:
|
|
8
|
+
* 1) 清单结构完整性(bundles 是数组、dependencies 是对象)
|
|
9
|
+
* 2) 每个声明依赖的目录与 package.json 存在且可解析
|
|
10
|
+
* 3) 入口文件完整性:main/module/browser/exports 指向的文件必须真的存在
|
|
11
|
+
* 4) lockfile 里声明的直接依赖与 node_modules 实际目录比对
|
|
12
|
+
*
|
|
13
|
+
* 移植自桌面版 v3.3.5 engine/healthgate.mjs,含三条误报修复:
|
|
14
|
+
* - exports 里的 "*" 是子路径通配符,不是文件名,不能拿去做 existsSync;
|
|
15
|
+
* - 桌面版把核心打进 app.asar,profile 依赖里本来就不该有 @deepseek-ai/dsh*;
|
|
16
|
+
* - 可选依赖缺失只算 warning,不算 error。
|
|
17
|
+
*/
|
|
18
|
+
import { existsSync } from 'node:fs';
|
|
19
|
+
import { readFile } from 'node:fs/promises';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
import { isValidPkgName } from './util.js';
|
|
22
|
+
|
|
23
|
+
/** 清单结构:这些字段写坏一个,DSH 就可能起不来 */
|
|
24
|
+
export function checkManifestShape(pkg) {
|
|
25
|
+
const problems = [];
|
|
26
|
+
if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg)) {
|
|
27
|
+
problems.push('package.json 不是对象');
|
|
28
|
+
return problems;
|
|
29
|
+
}
|
|
30
|
+
if (pkg.dependencies !== undefined && (typeof pkg.dependencies !== 'object' || Array.isArray(pkg.dependencies) || pkg.dependencies === null)) {
|
|
31
|
+
problems.push('dependencies 不是对象');
|
|
32
|
+
}
|
|
33
|
+
const prof = pkg.dsh && pkg.dsh.profile;
|
|
34
|
+
if (prof && prof.bundles !== undefined && !Array.isArray(prof.bundles)) {
|
|
35
|
+
problems.push('dsh.profile.bundles 不是数组');
|
|
36
|
+
}
|
|
37
|
+
if (Array.isArray(prof && prof.bundles)) {
|
|
38
|
+
for (const b of prof.bundles) {
|
|
39
|
+
if (typeof b !== 'string' || !isValidPkgName(b)) problems.push('bundles 里有非法项:' + String(b).slice(0, 60));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return problems;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 入口完整性:只检查「插件自己声明了入口,但那个文件不在」这一种情况。
|
|
47
|
+
* 这是最可靠的损坏信号——下载中断、磁盘写满、杀毒误删都会留下它。
|
|
48
|
+
* require.resolve 失败的原因太多(exports 条件、平台分支、peer 缺失),
|
|
49
|
+
* 拿它当回滚判据会误伤一大片,所以只作 warning。
|
|
50
|
+
*/
|
|
51
|
+
export async function entryProblems(dir, name) {
|
|
52
|
+
const out = [];
|
|
53
|
+
let pj = null;
|
|
54
|
+
try { pj = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')); }
|
|
55
|
+
catch (e) { return [{ code: 'bad-manifest', name, reason: 'package.json 无法解析:' + String((e && e.message) || e).slice(0, 120), severity: 'error' }]; }
|
|
56
|
+
|
|
57
|
+
const targets = [];
|
|
58
|
+
/* strict=false:main/module/browser 本来就是文件路径,"index.js" 与 "./index.js" 等价;
|
|
59
|
+
strict=true(exports):只有 "./" 开头的才是本包文件,其余是外部包引用 */
|
|
60
|
+
const addTarget = (rel, field, strict) => {
|
|
61
|
+
if (typeof rel !== 'string' || !rel) return;
|
|
62
|
+
/* exports 里带 "*" 的是子路径通配符(如 "./locale/*.json"),不是文件名。
|
|
63
|
+
按字面量 existsSync 必然为 false,会把 exports 写得完全正确的插件
|
|
64
|
+
判成「入口缺失」,进而整批回滚——桌面版 v3.3.5 实测有 5 个正常插件因此中招。 */
|
|
65
|
+
if (rel.indexOf('*') >= 0) return;
|
|
66
|
+
if (!strict) { targets.push({ rel, field }); return; }
|
|
67
|
+
if (rel.startsWith('./') || rel.startsWith('/')) targets.push({ rel, field });
|
|
68
|
+
};
|
|
69
|
+
addTarget(pj.main, 'main');
|
|
70
|
+
addTarget(pj.module, 'module');
|
|
71
|
+
addTarget(pj.browser, 'browser');
|
|
72
|
+
const walkExports = (val, field) => {
|
|
73
|
+
if (!val) return;
|
|
74
|
+
if (typeof val === 'string') { addTarget(val, field, true); return; }
|
|
75
|
+
if (Array.isArray(val)) { for (const v of val) walkExports(v, field); return; }
|
|
76
|
+
if (typeof val === 'object') for (const k of Object.keys(val)) walkExports(val[k], field + '.' + k);
|
|
77
|
+
};
|
|
78
|
+
if (pj.exports !== undefined) walkExports(pj.exports, 'exports');
|
|
79
|
+
|
|
80
|
+
for (const t of targets) {
|
|
81
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t.rel)) continue; // data: / http: 之类不是文件
|
|
82
|
+
const rel = t.rel.replace(/^\.\//, '').replace(/^\//, '');
|
|
83
|
+
if (!existsSync(join(dir, ...rel.split('/')))) {
|
|
84
|
+
out.push({ code: 'entry-missing', name, reason: t.field + ' 指向的 ' + t.rel + ' 不存在,DSH 加载该插件会失败', severity: 'error' });
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 从 lockfile 的 importers 段读出直接依赖的解析版本 */
|
|
92
|
+
export async function lockfileImporterVersions(profileDir) {
|
|
93
|
+
try {
|
|
94
|
+
const txt = await readFile(join(profileDir, 'pnpm-lock.yaml'), 'utf8');
|
|
95
|
+
const out = {};
|
|
96
|
+
let inImporters = false, inDeps = false, depIndent = -1, cur = null;
|
|
97
|
+
for (const raw of txt.split(/\r?\n/)) {
|
|
98
|
+
if (/^importers:\s*$/.test(raw)) { inImporters = true; continue; }
|
|
99
|
+
if (inImporters && /^[a-zA-Z]/.test(raw)) { inImporters = false; continue; }
|
|
100
|
+
if (!inImporters) continue;
|
|
101
|
+
if (/^\s+dependencies:\s*$/.test(raw)) { inDeps = true; depIndent = raw.indexOf('dependencies:'); cur = null; continue; }
|
|
102
|
+
if (inDeps && /^\s+(devDependencies|optionalDependencies):\s*$/.test(raw)) { inDeps = false; continue; }
|
|
103
|
+
if (!inDeps) continue;
|
|
104
|
+
const indent = raw.length - raw.trimStart().length;
|
|
105
|
+
const t = raw.trim();
|
|
106
|
+
if (!t) continue;
|
|
107
|
+
if (indent === depIndent + 2 && /^[^:]+:\s*$/.test(t)) { cur = t.slice(0, -1).trim().replace(/^['"]|['"]$/g, ''); continue; }
|
|
108
|
+
if (cur && indent === depIndent + 4) {
|
|
109
|
+
const m = /^version:\s*(.+)$/.exec(t);
|
|
110
|
+
if (m) { out[cur] = m[1].trim().replace(/^['"]|['"]$/g, ''); cur = null; }
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
} catch (e) { return null; }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 完整健康检查。
|
|
119
|
+
* @returns {{ ok, problems: Array<{name,reason,severity,code?}>, checked, ms }}
|
|
120
|
+
*/
|
|
121
|
+
export async function healthCheck(cfg, opts) {
|
|
122
|
+
const t0 = Date.now();
|
|
123
|
+
const problems = [];
|
|
124
|
+
const push = (name, reason, severity, code) => problems.push({ name, reason, severity: severity || 'error', code: code || '' });
|
|
125
|
+
const profileDir = String((cfg && cfg.profileDir) || '');
|
|
126
|
+
|
|
127
|
+
let pkg = null;
|
|
128
|
+
try { pkg = JSON.parse(await readFile(join(profileDir, 'package.json'), 'utf8')); }
|
|
129
|
+
catch (e) {
|
|
130
|
+
return { ok: false, problems: [{ name: 'package.json', reason: '无法读取或解析:' + String((e && e.message) || e), severity: 'error', code: 'bad-manifest' }], checked: 0, ms: Date.now() - t0 };
|
|
131
|
+
}
|
|
132
|
+
for (const p of checkManifestShape(pkg)) push('package.json', p, 'error', 'shape');
|
|
133
|
+
|
|
134
|
+
const deps = (pkg && pkg.dependencies) || {};
|
|
135
|
+
const nm = join(profileDir, 'node_modules');
|
|
136
|
+
|
|
137
|
+
/* 1) 每个声明依赖都要有目录 + 可解析的 package.json */
|
|
138
|
+
let checked = 0;
|
|
139
|
+
for (const name of Object.keys(deps)) {
|
|
140
|
+
if (!isValidPkgName(name)) { push(name, '包名不合法', 'error', 'bad-name'); continue; }
|
|
141
|
+
checked++;
|
|
142
|
+
const dir = join(nm, ...name.split('/'));
|
|
143
|
+
if (!existsSync(dir)) {
|
|
144
|
+
const optional = (pkg.optionalDependencies && pkg.optionalDependencies[name]) || (pkg.peerDependencies && pkg.peerDependencies[name]);
|
|
145
|
+
push(name, optional ? '依赖目录不存在(可选依赖,可忽略)' : '依赖目录不存在', optional ? 'warning' : 'error', 'missing-dir');
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
const pj = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8'));
|
|
150
|
+
if (!pj || typeof pj !== 'object' || !pj.name) push(name, 'package.json 内容异常', 'error', 'bad-pkg');
|
|
151
|
+
} catch (e) {
|
|
152
|
+
push(name, 'package.json 无法解析:' + String((e && e.message) || e).slice(0, 120), 'error', 'bad-pkg');
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/* 2) 入口完整性:只对被启用的 bundle 做,避免整树扫描 */
|
|
157
|
+
const bundles = ((pkg.dsh && pkg.dsh.profile && pkg.dsh.profile.bundles) || []).filter((x) => typeof x === 'string' && isValidPkgName(x));
|
|
158
|
+
const seen = new Set();
|
|
159
|
+
for (const b of bundles) {
|
|
160
|
+
if (seen.has(b)) continue;
|
|
161
|
+
seen.add(b);
|
|
162
|
+
const dir = join(nm, ...b.split('/'));
|
|
163
|
+
if (!existsSync(dir)) continue; // 缺失已在第 1 步记过
|
|
164
|
+
for (const p of await entryProblems(dir, b)) problems.push(p);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/* 3) lockfile 与磁盘版本比对:不一致说明依赖树可疑 */
|
|
168
|
+
const lockVers = await lockfileImporterVersions(profileDir);
|
|
169
|
+
if (lockVers) {
|
|
170
|
+
for (const name of Object.keys(lockVers)) {
|
|
171
|
+
if (!isValidPkgName(name)) continue;
|
|
172
|
+
const dir = join(nm, ...name.split('/'));
|
|
173
|
+
if (!existsSync(dir)) continue;
|
|
174
|
+
let disk = '';
|
|
175
|
+
try { disk = String(JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')).version || ''); } catch (e) { continue; }
|
|
176
|
+
const want = String(lockVers[name]).replace(/^\(/, '').replace(/\)$/, '').split('(')[0].trim();
|
|
177
|
+
if (disk && want && disk !== want && want.indexOf(':') < 0 && !/^file:|^link:/.test(lockVers[name])) {
|
|
178
|
+
push(name, 'lockfile 记为 ' + want + ',磁盘上是 ' + disk, 'warning', 'lock-mismatch');
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const errors = problems.filter((p) => p.severity === 'error');
|
|
184
|
+
return { ok: errors.length === 0, problems, checked, ms: Date.now() - t0 };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** 前后对比:只保留这次新增的问题,避免历史问题反复触发回滚 */
|
|
188
|
+
export function diffHealth(before, after) {
|
|
189
|
+
const key = (p) => p.name + '|' + p.code + '|' + p.reason;
|
|
190
|
+
const seen = new Set(((before && before.problems) || []).map(key));
|
|
191
|
+
return ((after && after.problems) || []).filter((p) => !seen.has(key(p)));
|
|
192
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -28,13 +28,19 @@ import { createSnapshot, listSnapshots, restoreSnapshot } from './snapshot.js';
|
|
|
28
28
|
import { checkUpdates } from './updates.js';
|
|
29
29
|
import { scanPlugins, detectConflicts, priorityOf } from './doctor.js';
|
|
30
30
|
import { mountRoutes } from './routes.js';
|
|
31
|
-
import { runAutoUpdate } from './auto-update.js';
|
|
31
|
+
import { runAutoUpdate, capabilities as autoCapabilities, requestCancel, isRunning } from './auto-update.js';
|
|
32
32
|
import { Logger, dataDir } from './util.js';
|
|
33
33
|
|
|
34
34
|
export const name = 'dsh-plugin-snapshot';
|
|
35
35
|
|
|
36
36
|
export const inject = ['tools'];
|
|
37
37
|
|
|
38
|
+
/** 插件形态的能力声明:与桌面版同名同结构,差异用布尔值表达而非静默行为差异 */
|
|
39
|
+
export function capabilities() { return autoCapabilities(); }
|
|
40
|
+
|
|
41
|
+
/** 供面板/外部调用:请求取消正在跑的自动更新 */
|
|
42
|
+
export function cancelAutoUpdate() { requestCancel(); return { running: isRunning() }; }
|
|
43
|
+
|
|
38
44
|
const TOOL = {
|
|
39
45
|
updates: 'plugin_updates',
|
|
40
46
|
snapshot: 'plugin_snapshot',
|
|
@@ -57,6 +63,16 @@ function makeCtx(config) {
|
|
|
57
63
|
autoUpdate: cfg.autoUpdate === true || String(cfg.autoUpdate).toLowerCase() === 'true',
|
|
58
64
|
autoUpdateScope: cfg.autoUpdateScope || 'patch',
|
|
59
65
|
autoExclude: Array.isArray(cfg.autoExclude) ? cfg.autoExclude : [],
|
|
66
|
+
/* 与桌面版 3.3.5 同名同义:安全等级决定「装什么」,冷却决定「多久内不再自动装」 */
|
|
67
|
+
safetyLevel: ['conservative', 'standard', 'aggressive'].indexOf(String(cfg.safetyLevel || '')) >= 0
|
|
68
|
+
? String(cfg.safetyLevel) : (cfg.allowMajorUpdates === true ? 'standard' : 'conservative'),
|
|
69
|
+
allowMajorUpdates: typeof cfg.allowMajorUpdates === 'boolean' ? cfg.allowMajorUpdates : undefined,
|
|
70
|
+
healthGate: typeof cfg.healthGate === 'boolean' ? cfg.healthGate : undefined,
|
|
71
|
+
autoRollbackOnUnhealthy: typeof cfg.autoRollbackOnUnhealthy === 'boolean' ? cfg.autoRollbackOnUnhealthy : undefined,
|
|
72
|
+
cancelCooldownMin: cfg.cancelCooldownMin == null ? 30 : Math.max(0, Number(cfg.cancelCooldownMin) || 0),
|
|
73
|
+
maxRetries: cfg.maxRetries == null ? 1 : Math.max(0, Number(cfg.maxRetries) || 0),
|
|
74
|
+
retryDelayMs: Number(cfg.retryDelayMs) > 0 ? Number(cfg.retryDelayMs) : 45000,
|
|
75
|
+
frozenPackages: Array.isArray(cfg.frozenPackages) ? cfg.frozenPackages : [],
|
|
60
76
|
logger: new Logger()
|
|
61
77
|
});
|
|
62
78
|
}
|
|
@@ -319,15 +335,41 @@ export function apply(ctx, config) {
|
|
|
319
335
|
避免「装一个快照工具,45 秒后它静默改了整个依赖树」。
|
|
320
336
|
启用后的策略:默认仅补丁版、不自动重启、失败回滚到更新前的快照。 */
|
|
321
337
|
if (cfg.autoUpdate === true) {
|
|
338
|
+
/* 定时点:配置 scheduleTimes: ["10:00","16:00"] 时按点触发;
|
|
339
|
+
没配就沿用「启动后 45 秒跑一次」——两者都要,用户才能选。 */
|
|
340
|
+
const times = Array.isArray(cfg.scheduleTimes)
|
|
341
|
+
? cfg.scheduleTimes.map((x) => String(x).trim()).filter((x) => /^\d{1,2}:\d{2}$/.test(x))
|
|
342
|
+
: [];
|
|
322
343
|
ctx.effect(() => {
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
344
|
+
if (!times.length) {
|
|
345
|
+
const autoTimer = setTimeout(() => {
|
|
346
|
+
runAutoUpdate(cfg, needProfile, cfg.logger).catch(() => {});
|
|
347
|
+
}, 45000);
|
|
348
|
+
return () => clearTimeout(autoTimer);
|
|
349
|
+
}
|
|
350
|
+
let lastKey = '';
|
|
351
|
+
const tick = () => {
|
|
352
|
+
if (isRunning()) return;
|
|
353
|
+
const now = new Date();
|
|
354
|
+
const cur = String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0');
|
|
355
|
+
if (times.indexOf(cur) < 0) return;
|
|
356
|
+
const key = now.toISOString().slice(0, 10) + ' ' + cur;
|
|
357
|
+
if (key === lastKey) return;
|
|
358
|
+
lastKey = key;
|
|
359
|
+
cfg.logger.info('[dsh-plugin-snapshot] 到点触发自动更新 ' + cur);
|
|
360
|
+
runAutoUpdate(cfg, needProfile, cfg.logger).catch((e) => {
|
|
361
|
+
cfg.logger.warn('[dsh-plugin-snapshot] 自动更新异常: ' + String((e && e.message) || e));
|
|
362
|
+
});
|
|
363
|
+
};
|
|
364
|
+
const timer = setInterval(tick, 60000);
|
|
365
|
+
/* 启动时补跑一次:错过时点的机器不必等到明天 */
|
|
366
|
+
const boot = setTimeout(tick, 45000);
|
|
367
|
+
return () => { clearInterval(timer); clearTimeout(boot); };
|
|
327
368
|
}, 'dsh-plugin-snapshot: auto update');
|
|
328
|
-
|
|
369
|
+
cfg.logger.info('[dsh-plugin-snapshot] 自动更新已启用,scope=' + cfg.autoUpdateScope +
|
|
370
|
+
(times.length ? ',定时点 ' + times.join(' / ') : ',启动后 45 秒执行一次'));
|
|
329
371
|
} else {
|
|
330
|
-
|
|
372
|
+
cfg.logger.info('[dsh-plugin-snapshot] 自动更新未启用(配置 autoUpdate: true 可开启)');
|
|
331
373
|
}
|
|
332
374
|
|
|
333
375
|
ctx.logger?.info?.('[dsh-plugin-snapshot] tools registered on ' + needProfileSafe(cfg));
|