dsh-postbox 0.0.0-stage → 0.2.2
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/LICENSE +21 -0
- package/README.md +531 -2
- package/client.js +2717 -0
- package/cordis.patch.yml +83 -0
- package/docs/DETAIL.md +56 -0
- package/icon.svg +1 -0
- package/index.js +2312 -0
- package/lib/backend-sqlite.js +65 -0
- package/lib/bridge.js +940 -0
- package/lib/config.js +289 -0
- package/lib/digest.js +213 -0
- package/lib/errors.js +83 -0
- package/lib/ft.js +211 -0
- package/lib/host-settings.js +237 -0
- package/lib/imap.js +635 -0
- package/lib/importance.js +83 -0
- package/lib/llm.js +411 -0
- package/lib/log.js +75 -0
- package/lib/mime.js +381 -0
- package/lib/mutf7.js +54 -0
- package/lib/notify.js +328 -0
- package/lib/oauth.js +275 -0
- package/lib/schema.js +177 -0
- package/lib/search.js +129 -0
- package/lib/settings.js +395 -0
- package/lib/smtp.js +153 -0
- package/lib/store.js +1068 -0
- package/lib/sync.js +899 -0
- package/lib/tool.js +232 -0
- package/lib/tools-m4.js +863 -0
- package/lib/update.js +642 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +60 -4
package/lib/ft.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
// lib/ft.js — M5 全文检索:分词 + 倒排 + 打分。
|
|
2
|
+
//
|
|
3
|
+
// **纯函数,零依赖**(不碰 fs / sqlite / IMAP):这样它能被离线测试集直接喂字符串,
|
|
4
|
+
// 命中率与排序都能在 `node test/run.mjs` 里量出来,而不是靠"上线看一眼感觉还行"。
|
|
5
|
+
//
|
|
6
|
+
// ── 分词策略(为什么是这个)────────────────────────────────────────────────────
|
|
7
|
+
// · **CJK 用二元(bigram)**:中文没有词边界,零依赖下没有比二元更稳的折中
|
|
8
|
+
// (单字切分噪声太大、词典分词要维护几万个词条)。单字也一并入索引,否则
|
|
9
|
+
// 「搜一个字」永远 0 命中;但单字的字段权重砍半,靠 idf 自然压下去。
|
|
10
|
+
// · **latin/数字用词**:长度 ≥2,查小停用词表(标题里的 "the/and/for" 全是噪声)。
|
|
11
|
+
// · 全角 → 半角后再小写:用户从中文输入法里敲的 HTTP 也要能命中 http。
|
|
12
|
+
//
|
|
13
|
+
// ── 字段权重(ROADMAP M5):subject > from > attachment-text > to > body ────────
|
|
14
|
+
// 权重列 `tokens.weight` = 字段权重 × min(词频, 5)(封顶 48),所以一条记录就能
|
|
15
|
+
// 同时表达"出现在哪个字段"和"出现了几次",不需要 positions 列。
|
|
16
|
+
//
|
|
17
|
+
// ── 打分(可解释、够用)──────────────────────────────────────────────────────
|
|
18
|
+
// df 按**消息数**去重统计(同一词在 subject 和 body 各一行,不能算两篇文档),
|
|
19
|
+
// idf = ln(1 + (N - df + 0.5)/(df + 0.5)),单条贡献 = idf × (1 + ln(1 + weight))。
|
|
20
|
+
// 排序键:命中词覆盖率 → 分数 → ref(稳定)。**AND 优先**:先把全词命中的挑出来,
|
|
21
|
+
// 一个都没有才退回 OR 结果(并把 partial 标出来,让工具如实告诉用户)。
|
|
22
|
+
|
|
23
|
+
/** 查询词上限:再多也没意义,而且 SQL 的 IN 列表要控制长度。 */
|
|
24
|
+
export const MAX_TERMS = 24;
|
|
25
|
+
/** 字段权重(越大越"像标题")。body/attachment 只在 full 模式下入索引。 */
|
|
26
|
+
export const FIELD_WEIGHTS = { subject: 5, from: 4, to: 3, attachment: 2, body: 1 };
|
|
27
|
+
/** 文本类附件才纳入索引(PDF 文字层是开放问题,见 ROADMAP §8-2)。 */
|
|
28
|
+
export const TEXT_ATTACHMENT_TYPES = [
|
|
29
|
+
"text/plain", "text/html", "text/csv", "text/markdown", "text/tab-separated-values",
|
|
30
|
+
"application/json", "application/xml", "text/xml",
|
|
31
|
+
];
|
|
32
|
+
/** 单个词条权重封顶(字段权重 5 × 词频 5 = 25;留够余量但不让一个词压死全部)。 */
|
|
33
|
+
const MAX_WEIGHT = 48;
|
|
34
|
+
const MAX_TF = 5;
|
|
35
|
+
|
|
36
|
+
const STOP = new Set([
|
|
37
|
+
"the", "and", "for", "are", "but", "not", "you", "your", "with", "this", "that", "from",
|
|
38
|
+
"have", "has", "was", "were", "will", "would", "can", "could", "should", "about", "into",
|
|
39
|
+
"our", "their", "them", "they", "his", "her", "its", "it", "is", "of", "to", "in", "on",
|
|
40
|
+
"at", "by", "or", "as", "be", "an", "if", "we", "he", "she", "do", "does", "did", "so",
|
|
41
|
+
// 中文虚词(以单字形式进索引时才有意义;这里只是让检索词更像"实词")
|
|
42
|
+
"的了在是有和就不都一个上也很到说要去你会着没有看",
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
/** 全角 → 半角 + 小写。仅用于匹配,**不改动落库的原文**。 */
|
|
46
|
+
export function normalize(input) {
|
|
47
|
+
return String(input ?? "")
|
|
48
|
+
.replace(/[\uff01-\uff5e]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0xfee0))
|
|
49
|
+
.replace(/\u3000/g, " ")
|
|
50
|
+
.toLowerCase();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const LATIN = /[a-z0-9]+/g;
|
|
54
|
+
const CJK = /[\u3400-\u9fff\uf900-\ufaff\u3040-\u30ff]+/g;
|
|
55
|
+
const CJK_CHAR = /[\u3400-\u9fff\uf900-\ufaff\u3040-\u30ff]/;
|
|
56
|
+
|
|
57
|
+
/** 文本 → Map(词 → 出现次数)。索引侧用(单字 + 二元都收)。 */
|
|
58
|
+
export function tokensOf(text) {
|
|
59
|
+
const counts = new Map();
|
|
60
|
+
const s = normalize(text);
|
|
61
|
+
const bump = (t) => counts.set(t, (counts.get(t) ?? 0) + 1);
|
|
62
|
+
for (const m of s.matchAll(LATIN)) {
|
|
63
|
+
const w = m[0];
|
|
64
|
+
if (w.length >= 2 && !STOP.has(w)) bump(w);
|
|
65
|
+
}
|
|
66
|
+
for (const m of s.matchAll(CJK)) {
|
|
67
|
+
const run = m[0];
|
|
68
|
+
for (const ch of run) bump(ch); // 单字:保证「搜一个字」有结果
|
|
69
|
+
for (let i = 0; i + 2 <= run.length; i++) bump(run.slice(i, i + 2)); // 二元:主力
|
|
70
|
+
}
|
|
71
|
+
return counts;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 查询 → 词条数组(去重,保持顺序)。**只取二元,不取单字**(避免"银"命中一切)。 */
|
|
75
|
+
export function queryTerms(input) {
|
|
76
|
+
const out = [];
|
|
77
|
+
const s = normalize(input);
|
|
78
|
+
for (const m of s.matchAll(LATIN)) {
|
|
79
|
+
const w = m[0];
|
|
80
|
+
if (w.length >= 2 && !STOP.has(w)) out.push(w);
|
|
81
|
+
}
|
|
82
|
+
for (const m of s.matchAll(CJK)) {
|
|
83
|
+
const run = m[0];
|
|
84
|
+
if (run.length === 1) out.push(run);
|
|
85
|
+
else for (let i = 0; i + 2 <= run.length; i++) out.push(run.slice(i, i + 2));
|
|
86
|
+
}
|
|
87
|
+
return [...new Set(out)].slice(0, MAX_TERMS);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const weightOf = (base, tf) => Math.max(1, Math.min(MAX_WEIGHT, base * Math.min(tf, MAX_TF)));
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 一封邮件 → 倒排词条。
|
|
94
|
+
* @param msg { subject, from, to, snippet, body, attachments:[{name,contentType,text}] }
|
|
95
|
+
* @param opts.withBody 只在 `archive.mode=full` 时为 true(metadata 模式**不**把正文入索引,
|
|
96
|
+
* 否则等于把正文以"词集合"的形式留在库里,和"metadata 不落正文"自相矛盾)。
|
|
97
|
+
*/
|
|
98
|
+
export function indexFields(msg = {}, { withBody = false } = {}) {
|
|
99
|
+
const out = [];
|
|
100
|
+
const push = (field, text) => {
|
|
101
|
+
if (!text) return;
|
|
102
|
+
const base = FIELD_WEIGHTS[field] ?? 1;
|
|
103
|
+
for (const [token, tf] of tokensOf(text)) {
|
|
104
|
+
// 单字是"兜底"而不是主力:权重砍半,靠 idf 压住
|
|
105
|
+
const b = token.length === 1 && CJK_CHAR.test(token) ? Math.max(1, Math.round(base / 2)) : base;
|
|
106
|
+
out.push({ token, field, weight: weightOf(b, tf) });
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
push("subject", msg.subject);
|
|
110
|
+
push("from", msg.from);
|
|
111
|
+
push("to", Array.isArray(msg.to) ? msg.to.join(" ") : msg.to);
|
|
112
|
+
if (withBody) {
|
|
113
|
+
push("body", msg.body || msg.snippet);
|
|
114
|
+
const list = Array.isArray(msg.attachments) ? msg.attachments : [];
|
|
115
|
+
for (const att of list) {
|
|
116
|
+
if (!att) continue;
|
|
117
|
+
const ct = String(att.contentType ?? "").split(";")[0].trim().toLowerCase();
|
|
118
|
+
if (!TEXT_ATTACHMENT_TYPES.includes(ct)) continue;
|
|
119
|
+
push("attachment", `${att.name ?? ""} ${att.text ?? ""}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 从 parseMime 的 attachments 里挑出文本类附件并解码(其它类型直接跳过)。 */
|
|
126
|
+
export function textAttachments(attachments = []) {
|
|
127
|
+
const out = [];
|
|
128
|
+
for (const att of attachments) {
|
|
129
|
+
if (!att?.payload) continue;
|
|
130
|
+
const ct = String(att.contentType ?? "").split(";")[0].trim().toLowerCase();
|
|
131
|
+
if (!TEXT_ATTACHMENT_TYPES.includes(ct)) continue;
|
|
132
|
+
try { out.push({ name: att.name ?? null, contentType: ct, text: att.payload.toString("utf8") }); }
|
|
133
|
+
catch { /* 解不开就跳过:索引少一段,不拖垮整轮抓取 */ }
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** idf。N=索引里的消息总数,df=含该词的消息数。 */
|
|
139
|
+
export function idfFor(df, total) {
|
|
140
|
+
const N = Math.max(Number(total) || 0, 1);
|
|
141
|
+
const d = Math.max(Number(df) || 0, 0);
|
|
142
|
+
return Math.log(1 + (N - d + 0.5) / (d + 0.5));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export const refKeyOf = (r) => `${r?.account ?? ""}\u0000${r?.folder ?? ""}\u0000${r?.uid ?? ""}`;
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* 倒排行 → 排序好的命中列表。
|
|
149
|
+
* @param rows [{token,account,folder,uid,field,weight}](直接来自 tokens 表)
|
|
150
|
+
* @param terms 查询词条(queryTerms 的输出)
|
|
151
|
+
* @returns { hits, exact, terms, total, perTerm }
|
|
152
|
+
* hits 按 覆盖率 → 分数 → ref 排序
|
|
153
|
+
* exact 只含覆盖全部词条的消息(AND 结果)
|
|
154
|
+
* perTerm 每个词命中的消息数(诊断"哪个词太冷")
|
|
155
|
+
*/
|
|
156
|
+
export function rankRows(rows = [], terms = [], { total = 0 } = {}) {
|
|
157
|
+
const wanted = new Set(terms);
|
|
158
|
+
const dfSets = new Map();
|
|
159
|
+
const per = new Map();
|
|
160
|
+
|
|
161
|
+
for (const r of rows) {
|
|
162
|
+
if (!r || !wanted.has(r.token)) continue;
|
|
163
|
+
const key = refKeyOf(r);
|
|
164
|
+
if (!dfSets.has(r.token)) dfSets.set(r.token, new Set());
|
|
165
|
+
dfSets.get(r.token).add(key);
|
|
166
|
+
if (!per.has(key)) {
|
|
167
|
+
per.set(key, { ref: { account: r.account, folder: r.folder, uid: r.uid }, tokens: new Map(), byField: {} });
|
|
168
|
+
}
|
|
169
|
+
const e = per.get(key);
|
|
170
|
+
const w = Math.max(1, Number(r.weight) || 1);
|
|
171
|
+
// 同一个词可能既在 subject 又在 body ⇒ 累加(出现得越多越相关)
|
|
172
|
+
e.tokens.set(r.token, (e.tokens.get(r.token) ?? 0) + w);
|
|
173
|
+
e.byField[r.field] = (e.byField[r.field] ?? 0) + w;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const N = total || per.size;
|
|
177
|
+
const hits = [...per.values()].map((e) => {
|
|
178
|
+
let score = 0;
|
|
179
|
+
for (const [t, w] of e.tokens) score += idfFor(dfSets.get(t)?.size ?? 1, N) * (1 + Math.log1p(w));
|
|
180
|
+
return {
|
|
181
|
+
ref: e.ref,
|
|
182
|
+
score: Number(score.toFixed(6)),
|
|
183
|
+
coverage: terms.length ? e.tokens.size / terms.length : 0,
|
|
184
|
+
matched: [...e.tokens.keys()],
|
|
185
|
+
fields: Object.keys(e.byField),
|
|
186
|
+
byField: e.byField,
|
|
187
|
+
};
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
hits.sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score)
|
|
191
|
+
|| (a.ref.account + a.ref.folder).localeCompare(b.ref.account + b.ref.folder)
|
|
192
|
+
|| (a.ref.uid - b.ref.uid));
|
|
193
|
+
|
|
194
|
+
const perTerm = Object.fromEntries(terms.map((t) => [t, dfSets.get(t)?.size ?? 0]));
|
|
195
|
+
return {
|
|
196
|
+
hits,
|
|
197
|
+
exact: hits.filter((x) => x.coverage >= 1),
|
|
198
|
+
terms: [...terms],
|
|
199
|
+
total: N,
|
|
200
|
+
perTerm,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** 命中数 → 一句诊断(哪个词太冷/全部落空),给工具直接贴出来。 */
|
|
205
|
+
export function explainMiss(perTerm = {}, terms = []) {
|
|
206
|
+
const cold = terms.filter((t) => !(perTerm[t] > 0));
|
|
207
|
+
if (!terms.length) return "没有可检索的词(查询太短或全是停用词)";
|
|
208
|
+
if (cold.length === terms.length) return `所有词都没命中:${cold.join(" / ")}`;
|
|
209
|
+
if (cold.length) return `部分词未命中:${cold.join(" / ")}`;
|
|
210
|
+
return "全部词都有命中";
|
|
211
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// lib/host-settings.js — M6.1:把「运行时设置」的真相交给**宿主配置页**(volatile 节点)。
|
|
2
|
+
//
|
|
3
|
+
// 背景(为什么要这一层):
|
|
4
|
+
// M3.3 自己造了 `<dataDir>/settings.json` 当用户层。M6.0 真机上了宿主配置页之后,
|
|
5
|
+
// 同一个字段有了**两个**可写入口 ⇒ 「页面里改了 70,工具 status 显示 60」这种双真相。
|
|
6
|
+
// D15 定案:宿主配置页是唯一真相,settings.json 降级为「一次性迁移源 + 无 settings 服务时的兜底」。
|
|
7
|
+
//
|
|
8
|
+
// 宿主契约(0.2.0-rc.2 实测,dsh-settings/lib/index.js:406-537):
|
|
9
|
+
// * `describe()` → 每行一个 descriptor:`{ ns, revision, value, base, user, schema, … }`
|
|
10
|
+
// * `update(ns, patch)` → patch 是**表单形状**的增量合并:`{ [volatileKey]: { … } }`
|
|
11
|
+
// * `replace(ns, section)` → 以「部署层 base」为底,套上 section ⇒ 传 `{}` 即**清空用户覆盖**
|
|
12
|
+
// * 冲突 → 抛 `SettingsConflictError`(名字/消息里带 revision/conflict)
|
|
13
|
+
//
|
|
14
|
+
// 三个必须记住的细节(踩过才写在这里):
|
|
15
|
+
// ① 写入形状的**第一段是 volatile 节点名 `runtime`**,不是命名空间 `mailbox`
|
|
16
|
+
// (write() 里 `change(projectForm(form, raw), …)`,M6.0 首版卡片就死在这一条)。
|
|
17
|
+
// ② `update` 只做**深合并**,数组是整体替换(mergeLayers 对非 plain object 直接 return over)
|
|
18
|
+
// ⇒ 传 `notify.filter.skip` 必须给完整数组,不能给单个元素。
|
|
19
|
+
// ③ `replace(ns, {})` 的结果是**部署层 base**,不是「删掉所有键」——
|
|
20
|
+
// 所以 reset 的正确实现是 replace 空 section(见 reset())。
|
|
21
|
+
|
|
22
|
+
import fs from "node:fs";
|
|
23
|
+
import { SETTINGS_FIELDS } from "./settings.js";
|
|
24
|
+
|
|
25
|
+
/** 宿主里本插件的命名空间 = Loader 行 id(cordis.patch.yml 那行的 `id: mailbox`)。 */
|
|
26
|
+
export const MAILBOX_NS = "mailbox";
|
|
27
|
+
/** Config 里那个**恰好一个** volatile 节点的名字,也是写入路径的第一段。 */
|
|
28
|
+
export const VOLATILE_KEY = "runtime";
|
|
29
|
+
/** 迁移后旧文件的改名后缀(留档,不删 —— 万一要回滚)。 */
|
|
30
|
+
export const IMPORTED_SUFFIX = ".imported";
|
|
31
|
+
|
|
32
|
+
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
33
|
+
|
|
34
|
+
/** 用户视角的嵌套子树 → 宿主表单形状(`{ runtime: section }`)。 */
|
|
35
|
+
export function toFormShape(section = {}) {
|
|
36
|
+
return { [VOLATILE_KEY]: isPlainObject(section) ? section : {} };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 表单值 → volatile 子树。value 可能是 `{runtime:…}`,也可能已经是 runtime 本身(容错)。 */
|
|
40
|
+
export function runtimeOf(value) {
|
|
41
|
+
if (!isPlainObject(value)) return {};
|
|
42
|
+
const section = value[VOLATILE_KEY];
|
|
43
|
+
if (isPlainObject(section)) return section;
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** describe() 结果里挑出本命名空间那一行。 */
|
|
48
|
+
export function findDescriptor(descriptors, ns = MAILBOX_NS) {
|
|
49
|
+
if (!Array.isArray(descriptors)) return null;
|
|
50
|
+
return descriptors.find((d) => isPlainObject(d) && d.ns === ns) ?? null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 陈旧 revision 冲突判定。宿主抛 `SettingsConflictError`(name + `code:"SETTINGS_CONFLICT"`);
|
|
54
|
+
* 个别路径(remote RPC 包装)只给消息,所以三条线索都认。 */
|
|
55
|
+
export function isConflictError(err) {
|
|
56
|
+
if (!err) return false;
|
|
57
|
+
if (String(err.code ?? "") === "SETTINGS_CONFLICT") return true;
|
|
58
|
+
const name = String(err?.name ?? err?.constructor?.name ?? "");
|
|
59
|
+
if (/conflict/i.test(name)) return true;
|
|
60
|
+
const msg = String(err?.message ?? err ?? "");
|
|
61
|
+
return /revision/i.test(msg) && /conflict|changed|modified|并发|冲突/i.test(msg);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 点号路径读取(缺任一段 → undefined)。 */
|
|
65
|
+
export function readPath(obj, dotted) {
|
|
66
|
+
let cur = obj;
|
|
67
|
+
for (const p of String(dotted).split(".")) {
|
|
68
|
+
if (!isPlainObject(cur)) return undefined;
|
|
69
|
+
cur = cur[p];
|
|
70
|
+
}
|
|
71
|
+
return cur;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 收集一个对象里所有**叶子**的点号路径(用于判断「用户层到底覆盖了哪些字段」)。 */
|
|
75
|
+
export function leafPaths(obj, prefix = [], out = []) {
|
|
76
|
+
if (!isPlainObject(obj)) { if (prefix.length) out.push(prefix.join(".")); return out; }
|
|
77
|
+
for (const [k, v] of Object.entries(obj)) leafPaths(v, [...prefix, k], out);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 逐字段判定「生效值是谁说了算」。
|
|
83
|
+
*
|
|
84
|
+
* 优先级与**实际生效顺序**一致(否则文案就是在骗用户):
|
|
85
|
+
* file(settings.json 过渡层) > host(宿主配置页 / volatile 覆盖) > config(部署层 patch) > default
|
|
86
|
+
*
|
|
87
|
+
* @param {object} p
|
|
88
|
+
* @param {object} p.hostRuntime 宿主用户层(volatile 子树)
|
|
89
|
+
* @param {object} p.fileLayer settings.json 的内容(迁移后为空)
|
|
90
|
+
* @param {object} p.deploymentConfig 去掉 volatile 之后的行 config(部署层)
|
|
91
|
+
* @param {Array} [p.fields] SETTINGS_FIELDS
|
|
92
|
+
* @returns {Record<string,string>} path → "file" | "host" | "config" | "default"
|
|
93
|
+
*/
|
|
94
|
+
export function resolveSources({ hostRuntime = {}, fileLayer = {}, deploymentConfig = {}, fields = SETTINGS_FIELDS } = {}) {
|
|
95
|
+
const out = {};
|
|
96
|
+
for (const f of fields) {
|
|
97
|
+
const cfgPath = f.cfg ?? f.path;
|
|
98
|
+
if (readPath(fileLayer, f.path) !== undefined) out[f.path] = "file";
|
|
99
|
+
else if (readPath(hostRuntime, f.path) !== undefined) out[f.path] = "host";
|
|
100
|
+
else if (readPath(deploymentConfig, cfgPath) !== undefined) out[f.path] = "config";
|
|
101
|
+
else out[f.path] = "default";
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 来源层的用户可读名(status 输出用;中文,与卡片文案一致才不至于让人困惑)。 */
|
|
107
|
+
export function sourceLabel(src) {
|
|
108
|
+
switch (src) {
|
|
109
|
+
case "file": return "settings.json(过渡)";
|
|
110
|
+
case "host": return "宿主配置页";
|
|
111
|
+
case "config": return "cordis";
|
|
112
|
+
default: return "default";
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 宿主 settings 服务的**窄适配器**。
|
|
118
|
+
* service 既可以直接给服务对象,也可以给 getter(服务可能比 apply() 晚就绪)。
|
|
119
|
+
*/
|
|
120
|
+
export function createHostSettings({ service, getService, ns = MAILBOX_NS, log = () => {} } = {}) {
|
|
121
|
+
const svc = () => {
|
|
122
|
+
try {
|
|
123
|
+
const s = typeof getService === "function" ? getService() : service;
|
|
124
|
+
return s ?? null;
|
|
125
|
+
} catch { return null; }
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
return {
|
|
129
|
+
ns,
|
|
130
|
+
/** 服务在场且具备我们真正依赖的两个方法。 */
|
|
131
|
+
available() {
|
|
132
|
+
const s = svc();
|
|
133
|
+
return !!s && typeof s.update === "function" && typeof s.describe === "function";
|
|
134
|
+
},
|
|
135
|
+
/** describe() 里本命名空间那一行(带容错)。 */
|
|
136
|
+
read() {
|
|
137
|
+
const s = svc();
|
|
138
|
+
if (!s || typeof s.describe !== "function") return { ok: false, reason: "no-settings-service" };
|
|
139
|
+
let desc;
|
|
140
|
+
try { desc = findDescriptor(s.describe(), ns); }
|
|
141
|
+
catch (e) { return { ok: false, reason: "describe-failed", error: String(e?.message ?? e) }; }
|
|
142
|
+
if (!desc) return { ok: false, reason: "namespace-not-served" };
|
|
143
|
+
const value = isPlainObject(desc.value) ? desc.value : {};
|
|
144
|
+
return {
|
|
145
|
+
ok: true,
|
|
146
|
+
revision: Number(desc.revision ?? 0) || 0,
|
|
147
|
+
autoGenerate: desc.autoGenerate,
|
|
148
|
+
value,
|
|
149
|
+
runtime: runtimeOf(value),
|
|
150
|
+
base: runtimeOf(desc.base),
|
|
151
|
+
user: runtimeOf(desc.user),
|
|
152
|
+
};
|
|
153
|
+
},
|
|
154
|
+
/** 用户层显式覆盖了哪些路径(点号,用户视角)。 */
|
|
155
|
+
overriddenPaths() {
|
|
156
|
+
const r = this.read();
|
|
157
|
+
return r.ok ? new Set(leafPaths(r.user)) : new Set();
|
|
158
|
+
},
|
|
159
|
+
/**
|
|
160
|
+
* 增量写入。section = 用户视角的嵌套子树(如 `{notify:{enabled:false}}`)。
|
|
161
|
+
* @returns {Promise<{ok:boolean, via:string, op:string, reason?:string, error?:string, conflict?:boolean}>}
|
|
162
|
+
*/
|
|
163
|
+
async update(section = {}) {
|
|
164
|
+
const s = svc();
|
|
165
|
+
if (!s || typeof s.update !== "function") return { ok: false, via: "host", op: "update", reason: "no-settings-service" };
|
|
166
|
+
try {
|
|
167
|
+
await s.update(ns, toFormShape(section));
|
|
168
|
+
return { ok: true, via: "host", op: "update" };
|
|
169
|
+
} catch (e) {
|
|
170
|
+
const conflict = isConflictError(e);
|
|
171
|
+
const reason = conflict ? "conflict" : "error";
|
|
172
|
+
log("warn", `宿主配置写入失败(${reason}): ${e?.message ?? e}`);
|
|
173
|
+
return { ok: false, via: "host", op: "update", reason, conflict, error: String(e?.message ?? e) };
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
/** 以部署层 base 为底重写(空 section = 清空所有用户覆盖)。 */
|
|
177
|
+
async replace(section = {}) {
|
|
178
|
+
const s = svc();
|
|
179
|
+
if (!s || typeof s.replace !== "function") return { ok: false, via: "host", op: "replace", reason: "no-settings-service" };
|
|
180
|
+
try {
|
|
181
|
+
await s.replace(ns, toFormShape(section));
|
|
182
|
+
return { ok: true, via: "host", op: "replace" };
|
|
183
|
+
} catch (e) {
|
|
184
|
+
const conflict = isConflictError(e);
|
|
185
|
+
const reason = conflict ? "conflict" : "error";
|
|
186
|
+
log("warn", `宿主配置重置失败(${reason}): ${e?.message ?? e}`);
|
|
187
|
+
return { ok: false, via: "host", op: "replace", reason, conflict, error: String(e?.message ?? e) };
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
/** 清空用户覆盖(= 回到 cordis 部署层)。 */
|
|
191
|
+
async reset() { return this.replace({}); },
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** 迁移留档的目标路径:绝不覆盖已有留档。 */
|
|
196
|
+
export function importedPathOf(file) {
|
|
197
|
+
const base = `${file}${IMPORTED_SUFFIX}`;
|
|
198
|
+
if (!fs.existsSync(base)) return base;
|
|
199
|
+
for (let i = 1; i < 1000; i += 1) {
|
|
200
|
+
const next = `${base}.${i}`;
|
|
201
|
+
if (!fs.existsSync(next)) return next;
|
|
202
|
+
}
|
|
203
|
+
return `${base}.${Date.now()}`;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* 一次性迁移:`settings.json` → 宿主配置页;**成功后**才把旧文件改名留档。
|
|
208
|
+
*
|
|
209
|
+
* 为什么必须「成功才改名」:改名 = 放弃兜底真相。宿主写入失败还改名,用户的值就凭空消失了。
|
|
210
|
+
* 空文件也照样收掉(否则一个空的 settings.json 会永远被当成"用户层存在")。
|
|
211
|
+
*
|
|
212
|
+
* @returns {Promise<{ok:boolean, reason:string, renamedTo?:string, error?:string}>}
|
|
213
|
+
*/
|
|
214
|
+
export async function migrateLegacyFile({ host, file, legacyValue = {}, log = () => {} } = {}) {
|
|
215
|
+
if (!file) return { ok: false, reason: "no-file" };
|
|
216
|
+
if (!fs.existsSync(file)) return { ok: false, reason: "absent" };
|
|
217
|
+
if (!host?.available?.()) return { ok: false, reason: "no-host" };
|
|
218
|
+
|
|
219
|
+
const keys = Object.keys(legacyValue ?? {});
|
|
220
|
+
if (keys.length) {
|
|
221
|
+
const r = await host.update(legacyValue);
|
|
222
|
+
if (!r.ok) {
|
|
223
|
+
log("warn", `settings.json → 宿主配置页迁移失败(${r.reason}),保留原文件: ${r.error ?? ""}`);
|
|
224
|
+
return { ok: false, reason: r.reason, error: r.error };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const renamedTo = importedPathOf(file);
|
|
228
|
+
try {
|
|
229
|
+
fs.renameSync(file, renamedTo);
|
|
230
|
+
} catch (e) {
|
|
231
|
+
// 值已经进宿主了,只是留档没成:不谎报失败,但要把文件收掉,免得下次重复导入
|
|
232
|
+
log("warn", `settings.json 迁移留档改名失败: ${e?.message ?? e}`);
|
|
233
|
+
return { ok: true, reason: "renamed-failed", renamedTo: null };
|
|
234
|
+
}
|
|
235
|
+
log("info", `settings.json 已迁移到宿主配置页并留档为 ${renamedTo}(${keys.length} 个顶层键)`);
|
|
236
|
+
return { ok: true, reason: keys.length ? "imported" : "empty", renamedTo };
|
|
237
|
+
}
|