mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-27 17:10:23 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da38b51675 | ||
|
|
926397b80b | ||
|
|
e5b69e61dc | ||
|
|
7c43cf789e | ||
|
|
2724bdc02d | ||
|
|
5344d7e1cb | ||
|
|
fee23ac031 | ||
|
|
fd19b7346c | ||
|
|
abba659cfb | ||
|
|
429bad7e18 | ||
|
|
77d61804c8 | ||
|
|
7a78399e0b |
No files matched your search
+2
-7
@@ -24,15 +24,10 @@ function printStatus(state) {
|
||||
out.push(` 注入文件 ${state.override_path}`);
|
||||
out.push(` 注入状态 ${state.override_status}`);
|
||||
out.push("");
|
||||
out.push(` 补丁 ${state.patches_applied}/${core.ALL_PATCHES.length} 已清洗, ${state.patches_pending} 待清洗`
|
||||
+ (state.patches_drifted ? `, ${state.patches_drifted} 漂移(官方原文已改,需更新 pattern)` : ""));
|
||||
if (state.host_version) {
|
||||
const compat = state.host_supported === false ? ` ← 未适配:插件声明 ${state.host_target || "?"}` : "";
|
||||
out.push(` 宿主版本 / host ${state.host_version}${compat}`);
|
||||
}
|
||||
out.push(` 补丁 ${state.patches_applied}/${core.ALL_PATCHES.length} 已清洗, ${state.patches_pending} 待清洗`);
|
||||
for (const p of core.ALL_PATCHES) {
|
||||
const s = state.patch_status[p.id];
|
||||
const mark = s === "applied" ? "✓" : s === "pending" ? "✗" : s === "drifted" ? "!" : "·";
|
||||
const mark = s === "applied" ? "✓" : s === "pending" ? "✗" : "·";
|
||||
out.push(` ${mark} [#${String(p.id).padEnd(2)}] ${p.name.padEnd(30)} ${p.layer}/${p.layer_en} — ${s}`);
|
||||
}
|
||||
out.push("");
|
||||
|
||||
@@ -183,7 +183,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"metric.purged.skip": "已写入。跳过 {n} 项,本机没有这些文件",
|
||||
"metric.pendingShort": "待处理 {n}",
|
||||
"metric.unmatchedShort": "没对上 {n}",
|
||||
"metric.driftedShort": "漂移 {n}",
|
||||
"metric.skipShort": "跳过 {n}",
|
||||
"metric.unlocated.count": "—",
|
||||
"metric.shim": "shim",
|
||||
@@ -197,9 +196,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"status.off": "已关闭",
|
||||
"status.pending": "待应用",
|
||||
"status.unmatched": "没对上",
|
||||
"status.drifted": "已漂移",
|
||||
"status.skipped": "跳过",
|
||||
"apply.hint": "没改提示词框不用点保存,默认就是这份,启动和应用会写进 prompt-inject.md。只有自己改过再点保存才会覆盖。点应用打补丁。待应用=原文还在。跳过=当前版本不需要或组件未安装。漂移=官方原文已改,这条补丁没打上,需要更新 pattern。",
|
||||
"apply.hint": "没改提示词框不用点保存,默认就是这份,启动和应用会写进 prompt-inject.md。只有自己改过再点保存才会覆盖。点应用打补丁。待应用=原文还在。跳过=当前版本不需要或组件未安装。",
|
||||
"flow.title": "清洗流程",
|
||||
"flow.apply": "应用",
|
||||
"flow.revert": "还原",
|
||||
@@ -219,7 +217,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"unpack.restarting": "补丁已写入。点「重启」后客户端会自己重新打开。",
|
||||
"restart.fullQuit": "正在重启,客户端会自己重新打开。",
|
||||
"warn.noInject": "官方始终用默认提示词。红队开了规则集就只用规则集;没开时用去掉 CTF 的默认提示词,再接红队操作。两边都空会提示必须添加。",
|
||||
"warn.hostVersion": "当前宿主是 {v},插件适配的是 {t}。官方原文对不上时补丁会显示「漂移」,建议换回适配的宿主版本。",
|
||||
"need.prompt": "提示词和规则集都是空的,必须先添加提示词,或启用一条有内容的规则集。",
|
||||
"btn.restoreInject": "恢复默认",
|
||||
"saved.restoreInject": "已恢复默认提示词",
|
||||
@@ -544,7 +541,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"metric.purged.skip": "Written. Skipped {n}; those files are not on this install",
|
||||
"metric.pendingShort": "Pending {n}",
|
||||
"metric.unmatchedShort": "No match {n}",
|
||||
"metric.driftedShort": "Drifted {n}",
|
||||
"metric.skipShort": "Skipped {n}",
|
||||
"metric.unlocated.count": "—",
|
||||
"metric.shim": "shim",
|
||||
@@ -558,9 +554,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"status.off": "Off",
|
||||
"status.pending": "Pending",
|
||||
"status.unmatched": "No match",
|
||||
"status.drifted": "Drifted",
|
||||
"status.skipped": "Skipped",
|
||||
"apply.hint": "If you did not edit the prompt box, do not save. The default is already used and is written to prompt-inject.md on start/apply. Save only after you change it. Apply writes host patches. Pending = original text still present. Skipped = not needed for this version or the component is not installed. Drifted = the official source changed, this patch did not land and its pattern needs an update.",
|
||||
"apply.hint": "If you did not edit the prompt box, do not save. The default is already used and is written to prompt-inject.md on start/apply. Save only after you change it. Apply writes host patches. Pending = original text still present. Skipped = not needed for this version or the component is not installed.",
|
||||
"flow.title": "Clean flow",
|
||||
"flow.apply": "Apply",
|
||||
"flow.revert": "Restore",
|
||||
@@ -580,7 +575,6 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"unpack.restarting": "Patches are written. Click Restart and the client opens again by itself.",
|
||||
"restart.fullQuit": "Restarting. The client will open again by itself.",
|
||||
"warn.noInject": "Official mode always uses the default prompt. Red team uses only the active rule set; otherwise it uses the default prompt without the CTF section, then the red team steps. If both are empty you will be asked to add a prompt.",
|
||||
"warn.hostVersion": "This host is {v}, but the plugin targets {t}. When the official source no longer matches, patches show up as “drifted” — switch back to the targeted host version.",
|
||||
"need.prompt": "Both the prompt and the rule set are empty. Add a prompt, or enable a rule that has content.",
|
||||
"btn.restoreInject": "Reset default",
|
||||
"saved.restoreInject": "Default prompt restored",
|
||||
@@ -1158,7 +1152,6 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
if (st === "applied" || st === "already") return "ok";
|
||||
if (st === "pending") return "wait";
|
||||
if (st === "unmatched") return "bad";
|
||||
if (st === "drifted") return "bad";
|
||||
if (st === "na") return "ok";
|
||||
if (st === "missing_file" || st === "skipped" || st === "unlocated" || st === "off") return "miss";
|
||||
return "bad";
|
||||
@@ -1169,7 +1162,6 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
if (st === "off") return t("status.skipped");
|
||||
if (st === "pending") return t("status.pending");
|
||||
if (st === "unmatched") return t("status.unmatched");
|
||||
if (st === "drifted") return t("status.drifted");
|
||||
if (st === "skipped") return t("status.skipped");
|
||||
if (st === "missing_file") return t("skip");
|
||||
if (st === "unlocated") return t("status.unlocated");
|
||||
@@ -1306,13 +1298,12 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
}
|
||||
|
||||
function tallyPatches(rows) {
|
||||
const out = { applied: 0, pending: 0, unmatched: 0, skipped: 0, drifted: 0, total: 0 };
|
||||
const out = { applied: 0, pending: 0, unmatched: 0, skipped: 0, total: 0 };
|
||||
for (const row of rows || []) {
|
||||
out.total += 1;
|
||||
if (row.st === "applied" || row.st === "already") out.applied += 1;
|
||||
else if (row.st === "pending") out.pending += 1;
|
||||
else if (row.st === "unmatched") out.unmatched += 1;
|
||||
else if (row.st === "drifted") out.drifted += 1;
|
||||
else out.skipped += 1;
|
||||
}
|
||||
return out;
|
||||
@@ -1337,7 +1328,6 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
const notes = [];
|
||||
if (tally.pending) notes.push(t("metric.pendingShort", { n: tally.pending }));
|
||||
if (tally.unmatched) notes.push(t("metric.unmatchedShort", { n: tally.unmatched }));
|
||||
if (tally.drifted) notes.push(t("metric.driftedShort", { n: tally.drifted }));
|
||||
if (tally.skipped) notes.push(t("metric.skipShort", { n: tally.skipped }));
|
||||
const expanded = !!open[key];
|
||||
return h("div", { key: key, className: "dshp-group" },
|
||||
@@ -2051,7 +2041,7 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
const desktopLikely = hostSurface === "desktop" || clientGuessSurface() === "desktop";
|
||||
const sealedReady = !located && desktopLikely && !!(s && (s.asar_still_sealed || s.desktop_exe || s.desktop_install));
|
||||
const patchesLost = !located && !!(s && s.patches_lost);
|
||||
const tally = located ? tallyPatches(patchRowsOf(s)) : { applied: 0, pending: 0, unmatched: 0, skipped: 0, drifted: 0, total: 0 };
|
||||
const tally = located ? tallyPatches(patchRowsOf(s)) : { applied: 0, pending: 0, unmatched: 0, skipped: 0, total: 0 };
|
||||
const total = tally.total;
|
||||
const applied = tally.applied;
|
||||
const job = s && s.apply_progress;
|
||||
@@ -2064,7 +2054,6 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
const metricNotes = [];
|
||||
if (tally.pending) metricNotes.push(t("metric.pendingShort", { n: tally.pending }));
|
||||
if (tally.unmatched) metricNotes.push(t("metric.unmatchedShort", { n: tally.unmatched }));
|
||||
if (tally.drifted) metricNotes.push(t("metric.driftedShort", { n: tally.drifted }));
|
||||
if (tally.skipped) metricNotes.push(t("metric.skipShort", { n: tally.skipped }));
|
||||
|
||||
const versions = (updateInfo && updateInfo.versions) || [];
|
||||
@@ -2200,7 +2189,6 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-mute)", fontSize: 12 } }, t("apply.hint")),
|
||||
s && !s.ai_base ? h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-danger, #c44)", fontSize: 12 } }, hostText(t, "warn.noRoot", hostSurface)) : null,
|
||||
s && s.ai_base && s.override_status === "missing" ? h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-mute)", fontSize: 12 } }, t("warn.noInject")) : null,
|
||||
s && s.ai_base && s.host_supported === false ? h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-danger, #c44)", fontSize: 12 } }, t("warn.hostVersion", { v: s.host_version || "?", t: s.host_target || "?" })) : null,
|
||||
askRestart ? h(RestartAsk, {
|
||||
t: t,
|
||||
theme: detectHostTheme(),
|
||||
|
||||
+27
-232
@@ -2304,9 +2304,7 @@ export async function ensureHostClean() {
|
||||
await patchAllShims();
|
||||
const summary = summarizeApplyReport(multi.report);
|
||||
pending = await pendingAcross(allHosts.map((h) => h.aiBase));
|
||||
// 失败就是失败:pattern_not_found 同样是"没打上",以前被过滤掉,
|
||||
// 于是宿主半打状态照样重启,用户只看到一片绿。现在一律当阻断项。
|
||||
const blocking = summary.failed;
|
||||
const blocking = summary.failed.filter((row) => row.status !== "pattern_not_found");
|
||||
const flashOk = allHosts.every((h) => h.flash?.ok === true);
|
||||
if (pending.length || blocking.length || !flashOk) {
|
||||
return {
|
||||
@@ -5150,24 +5148,22 @@ const NEW_TOOL_PATCHES = [
|
||||
skipIfMarked: true,
|
||||
replacements: [
|
||||
{
|
||||
// 不再写死整段 5 行:官方在中间加一行就整条失配
|
||||
// (0.2.1-rc.2 起是 if (this.revised.size > 0) this.revised.clear();,
|
||||
// 0.2.1-rc.3 又改了一次)。
|
||||
// 这里只锚方法头、event 取值、去重判断和结尾的 set,中间用非贪婪窗口吃掉,
|
||||
// 窗口内容原样搬回去 —— 官方再往里加行也不影响。
|
||||
// 窗口里排除 isRewindMarker:打过一次之后正文里就有这个词,
|
||||
// 再不排除的话第二次 apply 会把注入块再插一遍(历史事故:每次 apply 越滚越长)。
|
||||
pattern:
|
||||
/(\t*)append\(record\) \{\n(\t*)const event = record\.event;\n(\t*)if \(this\.inputs\.has\(event\.seq\)\) return "none";\n((?:(?!isRewindMarker)[\s\S]){0,300}?)(\t*)this\.inputs\.set\(event\.seq, record\);\n/g,
|
||||
"\t\t\tappend(record) {\n" +
|
||||
"\t\t\t\tconst event = record.event;\n" +
|
||||
"\t\t\t\tif (this.inputs.has(event.seq)) return \"none\";\n" +
|
||||
"\t\t\t\tthis.revised.clear();\n" +
|
||||
"\t\t\t\tthis.inputs.set(event.seq, record);\n",
|
||||
replace:
|
||||
"$1append(record) {\n" +
|
||||
"$2const event = record.event;\n" +
|
||||
"$3if (this.inputs.has(event.seq)) return \"none\";\n" +
|
||||
"$3if (isRewindMarker(event)) {\n" +
|
||||
"$3\tconst entries = [...this.inputs.values(), record];\n" +
|
||||
"$3\treturn this.replaceWindow(entries, this.hasMore); // [dsh-purge] rewind drops sent messages in this conversation\n" +
|
||||
"$3}\n" +
|
||||
"$4$5this.inputs.set(event.seq, record);\n",
|
||||
"\t\t\tappend(record) {\n" +
|
||||
"\t\t\t\tconst event = record.event;\n" +
|
||||
"\t\t\t\tif (this.inputs.has(event.seq)) return \"none\";\n" +
|
||||
"\t\t\t\tif (isRewindMarker(event)) {\n" +
|
||||
"\t\t\t\t\tconst entries = [...this.inputs.values(), record];\n" +
|
||||
"\t\t\t\t\treturn this.replaceWindow(entries, this.hasMore); // [dsh-purge] rewind drops sent messages in this conversation\n" +
|
||||
"\t\t\t\t}\n" +
|
||||
"\t\t\t\tthis.revised.clear();\n" +
|
||||
"\t\t\t\tthis.inputs.set(event.seq, record);\n",
|
||||
},
|
||||
],
|
||||
markers: ["[dsh-purge] rewind drops sent messages in this conversation"],
|
||||
@@ -5867,8 +5863,6 @@ export function rollupDisplayStatus(statuses) {
|
||||
if (list.length === 0) return "skipped";
|
||||
if (list.some((s) => s === "pending")) return "pending";
|
||||
if (list.some((s) => s === "unmatched")) return "unmatched";
|
||||
// 漂移压过"已完成":一组里只要有一条对不上官方原文,这组就不是干净的。
|
||||
if (list.some((s) => s === "drifted")) return "drifted";
|
||||
if (list.every((s) => DISPLAY_SKIP.has(s))) return "skipped";
|
||||
if (list.some((s) => DISPLAY_DONE.has(s))) return "applied";
|
||||
return "skipped";
|
||||
@@ -5901,7 +5895,7 @@ export function groupPatchesForDisplay(patches = ALL_PATCHES, patch_status = {},
|
||||
}
|
||||
|
||||
export function tallyDisplayPatches(rows) {
|
||||
const out = { applied: 0, pending: 0, unmatched: 0, skipped: 0, drifted: 0, total: 0, ready: 0 };
|
||||
const out = { applied: 0, pending: 0, unmatched: 0, skipped: 0, total: 0, ready: 0 };
|
||||
for (const row of rows || []) {
|
||||
const st = row.status || row.st;
|
||||
out.total += 1;
|
||||
@@ -5910,10 +5904,7 @@ export function tallyDisplayPatches(rows) {
|
||||
out.ready += 1;
|
||||
} else if (st === "pending") out.pending += 1;
|
||||
else if (st === "unmatched") out.unmatched += 1;
|
||||
else if (st === "drifted") {
|
||||
// 漂移不算就绪:这正是"看起来全绿、实际没打上"的来源。
|
||||
out.drifted += 1;
|
||||
} else {
|
||||
else {
|
||||
out.skipped += 1;
|
||||
out.ready += 1;
|
||||
}
|
||||
@@ -6287,83 +6278,6 @@ function packageRootFromAiBase(aiBase) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 宿主版本门禁
|
||||
* 补丁全部靠字面量匹配官方源码,宿主一升级就可能整段失配。这里把"宿主到底是哪个
|
||||
* 版本、我这套 pattern 声明适配哪个版本"变成可比较的事实,供状态页/CLI 直接告警。
|
||||
*/
|
||||
|
||||
/** package.json 里声明的适配版本(唯一的真值来源,历史上前端从未读过它)。 */
|
||||
export const HOST_TARGET = (() => {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
||||
return typeof pkg.dshTarget === "string" ? pkg.dshTarget : "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
})();
|
||||
|
||||
/** "0.2.1-rc.3" → 可比较结构;解析不了返回 null。 */
|
||||
export function parseHostVersion(raw) {
|
||||
const m = String(raw ?? "").trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);
|
||||
if (!m) return null;
|
||||
return {
|
||||
major: Number(m[1]),
|
||||
minor: Number(m[2]),
|
||||
patch: Number(m[3]),
|
||||
pre: m[4] ? m[4].split(".") : [],
|
||||
};
|
||||
}
|
||||
|
||||
/** 这份 package.json 是不是官方宿主自己的?(别把本插件当成宿主) */
|
||||
function looksLikeHostPackage(pkg) {
|
||||
if (!pkg || typeof pkg.version !== "string" || !pkg.version) return false;
|
||||
const name = String(pkg.name || "");
|
||||
if (!name) return false;
|
||||
if (/purge/i.test(name)) return false;
|
||||
return /dsh|deepseek/i.test(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读宿主真实版本。npm 布局里宿主包是 <dsh>/package.json,桌面解包布局同理;
|
||||
* 源码仓库布局(packages/bundle/base)则看版本根的 package.json。
|
||||
*/
|
||||
export function readHostVersion(aiBase) {
|
||||
if (!aiBase) return null;
|
||||
const candidates = [
|
||||
path.join(aiBase, "dsh", "package.json"),
|
||||
path.resolve(aiBase, "..", "..", "package.json"),
|
||||
];
|
||||
const root = packageRootFromAiBase(aiBase);
|
||||
if (root) candidates.push(path.join(root, "package.json"));
|
||||
for (const fp of candidates) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(fp, "utf8"));
|
||||
if (looksLikeHostPackage(pkg)) {
|
||||
return { version: pkg.version, name: String(pkg.name || ""), path: fp };
|
||||
}
|
||||
} catch {
|
||||
/* 换下一个候选 */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比对宿主版本与 dshTarget。
|
||||
* ok === false 表示宿主已经跑在插件自己声明不适配的版本上 —— 此时仍允许 apply,
|
||||
* 但必须让用户看见,而不是靠补丁静默失效去发现。
|
||||
*/
|
||||
export function hostCompat(aiBase, target = HOST_TARGET) {
|
||||
const host = readHostVersion(aiBase);
|
||||
if (!host || !target) return { known: false, ok: null, host: host?.version ?? "", target, path: host?.path ?? "" };
|
||||
const a = parseHostVersion(host.version);
|
||||
const b = parseHostVersion(target);
|
||||
if (!a || !b) return { known: false, ok: null, host: host.version, target, path: host.path };
|
||||
const ok = a.major === b.major && a.minor === b.minor && a.patch === b.patch
|
||||
&& a.pre.join(".") === b.pre.join(".");
|
||||
return { known: true, ok, host: host.version, target, path: host.path };
|
||||
}
|
||||
|
||||
function filterTargetFiles(files) {
|
||||
const out = {};
|
||||
for (const [key, val] of Object.entries(files)) {
|
||||
@@ -6934,15 +6848,11 @@ function filePatchSettled(text, patch, fp = "") {
|
||||
return false;
|
||||
}
|
||||
|
||||
export function filePatchOutcome(text, patch, fp = "") {
|
||||
function filePatchOutcome(text, patch, fp = "") {
|
||||
if (filePatchSettled(text, patch, fp)) return "applied";
|
||||
if (patchHasRemainingWork(text, patch, fp)) return "pending";
|
||||
// 走到这里:文件在、marker 没有、pattern 一条都不中。
|
||||
// pattern 本身就是本插件写进宿主的痕迹(撤销型补丁)→ 本来就没加过,正常,算不用做;
|
||||
// 否则就是官方原文已被改写或搬走 = 上游漂移。以前这种情况一律返回 "skipped"
|
||||
// 并被当成软成功,导致官方升级后插件静默失效、界面却全绿。
|
||||
if (isSelfMarkedPatch(patch)) return "skipped";
|
||||
return "drifted";
|
||||
// 原文对不上、再点应用也变不了:可选/布局软补丁显示跳过,不再假装待应用。
|
||||
return "skipped";
|
||||
}
|
||||
|
||||
function fileKeysOf(p) {
|
||||
@@ -6968,22 +6878,6 @@ function patchReplacements(p) {
|
||||
return (p.patterns ?? []).map((pat) => ({ pattern: pat, replace: p.replace }));
|
||||
}
|
||||
|
||||
/**
|
||||
* pattern 全部是本插件自己写进宿主的痕迹 —— 撤销型/注入型补丁(例如 #80 要撤掉的
|
||||
* "# [dsh-purge] minimal fs tool parity")。这类 pattern 找不到 = 本来就没加过或已撤过,
|
||||
* 属正常,不能算上游漂移;否则每次 apply 都要在状态页刷一堆假告警。
|
||||
*/
|
||||
export function isSelfMarkedPatch(p) {
|
||||
if (!p) return false;
|
||||
const reps = patchReplacements(p);
|
||||
if (!Array.isArray(reps) || reps.length === 0) return false;
|
||||
return reps.every(({ pattern }) => {
|
||||
if (!pattern) return false;
|
||||
const needle = asLf(String(pattern));
|
||||
return needle.includes("[dsh-purge]") || needle.includes("# dsh-purge");
|
||||
});
|
||||
}
|
||||
|
||||
function isBareIdentityNeedle(pattern) {
|
||||
const needle = asLf(pattern);
|
||||
if (!needle) return false;
|
||||
@@ -7046,32 +6940,13 @@ export function applyReplacementsToText(text, patch, fp = "") {
|
||||
const yaml = isYamlPath(fp);
|
||||
let out = asLf(source);
|
||||
let changed = false;
|
||||
for (const rep of patchReplacements(patch)) {
|
||||
const { pattern, replace } = rep;
|
||||
for (const { pattern, replace } of patchReplacements(patch)) {
|
||||
if (!pattern || typeof replace !== "string") continue;
|
||||
// YAML 块标量行首有缩进;无缩进 identity+\n\n 会留下 6 空格,再和下一段拼成 12 空格。
|
||||
if (yaml && isBareIdentityNeedle(pattern)) continue;
|
||||
const written = yaml ? yamlJsCommentsToHash(asLf(replace)) : asLf(replace);
|
||||
// 正则 pattern:用于自匹配型替换(产物包含原 pattern,如 timeoutMs 追加 0)。
|
||||
if (pattern instanceof RegExp) {
|
||||
// 命中数契约对正则同样生效:官方把同一段代码复制成两份时,
|
||||
// 正则会把两处一起改掉 —— 命中数与声明不符就整条拒写。
|
||||
// 0 次命中同样算不符(expect=1 就是"这里必须有一处")。
|
||||
if (typeof rep.expect === "number") {
|
||||
const hits = (out.match(cloneRegExp(pattern, true)) || []).length;
|
||||
if (hits !== rep.expect) {
|
||||
return {
|
||||
text: source,
|
||||
changed: preChanged,
|
||||
hitMismatch: {
|
||||
patch_id: patch?.id,
|
||||
expected: rep.expect,
|
||||
actual: hits,
|
||||
file: fp,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
const re = cloneRegExp(pattern, true);
|
||||
re.lastIndex = 0;
|
||||
if (!re.test(out)) continue;
|
||||
@@ -7084,25 +6959,6 @@ export function applyReplacementsToText(text, patch, fp = "") {
|
||||
continue;
|
||||
}
|
||||
const needle = asLf(pattern);
|
||||
// 命中数契约:补丁显式声明 expect 时,命中数必须完全一致才允许写。
|
||||
// 它同时是"上游又改了"的探针 —— 官方多一处/少一处同名代码都能当场暴露,
|
||||
// 而不是安静地把不相干的第二处一起改掉(split/join 是无上限全量替换)。
|
||||
// 命中 0 次也要算不符:expect=1 就是"这里必须有一处"。
|
||||
if (typeof rep.expect === "number") {
|
||||
const hits = needle ? out.split(needle).length - 1 : 0;
|
||||
if (hits !== rep.expect) {
|
||||
return {
|
||||
text: source,
|
||||
changed: preChanged,
|
||||
hitMismatch: {
|
||||
patch_id: patch?.id,
|
||||
expected: rep.expect,
|
||||
actual: hits,
|
||||
file: fp,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
if (!out.includes(needle)) continue;
|
||||
const next = out.split(needle).join(written);
|
||||
if (next === out) continue;
|
||||
@@ -7113,30 +6969,19 @@ export function applyReplacementsToText(text, patch, fp = "") {
|
||||
return { text: out, changed: changed || preChanged };
|
||||
}
|
||||
|
||||
export function rollupPatchStatus({
|
||||
applied, already, missing, notFound, drifted = 0, lastError, keyCount, layoutSoft, strictFiles,
|
||||
}) {
|
||||
// 写错误优先:以前只在 strictFiles 分支里返回,一个文件写成功就把 EACCES 吞成了绿。
|
||||
if (lastError) return lastError;
|
||||
function rollupPatchStatus({ applied, already, missing, notFound, lastError, keyCount, layoutSoft, strictFiles }) {
|
||||
if (strictFiles && lastError) return lastError;
|
||||
if (strictFiles && notFound > 0) return "pattern_not_found";
|
||||
// 只要有一个文件真的写入,就还算打上了;多文件补丁里个别文件本来就不含这段代码,
|
||||
// 不能因为那种文件报成"半打"而制造假告警。
|
||||
if (applied > 0) return "applied";
|
||||
// 已经落盘过的补丁同理:只剩"这一份文件本来就没有这段代码"时不算漂移。
|
||||
if (already > 0 && (notFound === 0 || layoutSoft)) return "already";
|
||||
// 所有文件都对不上官方原文、也没有本插件留下的痕迹 = 补丁整体漂移。
|
||||
// 以前这种情况会掉进 notFound===0 的分支被当成 skipped(软成功),
|
||||
// 于是官方升级后插件静默失效、状态页全绿 —— 判据在这里被掰正。
|
||||
if (drifted > 0) return "drifted";
|
||||
if (missing === keyCount) return "missing_file";
|
||||
if (lastError) return lastError;
|
||||
// 文件在,但这份原文不在:列表里本来就是跳过,不能再把整次应用判失败。
|
||||
if (notFound === 0) return "skipped";
|
||||
return "pattern_not_found";
|
||||
}
|
||||
|
||||
// 注意:skipped 已从软成功里摘掉 —— 它是"pattern 原文对不上"的旧落点,
|
||||
// 现在这类情况会走 drifted,skipped 只留给真正无需处理的边角。
|
||||
const ALWAYS_SOFT_STATUSES = new Set(["applied", "already", "missing_file", "na", "off"]);
|
||||
const ALWAYS_SOFT_STATUSES = new Set(["applied", "already", "missing_file", "skipped", "na", "off"]);
|
||||
|
||||
export function patchAppliesHere(patch, surface = detectSurface()) {
|
||||
const want = patch?.surfaces;
|
||||
@@ -7153,12 +6998,6 @@ export function isPatchResultSoftOk(row, patch = null) {
|
||||
if (p?.strictFiles && row.status === "pattern_not_found") return false;
|
||||
if (p?.optional && row.status === "pattern_not_found") return true;
|
||||
if (isLayoutSoftPatch(p) && row.status === "pattern_not_found") return true;
|
||||
// skipped 不再天然软成功:只有"可选补丁"或"自标记型(撤销型)补丁"才算当前版本不需要。
|
||||
if (row.status === "skipped") return p?.optional === true || isSelfMarkedPatch(p);
|
||||
// 漂移必须让用户看见(状态页标红、不计入就绪),但不阻断 Apply:
|
||||
// 官方宿主上被更老版本插件打过一遍的补丁,marker 文案对不上就会被误判成漂移,
|
||||
// 拿它去阻断重启会直接把 0.1.6 / 0.2.0 / 0.2.1-rc.2 上的用户堵死。
|
||||
if (row.status === "drifted") return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -7272,8 +7111,6 @@ export async function applyPatches(aiBase, patches = ALL_PATCHES, options = {})
|
||||
let already = 0;
|
||||
let missing = 0;
|
||||
let notFound = 0;
|
||||
let drifted = 0;
|
||||
let selfMarked = 0;
|
||||
let lastError = null;
|
||||
for (const key of keys) {
|
||||
const fps = pathsOf(files, key);
|
||||
@@ -7294,17 +7131,9 @@ export async function applyPatches(aiBase, patches = ALL_PATCHES, options = {})
|
||||
if (preserveClientBundles && isWatchedClientBundle(fp)) {
|
||||
if (filePatchSettled(text, p, fp)) already += 1;
|
||||
else if (patchHasRemainingWork(text, p, fp) || p.strictFiles) notFound += 1;
|
||||
else if (isSelfMarkedPatch(p)) selfMarked += 1;
|
||||
else drifted += 1;
|
||||
continue;
|
||||
}
|
||||
const appliedText = applyReplacementsToText(text, p, fp);
|
||||
// 命中数与补丁声明不符:官方同名代码多了一处/少了一处,宁可整条拒写也不猜。
|
||||
if (appliedText.hitMismatch) {
|
||||
const mm = appliedText.hitMismatch;
|
||||
lastError = `hit_count_mismatch:#${mm.patch_id}:${mm.actual}/${mm.expected}`;
|
||||
continue;
|
||||
}
|
||||
let textOut = appliedText.text;
|
||||
let changed = appliedText.changed;
|
||||
if (isYamlPath(fp)) {
|
||||
@@ -7328,20 +7157,11 @@ export async function applyPatches(aiBase, patches = ALL_PATCHES, options = {})
|
||||
already += 1;
|
||||
} else if (patchHasRemainingWork(text, p, fp) || p.strictFiles) {
|
||||
notFound += 1;
|
||||
} else if (isSelfMarkedPatch(p)) {
|
||||
// pattern 本身是本插件写进宿主的内容(撤销型/注入型补丁,例如 #80 的
|
||||
// "# [dsh-purge] minimal fs tool parity"):它不在 = 本来没加过或已经撤过,
|
||||
// 属于正常,不能当成上游漂移。
|
||||
selfMarked += 1;
|
||||
} else {
|
||||
// 文件在、marker 没有、pattern 一条都不中 —— 官方原文已经被改写或搬走。
|
||||
// 这是必须让用户看见的漂移,不能落进 skipped 软成功。
|
||||
drifted += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
const status = rollupPatchStatus({
|
||||
applied, already, missing, notFound, drifted, lastError, keyCount: keys.length,
|
||||
applied, already, missing, notFound, lastError, keyCount: keys.length,
|
||||
layoutSoft: isLayoutSoftPatch(p),
|
||||
strictFiles: !!p.strictFiles,
|
||||
});
|
||||
@@ -7353,8 +7173,6 @@ export async function applyPatches(aiBase, patches = ALL_PATCHES, options = {})
|
||||
applied,
|
||||
already,
|
||||
missing,
|
||||
drifted,
|
||||
self_marked: selfMarked,
|
||||
});
|
||||
}
|
||||
return report;
|
||||
@@ -7378,8 +7196,6 @@ export function patchWatchedClientBundlesSync(aiBase = findAiBase()) {
|
||||
try {
|
||||
const text = fs.readFileSync(fp, "utf8");
|
||||
const appliedText = applyReplacementsToText(text, p, fp);
|
||||
// 命中数对不上:宁可不写,也不把不相干的第二处一起改掉。
|
||||
if (appliedText.hitMismatch) continue;
|
||||
if (!appliedText.changed) continue;
|
||||
const next = Buffer.from(appliedText.text, "utf8");
|
||||
const current = fs.readFileSync(fp);
|
||||
@@ -7412,7 +7228,6 @@ export async function patchStatus(aiBase, patches = ALL_PATCHES) {
|
||||
let skipped = 0;
|
||||
let unmatched = 0;
|
||||
let missing = 0;
|
||||
let drifted = 0;
|
||||
for (const key of keys) {
|
||||
const fps = pathsOf(files, key);
|
||||
if (fps.length === 0) {
|
||||
@@ -7430,16 +7245,12 @@ export async function patchStatus(aiBase, patches = ALL_PATCHES) {
|
||||
const outcome = filePatchOutcome(text, p, fp);
|
||||
if (outcome === "applied") applied += 1;
|
||||
else if (outcome === "pending") pending += 1;
|
||||
// 漂移优先于严格补丁口径:严格补丁的文件宿主一定在,原文对不上
|
||||
// 只可能是官方改了文案(= 上游漂移),报 drifted 比报 unmatched 更有指向性。
|
||||
else if (outcome === "drifted") drifted += 1;
|
||||
else if (p.strictFiles) unmatched += 1;
|
||||
else skipped += 1;
|
||||
}
|
||||
}
|
||||
if (pending > 0) status[p.id] = "pending";
|
||||
else if (applied > 0) status[p.id] = "applied";
|
||||
else if (drifted > 0) status[p.id] = "drifted";
|
||||
else if (unmatched > 0) status[p.id] = "unmatched";
|
||||
else if (skipped > 0) status[p.id] = "skipped";
|
||||
else status[p.id] = p.optional ? "na" : "missing_file";
|
||||
@@ -8297,12 +8108,8 @@ export function editOverride(dshHome) {
|
||||
/** 列表上的“已就绪”:已写入、或当前版本不需要 / 组件未装(与 apply 的 soft-ok 对齐)。 */
|
||||
export function patchStatusReady(status, patch = null) {
|
||||
if (status === "applied" || status === "already" || status === "off") return true;
|
||||
if (status === "missing_file") return true;
|
||||
if (status === "skipped" || status === "missing_file") return true;
|
||||
if (status === "na") return false;
|
||||
// 上游漂移:可选补丁不阻断"已就绪",但状态本身会在列表里标出来,不再被当成做完了。
|
||||
if (status === "drifted") return patch?.optional === true;
|
||||
// skipped 不再天然就绪:只有可选补丁(或自标记型撤销补丁)才算"当前版本不需要"。
|
||||
if (status === "skipped") return patch?.optional === true || isSelfMarkedPatch(patch);
|
||||
if (status === "pattern_not_found" && patch?.strictFiles) return false;
|
||||
if (status === "pattern_not_found" && patch?.optional) return true;
|
||||
return false;
|
||||
@@ -8313,16 +8120,11 @@ export async function gatherState() {
|
||||
const aiBase = findAiBase();
|
||||
const shimDir = findShimDir();
|
||||
const desktop_runtimes = listDesktopCommandRuntimeDirs();
|
||||
const hostInfo = aiBase
|
||||
? hostCompat(aiBase)
|
||||
: { known: false, ok: null, host: "", target: HOST_TARGET };
|
||||
const host_version = hostInfo.host || "";
|
||||
const files = aiBase ? targetFiles(aiBase) : {};
|
||||
const patch_status = aiBase ? await patchStatus(aiBase) : {};
|
||||
let patches_applied = 0;
|
||||
let patches_pending = 0;
|
||||
let patches_skipped = 0;
|
||||
let patches_drifted = 0;
|
||||
let patches_ready = 0;
|
||||
let patches_na = 0;
|
||||
let patches_total = 0;
|
||||
@@ -8340,7 +8142,6 @@ export async function gatherState() {
|
||||
patches_total += 1;
|
||||
if (s === "applied") patches_applied += 1;
|
||||
if (s === "pending") patches_pending += 1;
|
||||
if (s === "drifted") patches_drifted += 1;
|
||||
if (s === "skipped" || s === "missing_file" || s === "off") patches_skipped += 1;
|
||||
if (patchStatusReady(s, p)) patches_ready += 1;
|
||||
}
|
||||
@@ -8381,19 +8182,13 @@ export async function gatherState() {
|
||||
patches_applied,
|
||||
patches_pending,
|
||||
patches_skipped,
|
||||
patches_drifted,
|
||||
patches_ready,
|
||||
patches_na,
|
||||
patches_total,
|
||||
host_version,
|
||||
host_target: hostInfo.target || "",
|
||||
host_supported: hostInfo.ok !== false,
|
||||
host_compat_known: hostInfo.known === true,
|
||||
display_patches,
|
||||
display_applied: displayTally.applied,
|
||||
display_pending: displayTally.pending,
|
||||
display_skipped: displayTally.skipped,
|
||||
display_drifted: displayTally.drifted ?? 0,
|
||||
display_ready: displayTally.ready,
|
||||
display_total: displayTally.total,
|
||||
has_backup: aiBase ? await hasBackup(aiBase) : false,
|
||||
|
||||
+2
-14
@@ -164,18 +164,10 @@ function renderStatus(state) {
|
||||
? state.display_patches
|
||||
: core.groupPatchesForDisplay(core.ALL_PATCHES, state.patch_status || {});
|
||||
const displayTally = core.tallyDisplayPatches(displayRows);
|
||||
out.push(`补丁 / patches: ${displayTally.applied}/${displayTally.total || 0} applied, ${displayTally.pending} pending`
|
||||
+ (displayTally.drifted ? `, ${displayTally.drifted} drifted(官方原文已改,需更新 pattern)` : ""));
|
||||
if (state.host_version) {
|
||||
const supported = state.host_supported !== false;
|
||||
const compat = supported
|
||||
? ""
|
||||
: ` ← 未适配:插件声明 ${state.host_target || "?"}`;
|
||||
out.push(`宿主 / host: ${state.host_version}${compat}`);
|
||||
}
|
||||
out.push(`补丁 / patches: ${displayTally.applied}/${displayTally.total || 0} applied, ${displayTally.pending} pending`);
|
||||
for (const row of displayRows) {
|
||||
const s = row.status || "n/a";
|
||||
const mark = s === "applied" ? "✓" : s === "pending" ? "✗" : s === "drifted" ? "!" : "·";
|
||||
const mark = s === "applied" ? "✓" : s === "pending" ? "✗" : "·";
|
||||
const patch = core.ALL_PATCHES.find((item) => item.id === row.id);
|
||||
const label = patch ? patch.name : `patch-${row.id}`;
|
||||
const layer = patch ? `${patch.layer}/${patch.layer_en}` : row.layer || "";
|
||||
@@ -1907,13 +1899,9 @@ function installWebServer(ctx, cfg) {
|
||||
patches_applied: state.ai_base ? (state.display_applied ?? state.patches_applied) : 0,
|
||||
patches_pending: state.display_pending ?? state.patches_pending,
|
||||
patches_skipped: state.display_skipped ?? state.patches_skipped ?? 0,
|
||||
patches_drifted: state.display_drifted ?? state.patches_drifted ?? 0,
|
||||
patches_ready: state.display_ready ?? state.patches_ready ?? 0,
|
||||
patches_na: state.patches_na || 0,
|
||||
patches_total: state.ai_base ? (state.display_total ?? state.patches_total ?? 0) : 0,
|
||||
host_version: state.host_version || "",
|
||||
host_target: state.host_target || "",
|
||||
host_supported: state.host_supported !== false,
|
||||
patches_lost: reapply.patchesLostAfterHostReset(),
|
||||
patch_status: state.patch_status,
|
||||
patches: (state.display_patches || []).map((p) => ({
|
||||
|
||||
+69
-82
@@ -1,11 +1,8 @@
|
||||
/**
|
||||
* 用户层 profile/cordis.patch.yml 的本体 insert(#154 / #159 / #191)。
|
||||
* 用户层 profile/cordis.patch.yml 的本体 insert(#154 / #159)。
|
||||
*
|
||||
* 包内 overlay 只改已入队行的 inject/config,不能再 insert 一次(Hub 已入队会
|
||||
* already queued)。postinstall 和演练台子行都走这里:行不存在就写一条。
|
||||
*
|
||||
* #191:文件本身是一个完整文档时(宿主生成的空 flow 序列 `[]`),不能再追加,
|
||||
* 追加会变成第二个文档,宿主启动解析失败。
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
@@ -50,52 +47,6 @@ export function profileHasPurgeBodyInsert(text) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 cordis.patch.yml 的数据部分形态(#191)。
|
||||
*
|
||||
* 宿主生成的 profile 层 patch 文件可能整体只有一个空 flow 序列 `[]`,
|
||||
* 那是**一个完整 YAML 文档**。往文件尾追加 `- insert:` 会变成第二个文档,
|
||||
* 宿主启动解析报 "end of the stream or a document separator is expected"。
|
||||
*
|
||||
* 只看最后一个文档的根节点类型(追加内容落在最后一个文档里):
|
||||
* - "empty" 没有数据行(空文件 / 只有注释和空行)
|
||||
* - "empty-flow" 数据部分恰好是空 flow 序列 `[]`(可带 `---` 前缀)
|
||||
* - "block-seq" 正常块序列(顶层 `- ...`),沿用旧的追加行为
|
||||
* - "flow-seq" 非空 flow 序列(宿主/用户内容,动不得)
|
||||
* - "unknown" 其它形态(顶层映射等),认不准就不写
|
||||
*/
|
||||
export function classifyPatchBody(text) {
|
||||
const lines = String(text || "").replace(/\r\n/g, "\n").split("\n");
|
||||
const dataLines = [];
|
||||
for (let i = 0; i < lines.length; i += 1) {
|
||||
const trimmed = lines[i].trim();
|
||||
if (!trimmed) continue; // 空行
|
||||
if (trimmed.startsWith("#")) continue; // 注释行
|
||||
dataLines.push({ index: i, trimmed });
|
||||
}
|
||||
// 按 `---` 切成多个文档,只看最后一个(追加内容会落在最后一个文档里)
|
||||
const lastDoc = [];
|
||||
for (const item of dataLines) {
|
||||
if (item.trimmed === "---") {
|
||||
lastDoc.length = 0;
|
||||
continue;
|
||||
}
|
||||
lastDoc.push(item);
|
||||
}
|
||||
if (lastDoc.length === 0) return { kind: "empty", lines };
|
||||
// 空 flow 序列:`[]` / `[ ]`,允许行尾注释
|
||||
if (lastDoc.length === 1 && /^\[\s*\]\s*(#.*)?$/.test(lastDoc[0].trimmed)) {
|
||||
return { kind: "empty-flow", lines, emptyFlowIndex: lastDoc[0].index };
|
||||
}
|
||||
if (lastDoc[0].trimmed.startsWith("[")) return { kind: "flow-seq", lines };
|
||||
if (/^-(\s|$)/.test(lastDoc[0].trimmed)) {
|
||||
// 块序列里混进顶层 flow 序列 → 本身就是坏 YAML,认不准就不动
|
||||
if (lastDoc.slice(1).some((item) => item.trimmed.startsWith("["))) return { kind: "unknown", lines };
|
||||
return { kind: "block-seq", lines };
|
||||
}
|
||||
return { kind: "unknown", lines };
|
||||
}
|
||||
|
||||
export function ensureProfileBodyInsert(profileDir) {
|
||||
const fp = path.join(profileDir, "cordis.patch.yml");
|
||||
let text = "";
|
||||
@@ -103,23 +54,6 @@ export function ensureProfileBodyInsert(profileDir) {
|
||||
if (profileHasPurgeBodyInsert(text)) {
|
||||
return { ok: true, wrote: false, path: fp };
|
||||
}
|
||||
const shape = classifyPatchBody(text);
|
||||
if (shape.kind === "empty-flow") {
|
||||
// `[]` 本身是一个完整文档:把整行替换成 insert 块,绝不追加成第二个文档(#191)
|
||||
const blockLines = INSERT_BLOCK.replace(/\n$/, "").split("\n");
|
||||
const out = [
|
||||
...shape.lines.slice(0, shape.emptyFlowIndex),
|
||||
...blockLines,
|
||||
...shape.lines.slice(shape.emptyFlowIndex + 1),
|
||||
].join("\n");
|
||||
fs.writeFileSync(fp, `${out.endsWith("\n") ? out : `${out}\n`}`, "utf8");
|
||||
return { ok: true, wrote: true, path: fp };
|
||||
}
|
||||
if (shape.kind === "flow-seq" || shape.kind === "unknown") {
|
||||
// 宿主 / 用户自己的内容,宁可不动也别写坏(#191)
|
||||
return { ok: false, wrote: false, path: fp };
|
||||
}
|
||||
// 空文件 / 只有注释 → 直接写 insert 块;正常块序列 → 沿用旧的追加行为
|
||||
const prefix = text && !text.endsWith("\n") ? "\n" : "";
|
||||
fs.writeFileSync(fp, `${text}${prefix}${text ? "\n" : ""}${INSERT_BLOCK}`, "utf8");
|
||||
return { ok: true, wrote: true, path: fp };
|
||||
@@ -171,18 +105,73 @@ export function ensureProfileBundles(profileDir) {
|
||||
return { ok: true, wrote: true, path: fp };
|
||||
}
|
||||
|
||||
function readPkgTarball() {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
||||
return String(pkg?.dsh?.install?.tarball || "").trim();
|
||||
} catch {
|
||||
return "https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* pnpm allowBuilds 期望键(#185)。
|
||||
*
|
||||
* 只写裸包名 `dsh-purge`:pnpm 的 allowBuilds 按包名匹配,tarball / git / registry
|
||||
* 三种安装形态都放行。而 `dsh-purge@https://...` 这类键在 pnpm 11(DSH 内置
|
||||
* 11.2.2)会被 semver 解析器当成版本联合,直接报
|
||||
* `[ERR_PNPM_INVALID_VERSION_UNION] Invalid versions union` 让 install 崩掉。
|
||||
*
|
||||
* profileDir 参数只为兼容旧调用保留,实际不再需要(#185)。
|
||||
* 从 profile 的 pnpm-lock.yaml 读 dsh-purge 实际解析到的 tarball URL(#180)。
|
||||
* 用户用 `github:user/repo#<commit>` 固定 commit 安装时,lock 里记录的是
|
||||
* `.../tar.gz/<commit>`,写死 master URL 会和实际键并存成两个 URL 键。
|
||||
* 简单文本/正则解析即可,不引 yaml 依赖;读不到返回空串。
|
||||
*/
|
||||
function readPurgeTarballFromLock(profileDir) {
|
||||
if (!profileDir) return "";
|
||||
let text = "";
|
||||
try {
|
||||
text = fs.readFileSync(path.join(profileDir, "pnpm-lock.yaml"), "utf8");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
const lines = String(text || "").replace(/\r\n/g, "\n").split("\n");
|
||||
let inImporters = false;
|
||||
for (let i = 0; i < lines.length; i += 1) {
|
||||
const line = lines[i];
|
||||
if (/^\S/.test(line)) {
|
||||
if (inImporters) break; // 已扫过 importers,遇到下一个顶层键就结束
|
||||
inImporters = /^importers[ \t]*:/.test(line);
|
||||
continue;
|
||||
}
|
||||
if (!inImporters) continue;
|
||||
const entry = line.match(/^([ \t]+)dsh-purge[ \t]*:[ \t]*$/);
|
||||
if (!entry) continue;
|
||||
const indent = entry[1].length;
|
||||
// 收集该条目下的 specifier / version 行,直到缩进回到条目本身
|
||||
let specifier = "";
|
||||
let version = "";
|
||||
for (let j = i + 1; j < lines.length; j += 1) {
|
||||
const sub = lines[j];
|
||||
if (sub.trim() && (sub.match(/^[ \t]*/) || [""])[0].length <= indent) break;
|
||||
const sm = sub.match(/^[ \t]+(specifier|version)[ \t]*:[ \t]*(.*)$/);
|
||||
if (!sm) continue;
|
||||
let value = String(sm[2] || "").trim();
|
||||
// 掉引号:pnpm-lock 里带引号与否取决于内容
|
||||
if (/^(["']).*\1[ \t]*$/.test(value)) value = value.slice(1, -1).trim();
|
||||
if (sm[1] === "specifier") specifier = value;
|
||||
else version = value;
|
||||
}
|
||||
// version 是实际解析结果,优先;specifier 只是没有 URL 化版本时兜底
|
||||
for (const candidate of [version, specifier]) {
|
||||
const url = String(candidate || "").match(/https?:\/\/[^\s'"]+/);
|
||||
if (url) return url[0];
|
||||
}
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/** pnpm 12 会给 tarball 单独写一行 `dsh-purge@https://...: set this to true or false`。只写包名不够。 */
|
||||
export function purgePnpmBuildSpecs(profileDir) {
|
||||
return [PURGE_NAME];
|
||||
const specs = ["dsh-purge"];
|
||||
// 期望键和实际安装形态一致:lock 里解析到的 URL > package.json 的 tarball > 只用裸包名
|
||||
const tarball = readPurgeTarballFromLock(profileDir) || readPkgTarball();
|
||||
if (tarball) specs.push(`${PURGE_NAME}@${tarball}`);
|
||||
return specs;
|
||||
}
|
||||
|
||||
function isPurgeAllowBuildKey(key) {
|
||||
@@ -262,12 +251,10 @@ export function validateAllowBuildRewrite(text) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 dsh-purge 写成 true,避免装别的插件还报 ERR_PNPM_IGNORED_BUILDS(#168)。
|
||||
*
|
||||
* #185:只写裸包名。`dsh-purge@https://...` 这类键在 pnpm 11 会被当成版本联合,
|
||||
* 直接触发 ERR_PNPM_INVALID_VERSION_UNION 让 install 崩掉。
|
||||
* 自愈时所有 `dsh-purge@*` 历史键(URL 键、旧截断键 `dsh-purge@https`、
|
||||
* `@1.1.81` 之类版本键)一律丢弃,只保留裸包名;非 purge 键原样保留。
|
||||
* 把 dsh-purge 以及 `dsh-purge@tarball` 都写成 true,避免装别的插件还报 ERR_PNPM_IGNORED_BUILDS(#168)。
|
||||
* profileDir 可选:给了就从该 profile 的 pnpm-lock.yaml 读实际 tarball URL(#180)。
|
||||
* 期望键精确命中的才保留;其它一切 `dsh-purge@*` 历史键(畸形 `dsh-purge@https`、过期版本/commit URL)一律丢弃,
|
||||
* 让旧的污染文件在下一次 ensure 时自动清干净。
|
||||
*/
|
||||
export function rewritePnpmAllowBuilds(raw, profileDir) {
|
||||
const wanted = purgePnpmBuildSpecs(profileDir);
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dsh-purge",
|
||||
"version": "1.1.83",
|
||||
"version": "1.1.82",
|
||||
"description": "DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model — swap prompts per model. 求 Star 收藏 ⭐ 如要二开,请查看署名要求部分",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
|
||||
@@ -1,29 +1,3 @@
|
||||
# 1.1.83
|
||||
|
||||
## 中文
|
||||
|
||||
- 版本 **1.1.83**。修复 bug,修复稳定性。
|
||||
- **#185**:修复 pnpm 11(DSH 内置 11.2.2)下 `pnpm install` 因 `allowBuilds` 崩溃的问题。
|
||||
- 之前 profile 的 `pnpm-workspace.yaml` 会写入 `dsh-purge@https://...` 这类 URL 键,pnpm 把它当版本联合解析,直接报 `[ERR_PNPM_INVALID_VERSION_UNION] Invalid versions union`。
|
||||
- 现在只写裸包名 `dsh-purge`:pnpm 的 `allowBuilds` 本来就按包名匹配,tarball / git / registry 三种安装形态都放行。
|
||||
- 自愈加强:所有 `dsh-purge@*` 历史键(URL 键、旧截断键 `dsh-purge@https`、`@1.1.81` 之类版本键)一律清掉,只保留裸包名;非 dsh-purge 的键原样保留。
|
||||
- **#191**:修复 macOS DSH Desktop(0.2.1-rc.4)启动崩溃 `failed to parse overlay .../cordis.patch.yml`。
|
||||
- 宿主生成的 profile 层 `cordis.patch.yml` 可能整体只有一个空 flow 序列 `[]`,那本身就是一个完整 YAML 文档;再往文件尾追加 `- insert:` 会变成第二个文档,宿主解析直接失败。
|
||||
- 现在写之前先判断数据部分形态:空 flow 序列(`[]`,可带 `---` 前缀)→ **替换** `[]` 整行而不是追加;空文件 / 只有注释 → 直接写 insert 块;正常块序列 → 沿用原来的追加行为。
|
||||
- 非空 flow 序列(宿主或用户自己的内容)认不准就不动,返回 `{ ok: false, wrote: false }`,宁可留着也不写坏。
|
||||
|
||||
## English
|
||||
|
||||
- **1.1.83**. Bug fixes and stability.
|
||||
- **#185**: fix `pnpm install` crashing under pnpm 11 (11.2.2, bundled with DSH) because of `allowBuilds`.
|
||||
- The profile `pnpm-workspace.yaml` used to get a `dsh-purge@https://...` URL key, which pnpm parses as a version union and rejects with `[ERR_PNPM_INVALID_VERSION_UNION] Invalid versions union`.
|
||||
- Now only the bare package name `dsh-purge` is written: pnpm matches `allowBuilds` by package name, so tarball / git / registry installs are all allowed.
|
||||
- Stronger self-healing: every `dsh-purge@*` legacy key (URL keys, truncated `dsh-purge@https`, `@1.1.81`-style version keys) is dropped and only the bare name is kept; non-dsh-purge keys are preserved as-is.
|
||||
- **#191**: fix the macOS DSH Desktop (0.2.1-rc.4) startup crash `failed to parse overlay .../cordis.patch.yml`.
|
||||
- The host-generated profile `cordis.patch.yml` may consist of a single empty flow sequence `[]`, which is already a complete YAML document; appending `- insert:` after it creates a second document and the host fails to parse it.
|
||||
- The data shape is now detected before writing: an empty flow sequence (`[]`, optionally `---`-prefixed) → **replace** the `[]` line instead of appending; empty file / comments only → write the insert block; a normal block sequence → the previous append behaviour is kept.
|
||||
- A non-empty flow sequence (host or user content) is left alone and returns `{ ok: false, wrote: false }` — better to skip than to write something broken.
|
||||
|
||||
# 1.1.82
|
||||
|
||||
## 中文
|
||||
|
||||
@@ -51,9 +51,6 @@ function ensureProfileInsert(profileDir) {
|
||||
const result = ensureProfileBodyInsert(profileDir);
|
||||
if (result.wrote) {
|
||||
process.stdout.write(`dsh-purge: wrote body insert (${result.path})\n`);
|
||||
} else if (result.ok === false) {
|
||||
// 宿主 / 用户自己的 cordis.patch.yml 内容,宁可不动也别写坏(#191)
|
||||
process.stdout.write(`dsh-purge: skipped body insert, unrecognized patch body (${result.path})\n`);
|
||||
} else {
|
||||
process.stdout.write(`dsh-purge: insert already in ${result.path}\n`);
|
||||
}
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
ALL_PATCHES,
|
||||
applyReplacementsToText,
|
||||
filePatchOutcome,
|
||||
isPatchResultSoftOk,
|
||||
isSelfMarkedPatch,
|
||||
parseHostVersion,
|
||||
patchStatusReady,
|
||||
rollupDisplayStatus,
|
||||
rollupPatchStatus,
|
||||
tallyDisplayPatches,
|
||||
} from "../lib/core.js";
|
||||
|
||||
const base = {
|
||||
applied: 0,
|
||||
already: 0,
|
||||
missing: 0,
|
||||
notFound: 0,
|
||||
drifted: 0,
|
||||
lastError: null,
|
||||
keyCount: 1,
|
||||
layoutSoft: false,
|
||||
strictFiles: false,
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 判据:上游漂移必须显性,不能落成 skipped(软成功)。
|
||||
* 这是"官方升级后插件静默失效、状态页却全绿"的唯一入口。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("rollupPatchStatus: 文件在、原文对不上 → drifted 而不是 skipped", () => {
|
||||
assert.equal(rollupPatchStatus({ ...base, drifted: 1 }), "drifted");
|
||||
});
|
||||
|
||||
test("rollupPatchStatus: pattern 还在 → pattern_not_found(可以打)", () => {
|
||||
assert.equal(rollupPatchStatus({ ...base, notFound: 1 }), "pattern_not_found");
|
||||
});
|
||||
|
||||
test("rollupPatchStatus: 有文件真的写成功就仍算 applied,不制造半打假告警", () => {
|
||||
assert.equal(rollupPatchStatus({ ...base, applied: 1, drifted: 1 }), "applied");
|
||||
});
|
||||
|
||||
test("rollupPatchStatus: 已经落盘过的补丁仍算 already,不因个别文件漂移翻红", () => {
|
||||
// 多文件补丁里个别文件本来就不含这段代码(另一个构建产物),
|
||||
// 这种"假漂移"不能盖掉已经打上的部分。
|
||||
assert.equal(rollupPatchStatus({ ...base, already: 1, drifted: 1 }), "already");
|
||||
});
|
||||
|
||||
test("rollupPatchStatus: 写错误优先于 applied,不能把 EACCES 吞成绿", () => {
|
||||
assert.equal(
|
||||
rollupPatchStatus({ ...base, applied: 1, lastError: "write_error:EACCES" }),
|
||||
"write_error:EACCES",
|
||||
);
|
||||
});
|
||||
|
||||
test("rollupPatchStatus: 文件全缺 → missing_file", () => {
|
||||
assert.equal(rollupPatchStatus({ ...base, missing: 1 }), "missing_file");
|
||||
});
|
||||
|
||||
test("filePatchOutcome: 文件在、marker 没有、pattern 一条都不中 → drifted", () => {
|
||||
const patch = { id: 9801, replacements: [{ pattern: "NEEDLE_NOT_THERE", replace: "x" }] };
|
||||
assert.equal(filePatchOutcome("host text", patch, ""), "drifted");
|
||||
});
|
||||
|
||||
test("filePatchOutcome: marker 在 → applied(不算漂移)", () => {
|
||||
const patch = {
|
||||
id: 9802,
|
||||
markers: ["[dsh-purge] marker"],
|
||||
replacements: [{ pattern: "NEEDLE_NOT_THERE", replace: "x" }],
|
||||
};
|
||||
assert.equal(filePatchOutcome("host [dsh-purge] marker text", patch, ""), "applied");
|
||||
});
|
||||
|
||||
test("filePatchOutcome: pattern 还在 → pending", () => {
|
||||
const patch = { id: 9803, replacements: [{ pattern: "NEEDLE", replace: "x" }] };
|
||||
assert.equal(filePatchOutcome("a NEEDLE b", patch, ""), "pending");
|
||||
});
|
||||
|
||||
test("自标记型补丁:pattern 就是本插件留下的痕迹,找不到 = 本来没加过,不算漂移", () => {
|
||||
const patch = {
|
||||
id: 9804,
|
||||
replacements: [{ pattern: "- id: tool-fs # [dsh-purge] minimal fs tool parity", replace: "x" }],
|
||||
};
|
||||
assert.equal(isSelfMarkedPatch(patch), true);
|
||||
assert.equal(filePatchOutcome("host text", patch, ""), "skipped");
|
||||
});
|
||||
|
||||
test("自标记型判定:普通补丁不算自标记,#80 算", () => {
|
||||
assert.equal(isSelfMarkedPatch({ id: 9805, replacements: [{ pattern: "const a = 1;", replace: "x" }] }), false);
|
||||
const p80 = ALL_PATCHES.find((p) => p.id === 80);
|
||||
assert.ok(p80, "找不到 #80");
|
||||
assert.equal(isSelfMarkedPatch(p80), true);
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 就绪口径:drifted 必须让"已就绪"变红(可选补丁不阻断 apply,但状态仍在)。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("patchStatusReady: drifted 的非可选补丁不算就绪", () => {
|
||||
assert.equal(patchStatusReady("drifted", { optional: false }), false);
|
||||
});
|
||||
|
||||
test("patchStatusReady: drifted 的可选补丁不阻断就绪", () => {
|
||||
assert.equal(patchStatusReady("drifted", { optional: true }), true);
|
||||
});
|
||||
|
||||
test("patchStatusReady: applied / already 算就绪", () => {
|
||||
assert.equal(patchStatusReady("applied"), true);
|
||||
assert.equal(patchStatusReady("already"), true);
|
||||
});
|
||||
|
||||
test("patchStatusReady: pending 不算就绪", () => {
|
||||
assert.equal(patchStatusReady("pending"), false);
|
||||
});
|
||||
|
||||
test("patchStatusReady: skipped 不再天然就绪,可选补丁仍然就绪", () => {
|
||||
assert.equal(patchStatusReady("skipped", { optional: false }), false);
|
||||
assert.equal(patchStatusReady("skipped", { optional: true }), true);
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 展示层统计:drifted 不能被算进 ready。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("tallyDisplayPatches: drifted 不计入 ready", () => {
|
||||
const out = tallyDisplayPatches([
|
||||
{ status: "applied" },
|
||||
{ status: "drifted" },
|
||||
{ status: "skipped" },
|
||||
]);
|
||||
assert.equal(out.applied, 1);
|
||||
assert.equal(out.drifted, 1);
|
||||
assert.equal(out.ready, 2, "只有 applied + skipped 计入 ready");
|
||||
});
|
||||
|
||||
test("rollupDisplayStatus: 一组里只要有一条漂移,这组就不是干净绿", () => {
|
||||
assert.equal(rollupDisplayStatus(["applied", "drifted"]), "drifted");
|
||||
assert.equal(rollupDisplayStatus(["applied", "applied"]), "applied");
|
||||
assert.equal(rollupDisplayStatus(["pending", "drifted"]), "pending");
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 软成功口径:skipped 不再天然软成功;drifted 看得见但不阻断 Apply。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("isPatchResultSoftOk: skipped 只有可选/自标记型才算软成功", () => {
|
||||
assert.equal(isPatchResultSoftOk({ status: "skipped" }, { id: 1, optional: false }), false);
|
||||
assert.equal(isPatchResultSoftOk({ status: "skipped" }, { id: 2, optional: true }), true);
|
||||
});
|
||||
|
||||
test("isPatchResultSoftOk: drifted 不阻断 Apply(兼容 0.1.6 / 0.2.0 / 0.2.1-rc.2)", () => {
|
||||
assert.equal(isPatchResultSoftOk({ status: "drifted" }, { id: 3, optional: false }), true);
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 幂等:二次应用不得继续增长(历史事故是每次 apply +841 字符、永不收敛)。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("applyReplacementsToText: 全部字面量 pattern 二次应用不叠加", () => {
|
||||
const offenders = [];
|
||||
for (const p of ALL_PATCHES) {
|
||||
const reps = (p.replacements || []).filter((r) => r.pattern && !(r.pattern instanceof RegExp));
|
||||
if (reps.length === 0) continue;
|
||||
// 用 pattern 本体合成输入:保证第一遍一定命中,从而真正检验收敛性。
|
||||
const src = reps.map((r) => String(r.pattern)).join("\n");
|
||||
const once = applyReplacementsToText(src, p, "");
|
||||
const twice = applyReplacementsToText(once.text, p, "");
|
||||
if (twice.text !== once.text) offenders.push(`#${p.id} ${p.name}`);
|
||||
}
|
||||
assert.deepEqual(offenders, [], `这些补丁二次应用还在变:${offenders.join(", ")}`);
|
||||
});
|
||||
|
||||
test("applyReplacementsToText: 没有残留 pattern 时 changed=false", () => {
|
||||
const patch = { id: 9901, replacements: [{ pattern: "NOT_PRESENT_ANYWHERE", replace: "x" }] };
|
||||
const r = applyReplacementsToText("hello world", patch, "");
|
||||
assert.equal(r.changed, false);
|
||||
assert.equal(r.text, "hello world");
|
||||
});
|
||||
|
||||
test("#77 锚点容错:官方在中间插一行也照样命中,且二次应用不叠加", () => {
|
||||
const p77 = ALL_PATCHES.find((p) => p.id === 77);
|
||||
assert.ok(p77, "找不到 #77");
|
||||
// 0.2.1-rc.2 起的官方原文:中间多了一行 revised.clear()
|
||||
const host =
|
||||
"\t\t\tappend(record) {\n" +
|
||||
"\t\t\t\tconst event = record.event;\n" +
|
||||
"\t\t\t\tif (this.inputs.has(event.seq)) return \"none\";\n" +
|
||||
"\t\t\t\tif (this.revised.size > 0) this.revised.clear();\n" +
|
||||
"\t\t\t\tthis.inputs.set(event.seq, record);\n";
|
||||
const once = applyReplacementsToText(host, p77, "");
|
||||
assert.equal(once.changed, true, "rc.2 的原文应当命中");
|
||||
assert.ok(once.text.includes("isRewindMarker(event)"), "应当注入回退判断");
|
||||
assert.ok(once.text.includes("if (this.revised.size > 0) this.revised.clear();"), "官方那行必须原样保留");
|
||||
const twice = applyReplacementsToText(once.text, p77, "");
|
||||
assert.equal(twice.text, once.text, "二次应用不得再插一遍");
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 命中数契约:官方同名代码多一处就该拒写,而不是把两处一起改掉。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("applyReplacementsToText: expect 命中数不符时拒写并回传实际命中数", () => {
|
||||
const patch = { id: 9902, replacements: [{ pattern: "NEEDLE", replace: "X", expect: 1 }] };
|
||||
const r = applyReplacementsToText("NEEDLE NEEDLE", patch, "");
|
||||
assert.ok(r.hitMismatch, "应当回传 hitMismatch");
|
||||
assert.equal(r.hitMismatch.expected, 1);
|
||||
assert.equal(r.hitMismatch.actual, 2);
|
||||
assert.equal(r.text, "NEEDLE NEEDLE", "拒写时原文必须原样返回");
|
||||
assert.equal(r.changed, false);
|
||||
});
|
||||
|
||||
test("applyReplacementsToText: expect 命中数一致时正常替换", () => {
|
||||
const patch = { id: 9903, replacements: [{ pattern: "NEEDLE", replace: "X", expect: 1 }] };
|
||||
const r = applyReplacementsToText("a NEEDLE b", patch, "");
|
||||
assert.equal(r.hitMismatch, undefined);
|
||||
assert.equal(r.text, "a X b");
|
||||
});
|
||||
|
||||
test("applyReplacementsToText: expect=1 但一处都没命中也算不符(不许静默跳过)", () => {
|
||||
const patch = { id: 9905, replacements: [{ pattern: "NEEDLE", replace: "X", expect: 1 }] };
|
||||
const r = applyReplacementsToText("nothing here", patch, "");
|
||||
assert.ok(r.hitMismatch, "0 次命中同样是失配");
|
||||
assert.equal(r.hitMismatch.actual, 0);
|
||||
assert.equal(r.changed, false);
|
||||
});
|
||||
|
||||
test("applyReplacementsToText: 未声明 expect 时保持旧行为(全量替换)", () => {
|
||||
const patch = { id: 9904, replacements: [{ pattern: "N", replace: "X" }] };
|
||||
const r = applyReplacementsToText("N N", patch, "");
|
||||
assert.equal(r.hitMismatch, undefined);
|
||||
assert.equal(r.text, "X X");
|
||||
});
|
||||
|
||||
test("applyReplacementsToText: 正则 pattern 的 expect 同样生效(官方复制成两份就拒写)", () => {
|
||||
const patch = { id: 9906, replacements: [{ pattern: /NEEDLE/g, replace: "X", expect: 1 }] };
|
||||
const r = applyReplacementsToText("NEEDLE NEEDLE", patch, "");
|
||||
assert.ok(r.hitMismatch, "正则也必须遵守命中数契约");
|
||||
assert.equal(r.hitMismatch.actual, 2);
|
||||
assert.equal(r.text, "NEEDLE NEEDLE", "拒写时原文必须原样返回");
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 宿主版本门禁
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("parseHostVersion: 拆出主次修订与预发布段", () => {
|
||||
assert.deepEqual(parseHostVersion("0.2.1-rc.3"), {
|
||||
major: 0, minor: 2, patch: 1, pre: ["rc", "3"],
|
||||
});
|
||||
assert.equal(parseHostVersion("not-a-version"), null);
|
||||
assert.deepEqual(parseHostVersion("v1.2.3"), { major: 1, minor: 2, patch: 3, pre: [] });
|
||||
});
|
||||
+27
-155
@@ -10,9 +10,6 @@ import {
|
||||
purgePnpmBuildSpecs,
|
||||
rewritePnpmAllowBuilds,
|
||||
ensurePnpmAllowBuild,
|
||||
ensureProfileBodyInsert,
|
||||
classifyPatchBody,
|
||||
INSERT_BLOCK,
|
||||
} from "../lib/profile-insert.js";
|
||||
|
||||
const MASTER_URL = "https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master";
|
||||
@@ -26,26 +23,6 @@ function withTempProfile(lockText) {
|
||||
return dir;
|
||||
}
|
||||
|
||||
function withTempPatch(content) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dsh-purge-patch-"));
|
||||
if (content !== undefined) {
|
||||
fs.writeFileSync(path.join(dir, "cordis.patch.yml"), content, "utf8");
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
/** 去掉注释和空行后,统计顶层 `- insert:` 组数(判定是不是第二个文档)。 */
|
||||
function topLevelInsertGroups(text) {
|
||||
const lines = String(text || "").split(/\r?\n/);
|
||||
let count = 0;
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith("#")) continue;
|
||||
if (/^-\s*insert:\s*$/.test(line)) count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
test("URL 键解析不被冒号截断", () => {
|
||||
const parsed = parseAllowBuildLine(` dsh-purge@${MASTER_URL}: true`);
|
||||
assert.equal(parsed.key, `dsh-purge@${MASTER_URL}`);
|
||||
@@ -109,7 +86,7 @@ test("污染的 allowBuilds 重写后只剩期望键", () => {
|
||||
].join("\n");
|
||||
const next = rewritePnpmAllowBuilds(polluted);
|
||||
const keys = next.split("\n").filter((line) => parseAllowBuildLine(line)).map((line) => parseAllowBuildLine(line).key);
|
||||
// 期望键:只有裸包名(#185,不再写 URL 键)
|
||||
// 期望键:裸包名 + package.json 的 tarball(本仓库装的是 master tarball,无 profileDir 时)
|
||||
const wanted = ["cpu-features", "ssh2", ...purgePnpmBuildSpecs()];
|
||||
assert.deepEqual([...new Set(keys)], wanted);
|
||||
// 畸形历史键一个都不留
|
||||
@@ -145,10 +122,7 @@ test("写前校验:重复顶层键 / 重复 allowBuilds 键 / 解析不了的
|
||||
assert.equal(validateAllowBuildRewrite("allowBuilds:\n# 注释行放行\n ssh2: true\n"), true);
|
||||
});
|
||||
|
||||
test("期望键只有裸包名,不含任何 URL 键(#185)", () => {
|
||||
// pnpm 11 遇到 `dsh-purge@https://...` 会报 ERR_PNPM_INVALID_VERSION_UNION,
|
||||
// allowBuilds 按包名匹配即可,tarball / git / registry 安装都放行
|
||||
assert.deepEqual(purgePnpmBuildSpecs(), ["dsh-purge"]);
|
||||
test("pnpm-lock.yaml 里的 commit URL 优先于 master", () => {
|
||||
const dir = withTempProfile([
|
||||
"lockfileVersion: '9.0'",
|
||||
"",
|
||||
@@ -161,25 +135,29 @@ test("期望键只有裸包名,不含任何 URL 键(#185)", () => {
|
||||
` version: dsh-purge@${COMMIT_URL}`,
|
||||
"",
|
||||
].join("\n"));
|
||||
assert.deepEqual(purgePnpmBuildSpecs(dir), ["dsh-purge"]);
|
||||
const specs = purgePnpmBuildSpecs(dir);
|
||||
assert.deepEqual(specs, ["dsh-purge", `dsh-purge@${COMMIT_URL}`]);
|
||||
});
|
||||
|
||||
test("输入只含 URL 键时重写后只剩裸包名", () => {
|
||||
const onlyUrl = [
|
||||
"allowBuilds:",
|
||||
` "dsh-purge@${MASTER_URL}": true`,
|
||||
` dsh-purge@${MASTER_URL}: true`,
|
||||
test("lock 读不到(旧 master 记录 / 无文件)退回 package.json tarball", () => {
|
||||
// 无 pnpm-lock.yaml 的临时目录 → 只用裸包名兜底逻辑应落到 package.json 的 master URL
|
||||
const dir = withTempProfile();
|
||||
assert.deepEqual(purgePnpmBuildSpecs(dir), ["dsh-purge", `dsh-purge@${MASTER_URL}`]);
|
||||
// lock 里 specifier 写死 master,也如实保留
|
||||
const dir2 = withTempProfile([
|
||||
"importers:",
|
||||
"",
|
||||
].join("\n");
|
||||
const next = rewritePnpmAllowBuilds(onlyUrl);
|
||||
const keys = next.split("\n").filter((line) => parseAllowBuildLine(line)).map((line) => parseAllowBuildLine(line).key);
|
||||
assert.deepEqual(keys, ["dsh-purge"]);
|
||||
assert.equal(next.includes("dsh-purge@"), false);
|
||||
assert.equal(next.split("\n").some((line) => line === " dsh-purge: true"), true);
|
||||
assert.equal(validateAllowBuildRewrite(next), true);
|
||||
" .:",
|
||||
" dependencies:",
|
||||
" dsh-purge:",
|
||||
" specifier: https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master",
|
||||
" version: '1.1.81'",
|
||||
"",
|
||||
].join("\n"));
|
||||
assert.deepEqual(purgePnpmBuildSpecs(dir2), ["dsh-purge", `dsh-purge@${MASTER_URL}`]);
|
||||
});
|
||||
|
||||
test("固定 commit 安装:重写后只剩裸包名,历史 URL / 畸形键全清", () => {
|
||||
test("固定 commit 安装:重写后过期 master 键被换成 commit 键", () => {
|
||||
const dir = withTempProfile([
|
||||
"lockfileVersion: '9.0'",
|
||||
"",
|
||||
@@ -199,19 +177,17 @@ test("固定 commit 安装:重写后只剩裸包名,历史 URL / 畸形键
|
||||
"allowBuilds:",
|
||||
" ssh2: true",
|
||||
` dsh-purge@${MASTER_URL}: true`,
|
||||
` "dsh-purge@${COMMIT_URL}": true`,
|
||||
" dsh-purge@https: true",
|
||||
"",
|
||||
].join("\n");
|
||||
const next = rewritePnpmAllowBuilds(polluted, dir);
|
||||
const keys = next.split("\n").filter((line) => parseAllowBuildLine(line)).map((line) => parseAllowBuildLine(line).key);
|
||||
assert.equal(keys.includes("dsh-purge"), true);
|
||||
assert.equal(keys.includes(`dsh-purge@${COMMIT_URL}`), false);
|
||||
assert.equal(keys.includes(`dsh-purge@${COMMIT_URL}`), true);
|
||||
assert.equal(keys.includes(`dsh-purge@${MASTER_URL}`), false);
|
||||
assert.equal(keys.includes("dsh-purge@https"), false);
|
||||
assert.equal(keys.includes("ssh2"), true);
|
||||
// 只写裸包名,不带引号
|
||||
assert.equal(next.split("\n").some((line) => line === " dsh-purge: true"), true);
|
||||
// URL 键写回带引号,可被 yaml 解析方安全读取
|
||||
assert.equal(next.split("\n").some((line) => line === ` "dsh-purge@${COMMIT_URL}": true`), true);
|
||||
});
|
||||
|
||||
test("幂等:健康文件重写输出等于输入,零写入", () => {
|
||||
@@ -224,7 +200,8 @@ test("幂等:健康文件重写输出等于输入,零写入", () => {
|
||||
"allowBuilds:",
|
||||
" cpu-features: true",
|
||||
" ssh2: true",
|
||||
" dsh-purge: true",
|
||||
' dsh-purge: true',
|
||||
` "dsh-purge@${MASTER_URL}": true`,
|
||||
"",
|
||||
].join("\n");
|
||||
fs.writeFileSync(fp, healthy, "utf8");
|
||||
@@ -246,115 +223,10 @@ test("幂等:第二次 ensure 不再写盘(自愈后收敛)", () => {
|
||||
const first = ensurePnpmAllowBuild(dir);
|
||||
assert.equal(first.wrote, true);
|
||||
const healed = fs.readFileSync(fp, "utf8");
|
||||
// 畸形历史键被清掉
|
||||
assert.equal(healed.includes("dsh-purge@https"), false);
|
||||
// 畸形历史键被清掉(URL 键带引号重写,不会留下这些裸键)
|
||||
assert.equal(healed.includes("dsh-purge@https: true"), false);
|
||||
assert.equal(healed.includes("dsh-purge@1.1.81"), false);
|
||||
// 只剩裸包名
|
||||
assert.equal(healed.includes(" dsh-purge: true"), true);
|
||||
const second = ensurePnpmAllowBuild(dir);
|
||||
assert.equal(second.wrote, false);
|
||||
assert.equal(fs.readFileSync(fp, "utf8"), healed);
|
||||
});
|
||||
|
||||
// ---- #191:cordis.patch.yml 是 `[]` 时追加会导致宿主启动解析失败 ----
|
||||
|
||||
test("patch 形态分类:空 / 空 flow / 块序列 / 非空 flow / 未知", () => {
|
||||
assert.equal(classifyPatchBody("").kind, "empty");
|
||||
assert.equal(classifyPatchBody("# 只有注释\n\n").kind, "empty");
|
||||
assert.equal(classifyPatchBody("[]").kind, "empty-flow");
|
||||
assert.equal(classifyPatchBody("# c\n[]\n").kind, "empty-flow");
|
||||
assert.equal(classifyPatchBody("---\n[]\n").kind, "empty-flow");
|
||||
assert.equal(classifyPatchBody("- id: foo\n name: foo\n").kind, "block-seq");
|
||||
assert.equal(classifyPatchBody("[a, b]\n").kind, "flow-seq");
|
||||
assert.equal(classifyPatchBody("foo: bar\n").kind, "unknown");
|
||||
});
|
||||
|
||||
test("空文件:直接写 insert 块", () => {
|
||||
const dir = withTempPatch(undefined);
|
||||
const fp = path.join(dir, "cordis.patch.yml");
|
||||
const result = ensureProfileBodyInsert(dir);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.wrote, true);
|
||||
assert.equal(fs.readFileSync(fp, "utf8"), INSERT_BLOCK);
|
||||
});
|
||||
|
||||
test("只有注释和空行:写 insert 块,注释保留", () => {
|
||||
const dir = withTempPatch("# overrides, disables, and insertions\n\n");
|
||||
const fp = path.join(dir, "cordis.patch.yml");
|
||||
const result = ensureProfileBodyInsert(dir);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.wrote, true);
|
||||
const text = fs.readFileSync(fp, "utf8");
|
||||
assert.equal(text.includes("# overrides, disables, and insertions"), true);
|
||||
assert.equal(text.includes("- insert:"), true);
|
||||
assert.equal(topLevelInsertGroups(text), 1);
|
||||
});
|
||||
|
||||
test("注释 + `[]`:`[]` 被替换成 insert 块,注释保留,无第二个文档", () => {
|
||||
const dir = withTempPatch("# overrides, disables, and insertions\n[]\n");
|
||||
const fp = path.join(dir, "cordis.patch.yml");
|
||||
const result = ensureProfileBodyInsert(dir);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.wrote, true);
|
||||
const text = fs.readFileSync(fp, "utf8");
|
||||
assert.equal(text.includes("[]"), false);
|
||||
assert.equal(text.includes("# overrides, disables, and insertions"), true);
|
||||
assert.equal(text.includes("- insert:"), true);
|
||||
// 只有一个顶层 `- insert:` 组 → 没有变成第二个文档
|
||||
assert.equal(topLevelInsertGroups(text), 1);
|
||||
});
|
||||
|
||||
test("`---` 前缀 + `[]`:同样替换,无第二个文档", () => {
|
||||
const dir = withTempPatch("---\n[]\n");
|
||||
const fp = path.join(dir, "cordis.patch.yml");
|
||||
const result = ensureProfileBodyInsert(dir);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.wrote, true);
|
||||
const text = fs.readFileSync(fp, "utf8");
|
||||
assert.equal(text.includes("[]"), false);
|
||||
assert.equal(topLevelInsertGroups(text), 1);
|
||||
});
|
||||
|
||||
test("正常块序列:沿用旧的追加行为", () => {
|
||||
const original = "- id: foo\n name: foo\n";
|
||||
const dir = withTempPatch(original);
|
||||
const fp = path.join(dir, "cordis.patch.yml");
|
||||
const result = ensureProfileBodyInsert(dir);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.wrote, true);
|
||||
const text = fs.readFileSync(fp, "utf8");
|
||||
assert.equal(text.startsWith(original), true);
|
||||
assert.equal(text.includes("- insert:"), true);
|
||||
assert.equal(topLevelInsertGroups(text), 1);
|
||||
});
|
||||
|
||||
test("非空 flow 序列:宿主内容不动,返回 ok:false", () => {
|
||||
const original = "[a, b]\n";
|
||||
const dir = withTempPatch(original);
|
||||
const fp = path.join(dir, "cordis.patch.yml");
|
||||
const result = ensureProfileBodyInsert(dir);
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.wrote, false);
|
||||
assert.equal(fs.readFileSync(fp, "utf8"), original);
|
||||
});
|
||||
|
||||
test("已有 dsh-purge 本体行:零写入", () => {
|
||||
const original = "- insert:\n - id: dsh-purge\n name: dsh-purge\n";
|
||||
const dir = withTempPatch(original);
|
||||
const fp = path.join(dir, "cordis.patch.yml");
|
||||
const result = ensureProfileBodyInsert(dir);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.wrote, false);
|
||||
assert.equal(fs.readFileSync(fp, "utf8"), original);
|
||||
});
|
||||
|
||||
test("`[]` 替换后幂等:再 ensure 一次零写入", () => {
|
||||
const dir = withTempPatch("# c\n[]\n");
|
||||
const fp = path.join(dir, "cordis.patch.yml");
|
||||
const first = ensureProfileBodyInsert(dir);
|
||||
assert.equal(first.wrote, true);
|
||||
const healed = fs.readFileSync(fp, "utf8");
|
||||
const second = ensureProfileBodyInsert(dir);
|
||||
assert.equal(second.wrote, false);
|
||||
assert.equal(fs.readFileSync(fp, "utf8"), healed);
|
||||
});
|
||||
Reference in new issue
Block a user